Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'integer + ""' a good way to convert a integer to string in Java? [duplicate]

Tags:

java

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?

like image 631
Sayakiss Avatar asked Oct 14 '15 08:10

Sayakiss


4 Answers

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()

like image 69
Suresh Atta Avatar answered Nov 09 '22 05:11

Suresh Atta


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

like image 29
Eran Avatar answered Nov 09 '22 03:11

Eran


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.

like image 3
Sakib Ahammed Avatar answered Nov 09 '22 03:11

Sakib Ahammed


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.

like image 3
wfranczyk Avatar answered Nov 09 '22 04:11

wfranczyk