Skip to lesson

Many objects, references and null

A real program has many objects: 60 students, 40 bus seats, 100 orders. You keep them in arrays of objects, pass them to methods, and sometimes have two variables pointing at the same object. Each of these works through references.

An array of objects

A class of three students needs three objects kept in one place. Student[] list = new Student[3]; makes an array of references: three slots that each start as null, and no Student objects yet.

Student[] list = new Student[3]; makes three slots that hold references. list[0] points to the object Aarav, 72 and list[1] to Priya, 91. list[2] was never filled, so it is null: list[2].name throws NullPointerException.

Example 1 · An array of students and a loop

ClassListDemo.javaJava
class Student {    String name;    int marks;}
public class ClassListDemo {    public static void main(String[] args) {        String[] names = {"Aarav", "Priya", "Kavya"};        int[] marks = {72, 91, 85};
        Student[] list = new Student[3];        for (int i = 0; i < list.length; i++) {            list[i] = new Student();            list[i].name = names[i];            list[i].marks = marks[i];        }
        Student topper = list[0];        for (int i = 0; i < list.length; i++) {            System.out.println(list[i].name + ": " + list[i].marks);            if (list[i].marks > topper.marks) {                topper = list[i];            }        }        System.out.println("Topper: " + topper.name);    }}
Output
Aarav: 72
Priya: 91
Kavya: 85
Topper: Priya

What this code does

  • The first loop puts a new object in every slot. Without list[i] = new Student(); the slots stay null.
  • topper is a reference too: it points at the best student object, so its name and marks always stay together.

Two variables, one object

You "copy" Rohan into b with Student b = a;, change b.marks, and a changes too. The line copies the reference, not the object, exactly as int[] same = marks; did in Arrays and methods (opens in a new tab).

After Student b = a; the variables a and b hold the same reference, so both arrows lead to one Student object with name = "Rohan" and marks = 80. The change b.marks = 80 is seen through a as well.

Example 2 · Two references, one object

SharedDemo.javaJava
class Student {    String name;    int marks;}
public class SharedDemo {    public static void main(String[] args) {        Student a = new Student();        a.name = "Rohan";        a.marks = 50;
        Student b = a;      // copies the reference, not the object        b.marks = 80;        System.out.println(a.name + ": " + a.marks);
        Student c = new Student();   // a real second object        c.name = a.name;        c.marks = a.marks;        c.marks = 30;        System.out.println(a.name + ": " + a.marks);    }}
Output
Rohan: 80
Rohan: 80

What this code does

  • a and b lead to the same object, so b.marks = 80; also changes what a.marks shows.
  • c is a separate object made with new and filled field by field, so c.marks = 30; leaves Rohan at 80.

A real copy needs its own new, then each field copied by hand. The Copying objects (opens in a new tab) module shows cleaner ways.

Passing an object to a method

A method adds grace marks to a Student, returns nothing, and yet main sees the change. Java still passes a copy, as in Pass-by-value (opens in a new tab); for an object, the copy is the reference, which leads to the same object.

Example 3 · Passing an object vs passing an int

PassDemo.javaJava
class Student {    String name;    int marks;}
public class PassDemo {    static void addGrace(Student s, int grace) {        s.marks = s.marks + grace;    }
    static void addGraceToInt(int m, int grace) {        m = m + grace;    }
    public static void main(String[] args) {        Student st = new Student();        st.name = "Diya";        st.marks = 33;        int plainMarks = 33;
        addGrace(st, 2);        addGraceToInt(plainMarks, 2);        System.out.println("Object: " + st.marks);        System.out.println("int: " + plainMarks);    }}
Output
Object: 35
int: 33

What this code does

  • addGrace got a copy of the reference, which leads to Diya's object, so the change to s.marks stays.
  • addGraceToInt got a copy of the number 33 and changed only its own copy m.

Example 4 · A new object inside the method does not reach the caller

ReassignDemo.javaJava
class Student {    String name;    int marks;}
public class ReassignDemo {    static void reset(Student s) {        s = new Student();        s.name = "Nobody";        s.marks = 0;    }
    public static void main(String[] args) {        Student st = new Student();        st.name = "Arjun";        st.marks = 64;        reset(st);        System.out.println(st.name + ": " + st.marks);    }}
Output
Arjun: 64

What this code does

  • s = new Student(); changes only the method's copy of the reference; it now leads to a brand-new object.
  • The fields set after that belong to the new object. st in main still leads to Arjun, untouched.

So a method can change the fields of an object it is given, but it cannot make the caller's variable point at a different object. To hand back a new object, return it.

null and NullPointerException

Slot list[1] was never filled, and list[1].name = "Rohan"; stops the program. null means no object, and using the dot on it throws a NullPointerException (NPE) when the line runs, as in Common exceptions (opens in a new tab).

Example 5 · Using a null reference

NullDemo.javaJava
class Student {    String name;    int marks;}
public class NullDemo {    public static void main(String[] args) {        Student[] list = new Student[3];        list[0] = new Student();        list[0].name = "Kavya";        System.out.println(list[0].name);        System.out.println(list[1]);        list[1].name = "Rohan";    }}
Sample output
Kavya
null
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "name" because "list[1]" is null
	at NullDemo.main(NullDemo.java:13)

What this code does

  • Only slot 0 got an object. Printing list[1] just prints null, but the dot on line 13 has no object to reach, so the program stops.
  • The message names list[1] and the line. Fix: list[1] = new Student(); before line 13. IDEs show the name; plain javac in a terminal may show "<local1>[1]" instead.

Example 6 · Skipping empty slots: a bus seat chart

BusDemo.javaJava
class Passenger {    String name;    int age;}
public class BusDemo {    public static void main(String[] args) {        Passenger[] seats = new Passenger[4];        seats[0] = new Passenger();        seats[0].name = "Priya";        seats[0].age = 21;        seats[2] = new Passenger();        seats[2].name = "Arjun";        seats[2].age = 19;
        int free = 0;        for (int i = 0; i < seats.length; i++) {            if (seats[i] != null) {                System.out.println("Seat " + (i + 1) + ": " + seats[i].name + " (" + seats[i].age + ")");            } else {                System.out.println("Seat " + (i + 1) + ": free");                free++;            }        }        System.out.println("Free seats: " + free);    }}
Output
Seat 1: Priya (21)
Seat 2: free
Seat 3: Arjun (19)
Seat 4: free
Free seats: 2

What this code does

  • Here null has a meaning: an empty seat. The check seats[i] != null comes before any dot, so there is no NPE.
  • seats[i].name is used only inside the if, where the slot surely holds an object.
Checking != null is right when "no object" is a normal case, like an empty seat. When an object should always exist, create it instead of hiding the bug with a check.

What happens to objects nobody uses

After a = b; nothing points at the Aarav object any more. The garbage collector, a part of the JVM, frees objects that no reference can reach.

Java
Student a = new Student();a.name = "Aarav";Student b = new Student();b.name = "Priya";
a = b;                        // nothing points at the Aarav object nowSystem.out.println(a.name);   // Priya

It runs on its own, at a time the JVM chooses, so you cannot predict when the memory comes back. Java has no delete: you just stop pointing at an object.

Next step

Check your understanding

12 quick questions