The switch Statement : Switch Statement « Statement Control « Java Tutorial






  1. An alternative to a series of else if is the switch statement.
  2. The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.
  3. The expression used in the switch statement must return an int or an enumerated value.

The syntax of the switch statement is as follows.

switch (expression) {
case value_1 :

     statement (s);
     break;
case value_2 :
     statement (s);
     break;
  .
  .
  .
case value_n :
     statement (s);
     break;
default:
     statement (s);
}

Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.

Here is an example of the switch statement:

public class MainClass {

  public static void main(String[] args) {
    int i = 1;
    switch (i) {
    case 1 :
        System.out.println("One.");
        break;
    case 2 :
        System.out.println("Two.");
        break;
    case 3 :
        System.out.println("Three.");
        break;
    default:
        System.out.println("You did not enter a valid value.");
    }
  }

}








4.3.Switch Statement
4.3.1.The switch Statement
4.3.2.The switch Statement: a demo
4.3.3.Execute the same statements for several different case labels
4.3.4.Free Flowing Switch Statement Example
4.3.5.Nested Switch Statements Example
4.3.6.Switch statement with enum