Chapter 4: Java Basics - Flow of Program

4.1: All Control Structures Are The Same as C++

The if, if/else, while, do/while, for and switch structures in Java is exactly the same as in C++.

4.2: Comma Operator

Comma operator has only one use: in the control expression of for structure, to separate a series of statements:

   
   for (int i = 1, j = i + 10; i < 5; i++, j = i * 2)...

4.3: Ternary if-else Operator ? :

   
   boolean expression ? value0 : value1

If the boolean expression is true, value0 is used as the result of the operator. Same as in C++.

4.4: Break, Continue and Label

Keyword break and continue is the same as in C++. Keyword break can only exit one layer of loop. To exit more than one layer of loops, put a label right before a loop, and use break label or continue label:

   
   label:
   for (int i = 1; i < 5; i++)
      for (int j = 1; j < 5; j++)
      {
         System.out.println("i = " + i + ", j = " + j);
         if(i == 3 && j == 3) continue label;
         if(i == 8 && j == 8) break label;
      }

Output will be:

   
   i = 1, j = 1
   i = 1, j = 2
   i = 1, j = 3
   i = 1, j = 4
   i = 2, j = 1
   i = 2, j = 2
   i = 3, j = 1
   i = 3, j = 2
   i = 3, j = 3

The continue label breaks out of both of the iterations and continues the next loop of the outer iteration, while normal continue continues the next loop at the local iteration. The break label breaks out of both of the iterations and do not re-enter them again. So the combination of break, continue and label replaces the "goto" statement in C++ with a less flexible and more safe method.

Make your own free website on Tripod.com