A switch statement enables a programmer to select one of the execution paths based on the value of an expression. It is very much similar to if-else if statement that we studied previously.
Let's start from the top of the switch block, each non-default case is checked. If the case gives true, the statements in that case and the following cases are executed until a break statement is encountered. If none of the non-default cases is true, and the execution control meets with the default case, the statements in the default case and all the following cases are executed until a break statement is encountered.
Syntax
switch(variable) { case value1: //code to be executed break; case value2: //code to be executed break; ... case valuen: //code to be executed break; default: //code to be executed break; }
Flowchart of switch statement
Example
public class Test { public static void main(String args[]) { int week=2; switch(week) { case 0: System.out.println("Sunday"); break; case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; default: System.out.println("Invalid week"); break; } } }
Output
Tuesday