1 / 46

JAVA

JAVA. Control Statement. 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.

alma
Download Presentation

JAVA

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA Control Statement

  2. 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.

  3. Scanner • Let us start with one simple program for Scanner class. import java.util.Scanner; public class ScannerDemo {     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.nextInt();    // Scan int type value System.out.print("Enter the second value b : "); int b = s.nextInt();    // Scan int type value int sum = a + b; System.out.println("The addition of a and b : a + b = "+sum);     } }

  4. 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 different methods for scanning different type of values.

  5. For Ex. in our program we use nextInt() method for scanning int type value. • Here are some in-built methods of  Scanner class for scanning different types of values. 1. nextByte()  for scanning byte type value. 2. nextShort()  for scanning short type value. 3. nextInt() for scanning int type value. 4. nextLong() for scanning long type value. 5. nextFloat() for scanning floting point value. 6. nextDouble() for scanning double type value. 7. next() for scanning a string.

  6. 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) {      statement1; } • 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.

  7. import java.util.Scanner; class larger1 {         public static void main(String args[])         { int x1,x2,x3; int large;                 Scanner s = new Scanner(System.in); System.out.println("Enter value for x1 : ");                 x1=s.nextInt(); System.out.println("Enter value for x2 : ");

  8.   x2=s.nextInt(); System.out.println("Enter value for x3 : ");                 x3=s.nextInt();                 large = x1;                 if (x2 > large)                         large = x2;                 if (x3 > large)                         large = x3; System.out.println("\n\n\tLargest number = " + large);         } }

  9. 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 x1, x2 and x3 in above program than largest number is x1 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.

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

  11. 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.nextInt();                 if (marks<40) System.out.println("\nThe student has failed .. ");                 else System.out.println("\nThe student has Passed .. ");         } }

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

  13. 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.

  14. 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.nextInt();                 if (day == 0)                 { System.out.println("\n Sunday");                 }                 else if (day == 1)                 { System.out.println("\n Monday");                 }                 else if (day == 2)

  15. { 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");                 }         } }

  16. 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.... }

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

  18.  if (a>b)                 {                         if(a>c)                            max=a;                         else        //This else is associate with this if(a>c)                            max=c;                 }                 else               //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);         } }

  19. 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;  }

  20. 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.

  21. import java.util.Scanner; public class Calci {     public static void main(String[] args)     { inta,b,ch;     double ans;     Scanner s = new Scanner(System.in); System.out.print("Enter a : ");     a=s.nextInt(); System.out.print("Enter b : ");     b=s.nextInt(); 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.nextInt();

  22. 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;

  23.  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");     }     } }

  24. 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.

  25. 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; }

  26. 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.

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

  28. 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.

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

  30. 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);

  31. 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.

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

  33. 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);             }        } }

  34. 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( ; ; ) {     // ... }

  35. 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.

  36. 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();                 }         } }

  37. 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.

  38. 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.

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

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

  41. An example of break to a label class break3 {         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 will not execute");                         } System.out.println("This is after b");                 }         } }

  42. 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.

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

  44. 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.

  45. class Return1 {        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.");      } }

  46. 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.

More Related