In this tutorial you will learn about the Java Switch Case Statement and its application with practical example.
Java Switch Case Statement
In Java, a switch case statement is a simplified form of the Java Nested if-else statement, it helps to avoid a long chain of if..else if..else statements. A switch-case statement evaluates an expression against multiple cases in order to identify the block of code to be executed.
Java Switch Case Flow Diagram
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 |
switch(expression){ case value1: // statements break; case value2: // statements break; default: // statements break; } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class Main { public static void main(String[] args) { int dayOfWeek = 5; System.out.println("W3Adda - Java Switch Case statement."); switch(dayOfWeek){ case 1: System.out.println("Today is Monday."); break; case 2: System.out.println("Today is Tuesday."); break; case 3: System.out.println("Today is Wednesday."); break; case 4: System.out.println("Today is Thursday."); break; case 5: System.out.println("Today is Friday."); break; case 6: System.out.println("Today is Saturday."); break; case 7: System.out.println("Today is Sunday."); break; default: System.out.println("Invalid Weekday."); break; } } } |
In the above program we have an integer variable dayOfWeek with initial value of 5, and we pass this variable as expression to following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed.
When we run the above java program, will see the following output –
Output:-