# Remove toString() on String

# Description

All method invocations of toString() are tested as to whether they are used on a String element. If this is the case, the method call is removed, because it is not necessary.
For example, "string".toString() becomes "string".

# Benefits

As the Java compiler will get rid of the redundant method call, there are no performance benefits. However, removing the call improves readability of the code.

# Tags

# Code Changes

Pre

public String testToStringOnStringLiteral() {
    return "anStringLiteral".toString();
}
public String testToStringOnStringVariable() {
    String s = "theStringS";
    return s.toString();
}
public String testToStringOnStringFunctionThatReturnsString() {
    return StringUtils.abbreviate("makeMeShorter", 4).toString();
    }
public String testToStringOnParenthesizeString(String s) {
    return (s).toString();
}
public String testToStringOnParenthesizePlusString(String s) {
    return (s + "abc").toString();
}

Post


public String testToStringOnStringLiteral() {
    return "anStringLiteral";
}
public String testToStringOnStringVariable() {
    String s = "theStringS";
    return s;
}
public String testToStringOnStringFunctionThatReturnsString() {
    return StringUtils.abbreviate("makeMeShorter", 4);
}
public String testToStringOnParenthesizeString(String s) {
    return s;
}
public String testToStringOnParenthesizePlusString(String s) {
    return s + "abc";
}

# Bytecode JDK 1.8

Pre

public void original(String value) {
    String newValue = value.toString();
}
0 aload_1
1 invokevirtual #2 <java/lang/String.toString>
4 astore_2
5 return

Post

public void transformed(String value) {
    String newValue = value;
}
0 aload_1
1 astore_2
2 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 RemoveToStringOnString
First seen in jSparrow version 1.0.0
Minimum Java version 1.1
Remediation cost 5 min
Links