Java-Array of Objects

Array of Objects

An array of object is a data structure that holds a group of object. For example :

Data[] obj = new Data[3];

This statement creates the array which can hold references to three Data objects. In this case, create an object for each of the null objects. Notice that we have to use the new keyword again, even though we used it when we created the array. Because we got three null references rather than actual objects from the original assignment, we have to create new ones here :

obj[0] = new Data();

obj[1] = new Data();

obj[2] = new Data();

Program

1

Program Source

class Data {
    
    int data1 ;
    int data2 ;
}

public class Javaapp {
    
    public static void main(String[] args){
        
        Data[] obj = new Data[3];
        
        obj[0] = new Data();
        obj[0].data1 = 10;
        obj[0].data2 = 20;
        
        obj[1] = new Data();
        obj[1].data1 = 30;
        obj[1].data2 = 40;
        
        obj[2] = new Data();
        obj[2].data1 = 50;
        obj[2].data2 = 60;

        System.out.println("obj[0].data1 = "+obj[0].data1);
        System.out.println("obj[0].data2 = "+obj[0].data2);
        System.out.println("obj[1].data1 = "+obj[1].data1);
        System.out.println("obj[1].data2 = "+obj[1].data2);
        System.out.println("obj[2].data1 = "+obj[2].data1);
        System.out.println("obj[2].data2 = "+obj[2].data2);
   }
}

Leave a Comment