Cute way to convert an int to a String

I picked up a nice little tip for easy conversion between an int and a String. Previously I'd always done something like


int one = 1;
String str = String.valueOf(one);

The alternative is


int one = 1;
String str = one + "";

From the bytecode point of view it isn't quite as efficient:


   L0 (0)
    ICONST_1
    ISTORE 1: one
   L1 (3)
    ILOAD 1: one
    INVOKESTATIC String.valueOf(int) : String
    ASTORE 2: str
   L2 (7)
    RETURN
   L3 (9)

vs


   L0 (0)
    ICONST_1
    ISTORE 1: one
   L1 (3)
    NEW StringBuffer
    DUP
    ILOAD 1: one
    INVOKESTATIC String.valueOf(int) : String
    INVOKESPECIAL StringBuffer.(String) : void
    INVOKEVIRTUAL StringBuffer.toString() : String
    ASTORE 2: str
   L2 (11)
    RETURN
   L3 (13)

All the same, I'd never thought of using autoconversion to convert to a string like that before. (note this doesn't rely on JDK 1.5 autoboxing)

Leave a Reply

Your email address will not be published. Required fields are marked *