Can we store objects in an array in Java?


Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.

  • Element: Each item stored in an array is called an element.
  • Index: Each location of an element in an array has a numerical index, which is used to identify the element.

Storing Objects in an array

Yes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.

Example

Following Java example have a class named Std and later in the program we are creating an array of type Std, populating it, and invoking a method on all the elements of the array.

class Std {
   private static int year = 2018;
   private String name;
   private int age;
   public Std(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public void display(){
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Year: "+Std.year);
   }
}
public class Sample {
   public static void main(String args[]) throws Exception {
      //Creating an array to store objects of type Std
      Std st[] = new Std[4];
      //Populating the array
      st[0] = new Std("Bala", 18);
      st[1] = new Std("Rama", 17);
      st[2] = new Std("Raju", 15);
      st[3] = new Std("Raghav", 20);
      //Invoking display method on each object in the array
      for(int i = 0; i<st.length; i++) {
         st[i].display();
         System.out.println(" ");
      }
   }
}

Output

Name: Bala
Age: 18
Year: 2018

Name: Rama
Age: 17
Year: 2018

Name: Raju
Age: 15
Year: 2018

Name: Raghav
Age: 20
Year: 2018

Updated on: 02-Jul-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements