Example: NullPointerException

When checking a program, the compiler can detect runtime exceptions, i.e. exceptions like the NullPointerException, which belongs to the essential package java.lang of the Java programming language.

Here are all the situations where a NullPointerException occurs that are directly* mentioned in the Java Language Specification:

  • Accessing an instance field of a null reference (i.e., retrieving or setting it). (Static fields do not count!)
  • Invoking an instance method of a null reference. (Static methods do not count!)
  • Null casting;
  • Accessing elements of a null array.
  • Synchronize to null – synchronized (someNullReference) { … }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a packed null reference
  • An unboxed conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException.
public class NullPointerExceptionExample {

  public static void main(String[] args) {
    String str = null;

    try {
      System.out.println(str.length());
    } catch (NullPointerException e) {
      System.out.println("Null pointer access!");
      System.out.println("Error: " + e);
    }
  }
}
Output
Null pointer access!
Error: java.lang.NullPointerException