The difference between Long.toString (i) vs i + ""

we often come across a scenario in which we need to pass a string representation of a primitive, and most often we do not use

WrapperClass.toString() ; 

and sometimes we usually write

  i + ""; 

if we check the toString implementation of any wrapper class, it creates a new String object every time we call it. and the same is true for primitive + "" (since Concatenation will create a new String object at runtime)

So, is there any difference between the two, or are they just alternative ways of converting the primitive to a String object;

+4
source share
3 answers

Good intentions.

By writing i + ""; , you may leave it in your future supporting code (which can be very useful to you) to figure out what will happen with this output.

WrapperClass.toString(); is more explicit and, although more detailed, his intentions are more clear. Also, weak typing is not what you usually see in Java, so I suggest you write idiomatic Java code.

After compilation, the emitted bytecode is likely to be the same or similar. After teasing and at runtime, you can expect the differences to be effectively nullified.

So in the end, this is a style issue, although I would suggest using a more detailed version of your code.

+5
source

Personally, I like String.valueOf(i) :

  • You can use it with all types (not even primitive ones).
  • It is not valid (it is assumed that you are satisfied with the string value "null" when converting a null value)
  • It expresses your intention much better than "" + i - this code expresses the concatenation of strings, which is not at all what you are doing.
+7
source

Functionally, they are the same. The difference is that i + ""; It mainly uses a side effect to archive its purpose, which may make it difficult for beginners to understand.

+3
source

All Articles