Modern Java 8+ Features · Modern Java (10–21)

Switch Expressions and Pattern Matching

Modern Java: switch that returns a value with arrows (no break needed), and instanceof that checks and names a type in one step.

ModernSwitchDemo.java

public class ModernSwitchDemo {
    static String kind(int day) {
        return switch (day) {                       // switch as an expression: it gives a value
            case 6, 7 -> "weekend";
            case 1, 2, 3, 4, 5 -> "weekday";
            default -> "unknown";
        };
    }

    static String describe(Object o) {
        if (o instanceof String s) {                 // check the type and name it in one go
            return "text of length " + s.length();
        } else if (o instanceof Integer n && n > 100) {
            return "big number";
        }
        return "something else";
    }

    public static void main(String[] args) {
        String d6 = kind(6);
        String d2 = kind(2);
        String a = describe("hello");
        String b = describe(500);
        System.out.println(d6 + " " + d2 + " " + a + " " + b);
    }
}

Step by step

  1. Java calls kind(), with day = 6. It gets its own variables on the stack. The program starts in main. args holds its command-line arguments (none here).
  2. A switch expression: it produces a value that is returned directly.
  3. case 6, 7 -> matches either value: "weekend".
  4. kind() has finished, so its variables are gone.
  5. The value it returned, "weekend", is stored in d6.
  6. Java calls kind(), with day = 2. It gets its own variables on the stack.
  7. The method returns switch (day) { // switch as an expression: it gives a value.
  8. Day 2 matches the weekday group.
  9. kind() has finished, so its variables are gone.
  10. The value it returned, "weekday", is stored in d2.
  11. Java calls describe(), with o = "hello". It gets its own variables on the stack.
  12. o instanceof String s checks the type and, if it matches, creates s already cast to String.
  13. describe() has finished, so its variables are gone.
  14. The value it returned, "text of length 5", is stored in a.
  15. Java calls describe(), with o = 500. It gets its own variables on the stack.
  16. Line runs: if (o instanceof String s) { // check the type and name it in one go.
  17. The pattern can be combined with a condition: an Integer over 100.
  18. describe() has finished, so its variables are gone.
  19. The value it returned, "big number", is stored in b.
  20. It prints weekend weekday text of length 5 big number.
  21. weekend, weekday, text of length 5, big number. Less code, and no casts or breaks.