StringBuilder.append() With Single-Character String

ID

java.stringbuilder_append_char_as_string

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports calls to StringBuilder.append() or StringBuffer.append() where the argument is a single-character String literal (e.g., append("x")). The char overload append('x') should be preferred for better performance.

Rationale

When append(String) is called with a single-character string, the JVM must resolve the String object, obtain its internal character array, and copy the single character. The append(char) overload bypasses this overhead entirely, appending the character directly to the internal buffer. In tight loops or heavily used string-building code, this micro-optimization adds up.

// Bad -- single-char string literal
sb.append(",");
sb.append("\n");

Remediation

Replace the single-character String literal with the corresponding char literal.

// Good -- char literal
sb.append(',');
sb.append('\n');