Single-Character String Concatenation in Loop

ID

java.string_single_char_concat_in_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports String += "x" concatenation inside a loop body where the right-hand side is a single-character String literal. Using StringBuilder.append(char) is significantly more efficient, especially for loops with many iterations, as it avoids creating a new String object on each iteration.

Rationale

Each += on a String inside a loop creates a new String object, copying the previous content plus the appended part. When the appended value is a single character, this is particularly wasteful since StringBuilder.append(char) can append the character directly without any intermediate String creation.

// Bad -- single-char string concatenation in loop
String result = "";
for (int i = 0; i < n; i++) {
    result += " ";
}

Remediation

Use a StringBuilder with the append(char) overload.

// Good -- StringBuilder with char append
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
    sb.append(' ');
}
String result = sb.toString();