Academic Java    Java Tutorial  >  Statements  >  switch (a)

switch Example

Java switch EXAMPLE output The program displays a box whose color depends on the outcome of a switch statement.

After the keyword switch is a parenthesised int, short, byte, or char expression.

Following is a block of code in curly braces containing a list of case alternative branches that correspond to possible matches of the expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Switch Statement Example
import java.awt.*;

class SwitchStatementExample {

   public static void main(String[] args) {

      ABox b = new ABox();
      b.draw();

      for(int i=0; i<4; i++) {
         Color c;

         switch (i) {
            case 0: c=Color.red; break;
            case 2: c=Color.magenta; break;
            default: c=Color.cyan; break;
         }

         b.setColor(c);

      }

   }
}

14-18 This is the switch statement.
When the statement is executed the expression i is evaluated and an appropriate case branch is taken.
default is used as a catchall for non-matching cases.
Notice the use of break to break out of the switch statement.
If you were watching the run you would see the box change color from yellow to red to cyan to magenta to cyan.