Add an empty string vs toString - why is it bad?

corgrath picture corgrath · Sep 2, 2010 · Viewed 8.3k times · Source

According to the tool PMD, the following is a bad practice:

String s = "" + 123; // bad 
String t = Integer.toString(456); // ok 


This is an inefficient way to convert any type to a `String`.

Why is it a bad thing to do?

Answer

Péter Török picture Péter Török · Sep 2, 2010

It is inefficient, as it involves an unneeded string concatenation, thus the creation of one or two extra String objects - although I believe the JIT can optimize it away.

To me the bigger problem is that the code is less clear. Calling toString is a standard idiom, understandable to every Java developer (hopefully :-), so you should prefer this.