JAVA Control Statement Javas Selection Statements Java supports

  • Slides: 46
Download presentation
JAVA Control Statement

JAVA Control Statement

Java’s Selection Statements: • Java supports two selection statements: if and switch. • These

Java’s Selection Statements: • Java supports two selection statements: if and switch. • These statements allow you to control the flow of your program’s execution based upon conditions known only during run time. • We discus these topics in detail in next two topics. • Before going further let us know something about Scanner class of java.

Scanner • Let us start with one simple program for Scanner class. import java.

Scanner • Let us start with one simple program for Scanner class. import java. util. Scanner; public class Scanner. Demo { public static void main(String[] args) { Scanner s = new Scanner(System. in); // Here we initialize object s for Scanner class. System. out. print("Enter the first value a : "); int a = s. next. Int(); // Scan int type value System. out. print("Enter the second value b : "); int b = s. next. Int(); // Scan int type value int sum = a + b; System. out. println("The addition of a and b : a + b = "+sum); } }

 • Here we import java. uti. Scanner because the Scanner class is inside

• Here we import java. uti. Scanner because the Scanner class is inside util package of java library. • Than we create reference (object) of class Scanner named s. • "System. in" This is the predefined library which allow user to enter value in any variable at run time through keyboard. We can say same as scanf() in c and cin >> in c++. • Now in Scanner class there are so many different methods for scanning different type of values.

 • For Ex. in our program we use next. Int() method for scanning

• For Ex. in our program we use next. Int() method for scanning int type value. • Here are some in-built methods of Scanner class for scanning different types of values. 1. next. Byte() for scanning byte type value. 2. next. Short() for scanning short type value. 3. next. Int() for scanning int type value. 4. next. Long() for scanning long type value. 5. next. Float() for scanning floting point value. 6. next. Double() for scanning double type value. 7. next() for scanning a string.

if else if in java: • The if statement is Java’s conditional branch statement.

if else if in java: • The if statement is Java’s conditional branch statement. It can be used to route program • execution through two different paths. Syntax : if (condition) { statement 1; } • When the condition is true the Statement within the if is executed. After that execution continues with the next statement after the if statement. • If the condition is false then the statement within the if is not executed and the execution continues with the statement after the if statement.

import java. util. Scanner; class larger 1 { public static void main(String args[]) {

import java. util. Scanner; class larger 1 { public static void main(String args[]) { int x 1, x 2, x 3; int large; Scanner s = new Scanner(System. in); System. out. println("Enter value for x 1 : "); x 1=s. next. Int(); System. out. println("Enter value for x 2 : ");

x 2=s. next. Int(); System. out. println("Enter value for x 3 : "); x

x 2=s. next. Int(); System. out. println("Enter value for x 3 : "); x 3=s. next. Int(); large = x 1; if (x 2 > large) large = x 2; if (x 3 > large) large = x 3; System. out. println("nnt. Largest number = " + large); } }

 • NOTE : The number of statement in if block is only one

• NOTE : The number of statement in if block is only one than parentheses are optional but if its more than one than parentheses are compulsury. And if we enter the same value in x 1, x 2 and x 3 in above program than largest number is x 1 because our both condition will be false because here we checked only > not >=. EX. if (condition) { Statement 1; Statement 2; } • Same as above, except that here multiple statements are executed if the condition Is true.

if else : • Syntax : if (condition) { statement 1; } else {

if else : • Syntax : if (condition) { statement 1; } else { statement 2; } • The if else work like this: If the condition is true, then statement 1 is executed. Otherwise, statement 2 is executed. In no case will both statements be executed.

import java. util. Scanner; class result { public static void main(String args[]) { Scanner

import java. util. Scanner; class result { public static void main(String args[]) { Scanner s = new Scanner(System. in); System. out. println("Enter marks : "); int marks = s. next. Int(); if (marks<40) System. out. println("n. The student has failed. . "); else System. out. println("n. The student has Passed. . "); } }

if-else-if Ladder : • Syntax : if(condition) statements; else if(condition) statemenst; else if(condition) statements;

if-else-if Ladder : • Syntax : if(condition) statements; else if(condition) statemenst; else if(condition) statements; . . . else statements;

 • The if statements are executed from the top down. As soon as

• The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. • If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. • If there is no final else and all other conditions are false, then no action will take place.

import java. util. Scanner; class Day { public static void main(String args[]) { Scanner

import java. util. Scanner; class Day { public static void main(String args[]) { Scanner s = new Scanner(System. in); System. out. println("Enet day between 0 to 6 Day = "); int day = s. next. Int(); if (day == 0) { System. out. println("n Sunday"); } else if (day == 1) { System. out. println("n Monday"); } else if (day == 2)

{ } System. out. println("n Tuesday"); } } else if (day == 3) {

{ } System. out. println("n Tuesday"); } } else if (day == 3) { System. out. println("n Wednesday"); } else if (day == 4) { System. out. println("n Thursday"); } else if (day == 5) { System. out. println("n Friday"); } else { System. out. println("n Saturday"); }

Nested if • • A nested if is an if statement that is the

Nested if • • A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. • Syntax : if(condition) { if(condition) statements. . else statements. . } else { if(condition) statements. . else statements. . }

import java. util. Scanner; class Max. Value { public static void main(String args[]) {

import java. util. Scanner; class Max. Value { public static void main(String args[]) { int a, b, c; int max=0; Scanner s = new Scanner(System. in); System. out. println("Enter value for a : "); a=s. next. Int(); System. out. println("Enter value for b : "); b=s. next. Int(); System. out. println("Enter value for c : "); c=s. next. Int();

if (a>b) { } else { } } if(a>c) max=a; else //This else is

if (a>b) { } else { } } if(a>c) max=a; else //This else is associate with this if(a>c) max=c; //This else is associate with this if(a>b) if(b>c) max=b; else //This else is associate with this if(b>c) max=c; } System. out. println("n max value = " +max);

switch : • • • The switch statement is Java’s multi way branch statement.

switch : • • • The switch statement is Java’s multi way branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. It is difficult to understand large number of if else. . if statements. So we have switch statement. Syntax : switch (expression) { case value 1 : statement 1 ; break; case value 2 : statement 2 ; break; . . . case value N : statement N ; break; default : statements ; break; }

 • • • • The expression must be of type byte, short, int,

• • • • The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (constant, not a variable). Duplicate case values are not allowed. The value of the expression is compared with each ‘case’ values. If a match is found, the corresponding statement or statements are executed. If no match is found, statement or statements in the default case are executed. Default statement is optional. If default statement is absent, then if no matches are found, then the switch statement completes without doing anything. The break statement is used inside the switch to terminate a statement sequence. NOTE : We will study break statement in further chapter.

import java. util. Scanner; public class Calci { public static void main(String[] args) {

import java. util. Scanner; public class Calci { public static void main(String[] args) { int a, b, ch; double ans; Scanner s = new Scanner(System. in); System. out. print("Enter a : "); a=s. next. Int(); System. out. print("Enter b : "); b=s. next. Int(); System. out. println("Enter 1 for addition"); System. out. println("Enter 2 for subtraction"); System. out. println("Enter 3 for multiplication"); System. out. println("Enter 4 for division"); System. out. print("Enter your choice : "); ch=s. next. Int();

switch(ch) { case 1: ans=a+b; System. out. println("a + b = " + ans);

switch(ch) { case 1: ans=a+b; System. out. println("a + b = " + ans); break; case 2: ans=a-b; System. out. println("a - b = " + ans); break;

case 3: ans=a*b; System. out. println("a * b = " + ans); break; case

case 3: ans=a*b; System. out. println("a * b = " + ans); break; case 4: ans=a/b; System. out. println("a / b = " + ans); break; } } } default: System. out. println("Enter correct choice");

Looping statements • Java’s repetition (iteration) statements are for, while, and do-while. These statements

Looping statements • Java’s repetition (iteration) statements are for, while, and do-while. These statements create what we commonly call loops. • As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met.

for : • The for loop repeats a set of statements a certain number

for : • The for loop repeats a set of statements a certain number of times until a condition is matched. • It is commonly used for simple iteration. The for loop appears as shown below. • Syntax : for (initialization; condition; expression) { Set of statements; }

 • In the first part a variable is initialized to a value. •

• In the first part a variable is initialized to a value. • The second part consists of a test condition that returns only a Boolean value. The last part is an expression, evaluated every time the loop is executed. • The following example depicts the usage of the for loop.

Example for loop class for 1 { public static void main(String args[]) { int

Example for loop class for 1 { public static void main(String args[]) { int i; for (i=0; i<10; i++) { System. out. println("n. Example of for loop "); } } }

while • The while loop executes a set of code repeatedly until the condition

while • The while loop executes a set of code repeatedly until the condition returns false. • Syntax : while (condition) { body(statements) of the loop } • Where <condition> is the condition to be tested. If the condition returns true then the statements inside the <body of the loop> are executed. • Else, the loop is not executed.

class while 1 { public static void main(String args[]) { int i=1; while(i<=10) {

class while 1 { public static void main(String args[]) { int i=1; while(i<=10) { System. out. println("n" + i); i++; } } }

do while : • The do while loop is similar to the while loop

do while : • The do while loop is similar to the while loop except that the condition to be evaluated is given at the end. • Hence the loop is executed at least once even when the condition is false. • Syntax : do { body of the loop } while (condition);

Do while (cont…) • In do while loop semicolon(; ) is compulsory after while.

Do while (cont…) • In do while loop semicolon(; ) is compulsory after while. • NOTE : for and while loops are entry control loop because here conditions are checked at entry time of loop but do while loop is exit control loop because the condition is checked at exit time.

class dowhile 1 { public static void main(String args[]) { int i = 1;

class dowhile 1 { public static void main(String args[]) { int i = 1; int sum = 0; do { sum = sum + i; i++; }while (i<=10); System. out. println("nnt. The sum of 1 to 10 is. . " + sum); } }

 • NOTE : When you declare a variable inside a for loop, there

• NOTE : When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. • => We can use comma operator inside for loop to declare more than one variable inside loop. class Sample { public static void main(String args[]) { int a, b; } } for(a=1, b = 4; a < b; a++, b--) { System. out. println("a = " + a); System. out. println("b = " + b); }

 • NOTE : The actual syntax of for loop is " for( ;

• NOTE : The actual syntax of for loop is " for( ; ; ) ". It means we can use or access every for loop which contain two semicolon (; ) inside round braces of for loop. • EX. for( ; ; ) { //. . . }

Nested loops : • Like all other programming languages, Java allows loops to be

Nested loops : • Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. • It can help you to scan and print multi dimensional array as well as in so many other application or program.

class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10;

class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) { System. out. print(". "); } System. out. println(); } } }

Jump Statements • Java supports three jump statements: break, continue, and return. These statements

Jump Statements • Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program. • 1. break. • 2. continue. • 3. return.

The break statement • This statement is used to jump out of a loop.

The break statement • This statement is used to jump out of a loop. • Break statement was previously used in switch – case statements. • On encountering a break statement within a loop, the execution continues with the next statement outside the loop. • The remaining statements which are after the break and within the loop are skipped.

 • Break statement can also be used with the label of a statement.

• Break statement can also be used with the label of a statement. • A statement can be labeled as follows. • statement. Name : Some. Java. Statement • When we use break statement along with label as break statement. Name; • The execution continues with the statement having the label. This is equivalent to a goto statement of c and c++. .

An example of break statement class break 1 { public static void main(String args[])

An example of break statement class break 1 { public static void main(String args[]) { int i = 1; while (i<=10) { System. out. println("n" + i); i++; if (i==5) { break; } }

An example of break to a label class break 3 { public static void

An example of break to a label class break 3 { public static void main (String args[]) { boolean t=true; a: { b: { c: { System. out. println("Before the break"); if(t) break b; System. out. println("This will not execute"); } System. out. println("This is after b"); } } }

Continue statement • This statement is used only within looping statements. • When the

Continue statement • This statement is used only within looping statements. • When the continue statement is encountered, the next iteration starts. • The remaining statements in the loop are skipped. The execution starts from the top of loop again.

class continue 1 { public static void main(String args[]) { for (int i=1; i<1=0;

class continue 1 { public static void main(String args[]) { for (int i=1; i<1=0; i++) { if (i%2 == 0) continue; } } } System. out. println("n" + i);

The return statement • The last control statement is return. The return statement is

The return statement • The last control statement is return. The return statement is used to explicitly return from a method. • That is, it causes program control to transfer back to the caller of the method. • the return statement immediately terminates the method in which it is executed.

class Return 1 { public static void main(String args[]) { boolean t = true;

class Return 1 { public static void main(String args[]) { boolean t = true; System. out. println("Before the return. "); if(t) return; // return to caller System. out. println("This won't execute. "); } }

 • NOTE : the if(t) statement is necessary. Without it, the Java compiler

• NOTE : the if(t) statement is necessary. Without it, the Java compiler would flag an “unreachable code” error, because the compiler would know that the last println( ) statement would never be executed. To prevent this error, the if statement is used here to trick the compiler for the sake of this demonstration.