Clean • Professional
In Java, you can create arrays not only for primitive types (like int, double) but also for objects, including user-defined classes. Arrays of objects are widely used to store multiple instances of a class in a single container, making data management efficient.
Student objects.Employee objects.Product objects.
Student[] students; // Declares an array of Student objects
students = new Student[3]; // Array can hold 3 Student references
At this point, students[0], students[1], students[2] are null because no objects have been created yet.
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
}
public class ArrayOfObjectsExample {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student(1, "Aman");
students[1] = new Student(2, "Neha");
students[2] = new Student(3, "Ravi");
for (Student s : students) {
s.display();
}
}
}
Output:
1 Aman
2 Neha
3 Ravi
NullPointerException.array.length to get the number of object references.Student[][] classes = new Student[2][3];
for (Student s : students) {
s.display();
}
You can store subclass objects in a superclass array:
class Animal { void sound() { System.out.println("Some sound"); } }
class Dog extends Animal { void sound() { System.out.println("Woof"); } }
class Cat extends Animal { void sound() { System.out.println("Meow"); } }
public class PolymorphismArrayExample {
public static void main(String[] args) {
Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();
for (Animal a : animals) {
a.sound(); // Runtime polymorphism
}
}
}
Output:
Woof
Meow
This demonstrates runtime polymorphism using arrays of objects.
| Operation | Example |
|---|---|
| Access object fields | students[0].name |
| Invoke methods | students[1].display() |
| Iterate array | for(Student s : students) { s.display(); } |
| Sorting objects | Use Arrays.sort() with Comparable/Comparator |
| Copying object references | Use loops or System.arraycopy() |