Switch Expressions in Java
Learn modern switch expressions, arrow labels, yield, and pattern-oriented syntax.
1. What is a Switch Expression?
A traditional switch statement is mainly used to control
program flow. A modern Java switch expression can also
produce a value.
Switch expressions were introduced as a preview feature in Java 12 and became a standard language feature in Java 14.
2. switch Statement
The older switch syntax commonly uses case,
break, and mutable variables.
int day = 2;
String name;
switch (day) {
case 1:
name = "Monday";
break;
case 2:
name = "Tuesday";
break;
default:
name = "Unknown";
}
3. Arrow Syntax
Modern switch expressions can use -> instead of
the traditional colon syntax.
Arrow labels do not fall through to the next case.
int day = 2;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
default -> System.out.println("Other day");
}
4. Switch Expression Returning a Value
A switch expression can directly return a value.
int day = 2;
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);
5. Multiple Case Labels
Multiple constants can be handled by a single switch arm.
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
System.out.println(type);
6. Block Body
A switch arm can contain multiple statements by using braces.
int number = 10;
String result = switch (number) {
case 10 -> {
System.out.println("Number is ten");
yield "TEN";
}
default -> {
System.out.println("Other number");
yield "OTHER";
}
};
System.out.println(result);
7. yield Keyword
The yield keyword is used to return a value from a
block inside a switch expression.
int score = 80;
String grade = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> {
System.out.println("Very good");
yield "B";
}
case 7 -> "C";
case 6 -> "D";
default -> "F";
};
System.out.println(grade);
yield when the switch arm uses a block and needs to
produce a value.
8. Exhaustiveness
A switch expression must be exhaustive. It must handle every possible input value.
For many types, a default case is used to cover remaining values.
int value = 5;
String result = switch (value) {
case 1 -> "One";
case 2 -> "Two";
default -> "Other";
};
9. Switch Expressions with Enum
Switch expressions work particularly well with enums.
enum Level {
LOW,
MEDIUM,
HIGH
}
Level level = Level.HIGH;
String message = switch (level) {
case LOW -> "Low priority";
case MEDIUM -> "Medium priority";
case HIGH -> "High priority";
};
System.out.println(message);
default
may not be necessary.
10. Switch Expressions with String
Strings can also be used with switch expressions.
String language = "Java";
String category = switch (language) {
case "Java" -> "Programming Language";
case "SQL" -> "Database Language";
case "HTML" -> "Markup Language";
default -> "Unknown";
};
System.out.println(category);
11. Switch Expressions with Character
char grade = 'A';
String result = switch (grade) {
case 'A' -> "Excellent";
case 'B' -> "Good";
case 'C' -> "Average";
default -> "Needs improvement";
};
System.out.println(result);
12. Switch Expression in a Method
A switch expression can be returned directly from a method.
public static String getDayType(int day) {
return switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
}
13. Avoid Complex Nested Switches
Although switch expressions are concise, deeply nested switches can still make code difficult to understand.
String result = switch (type) {
case "A" -> {
yield switch (status) {
case "ACTIVE" -> "Running";
default -> "Stopped";
};
}
default -> "Unknown";
};
For complex business logic, consider extracting logic into separate methods.
14. Switch and Pattern Matching
Modern Java also supports pattern matching with switch. This makes it possible to select behavior based on the type and characteristics of an object.
static String describe(Object value) {
return switch (value) {
case String text ->
"String: " + text;
case Integer number ->
"Integer: " + number;
case null ->
"null";
default ->
"Other type";
};
}
15. Pattern Matching with when
In modern Java, additional conditions can be expressed using a
when guard in pattern matching.
static String classify(Object value) {
return switch (value) {
case Integer number when number > 0 ->
"Positive integer";
case Integer number ->
"Zero or negative integer";
case String text ->
"Text";
default ->
"Other";
};
}
when syntax is part of the modern
pattern-matching switch language evolution and requires an appropriate
recent Java version.
16. Handling null
Modern pattern matching switch can explicitly handle null.
static String check(Object value) {
return switch (value) {
case null -> "Value is null";
case String text ->
"Text value";
default ->
"Other value";
};
}
17. Advantages of Switch Expressions
- Can directly return a value.
- Reduces boilerplate code.
- Arrow syntax prevents accidental fall-through.
- Supports multiple labels.
- Works well with enums and strings.
- Supports block expressions using
yield. - Works with modern pattern matching.
- Improves readability for many branching operations.
18. Traditional switch vs Switch Expression
| Traditional switch | Modern switch expression |
|---|---|
| Usually statement-oriented | Can produce a value |
| Often requires break | Arrow labels avoid fall-through |
| More verbose | More concise |
| Uses case with colon frequently | Can use arrow syntax |
| No yield concept | Uses yield inside block arms |
19. Example 😁🫥
public class Main {
public static String getCategory(String language) {
return switch (language) {
case "Java" ->
"Object-Oriented Programming";
case "SQL" ->
"Database";
case "HTML", "CSS" ->
"Web";
default ->
"Other";
};
}
public static void main(String[] args) {
String language = "Java";
String category =
getCategory(language);
System.out.println(
"Language: " + language
);
System.out.println(
"Category: " + category
);
}
}
20. Best Practices
- Use switch expressions when a branch naturally produces a value.
- Prefer arrow syntax for modern code.
- Keep each switch arm simple.
- Use exhaustive handling where practical.
- Use
yieldonly when a block needs to produce a value. - Use pattern matching when type-based branching improves clarity.
- Avoid deeply nested switch expressions.
- Use an appropriate Java version for the language features being used.
21. Interview Questions
yield returns a value from a block inside a
switch expression.
Summary
In this lesson, you learned:
- Traditional switch statements
- Modern switch expressions
- Arrow syntax
- Multiple case labels
- Switch expressions returning values
- The
yieldkeyword - Exhaustive switch expressions
- Switch expressions with enums and strings
- Pattern matching with switch
- Modern null handling
- Best practices for switch expressions