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.
In theory
The instruction
does the following: convert
ito String by callingInteger.toString(i), and concatenates this string to the empty string. This causes the creation of three String objects, and one concatenation.The instruction
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)