Array of Object in Java

 

MOHIT TYAGI
Array of Object in Java
  1. Declare an array variable of the object type. For example, to declare an array of Person objects:

    css
    Person[] people;
  2. Allocate memory for the array using the new keyword. For example, to create an array of 10 Person objects:

    javascript
    people = new Person[10];
  3. Initialize each element of the array by creating new objects and assigning their references to the array elements. For example:

    scss
    people[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:

csharp
public 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:

python
Alice is 25 years old Bob is 30 years old Charlie is 40 years old

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java