The switch
statement in Java is a control flow statement used to execute one block of code among many based on the value of a variable or expression. It provides a cleaner and more readable alternative to using multiple if-else
statements, especially when dealing with a large number of conditions.
- Expression Evaluation: The
switch
expression is evaluated. - Case Matching: The value is compared with the
case
labels in the order they are defined. - Execution: When a match is found, the statements in the corresponding case are executed.
- Break Statement: After executing the case block, the
break
statement exits the switch to prevent “fall-through.” - Default Case: If no match is found, the
default
block executes (optional).
Syntax
Java
1 2 3 4 5 6 7 8 9 10 11 |
switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; // Add more cases as needed default: // Code to execute if no case matches } |
- The
expression
in aswitch
must evaluate to a value of types likeint
,char
,String
, or enums. - The
break
statement is necessary to prevent execution from “falling through” to subsequent cases. - The
default
case is optional but useful for handling unexpected values. - Duplicate case values are not allowed.
Example
Java
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 |
public class SwitchExample { public static void main(String[] args) { int day = 5; // Example input representing a day of the week 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"); } } } |
- Input Value: The
day
variable holds the value5
. - Switch Execution:
- The
switch
statement evaluates theday
variable. - It matches
5
with thecase 5:
label. - The code inside
case 5:
executes:System.out.println("Friday");
.
- The
- Break: The
break
statement prevents the execution from falling into subsequent cases.
Output
Java
1 |
Friday |
Advanced Usage
From Java 12 onward, the switch
statement introduced an enhanced syntax called “switch expressions,” which simplifies the flow and allows returning a value directly.
Example
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class SwitchExpressionExample { public static void main(String[] args) { int day = 5; String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; case 4 -> "Thursday"; case 5 -> "Friday"; case 6 -> "Saturday"; case 7 -> "Sunday"; default -> "Invalid day"; }; System.out.println(dayName); } } |
Output
Java
1 |
Friday |