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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
