Incorrect null check before setting a value Medium

When a variable is assigned a value after checking if it's not null (for example, x != null), it might be inadvertently overwritten. We recommend that you verify a variable is null (for example, x == null) before assigning it a value.

Detector ID
java/incorrect-null-check-before-setting@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1public void nullCheckNoncompliant() {
2    if (data1 != null) {
3        // Noncompliant: overwriting immediately after a non-null check is likely to be a typo.
4        data1 = data2;
5    }
6}

Compliant example

1public void nullCheckCompliant() {
2    if (data1 == null) {
3        // Compliant: overwriting after a null check is a common pattern.
4        data1 = data2;
5    }
6}