TopWhile statementSwitch statement

Switch

The switch statement can be more efficient and easier to read if there is a multi-way conditional statement whose branches depend on the integer values of an expression. For example, recall the following from above:

   public void onMousePress(Location point) {

      nextLineStarts = point;

      // pick the color
      int randomInt = colorGenerator.nextValue();
      if ( randomInt == 0 ) {
         lineColor = Color.white;
      } else if ( randomInt == 1 ) {
         lineColor = Color.blue;
      } else {
         lineColor = Color.red;
      }
   }

A switch statement can choose the correct statements to execute based on the value of randomInt (see program SpirographThreeColorSwitch):

   int randomInt = colorGenerator.nextValue(); 
        switch(randomInt) { 
        case 0:  
                lineColor = Color.white; 
                break; 
        case 1: 
                lineColor = Color.blue; 
                break; 
        default: 
                lineColor = Color.red; 
                break; 
        } 

Note that each branch is executed when the value of randomInt is an exact match for the number after case. The default case is executed if none of the others match. Note that you cannot use inequalities.

Also note that the end of each case must include a break; statement. If the break is omitted, execution will continue to the first statement in the next case.


TopWhile statementSwitch statement