Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : String a = Integer.toString(1); creates how many objects?

Tags:

java

string

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?

like image 355
Ruobo Wang Avatar asked Apr 24 '26 00:04

Ruobo Wang


1 Answers

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);
}
like image 158
PermGenError Avatar answered Apr 26 '26 12:04

PermGenError