How to use switch expressions in Java 17

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:

  1. Return values directly from a switch block (as an expression).
  2. Use concise syntax with the arrow -> syntax.
  3. Prevent fall-through by removing the need for explicit break statements.
  4. Handle multiple case labels compactly.

Switch Expression Syntax

Basic Syntax

switch (expression) {
    case value1 -> result1;
    case value2 -> result2;
    default -> defaultResult;
}
  1. Use -> for expression forms.
  2. A default case is mandatory unless all possible values are handled.
  3. 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.

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, and yield to specify the value to return.

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.

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 the return value is implicit in switch expressions.

Key Features to Remember

  1. No need for break statements.
  2. Use -> for one-liner cases.
  3. Use yield to return values from block-style cases.
  4. Works well with var for type inference.

Switch expressions simplify many patterns while keeping your code readable and concise!

How do I use string in switch statement?

Starting from Java 7 release you can now use a String in the switch statement. On the previous version we can only use constants type of byte, char, short, int (and their corresponding reference / wrapper type) or enum constants in the switch statement.

The code below give you a simple example on how the Java 7 extended to allow the use of String in switch statement.

package org.kodejava.basic;

public class StringInSwitchExample {
    public static void main(String[] args) {
        String day = "Sunday";
        switch (day) {
            case "Sunday":
                System.out.println("doSomething");
                break;
            case "Monday":
                System.out.println("doSomethingElse");
                break;
            case "Tuesday":
            case "Wednesday":
                System.out.println("doSomeOtherThings");
                break;
            default:
                System.out.println("doDefault");
                break;
        }
    }
}

How do I use enum in switch statement?

This example show you how to use enumeration or enum type in a switch statement.

package org.kodejava.basic;

public enum RainbowColor {
    RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}
package org.kodejava.basic;

public class EnumSwitch {
    public static void main(String[] args) {
        RainbowColor color = RainbowColor.INDIGO;

        EnumSwitch es = new EnumSwitch();
        String colorCode = es.getColorCode(color);
        System.out.println("ColorCode = #" + colorCode);
    }

    public String getColorCode(RainbowColor color) {
        String colorCode = "";

        // We use the switch-case statement to get the hex color code of our
        // enum type rainbow colors. We can pass the enum type as expression
        // in the switch. In the case statement we only use the enum named
        // constant excluding its type name.
        switch (color) {
            // We use RED instead of RainbowColor.RED
            case RED -> colorCode = "FF0000";
            case ORANGE -> colorCode = "FFA500";
            case YELLOW -> colorCode = "FFFF00";
            case GREEN -> colorCode = "008000";
            case BLUE -> colorCode = "0000FF";
            case INDIGO -> colorCode = "4B0082";
            case VIOLET -> colorCode = "EE82EE";
        }
        return colorCode;
    }
}