array-of-objects-in-java-how-to-create-initialize-and-use

Array Of Objects In Java: How To Create, Initialize And Use

In this Java Tutorial, you can Learn to Create, Initialize, Sort the Array of Objects in Java with Complete Code Examples:

What is an Array of Objects?

As we all know, the Java programming language is all about objects as it is an object-oriented programming language.

If you want to store a single object in your program, then you can do so with the help of a variable of type object. But when you are dealing with numerous objects, then it is advisable to use an array of objects.

Java is capable of storing objects as elements of the array along with other primitive and custom data types. Note that when you say ‘array of objects’, it is not the object itself that is stored in the array but the references of the object.

In this tutorial, you will get acquainted with the creation, initialization, sorting as well as examples of the array of objects in Java.

What You Will Learn: [hide]

  • How To Create An Array Of Objects In Java?
    • Initialize Array Of Objects
    • Example Program For An Array Of Objects In Java
    • How To Sort An Array Of Objects In Java?
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

How To Create An Array Of Objects In Java?

An array of objects is created using the ‘Object’ class.

The following statement creates an Array of Objects.

Class_name [] objArray;

Alternatively, you can also declare an Array of Objects as shown below:

Class_nameobjArray[];

Both the above declarations imply that objArray is an array of objects.

So, if you have a class ‘Employee’ then you can create an array of Employee objects as given below:

Employee[] empObjects; 
OR
Employee empObjects[];

The declarations of the array of objects above will need to be instantiated using ‘new’ before being used in the program.

You can declare and instantiate the array of objects as shown below:

Employee[] empObjects = new Employee[2];

Note that once an array of objects is instantiated like above, the individual elements of the array of objects need to be created using new.

The above statement will create an array of objects ‘empObjects’ with 2 elements/object references.

Initialize Array Of Objects

Once the array of objects is instantiated, you have to initialize it with values. As the array of objects is different from an array of primitive types, you cannot initialize the array in the way you do with primitive types.

In the case of an array of objects, each element of array i.e. an object needs to be initialized. We already discussed that an array of objects contains references to the actual class objects. Thus, once the array of objects is declared and instantiated, you have to create actual objects of the class.

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

The following program shows the initialization of array objects using the constructor.

Here we have used the class Employee. The class has a constructor that takes in two parameters i.e. employee name and employee Id. In the main function, after an array of employees is created, we go ahead and create individual objects of the class employee.

Then we pass initial values to each of the objects using the constructor.

The output of the program shows the contents of each object that was initialized previously.

class Main{
   public static void main(String args[]){
     //create array of employee object 
    Employee[] obj = new Employee[2] ;
     //create & initialize actual employee objects using constructor
     obj[0] = new Employee(100,"ABC");
     obj[1] = new Employee(200,"XYZ");
     //display the employee object data
     System.out.println("Employee Object 1:");
     obj[0].showData();
     System.out.println("Employee Object 2:");
     obj[1].showData();
  }
}
//Employee class with empId and name as attributes
class Employee{
  int empId;
  String name;
  //Employee class constructor
  Employee(inteid, String n){
     empId = eid;
     name = n;
  }
public void showData(){
   System.out.print("EmpId = "+empId + "  " + " Employee Name = "+name);
   System.out.println();
 }
}

Output:

Output - Initializing an Array

The example program that we have given below shows a member function of the Employee class that is used to assign the initial values to the Employee objects.

Example Program For An Array Of Objects In Java

Given is a complete example that demonstrates the array of objects in Java.

In this program, we have an Employee class that has employee Id (empId) and employee name (name) as fields and ‘setData’ & ‘showData’ as methods that assign data to employee objects and display the contents of employee objects respectively.

In the main method of the program, we first define an array of Employee objects. Note that this is an array of references and not actual objects. Then using the default constructor, we create actual objects for the Employee class. Next, the objects are assigned data using the setData method.

Lastly, objects invoke the showData method to display the contents of the Employee class objects.

class Main{
   public static void main(String args[]){
     //create array of employee object 
     Employee[] obj = new Employee[2] ;
     //create actual employee object
     obj[0] = new Employee();
     obj[1] = new Employee();
     //assign data to employee objects
     obj[0].setData(100,"ABC");
     obj[1].setData(200,"XYZ");
     //display the employee object data
     System.out.println("Employee Object 1:");
     obj[0].showData();
     System.out.println("Employee Object 2:");
     obj[1].showData();
  }
}
//Employee class with empId and name as attributes
class Employee{
    int empId;
    String name;
    public void setData(intc,String d){
        empId=c;
        name=d;
     }
    public void showData(){
        System.out.print("EmpId = "+empId + "  " + " Employee Name = "+name);
        System.out.println();
     }
}

Output:

Display the contents of the Employee class objects

How To Sort An Array Of Objects In Java?

Like an array of primitive types, an array of objects can also be sorted using the ‘sort’ method of the Arrays class.

But the difference is that the class to which the objects belong should implement the ‘Comparable’ interface so that the array of objects are sorted. You also need to override the ‘compareTo’ method that will decide the field on which the array is to be sorted. The array of objects is sorted in ascending order by default.

The following program shows the sorting of an array of objects. We have used an Employee class for this purpose and the array is sorted based on employee Id (empId).

import java.util.*;
//employee class implementing comparable interface for array of objects
class Employee implements Comparable<Employee> {
    private String name;
    privateint empId;
    //constructor
    public Employee(String name, int empId) {
        this.name = name;
        this.empId = empId;
    }
    public String getName() {
        return name;
    }
    publicintgetempId() {
        return empId;
    }
    
    //overridden functions since we are working with array of objects
    @Override
    public String toString() {
        return "{" + "name='" + name + '\'' +
                    ", EmpId=" + empId + '}';
    }
    //compareTo method overridden for sorting array of objects
    @Override
    publicint compareTo(Employee o) {
        if (this.empId != o.getempId()) {
            returnthis.empId - o.getempId();
        }
        returnthis.name.compareTo(o.getName());
    }
}
//main class
class Main {
    public static void main(String[] args)
    {
        //array of Employee objects
        Employee[] employees = { new Employee("Rick", 1), new Employee("Sam", 20),
                    new Employee("Adi", 5), new Employee("Ben", 10) };
        //print original array
        System.out.println("Original Array of Employee objects:");
        System.out.println(Arrays.toString(employees));
        //sort array on empId
        Arrays.sort(employees);
        //display sorted array
        System.out.println("\nSorted Array of Employee objects:");
        System.out.println(Arrays.toString(employees));
    }
}

Output:

Array is sorted based on employee Id

Note that in the above program, the Employee class implements Comparable interface. Secondly, the method compareTo is overridden to sort the given array of objects on the empId field.

Also, the method ‘toString’ is overridden in order to facilitate the conversion of the array of objects to a string.

Frequently Asked Questions

Q #1) Can you have an Array of Objects in Java?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.

Q #2) What is an Array of Objects in Java?

Answer: In Java, an array is a dynamically created object that can have elements that are primitive data types or objects. The array may be assigned variables that are of type object.

Q #3) How do you Sort Objects in Java?

Answer: To sort objects in Java, we need to implement the ‘Comparable’ interface and override the ‘compareTo’ method according to a particular field. Then we can use the ‘Arrays.sort’ method to sort an array of objects.

Q #4) How do you Sort Objects in ArrayList?

Answer: ArrayList can be sorted using the Collections.sort() method directly. The Collections.sort() method sorts the elements naturally in ascending order.

Conclusion

In this instructional exercise, we examined the theme ‘Exhibit of Objects’ alongside the different subtopics identified with a variety of items. We saw instances of instating and arranging a variety of items.

For arranging the class whose articles are to be arranged should execute the ‘Practically identical’ interface and furthermore supersede the ‘compareTo’ technique. To print the substance of the ‘Variety of items’, we ought to likewise abrogate the ‘toString’ technique so we can compose every one of the substance of each article.

Related Posts