Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What happens in memory when you write new Student("Asha") in Java?

SHORT ANSWER

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

java
Student s1 = new Student("Asha");
Student s2 = s1;          // copies the reference, not the object
s2.name = "Rahul";
System.out.println(s1.name);  // prints: Rahul

Both 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.

#memory#java#objects

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.