# Use String Literals

# Description

Removes all class instantiations from String if its parameter is empty or a String. An empty parameter is replaced with the empty String and the construction of a String or String-literal removes the constructor.

# Benefits

Avoiding the constructor call has performance benefits as it reduces memory usage and improves readability.
Furthermore, these constructors are deprecated in Java 9, which is an indication that they will eventually be removed from the language altogether.

# Tags

# Code Changes

Pre

public String testNewStringOfLiteral() {
    return new String("StringLiteral");
}
public String testNewStringOfLiteralWithParentheses() {
    return new String(("StringLiteral"));
}
public String testNewStringOfOtherString(String s) {
    return new String(s);
}
public String testNewStringOnNonStringElement(StringBuilder sb) {
    return new String(sb);
}

Post

public String testNewStringOfLiteral() {
    return "StringLiteral";
}
public String testNewStringOfLiteralWithParentheses() {
    return "StringLiteral";
}
public String testNewStringOfOtherString(String s) {
    return s;
}
public String testNewStringOnNonStringElement(StringBuilder sb) {
    return new String(sb);
}

🛠️ 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 RemoveNewStringConstructor
First seen in jSparrow version 1.0.0
Minimum Java version 1.1
Remediation cost 5 min
Links