Boxed Type toString() Instead Of Static toString()

ID

java.boxed_tostring

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

efficiency

Description

Reports patterns like new Integer(x).toString() or Integer.valueOf(x).toString() where an intermediate boxed object is created solely to call toString(). The static Integer.toString(x) achieves the same result without allocating a wrapper object.

Rationale

Creating a boxed wrapper just to convert a primitive to a string wastes an allocation. The static toString() method on each wrapper class performs the conversion directly.

// Bad - allocates an Integer just to discard it
String s = new Integer(42).toString();
String t = Integer.valueOf(42).toString();

Remediation

Use the static toString() method directly.

// Good - no intermediate object
String s = Integer.toString(42);
String t = Long.toString(100L);