CodeQL documentation

Dereferenced variable may be null

ID: java/dereferenced-value-may-be-null
Kind: problem
Severity: warning
Precision: high
Tags:
   - reliability
   - correctness
   - exceptions
   - external/cwe/cwe-476
   - non-local
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

If a variable is dereferenced, and the variable may have a null value on some execution paths leading to the dereferencing, the dereferencing may result in a NullPointerException.

A variable may also be implicitly dereferenced if its type is a boxed primitive type, and the variable occurs in a context in which implicit unboxing occurs. Note that the conditional operator unboxes its second and third operands when one of them is a primitive type and the other is the corresponding boxed type.

Recommendation

Ensure that the variable does not have a null value when it is dereferenced.

Example

In the following example, the use of the conditional operator causes implicit unboxing, since the integer literal has type int. If the parameter p is ever null then a NullPointerException will occur.

public Integer f(Integer p) {
	return true ? p : 5;
}

If the implicit unboxing is unintentional, it can be prevented by making sure that both branches of the conditional operator have the same type.

References