liveBook · Manning

Missing value

As explained in 100 Java Mistakes and How to Avoid Them

The null value is Java's special reference value denoting the absence of an object reference.

Java's null value denotes the absence of an object reference, but it carries no inherent meaning. Code may use it for uninitialized, lazy, unspecified, missing, or empty states, making its interpretation a developer responsibility. section 5.1

Null becomes especially hazardous in these situations:

  • Passing null to a variable-arity method can select the array form, leave the parameter array null, and cause a NullPointerException during iteration. section 2.9.1
  • Collection interfaces do not reveal whether null elements are supported or whether contains(null) is safe; collection implementations differ. section 8.3
  • Streams may carry null intermediate values, but operations returning Optional and collectors such as toMap() or groupingBy() can reject them. section 9.4

Make a varargs intention explicit

printAll(null) passes a null Object[] rather than an array containing one null, so iteration fails. Use printAll((Object) null) for one null element, or printAll((Object[]) null) when a null array reference is intentional. section 2.9.1

Filter before a terminal operation

List<Integer> list = Arrays.asList(null, 1, 2); list.stream().filter(Objects::nonNull).findFirst(); Filtering early avoids findFirst() failing when the first stream element is null. section 9.4

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

Compare the two explicit casts that distinguish an array containing null from a null array reference. section 2.9.1

Stream.of((Object)null).findFirst()

Use this minimal expression to reproduce findFirst() failure on a null stream element. section 9.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains sentinel meanings and failure modes in varargs, collections, maps, and streams, then gives avoidance rules and diagnostic techniques.
Examples
Demonstrates null varargs calls, null-hostile collection searches, stream terminals, and collectors with null elements or results.
What it assumes
Assumes Java reference types, arrays, collections, streams, and Optional, while distinguishing nullable from non-nullable usage.
What you can do after
Diagnose null failures, clarify varargs intent, guard collection searches, filter streams, and choose Optional or annotations where appropriate.
How it connects
Connects null with NullPointerException, Optional, varargs, collections, maps, streams, static analysis, and nullability annotations.

Also explained in

Compare how 35 books explain missing value →

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.