Levels of Helpfulness in Helpful Null Pointers

Java introduced Helpful Null Pointers. Let’s take a look at a few versions using this class:

public class Helpful {
  private String name;
  private Helpful(String name) {
    this.name = name.toUpperCase();
  }
  public static void main(String... args) {
     new Helpful(null);
  }
}

Three approaches

First lets’ run this using Java 11. We get the stack trace

Exception in thread “main” java.lang.NullPointerException
at Helpful.(Helpful.java:4)
at Helpful.main(Helpful.java:7)

Well that’s not helpful. I have to go look at line 4 to even have a clue what is going on. Now let’s run it in Java 17. (Because I’m sticking with Long Term Support versions)

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.toUpperCase()” because “<parameter 1>” is null
at Helpful.(Helpful.java:4)
at Helpful.main(Helpful.java:7)

That’s more helpful. It tell us the toUppercase() call is the problem. And that a constructor was the cause. It would be even more helpful to know the name of the variable. This requires a command line flag. Compile with -g:vars and you get this when running

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.toUpperCase()” because “name” is null
at Helpful.(Unknown Source)
at Helpful.main(Unknown Source)

Conveniently, both Eclipse and IntelliJ turn on this flag by default.