Hello I would like to know how many objects are created with this array?
String arr[] = {"Paul", "Steven", "Jennifer", "Bart"};
Thanks in advance!
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.
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.
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