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 default label is optional. there can be at most one default label in a switch statement.
For example,
public class Main { public static void main(String[] args) { int i = 10;//www . ja v a 2 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"); } } }
public class Main { public static void main(String[] args) { int i = 50;/*from w w w. ja v a2 s . c om*/ switch (i) { case 10: System.out.println("Ten"); case 20: System.out.println("Twenty"); default: System.out.println("No-match"); /* Execution starts here */ } } }