liveBook · Manning

Nullable annotation

As explained in 100 Java Mistakes and How to Avoid Them

A nullity annotation is metadata declaring whether a program value, parameter, field, or method result may be null.

A nullable annotation records whether a value, parameter, field, or method result may be null. @Nullable permits null; @NotNull or @Nonnull declares that null is not expected. These annotations document contracts and guide static analysis. section 5.1.3

Two common warnings

A nullable result must be checked before dereferencing: calling getNullable().trim() is unsafe. Conversely, testing getNotNull() == null is redundant and may expose an incorrect assumption. XML DOM illustrates the danger: Element.getAttribute() returns an empty string, not null, when an attribute is absent; use hasAttribute() to distinguish absence from an empty value. section 5.1.3

import org.jetbrains.annotations.*;

interface MyInterface {
  @NotNull String getNotNull();
  @Nullable String getNullable();

  default void test() {
    if (getNotNull() == null) {    #1
      …
    }

    System.out.println(getNullable().trim());    #2
  }
}

Compare annotated interface methods with the unsafe dereference and redundant null check. section 5.1.3

Use nullity annotations defensively:

  • Annotate APIs consistently, configure custom annotations when needed, and treat analyzer warnings as contract clues rather than automatic proof. section 5.1.3
  • Remember that standard-library annotations may be supplied externally by tools such as IntelliJ IDEA, SpotBugs, and PVS-Studio. section 5.1.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines annotation meanings, demonstrates warnings and API-contract mistakes, and stops short of annotation implementation details.
Examples
Uses annotated interface methods, nullable dereferencing, redundant checks, and Element.getAttribute() versus hasAttribute().
What it assumes
Assumes Java familiarity while teaching nullable and non-null contracts through focused examples.
What you can do after
Diagnose unsafe dereferences and misleading null checks with annotations, API documentation, and configurable static analysis.
How it connects
Connects nullability with NullPointerException prevention, static analysis, null checks, and XML DOM API contracts.

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.