How to Create Array of Objects in JavaIn this section, we will learn how to create and initialize an array of objects in Java. Array of Objects in JavaJava is an object-oriented programming language. Most of the work done with the help of objects. We know that an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types. Java allows us to store objects in an array. In Java, the class is also a user-defined data type. An array that conations class type elements are known as an array of objects. It stores the reference variable of the object. Creating an Array of ObjectsBefore creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects. Syntax: Or Or Suppose, we have created a class named Employee. We want to keep records of 20 employees of a company having three departments. In this case, we will not create 20 separate variables. Instead of this, we will create an array of objects, as follows. The above statements create an array of objects with 20 elements. Let's create an array of objects in a Java program. In the following program, we have created a class named Product and initialized an array of objects using the constructor. We have created a constructor of the class Product that contains product id and product name. In the main function, we have created individual objects of the class Product. After that, we have passed initial values to each of the objects using the constructor. ArrayOfObjects.java Output: Product Object 1: Product Id = 23907 Product Name = Dell Laptop Product Object 2: Product Id = 91240 Product Name = HP 630 Product Object 3: Product Id = 29823 Product Name = LG OLED TV Product Object 4: Product Id = 11908 Product Name = MI Note Pro Max 9 Product Object 5: Product Id = 43590 Product Name = Kingston USB Next TopicHow to Create Package in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India