# Use StringBuilder::append

# Description

Replaces the infix operator + over String concatenations with at least three operands by StringBuilder::append. When possible, unwraps the parenthesized expressions.

# Benefits

Improves the performance of the String concatenations.

# Tags

# Code Changes

# Concatenating strings in infix expressions

Pre

String value = "prefix" + "value" + "suffix";

Post

String value = new StringBuilder().append("prefix")
    .append("value")
    .append("suffix")
    .toString();

# Resolving types of arithmetic expressions

Pre

String value = "prefix" + 2 * 3 + ("value" + 2 + 3) + (4 + 5) + "suffix";

Post

String value = new StringBuilder().append("prefix")
    .append(2*3)
    .append("value")
    .append(2)
    .append(3)
    .append(4 + 5)
    .append("suffix")
    .toString();

# Resolving types of numeric literals

Pre

String value = 5 + " (five) = " + 3 + " (three) + " + 2 + " (two).";

Post

String value = new StringBuilder().append(5)
    .append(" (five) = ")
    .append(3)
    .append(" (three) + ")
    .append(2)
    .append(" (two).")
    .toString();

# Limitations

If at least two of the first operands of the expression are numeric additions then the expression is evaluated by Java as numeric expression rather than String expression. Therefore, the transformation is not performed. E.g.:

Pre

String value = 2 + 3 + "";

🛠️ 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 UseStringBuilderAppend
First seen in jSparrow version 2.7.0
Minimum Java version 5
Remediation cost 2 min
Links