In Java 17, switch expressions provide a more concise and streamlined way to handle conditional logic. This feature was introduced in Java 12 as a preview and made a standard feature in Java 14. Java 17, being a Long-Term Support version, includes this feature as well.
Let me guide you through how to use them.
What Are Switch Expressions?
Switch expressions allow you to:
- Return values directly from a switch block (as an expression).
- Use concise syntax with the arrow
->
syntax. - Prevent fall-through by removing the need for explicit
break
statements. - Handle multiple case labels compactly.
Switch Expression Syntax
Basic Syntax
switch (expression) {
case value1 -> result1;
case value2 -> result2;
default -> defaultResult;
}
- Use
->
for expression forms. - A
default
case is mandatory unless all possible values are handled. - The switch expression evaluates to a single value, which can be assigned to a variable.
Examples
1. Assigning a Value with Switch Expression
package org.kodejava.basic;
public class SwitchExpressionExample {
public static void main(String[] args) {
String day = "MONDAY";
int dayNumber = switch (day) {
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> 1;
case "SATURDAY", "SUNDAY" -> 2;
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
System.out.println("Day Group: " + dayNumber);
}
}
- Explanation:
- Multiple case labels like
"MONDAY", "TUESDAY"
are handled via commas. - Default throws an exception if the input doesn’t match any case.
- Multiple case labels like
2. Block Syntax with yield
For cases where a more complex computation is needed, you can use a code block and yield
to return a value.
package org.kodejava.basic;
public class SwitchExpressionWithYieldExample {
public static void main(String[] args) {
String grade = "B";
String message = switch (grade) {
case "A" -> "Excellent!";
case "B" -> {
int score = 85;
yield "Good job! Your score is " + score;
}
case "C" -> "Passed.";
default -> {
yield "Invalid grade.";
}
};
System.out.println(message);
}
}
- Explanation:
- Use
{}
to enclose a block, andyield
to specify the value to return.
- Use
3. Enhanced Switch with Enums
Switch expressions work great with enums, promoting type safety and readability.
package org.kodejava.basic;
public class SwitchWithEnums {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static void main(String[] args) {
Day today = Day.FRIDAY;
String dayType = switch (today) {
case SATURDAY, SUNDAY -> "Weekend";
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
};
System.out.println("Today is a " + dayType);
}
}
- Explanation:
- Using enums eliminates the need for
default
because all cases are covered.
- Using enums eliminates the need for
4. Using Switch in a Method
You can use switch expressions for cleaner and more concise methods.
package org.kodejava.basic;
public class SwitchInMethodExample {
public static void main(String[] args) {
System.out.println(getSeason(3)); // Output: Spring
}
static String getSeason(int month) {
return switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Autumn";
default -> throw new IllegalArgumentException("Invalid month: " + month);
};
}
}
- Explanation:
- No
break
is needed, as thereturn
value is implicit in switch expressions.
- No
Key Features to Remember
- No need for
break
statements. - Use
->
for one-liner cases. - Use
yield
to return values from block-style cases. - Works well with
var
for type inference.
Switch expressions simplify many patterns while keeping your code readable and concise!