# 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 + "";

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID UseStringBuilderAppend
First seen in jSparrow version 2.7.0
Minimum Java version 5
Remediation cost 2 min
Links