Array of Object in Java
- Get link
- X
- Other Apps

Array of Object in Java
Declare an array variable of the object type. For example, to declare an array of
Person
objects:cssPerson[] people;
Allocate memory for the array using the
new
keyword. For example, to create an array of 10Person
objects:javascriptpeople = new Person[10];
Initialize each element of the array by creating new objects and assigning their references to the array elements. For example:
scsspeople[0] = new Person("Alice", 25); people[1] = new Person("Bob", 30); people[2] = new Person("Charlie", 40); // ...
Here's a complete example of creating and initializing an array of Person
objects:
csharppublic class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person("Alice", 25);
people[1] = new Person("Bob", 30);
people[2] = new Person("Charlie", 40);
for (int i = 0; i < people.length; i++) {
System.out.println(people[i].name + " is " + people[i].age + " years old");
}
}
}
This will output:
pythonAlice is 25 years old
Bob is 30 years old
Charlie is 40 years old
- Get link
- X
- Other Apps
Comments
Post a Comment