Avoid the Deprecated Boolean Constructor

ID

java.new_boolean_constructor

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

CWE:1046, code-style, efficiency

Description

Reports calls to the Boolean constructor (new Boolean(true), new Boolean("true")). The Boolean(boolean) and Boolean(String) constructors have been deprecated since JDK 9 because they always allocate a new object on the heap, whereas Boolean.TRUE and Boolean.FALSE are shared cached instances.

Rationale

Since Boolean is immutable and has only two possible values, there is no reason to create new instances. Every new Boolean(…​) call wastes memory and adds GC pressure for no benefit. Furthermore, using the constructor can break identity comparisons (==) that work correctly with the cached constants.

// Bad — allocates unnecessary objects
Boolean a = new Boolean(true);
Boolean b = new Boolean("false");

Remediation

Replace new Boolean(value) with Boolean.valueOf(value), Boolean.TRUE, or Boolean.FALSE.

// Good — reuses cached instances
Boolean a = Boolean.TRUE;
Boolean b = Boolean.valueOf("false");
Boolean c = Boolean.valueOf(flag);