Switch Statement in Java | Control Flow in Java
The switch statement in Java is a control flow statement that allows a variable to be tested for equality against multiple values. Each value is called a case, and the variable being switched on is checked for each case.
Key Points on Switch Statement:
- The switch statement can have multiple cases and an optional default case.
- Each case ends with a
break
statement to stop further execution after matching a case. - The default case executes when no cases match the given value.
- The switch statement works best when comparing a variable against fixed values.
- Only the case that matches will execute, and no other cases are evaluated.
- The
break
statement is crucial; without it, execution "falls through" to the next case.
Syntax of Switch Statement:
Syntax Example
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases
default:
// Code to execute if none of the cases match
}
Example of Switch Statement in Java:
This example uses a switch statement to determine the day of the week based on a number.
Code Example
public class Weekday {
public static void main(String[] args) {
int day = 3;
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("Invalid day");
}
}
}
Output
Wednesday
Switch Statement Flowchart:
The flowchart below shows the control flow of a switch statement.
 }})
Detailed Explanation:
- Expression: The variable or expression in the switch statement is evaluated once.
- Case Labels: The expression result is compared with each case label, and the matching case block is executed.
- Break Statement: Placed at the end of each case block to terminate the switch statement execution once a match is found.
- Default Case: The default case executes if none of the cases match the expression. It’s optional but recommended for completeness.
- Efficiency: Switch is generally faster than a chain of if-else statements when comparing multiple fixed values.
- Limitations: In Java, switch works with int, char, byte, short, and enumerated types. Since Java 7, switch also supports String.
Using switch statements effectively helps make code cleaner and more readable when handling multiple conditions based on constant values.