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

后端 未结 9 736
独厮守ぢ
独厮守ぢ 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 think the answer really depends on what you're trying to convert, and for what purpose, but in general, I'm not a big fan of doing naked conversions, because in most instances, conversions to a string are for logging, or other human readability purposes.

    MessageFormat.format("The value of XYZ object is {0}", object);
    

    This gives good readability, fine grained control over the formatting of the output, and importantly, it can be internationalized by replacing the string with a message bundle reference.

    Need I mention this also avoids the possible NPE problem of calling object.toString()?

提交回复
热议问题