0

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)};
        }
    }
  1. Left(TextBook)

  2. My Thought

1 Answer 1

1

why the memory allocation is not the one I draw on the right,

It is on the right, but if you were to use the value

per

or

per[0]

that reference would be brought onto the stack.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Peter,thank you of your reply, this is the entire code I got on the textbook, which means I didn't use the value of per[0] to do other things, but the author drew that left image made me really confusing...as you see, what I understand is the image I drew on the right, i really don't quite know which one should I go for...
@Ruizhi an array isn't very useful unless you access it's elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.