Java switch Statement

Description

The switch statement is a multiway branch statement. It provides a better alternative than a large series of if-else-if statements.

Syntax

Here is the general form of a switch statement:


switch (expression) { 
case value1: // ww  w  . ja  v  a  2 s  .c om
    statement sequence 
    break; 
case value2: 
    statement sequence 
    break; 
. 
. 
. 
case valueN: 
    statement sequence 
    break; 
default: 
    default statement sequence 
}

The value1 to valueN are the possible case values for expression. Duplicate case values are not allowed.

A break statement jumps out of switch statement to the first line that follows the entire switch statement.

Example

Here is a simple example that uses a switch statement:

 
public class Main {
  public static void main(String args[]) {
    for (int i = 0; i < 6; i++)
      switch (i) {
        case 0://from   w w w  . j  a  v  a 2 s .com
          System.out.println("i is zero.");
          break;

        case 1:
          System.out.println("i is one.");
          break;

        case 2:
          System.out.println("i is two.");
          break;

        case 3:
          System.out.println("i is three.");
          break;

        default:
          System.out.println("i is greater than 3.");
      }
  }
}

The output produced by this program is shown here:

Example 2

The break statement is optional. If you omit the break, execution will continue on into the next case. For example, consider the following program:

 
public class Main {
  public static void main(String args[]) {
    for (int i = 0; i < 12; i++)
      switch (i) {
        case 0://from www  .j a  v a 2 s .c o m
        case 1:
        case 2:
        case 3:
        case 4:
          System.out.println("i is less than 5");
          break;
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
          System.out.println("i is less than 10");
          break;
        default:
          System.out.println("i is 10 or more");
      }
  }
}

This program generates the following output:

Example 3

Java supports the nested switch statements. For example, the following fragment is a valid nested switch statement.


public class Main {
  public static void main(String args[]) {
    for (int i = 0; i < 6; i++)
      switch(i) { 
        case 0: //from w w w.  j  a  v  a 2 s.c  o  m
          switch(i+1) { // nested switch 
            case 0: 
              System.out.println("target is zero"); 
              break; 
            case 1: 
              System.out.println("target is one"); 
              break; 
          } 
          break; 
        case 2: // ...
     }
  }
}

The output:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures