Core Java: A switch expression can match case null before any type pattern

Since pattern matching for switch, a case null label lets a switch handle a null selector directly instead of throwing a NullPointerException, as long as it appears before or as part of the matching cases.

Code
String input = null;
String result = switch (input) {
    case null -> "was null";
    case "a" -> "letter a";
    default -> "something else";
};
System.out.println("Result: " + result);
Output
Result: was null
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms