Many objects, references and null
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · An array of students and a loop
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); }}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 staynull. topperis 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).
Example 2 · Two references, one object
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); }}Rohan: 80 Rohan: 80
What this code does
aandblead to the same object, sob.marks = 80;also changes whata.marksshows.cis a separate object made withnewand filled field by field, soc.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
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); }}Object: 35 int: 33
What this code does
addGracegot a copy of the reference, which leads to Diya's object, so the change tos.marksstays.addGraceToIntgot a copy of the number 33 and changed only its own copym.
Example 4 · A new object inside the method does not reach the caller
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); }}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.
stinmainstill 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
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"; }}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 printsnull, 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; plainjavacin a terminal may show"<local1>[1]"instead.
Example 6 · Skipping empty slots: a bus seat chart
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); }}Seat 1: Priya (21) Seat 2: free Seat 3: Arjun (19) Seat 4: free Free seats: 2
What this code does
- Here
nullhas a meaning: an empty seat. The checkseats[i] != nullcomes before any dot, so there is no NPE. seats[i].nameis used only inside theif, where the slot surely holds an object.
!= 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.
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); // PriyaIt 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