Java Control Statements                                      P.Komisar
                                                                                                                                           minor revision  May 22 / 2001

reference: 'Java Statements', 'Just Java', van der Linden, 'Core Java', Hoorstman & Cornell


Statements express what a program does. Statements are typically grouped inside blocks,
constructors or methods. Most texts will try to organize the presentation of statements in
one way or another. Van der Linden's choice of categories is good, so we will follow suite
and present each statement type by whether they are organizing, expression, selection or
iteration statements.

Organizing Statements

1) The Block Statement is a pair of curly braces {   } containing zero or more local
    variables and statements.Wherever a single statement can be put, a block can be put.

Example 1  {
                // zero or more variables
                       // zero or more assignments, increments, method calls, new instances etc.
                 }

2) The Empty Statement is simply a semicolon by itself.

    ;

    It does nothing by itself which is sometimes what you want.

Example 2     boolean Rain = true;
                   if (Rain)
                     ;                   // if rain do nothing
                   else
                   go_swim( );    // assume this method is defined somewhere


Expression Statements

When an expression ends with a semi-colon, it is considered to be a statement.

Examples       JButton jb = new JButton("New button");     //  instance creation
                        jb.setLabel("Older Button");                     //  method call
                        ++ j ;                                                       //  pre increment
                        a = z;                                                       //  assignment
 
 
More on Expressions 

An unreferenced, expression statement result is discarded. Recall an expression evaluates to
a result, either a variable, value or a void. In the case that an expression is not assigned to a
reference, the result is discarded

   Example        new TextArea ("not referenced");             //  the resultant pointer is discarded
                          panel.add (new TextArea ("not referenced") );   //  example again in a context 
 


Selection Statements       // also referred to as conditional statements.
 

if  ( boolean expression )Statement  opt. [ else Statement ]

Example     boolean shootsLeft = true;
                     if  (shootsLeft)
                          make_Left_Wing("player's name");       // assume this method is callable
                        else
                         make_Right_Wing("player's name");

  //  to execute multiple  statements after an  if  block, enclose the statements in curly braces, { }


switch ( expression ) Statement // where expression is, or resolves to, a byte, char, short or int

Example   // notice the case statements end with a colon
               int i;
               for (i = 4;  i > 0; i--) {

                      switch ( i ){
                        case 4:
                         System.out.println("Ready");
                         break;
                         case 3:
                         System.out.println("On your marks");
                         break;
                         case 2:
                         System.out.println("Get set");
                         break;
                         case 1:
                         System.out.println("Go");
                         break;
                        default:
                         System.out.println("Restart");
                         }
                 }

If you leave break out, execution falls through to the next case. Note also, the default
statement is optional and can be placed anywhere in the switch construct.Where there is
no default and no case matches, nothing is printed out.
 
More on the switch


The switch fallthrough feature is error-prone. Van der Linden also observes it is rarely used 
feature.He did an interesting survey where he viewed 320 switches in the java source code, 
observing less than 1% used the fallthrough feature. The implication is the behaviour should 
have been left out of the construct and added optionally rather than the other way around. 


 Imitation of switch behaviour using if statements 

class tif{ 
public static void main(String[]args){
int x=(int)(Math.random( )*3)+1;
   if(x==1)
   to("One");
   if(x==2)
   to("Two");
   if(x==3)
   to("Three");
   }
static void to(String s){
  System.out.println(s);
  }
}


Iteration Statements

for  ( initialization   test condition   increment )

The for loop is sometimes called a determinate loop. Declarations can happen
inside or outside the for loop

Example        int i;
                   for ( i = 0; i< 99; i++)

       or          for (int i = 0; i< 99; i++)

Loops can contain compound initialization and increments

Example    for (int i = 0, j = 0 ; i < 100; i++ , j +=2 )

An infinite for loop  is created by leaving out the expressions of the for loop,
leaving two empty statements.

Example           for ( ; ; )
 
 
More on 'for'


  class forT{
     public static void main(String[] args){

     // Good
     int j=9;
     System.out.println("\n First for loop \n");
     for(int x=0; x<4;x++,j++){
        System.out.println( x + "  " + j);
        }

      // Also OK
    int k=0;
     System.out.println("\n Second for loop \n");
     for(int x=0, k=4; x<5;x++,k++){
        System.out.println(x*2 + "  " + k*2);
        }

      // NOT good! 
      // You can't mix variable declarations inside expressions
      /*
     int q;
     for(q=0, int w=4; q<10;q++,w++){
        System.out.println(q + "  " + w);
        }
     */
      } 
     }

 // Summary
 // There are only the three, semicolon-seperated regions 
 // in the for loop which internally can be compounded by 
 // comma seperation. You can't mix variable declarations
// inside expressions. 
 


while ( boolean expression ) Statement

The while and do...while statement are sometimes called indeterminate loops.While
the boolean expression is true the statement is executed. The loop iterates 0 or more
times. If the expression is false control passes to the first line of code past the statement.
If on first evaluation, the expression resolves to false the statement is never executed.


do  Statement  while  ( boolean expression )

The statement is executed at least once and then the expression is evaluated,
continuing while the boolean expression remains true.


continue  opt. label

continue moves the flow of control to the next iteration of a loop. It is only used in
loops.If used within nested loops, label can be placed to indicate which loop's next
iteration is executed.


break  opt. label

break is more 'extreme' then continue. It causes control to pass right out (to the end)
of the loop it is contained in. If used with a label, the break is to the end of the block
the label is attached to.



 
 break & continue code sample 


class BC{ 
  public static void main(String[] s){ 
    int i; 
   for(i=1; i <8; i++){ 
     if (i==5) 
     break;                             // break 'breaks' right out of the loop it is in 
     System.out.println(i); 
     } 

  System.out.println("\n");    // ********** just a spacer ************* 

  int j; 
  for (j=1;j<8; j++){ 
      if(j==5) 
     continue;                      // continue 'continues' with the next iteration 
     System.out.println(j); 
   } 

System.out.println("\n");     //*********************************
 

{
   // block expression limits the naming scope of the variables so I can reuse the 
   // code below  this is not a recommended use but just a display of the limiting 
   // effect of block on the naming scope of variables 

         int x; 
         int y; 

  // when the system breaks to labelA associated with  the break, control
 // continues at the end of the block the label is associated with leaving 
// the outer loop

  labelA:  for(x=0; x < 3; x++){ 
                    for(y=0; y < 3; y++){ 
                       if(y==1) 
                        break labelA; 
                        System.out.println(x + " " + y ); 
                      } 
                   }  // this is the end of the block with the label 
                       // and where the code continues after break
 
} // the end of the first  block 

   System.out.println("\n"); //***************************

   { // here's the same variables used showing continue used with a label 
         int x; 
         int y; 

  labelB: for(x=0;  x < 3; x++){ 
                  for(y=0; y < 3; y++){ 
                      if(y==1) 
                       continue labelB; 
                       System.out.println(x + " " + y ); 
                     } 
                  } 
              }  // the end of the second block 
           } 
        } 

     Output

 1
 2
 3
 4

 1
 2
 3
 4
 6
 7

 0 0 

 0 0 
 1 0
 2 0
.



return     opt. expression
return;                           //  returns  the caller back to where the method was called from
return expression;  // returns a value and so cannot be used in a method returning void


throw  -raises an exception and belongs in the discussion of Exceptions.
goto     -is reserved but not in use