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

后端 未结 9 606
独厮守ぢ
独厮守ぢ 2021-02-06 21:09

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

9条回答
  •  庸人自扰
    2021-02-06 21:43

    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.)

提交回复
热议问题