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
