Arrays are an essential component in Java programming to store and access a large number of elements of the same data type. While a standard array in Java can store primitive data types like int, boolean etc., to store objects you need to create an array of objects.
An array of objects allows you to store multiple objects of a class in one single variable. So instead of making several variables to store individual objects, you can group all objects into a single array variable.
This comprehensive guide will provide a complete overview on arrays of objects in Java with detailed examples.
Why Use Arrays of Objects in Java
Here are some prominent reasons to use object arrays in your Java programs:
-
Organize objects in one place – You can group multiple objects of a class together in a single array variable for easy access and organization.
-
Iterate through objects – Object arrays allow you to easily iterate through all the objects using a loop and access individual objects.
-
Implement algorithms/logic – Many algorithms like sorting can be easily implemented by storing objects in an array.
-
Flexible size – You can define the size dynamically based on requirement instead of creating multiple object variables.
-
Code reusability – The same array processing logic can work for any type of object arrays.
Ways to Create Array of Objects in Java
An array of objects can be created in Java in the following ways:
- Object Array Declaration – Declare the object array without memory allocation
- Object Array Instantiation – Declare array and allocate memory in one statement
- Object Array Initialization – Initialize object array elements during declaration
Let‘s look at each of these methods for object array creation in detail with examples.
1. Object Array Declaration in Java
This method first declares an array variable to store the objects. Later, memory is allocated separately using the new keyword.
Syntax:
ClassName[] arrayRefVar; //declaration
arrayRefVar = new ClassName[arraySize]; //memory allocation
Example:
//declare
Student[] students;
//allocate memory
students = new Student[5];
Here, Student is the class whose objects will be stored in the array.
First, students array is declared as a reference variable of Student type. Later, memory is allocated to store 5 Student object references.
Let‘s implement the full program:
class Student{
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
}
public class Main{
public static void main(String[] args){
//declare array
Student[] students;
//allocate memory
students = new Student[5];
//initialize array elements
students[0] = new Student(1,"John");
students[1] = new Student(2,"Amy");
//print student name of first element
System.out.println(students[0].name);
}
}
Output:
John
Here, Student class represents the entity having rollNo and name as attributes.
An object array students is declared to store multiple Student objects. Later, memory for 5 objects is allocated.
Next, array elements are initialized by creating Student objects at index 0 and 1.
Finally, name of student at 0th index is printed.
This approach of declaring and allocating memory separately makes code more readable. But requires more lines of code.
Next, let‘s see how we can combine declaration and memory allocation in one statement.
2. Object Array Instantiation in Java
We can initialize an array while declaring it by directly allocating the required memory.
This combines both declaration and instantiation in one statement for convenience.
Syntax:
ClassName[] arrayRefVar = new ClassName[arraySize];
Example:
//declare and instantiate together
Student[] students = new Student[3];
This creates students array with memory to store 3 object references of Student class.
Let‘s implement the full program of object array instantiation:
class Employee{
int id;
String name;
Employee(int id, String name){
this.id = id;
this.name = name;
}
}
public class Main{
public static void main(String[] args){
//declare & instantiate array
Employee[] employees = new Employee[3];
//initialize array
employees[0] = new Employee(1,"Rita");
employees[1] = new Employee(2,"Saima");
//print name of second employee
System.out.println(employees[1].name);
}
}
Output:
Saima
Here, Employee array is declared and memory is allocated to store 3 objects in one statement.
Later, array elements are initialized and name attribute of second employee is printed.
This approach reduces code and combines declaration and memory allocation logically in one line.
Next, let‘s initialize the array elements directly during declaration.
3. Object Array Initialization in Java
We can initialize the elements of an object array during declaration itself instead of doing it separately.
Syntax:
ClassName[] arrayRefVar = {obj1, obj2, obj3};
Here, the object array is created with specified object elements defined within curly brackets {}.
Example:
Student[] students = {new Student(1), new Student(2), new Student(3)};
This both declares as well as initializes the students array with 3 Student objects.
Let‘s use object array initialization to store details of products:
class Product{
int id;
String name;
float price;
Product(int id, String name, float price){
this.id = id;
this.name = name;
this.price = price;
}
}
public class Main{
public static void main(String[] args){
Product[] products = {
new Product(1,"Laptop",178000),
new Product(2,"Smart Watch",24000),
new Product(3,"Tablet",45000)
};
float total = 0;
for(Product product: products){
total+=product.price;
}
System.out.println(total);
}
}
Output:
247000.0
Here, products array is declared and initialized with 3 Product objects having details like id, name and price.
We iterate over the array using enhanced for loop to calculate total value of all products.
This way object array initialization simplifies code by combining declaration and initialization.
Now that you have understood the basics of array of objects creation, let‘s move on to some additional concepts related to it.
Additional Concepts on Arrays of Objects
Here are some additional things you must know about arrays of objects in Java:
-
Object arrays can store objects of any class like custom classes, String class, Integer class etc. It can even store objects of different classes in the same array (which is not possible in standard arrays).
-
The length or size of an object array must be provided during array creation only either explicitly like
new ClassName[5]or based on number of elements within{}. It cannot be modified later to resize an array. -
Default value of elements in an object array is
null. -
Arrays use zero based indexing in Java. The first element is stored at
arrayRefVar[0], second element atarrayRefVar[1]and so on. -
An object array is always stored in contiguous memory locations. Hence indexed based access to array elements is extremely fast.
Let‘s explore some common usages of object arrays in Java:
1. Store Custom Class Objects
Most commonly, object arrays are used to store instances of custom classes in application programs.
For example:
class Book {
int id;
String name;
String author;
Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
}
public class Library {
public static void main(String[] args) {
//array of Book objects
Book[] books = new Book[3];
books[0] = new Book(1, "The Alchemist", "Paulo Coelho");
books[1] = new Book(2, "Harry Potter", "J. K. Rowling ");
books[2] = new Book(3, "To Kill a Mockingbird", "Harper Lee");
}
}
Here books array stores multiple Book objects to represent a library collection. More books can be added by resizing array when needed.
2. Store Wrapper Class Objects
Wrapper classes like Integer, Character, Boolean etc. are widely used in Java programs.
Object arrays provide an ideal way to store multiple instances of wrapper classes.
Example:
Integer[] integers = {6,9,12};
Character[] vowels = {‘a‘,‘e‘,‘i‘};
3. Implement Algorithms
Many algorithms that apply same logic to multiple elements can be easily implemented using object arrays.
For example, sorting a list of objects, filtering objects based on some criteria, accessing max/min object etc.
Here is a simple program to find a Product with maximum price from Product[] array:
class Product {
int id;
String name;
float price;
//Product class code
}
public class Main{
public static void main(String[] args) {
Product[] products = {
new Product(1,"Laptop",178000f),
new Product(2,"Smart Watch",24000f),
new Product(3,"Tablet",45000f)
};
Product maxPriceProduct = getMaxPriceProduct(products);
System.out.println(maxPriceProduct.name);
}
//return product with maximum price
public static Product getMaxPriceProduct(Product[] products){
Product maxPriceProduct = products[0];
for(Product product : products) {
if(product.price > maxPriceProduct.price) {
maxPriceProduct = product;
}
}
return maxPriceProduct;
}
}
Here a simple algorithm is implemented to get max priced product from the Product array by iterating over it.
Similarly, arrays can be leveraged to implement all kinds of algorithms involving objects to reuse code.
Conclusion
Arrays are extremely useful in Java for storing and organizing multiple objects of a class together instead of creating many single variables.
We learned the following concepts related to arrays of objects in this guide:
- Storing custom class objects together makes code more organized and optimized
- An object array provides easy way to iterate through objects of a class
- Various ways like declaration, instantiation and initialization to create array of objects
- Additional aspects like default value, indexing etc. for object arrays
- Common use cases of object arrays in Java programs
I hope this comprehensive tutorial helped you learn in depth about arrays of objects in Java with practical examples. Let me know if you have any queries!


