« Previous day (Jun 7, 2005) | Main | Next day (Jun 9, 2005) »

20050608 Wednesday June 08, 2005

Converting an int to a String

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:   return
and 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.)

(2005-06-08 22:43:59.0) Permalink Comments [5]