Java programming Prof Rohini S Hanchate Pimpri Chinchawad

  • Slides: 106
Download presentation
Java programming Prof. Rohini S Hanchate Pimpri Chinchawad polytechnic (PCP)

Java programming Prof. Rohini S Hanchate Pimpri Chinchawad polytechnic (PCP)

Contents Why java? ? Java Introduction Java Features How Java Differs from other Object

Contents Why java? ? Java Introduction Java Features How Java Differs from other Object Oriented languages

Why java? ? It’s entirely object-oriented It has a vast library of predefined objects

Why java? ? It’s entirely object-oriented It has a vast library of predefined objects and operations It’s more platform independent this makes it great for Web programming It’s more secure It isn’t C++

Java - An Introduction Java - The new programming language developed by Sun Microsystems

Java - An Introduction Java - The new programming language developed by Sun Microsystems in 1991. Originally called Oak by James Gosling, one of the inventors of the Java Language. Java Authors: James , Arthur Van , and others Java is purely object oriented.

Java Introduction Originally created for consumer electronics (TV, VCR, Freeze, Washing Machine, Mobile Phone).

Java Introduction Originally created for consumer electronics (TV, VCR, Freeze, Washing Machine, Mobile Phone). Java - Machine Independent language Java is language of Internet Programming. It allows you to publish a webpage with Java code in it.

Java Milestones Year Development 1990 Sun decided to developed special software that could be

Java Milestones Year Development 1990 Sun decided to developed special software that could be used for electronic devices. A project called Green Project created and head by James Gosling. 1991 Explored possibility of using C++, with some updates announced a new language named “Oak” 1992 The team demonstrated the application of their new language to control a list of home appliances using a hand held device. 1993 The World Wide Web appeared on the Internet and transformed the text-based interface to a graphical rich environment. The team developed Web applets (time

Java Milestones Year Development 1994 The team developed a new Web browsed called “Hot

Java Milestones Year Development 1994 The team developed a new Web browsed called “Hot Java” to locate and run Applets. Hot. Java gained instance success. 1995 Oak was renamed to Java, as it did not survive “legal” registration. Many companies such as Netscape and Microsoft announced their support for Java 1996 Java established itself it self as “the language for Internet programming” and Object Oriented language. 1997 - A class libraries, Community effort and standardization, Enterprise Java, Clustering, etc. .

Java Attributes Familiar, Simple, Small Compiled and Interpreted Platform-Independent and Portable Object-Oriented Robust and

Java Attributes Familiar, Simple, Small Compiled and Interpreted Platform-Independent and Portable Object-Oriented Robust and Secure Distributed Multithreaded and Interactive High Performance Dynamic and Extensible

Java is Compiled and Interpreted Hardware and Operating System Programmer Source Code Text Editor

Java is Compiled and Interpreted Hardware and Operating System Programmer Source Code Text Editor Byte Code Compiler . java file Notepad, emacs, vi Interpreter. class file javac java appletviewer netscape

Compiled Languages Programmer Source Code Text Editor Executable Code linker . o file a.

Compiled Languages Programmer Source Code Text Editor Executable Code linker . o file a. out file Compiler. c file Notepad, emacs, vi Object Code gcc

Total Platform Independence JAVA COMPILER (translator) JAVA BYTE CODE (same for all platforms) JAVA

Total Platform Independence JAVA COMPILER (translator) JAVA BYTE CODE (same for all platforms) JAVA INTERPRETER (one for each different system) Windows 95 Macintosh Solaris Windows NT

Architecture Neutral & Portable Java Compiler - Java source code(. java file) to byte

Architecture Neutral & Portable Java Compiler - Java source code(. java file) to byte code (file with. class) Bytecode - an intermediate form, closer to machine representation A interpreter interprets the bytecode.

Architecture Neutral & Portable Porting the java system to any new platform any where

Architecture Neutral & Portable Porting the java system to any new platform any where any time. The interpreter will figure out what the equivalent machine dependent code to run.

Rich Class Environment Core Classes language Utilities Input/Output Low-Level Networking Graphical User Interface Internet

Rich Class Environment Core Classes language Utilities Input/Output Low-Level Networking Graphical User Interface Internet Classes TCP/IP Networking WWW and HTML Distributed Programs

How Does Java Compares to C++ and Other OO Languages

How Does Java Compares to C++ and Other OO Languages

Overlap of C, C++, and Java C++ C Java

Overlap of C, C++, and Java C++ C Java

Java better than C++ ? No No Typedefs, Defines, or Preprocessor Global Variables Goto

Java better than C++ ? No No Typedefs, Defines, or Preprocessor Global Variables Goto statements Pointers Unsafe Structures Multiple Inheritance Operator Overloading

Object Oriented Languages -A Comparison Feature Encapsulation Inheritance Multiple Inherit. Polymorphism C++ Objective C

Object Oriented Languages -A Comparison Feature Encapsulation Inheritance Multiple Inherit. Polymorphism C++ Objective C Java Yes Yes No Yes Yes

Simple java program Class first_program { Public static void main(String args[]) { System. out.

Simple java program Class first_program { Public static void main(String args[]) { System. out. println(“hellow world”); } } Class method

Simple java program cntd. . . Public: The keyword public is an access specifies

Simple java program cntd. . . Public: The keyword public is an access specifies that declares the main method as unprotected. Static: Which declares main method as one that belongs to the entire class , The main must always declare as static since the interpreter uses this method before any objects are created. If static keyword is specified then it is invoked first and no object creation is done for method Void: The type modifier void states that the main method does not return any value. Main() it is method to

JAVA Tokens Smallest individual units in a program are known as Tokens. Five different

JAVA Tokens Smallest individual units in a program are known as Tokens. Five different types of tokens: Reserved Keywords. (60 Keywords, false, null, true, package etc. , ). Identifiers (alphabets, digits and underscore and dollar sign characters. ) Literals. (Integer, Floating Point. Character, String, Boolean) Operators. Separators.

Tokens cntd. . (Keywords) Java language is having reserved 50 word as keywords. abstract

Tokens cntd. . (Keywords) Java language is having reserved 50 word as keywords. abstract assert boolean break byte case catch char class const continue deafult do double Else enum extends finally float for goto if implements

Tokens cntd. . (identifiers) These are programer designed tokens. Classes. Methods Variables. Objects Labels

Tokens cntd. . (identifiers) These are programer designed tokens. Classes. Methods Variables. Objects Labels Packages Interfaces

Identfiers cntd. . . Rules for identifiers: Alphabets, digits, underscore(_)and $ are allowed. They

Identfiers cntd. . . Rules for identifiers: Alphabets, digits, underscore(_)and $ are allowed. They must not begin with digit. Uppercase and lowercase letters are distinct. Identifier can be of any length. Identfiers must be meaningful. Short, easy, quick. Easily readable and discriptive. Eg: average, day. Temerature, first_name, TOTAL.

Literals are sequence of characters. 5 types of literals Integer literals Floating point literals

Literals are sequence of characters. 5 types of literals Integer literals Floating point literals Charester literals String literals Boolean literals

Operators An operator is symbol that takes one or more arguments and operates on

Operators An operator is symbol that takes one or more arguments and operates on them to produce results.

Separators Symbols used to indicate where groups of code are divided and arranged. Parentheses

Separators Symbols used to indicate where groups of code are divided and arranged. Parentheses () Method definition and invocation, defining precedence in expressions Braces {} Define a block of code for classes, methods and local scopes Brackets [] Declare array types and for dereferencing array values. Semicolon ; Separate the statements. Comma , Consecutive identifiers in a variable declaration and chain statements (For loop and int a, b) Period. Separate package names from the sub-packages and class, separate a variable or method from a reference

Costants Constant in java refered to fixed values that do not change during execution

Costants Constant in java refered to fixed values that do not change during execution of a program. Numeric constants Integer constants Real constants Charecter constants Charechter constants String constants

Constants cntd. . Integer constants: it refer as sequence of digits Decimal integer constant

Constants cntd. . Integer constants: it refer as sequence of digits Decimal integer constant consist of set of digit from 0 to 9 eg. 123 Octal integer constants consist of from 0 to 7 eg. 037, 0435 Real constants: numbers contain fractional parts refered to real constants eg 0. 67878 Character constants: single character enclosed within a pair of single quotes eg. '4', 'a'. String constants: a sequence of charater encloused with in double qoutes eg. “hello”, ” 1998”.

Backslash character constants meaning ‘b’ Back Space. ‘f’ Form Feed. ‘n’ New line ‘t’

Backslash character constants meaning ‘b’ Back Space. ‘f’ Form Feed. ‘n’ New line ‘t’ Horizontal tab '' Single qoute '\' backslash

Symboliuc constants Symbolic names take the same form as variable names. SC's are written

Symboliuc constants Symbolic names take the same form as variable names. SC's are written in CAPITALS to distinguish them from normal variable names. they should not be assigned any other value within the program after declaration of symbolic constants by using an assignment statement. eg. final int PEOPLE = 100; //we can not change the value. This is not done in C and C++ where it is defined using the #define statement.

Variables Variable is an idenitfier that denotes a storage location used to store data

Variables Variable is an idenitfier that denotes a storage location used to store data value. Variable may take different value at different times during execution of the program Variable name should be Meaningful. Variable must not begin with a digit. Uppercase and lower case letters are distinct. It should not be keyword.

Declaration of variables Variable are names of storage locations. After designing suitable variable names

Declaration of variables Variable are names of storage locations. After designing suitable variable names we must declare them to the compiler Why declaration? ? ? It tells the variable name to compiler Type of data that variable holding Place of variable decides scope of the variables Variable must be declared before it used in program • Variable used to store value of any data type. • •

Declaration of variable cntd… Type variable 1, variable 2, variable 3……. ; • Variables

Declaration of variable cntd… Type variable 1, variable 2, variable 3……. ; • Variables are separated by comma’s (, ) • Declaration statement should end with ; . Eg , int count; float area; double p 1; char c 1, c 2, c 3;

Assigning values to variables • Using assignment statement Variable_Name = value; Eg intial. Value=0;

Assigning values to variables • Using assignment statement Variable_Name = value; Eg intial. Value=0; final. Value=100; • String assignment eg x=y=z=0; • Assign values at declaration time Eg int final. Value=100; Char yes = ‘x’;

Scope of variable • Instance variable • Class variable • Local variable Instance and

Scope of variable • Instance variable • Class variable • Local variable Instance and class variables are declared inside a class. Instance variables are created when the object are initiated and those variables are associated with the object. Instance variable take different values for each object

 Class variables are global to class. Belongs to objects that class creates Only

Class variables are global to class. Belongs to objects that class creates Only one memory location is created for class variables. Variables used and defined inside the method are local variables Not available to outside the method definition.

Eg : statement 1; { int x=0; \ available to all { int n=5;

Eg : statement 1; { int x=0; \ available to all { int n=5; \ only with in braces } Statment 2; { int m=20; \ local variable } }

Type casting • Want store variable of one type in into a variable of

Type casting • Want store variable of one type in into a variable of other type. Type variable 1 = (type) variable 2; • It is converting one data type to another is known as casting. Eg int m= 12; byte n =(byte) m; Long count = (long) m;

Casting with no loss of information From To Byte Short, char, int, long, float,

Casting with no loss of information From To Byte Short, char, int, long, float, double Short Int, long, float, double Char Int, long, float, double Int Long, float, double Long Float, double Float double

Data types • Every variable is having Data type • Data type specify size

Data types • Every variable is having Data type • Data type specify size and type of values that can be stored. • Depend on need of application select appropriate data type Category of Data Types • Primitive type • Derived type

DT cntd…

DT cntd…

Integer types Java support 4 types of integers.

Integer types Java support 4 types of integers.

Floating point Data types Type Size Value Float 4 bytes 3. 4 e-038 to

Floating point Data types Type Size Value Float 4 bytes 3. 4 e-038 to 3. 4 e+038 Double 8 bytes 1. 7 e-308 to 1. 7 e+308

DT cntd. . Character type • To store character constants in memory. • Size

DT cntd. . Character type • To store character constants in memory. • Size is 2 bytes Boolean type • To test particular condition we use Boolean type. • Only two values it takes True & False. • All comparison operators return Boolean type.

Standard default values • Every variable has default values. Type of variable Default values

Standard default values • Every variable has default values. Type of variable Default values Byte 0(zero) Short 0 int 0 Long 0 L Float 0. 0 f Double 0. 0 d Char Null Boolean False Reference null

Reading data from Keyboard Import java. lang. *; Import java. io. Data. Input. Stream;

Reading data from Keyboard Import java. lang. *; Import java. io. Data. Input. Stream; Class read { public static void main (String args []) { Data. Input. Stream in = new Data. Input. Stream (System. in) int num = 0; System. out. println (“Enter a number : ”); num = Integer. parse. Int (in. read. Line () ); System. out. println (“entered number Num = “ +num); } }

Output: Enter a Number: 123 entered number Num = 123

Output: Enter a Number: 123 entered number Num = 123

Operators Arithmetic operators Operator Meaning Example + Addition or unary plus a+b - Subtraction

Operators Arithmetic operators Operator Meaning Example + Addition or unary plus a+b - Subtraction a-b * Multiplication a*b / Division a/b % Modulo a%b

Relational operators: Compare two quantities and depend on their relation take certain decisions. Oper

Relational operators: Compare two quantities and depend on their relation take certain decisions. Oper Meaning ator Example < Less than a<b <= Less than or equal to 4. 5<=10 > Greater than b>c >= Greater than or equal to -35>=0 == Equal to a+b==c+d

Logical operators Operator Meaning Example && Logical AND a>b && x==10 || Logical OR

Logical operators Operator Meaning Example && Logical AND a>b && x==10 || Logical OR if(a<0||b>100) ! Logical NOT a!=b

Increment & decrement operators ++ increments the value of its operand by 1. --

Increment & decrement operators ++ increments the value of its operand by 1. -- decrements the value of its operand by 1. Syntax: Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable--

Increment (++) operator it is used in for and while loops. Eg. ++m, m++

Increment (++) operator it is used in for and while loops. Eg. ++m, m++ or m=m+1, or m+=1; Decrement operator (--) : Eg: --m, m=m-1, m-=1;

Example of Operator Class increment_operator { Public static void main(String args[]) { Int m=10,

Example of Operator Class increment_operator { Public static void main(String args[]) { Int m=10, n=20; System. out. println(“m = “ +m); System. out. println(“n = “ +n); System. out. println(“++m = “ + ++m); System. out. println(“n++ = “ + n++); System. out. println(“m = “ +m); System. out. println(“n = “ +n); } }

Output M=10 N =20 ++m=11 N++ =20 M=11 N=21 ------------------------------Eg: a[i++] =10; Or a[i]

Output M=10 N =20 ++m=11 N++ =20 M=11 N=21 ------------------------------Eg: a[i++] =10; Or a[i] = 10 i=i+1;

Conditional operator To construct conditional expressions exp 1 ? exp 2 : exp 3

Conditional operator To construct conditional expressions exp 1 ? exp 2 : exp 3 Where exp 1, exp 2, exp 3 are expressions • Exp 1 is true then execute exp 2 • Exp 1 is false then execute exp 3 • Only one expression is evaluated Eg: a=10, b=15, x=(a>b)? a : b

Bitwise operators • Manipulation of data at values of bit level. • This operator

Bitwise operators • Manipulation of data at values of bit level. • This operator is used to testing bits or shifting bits right or left • Not applicable to float or double

Bitwise cntd. . Operator Meaning & Bitwise AND ! Bitwise OR ^ Bitwise exclusive

Bitwise cntd. . Operator Meaning & Bitwise AND ! Bitwise OR ^ Bitwise exclusive OR ~ One’s complicate << Shift left >> Shift right >>> Shift right with zero fill

Special operator • Java supports instanceof operator and member selection operator dot(. ). •

Special operator • Java supports instanceof operator and member selection operator dot(. ). • Instanceof operator: is object reference operator. • If object is instance of the given class Person instanceof student Above statement is true if object person is belongs to class student. DOT operator (. ): Access the instance variable and methods of class objects. Access classes and sub-packages from a package • Person 1. age; //reference to variable age • Person 1. salary() //reference to method salary()

Assignment operator Assign value of an expression to variable Variable 1 op = exp;

Assignment operator Assign value of an expression to variable Variable 1 op = exp; x+=y+1; V 1 = v 2 op(exp); X=x+(y+1);

Operator precedence Expression with no parentheses evaluate from left to right » High priority

Operator precedence Expression with no parentheses evaluate from left to right » High priority * / % » Low priority + Eg: x=a-b/3+c*2 -1 A=9, b=12, c=3

Expressions Integral expressions Floating-point or decimal expressions Mixed expressions

Expressions Integral expressions Floating-point or decimal expressions Mixed expressions

Integral expressions All operands are integers. Examples: 2 + 3 * 5 3 +

Integral expressions All operands are integers. Examples: 2 + 3 * 5 3 + x – y / 7 x + 2 * (y – z) + 18

Floating-point expressions All operands are floating-point numbers. Examples: 12. 8 * 17. 5 –

Floating-point expressions All operands are floating-point numbers. Examples: 12. 8 * 17. 5 – 34. 50 x * 10. 5 + y - 16. 2

Mixed Expressions Operands of different types. Examples: 2 + 3. 5 6 / 4

Mixed Expressions Operands of different types. Examples: 2 + 3. 5 6 / 4 + 3. 9 Integer operands yield an integer result. floating-point numbers yield floating-point results. If both types of operands are present, the result is a floating-point number.

Evaluation expressions Expressions are evaluated using an assignment operator. Variable = expression; Eg; x=a*b-c;

Evaluation expressions Expressions are evaluated using an assignment operator. Variable = expression; Eg; x=a*b-c; y=b/c*a;

Type converssion of expression Automatic type concversion. Generic type conversions Used to avoid implicit

Type converssion of expression Automatic type concversion. Generic type conversions Used to avoid implicit type coercion. Syntax: (data. Type. Name) expression Expression evaluated first, then type converted to: data. Type. Name Examples: (int)(7. 9 + 6. 7) = 14 (int)(7. 9) + (int)(6. 7) = 13

Type converssions cntd. . Float to int causes truncation of fractional part Double to

Type converssions cntd. . Float to int causes truncation of fractional part Double to float causes rounding of digits Long to int causes dropping of the higher order bits Type converssions Data type Byte, short, int Promoted/Converted to int long int Int except 1 or L is appened float

Type converssions cntd. . Casting values: Syntax : (type_name) expression Eg, x= (int) 7.

Type converssions cntd. . Casting values: Syntax : (type_name) expression Eg, x= (int) 7. 5 a=(int)21. 8/(int) 3. 4 b=(double) sum/n : division by floating mode Y = (int) (a+b) X= (int) (y+0. 5)

Casting operation example Class casting { Public static void main(String args[]) { Float sum;

Casting operation example Class casting { Public static void main(String args[]) { Float sum; Int i; Sum= 0. 0 F; For(i=1; i<=10; i++) { sum=sum+1/(float) i; Syetem. out. print(“i = “ +i); Syetem. out. print(“sum = “ +sum); }}}

Operator precedence and associativity operator description associativity rank . Member selection L to R

Operator precedence and associativity operator description associativity rank . Member selection L to R 1 () Function call L to R 1 [] Array element L to R 1 - Unary minus R to L 2 ++ increment R to L 2 -- decrement R to L 2 ! Logical negation R to L 2 ~ Ones compliment R to L 2 (type) casting R to L 2

Mathematical functions Math class is defined in java. lang packages. Math. function_name(); Eg double

Mathematical functions Math class is defined in java. lang packages. Math. function_name(); Eg double y = Math. sqrt(); function action example min() Return the minimum min(a, b) max() Return maximum value max(a, b) sqrt() Return squre root value sqrt(x) pow() Return x raised to y pow(x^y) exp() Return e raised to x exp(x)= e^x round() Return integer closeset to the argument round(x)

Mathematical functions

Mathematical functions

Decision Making and Looping Control or decision making statment: it used to control the

Decision Making and Looping Control or decision making statment: it used to control the flow of execution of statement If-else statement Nested if else If else ladder Switch statement Nested switch Conditional operator

Decision making

Decision making

If statment Determines whether it is true or false Uses logical operators to compare

If statment Determines whether it is true or false Uses logical operators to compare values Syntax: if(test expression) { Statement_ block; } statement_x; Eg if(age>60) { Sytem. out. print(“Retired person”); } Sytem. out. print(“all are working on govt office”);

if. . . else statement Syntax if(test expression) { True block Statements; } else

if. . . else statement Syntax if(test expression) { True block Statements; } else { False block statements; } statement_x;

Nested if. . else statement Syntax: if(test condition 1) { if(test condition 2) {

Nested if. . else statement Syntax: if(test condition 1) { if(test condition 2) { statement— 1; } else { statement--2; } } else { statement— 3; } statement_x;

Else. . . if ladder Syntax: if(test condition 1) statement— 1; else if(test condition

Else. . . if ladder Syntax: if(test condition 1) statement— 1; else if(test condition 2) statement— 2; else if(condition 3) statement— 3; else if( condtion n) statement—n; else default-statement; statement_x;

Switch statement To reduce complexity of program. Readable statements. Reduces Misperception of program. Java

Switch statement To reduce complexity of program. Readable statements. Reduces Misperception of program. Java multi-ways of decision making statements known as switch • Set of statements are tested against list of cases when match is found a block of statement is executed. • •

Switch Syntax Switch(expression) { Case value-1: block-1 break; Case value-2: block-2 break; ……………… Default

Switch Syntax Switch(expression) { Case value-1: block-1 break; Case value-2: block-2 break; ……………… Default : default –block; break; } Statement-x;

Class switch_statement { Public static void main(String args[]) { System. out. println(“enter your choicen”);

Class switch_statement { Public static void main(String args[]) { System. out. println(“enter your choicen”); Char ch = (char) Sytem. in. read(); switch (ch) { case 0: System. out. println(“i am good in java programming”); break; case 1: System. out. println(“i dont know java”); break; default: System. out. println(“i understand c++”); }

Example of switch class guide { public static void main (String args []) {

Example of switch class guide { public static void main (String args []) { char ch; System. out. println (“Select your Choice”); System. out. println (“ M Madras”); System. out. println (“ B Bombay”); System. out. println (“ C Calcutta”); System. out. println (“ Please select any one”); try { switch (ch = (char)System. in. read() )

Class switch_statement { Public static void main(String args[]) { switch (number. Of. Passengers) {

Class switch_statement { Public static void main(String args[]) { switch (number. Of. Passengers) { case 0: out. println(“The Harley”); break; case 1: out. println(“The Dune Buggy”); break; default: out. println(“The Humvee”); } }

{ case ‘M’: case ‘m’: System. out. println (“ Madras Booklet 5”); break; case

{ case ‘M’: case ‘m’: System. out. println (“ Madras Booklet 5”); break; case ‘b’: case ‘B’: System. out. println (“ Bombay Booklet 7”); break; case ‘C’ case ‘c’ System. out. println (“ Calcutta Booklet 10”);

break; default: System. out. println (“ Invalid Choice”); } } catch (Exception e )

break; default: System. out. println (“ Invalid Choice”); } } catch (Exception e ) { System. out. println (“I/O Error”); } } }

Output Select your choice M madras B Bombay C Calcutta Choice m Madras: booklet

Output Select your choice M madras B Bombay C Calcutta Choice m Madras: booklet 5

Why break is needed in switch int i = 1; switch (i) { case

Why break is needed in switch int i = 1; switch (i) { case 0: System. out. println(“ 0”); case 1: System. out. println(“ 1”); case 2: System. out. println(“ 2”); case 3: System. out. println(“ 3”); } System. out. println( ); output is: 123

The ? : operator • Making two-way decisions • Operator is combination of ?

The ? : operator • Making two-way decisions • Operator is combination of ? and : it is refereed as conditional operator Conditional expression ? Expression 1 : expression 2 Expression Boolean type Execute expression Conditional expression True expression 1 Conditional expression False expression 2

The ? : operator • • Making two-way decisions Operator is combination of ?

The ? : operator • • Making two-way decisions Operator is combination of ? and : it is refereed as conditional operator Conditional expression ? Expression 1 : expression 2 Expression Boolean type Execute expression Conditional expression True expression 1 Conditional expression False expression 2

Repeatedly executing blocks is refereed looping. • Statement in block can be executed infinite

Repeatedly executing blocks is refereed looping. • Statement in block can be executed infinite time start from 0 to infinite number of time. • If loop continues it is refereed as infinite loop • No goto statements.

Control structures

Control structures

Looping process • Setting and initialization of a counter (initialization). • Execution of the

Looping process • Setting and initialization of a counter (initialization). • Execution of the statement in the loop. • Test for specified condition(condition). • Increment or decrement counter (increment). Java supports • While loop • Do-while loop • For loop

While loop It is Entry controlled loop statement. Syntax for while loop: 1. Initialization

While loop It is Entry controlled loop statement. Syntax for while loop: 1. Initialization ; 2. While( test condition) 3. { 4. Body of the loop 5. }

Program for while loop Class while_program { Public static void main(String args[]) { System.

Program for while loop Class while_program { Public static void main(String args[]) { System. out. println(“begin of while loop”); Int i=0; While(i<=10) { System. out. println(i); i++; } System. out. println(“end of while loop”); } }

Output Begin of while loop 0 1 2 3 4 5 6 7 8

Output Begin of while loop 0 1 2 3 4 5 6 7 8 9 10 End of while loop

Do-While loop • To execute body of loop once • Exit control statement Syntax:

Do-While loop • To execute body of loop once • Exit control statement Syntax: 1. Initialization; 2. Do 3. { 4. Body of the loop; 5. } while(test condition);

class excute_dowhile { Public static void main(String args[]) { int count = 0; do

class excute_dowhile { Public static void main(String args[]) { int count = 0; do { count++; System. out. println (count); } while (count < 5); } }

For statement The initialization is executed once before the loop begins The statement is

For statement The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

 For loop executed for specific amount of time If the initialization is left

For loop executed for specific amount of time If the initialization is left out, no initialization is performed If the condition is left out, it is always true, and creates an infinite loop If increment is left out, no increment operation is performed Example: for (int count=1; count <= 5; count++) System. out. println (count);

Use of break & continue in looping When break statement is encountered inside a

Use of break & continue in looping When break statement is encountered inside a loop, loop immediately exited while(condition) { Statements. . . if(condition) Break; Statement. . } Statements. . . Do { Statements. . if(condition) Break; . . . . } while(condition) Statements For() }. . . if(condition) Break; } statements For(condition 1) { For((condition 2) { If(condition) Break; } Statements; }

Labelled Loops Label is valid variable name , Labels to block of statements. Assigning

Labelled Loops Label is valid variable name , Labels to block of statements. Assigning label to loops: Loop 1: for(condition) { Statement; } Block 1: {…… ……. Block 2: { ……. }

Example for labelled loops Class Continue. Break { Public static void main(String args[]) {

Example for labelled loops Class Continue. Break { Public static void main(String args[]) { LOOP 1: for(int i=1; i<10; i++) { If(i>=5) break; For(int j=1; j<100; j++) { System. out. println(“*”); If(j==i) Continue LOOP 1; } } //termination by break }

Nested loops Nested for loop For(i=1; i<4; i++) { For(j=1; j<=5; ++j) { Statements;

Nested loops Nested for loop For(i=1; i<4; i++) { For(j=1; j<=5; ++j) { Statements; } } Nested while loop Nested do-while Do { Int X=1; Do { Int y=1; Int c= x+y; }while(x==1); System. out. println(“x=“+x); }while(y==1); System. out. println(“c=“+c);

Enhanced for loop To retrieve array elements efficiently instead of using array index. Syntax:

Enhanced for loop To retrieve array elements efficiently instead of using array index. Syntax: For(type identifier : expression) { Statements ; } Example Int a[3]=[10, 20, 30]; For(int i: a) { If(i>5 &&i<50) { System. out. println(“the selected values are”+i); } }

Perform Assignments 1. WAP to display month names using given the month numbers. 2.

Perform Assignments 1. WAP to display month names using given the month numbers. 2. WAP to display array values using for loop and for-each loop. given a[100, 200, 300, 400, 500]