August 18 2015

Array of objects in java

Array of objects in java

Arrays are objects that can store multiple variables of same data type. The element of the array can be accessed using index number. The index of the array will always start from zero. If array’s size 5, the index will be from 0 to 4.

Array can hold either primitives or object references.If array is initialized the elements will get their default values, primitives will get the default values as per the data type whereas object references will get null.

 Array of Primitives

In the below example, marks is an array of primitives(int). Values can be initialized using index.

int[] marks = new int[5];

marks[1] = 10;

Array of Object References

In the below example, empArray is an array of Employee Object References. The Employee object reference has to be assigned to the array using index.

Employee[] empArray = new Employee[3];

Employee emp1 = new Employee();

emp1.empId = 10;

empArray[0] = emp1;

Example

ObjectArray.java

package com.answersz.arrays;

public class ObjectArray {

 public static void main(String[] args) {

 // Array of Primitives

 int[] marks = new int[5];
 marks[1] = 10;

 // Array of objects in java

 Employee[] empArray = new Employee[3];

 Employee emp1 = new Employee();
 emp1.empId = 10;
 emp1.name = "PAUL";
 emp1.age = 25;

 empArray[0] = emp1;

 Employee emp2 = new Employee();
 emp2.empId = 11;
 emp2.name = "GEORGE";
 emp2.age = 25;

 empArray[1] = emp2;

 Employee emp3 = new Employee();
 emp3.empId = 12;
 emp3.name = "John";
 emp3.age = 25;

 empArray[2] = emp3;

 // Iterating using for each loop

 for (Employee emp : empArray) {
 System.out.println("Emp Id : " + emp.empId);
 System.out.println("Name : " + emp.name);
 }

 }

}

Employee.java


package com.answersz.arrays;

public class Employee {

int empId;
String name;
int age;

}

Output

Emp Id : 10
Name : PAUL
Emp Id : 11
Name : GEORGE
Emp Id : 12
Name : John


Copyright © 2014. All rights reserved.

Posted August 18, 2015 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*