What is the better approach to convert primitive data type into String

I can convert an integer into string using

String s = "" + 4; // correct, but poor style
or
String u = Integer.toString(4); // this is good

I can convert a double into string using

String s = "" + 4.5; // correct, but poor style
or
String u = Double.toString(4.5); // this is good

I can use String s = "" + dataapproach to convert either an int or double into String. While If I wants to use the other approach using toString() I have to use the Wrapper class of each data type. Then why in some books it is mentioned that the first approach is poor one while the second one is the better. Which one is the better approach and why?


Solution 1:

I would use

String.valueOf(...)

You can use the same code for all types, but without the hideous and pointless string concatenation.

Note that it also says exactly what you want - the string value corresponding to the given primitive value. Compare that with the "" + x approach, where you're applying string concatenation even though you have no intention of concatenating anything, and the empty string is irrelevant to you. (It's probably more expensive, but it's the readability hit that I mind more than performance.)

Solution 2:

How about String.valueOf()? It's overridden overloaded for all primitive types and delegates to toString() for reference types.

Solution 3:

String s = "" + 4;

Is compiled to this code:

StringBuffer _$_helper = new StringBuffer("");
_$_helper.append(Integer.toString(4));
String s = _$_helper.toString();

Obviously that is pretty wastefull. Keep in mind that behind the scene the compiler is always using StringBuffers if you use + in asociation with String's