- Array is collection of similar data types.
- Arrays can hold collection of data with indexes
- We already know that we can hold group of primitive variables
- Arrays can hold referenced variables also like Strings and objects
- So we can say it is possible to store or create array of objects in java
Declaring arrays in java:
- One dimensional array can be created like
- int[] singlearray;
- Two dimensional array can be created like
- int[][] intdoubleArray;
- double[][] doubleArray;
Instantiation and Initialization of Arrays
Program #1: Java example program to store string object in array
- package arraysofobjectsinjava;
- public class ArrayOfObjects {
- /**
- * @www.instanceofjava.com
- * creating and assigning values to arrays in java
- */
- public static void main(String[] args) {
- int[] a= new int[2];
- a[0]=1;
- a[1]=2;
- System.out.println(a[0]);
- System.out.println(a[1]);
- int[] var= {1,2,3,4,5};
- for (int i = 0; i < var.length; i++) {
- System.out.println(var[i]);
- }
- int[][] array=new int[2][2];
- array[0][0]=1;
- array[0][1]=2;
- array[1][0]=3;
- array[1][1]=4;
- for(int i=0; i<array.length; i++) {
- for(int j=0; j<array[1].length; j++)
- System.out.print(array[i][j] + " ");
- System.out.println();
- }
- }
- }
Output:
- 1
- 2
- 1
- 2
- 3
- 4
- 5
- 1 2
- 3 4
Array of objects in java:
Program #2: Java example program to store string object in array
- package arraysofobjectsinjava;
- public class ArrayofStringObjects {
- /**
- * @www.instanceofjava.com
- * Storing String objects in String array
- */
- public static void main(String[] args) {
- String a[]= new String[5];
- a[0]="array of objects";
- a[1]="object array in java";
- a[2]="array of objects in java example program";
- a[3]="array of objects in java tutorial";
- a[4]="how to make array of objects in java";
- for (int i = 0; i < a.length; i++) {
- System.out.println(a[i]);
- }
- }
- }
Output:
- array of objects
- object array in java
- array of objects in java example program
- array of objects in java tutorial
- how to make array of objects in java
Creating custom array of objects in java
- We can also store custom objects in arrays .
- Create a employee class.
- Create multiple objects of employee class and assign employee objects to array.
- Arrays can store objects but we need to instantiate each and every object and array can store it
Program#3: java example program to create custom objects and store in array
Employee.java
- package arraysofobjectsinjava;
- public class Employee {
- String name;
- int id;
- Employee(String name, int id){
- this.name=name;
- this.id=id;
- }
- }
No comments