Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using int + "" bad for converting Java int's to Strings?

Tags:

java

string

int

So our computer science teacher taught us how to convert ints to Strings by doing this:

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

I guess he taught it to us this way since this was relatively basic computer science (high school class, mind you), but I was wondering if this was in some way "bad" when compared to:

int i=0;
String s = Integer.toString(i);

Is it more costly? Poor habit? Thanks in advance.

like image 215
John L. Avatar asked Nov 30 '22 16:11

John L.


2 Answers

In theory

The instruction

String s = i + "";

does the following: convert i to String by calling Integer.toString(i), and concatenates this string to the empty string. This causes the creation of three String objects, and one concatenation.

The instruction

String s = Integer.toString(i);

does the conversion, and only the conversion.

In practice

Most JIT compilers are able to optimise the first statement to the second one. I wouldn't be surprised if this optimisation is done even before (by the javac compiler, at compilation of your Java source to bytecode)

like image 131
Vivien Barousse Avatar answered Dec 05 '22 02:12

Vivien Barousse


i+""

is equivalent to

new StringBuilder().append(i).append("").toString();

so yes it is less efficient, but unless you are doing that in a loop or such you probably won't notice it.

[edited: from comments by StriplingWarrior-thanks]

like image 31
MeBigFatGuy Avatar answered Dec 05 '22 03:12

MeBigFatGuy