Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    Objects in Memory

    Objects always live on the heap. A variable of a class type (Student priya) holds a reference — the address card

    Chapter 4 of 107 min readOften asked in interviews

    The Plain Picture#

    The house (object) is built somewhere in a big city (the heap). You don't carry the house around — you carry a card with its address. You can photocopy the card and give it to a friend: now two cards point to one house. If your friend repaints the house, you'll see it too. And a card can be blank — pointing to no house at all.

    The Real Names#

    • Objects always live on the heap. A variable of a class type (Student priya) holds a reference — the address card (How Computers Work Ch 7) — not the object itself.

    • Local variables (including references) live in the method's stack frame (Operating Systems Ch 6).

    • null is the blank card: a reference to no object.

    • Using a null reference as if it pointed somewhere throws a NullPointerException (NPE) — the most common runtime error in Java.

    Under the Hood#

    Stack and heap together#

    Java
    public static void main(String[] args) {
        int count = 2;
        Student priya = new Student("Priya", 200);
        Student same = priya;
    }
            STACK (main's frame)                         HEAP
      ┌──────────────────────────┐
      │ count = 2                │   (a primitive: the value itself is in the frame)
      │ priya = ref ─────────────┼──────┐         ┌──────────────────────┐
      │ same  = ref ─────────────┼──────┴───────▶ │ Student              │
      └──────────────────────────┘                │   name  = ref ───────┼──▶ String "Priya"
                                                  │   score = 200        │
                                                  └──────────────────────┘

    Notice three things: the primitive count sits directly in the frame; priya and same are two references to one object (aliasing, exactly like arrays in Java Basics Ch 8); and even the name field is itself a reference, to a separate String object.

    Java
    Student same = priya;
    
    same.score = 0;
    
    System.out.println(priya.score); // 0   ← one object, two names

    Pass-by-value, with objects — the full picture#

    Java Basics Ch 7 said Java always copies the value in the variable. With objects, that value is the reference. So a method can change the object the reference points to, but can't change which object the caller's variable points to:

    Java
    static void rename(Student s) {
        s.name = "Changed";
    } // follows the copied card to the SAME house
    
    static void replace(Student s) {
        s = new Student("New", 999);
    } // points ITS OWN card at a new house
    
    rename(priya);
    
    System.out.println(priya.name); // Changed
    
    replace(priya);
    
    System.out.println(priya.name + " " + priya.score); // Changed 0   ← unaffected!
      during replace(priya):
    
      main frame:     priya ──────────────▶  [Student "Changed", 0]
      replace frame:  s     ──X──(was)──▶    (same object)
                      s     ──────────────▶  [Student "New", 999]   ← only replace's copy moved

    If Java were pass-by-reference, replace would have changed priya in main. It didn't — that's the proof.

    NullPointerException#

    Java
    Student nobody = null;
    
    System.out.println(nobody.name);
    Output
    Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "nobody" is null
    	at Npe.main(Npe.java:5)

    Since Java 14, the message names exactly which reference was null ("helpful NullPointerExceptions"). Read it — it tells you where to look. Typical causes: a field never initialised, a method returning null for "not found", a map lookup for a missing key (Collections, From the Inside).

    Defences: initialise fields in constructors; check if (x != null) where null is a legitimate value; return empty collections instead of null; and Optional for "maybe no value" results (Modern Java).

    Garbage collection — when does an object die?#

    An object can be freed once nothing refers to it any more — no local variable, field, array element or static field anywhere can reach it. The garbage collector (Operating Systems Ch 6) finds such objects and reclaims their memory; you never free memory by hand in Java.

    Java
    Student temp = new Student("Temp", 1);
    
    temp = null; // the "Temp" object is now unreachable → eligible for garbage collection

    When the GC actually runs is up to the JVM. How it works inside — generations, G1, ZGC, pauses — is in Inside the JVM.

    Gotchas

    • "Changing a copy" often isn't a copy. Student b = a; copies the reference, not the object.

    • A method can mutate the objects you pass in. When you don't want that, pass a copy or use immutable objects (Ch 5).

    • Memory leaks are still possible: objects stay alive as long as something — often a forgotten static list or cache — still refers to them (Operating Systems Ch 6).

    Check yourself

    5 questions
    1

    Where do objects live, and what does a variable of a class type actually hold?

    Show answer

    On the heap; the variable holds a reference (address) to it.

    2

    After Student b = a; b.score = 5;, what is a.score? Why?

    Show answer

    5 — a and b refer to the same object.

    3

    Explain why replace(priya) above doesn't change priya in main.

    Show answer

    The method received a copy of the reference; reassigning that copy points only the method's parameter at a new object.

    4

    What causes a NullPointerException? Name two ways to avoid them.

    Show answer

    Using a null reference to access a field or method. Initialise fields; check for null; return empty collections or Optional instead of null.

    5

    When can an object be garbage collected?

    Show answer

    When nothing reachable in the program still refers to it.