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