Java / Java 21 Coding Standards Interview Questions
How do you troubleshoot a NullPointerException using Objects.requireNonNull as a coding standard?
The standard practice is to validate constructor and setter arguments with Objects.requireNonNull(value, "message") at the boundary where the value enters the object, rather than letting a null quietly propagate until it is dereferenced several calls later, far from its actual source.
public Order(String id, Customer customer) { this.id = Objects.requireNonNull(id, "id must not be null"); this.customer = Objects.requireNonNull(customer, "customer must not be null"); }
When troubleshooting an existing NullPointerException, Java's "helpful NPE" messages (enabled by default since Java 14) already report the exact variable or method call that was null, so the fix is usually to add a requireNonNull guard at the point where that value was first accepted, not just where it later blew up.
This turns a null bug from a stack trace pointing at an unrelated line of business logic into an immediate, clearly labeled failure at construction time, which is far faster to diagnose during code review or in a failing test.
More Related questions...