Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many Java objects are generated by this - new String("abcd")

String s = new String("abcd");
like image 871
Will Tu Avatar asked Sep 09 '26 02:09

Will Tu


1 Answers

There's one string in the intern pool, which will be reused every time you run the code.

Then there's the extra string which is constructed each time you run that line. So for example:

for (int i = 0; i < 10; i++) {
    String s = new String("abcd");
}

will end up with 11 strings with the contents "abcd" in memory - the interned one and 10 copies.

like image 122
Jon Skeet Avatar answered Sep 10 '26 17:09

Jon Skeet