Java Switch Statements: Simplifying Conditional Logic
Learn how to use Java switch statements to simplify conditional logic and execute one of several code blocks. Switch statements offer a cleaner, more efficient alternative to multiple if...else conditions in your Java programs.
Java Switch Statements
Instead of using many if...else statements, you can use the switch statement to execute one of several code blocks.
Syntax
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
Example
int day = 4;
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;
}
Output
Thursday
Explanation: In this example, the switch statement evaluates the day variable. Depending on its value (4 in this case), it executes the corresponding case block. Here, it prints "Thursday" because day is 4.
The break Keyword
When Java encounters a break keyword inside a switch block, it exits the block immediately. This prevents further execution of code within the switch statement.
The default Keyword
The default keyword specifies what happens if none of the case values match the expression. It is like the "else" part of an if...else statement.
Example
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
Output
Looking forward to the Weekend
If thedefaultstatement is the last one in aswitchblock, it does not require abreakstatement.