Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8289894

A NullPointerException thrown from guard expression

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 19
    • 19
    • tools
    • None
    • b31

        Consider code like:
        ---
        public class SwitchGuard {
            public static void main(String... args) {
                test(null);
            }
            private static void test(Object o) {
                switch (o) {
                    case null, String s when s.isEmpty() -> System.err.println("OK.");
                    default -> {}
                }
            }
        }
        ---

        when ran, this should print "OK.", but it fails with a NPE:
        ---
        $ java --enable-preview SwitchGuard
        Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "<local3>" is null
                at SwitchGuard.test(SwitchGuard.java:7)
                at SwitchGuard.main(SwitchGuard.java:3)
        ---

              jlahoda Jan Lahoda
              jlahoda Jan Lahoda
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Created:
                Updated:
                Resolved: