liveBook · Manning

NonNegative annotation

As explained in 100 Java Mistakes and How to Avoid Them

The NonNegative annotation declares that an annotated numeric value or parameter must not be less than zero.

The @NonNegative annotation documents that a numeric parameter cannot be negative. Applied to an index, it can help a static analyzer warn about calls that pass a negative value. section 5.2

Annotating an index

int getValue(@NonNegative int index) { return myData[index]; } The annotation does not replace a runtime bounds check: an index may be nonnegative yet still exceed the array or list bounds. Check client-supplied indexes immediately, and distinguish < from <= when the valid endpoint matters. section 5.2

For an int parameter, JetBrains’ @Range(from = 0, to = Integer.MAX_VALUE) expresses equivalent bounds explicitly. Use annotations to document contracts and aid analysis, not as a substitute for enforcing them. section 5.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the constraint, analyzer warning, equivalent range form, and limits; stops short of runtime enforcement.
Examples
Uses an annotated array index and contrasts nonnegative validation with complete array or list bounds checking.
What it assumes
Assumes familiarity with Java parameters, numeric comparisons, and array or list indexing.
What you can do after
Apply @NonNegative or @Range to document numeric contracts and support static analysis before invalid indexing reaches runtime.
How it connects
Connects nonnegative parameters with index bounds, static analysis, @Positive, @Range, and IndexOutOfBoundsException.

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.