Array of Objects
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
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);
}
}
}Before: null
Navika: 82
Srihitha: 95
Advitha: 88How it works
- Lines 2 to 10 define a small
Studenttype with a name and marks. Classes and constructors (Student(...)) are covered properly in Level 2. - Line 13:
new Student[3]creates an array of 3 references, allnull. NoStudentexists yet, as line 14 shows. - Lines 15 to 17 create three
Studentobjects withnewand store a reference to each. - The for-each loop reads each object's fields with
s.nameands.marks.
Try it yourself: comment out line 17 and run it. What happens in the loop, and why?
Shorter: Create and Fill Together
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);
}
}
}Berth 23: Navika Anamaneni
Berth 24: Advitha AnamaneniThe NullPointerException Trap
Reading a field of a slot that is still null crashes:
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "s" is nullJava'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
- Easy: Add a fourth student and print the average marks of all four.
- Harder: Print the name of the student with the highest marks, using an index-based loop over the array of objects.
Key Takeaways
Was this tutorial helpful?