Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I parse an integer to string in Java, when not necessary? [duplicate]

I want to append an integer to a string. Is there a difference between doing:

String str = "Number: " + myInt;

and

String str = "Number: " + Integer.toString(myInt);

In other words, should I bother using the Integer.toString() method, when not necessary?

Edit: I am not wondering "How to convert an integer to string", but "if I am required to use a certain method, to convert".

like image 261
Victor2748 Avatar asked Mar 15 '23 03:03

Victor2748


1 Answers

There's no difference. The compiler (Oracle JVM 1.8) transform both snippets to

(new StringBuilder()).append("Number: ").append(myInt).toString();

Personally, I wouldn't use Integer.toString() as it adds noise to the code, and that doesn't provide clarity nor readability.

Edit

I made a mistake on the original answer and described that there would be a minor difference (see the answer history if you want!)

like image 165
Augusto Avatar answered Mar 18 '23 05:03

Augusto