Presentation is loading. Please wait.

Presentation is loading. Please wait.

 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.

Similar presentations


Presentation on theme: " The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping."— Presentation transcript:

1

2  The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping constructs—for, while, and do—so you can execute the same code over and over again depending on some condition being true

3  If Condition  Switch Statement

4 The basic format of an if statement is as follows: if (booleanExpression) { System.out.println("Inside if statement"); } Ex : int x = 3 ; if (x > 3) { System.out.println("x is greater than 3"); } else { System.out.println("x is not greater than 3"); }

5 If condition represents in another way. But this is not good practice. If( x > 3) y = 5 ; System.out.println(“If condition”); In here only y = 5 statement consider to if condition.

6 class IfTest { public static void main(String arg[]){ int marks = 56; If( marks < 35){ System.out.println(“Grade is F”); } else if ( marks < 55){ System.out.println(“Grade is S”); } else if (marks < 75){ System.out.println(“Grade is C”); } else if (marks < 100){ System.out.println(“Grade is D”); }}}

7 if (price < 300) { buyProduct(); } else { if (price < 400) { getApproval(); } else { dontBuyProduct(); } if (price < 300) { buyProduct(); } else if (price < 400) { getApproval(); } else { dontBuyProduct(); }

8 ■ You can have zero or one else for a given if, and it must come after any else ifs. ■ You can have zero to many else ifs for a given if and they must come before the (optional) else. ■ Once an else if succeeds, none of the remaining else ifs or elses will be tested.

9 The general form of the switch statement is: switch (expression) { case constant1: code block case constant2: code block default: code block }

10 int x = 1; switch(x) { case 1: System.out.println("x is one"); case 2: System.out.println("x is two"); case 3: System.out.println("x is three"); } System.out.println("out of the switch");

11  A switch's expression must evaluate to a char, byte, short, int, or, as of Java6, an enum.  That means if you're not using an enum, only variables and values that can be automatically promoted (in other words, implicitly cast) to an int are acceptable.  You won't be able to compile if you use anything else, including the remaining numeric types of long, float, and double.

12  A case constant must evaluate to the same type as the switch expression can use, with one additional—and big—constraint: the case constant must be a compile time constant.  Since the case argument has to be resolved at compile time, that means you can use only a constant or final variable that is assigned a literal value.  It is not enough to be final, it must be a compile time constant.

13 final int a = 1; int b; b = 2; int x = 0; switch (x) { case a: // ok case b: // compiler error } Case value are must be final variables;

14 byte g = 2; switch(g) { case 23: case 128: } This is compile time error Test.java:6: possible loss of precision found : int required: byte case 128:

15  illegal to have more than one case label using the same value int temp = 90; switch(temp) { case 80 : System.out.println("80"); // won't compile! case 90 : System.out.println("90"); default : System.out.println("default"); }

16 enum Color {red, green, blue} class SwitchEnum { public static void main(String [] args) { Color c = Color.green; switch(c) { case red: System.out.print("red "); case green: System.out.print("green "); case blue: System.out.print("blue "); default: System.out.println("done"); }

17 int x = 1; switch(x) { case 1: { System.out.println("x is one"); break; } case 2: { System.out.println("x is two"); break; } case 3: { System.out.println("x is two"); break; }} System.out.println("out of the switch");

18  If there are no available match case statement then default case will execute.  Usually default case mention end of the switch statement. But it is not mandatory. int x = 2; switch (x) { case 2: System.out.println("2"); default: System.out.println("default"); case 3: System.out.println("3"); case 4: System.out.println("4"); }

19  Java loops come in three flavors: while, do, and for (and as of Java 6, the for loop has two variations).

20 While loop iterate the loop until condition is true. while (expression) { // do stuff } or int x = 2; while(x == 2) { System.out.println(x); ++x; }

21 int x = 1; while (x) { } // Won't compile; x is not a boolean while (x = 5) { } // Won't compile; resolves to 5 //(as the result of assignment) while (x == 5) { } // Legal, equality test while (true) { } // Legal

22 The do loop is similar to the while loop, except that the expression is not evaluated until after the do loop's code is executed. Therefore the code in a do loop is guaranteed to execute at least once even the condition is false. do { System.out.println("Inside loop"); } while(false);

23  As of Java 6, the for loop took on a second structure. We'll call the old style of for loop the "basic for loop", and we'll call the new style of for loop the "enhanced for loop“.  The basic for loop is more flexible than the enhanced for loop, but the enhanced for loop was designed to make iterating through arrays and collections easier to code.

24 The for loop declaration has three main parts, besides the body of the loop: ■ Declaration and initialization of variables ■ The boolean expression (conditional test) ■ The iteration expression

25 for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) { /* loop body */ } for (int i = 0; i<10; i++) { System.out.println("i is " + i); }

26 for (int x = 10, y = 3; y > 3; y++) { } for (int x = 1; x < 2; x++) { System.out.println(x); // Legal } System.out.println(x); // Not Legal! x is now out of scope // and can't be accessed.

27  Must evaluate to a boolean value. Can have only one logical expression, but it can be very complex. This is legal. for (int x = 0; ((((x 2)) | x == 3)); x++) { } This is illegal for (int x = 0; (x > 5), (y < 2); x++) { } // too many expressions

28 for (int x = 0; x < 1; ++x) { //body code that doesn't change the value of x } After the body of the loop runs, the iteration expression runs,incrementing x by 1.

29  break : Execution jumps immediately to the 1st statement after the for loop.  return : Execution jumps immediately back to the calling method.  System.exit(milliseconds) : All program execution stops; the Virtual Machine(VM) shuts down.  Continue : Stop current iteration

30  None of the three sections of the for declaration are required! The following example is perfectly legal.(Not good practice) for( ; ; ) { System.out.println("Inside an endless loop"); }  Initialization and increment sections, the loop will act like a while loop int i = 0; for (;i<10;) { i++; //do some other work }

31  Demonstrates a for loop with multiple variables. for (int i = 0,j = 0; (i<10) && (j<10); i++, j++) { System.out.println("i is " + i + " j is " +j); }

32  The enhanced for loop is a specialized for loop that simplifies looping through an array or a collection.  Instead of having three components,enhanced for has two.  Let's loop through an array the basic (old) way, and then using the enhanced for:

33 for(declaration : expression) The two pieces of the for statement are ■ declaration The newly declared block variable, of a type compatible with the elements of the array you are accessing. This variable will be available within the for block. ■ expression This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array. The array can be any type: primitives, objects, even arrays of arrays.

34 int [] a = {1,2,3,4}; for(int x = 0; x < a.length; x++) // basic for loop System.out.print(a[x]); for(int n : a) // enhanced for loop System.out.print(n);

35 int x; long x2; Long [] La = {4L, 5L, 6L}; long [] la = {7L, 8L, 9L}; int [][] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}}; String [] sNums = {"one", "two", "three"}; Animal [] animals = {new Dog(), new Cat()};

36 // legal 'for' declarations for(long y : la ) ; // loop thru an array of longs for(long lp : La) ; // autoboxing the Long objects // into longs for(int[] n : twoDee) ; // loop thru the array of arrays for(int n2 : twoDee[2]) ; // loop thru the 3rd sub-array for(String s : sNums) ; // loop thru the array of Strings for(Object o : sNums) ; // set an Object reference to // each String for(Animal a : animals) ; // set an Animal reference to each

37 for(x2 : la) ; // x2 is already declared for(int x2 : twoDee) ; // can't stuff an array into an int for(int x3 : la) ; // can't stuff a long into an int for(Dog d : animals) ; // you might get a Cat!

38 public class NewForArray { public static void main(String[] args) { int[] squares = {0, 1, 4, 9, 16, 25}; for (int i : squares) { System.out.println(“square : “ + i); } } }

39 public class OldForArray { public static void main(String[] args){ int[] squares = {0,1,4,9,16,25}; for (int i=0; i< squares.length; i++){ System.out.println(“Square : “ + squares[i]); } } }

40  The break and continue keywords are used to stop either the entire loop (break) or just the current iteration (continue)  Continue statements must be inside a loop; otherwise,compiler error.  break statements must be used inside either a loop or switch statement.

41 for (int i = 0; i < 10; i++) { System.out.println("Inside loop : “ + i); If(i == 5){ continue; }} for (int i = 0; i < 10; i++) { System.out.println("Inside loop : “+ i); If(i== 5){ break; } }}

42  Java program can be labeled with loop statements like for or while, in conjunction with break and continue statements.  A label statement must be placed just before the statement being labeled, and it consists of a valid identifier that ends with a colon (:). A break statement will exit out of the labeled loop.

43 boolean isTrue = true; outer: for(int i=0; i<5; i++) { while (isTrue) { System.out.println("Hello"); break outer; } // end of inner while loop System.out.println("Outer loop."); } // end of outer for loop System.out.println("Good-Bye"); Running this code produces Hello Good-Bye

44 outer: for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { System.out.println("Hello"); continue outer; } // end of inner loop System.out.println("outer"); } System.out.println("Good-Bye"); Output : Hello Hello Hello Hello Hello Good-Bye

45


Download ppt " The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping."

Similar presentations


Ads by Google