When I do ""+1 I get a String - Why

java

Solution

Actually, for "" + 1 the compiler creates a String constant String with the value of "1" and puts it into the constant pool - so nothing is done at runtime.

If you have "" + x (where x is an int variable) you get the following bytecode (from the current JDK 1.6):

  0:   new     #2; //class java/lang/StringBuilder
  3:   dup
  4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
  7:   ldc     #4; //String
  9:   invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  12:  aload_0
  13:  arraylength
  14:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
  17:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
  20:  astore_1
  21:  return

So it creates a StringBuilder, appends the "" to it, then appends the int value to it, then calls toString on the StringBuilder instance.

Inside the StringBuilder.append(int) method it ultimately calls Integer.getChars (a package private method).

You can look up the source to the append and getChars in the your copy of the JDK src.zip (or src.jar).

Problem

Please understand firstly that I fully understand that Java will return a String when I use ""+int. What I'm really not sure about is what exactly is happening down at the memory aspect. How exactly is java performing this conversion. I mean this in a very indepth way, not 'auto boxing' or anything like that :) I'm hoping someone with a deeper understanding can explain what exactly is done.

Original source