This product is not supported for your selected Datadog site. ().

Metadata

ID: java-best-practices/boxed-types-null

Language: Java

Severity: Notice

Category: Best Practices

Description

This rule checks that boxed primitive types (such as Integer, Float, Double, and Boolean) are not used in a way that assumes they can never be null. Boxed types can hold a null value, which may lead to NullPointerException if dereferenced without a null check. Ensuring that these types are either properly checked for null or avoided helps maintain code robustness and prevents runtime errors.

It is important to avoid unnecessary use of boxed types when primitive types suffice, as primitives cannot be null and thus eliminate the risk of null-related exceptions. When a boxed type is necessary, for example, when using collections or generics, always perform explicit null checks before usage. Additionally, consider using primitive types directly (int, float, double, boolean) whenever possible to improve performance and safety.

To comply with this rule, prefer using primitive types in variable declarations and operations. If you must use boxed types, write defensive code by checking for null values before any dereference. For example, instead of Float foo = 1.0; without null checks, use float foo = 1.0f; or ensure null safety when using Float. This practice leads to more reliable and maintainable Java code.

Non-Compliant Code Examples

class MyClass {
    public void foo() {
        Float foo = 1.0;
        if (bla) {
            foo = 2.0;
        }
        foo = 3.0;
    }
}
class MyClass {
    public void foo() {
        Double foo = 1.0;
        if (bla) {
            foo = 2.0;
        }
        foo = 3.0;
    }
}
class MyClass {
    public void foo() {
        Integer foo = 1;
        if (bla) {
            foo = 3;
        }
        foo = 2;
    }
}
class MyClass {
    public void foo() {
        Boolean foo = true;
        if (bla) {
            foo = true;
        }
        foo = false;
    }
}

Compliant Code Examples

class MyClass {
    public void foo() {
        float foo = 1.0;
        if (bla) {
            foo = 3.0;
        }
        foo = 2.0;
    }
}
class MyClass {
    public void foo() {
        int foo = 1;
        if (bla) {
            foo = 3;
        }
        foo = 2;
    }
}
class MyClass {
    public void foo() {
        Integer foo = 1;
        if (bla) {
            foo = null;
        }
        foo = 2;
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security