I have initialised an array of class objects, I'm curious about how they're allocated in memory(stack and heap), I found a piece of code from a textbook, it draws the memory allocation on the left below.
My Question is: why the memory allocation is not the one I draw on the right, in the code below, new Person[]{new Person("Simon", 20)...}, the new Person object would assign its memory address to the per[0],however, the per[0] is created in the heap when Person[] per = new Person[3] is executed.
Initialization of an array of class objects
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person[] per = new Person[]{new Person("Simon", 20), new Person("John", 21), new Person("Willy", 22)};
}
}