Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects are created with an Array? [Java]

Hello I would like to know how many objects are created with this array?

String arr[] = {"Paul", "Steven", "Jennifer", "Bart"};

Thanks in advance!

like image 759
Sebastian Avatar asked May 05 '11 05:05

Sebastian


2 Answers

Nine objects are created.

Each String is TWO objects. The String reference, and the String's underlying char[]. So for 4 strings, that's 8 objects.

Then, there is the String[] itself for a total of 9.

This of course assumes the String literal has not been intern()ed yet by the JVM. If it has, then it will not create the String, but instead pull it from the intern pool, which could give you a total of 1, 3, 5, 7, or the original 9 objects created, depending on how many Strings are interned.

like image 124
corsiKa Avatar answered Sep 19 '22 16:09

corsiKa


String arr[] = {"Paul", "Steven", "Jennifer", "Bart"};
for (Object o : arr) {
   System.out.format("%d\n", o.hashCode());
}
System.out.format("%d\n", arr);

You should get 5 distinct hashCode. A strong suggestion that there now exists 5 objects in your heap.

like image 21
alphazero Avatar answered Sep 19 '22 16:09

alphazero