October 3, 2022
Java Programming languages

Objects and Arrays

  • If we beed single object to store in program, we have variable.
  • And, if we have numbers of objects, we need to create array of objects
  • It stores arrays of objects.
  • Array of object is not object stored in array, but reference of the object is stored.

How to create array of objects in JAVA?

  • Name of the class is followed by square bracket. And then object reference name is given to create array of object
  • Example
    • Name_Of_Class objectArrayReference[ ]; or
    • Name_Of_Class [ ] objectArrayReference ;
  • If we hve employee class then we can
    • Employee [ ] employeeObjects; or
    • Employee  employeeObjects[];

How to instantiate the array of objects?

  • Syntax is
    • Name_of_Class [ ] = new Name_of_Class [length_of_array];
  • Example
    • Employee [] employeeObject=new Employee [10];
    • After array of object is instantiated, you need to create individual elements in array of objects using new keyword.
    • Example
      • car c[ ] = new car [5]
      • c[0] = new car [3762, 13 pa ]
      • c [1] = new car [8385, 15 pa ]

Initializing Array of Objects

  • after array of object is instantiated; value needs to be iniatialized in it.
  • Like in primitive  type, we can’t initialize value in array of objects.
  • Ways to initialize array of obkects
    • By use of constructor
    • By use of separate member method

By using Constructer, we initialize array of objects.

Example

Class ICTByte {

Public static void main (String args [])

{

               //declaration of array of objects

               Employee[] arr;

               //allocation of memory for 3 objects to type employee

               Arr = new Employee [3];

               //initialization of first element

               Arr[0]=new Employee (1502, “Ram Bahadur”, “Bhaktapur”);

               //initialization of second element

               Arr [1] = new Employee (1502, “Shyam”, “Banepa”);

               //Displaying result

               System.out.println( “Data in arr 0”); arr[0].display();

               System.out.println (“Data in 1”); arr[1].display();

               }

}

//Creating employee class with id, name and address as attribute

Class Employee{

               public  int id;

               public String  name;

public String address;

//Employee class constructor

Employee (int id, String name, String address)

{

this.id = id;

this.name=name;

this.address=address;

//display( ) method to display

Public void display()

{

               System.out.println(“Employee id  is” + id + “ “+ “name is” + name + “address is” +address);

System.out.println()

}

}

https://www.geeksforgeeks.org/how-to-create-array-of-objects-in-java/
Facebook Comments