# Remove Boxing for String Conversions

# Description

When calling toString() on a boxed primitive no new instance of that primitive has to be created. This rule replaces occurrences of such code with a static method.

# Benefits

This rule has performance benefits. As described above boxing the object simply to use the static toString method is a waste of memory and CPU cycles.

# Tags

# Code Changes

# Boolean

Pre

new Boolean(true).toString();

Post

Boolean.toString(true);

# Byte

Pre

new Byte(1).toString();

Post

Byte.toString(1);

# Double

Pre

new Double(1.0).toString();

Post

Double.toString(1.0);

# Float

Pre

new Float(1.0).toString();

Post

Float.toString(1.0);

# Integer

Pre

new Integer(1).toString();

Post

Integer.toString(1);

# Long

Pre

new Long(1).toString();

Post

Long.toString(1);

# Short

Pre

new Short(1).toString();

Post

Short.toString(1);

# Bytecode JDK 1.8

Pre

public void original(boolean b) {
    String value = new Boolean(b).toString();
}
 0 new #2 <java/lang/Boolean>
 3 dup
 4 iload_1
 5 invokespecial #3 <java/lang/Boolean.<init>>
 8 invokevirtual #4 <java/lang/Boolean.toString>
11 astore_2
12 return

Post

public void transformed(boolean b) {
    String value = Boolean.toString(b);
}
0 iload_1
1 invokestatic #5 <java/lang/Boolean.toString>
4 astore_2
5 return

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID PrimitiveBoxedForString
First seen in jSparrow version 1.0.0
Minimum Java version 1.1
Remediation cost 5 min
Links