java_basics

119
1  A Simple Java Program 1 public class Hello 2 { 3 /** 4 * My first Java program 5 */ 6 public static void main( String[] args ){ 7 8 //prints string Hello world on screen 9 System.out.println(³Hello world´); 10 11 } 12 }

Upload: abhishek-kumar-jha

Post on 08-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 1/119

1

A Simple Java Program1 public class Hello2 {3 /**4 * My first Java program

5 */6 public static void main( String[] args ){78 //prints string Hello world on screen9 System.out.println(³Hello world´);1011 }12 }

Page 2: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 2/119

2

A Simple Java Program1 public class Hello2 {3 /**4 * My first Java program 5 */

indicates the name of the class which is HelloIn Java, all code should be placed inside a classdeclaration

The class uses an access specifier public , which indicatesthat our class in accessible to other classes from other packages (packages are a collection of classes). We willbe covering packages and access specifiers later.curly brace { indicates the start of a block.

Page 3: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 3/119

3

A Simple Java Program1 public class Hello2 {3 /**4 * My first Java program 5 */

The next three lines indicates a Java comment. A comment

± something used to document a part of a code.

± It is not part of the program itself, but used for documentation purposes. ± It is good programming practice to add comments to your

code.

Page 4: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 4/119

4

A Simple Java Program1 public class Hello2 {3 /**4 * My first Java program 5 */6 public static void main( String[] args ){

indicates the name of one method in Hello which is themain method.The main method is the starting point of a Java program.

All programs except Applets written in Java start with themain method.Make sure to follow the exact signature.

Page 5: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 5/119

5

A Simple Java Program1 public class Hello2 {3 /**4 * My first Java program 5 */6 public static void main( String[] args ){

78 //prints string Hello world on screen9 System.out.println(³Hello world´);

The command System.out.println() , prints the text enclosed byquotation on the screen.

System is a predefined class which provides access to the systemout is output stream connected to console.println displays the string which is passed to it.

Page 6: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 6/119

6

C omments

Three kinds of comments:1) Ignore the text between /* and */

/* text */2 ) Documentation comment ( javadoc tool uses

this kind of comment to automaticallygenerate software documentation)

/** documentation */3) Ignore all text from // to the end of the line

// text

Page 7: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 7/119

7

R unning a Java Application

You writeJava codeusing aneditor

javac MyProg.java

java MyProg

Java code:MyProg.java

Bytecode:MyProg.class

Text Editor

Output

You save thefile with a.javaextension

You run theJavacompiler' javac '

You execute thebytecode withthe command' java'

This createsa file ofbytecodewith a .classextension

Page 8: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 8/119

8

Page 9: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 9/119

9

Coding Guidelines1. Your Java programs should always end with the .java

extension.

2. Filenames should match the name of your publicclass . So for example, if the name of your publicclass is Hello, you should save it in a file called

Hello.java.

3. You should write comments in your code explainingwhat a certain class does, or what a certain method

does.

Page 10: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 10/119

10

Java St a tements a nd Blocks Coding Guidelines

1. In creating blocks, you can place the opening curly brace in linewith the statement. For example:

public static void main( String[] args ) {

or you can place the curly brace on the next line, like,

public static void main( String[] args ){

2 . You should indent the next statements after the start of a block.

public static void main( String[] args ){System.out.println("Hello");System.out.println("world");

}

Page 11: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 11/119

11

Java IdentifiersIdentifiers are tokens that represent names of variables,methods, classes, etc.

± examples: Hello, main, System, out.

Java identifiers are case-sensitive. ± i.e. Identifier H ello is not the same as hello .

Identifiers must begin with either a letter, an underscore³_´, or a dollar sign ³$´. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9.

Identifiers cannot use Java keywords like class , public ,void, etc. We will discuss more about Java keywords later.

Page 12: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 12/119

12

Java Identifiers Coding GuidelinesFor names of classes, capitalize the first letter of the class name.For example, ThisIsAnExampleOfClassName

For names of methods and variables, the first letter of the wordshould start with a small letter. For example,thisIsAnExampleOfMethodName.

In case of multi-word identifiers, use capital letters to indicate the

start of the word except the first word. For example,charArray, fileNumber , className .

Avoid using underscores at the start of the identifier such as _read

or _write.

Page 13: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 13/119

13

Java KeywordsK eywords are reserved words recognized by Java that cannot beused as identifiers.

Page 14: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 14/119

14

P rimiti ve D a ta Types

Java defines eight simple types :

1. byte - 8-bit integer type2 . short - 16-bit integer type3. int - 32 -bit integer type4. long - 64-bit integer type5. float - 32 -bit floating-point type6. double - 64-bit floating-point type7. char - symbols in a character set8. boolean - logical values true and false

Page 15: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 15/119

15

Primiti v e Type: byte

8-bit integer type.

R ange:-12 8 to 12 7.

Example:

byte b = -15;

Usage: particularly when working with data streams.

Page 16: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 16/119

16

Primiti v e Type: short

16-bit integer type.

R ange:-32 768 to 32 767

Example:

short c = 1000;

Usage: probably the least used simple type.

Page 17: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 17/119

17

Primiti

ve Type: int32 -bit integer type.

R ange:-2 147483648 to 2 147483647 .

Example:int b = -50000;

Usage:

1) Most common integer type.2 ) Typically used to control loops and to index arrays.3) Expressions involving the byte, short and int values are promotedto int before calculation.

Page 18: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 18/119

Page 19: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 19/119

19

Example: Long// compute the light travel distanceclass Light {

public static void main(String args[]) {int lightspeed = 186000;long days = = 1000;long seconds = days * 24 * 60 * 60;long distance = lightspeed * seconds;System.out.print("In " + days);System.out.print(" light will

travelabout");System.out.println(distance + " miles.");}

}

Page 20: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 20/119

20

P rimiti v e Type: flo a t32 -bit floating-point number.

R ange:

1.4e-045 to 3.4e+038 .

Example:float f = 1.5;

Usage:1) fractional part is needed2 ) large degree of precision is not required

Page 21: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 21/119

21

P rimiti v e Type: double64-bit floating-point number.

R ange:4.9e-3 2 4 to 1.8e+308 .

Example:double pi = 3.1416;

Usage:1) accuracy over many iterative calculations2 ) manipulation of large-valued numbers

Page 22: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 22/119

22

Example: double

// Compute the area of a circle.class Area {

public static void main(String args[]) {double pi = 3.1416; // approximate pi valuedouble r = 10.8; // radius of circledouble a = pi * r * r; // compute areaSystem.out.println("Area of circle is " + a);

}

}

Page 23: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 23/119

23

P rimiti v e Type: ch a r 16-bit data type used to store characters.

R ange:0 to 65536 .

Example:ch a r c = µ a¶;

Usage:

1) R epresents both ASCII and Unicode character sets; Unicode defines acharacter set with characters found in (almost) all human languages.2 ) Not the same as in C/C++ where char is 8-bit and represents ASCII

only.

Page 24: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 24/119

24

Example char // Demonstrate char data type.class CharDemo {

public static void main(String args[]) {char ch1, ch2;ch1 = 88; // code for Xch2 = 'Y';System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);}}

Page 25: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 25/119

25

P rimiti v e Type: boole a n

Two-valued type of logical values.

R ange: values true and false .

Example:boolean b = (1< 2 );

Usage:

1) returned by relational operators, such as 1< 22 ) required by branching expressions such as if or for

Page 26: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 26/119

26

Example boolean

class BoolTest { public static void main(String args[]) {

boolean b; b = false;

System.out.println("b is " + b); b = true;

System.out.println("b is " + b);if (b) System.out.println("executed");

b = false;if (b) System.out.println(³not executed");

System.out.println("10 > 9 is " + (10 > 9));}}

Page 27: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 27/119

27

Java Liter a ls

Literals are tokens that do not change -they are constant.The different types of literals in Java are: ± Integer Literals ± Floating-Point Literals ± Boolean Literals

± Character Literals ± String Literals

Page 28: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 28/119

28

Integer Liter a ls

Integer literals come in different formats: ± decimal, example: 1 2

± hexadecimal, example: 0xC ± octal, example: 014

Integer literals are of type int by default.Integer literal written with ³L´ are of typelong e.g. 1 2 3L

Page 29: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 29/119

29

Flo

ating

Point Liter

alsR epresents decimals with fractional parts

± Example: 3.1416Can be expressed in standard or scientific

notation e.g.583.45 (standard),5.8345e 2 (scientific)

Floating-point literals are of type double bydefault.Floating-point literal written with ³F´ are of typefloat e.g. 2 .0005e3F

Page 30: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 30/119

30

Boolean Literals

Boolean literals have only two values, trueor false .Those values do not convert to anynumerical representation.In particular:1) true is not equal to 12 ) false is not equal to 0

Page 31: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 31/119

31

Character LiteralsCharacter Literals represent single Unicode characters.Unicode character

± A 16-bit character set that replaces the 8-bit ASCIIcharacter set.

± Unicode allows the inclusion of symbols and specialcharacters from other languages.To use a character literal, enclose the character in singlequote delimiter. For example

± the letter a, is represented as µa¶.

± special characters such as a newline character, abackslash is used followed by the character code. For example, µ\n¶ for the newline character, µ\r¶ for thecarriage return, µ\b¶ for backspace.

Page 32: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 32/119

32

String Literals

String is not a simple type.String literals are character-sequences enclosed indouble quotes.

An example of a string literal is, ³Hello World!´.Notes:1) escape sequences can be used inside string literals2 ) string literals must begin and end on the same line3) unlike in C/C++, in Java String is not an array of characters

Page 33: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 33/119

33

V ariables A variable is an item of data used to store thestate of objects.

A variable has a: ± data type, which indicates the type of valuethat the variable can hold. ± name, it must follow rules for identifiers.

Declare a variable as follows: < data type> < name> [=initial value];

Note: V alues enclosed in <> are requiredvalues, while those values in [] are optional.

Page 34: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 34/119

34

V ariable DeclarationWe can declare several variables at the sametime, We can declare several variables at thesame time:

type identifier [=value][, identifier [=value] «];

Examples:int a, b, c;

int d = 3, e, f = 5; byte hog = 22;

double pi = 3.14159;char kat = 'x';

Page 35: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 35/119

35

Constant Declaration

A variable can be declared as final:

final double PI = 3.14;

The value of the final variable cannotchange after it has been initialized:

PI = 3.13; // Not allowed

Page 36: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 36/119

36

V ariable InitializationDuring declaration, variables may be optionallyinitialized.Initialization can be static or dynamic:1) static initialize with a literal:int n = 1;2 ) dynamic initialize with an expressioncomposed of any literals, variables or methodcalls available at the time of initialization:int m = n + 1;The types of the expression and variable mustbe the same.

Page 37: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 37/119

37

Coding GuidelinesIt always good to initialize your variables as you declare them.Use descriptive names for your variables. Like for example, if you wantto have a variable that contains a grade for a student, name it as, gradeand not just some random letters you choose.

Declare one variable per line of code. For example, the variabledeclarations,

double exam=0;double quiz=10;double grade = 0;

is preferred over the declaration,double exam=0, quiz=10, grade=0;

Page 38: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 38/119

38

O utputting V a ria ble D a ta

public class OutputVariable { public static void main( String[] args ){

int value = 10;char x;x = µA¶;

System.out.println( value );System.out.println( ³The value of x=³ + x );

}}

The program will output the following text on screen:

10The value of x=A

Page 39: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 39/119

39

P rimiti ve a nd Reference V a ria bles

Two types of variables in Java: ± Primitive V ariables ± R eference V ariablesPrimitive V ariables

± variables with primitive data types such as int or long. ± stores data in the actual memory location of the variableR eference V ariables

± variables that stores the address in the memory location

± points to another memory location where the actual data is ± When you declare a variable of a certain class, you areactually declaring a reference variable to the object with thatcertain class.

Page 40: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 40/119

40

Example

Suppose we have two variables with datatypes int and String.

int num = 10; // primitive typeString name = "Hello"; // reference type

Page 41: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 41/119

41

Arrays An array is a group of liked-typed variablesreferred to by a common name, with individualvariables accessed by their index.

Arrays are:1) declared2 ) created3) initialized4) used

Also, arrays can have one or several dimensions.

Page 42: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 42/119

42

Array Declaration

Array declaration involves:1) declaring an array identifier 2 ) declaring the number of dimensions3) declaring the data type of the array elementsTwo styles of array declaration:

type array-variable[];

or

type [] array-variable;

Page 43: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 43/119

43

Array Creation After declaration, no array actually exists.In order to create an array, we use the newoperator:

type array-variable[];array-variable = new type[size];

This creates a new array to hold size elementsof type type, which reference will be kept in thevariable array-variable.

Page 44: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 44/119

44

Array Indexing

Later we can refer to the elements of this arraythrough their indexes:

array-variable[index]

The array index always starts with zero!

The Java run-time system makes sure that allarray indexes are in the correct range, otherwiseraises a run-time error.

Page 45: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 45/119

45

Array Useclass Array {

public static void main(String args[]) {int monthDays[];

monthDays = new int[12]; monthDays[0] = 31; monthDays[1] = 28;

monthDays[2] = 31; monthDays[3] = 30; monthDays[4] = 31; monthDays[5] = 30;

« monthDays[12] = 31;

System.out.print(³April has ́ );System.out.println(monthDays[3] +³ days.´);

}}

Page 46: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 46/119

46

Array Initialization

Arrays can be initialized when they are declared:

int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};

Comments:1) there is no need to use the new operator 2 ) the array is created large enough to hold all specifiedelements

Page 47: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 47/119

47

Multidimensional Arrays

Multidimensional arrays are arrays of arrays:1) declaration

int array[][];2 ) creation

int array = new int[2][3];

3) initializationint array[][] = { {1, 2, 3}, {4, 5, 6} };

Page 48: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 48/119

48

Example: Multidimensional Arrays

class Array { public static void main(String args[]) {

int array[][] = { {1, 2, 3}, {4, 5, 6} };int i, j, k = 0;for(i=0; i < 2; i++) {

for(j=0; j < 3; j++)System.out.print(array[i][j] + ³ ");

System.out.println();

}}

}

Page 49: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 49/119

49

O perators

Java operators are used to build value expressions.

Java provides a rich set of operators:

1) assignment2 ) arithmetic3) relational4) logical

5) bitwise6) other

Page 50: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 50/119

50

Assignment O perator

A binary operator:variable = expression;

It assigns the value of the expression to the variable.The types of the variable and expression must becompatible.

The value of the whole assignment expression is the

value of the expression on the right, so it is possible tochain assignment expressions as follows:int x, y, z;x = y = z = 2;

Page 51: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 51/119

51

A rithmetic O per a tors

Page 52: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 52/119

52

Arithmetic O perators

Java supports arithmetic operators for:- integer numbers- floating-point numbers

Note: ± When an integer and a floating-point number are usedas operands to a single arithmetic operation, the result is

a floating point. The integer is implicitly converted to afloating-point number before the operation takes place.

Page 53: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 53/119

53

Increment a nd Decrement O per a tors

unary increment operator (++)unary decrement operator (--)Increment and decrement operators increase anddecrease a value stored in a number variable by 1.For example, the expression,count=count + 1 ; //increment the value of count by 1is equivalent to,count++;

Page 54: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 54/119

54

Increment a nd Decrement O per a tors

Page 55: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 55/119

55

Increment a nd Decrement O per a torsThe increment and decrement operators can be placed before or

after an operand.

When used before an operand, it causes the variable to beincremented or decremented by 1, and then the new value is used inthe expression in which it appears. For example,int i = 10;

int j = 3;int k = 0;k = ++j + i; //will result to k = 4+10 = 14

When the increment and decrement operators are placed after theoperand, the old value of the variable will be used in the expressionwhere it appears. For example,int i = 10;int j = 3;int k = 0;k = j++ + i; //will result to k = 3+10 = 13

Page 56: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 56/119

56

Example: Increment/Decrement

class IncDec { public static void main(String args[]) {

int a = 1;int b = 2;int c, d;c = ++b;d = a++;c++;System.out.println(³a= ³ + a);

System.out.println(³b= ³ + b);System.out.println(³c= ³ + c);System.out.println(³d= ³ + d);

}}

Page 57: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 57/119

57

Rel a tion a l O per a tors

Page 58: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 58/119

58

R elational O perator

R elational operators determine therelationship that one operand has to theother operand, specifically equality andordering.The outcome is always a value of typeboolean i.e. true or false.They are most often used in branchingand loop control statements.

Page 59: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 59/119

59

Logical O perator

& op1 & op2 Logical AND

| op1 | op2 Logical OR

&& op1 && op2 Short-circuitAND

|| op1 || op2 Short-circuit

OR! ! op Logical NOT

^ op1 ̂ op2 Logical XOR

Page 60: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 60/119

60

Logical O perator

Logical operators act upon boolean operands only.The outcome is always a value of type boolean.In particular, AND and OR logical operators occur in two forms:1) full op1 & op 2 and op1 | op 2 where both op1and op 2 are evaluated2 ) short-circuit - op1 && op 2 and op1 || op 2 whereop2 is only evaluated if the value of op1 isinsufficient to determine the final outcome

Page 61: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 61/119

61

Example: Logical O perators

class LogicalDemo { public static void main(String[] args) {

int n = 2;if (n != 0 && n / 0 > 10)

System.out.println("This is true");else

System.out.println("This is false");}

}

Page 62: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 62/119

62

Bitwise O perators

Bitwise operators apply to integer types only.They act on individual bits of their operands.

There are three kinds of bitwise operators:1) basic bitwise AND, OR , NO T and X OR

2 ) shifts left, right and right-zero-fill3) bitwise assignment for all basic and shift

operators

Page 63: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 63/119

Page 64: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 64/119

64

Example: Bitwise O peratorsclass BitLogic { public static void main(String args[]) {

String binary[] = { "0000","0001","0010", « };int a = 3; // 0 + 2 + 1 or 0011 in binaryint b = 6; // 4 + 2 + 0 or 0110 in binaryint c = a | b;int d = a & b;int e = a ^ b;System.out.print("a =" + binary[a]);System.out.println("and b =" + binary[b]);System.out.println("a|b = " + binary[c]);

System.out.println("a&b = " + binary[d]);System.out.println("a^b = " + binary[e]);}

}

Page 65: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 65/119

65

O ther O perators? : shortcut if-else statement / conditional operator

[ ] used to declare arrays, create arrays, access arrayelements

. used to form qualified names

(p a r a ms) delimits a comma-separated list of parameters

(type) casts a value to the specified type

new creates a new object or a new array

inst a nceof determines if its first operand is an instance of thesecond

Page 66: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 66/119

66

Conditional O perator General form:expr1? expr 2 : expr3Where:1) expr1 is of type boolean2 ) expr 2 and expr3 are of the same type

If expr1 is true, expr 2 is evaluated,otherwise expr3 is evaluated.

Page 67: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 67/119

67

Example: Conditional O perator class Ternary {

public static void main(String args[]) {int i, k;i = 10;k = i < 0 ? -i : i;System.out.print("Abs value of ³ + i + " is " + k);i = -10;k = i < 0 ? -i : i;System.out.print("Abs value of ³ + i + " is " + k);

}

}

Page 68: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 68/119

Page 69: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 69/119

69

O perator Precedence

Page 70: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 70/119

70

Type Differences

Suppose a value of one type is assignedto a variable of another type.T1 t1;T2 t2 = t1;What happens? Different situations:1) types T1 and T 2 are incompatible2 ) types T1 and T 2 are compatible:

a) T1 and T 2 are the sameb) T1 is larger than T 2

c) T2 is larger than T1

Page 71: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 71/119

71

Type Comaptibility

When types are compatible?1) integer types and floating-point types arecompatible with each other 2 ) numeric types are not compatible with char or boolean3) char and boolean are not compatible witheach other Examples:

byte b;int i = b;char c = b; // Not allowed

Page 72: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 72/119

72

Widening Type ConversionJava performs automatic type conversionwhen:1) two types are compatible

2 ) destination type is larger than thesource typeExample:

int i;double d = i;

Page 73: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 73/119

Page 74: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 74/119

74

Type CastingGeneral form: (targetType) valueExamples:1) integer value will be reduced module byte¶srange:int i;

byte b = (byte) i;2 ) floating-point value will be truncated to integer value:float f;int i = (int) f;

Page 75: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 75/119

75

Example: Type Castingclass Conversion {

public static void main(String args[]) { byte b;

int i = 257;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("\ndouble to int.");i = (int) d;System.out.println("d and i " + d + " " + i);

}}

Page 76: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 76/119

76

Type Promotion

In an expression, precision required to hold anintermediate value may sometimes exceed therange of either operand:

byte a = 40; byte b = 50; byte c = 100;

int d = a * b / c;

Java promotes each byte operand to int whenevaluating the expression.

Page 77: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 77/119

77

Type Promotion R ules1) byte and short are always promoted to int2 ) if one operand is long, the whole expression is

promoted to long3) if one operand is float, the entire expression is

promoted to float4) if any operand is double, the result is double

Danger of automatic type promotion: byte b = 50; b = b * 2;

What is the problem?

Page 78: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 78/119

78

Example: Type Promotionclass Promote {

public static void main(String args[]) { byte b = 42;

char c = 'a';short s = 1024;int i = 50000;float f = 5.67f;double d = .1234;double result = (f * b) + (i / c) - (d * s);System.out.println("result = " + result);

}}

Page 79: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 79/119

79

Exercise: O perators1) What operators do the code snippet below contain?

arrayOfInts[j] > arrayOfInts[j+1];

2 ) Consider the following code snippet:int i = 10;int n = i++%5;

a) What are the values of i and n after the code is executed?b) What are the final values of i and n if instead of using the postfixincrement operator (i++), you use the prefix version (++i))?

3) What is the value of i after the following code snippet executes?int i = 8;i >>=2;

4) What¶s the result of System.out.println(010| 4); ?

Page 80: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 80/119

80

Control F low

Page 81: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 81/119

81

Control Flow

Writing a program means typing statements intoa file.

Without control flow, the interpreter wouldexecute these statements in the order theyappear in the file, left-to-right, top-down.

Control flow statements, when inserted into thetext of the program, determine in which order theprogram should be executed.

Page 82: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 82/119

82

Control Flow Statements

Java control statements cause the flow of execution toadvance and branch based on the changes to the stateof the program.Control statements are divided into three groups:

1) selection statements allow the program to choosedifferent parts of the execution based on the outcome of an expression

2 ) iteration statements enable program execution to repeat

one or more statements3) jump statements enable your program to execute in a

non-linear fashion

Page 83: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 83/119

83

Selection Statements

Java selection statements allow to control theflow of program¶s execution based uponconditions known only during run-time.Java provides four selection statements:

1) if2) if-else

3) if-else-if4) switch

Page 84: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 84/119

84

if Statements

General form:if (expression) statement

If expression evaluates to true , executestatement , otherwise do nothing.

The expression must be of type boolean .

Page 85: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 85/119

85

Simple/Compound Statements

Simpleif (expression) statement;

Compoundif (expression) {

statement;

}

Page 86: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 86/119

86

if-else Statements

Suppose you want to perform two differentstatements depending on the outcome of aboolean expression. if-else statement canbe used.General form:if (expression) statement1else statement2

Again, statement1 and statement 2 may besimple or compound.

Page 87: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 87/119

Page 88: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 88/119

88

Example: if-else-if class IfElse {

public static void main(String args[]) {int month = 4;String season;if (month == 12 || month == 1 || month == 2)

season = "Winter";

else if(month == 3 || month == 4 || month == 5)season = "Spring";else if(month == 6 || month == 7 || month == 8)

season = "Summer";else if(month == 9 || month == 10 || month == 11)

season = "Autumn";else season = "Bogus Month";System.out.println("April is in the " + season +".");

}}

Page 89: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 89/119

89

switch Statements

switch provides a better alternative than if-else-if when the execution follows several branchesdepending on the value of an expression.

General form:switch (expression) {

case value1: statement1; break;case value2: statement2; break;case value3: statement3; break;«default: statement;

}

Page 90: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 90/119

90

switch Assumptions/Semantics Assumptions:1) expression must be of type byte, short, int or char 2 ) each of the case values must be a literal of thecompatible type3) case values must be uniqueSemantics:1) expression is evaluated2 ) its value is compared with each of the case values3) if a match is found, the statement following the case isexecuted

4) if no match is found, the statement following default isexecutedbreak makes sure that only the matching statement isexecuted.Both default and break are optional.

E l i h

Page 91: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 91/119

91

Example: switchclass Switch {

public static void main(String args[]) {int month = 4;String season;switch (month) {

case 12:case 1:case 2: season = "Winter"; break;case 3:case 4:case 5: season = "Spring"; break;case 6:case 7:case 8: season = "Summer"; break;

case 9:case 10:case 11: season = "Autumn"; break;default: season = "Bogus Month";

}System.out.println("April is in " + season + ".");

}

Page 92: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 92/119

Page 93: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 93/119

93

Comparing switch and if

Two main differences:

1) switch can only test for equality, while if

can evaluate any kind of booleanexpression

2 ) Java creates a ³jump table´ for switchexpressions, so a switch statement isusually more efficient than a set of nestedif statements

Page 94: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 94/119

94

iteration Statements

Java iteration statements enable repeatedexecution of part of a program until acertain termination condition becomes true.

Java provides three iteration statements:

1) while2 ) do-while3) for

h l

Page 95: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 95/119

95

while Statements

General form: while ( expression ) statement

where expression must be of type boolean.

Semantics:1. repeat execution of statement until

expression becomes false

2. expression is always evaluated beforestatement3. if expression is false initially, statement will

never get executed

E l hil

Page 96: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 96/119

96

Example: while

class MidPoint { public static void main(String args[]) {int i, j;i = 100;j = 200;

while(++i < --j) {System.out.println(³i is " + i);System.out.println(³j is " + j);

}

System.out.println(³The midpoint is " +i);}

}

d hil S

Page 97: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 97/119

97

do-while Statements

If a component statement has to be executed at leastonce, the do-while statement is more appropriate thanthe while statement.General form:

do statement while ( expression );

where expression must be of type boolean.Semantics:

1. repeat execution of statement until expression becomesfalse

2 . expression is always evaluated after statement3. even if expression is false initially, statement will be

executed

E l d hil

Page 98: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 98/119

98

Example: do-while

class DoWhile { public static void main(String args[]) {

int i;i = 0;do

i++; while ( 1/i < 0.001);

System.out.println(³i is ³ + i);}

}

f S

Page 99: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 99/119

99

for Statements

When iterating over a range of values, for statement ismore suitable to use than while or do-while.General form:

for (initialization; termination; increment)

statement

where:1. initialization statement is executed once before the first

iteration2 . termination expression is evaluated before each iteration

to determine when the loop should terminate3. increment statement is executed after each iteration

f S

Page 100: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 100/119

100

for Statements

This is how the for statement is executed:1. initialization is executed once2 . termination expression is evaluated:

a) if false, the statement terminatesb) otherwise, continue to (3)

3. increment statement is executed4. component statement is executed5. control flow continues from ( 2 )

Page 101: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 101/119

101

Loop Control V ariable

The for statement may include declarationof a loop control variable:

for (int i = 0; i < 1000; i++) {«

}

The variable does not exist outside the for statement.

Example: for

Page 102: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 102/119

102

Example: for class FindPrime {

public static void main(String args[]) {int num = 14;

boolean isPrime = true;for (int i=2; i < num/2; i++) {

if ((num % i) == 0) {isPrime = false; break;

}}if (isPrime)

System.out.println("Prime");else System.out.println("Not Prime");

}}

Many Initialization/Iteration parts

Page 103: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 103/119

103

Many Initialization/Iteration parts

The for statement may include several initialization anditeration parts.Parts are separated by a comma:

int a, b;

for (a = 1, b = 4; a < b; a++, b--) {«}

for Statement V ariations

Page 104: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 104/119

104

for Statement V ariations

The for statement need not have all components:class ForVar {

public static void main(String args[]) {int i = 0;

boolean done = false;for( ; !done; ) {

System.out.println("i is " + i);if(i == 10) done = true;i++;

}

}}

Page 105: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 105/119

Page 106: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 106/119

106

Jump StatementsJava jump statements enable transfer of controlto other parts of program.

Java provides three jump statements:1) break2 ) continue3) return

In addition, Java supports exception handlingthat can also alter the control flow of a program.

b k

Page 107: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 107/119

107

break Statements

The break statement has three uses:1. to terminate a case inside the switch

statement2 . to exit an iterative statement3. to transfer control to another statement

(1) has been described.We continue with ( 2 ) and (3).

L E i i h b k

Page 108: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 108/119

108

Loop Exit with breakWhen break is used inside a loop, the loop terminatesand control is transferred to the following instruction.

class BreakLoop { public static void main(String args[]) {

for (int i=0; i < 100; i++) {if (i == 10) break;System.out.println("i: " + i);

}System.out.println("Loop complete");

}}

b k i N d L

Page 109: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 109/119

109

break in Nested LoopUsed inside nested loops, break will only terminate the innermost loop:

class NestedLoopBreak { public static void main(String args[]) {

for (int i=0; i < 3; i++) {System.out.print("Pass " + i + ": ");

for (int j=0; j < 100; j++) {if (j == 10) break;System.out.print(j + " ");

}System.out.println();

}System.out.println("Loops complete.");}

}

C l T f i h b k

Page 110: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 110/119

110

Control Transfer with breakJava does not have an unrestricted ³goto´statement, which tends to produce code that ishard to understand and maintain.However, in some places, the use of gotos is well

justified. In particular, when breaking out from thedeeply nested blocks of code.break occurs in two versions:

1) unlabelled

2 ) labeledThe labeled break statement is a ³civilized´replacement for goto.

L b l d b k

Page 111: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 111/119

111

Labeled break

General form: break label;

where label is the name of a label that

identifies a block of code:label: { « }

The effect of executing break label; is to

transfer control immediately after the blockof code identified by label.

E l L b l d b k

Page 112: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 112/119

112

Example: Labeled breakclass Break {public static void main(String args[]) {

boolean t = true;first: {

second: {third: {

System.out.println("Before the break.");if (t) break second;System.out.println("This won't execute");

}System.out.println("This won't execute");

}System.out.println(³After second block.");}

}}

E l N d L b k

Page 113: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 113/119

113

Example: Nested Loop breakclass NestedLoopBreak { public static void main(String args[]) {

outer: for (int i=0; i < 3; i++) {System.out.print("Pass " + i + ": ");for (int j=0; j < 100; j++) {

// exit both loopsif (j == 10) break outer;System.out.print(j + " ");

}System.out.println("This will not print");

}System.out.println("Loops complete.");

}}

continue Statement

Page 114: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 114/119

114

continue Statement

The break statement terminates the block of code, inparticular it terminates the execution of an iterativestatement.The continue statement forces the early terminationof the current iteration to begin immediately the next

iteration.Like break, continue has two versions:

1. unlabelled ± continue with the next iteration of thecurrent loop

2 . labeled ± specifies which enclosing loop to continue

Example: Unlabeled continue

Page 115: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 115/119

115

Example: Unlabeled continue

class Continue { public static void main(String args[])

{for (int i=0; i < 10; i++) {

System.out.print(i + " ");if (i%2 == 0) continue;System.out.println("");

}

}}

Example: Labeled continue

Page 116: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 116/119

116

Example: Labeled continue

class LabeledContinue { public static void main(String args[]) {outer: for (int i=0; i < 10; i++) {

for (int j=0; j < 10; j++) {if (j > i) {

System.out.println();continue outer;}System.out.print(" " + (i * j));

}

}System.out.println();}

}

return Statement

Page 117: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 117/119

117

return Statement

The return statement is used to return from thecurrent method: it causes program control to transfer back to the caller of the method.Two forms:

1) return without valuereturn;

2 ) return with valuereturn expression;

Example: return

Page 118: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 118/119

118

Example: return

class Return { public static void main(String args[]) {

boolean t = true;System.out.println("Before the return.");

if (t) return; // return to callerSystem.out.println("This won't execute.");

}}

Exercise: Control Flow

Page 119: Java_Basics

8/7/2019 Java_Basics

http://slidepdf.com/reader/full/javabasics 119/119

Exercise: Control Flow

1. Write a program that prints all the prime numbers between1 and 49 to the console.

2 . Write a program that prints the first 2 0 Fibonacci numbers.

The Fibonacci numbers are defined as follows:The zeroth Fibonacci number is 1.The first Fibonacci number is also 1.The second Fibonacci number is 1 + 1 = 2 .

The third Fibonacci number is 1 + 2 = 3.In other words, except for the first two numbers each Fibonacci number is the sum of the two previous numbers.