Callers of a Boolean method often expect to receive either true or false. However, unlike the primitive
boolean type, Boolean objects can also be null. When a null Boolean is implicitly
unboxed, using it as a primitive value can cause a NullPointerException.
This rule is intentionally scoped to methods returning Boolean. The same unboxing risk exists for other nullable wrapper types, but
Boolean values are commonly used as predicates, where null introduces a third state to a value callers may otherwise expect
to be binary. The rule does not prohibit a deliberate tri-state Boolean; it requires the nullable return contract to be explicit.
If null is a legitimate return value, annotate the method with a nullability annotation supported by the analyzer. Examples include
@javax.annotation.Nullable, @javax.annotation.CheckForNull, @jakarta.annotation.Nullable, and
@org.jspecify.annotations.Nullable. This makes the contract clear to callers and to tools that check nullability. If null is
not a legitimate value, return a primitive boolean or a non-null Boolean instead.
public Boolean isUsable() {
// ...
return null; // Noncompliant
}
public void caller() {
if (isUsable()) { // A NullPointerException might occur here
// ...
}
}
@javax.annotation.Nullable
public Boolean isUsable() {
// ...
return null; // null represents an unknown state
}
@javax.annotation.CheckForNull
public Boolean isUsableOrUnknown() {
// ...
return null; // null represents an unknown state
}
public void caller() {
if (Boolean.TRUE.equals(isUsable())) { // null is handled explicitly
// ...
}
}