9

I always use String.valueOf(integer) to convert an integer to a string, but I saw someone to do it by integer + "". For example,

int i = 0;
String i0 = i + "";

So, is that a good way to convert integer to string?

Sayakiss
  • 6,878
  • 8
  • 61
  • 107

4 Answers4

13

Though it works, i + "" is kind of hack to convert int to String. The + operator on string never designed to use that way. Always use String.valueOf()

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
9

Use whatever method is more readable. String.valueOf(i) or Integer.toString(i) make your intent much clearer than i + "".

Eran
  • 387,369
  • 54
  • 702
  • 768
3

It's not only the optimization. I don't like

"" + i

because it does not express what I really want to do.

I don't want to append an integer to an (empty) string. I want to convert an integer to string:

Integer.toString(i)

Or, not my prefered, but still better than concatenation, get a string representation of an object (integer

String.valueOf(i)

N.B: For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.

Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
3

The thing there is that if you have an Integer i (non-primitive) and use i + "", you may end up with a non-null string of "null" value if i is null, while String.valueOf(...) will throw NullPointerException in this case.

In all other cases it's the same (also very similar as for the internal process that will be invoked to return the result). Given what's above, it all depends on the context that you use it for, e.x. if you plan to convert the string back to int/Integer the + case, may be more problematic.

wfranczyk
  • 420
  • 3
  • 12