StringBuffer/StringBuilder for Constant Value

ID

java.stringbuffer_for_constant_value

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports local StringBuffer or StringBuilder variables that are never mutated. When no mutator method (append, insert, delete, replace, reverse, setCharAt, setLength, deleteCharAt, appendCodePoint) is called on the variable, a plain String would suffice and avoids the overhead of maintaining a mutable buffer object.

Rationale

String objects are immutable and cheap to create, while StringBuffer and StringBuilder carry the overhead of a resizable character array and synchronization (for StringBuffer). If the buffer is never modified after construction, using it is wasteful.

// Bad -- StringBuffer is never mutated
StringBuffer sb = new StringBuffer("Hello");
String result = sb.toString();

A buffer that is handed to something else — passed as an argument, returned, stored in a field or added to a collection — is not reported: the receiver may append to it out of sight, so "never mutated" is no longer decidable from the declaring method alone.

// Not reported -- the helper appends to the buffer
StringBuilder sb = new StringBuilder("{");
addField(sb, "\"login\": ", login);
return sb.toString();

Remediation

Replace the StringBuffer/StringBuilder with a plain String.

// Good -- use String directly
String result = "Hello";

© 2026 Xygeni. All rights reserved