Useless null check¶
ID: java/useless-null-checkKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - maintainability - useless-code - external/cwe/cwe-561Query 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 acatch 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 bynew can never be null, so this check is superfluous.
Objecto=newObject();if(o==null){// this cannot happen!}
References¶
Java Language Specification:Creation of New Class Instances,Execution of try-catch.
Common Weakness Enumeration:CWE-561.