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

后端 未结 9 589
独厮守ぢ
独厮守ぢ 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()?

    0 讨论(0)
  • 2021-02-06 21:46

    There's a third one - String.valueOf(..) (which calls Wrapper.toString(..)

    Actually the compiler adds Wrapper.toString(..) in these places, so it's the same in terms of bytecode. But ""+x is uglier.

    0 讨论(0)
  • 2021-02-06 21:48

    Appending a double quote is a bad way of doing it especially for readability. I would consider using some of the Apache util classes for conversion or writing your own utility methods for doing this type of stuff.

    0 讨论(0)
提交回复
热议问题