To expand on Kev’s post,
public class Demo
{
public void printInt(int i)
{
System.out.println("" + i);
}
}
produces bytecode (as disassembled by javap -c)
public class Demo extends java.lang.Object{
public Demo();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public void printInt(int);
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: new #3; //class java/lang/StringBuilder
6: dup
7: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V
10: ldc #5; //String
12: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: iload_1
16: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
19: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25: return
}
Or, to rephrase that as Java for those who don’t read bytecode, it is translated to
public class Demo
{
public void printInt(int i)
{
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
System.out.println(sb.toString());
}
}
That was compiled with 1.6: pre-1.5 it would indeed use StringBuffer rather than StringBuilder, which was even slower.
kingaschi, in Sun’s implementation the String.valueOf(primitive) methods call the Primitive.toString(primitive) methods. (Well, to be precise, String.valueOf(int) calls Integer.toString(int, int)). It’s possible that third party implementations have it the other way round. In nearly every circumstance which you choose is a matter of taste.