What happens in memory when you write new Student("Asha") in Java?
new allocates memory for the object on the heap, sets fields to default values, runs the constructor, and returns a reference. The variable on the stack holds only that reference.
Explain it simply
Think of booking a hall for an event. The hall (the object) is a big space in the venue complex (the heap). What you carry in your pocket is only the booking slip with the hall number (the reference on the stack). Losing the slip does not demolish the hall, but nobody can find it any more.
Steps for Student s = new Student("Asha");: the class is loaded if it is not already; memory is reserved on the heap; every field gets a default (0, false, null); the constructor body runs and sets real values; the address comes back and is stored in s.
Example
Student s1 = new Student("Asha");
Student s2 = s1; // copies the reference, not the object
s2.name = "Rahul";
System.out.println(s1.name); // prints: RahulBoth variables point to one object, so a change through s2 is visible through s1. Writing s2 = new Student("Meera") would make s2 point somewhere else and leave s1 alone.
What to say in the interview
"new allocates the object on the heap, zero-initialises the fields, runs the constructor and returns a reference, which is stored in a local variable on the stack. Assigning one reference to another copies the address, so both point to the same object."
Common mistakes
- Thinking s2 = s1 makes a copy of the object.
- Saying objects live on the stack. In Java, local references do; objects live on the heap.