1 of 31

Basics

1

LEVEL -2

2 of 31

2

7/12/2019

Contents

  • Rules
  • Identifiers & Variables
  • Special characters
  • Data Types
  • Conditions
  • Loop
  • Functions
  • classes
  • Modules
  • Read/Write files

3 of 31

3

Rule1: while using java with html code should

start with <script> and end with </script>

Rule2: keywords should not be identifier

Rule3: case sensitive

Rule 4: proper brackets have to use for blocks {

4 of 31

4

Identifiers & Variables

  • JAVA identifier is a name used to identify a variable, function, class, module, or other object.
  • An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Example: x=1 here ‘x’ is identifier and ‘1’ is variable

JAVA does not allow punctuation characters such as @, $, and % within identifiers except _.

Case sensitive:

X=1

x=2

Console.log(X)🡪 result: 1

Console.log(x)🡪 result: 2

Console.log(‘Word’==‘word’) 🡪 result: False

5 of 31

5

Special Characters

  1. { } To define blocks of function, condition and loop
  2. // To add comment line
  3. /* */ To add comment block
  4. ‘ ” To specify string characters
  5. ; To merge multiline to single line
  6. \n To new line
  7. \t To Tab space

6 of 31

6

Quotation

JAVA accepts single (') and double (") quotes to denote string literals, as long as the same type of quote starts and ends the string.

word = 'word'

sentence = "This is a sentence."

Comments

double slash sign (//) that is not inside a string literal begins a comment. All characters after the // and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

//console.log(“first”)

console.log(“second’)

Result will be second

7 of 31

7

Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that

neither statement starts a new code block.

Here is a sample snip using the semicolon:

x = ‘1’; console.log(x)

8 of 31

8

Standard Data Types

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. JAVA has various standard data types that are used to define the operations possible on them and the storage method for each of them.

standard data types:

  • Numbers
  • String
  • List (Array)
  • Dictionary

9 of 31

9

Java Numbers

Number data types store numeric values. Number objects are created when you assign a value to them. For example:

x = 1.0

y = 10

console.log(x+y)

>11

console.log(Math.floor(11.7))

>11

console.log((11).toFixed(2))

>11.00

10 of 31

10

number Operations

Option

syntax

Example

Result

Maximum

Math.max(numbers list)

console.log(Math.max(5, 4,7))

7

Minimum

Math.min(numbers list)

console.log(Math.min(5, 4,7))

4

Absolute (whole number to natural number)

Math.abs(whole numbers)

console.log(Math.abs(-2))

2

Multiplication Round

base * Math.round(x/base)

print(5 *Math.round(134/5))

135

Multiplication Round

base * Math.floor(x/base)

print(5 * Math.floor(134/5))

130

11 of 31

11

Strings

Strings in Java are identified as a contiguous set of characters represented in the quotation marks.

Java allows for either pairs of single or double quotes. indexes starting at 0 in the beginning of the string and working their way from str.length-1 at the end.

The plus (+) sign is the string concatenation operator

For example:

str = 'Hello World!'

Console.log(str) //Prints complete string Hello World!

Console.log(str[0] ) //Prints first character of the string H

Console.log(str + "TEST“) //Prints concatenated string Hello World!TEST

console.log(str.slice(0, 3)) //Prints characters starting from 0th to 5th Hel

12 of 31

12

String Operations

Option

syntax

Example

Result

count

String.length

Console.log(“hello”.length)

5

split

string.split(chr)

console.log(‘hello world’.split(“ "))

['hello', 'world']

replace

string.replace(chr1,chr2)

console.log(‘hallo’.replace(“a", “e"))

hello

upper

string.toUpperCase())

console.log(“hELlo”.toUpperCase())

HELLO

lower

string.toLowerCase())

console.log(“hELlo”.toLowerCase())

hello

13 of 31

13

Lists (Arrays)

Lists are the most versatile of JAVA's compound data types. A list contains items separated by commas and enclosed within square brackets ([]).

To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

indexes starting at 0 in the beginning of the list and working their way to end str.length-1.

For example:

x= [ 1,2,3,4,5]

y=[4,5]

console.log(x) // Prints complete list [1,2,3,4,5]

console.log(x[0]) //Prints first element of the list 1

z=[].concat(x,y); console.log(z) [1, 2, 3, 4, 5,4,5]

x.slice(1, 3) [2, 3]

14 of 31

14

List Operations

Option

syntax

Example

Result

count

list.length

Consol.log([1,2,3,4].length)

4

Remove(index)

List.splice(index,count)

Consol.log([1,2,3,4].splice(2, 1))

[1, 2, 4]

Remove(value)

remove duplicate

Consol.log(Array.from(new Set([1,2,1,3])))

[1,2,3]

Add

list1.concat(list2)

[1,2].concat([3,4])

[1,2,3,4]

subtract

index

console.log([1,2,3,4,'a'].indexOf('a'))

5

Change index

insert

list.splice(index,0,value)

[1,2,3,4].splice( 1, 0, ‘a’)

[1,’a’,2,3,4]

append

list.push(value)

[1,2,3].push(4)

[1,2,3,4]

append

list.unshift(value)

[1,2,3].unshift(4)

[4,1,2,3]

15 of 31

15

Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In JAVA dictionaries are written with curly brackets, and they have keys and values.

Dictionaries differ from lists primarily in how elements are accessed:

  • List elements are accessed by their position in the list, via indexing.
  • Dictionary elements are accessed via keys.

d={<key>:<value>,<key>:<value>,……}

d = {3: 'd', 2: 'c', 1: 'b', 0: 'a‘}

>>> d[0] >>> 'a'

d[4]=‘e’

>>>d >>> {3: 'd', 2: 'c', 1: 'b', 0: 'a‘,4:’e’}

16 of 31

16

Dictinary Operations

Option

syntax

Example

Result

count

Object.keys(dict).length

Object.keys({'one':1,'two':4}).length

2

remove

delele d[key]

a={2:2,’1’:1,'four‘:4};delete a[‘four’]

{2: 2, '1': 1}

change

d[key]=value

a={2:2,’1’:1,'four‘:4};a[‘1’]=‘one’;print(a)

{2: 2, '1': 'one', 'four': 4}

Get keys

Object.keys(dict)

a={2:2,'1':1,'four':4} console.log(Object.keys(a))

[2, '1', 'four']

Get values

Object.values(dict)

a={2:2,'1':1,'four':4} console.log(Object.values(a))

[2, 1, 4]

17 of 31

Date/Time

Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

Basic Required functions related to Date are given below

18 of 31

Get full Date

x=new Date()

Tue Sep 10 2019 14:35:43 GMT+0530 (India Standard Time)

Get year

x.getFullYear()

2019

Get month

x.getMonth()

8

Get month

x.toLocaleString("en", { month: "long" })

September

Get month

x.toLocaleString("en", { month: “short" })

Sep

Get Date

x.getDate()

10

Get Hours

x.getHours()

14

Get Hours

x.getHours() % 12 || 12)

2

Get Minute

x.getMinutes()

35

Get seconds

x.getSeconds()

43

Get Day

x.getDay()

2

Get Day

x.toLocaleString("en", { weekday: 'long' })

Tuesday

Get Day

x.toLocaleString("en", { weekday: ‘short' })

Tue

Time string

x.toLocaleTimeString()

2:47:59 PM

Date string

x.toLocaleDateString()

9/10/2019

Time date string

x.toLocaleString()

9/10/2019, 2:49:22 PM

Time string

x.toLocaleString("en-US",{hour12: false })

9/10/2019, 16:02:14

Get Attributes

19 of 31

Time Delay

Run function after time:

function fun1(){console.log(step3)}

console.log(‘step1’)

setTimeout(function, 3000)

console.log(step2)

Pause script

function sleep(ms) {now = new Date().getTime();while(new Date().getTime() < now + ms*1000){}}

console.log(‘step1’)

sleep(3)

console.log(step2)

Result :

step1

Step2

//pause for 3 sec

step3

Result :

step1

//pause for 3 sec

step2

20 of 31

Time Subtract

<script>

function sleep(ms) {now = new Date().getTime();while(new Date().getTime() < now + ms*1000){}}

x=new Date()

sleep(3)

y=new Date()

console.log(y-x)

</script>

Result: 3000

Time Convert

<script>

function time( milliseconds ) {

seconds = Math.floor(milliseconds / 1000)

minute = Math.floor(seconds / 60)

seconds = seconds % 60

hour = Math.floor(minute / 60)

minute = minute % 60

day = Math.floor(hour / 24)

hour = hour % 24

return {day: day,hour: hour,minute: minute,seconds: seconds}

}

x=time(3000)

console.log(x)

</script>

21 of 31

Path

Get current script file directory

console.log(location.pathname)

/C:/Users/lvishwan/Desktop/java.html

Get current script file directory

console.log(document.URL)

file:///C:/Users/lvishwan/Desktop/java.html

Get current user

Get current ip address

List of file in given folder

22 of 31

CDSID: lvishwan

22

JAVA─ Decision Making

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of

the programming languages:

Syntax:

If (condition)

{expression}

else

{expression}

<script>

a=2

if (a==1)

{console.log('ok')

console.log('ok1')}

else {console.log('false')}

</script>

23 of 31

CDSID: lvishwan

23

Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then:

24 of 31

CDSID: lvishwan

24

Loops

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times.

The following diagram illustrates a loop statement:

Syntax:

for (start,end,incremental)

{expression}

25 of 31

For loop types

  • For /Range
  • For/In
  • For/of

Other types of loop:

  • While
  • Do/while

Option

Example

Result

For/Range

for(i=5;i<10;i++) {console.log(i)}

5,6,7,8,9

For/in

for (i in [‘a’,’b’,’c’]) {console.log(i)}

0,1,2

For/of

for (i of ['a','b','c']) {console.log(i)}

a,b,c

while

i=5;while (i < 10) {console.log(i);i++}

5,6,7,8,9

do/while

i=5;do {console.log(i);i++} while (i < 10)

5,6,7,8,9

26 of 31

Loop Controls

  • Break
  • Continue
  • Break label
  • Continue label

<script>

for (i of [1,2,3])

{

if (i==2) {continue}

console.log(i)

}

</script>

Result: 1,3

<script>

for (i of [1,2,3])

{

console.log(i)

if (i==2) {break}

}

</script>

Reuslt:1,2

27 of 31

Data type Conversion

conversion

example

Result

Check type

typeof(‘123’)

“number”

String to number

Number(‘123’)

123

Number to String

String(123.1)

‘123.1’

Float to integer

Math.floor(123.66)

123

Float to integer(round)

Math.round(123.66)

124

Integer to float

(123).toFixed(2))

123.00

28 of 31

Handling Exceptions

When a JavaScript statement generates an error, it is said to throw an exception.

Instead of proceeding to the next statement, the JavaScript interpreter checks for exception handling code.

If there is no exception handler, then the program returns from whatever function threw the exception.

This is repeated for each function on the call stack until an exception handler is found or until the top level function is reached,

causing the program to terminate.

try {expression}

catch (exception) {console.log(exception.message)}

<script>

x='123'

try {console.log(x.toFixed(2))}

catch (exception){console.log(exception.message)}

</script>

29 of 31

FUNCTIONS

What is a Function?

  • A function is a subprogram designed to perform a particular task.
  • Functions are executed when they are called. This is known as invoking a function.
  • Values can be passed into functions and used within the function.
  • Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.
  • Functions are objects.

function name(parameters){statements�}

30 of 31

Simple Function example

<script>

function sq_sum(x,y){return ((x**2)+(y**2))}

x=sq_sum(2,5)

console.log(x)

</script>

31 of 31

Modules:

<script src="C:\Users\lvishwan\Desktop\VL\java.js"> </script>

We have some important modules to do some specific operations

Like creating windows –jqueryui

Create excel- infragmengt

Variable interaction –jquery

We will discuss about these modules in next level