What is Switch Expression in Java: Simple Explanation and Example
switch expression in Java is a modern form of the traditional switch statement that returns a value. It allows you to write cleaner and more concise code by using case labels to produce a result directly, instead of just controlling flow.How It Works
Think of a switch expression as a smart decision-maker that picks one option from many and gives you back a result. Unlike the old switch statement that just runs code blocks, the switch expression evaluates to a value you can store or use immediately.
It works by matching the input against different case labels. When it finds a match, it returns the value associated with that case. This is like choosing a flavor of ice cream and getting the scoop right away, instead of just deciding which flavor to pick.
This new form also supports the yield keyword to return values from complex case blocks, making the code easier to read and less error-prone.
Example
This example shows how a switch expression returns a string based on the day number.
public class SwitchExpressionExample { public static void main(String[] args) { int day = 3; 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); } }
When to Use
Use switch expressions when you want to select a value from multiple options in a clear and concise way. They are great for replacing long if-else chains that assign values based on conditions.
Real-world uses include mapping codes to descriptions, converting enums to strings, or deciding values based on user input. Switch expressions reduce bugs by forcing you to handle all cases or provide a default.
Key Points
- Switch expressions return a value, unlike traditional switch statements.
- They use
caselabels with->to associate values. - The
yieldkeyword can return values from complex case blocks. - They make code shorter, clearer, and less error-prone.
- Introduced in Java 12 as a preview and standardized in Java 14.