CodeQL documentation

Useless null check

ID: java/useless-null-check
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - maintainability
   - useless-code
   - external/cwe/cwe-561
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Sometimes you can guarantee that a particular variable will never be null. For example when that variable has just been assigned a newly created object or is the exception caught by a catch clause. A null check on such a variable is misleading, and can potentially indicate a logic error.

Recommendation

Do not check a variable for null if a null value is clearly impossible.

Example

The following example shows a null check on a newly created object. An object returned by new can never be null, so this check is superfluous.

Object o = new Object();
if (o == null) {
  // this cannot happen!
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy