CodeQL documentation

Dereferenced variable is always null

ID: java/dereferenced-value-is-always-null
Kind: problem
Severity: error
Precision: very-high
Tags:
   - reliability
   - correctness
   - exceptions
   - external/cwe/cwe-476
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

If a variable is dereferenced, and the variable has a null value on all possible execution paths leading to the dereferencing, the dereferencing is guaranteed to 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 examples, the condition !dir.exists() is only executed if dir is null. The second example guards the expression correctly by using && instead of ||.

public void createDir(File dir) {
	if (dir != null || !dir.exists()) // BAD
		dir.mkdir();
}

public void createDir(File dir) {
	if (dir != null && !dir.exists()) // GOOD
		dir.mkdir();
}

References