Redundant toString() on StringBuilder in Concatenation

ID

java.stringbuilder_redundant_tostring_in_concat

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

code-style, efficiency

Description

Reports calls to .toString() on a StringBuilder or StringBuffer inside a + string concatenation expression. The Java compiler automatically invokes toString() during string concatenation, making the explicit call redundant and the code less readable.

Rationale

In a string concatenation such as "prefix " + sb.toString(), the compiler generates a StringBuilder chain internally and calls toString() on each operand automatically. The explicit toString() creates an unnecessary intermediate String object that is immediately discarded.

// Bad -- redundant toString() in concatenation
String result = "Hello " + sb.toString();

Remediation

Remove the explicit toString() call; the compiler handles the conversion automatically.

// Good -- compiler calls toString() automatically
String result = "Hello " + sb;