Rob Prime wrote:Still, Integer.parseInt is more efficient because it doesn't create a new Integer object, which Integer.valueOf will do.
The method Integer.valueOf(int i) uses a cache if i is between -128 and 127, so it doesn't create a new object if the value is between those boundaries. So I thought you were incorrect when you said that Integer.valueOf(String s) always creates a new object. I checked out the source code of class Integer (available in
src.zip in the JDK directory), and to my surprise saw this:
So indeed, the method that takes a String always creates a new Integer object - you were right.
I wonder why this is - why did the people who programmed the JDK not write it like this?
Strange! But you know, the standard
Java library isn't perfect...