Empty String Concatenation for Type Conversion

ID

java.string_concat_for_conversion

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, code-style

Description

Reports the use of "" + x or x + "" to convert a value to a String. While functionally correct, this idiom is less readable than the explicit conversion methods and creates an unnecessary intermediate StringBuilder.

Rationale

Concatenating an empty string with a value is a common shortcut for converting the value to a String. However, it obscures the intent of the code. The reader has to recognize the pattern rather than seeing an explicit conversion call. Additionally, the compiler generates a StringBuilder to perform the concatenation, which is wasteful when the goal is simply to obtain a string representation.

// Bad -- empty-string concatenation for conversion
String s = "" + count;
String t = value + "";

Remediation

Use String.valueOf(x) or the appropriate wrapper type’s toString() method for explicit, readable conversion.

// Good -- explicit conversion
String s = String.valueOf(count);
String t = Integer.toString(value);