java create object array code example

Example 1: array objects java

obj array[] = new obj[10];

for (int i = 0; i < array.length; i++) {
  array[i] = new obj(i);
}

Example 2: creating array of objects in java

class Main{
   public static void main(String args[]){
     //create array of employee object  
    Employee[] obj = new Employee[2] ;
 
     //create & initialize actual employee objects using constructor
     obj[0] = new Employee(100,"ABC");
     obj[1] = new Employee(200,"XYZ");
 
     //display the employee object data
     System.out.println("Employee Object 1:");
     obj[0].showData();
     System.out.println("Employee Object 2:");
     obj[1].showData();
  }
}
//Employee class with empId and name as attributes
class Employee{
  int empId;
  String name;
  //Employee class constructor
  Employee(inteid, String n){
     empId = eid;
     name = n;
  }
public void showData(){
   System.out.print("EmpId = "+empId + "  " + " Employee Name = "+name);
   System.out.println();
 }
}

Example 3: java initialize object array

import java.util.stream.Stream;

class Example {
  
  public static void main(String[] args) {
    int len = 5;  // For example.
    
    // Use Stream to initialize array.
    Foo[] arr = Stream.generate(() -> new Foo(1))  // Lambda can be anything that returns Foo. 
                      .limit(len)
                      .toArray(Foo[]::new);
  }
  
  // For example.
  class Foo {
    public int bar;

    public Foo(int bar) {
      this.bar = bar;
    }
  }
}

Example 4: java array object

Class obj[]= new Class[array_length]