Home » Core Java » How to create an array of objects in Java

About Mohammad Meraj Zia

Senior Java Developer

How to create an array of objects in Java

In this article, we will show how to create an array of objects in Java.

1. Introduction

Everything in Java is associated with classes and objects, along with its attributes and methods. A Class is like an object constructor or a “blueprint” for creating objects. A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

array of objects java

2. Creating objects

In this section we will see different ways of creating a Java object.

2.1 new operator

The most common way to create a Java is to use the new operator.

SpecialClass object1 = new SpecialClass();

2.2 newInstance()

Another way of creating the Java object is to use the newInstance() method of the Class class:

SpecialClass object2 = SpecialClass.class.newInstance();

Please note that this way of creating the objected has been deprecated since Java 9. This method propagates any exception thrown by the nullary constructor, including a checked exception. The use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. This call can be replaced with clazz.getDeclaredConstructor().newInstance(). The latter sequence of calls is inferred to be able to throw the additional exception types InvocationTargetException, NoSuchMethodException. Both of these exception types are subclasses of ReflectiveOperationException.

2.3 clone

Now let us look at another way of creating a java object. We can use the clone() method of the object class. This creates and returns a copy of the object on which this is called. The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type.

This method performs a “shallow copy” of this object, not a “deep copy” operation. The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

final Object object4 = object1.clone();

2.4 De/Serialization

The readObject() method of ObjectInputStream class can be used to create objects.

ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("filename"));
SpecialClass object5 = (SpecialClass) objectInputStream.readObject();

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

3. Array

Arrays in Java are used to store multiple values in a single variable instead of declaring separate variables for each value. There are two ways of declaring an array:

String[] str1;
String str2[];

An array declaration has two components: the type and the name. Type declares the element type of the array. The element type determines the data type of each element that comprises the array.

When an array is declared only a reference is created. To create and give memory to an array we need to instantiate it. We can make use of the new operator to do that.

arrVariable = new arrayType[]

arrayType refers to the type of array (e.g. String, int etc), size refers to the size of the array. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types)

We can also use a shortcut syntax to create and initialize an array:

int[] arr = {40, 2, 300};

We can also declare array of arrays also known as multi-dimensional arrays by using two or more sets of brackets. e.g. int[][] arr.

4. Array of objects in Java

In this section, we will see how to create an array of objects in Java. The syntax to create and initialize an array of the object is as below:

ClassName[] objectName = new ClassName[];

Example: To create an array of objects of class SpecialClass you can use the below syntax:

SpecialClass[] objects = new SpecialClass[3];

To access the class elements you will need to provide the index and calls the method/variable – objects[<index>].classMethod

5. Summary

In this article, we showed how to create an array of objects in Java. Then we discussed what arrays are and how to create and initialize them. In the end, we discussed how to create an array of objects in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments