liveBook · Manning

NonNullByDefault annotation

As explained in 100 Java Mistakes and How to Avoid Them

A NonNullByDefault annotation declares that applicable types, parameters, or return values are non-null unless explicitly specified otherwise.

A NonNullByDefault annotation makes selected types non-null unless a declaration explicitly overrides the default. It can apply to a class, interface, or package, reducing repetitive nullity annotations. section 5.1.3

Defaulting parameters and return values

@NonNullByDefault({DefaultLocation.PARAMETER, DefaultLocation.RETURN_TYPE}) public interface MyInterface { String processString(String input); } Here, processString() is specified to reject a null input and never return null. Use an explicit nullable annotation when an exception to the default is part of the API. section 5.1.3

Treat the annotation as an API contract: it simplifies nullity specification, while static analysis can check calls against the declared defaults and expose contradictory null assumptions. section 5.1.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines class, interface, and package scope plus parameter and return locations, but does not detail implementation mechanics.
Examples
Uses an Eclipse JDT interface declaration with parameter and return-type defaults.
What you can do after
Apply it via Eclipse JDT annotations to declare non-null API defaults across selected program elements.
How it connects
Connects default nullity with nullable annotations and static analysis.

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.