Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Long.toString(i) vs i + ""

Tags:

java

string

we often come across a scenario where in we need to pass a String representation of a primitive and More often then not we use

  WrapperClass.toString() ;

and sometimes we usually write

  i + "";

if we check to toString implementation of any wrapper class it creates a new String object every time we call it. and same is also true for primitive + "" (as Concatenation during runtime will create new String Object)

So is there any difference between them or they are just an alternative ways to convert a primitive to a String object;

like image 716
dpsdce Avatar asked Dec 07 '22 18:12

dpsdce


1 Answers

Personally I like String.valueOf(i):

  • You can use it with all types (even non-primitives)
  • It's null-safe (assuming you're happy with a string value of "null" when converting a value of null)
  • It expresses your intention far better than "" + i - that code expresses string concatenation, which isn't what you're after at all.
like image 175
Jon Skeet Avatar answered Dec 20 '22 19:12

Jon Skeet