Originally posted by Javier Sanchez Cerrillo:
. But when you call String.toString() the Java Virtual Machine looks for references identical already on the stack for optimization.
Sorry, no, this explanation is quite incorrect. The JVM does nothing special. It's simply how the implementation of java.lang.String.toString() is written:
No magic about it. Now, as to your next point:
The same happens if you try:
String j = "Javier";
String j2 = "Javier";
Again, this explanation is not right at all. It is simply not true that "the Java Virtual Machine looks for references identical already on the stack for optimization", under any circumstances, ever. The reason j and j2 are the same is because during class loading, identical literals are resolved to a single String instance. Nothing to do with the stack, nor with "looking" or "optimization" -- just how classes are loaded.