English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Can Java arrays store objects?

An array is a container that can hold a fixed number of items, which should be of the same type. Most data structures use arrays to implement their algorithms. The following are important terms to understand the concept of arrays.

  • Element: Each item stored in an array is called an element.

  • Index: Each position of an element in an array has a numeric index that identifies the element.

Store objects in the array

Yes, because in Java objects are also considered data types (references), so you can create an array of a specific class type and fill it with instances of that class.

Example

The following Java example has a class named Std, which we will create an array of type Std later in the program, fill it, and call a method on all 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 {
      //Create an array to store Std type objects
      Std st[] = new Std[4];
      //Fill 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);
      //Call the display method on each object in the array
      for(int i = 0; i<st.length; i++) {
         st[i].display();
         System.out.println(" ");
      }
   }
}

Output Result

Name: Bala
Age: 18
Year: 2018
Name: Rama
Age: 17
Year: 2018
Name: Raju
Age: 15
Year: 2018
Name: Raghav
Age: 20
Year: 2018