Java Switch statement new Pattern Matching feature

JEP 406 enhances the Java programming language with pattern matching for switch expressions and statements and extensions to the language of patterns. These capabilities are a preview feature in JDK 17.

Code sample:

public static String formatterPatternSwitch(Object o) {
return switch (o) {
    case Integer i -> String.format("int %d", i);
    case Long l -> String.format("long %d", l);
    case Double d -> String.format("double %f", d);
    case String s -> String.format("String %s", s);
   default -> o.toString();
  };
}

no more null pointer

static void testFooBar(String s) {
    switch (s) {
        case null         -> System.out.println("Oops");
        case "Foo", "Bar" -> System.out.println("Great");
        default           -> System.out.println("Ok");
    }
}

Author

lz402@tuta.io
Total post: 9