liveBook · Manning

Null handling

As explained in 100 Java Mistakes and How to Avoid Them

A null check is a condition that tests whether a reference has the null value.

A null check tests whether a reference contains null, but operator precedence can make the check test the wrong expression. In `"Value: " + value != null ? value : "(unknown)"`, concatenation happens first, so the condition is always true and null may be returned unchanged. section 2.2.3

A check defeated by concatenation

The faulty expression is parsed as `(("Value: " + value) != null) ? value : "(unknown)"`. Split the computation into steps: first select `value != null ? value : "(unknown)"`, then concatenate it. Parentheses also make the intended grouping explicit. section 2.2.3

Reduce null-related failures with targeted practices:

  • Separate expressions that combine concatenation, arithmetic, and conditional operators; for display text, use a temporary variable or a formatting call. Java 15 also provides `formatted`, while `requireNonNullElse` can supply a fallback. section 2.2.3
  • Avoid null values where possible, use `Optional` when absence is meaningful, add nullability annotations, and use interprocedural static analysis for potential `NullPointerException` problems. section 5.1
  • In concurrent queues, replace an `isEmpty()` check followed by `remove()` with `poll()` and check the returned local value; use atomic map operations such as `merge()` for related get-and-put patterns. section 9.12
String format(String value) { 
  return "Value: " + value != null ? value : "(unknown)"; 
}

Inspect the compact faulty expression, then compare its precedence-expanded form with the separated corrected version. section 2.2.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains operator precedence, prevention practices, nullability strategies, and atomic queue handling without developing a complete nullability type system.
Examples
Uses faulty string formatting, ArrayList capacity arithmetic, queue polling, ConcurrentMap.merge, and AtomicInteger.updateAndGet examples.
What it assumes
Assumes Java references, conditional expressions, operators, collections, and basic concurrency while distinguishing nullable from non-nullable values.
What you can do after
Diagnose/debug with precedence-aware inspection, static analyzers, local null checks, and atomic collection methods.
How it connects
Connects null checks with conditional operators, string concatenation, NullPointerException, Optional, static analysis, and concurrent collections.

Also explained in

Compare how 2 books explain null handling →

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.