Java - Statement switch Statement

Syntax

The general form of a switch statement is

switch (switch-expression) {
        case label1:
                statements

        case label2:
                statements

        case label3:
                statements

        default:
                statements
}

The switch-expression must evaluate to a type: byte, short, char, int, enum, or String.

The label1, label2, etc. are compile-time constant expressions whose values must be in the range of the type of the switch-expression.

A switch statement is evaluated as follows:

  • The switch-expression is evaluated.
  • If switch-expression's value matches a case label, the execution runs from the matched case label until the end of the switch statement.
  • If switch-expression's value does not match a case label, the execution runs at the statement following the optional default label until the end of the switch statement.

The default label is optional. there can be at most one default label in a switch statement.

For example,

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10;/* w w w.  j  a va2  s.  c  o m*/
    switch (i) {
    case 10: // Found the match
      System.out.println("Ten"); // Execution starts here
    case 20:
      System.out.println("Twenty");
    default:
      System.out.println("No-match");
    }

  }
}

Result

Demo

public class Main {
  public static void main(String[] args) {
    int i = 50;//w ww  .  j  av a2  s  .c o m
    switch (i) {
    case 10:
      System.out.println("Ten");
    case 20:
      System.out.println("Twenty");
    default:
      System.out.println("No-match"); /* Execution starts here */
    }

  }
}

Result

Related Topics

Quiz