In Part 2, we explored the traditional switch statement and learned about case labels, fall-through, break, and default.
While the traditional switch has been part of Java since its early days, it also has a few drawbacks:
- Forgetting a
breakcauses accidental fall-through. - Returning a value requires extra variables.
- The syntax can become verbose.
- Some bugs are easy to introduce.
To solve these problems, Java introduced Switch Expressions.
They first appeared as a preview feature in Java 12 and Java 13, and became a standard feature in Java 14.
If you're using Java 17, Java 21, or newer, this is the recommended way to write most switch statements.
Why Was a New switch Needed?
Consider the traditional approach.
String grade = "A";
String result;
switch (grade) {
case "A":
result = "Excellent";
break;
case "B":
result = "Good";
break;
case "C":
result = "Average";
break;
default:
result = "Needs Improvement";
}
System.out.println(result);
Notice how we need:
- a separate variable
- multiple assignments
- multiple
breakstatements
Modern Java lets us write the same code much more cleanly.
What Is a Switch Expression?
A switch expression returns a value.
Instead of executing statements only, it can produce a result that can be assigned directly to a variable.
Example
String grade = "A";
String result = switch (grade) {
case "A" -> "Excellent";
case "B" -> "Good";
case "C" -> "Average";
default -> "Needs Improvement";
};
System.out.println(result);
Output
Excellent
Much shorter and easier to read.
New Arrow (->) Syntax
The biggest visual difference is the new arrow operator.
Traditional syntax
case "A":
System.out.println("Excellent");
break;
Modern syntax
case "A" -> System.out.println("Excellent");
The arrow automatically prevents fall-through.
No break is needed.
No More Accidental Fall-Through
Traditional switch
int day = 1;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
}
Output
Monday
Tuesday
The missing break caused fall-through.
Modern switch
int day = 1;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
}
Output
Monday
Each case is isolated.
Returning Values Directly
One of the biggest improvements is that a switch can now return a value.
Example
int marks = 90;
String grade = switch (marks / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> "D";
};
System.out.println(grade);
Output
A
Notice that no temporary variable assignments are needed inside the switch.
Multiple Case Labels
Instead of writing
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
default:
System.out.println("Weekend");
}
Modern Java allows
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
default -> System.out.println("Weekend");
}
Much cleaner.
Using Blocks with Arrow Cases
Sometimes one line isn't enough.
You can use a block.
String browser = "Chrome";
switch (browser) {
case "Chrome" -> {
System.out.println("Launching Chrome");
System.out.println("Opening homepage");
}
default -> System.out.println("Unsupported Browser");
}
The yield Keyword
Suppose a case contains multiple statements and still needs to return a value.
That's where yield comes in.
Example
String browser = "Chrome";
String company = switch (browser) {
case "Chrome" -> {
System.out.println("Google Browser");
yield "Google";
}
case "Firefox" -> {
System.out.println("Mozilla Browser");
yield "Mozilla";
}
default -> "Unknown";
};
System.out.println(company);
Output
Google Browser
Google
Think of yield as the return statement for a switch expression.
switch Expression with Enum
Enums work beautifully with switch expressions.
enum Coffee {
ESPRESSO,
LATTE,
CAPPUCCINO,
AMERICANO
}
Coffee coffee = Coffee.LATTE;
String description = switch (coffee) {
case ESPRESSO -> "Strong";
case LATTE -> "Creamy";
case CAPPUCCINO -> "Foamy";
case AMERICANO -> "Black";
};
System.out.println(description);
Output
Creamy
switch Expression with String
String browser = "Edge";
String engine = switch (browser) {
case "Chrome" -> "Blink";
case "Edge" -> "Blink";
case "Firefox" -> "Gecko";
case "Safari" -> "WebKit";
default -> "Unknown";
};
System.out.println(engine);
Output
Blink
Exhaustive Switch
A switch expression must always return a value.
Therefore every possible path must produce a result.
Example
String color = switch (number) {
case 1 -> "Red";
case 2 -> "Blue";
};
Compile-time error
The compiler complains because some values are not handled.
Adding default fixes the problem.
String color = switch (number) {
case 1 -> "Red";
case 2 -> "Blue";
default -> "Unknown";
};
Traditional vs Modern Switch
| Feature | Traditional Switch | Switch Expression |
|---|---|---|
| Introduced | Java 1 | Java 14 |
| Returns value | ❌ No | ✅ Yes |
Needs break
|
✅ Yes | ❌ No |
| Fall-through | ✅ Yes | ❌ No |
| Arrow syntax | ❌ No | ✅ Yes |
| Multiple labels | Limited | ✅ Easy |
| Safer | ❌ Less | ✅ More |
| Recommended for new code | ❌ Mostly legacy | ✅ Yes |
Common Beginner Mistakes
Forgetting default
A switch expression should handle every possible value.
Always include a default unless the compiler knows all possibilities (for example, every enum constant is covered).
Using break Instead of yield
Incorrect
case "Chrome" -> {
break;
}
Correct
case "Chrome" -> {
yield "Google";
}
Remember:
-
breakexits a traditional switch statement. -
yieldreturns a value from a switch expression.
Mixing Old and New Syntax
Avoid writing code like
case 1 ->
break;
The arrow syntax already prevents fall-through.
No break is needed.
Interview Questions
Why were switch expressions introduced?
To make switch statements:
- more concise
- safer
- less error-prone
- capable of returning values
What is the purpose of yield?
yield returns a value from a block inside a switch expression.
Does arrow syntax support fall-through?
No.
Each arrow case executes independently.
Can switch expressions return objects?
Yes.
They can return any type.
Example
Student student = switch (department) {
case "IT" -> new Student("Rajesh");
default -> new Student("Guest");
};
Best Practices
- Prefer switch expressions in modern Java projects.
- Use arrow syntax whenever possible.
- Use
yieldonly when a case contains multiple statements. - Keep each case small and readable.
- Always include a
defaultfor non-enum switches. - Avoid mixing old and new switch styles.
Quick Memory Trick 🧠
Remember the word ARROW:
-
A → Arrow (
->) - R → Returns values
- R → Readable
- O → One case, no fall-through
- W → Works great in modern Java
Key Takeaways
- Switch expressions became a standard feature in Java 14.
- They can directly return values.
- Arrow (
->) syntax removes the need forbreak. - There is no accidental fall-through.
- Multiple case labels can be grouped together.
-
yieldreturns a value from a block. - Switch expressions are cleaner, safer, and more readable than traditional switch statements.
- They are the preferred choice for new Java applications.
If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.
Happy Coding!
Top comments (0)