Boxed Number Constructor Is Inefficient

ID

java.number_ctor_inefficient

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

efficiency

Description

Reports constructor calls on boxed-number wrapper types: new Integer(x), new Long(x), new Double(x), new Float(x), new Short(x), new Byte(x), and new Boolean(x). These constructors were deprecated in Java 9 and removed in Java 16.

Rationale

The valueOf() factory methods cache frequently-used values (all Boolean values, Byte, Short, Integer, and Long values in [-128, 127]). Constructors always allocate a new object, bypassing the cache and wasting memory. In modern Java the constructors are no longer available, so code using them will fail to compile.

// Bad - always allocates a new object, deprecated/removed
Integer a = new Integer(42);
Boolean b = new Boolean(true);

Remediation

Use the static valueOf() factory method or autoboxing.

// Good - uses cached instances when possible
Integer a = Integer.valueOf(42);
Boolean b = Boolean.valueOf(true);
// Or simply: Integer a = 42;