liveBook · Manning

NullPointerException

As explained in 100 Java Mistakes and How to Avoid Them

NullPointerException is the Java runtime exception raised when an operation dereferences or otherwise improperly uses a null reference.

NullPointerException occurs when Java code uses a null reference where an object or array is required. Null is legal for non-primitive variables and return values, but carries no intrinsic meaning: it may represent an uninitialized value, lazy state, an unspecified field, a missing map entry, or an empty queue. The practical question at every reference is whether null is possible and, if so, what it means. section 5.1

Treat nullable and non-nullable values differently. Java does not encode that distinction in its type system, so unexpected nulls can travel through APIs until a dereference fails. Prefer avoiding null where practical; use Optional for an absent value and nullability annotations to document and check contracts. At public API boundaries, reject null inputs before storing them in fields, so failures occur near their cause. section 5.1 section 5.5

A null varargs array

A single null passed to an Object... parameter is not necessarily an array containing one null. Because null is assignable to Object[], Java can pass a null array reference instead; iterating over that parameter then throws NullPointerException. Cast deliberately when intent matters: (Object)null requests one null element, while (Object[])null requests a null array. section 2.9.1

// I want an array containing null 
printAll((Object)null); 
// I want just null array reference 
printAll((Object[])null);

These casts make the two meanings of a null varargs call explicit and prevent an accidental null array from reaching code that iterates it. section 2.9.1

Static initialization order

Static fields initialize in declaration order. If one field calls code that dereferences a later static field, that later field is still null. For example, initializing a current version through parse() before initializing the regular-expression Pattern makes REGEX.matcher fail. Reorder dependent declarations; similarly, initialize a logger before a singleton constructor might need it to report an exception. section 3.9.1

Collections add another source of surprises. Some collections permit null elements; some reject null elements but let contains(null) return a not-found result; others reject null searches themselves. In particular, replacing an older unmodifiable set with Set.of can turn PLATFORMS.contains(str), when str is null, from false into NullPointerException. Do not assume the Set, List, Map, or Collection interface reveals null behavior; guard a possibly null search value first. section 8.3

Reduce null-related failures with explicit contracts and local checks:

  • Avoid null values where possible; represent an allowed absence with Optional and annotate nullable contracts. section 5.1
  • Validate public-method inputs before persisting them to object state. section 5.5
  • When one varargs argument might be ambiguous, add an explicit cast rather than relying on null inference. section 2.9.1
  • Avoid collection.contains(value) when value may be null; use value != null && collection.contains(value). section 8.3
  • Investigate nullability warnings around static fields for declaration-order dependencies; advanced initialization analysis can find cycles that simpler data-flow checks miss. section 3.9.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines nullability concerns and develops focused failure mechanisms, stopping at prevention rules and tool guidance.
Examples
Uses null varargs casts, static field ordering, logger initialization, and Set.of contains(null) migration cases.
What it assumes
Assumes working Java knowledge of references, methods, static fields, and collection interfaces.
What you can do after
Diagnose/debug with it by tracing nullable flows, initialization order, varargs binding, and collection null policies.
How it connects
Connects nullability with Optional, annotations, varargs, static initialization, collection factories, and static analysis.

Also explained in

Compare how 2 books explain NullPointerException →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.