String.valueOf("99")
returns the same instance passed to it (since valueOf(Object obj)
returns that Object
's totString
and String
's toString
returns this
). Since both "99"
Strings are the same instance (due to String
pool), both calls to String.valueOf("99")
return the same instance.
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
On the other hand, each call to String.valueOf(99)
calls Integer.toString(99)
, which produces a new String
instance.
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}