SyntaxPilot
Courses/Java/Lesson 14

Java · Lesson 14 of 51 · 13 min

Classes and objects, stack vs heap

queued

These are the notes for Java episode 14, the start of object-oriented programming (OOP). Last episode's marks system kept one student in three separate arrays. Today we invent a better way: a class (our own type, Student), objects made with new, fields and instance methods, and we look inside memory to see where everything lives: references on the stack, objects on the heap. Then the classic traps: aliasing, == on objects, null and NullPointerException, and arrays of objects. Every example runs as-is in the SyntaxPilot compiler, with its real output from javac 21.

The problem: one student, three places

In episode 13 a student lived in parallel arrays: names[i], marks[i], totals[i]. Parallel arrays are separate arrays where the same index describes the same thing. Only the index ties them together, so every move must be done in every array. Forget one, and the data is silently wrong:

public class Main {
    public static void main(String[] args) {
        String[] names = {"Kabir", "Diya", "Aarav"};
        int[] totals = {135, 274, 255};
        // topper first: swap student 0 and 1
        int t = totals[0];
        totals[0] = totals[1];
        totals[1] = t;
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i] + " " + totals[i]);
        }
    }
}
Kabir 274
Diya 135
Aarav 255

We swapped the totals and forgot the names, so Kabir got Diya's 274. No error, no warning. Add phone, age and city, and every swap needs six swaps. What we want is one box per student holding everything, so the box moves as a whole. Java has int, double and String, but no Student type, so we make one.

Class = blank form, object = filled form

Real-life example: the school office has one design of admission form with empty boxes (name, marks, total). The design itself is not a student.

School admission In Java
the blank form design class Student (the class: a blueprint for a new type)
each box on the form a field: a variable that belongs to every object
printing a fresh copy new Student() creates a new object
Diya's filled form one object (also called an instance of the class)

One class, as many objects as you like.

Writing a class, new and the dot

class Student {
    String name;
    int[] marks;
    int total;
}

public class Main {
    public static void main(String[] args) {
        Student diya = new Student();
        diya.name = "Diya";
        diya.marks = new int[]{95, 88, 91};
        diya.total = 274;
        System.out.println(diya.name + " " + diya.total);
    }
}
Diya 274
  • class Student { ... } sits next to Main in the same file (only one class per file may be public, and the file is named after it).
  • The fields have no values in the class: it's a blank form.
  • Student diya = new Student(); declares a variable of type Student and creates an object. Student is now a type, just like int or String.
  • The dot operator object.field means "inside this object": diya.name = "Diya"; writes a box, diya.total reads one.

Default values and printing an object

class Student {
    String name;
    int[] marks;
    int total;
}

public class Main {
    public static void main(String[] args) {
        Student diya = new Student();
        diya.name = "Diya";
        diya.total = 274;
        Student kabir = new Student();
        System.out.println(diya);
        System.out.println(kabir.name + " " + kabir.total);
        System.out.println(kabir.marks);
    }
}
Student@15db9742
null 0
null
  • Printing an object itself prints the class name, @, and a hex hash code (an ID number Java gives the object). Your number will differ. Later (episode 22, toString) we teach objects to print nicely.
  • A new object's fields are never garbage: each gets a default value.
Field type Default value
int, long, short, byte 0
double, float 0.0
char '\u0000' (the null character)
boolean false
any object type (String, arrays, Student, ...) null

null means "this reference points to no object". Note: defaults apply to fields only; local variables inside a method have no default, and using one before assigning it is a compile error (variable x might not have been initialized).

Instance methods: ask the object

A stored total field can go stale: correct a mark and forget the total, and they disagree. In class, a teacher simply asks "Diya, what's your total?" and she adds her own marks. So we put the question inside the class as a method:

class Student {
    String name;
    int[] marks;

    int total() {
        int sum = 0;
        for (int m : marks) sum += m;
        return sum;
    }

    void print() {
        System.out.println(name + " " + total());
    }
}

public class Main {
    public static void main(String[] args) {
        Student diya = new Student();
        diya.name = "Diya";
        diya.marks = new int[]{95, 88, 91};
        Student kabir = new Student();
        kabir.name = "Kabir";
        kabir.marks = new int[]{45, 38, 52};
        diya.print();
        kabir.print();
    }
}
Diya 274
Kabir 135
  • total() and print() have no static: they are instance methods. They belong to each object and work on that object's fields. diya.print() uses Diya's name and marks; kabir.print() uses Kabir's.
  • Inside the class, marks and name mean "the fields of the object this method was called on". (Next episode gives that object a name: this.)
  • Fields = what an object has; methods = what it does. Calculating the total instead of storing it means it can never be out of date.

Stack vs heap

Real-life example: a temple cloakroom.

Cloakroom Java
the small token in your pocket the variable Student diya: a reference, kept on the stack
your bag on the shelf the object made by new, kept on the heap
two tokens for the same shelf two references to one object: aliasing
an unclaimed bag is cleared away an unreachable object is freed by the garbage collector
  • The stack is the memory where each method call keeps its local variables, in a frame (one frame per call, removed when the method returns).
  • The heap is a large shared area where every object made with new lives.
  • A primitive local variable (int count = 3;) holds its value directly on the stack. An object variable holds only a reference (think: the object's address, drawn as an arrow).
STACK (main's frame)            HEAP
int count   [ 3 ]
Student a   [ o-]-----------> Student@1b6d { name = "Kabir", marks = {95, 88, 91} }
Student b   [ o-]-----------^
Student c   [ o-]-----------> Student@4554 { name = "Kabir", marks = null }

Aliasing and ==

class Student {
    String name;
    int[] marks;

    int total() {
        int sum = 0;
        for (int m : marks) sum += m;
        return sum;
    }

    void print() {
        System.out.println(name + " " + total());
    }
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student();
        a.name = "Diya";
        Student b = a;
        b.name = "Kabir";
        System.out.println(a.name);
        Student c = new Student();
        c.name = "Kabir";
        System.out.println(a == b);
        System.out.println(b == c);
    }
}
Kabir
true
false
  • Student b = a; copies the reference, not the object. a and b are two names for one object, so b.name = "Kabir" changes what a.name shows.
  • == on objects asks "is this the same object?" (same reference), not "do they look the same?". b and c both have the name Kabir but are two objects, so b == c is false. (Comparing contents is equals, episode 22; for Strings you already use s1.equals(s2).)
  • Each new always creates a brand-new object.

null and NullPointerException

A null reference is a token for an empty shelf. Using it to reach an object crashes:

class Student {
    String name;
    int[] marks;

    int total() {
        int sum = 0;
        for (int m : marks) sum += m;
        return sum;
    }

    void print() {
        System.out.println(name + " " + total());
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = null;
        s.print();
    }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Student.print()" because "<local1>" is null
    at Main.main(Main.java:19)

<local1> is Java's name for local variable number 1 (here s; args is number 0) when the class is compiled without debug names; compile with javac -g and the message says "s" instead. The fix is always: make sure the object exists (new) before you use it.

Arrays of objects

class Student {
    String name;
    int[] marks;

    int total() {
        int sum = 0;
        for (int m : marks) sum += m;
        return sum;
    }

    void print() {
        System.out.println(name + " " + total());
    }
}

public class Main {
    public static void main(String[] args) {
        Student[] cls = new Student[3];
        System.out.println(cls[0]);
        cls[0].name = "Diya";
    }
}
null
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "name" because "<local1>[0]" is null
    at Main.main(Main.java:20)

new Student[3] makes an array of 3 references, all null: three empty hooks, not three students. Create each object yourself:

class Student {
    String name;
    int[] marks;

    int total() {
        int sum = 0;
        for (int m : marks) sum += m;
        return sum;
    }

    void print() {
        System.out.println(name + " " + total());
    }
}

public class Main {
    public static void main(String[] args) {
        String[] names = {"Kabir", "Diya", "Aarav"};
        int[][] marks = {{45, 38, 52}, {95, 88, 91},
                         {78, 85, 92}};
        Student[] cls = new Student[3];
        for (int i = 0; i < cls.length; i++) {
            cls[i] = new Student();
            cls[i].name = names[i];
            cls[i].marks = marks[i];
        }
        // topper first: swap student 0 and 1
        Student tmp = cls[0];
        cls[0] = cls[1];
        cls[1] = tmp;
        for (Student s : cls) s.print();
    }
}
Diya 274
Kabir 135
Aarav 255

Now the topper swap moves whole students (two references), so a name can never again be separated from its marks. The episode-13 bug is gone for good.

Garbage collection

When no reference points to an object any more (for example a = null; b = null;), nobody can reach it. The JVM's garbage collector frees that memory automatically, at a time it chooses. You never delete objects yourself in Java (no delete/free as in C/C++).

What you just invented

  1. Parallel arrays fell out of step, so we wanted one thing per student.
  2. A class is the blank form; new prints a fresh copy; the filled copy is an object.
  3. Fields are what it has, instance methods what it does.
  4. The variable is a reference on the stack; the object lives on the heap.
  5. Copying a variable copies the arrow; == compares arrows; null is no arrow.

Common mistakes (and the real error messages)

Mistake What you see Why Fix
Student s = null; s.print(); java.lang.NullPointerException: Cannot invoke "Student.print()" because "<local1>" is null s points to no object s = new Student(); first
Student[] cls = new Student[3]; cls[0].name = "Diya"; java.lang.NullPointerException: Cannot assign field "name" because "<local1>[0]" is null the array holds 3 nulls cls[i] = new Student(); in a loop
Student b = a; to "copy" a student no error, changing b changes a copies the reference, not the object make a new object (constructors next episode)
if (a == c) to compare two students' data false even when all fields match == compares references compare fields, or equals (episode 22)
System.out.println(diya); Student@15db9742 default printing: class name + hash code print fields or call print()
swapping one parallel array no error, wrong pairs the other arrays didn't move one array of objects

Mini project: a bookshelf

Make a Book class (title, author, price) with isCheap() (price below Rs 300) and print(), an array of three books, and print only the cheap ones (this is also the episode's homework):

class Book {
    String title;
    String author;
    int price;

    boolean isCheap() {
        return price < 300;
    }

    void print() {
        System.out.println(title + " by " + author + ", Rs " + price);
    }
}

public class Main {
    public static void main(String[] args) {
        String[] titles = {"Godaan", "Wings of Fire", "The Guide"};
        String[] authors = {"Premchand", "A. P. J. Abdul Kalam", "R. K. Narayan"};
        int[] prices = {199, 350, 250};
        Book[] shelf = new Book[3];
        for (int i = 0; i < shelf.length; i++) {
            shelf[i] = new Book();
            shelf[i].title = titles[i];
            shelf[i].author = authors[i];
            shelf[i].price = prices[i];
        }
        System.out.println("Cheap books:");
        for (Book b : shelf) {
            if (b.isCheap()) b.print();
        }
    }
}
Cheap books:
Godaan by Premchand, Rs 199
The Guide by R. K. Narayan, Rs 250

Then draw its memory: shelf on the stack, pointing to an array object on the heap, whose three slots point to three Book objects, each pointing to its own Strings.

Practice

  1. Add a boolean passed() method to Student: false if any mark is below 33. Test it on Kabir {45, 38, 52} and on {45, 28, 52}.
  2. Write static Student topper(Student[] cls) that returns the student with the highest total().
  3. Predict the output, then run it:
class Point {
    int x;
    int y;
}

public class Main {
    static void move(Point p) {
        p.x = 10;
    }

    static void reset(Point p) {
        p = new Point();
    }

    public static void main(String[] args) {
        Point a = new Point();
        move(a);
        System.out.println(a.x);
        reset(a);
        System.out.println(a.x);
    }
}
Solutions
  1. java boolean passed() { for (int m : marks) { if (m < 33) return false; } return true; } Kabir {45, 38, 52} gives true; {45, 28, 52} gives false.

  2. java static Student topper(Student[] cls) { Student best = cls[0]; for (Student s : cls) { if (s.total() > best.total()) best = s; } return best; } It returns a reference to the best object, so topper(cls).print() prints Diya 274.

  3. It prints 10 and 10. move(a) receives a copy of the reference (Java is pass-by-value, episode 11), but the copy points to the same object, so p.x = 10 changes a's object. reset(a) makes its local copy p point to a new object; a itself still points to the old one, so a.x is still 10.

Quick quiz

What does this print?

Student a = new Student();
a.name = "Diya";
Student b = new Student();
b.name = "Diya";
Student c = b;
c.name = "Meera";
System.out.println(a.name + " " + b.name
    + " " + (a == b));
  • A. Diya Diya true
  • B. Diya Meera false
  • C. Meera Meera false
  • D. Diya Meera true
Answer

B. Diya Meera false. Two news make two objects, so a == b is false even with the same name. c = b makes c point to b's object, so c.name = "Meera" changes b. a is untouched.

Interview questions

  1. What is the difference between a class and an object? A class is a blueprint that defines fields and methods (a type); an object is one instance of it, created at run time with new, with its own field values.
  2. Where are objects and local variables stored in Java? Objects live on the heap. Local variables (including references) live in the method's frame on the stack; a reference holds the location of its object on the heap.
  3. What does Student b = a; do? Copies the reference: a and b refer to the same object (aliasing). No new object is created.
  4. == vs equals() for objects? == checks whether two references point to the same object; equals() is meant to compare contents (the default Object.equals is == until a class overrides it).
  5. What are the default values of fields? 0 for numbers, 0.0 for decimals, false for boolean, '\u0000' for char, null for references. Local variables get no default.
  6. What causes NullPointerException and how do you avoid it? Using a null reference to access a field or method. Create objects before use, check for null where a value may be missing, and initialise every element of an object array.
  7. What happens to an object no reference points to? It becomes unreachable and is eligible for garbage collection; the JVM frees it automatically.
  8. What does new Student[3] create? One array object with three references, all null; no Student objects.
  9. Why does printing an object show Student@15db9742? The default toString() from Object prints the class name, @, and the hash code in hex.

Glossary

Term Meaning Example
object-oriented programming (OOP) building programs from objects that hold data and the code that works on it Student objects
class a blueprint that defines a new type: its fields and methods class Student { ... }
object / instance one thing made from a class, with its own field values Diya's Student
field a variable declared in a class; every object has its own copy String name;
new creates a new object on the heap and gives back a reference to it new Student()
dot operator reaches a field or method inside an object diya.name, diya.print()
default value the value a field has before you set it 0, false, null
null a reference that points to no object Student s = null;
hash code a number Java gives an object, shown in hex when an object is printed Student@15db9742
instance method a method without static; runs on one object and uses its fields diya.total()
parallel arrays separate arrays where index i means the same thing names[i], totals[i]
primitive type a simple value type stored directly: int, double, char, boolean, ... int count = 3;
reference a value that tells Java where an object is (its address) the value inside diya
reference variable a variable of a class type; holds a reference, not the object Student diya
stack memory for method calls: each call gets a frame with its local variables main()'s frame
frame the stack space of one method call, removed when it returns
heap shared memory where all objects created with new live the Student objects
aliasing two references pointing to the same object Student b = a;
== (on objects) true only if both references point to the same object a == b
NullPointerException the crash when you use a null reference to reach a field or method s.print() with s == null
array of objects an array whose slots hold references (initially null) new Student[3]
garbage collector the part of the JVM that frees objects nothing refers to after a = null; b = null;
unreachable object an object no reference points to the old Diya object

Summary

  • Parallel arrays fall out of step; a class groups the data of one thing into one type.
  • class = blank form, object = filled form, new = a fresh copy; reach inside with the dot.
  • Fields start with default values (0, false, null); printing an object gives ClassName@hash.
  • Instance methods (no static) run on one object and use its own fields.
  • A reference variable lives on the stack; the object lives on the heap.
  • b = a copies the reference (aliasing); == compares references.
  • Using null gives NullPointerException; new Student[3] holds three nulls.
  • Objects nothing points to are freed by the garbage collector.

Next episode: Constructors, this, and constructor chaining. Making one student took four lines (new, then each field). Forget one and you get a half-filled object full of nulls. Next we invent a way to create an object complete in one step.