I am confused about how the toString()works.
Sec 3.10.5 of the JLS says:
Strings computed by constant expressions (�15.28) are computed at compile time and then treated as if they were literals.
Strings computed at run time are newly created and therefore distinct.
In the above code, isn't i.toString() evaluated at run time? But the output says both strings are Equal. Why is this so? Please explain.
Don't use == to compare strings. Use .equals(...) instead.
The == operator checks if the two references you are comparing refer to the exact same String object. That's not the same as having two separate String objects that contain the same sequence of characters.
It is up to the implementation of class Integer, class String etc. if it wants to implement some caching mechanism, to that if you call toString() twice on the same Integer object it returns exactly the same String object twice. you should not write programs that count on that implementation specific behaviour.
Probably class Integer has such an optimization. I haven't looked at the source code for class Integer, but it probably caches the result of toString when you call it for the first time, something like this:
and Integer.toString(int) returns an appropriate String literal if the argument is equal to Integer.MAX_VALUE or is between -3 and 10 inclusive. Otherwise it returns a new String object
is exactly the one returned by the Integer.toString method of one argument
So should return true if i contains the value Integer.MAX_VALUE or is between -3 and 10 inclusive and false otherwise.