So our computer science teacher taught us how to convert int
s to String
s 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.
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.
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)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With