In Java, an array of objects is a special type of array that stores references to objects rather than primitive values. Each element in the array is a reference to an object of a particular class. This feature is commonly used to manage multiple objects of the same type.
Key Points about Array of Objects
- Stores Object References: Each element in the array is a reference to an object.
- Null by Default: Elements are initialized to null until explicitly assigned.
- Object Initialization Required: Each object in the array must be created and initialized individually.
- Class Specific: All elements must be objects of the same class or a subclass thereof.
Declaring an Array of Objects
- Declare an array reference for the class.
- Initialize the array and assign objects to its elements.
Syntax:
ClassName[] arrayName = new ClassName[size];
Example 1: Array of Objects
Creating and Accessing an Array of Objects
class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println(“Name: ” + name + “, Age: ” + age);
}
}
public class Main {
public static void main(String[] args) {
// Create an array of Student objects
Student[] students = new Student[3];
// Initialize each element with a Student object
students[0] = new Student(“Alice”, 20);
students[1] = new Student(“Bob”, 22);
students[2] = new Student(“Charlie”, 19);
// Access and display each student’s information
for (Student student : students) {
student.displayInfo();
}
}
}
Output:
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: Charlie, Age: 19
Example 2: Array of Objects with User Input
Dynamic Object Initialization Using Loops
import java.util.Scanner;
class Product {
String name;
double price;
// Constructor
Product(String name, double price) {
this.name = name;
this.price = price;
}
void displayProduct() {
System.out.println(“Product Name: ” + name + “, Price: $” + price);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Create an array of Product objects
Product[] products = new Product[2];
// Populate the array with user input
for (int i = 0; i < products.length; i++) {
System.out.print(“Enter product name: “);
String name = scanner.nextLine();
System.out.print(“Enter product price: “);
double price = scanner.nextDouble();
scanner.nextLine(); // Consume the newline
products[i] = new Product(name, price);
}
// Display the products
System.out.println(“Product Details:”);
for (Product product : products) {
product.displayProduct();
}
scanner.close();
}
}
Output:
Enter product name: Laptop
Enter product price: 800.5
Enter product name: Smartphone
Enter product price: 500.75
Product Details:
Product Name: Laptop, Price: $800.5
Product Name: Smartphone, Price: $500.75
Example 3: Array of Objects in a 2D Structure
You can create a 2D array of objects to represent more complex data.
class Book {
String title;
String author;
// Constructor
Book(String title, String author) {
this.title = title;
this.author = author;
}
void displayBook() {
System.out.println(“Title: ” + title + “, Author: ” + author);
}
}
public class Main {
public static void main(String[] args) {
// Create a 2D array of Book objects
Book[][] library = new Book[2][2];
// Initialize the 2D array
library[0][0] = new Book(“Java Programming”, “Author A”);
library[0][1] = new Book(“Python Basics”, “Author B”);
library[1][0] = new Book(“Web Development”, “Author C”);
library[1][1] = new Book(“Data Structures”, “Author D”);
// Display the books
System.out.println(“Library Books:”);
for (int i = 0; i < library.length; i++) {
for (int j = 0; j < library[i].length; j++) {
library[i][j].displayBook();
}
}
}
}
Output:
Library Books:
Title: Java Programming, Author: Author A
Title: Python Basics, Author: Author B
Title: Web Development, Author: Author C
Title: Data Structures, Author: Author D
Best Practices for Array of Objects
- Avoid NullPointerException:
- Initialize objects before accessing them.
- Use null checks when dealing with partially initialized arrays.
if (array[i] != null) {
array[i].displayInfo();
}
- Use Enhanced for Loops:
- For simpler traversal, use the enhanced for loop.
for (ClassName obj : arrayName) {
obj.methodName();
}
- Design Object-Oriented:
- Use encapsulation (getters and setters) for better control over object data.
- Memory Efficiency:
- Allocate memory only when needed to optimize resource usage.
Applications
- Management Systems: For handling students, employees, products, etc.
- Data Storage: To store and manipulate a collection of objects of a specific type.
- Grid-Based Applications: Such as games or 2D maps with complex object interactions.
Conclusion
An array of objects in Java is a powerful construct for managing and manipulating collections of objects efficiently. By understanding its initialization, traversal, and best practices, you can create robust and scalable applications that handle structured data elegantly.