Write a Java program to Create an array of objects


This code defines two classes: ArrayObject and Sample. The ArrayObject class contains a main method, which creates an array of Sample objects called arrobj with a size of 5. Then, each element of the array is assigned a new Sample object using the constructor.

Finally, the sayHello method of each Sample object in the array is called using the dot notation to access the method, and it simply prints "Java Exercise" to the console. Therefore, when this program is executed, it will print "Java Exercise" five times, once for each Sample object in the array.

Source Code

class ArrayObject
{
	public static void main(String args[])
	{
		Sample[] arrobj = new Sample[5];
 
		arrobj[0] = new Sample();
		arrobj[1] = new Sample();
		arrobj[2] = new Sample();
		arrobj[3] = new Sample();
		arrobj[4] = new Sample();
 
		arrobj[0].sayHello();
		arrobj[1].sayHello();
		arrobj[2].sayHello();
		arrobj[3].sayHello();
		arrobj[4].sayHello();
	}
}
class Sample
{
	void sayHello()
	{
		System.out.println("Java Exercise");
	}
}

Output

Java Exercise
Java Exercise
Java Exercise
Java Exercise
Java Exercise