Array of Objects

Naveen AnamaneniUpdated · 4 min read

A school register is a list of students, and each student has a name, a roll number and marks. You could keep three separate arrays, but they easily get out of step. Better: make a Student type that holds all three, and keep one array of Student objects. There's one surprise, though: a new array of objects starts out empty, with no students in it at all.

A New Array Holds References, Not Objects

The array holds references; each object must be created
Register.java▶ Try it
public class Register {
    static class Student {
        String name;
        int marks;
 
        Student(String name, int marks) {
            this.name = name;
            this.marks = marks;
        }
    }
 
    public static void main(String[] args) {
        Student[] students = new Student[3];
        System.out.println("Before: " + students[0]);
        students[0] = new Student("Navika", 82);
        students[1] = new Student("Srihitha", 95);
        students[2] = new Student("Advitha", 88);
        for (Student s : students) {
            System.out.println(s.name + ": " + s.marks);
        }
    }
}
Output
Before: null
Navika: 82
Srihitha: 95
Advitha: 88

How it works

  1. Lines 2 to 10 define a small Student type with a name and marks. Classes and constructors (Student(...)) are covered properly in Level 2.
  2. Line 13: new Student[3] creates an array of 3 references, all null. No Student exists yet, as line 14 shows.
  3. Lines 15 to 17 create three Student objects with new and store a reference to each.
  4. The for-each loop reads each object's fields with s.name and s.marks.

Try it yourself: comment out line 17 and run it. What happens in the loop, and why?

Shorter: Create and Fill Together

Coach.java▶ Try it
public class Coach {
    static class Passenger {
        String name;
        int berth;
 
        Passenger(String name, int berth) {
            this.name = name;
            this.berth = berth;
        }
    }
 
    public static void main(String[] args) {
        Passenger[] list = {
            new Passenger("Navika Anamaneni", 23),
            new Passenger("Advitha Anamaneni", 24)
        };
        for (Passenger p : list) {
            System.out.println("Berth " + p.berth + ": " + p.name);
        }
    }
}
Output
Berth 23: Navika Anamaneni
Berth 24: Advitha Anamaneni

The NullPointerException Trap

Reading a field of a slot that is still null crashes:

Terminal output
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "s" is null

Java's message names the exact field and variable, which makes it quick to find. Fill every slot before reading it, or check if (s != null) when some slots may stay empty.

Common Mistakes

Expecting new Student[3] to create three students. It creates three empty slots.

Copying references and expecting copies of objects. students[1] = students[0]; makes both slots point to the same object; changing one changes "both".

Printing an object directly. println(students[0]) prints something like Register$Student@1b6d3586 until the class defines toString() (see "toString() Method in Java").

Practice

  1. Easy: Add a fourth student and print the average marks of all four.
  2. Harder: Print the name of the student with the highest marks, using an index-based loop over the array of objects.

Quick check: Array of objects

4 questions
1What does new Student[3] contain right after creation?
2What happens when you read students[2].name while students[2] is null?
3After students[1] = students[0];, how many Student objects are referenced by those two slots?
4What's a better choice when you don't know how many objects you'll need?

Key Takeaways

Was this tutorial helpful?

Lesson 73 of 482