# Remove toString() on String

# Properties

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

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

# 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

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? 😊