java notes 1 - operators control-flow

48
Java - Basics Prepared by Mohammed Sikander Technical Lead Cranes Varsity

Upload: mohammed-sikander

Post on 13-Jan-2017

52 views

Category:

Software


3 download

TRANSCRIPT

Page 1: Java notes   1 - operators control-flow

Java - BasicsPrepared byMohammed SikanderTechnical LeadCranes Varsity

Page 2: Java notes   1 - operators control-flow

Language BasicsVariablesOperatorsControl-flowArrays

Page 3: Java notes   1 - operators control-flow

[email protected]

3

Converting Ideas to Program

Page 4: Java notes   1 - operators control-flow

[email protected]

4

C++ Compilation Process

Page 5: Java notes   1 - operators control-flow

[email protected]

5

JAVA Compilation Process

Page 6: Java notes   1 - operators control-flow

[email protected]

6

First Java Program

Page 7: Java notes   1 - operators control-flow

[email protected]

7

The class can be public [not compulsory]

main should be public [compulsory]

main should be static [compulsory]

return type of main should be void [compulsory]

Argument of String [] is compulsory.

only the order of public and static can be swapped.

Page 9: Java notes   1 - operators control-flow

[email protected]

9

If class is public, filename should match class name.

If class is not public, filename can be different.

Page 10: Java notes   1 - operators control-flow

[email protected]

10

javac FirstProgram.java

Java SecondProgram

Page 11: Java notes   1 - operators control-flow

[email protected]

11

Naming ConventionsName Conventionclass Names hould start with uppercase letter and

be a noune.g. String, Color, Button, System, Thread etc.

interface Name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.

method Name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.

variable Name should start with lowercase letter e.g. firstName, orderNumber etc.

package Name should be in lowercase letter e.g. java, lang, sql, util.

Constants Name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.

Page 12: Java notes   1 - operators control-flow

[email protected]

12

CamelCase in java naming conventionsJava follows camelcase syntax for

naming the class, interface, method and variable.

If name is combined with two words, second word will start with uppercase letter always

actionPerformed( ), firstName, ActionEvent, ActionListener etc.

Page 13: Java notes   1 - operators control-flow

[email protected]

13

Variables naming - RulesAll variable names must begin with a

letter, an underscore ( _ ), or a dollar sign ($). 

[a-z/_/$] [a-z/_/$/0-9]Case sensitive – similar to c/c++

Samples of acceptable variable names:   YES

 Samples of unacceptable variable

names:   NOGrade  Grade(Test)GradeOnTest GradeTest#1Grade_On_Test 3rd_Test_GradeGradeTest Grade Test   (has a

space) int $a = 5; int a$b = 8; int _x = 4; int _ = 9;

Page 14: Java notes   1 - operators control-flow

[email protected]

14

Variable naming – GuidelinesThe convention is to always use a

letter of the alphabet.  The dollar sign and the underscore are discouraged.

Variable should begin with lowercase, multiple word variable can use camelCasing.

All characters in uppercase are reserved for final(constants)

Page 16: Java notes   1 - operators control-flow

[email protected]

16

DatatypesByte - 1 byteShort - 2 byteInt - 4Long - 8Float - 4 (IEEE 754)Double - 8 (IEEE 754)Char - 2 (unicode)Boolean - 1 (size undefined)Note : java does not support unsigned.

Page 17: Java notes   1 - operators control-flow

[email protected]

17

LITERALS Integer literals Decimal [1-9][0-9]Octal 0[0-7]Hexadecimal 0x[0-9,A-F]Binary (JAVA SE7) 0b[0-1]Underscore can appear in literals (JAVA SE7)long creditCardNum =

1234_5678_9012_3456L; Floating-point literals Double 4.5 or 4.5d 1.23e2Float4.5f 1.23e2f

Page 18: Java notes   1 - operators control-flow

[email protected]

18

Write the Outputclass ArithmeticOperation {

public static void main(String [] args ) {

byte a = 5; byte b = 10; byte sum = a + b;

System.out.println("Sum = " + sum); }

}

int sum = a + b;byte sum = (byte)(a + b);

Page 19: Java notes   1 - operators control-flow

[email protected]

19

Write the Output

Java Programclass ArithmeticOperation {

public static void main(String [] args ) {float res = 9 % 2.5f;System.out.println("res = " + res);}

}

C/ C++ Programint main( ){

float res = 9 % 2.5f;printf(" %f " ,res);

}

Page 20: Java notes   1 - operators control-flow

[email protected]

20

Arithmetic Operatorsint / int => intfloat / int => floatbyte + byte => int% operator can be applied to

float-typesEg : 5.0 % 2.4 = 0.29 % 2.5 => 1.5; 10 % 2.5 => 0

Page 21: Java notes   1 - operators control-flow

[email protected]

21

Outputclass ArithmeticOperation {

public static void main(String [] args ) { byte a = 5; byte b = 10; int sum = a + b; byte diff = (byte)(a – b);System.out.println("Sum = " + sum); System.out.println(“diff = " + diff); }

}

Page 22: Java notes   1 - operators control-flow

[email protected]

22

Conversion from Small to Largepublic class Conversion {public static void main(String args[]) {

byte b = 12;int i = 300;double d = 323.142;System.out.println("\nConversion of byte to

int.");i = b;System.out.println("i and b " + i + " " + b);System.out.println("\nConversion of int to

double.");d = i;System.out.println("d and i " + d + " " + i);

}}

Page 23: Java notes   1 - operators control-flow

[email protected]

23

Conversion from Large to Smallpublic class Conversion {public static void main(String args[]) {

byte b;int i = 300;double d = 323.142;System.out.println("\nConversion of int to byte.");b = (byte) i;System.out.println("i and b " + i + " " + b);System.out.println("\nConversion of double to int.");i = (int) d;System.out.println("d and i " + d + " " + i);System.out.println("\nConversion of double to byte.");b = (byte) d;System.out.println("d and b " + d + " " + b);

}}

Page 24: Java notes   1 - operators control-flow

[email protected]

24

Write the Outputpublic class ByteDemo { public static void main(String [] args) { byte x = 127; System.out.println(x); x++; System.out.println(x); }}

Page 25: Java notes   1 - operators control-flow

[email protected]

25

Code to Print ASCII / UNICODE Value of a Character public class CharAsciiValue { public static void main(String[]

args) { char a = 'A'; System.out.println(a + " " +

(int)a); }}

Page 26: Java notes   1 - operators control-flow

[email protected]

26

Question

Consider the statement double ans = 10.0+2.0/3.0−2.0∗2.0; Rewrite this statement, inserting

parentheses to ensure that ans = 11.0 upon evaluation of this statement.

Page 27: Java notes   1 - operators control-flow

[email protected]

27

What should be the datatype of res variable?public static void main( String []

args){

int a = 5;int b = 10;

____ res = a > b;System.out.println(res);

}

Page 28: Java notes   1 - operators control-flow

[email protected]

28

int main( ){

int a = 5;if(a)

printf(“True");else

printf(“False”);}

public static void main(String [] args)

{int a = 5;if(a)System.out.print("TRUE");elseSystem.out.print(“FALSE");

}

Page 29: Java notes   1 - operators control-flow

[email protected]

29

Relational Operators Result of Relational operators is of type boolean. int x = 5 > 2;//In valid – cannot assign boolean to int.

boolean  flag = false; if(flag)  {                }

 if(flag = true)      {                }     int x = 5;   if(x = 0)   {  }

Page 30: Java notes   1 - operators control-flow

[email protected]

30

Logical Operators&& , || - Short-circuiting operators, Same as C & , | - evaluates both condition.

if(++x > 5 & ++ y > 5){}Both x and y are updated

if(++x > 5 && ++ y > 5){}Only x is updated.

Page 31: Java notes   1 - operators control-flow

[email protected]

31

Write the Output

Try with following Changes 1. Change the value of x to 8.2. Replace && with &3. Try with OR Operators (| | and | )

Page 32: Java notes   1 - operators control-flow

[email protected]

32

Bitwise OperatorsCan be applied on integral types only& , | , ^ , ~, >> , << , >>> >>> (unsigned right shift)

If left and right are boolean, it is relational.

(a > b & a > c)

If left and right are integral, it is bitwise.(a & c)

Page 33: Java notes   1 - operators control-flow

[email protected]

33

To print in Binary FormInteger.toBinaryString(int)

Output:X = 2310111

Page 35: Java notes   1 - operators control-flow

[email protected]

35

Control Flow - ifIf (boolean)

◦Condition should be of booleanif( x ) invalid is not same as if(x != 0 )

(valid){ {} }boolean x = false;if( x ) if(x = true ) { {} }

Page 37: Java notes   1 - operators control-flow

[email protected]

37

Control Flow - switchThe switch statement is multiway

branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.

It often provides a better alternative than a large series of if-else-if statements

Case label can be of◦ Byte, short, char, int ◦ Enum , String (SE 7 & later)◦ Character , Byte, Short,Integer(Wrapper

class)◦ Break is not a must after every case

(similar to C).

Page 38: Java notes   1 - operators control-flow

[email protected]

38

Control Flow - switchpublic static void main(String [] args){byte b = 1;switch(b){ case 1 : System.out.println("Case 1"); case 2 :System.out.println("Case 2");}}

Page 39: Java notes   1 - operators control-flow

[email protected]

39

Iteration StatementsWhile Do-whileForEnhanced for loop for accessing

array elements

Page 40: Java notes   1 - operators control-flow

[email protected]

40

Enhanced for LoopIt was mainly designed for

iteration through collections and arrays. It can be used to make your loops more compact and easy to read.

int [ ] numbers = {5 , 8 , 2, 6,1};For(int x : numbers)

◦S.o.println(x);

Page 42: Java notes   1 - operators control-flow

[email protected]

42

Enhanced For with Multidimensional Arraysint sum = 0;int nums[][] = new int[3][5];for(int i = 0; i < 3; i++)

for(int j=0; j < 5; j++)nums[i][j] = (i+1)*(j+1);

// use for-each for to display and sum the valuesfor(int x[ ] : nums) {

for(int y : x) {System.out.println("Value is: " + y);sum += y;}

}System.out.println("Summation: " + sum);

Page 43: Java notes   1 - operators control-flow

[email protected]

43

Method 2: No. of columns are same in all rows

Datatype [ ][ ] matrix;Matrix = new datatype[row][col];Method 3 : Each row can have diff. no of

elements(cols)Datatype [ ][ ] matrix;Matrix = new datatype[row][ ];For(I = 0 ; I < row ; i++)

◦ Matrix[i] = new datatype[col]

Page 44: Java notes   1 - operators control-flow

[email protected]

44

breakUnlabelled break & continue – similar to c/c+

+Labelled breaksearch: for (i = 0; i < arrayOfInts.length; i++) {

for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } }

}

Page 46: Java notes   1 - operators control-flow

[email protected]

46

Kangaroohttps://www.hackerrank.com/challenges/kangaroo

There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?

Input Format A single line of four space-separated integers denoting the respective

values of x1, v1, x2, and v2. Output Format Print No if they cannot land on the same location at the same time. Print YES if they can land on the same location at the same time;

also print the location where they will land at same time. Note: The two kangaroos must land at the same location after making the same number

of jumps.