Java / Java 21 Interview Questions
What improvements were made to NullPointerException messages in Java 14?
JEP 358 (Java 14) enabled helpful NullPointerException messages that precisely identify which variable or expression was null, rather than just the line number and a generic message. This was one of the most immediately useful quality-of-life improvements in recent Java history.
// Before Java 14: vague NPE
// Exception in thread "main" java.lang.NullPointerException
// at com.example.Main.main(Main.java:12)
// Java 14+: helpful NPE message
// NullPointerException: Cannot invoke "String.length()" because
// "" is null
// Detailed example
a.b.c.d = 42;
// Cannot assign field "d" because "a.b.c" is null
a[5].b = 42;
// Cannot assign field "b" because "a[5]" is null
a.b = foo();
// Cannot invoke "Main.foo()" because "a" is null
// Enabled by default since Java 15
// (In Java 14 it was enabled with -XX:+ShowCodeDetailsInExceptionMessages)
// Complements with Objects.requireNonNull for fail-fast validation
String name = Objects.requireNonNull(input, "input must not be null");
// Objects.requireNonNullElse — Java 9
String display = Objects.requireNonNullElse(name, "Unknown");
// Objects.requireNonNullElseGet — lazy supplier
String display2 = Objects.requireNonNullElseGet(name, () -> computeDefault()); The JVM analyses the bytecode at the point of the NPE and constructs a sentence describing which specific reference in a complex expression was null. This works for field access, method invocations, array accesses, and unboxing operations. It dramatically reduces debugging time for nested null-checks.
More Related questions...