How do you use switch expressions with a simple code example?

Switch expressions introduced in Java 12 provide a more concise and flexible way to handle multiple conditions. Unlike the traditional switch statement, switch expressions can return a value, which can make your code simpler and cleaner.

Here is a simple example that demonstrates how to use a switch expression in Java:

public class SwitchExample { public static void main(String[] args) { int day = 4; 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); } }

switch expressions Java programming Java code example