Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0049 switch statement

The switch statement is a multiway branch statement. It provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement: switch (expression) { case value1: statement sequence break; case value2: statement sequence break; . . . case valueN: statement sequence break; default: default statement sequence } Duplicate case values are not allowed. A break statement jumps out of switch statement to the first line that follows the entire switch statement. 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: 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: i is zero. i is one. i is two. i is three. i is greater than 3. i is greater than 3.