switch

Syntax

                           v-------------------------------------------'
>>-switch-(-Expression-)-{-+-case-ConstantExpression-:-BlockStatements-+->

>-+---------------------------+-}-><
  '-default-:-BlockStatements-'

Description
The switch statement enables you to compare a variable against different test values. It transfers control to one of several statements in a loop depending on the value of an expression. If the test value equals any of the case values, then the corresponding result occurs and the break statement causes execution of the switch statement to end.  The type of the Expression must be  byte, short , int, or long, or a compilation error occurs.

The body of a switch statement must be a block. Any statement immediately contained by the block may be labeled with one or more case or default labels.

When the switch statement is executed, first the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant. After that, a decision is made, based on the following rules:

Example
In the following example, we use a for loop to iterate over our switch statement four times, testing it with values zero to three.

for (int test = 0; test <= 3; test++) {
    switch (test){
    case 1:
        System.out.println( "Good" ); 
        break;
    case 2:
        System.out.println( "Very Good" ); 
        break;
    default:
        System.out.println( "Boring" );
        break;
    }
}

The above code produces the following output:

Boring
Good
Very Good
Boring

ngrelr.gif (548 bytes)
Syntax diagrams
Java types
break keyword
byte keyword
case keyword
default keyword
int keyword
long keyword
short keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.