object array in java code example
Example 1: how to create an array in java
int[] array1 = new int[5];
String[] array2 = new String[5]
double[] array3 = new double[5]
Example 2: array objects java
obj array[] = new obj[10];
for (int i = 0; i < array.length; i++) {
array[i] = new obj(i);
}
Example 3: creating array of objects in java
class Main{
public static void main(String args[]){
Employee[] obj = new Employee[2] ;
obj[0] = new Employee(100,"ABC");
obj[1] = new Employee(200,"XYZ");
System.out.println("Employee Object 1:");
obj[0].showData();
System.out.println("Employee Object 2:");
obj[1].showData();
}
}
class Employee{
int empId;
String name;
Employee(inteid, String n){
empId = eid;
name = n;
}
public void showData(){
System.out.print("EmpId = "+empId + " " + " Employee Name = "+name);
System.out.println();
}
}
Example 4: java initialize object array
import java.util.stream.Stream;
class Example {
public static void main(String[] args) {
int len = 5;
Foo[] arr = Stream.generate(() -> new Foo(1))
.limit(len)
.toArray(Foo[]::new);
}
class Foo {
public int bar;
public Foo(int bar) {
this.bar = bar;
}
}
}
Example 5: java array object
Class obj[]= new Class[array_length]
Example 6: how to make array of objects in java and use it
class enemies {
int marks;
}
enemies[] enemiesArray = new enemies[7];
enemiesArray[5] = new enemies(95);