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

后端 未结 9 599
独厮守ぢ
独厮守ぢ 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:28

    It is always better that you're aware of the type of argument you are trying to convert to string and also make compiler aware of the type. That simplifies the operation as well as the cycles. When you follow the append method, you are leaving the type decision to the compiler and also increasing the code lines for the compiler to do the same.

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

    The string-concatenation way creates an extra object (that then gets GCed), that is one reason why it's considered "poorer". Plus it is trickier and less readable, which as Jon Skeet points out is usually a bigger consideration.

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

    I would also use String.valueOf() method, which, in effect, uses the primitive type's Wrapper object and calls the toString() method for you:

    Example, in the String class:

    public static String valueOf(int i) {
            return Integer.toString(i, 10);
        }
    
    0 讨论(0)
  • 2021-02-06 21:36
    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

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

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

    0 讨论(0)
  • 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.)

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