I have seen statements that says :
String a = new String("1");
creates 2 objects, both on heap, one is referenced by a, one is ref-ed from String literal pool
but, how about:
String a = Integer.toString(1);
will it create 2 objects or 1? I think it creates 2, am I correct?
Check the source of Integer#toString(int). It returns a new String object.
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(0, size, buf);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With