Java switch statement checks multiple conditions by using different cases and if the cases not match then it executes a default statement. The working of a switch case is similar to the if statements and it also control the flow of the program execution.
How To Write Switch Statement In Java
switch(condition) { case label_1: // statement 1 will be here break; case label_2: // statement 2 will be here break; case label_3: // statement 3 will be here break; default: // statement 4 will be here }
Program For Switch Statement In Java
Let’s see the following example of the switch-case-
public class DemoSwitch { public static void main(String[] args) { int day=1; switch(day){ 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; case 7: System.out.println("Sunday"); break; default: System.out.println("its an amazing day"); } } }
it will produce the following output-
Monday
In switch case break statement is optional means if you don’t want to use a break statement in your program then you can exclude break statement. Let’s see the following example without the break statement-
Example:
public class DemoSwitch1 { public static void main(String[] args) { int day=1; switch(day){ case 1: case 2: case 3: case 4: case 5: System.out.println("Friday"); case 6: case 7: System.out.println("Weekend"); default: System.out.println("its an amazing day"); } } }
it will produce the following output-
Friday