Ticker

6/recent/ticker-posts

Array of Objects in Java

Array of Objects in Java

Introduction
In Java, arrays can hold elements of a single data type. However, it is also possible to create an array of objects where each element of the array is an instance of a class or an object. This allows you to store multiple objects of the same class in a single array, making it convenient to manage and manipulate related data.

Creating Array of Objects
To create an array of objects in Java, follow these steps:

  1. Define the Class: First, define the class whose objects you want to store in the array. For example, let's create a simple class called Person with two attributes: name and age.
java
class Person {
String name;
int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
  1. Declare and Initialize the Array: After defining the class, declare and initialize the array of objects. Specify the class type followed by square brackets to indicate it's an array.
java
public class Main {
public static void main(String[] args) {
// Create an array of Person objects
Person[] peopleArray = new Person[3];

// Initialize each element with new instances of Person
peopleArray[0] = new Person("Alice", 30);
peopleArray[1] = new Person("Bob", 25);
peopleArray[2] = new Person("Charlie", 35);
}
}
  1. Accessing Array Elements: You can access individual elements of the array just like any other array.
java
Person person1 = peopleArray[0];
System.out.println("Name: " + person1.name + ", Age: " + person1.age);

Explanation
In the provided example, we created an array peopleArray that can hold three instances of the Person class. We then initialized each element of the array with new Person objects, setting their respective name and age attributes. Finally, we accessed the first element of the array and printed the name and age of the person.

Note: When creating an array of objects, the array only holds references to the objects, not the objects themselves. So, when initializing the array, make sure to also create new instances of the objects using the new keyword, as shown in the example.

That's it! You now know how to create an array of objects in Java and how to access and manipulate the objects stored in the array.

Post a Comment

0 Comments