Wednesday June 08, 2005 I came across this tip in a blog referenced from Eric's linkblog.
The author mentions that you can convert from an int to a String like this:
int one = 1; String str = one + "";And he calls that cute!
I disagree - I think that's ugly (and as he points out it's less efficient).
There's a clean way to do this, not listed in his blog:
int one = 1; String str = Integer.toString(one);Nice efficient bytecode too:
0: iconst_1 1: istore_1 2: iload_1 3: invokestatic #2; //Method java/lang/Integer.toString:(I)Ljava/lang/String; 6: astore_2 7: returnand there are variations of the method which lets you convert using another base - so you can convert to hex using
Integer.toString(one, 16) for example.
(String.valueOf(int) will turn around and call the above method by the way.)
-Alexis
Posted by Alexis MP on June 09, 2005 at 01:30 AM PDT #
String text = foo.toString();
but that doesn't work, of course. AutoBoxing allows to write somehow similar code: String fooStr = ((Integer)foo).toString(); Well... that's neither elegant nor efficient (if foo is outside the cached range of values).
I think this is a bit of an oversight in the Java language design, the same with arrays, where you can call array.toString, array.length, but not array.copy... Just more inconsistencies to remember...
On weirdness with primitives and Strings If you're a new dev and find
boolean Boolean.getBoolean(String)
expect the unexpected...
Posted by murphee on June 09, 2005 at 03:09 AM PDT #
Posted by Tom on June 09, 2005 at 05:02 AM PDT #
I actually have traditionally used Integer.toString(intValue). However, when I was witing that thing I looked at the bytecode of the (intValue + "") conversion, noticed it used String.valueOf() and wrote it that way.
I don't actually see a lot of difference between the two.
Re Tom's comment: The Eclipse 1.4 compiler will actually generate better bytecode for the following: String str = 1 + ""; (it won't create String buffers etc).
Posted by Nick Lothian on June 09, 2005 at 04:55 PM PDT #
Posted by Tor Norbye on June 10, 2005 at 03:19 PM PDT #