# Remove Boxing for String Conversions

# Properties

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

# 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.

# 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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow versions:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊