ADVERTISEMENT
ADVERTISEMENT

Java program to create an array of objects

Learn how to create an array of objects in Java?
Submitted by Nidhi, on March 20, 2022

Problem Solution:

In this program, we will create a Sample class with a method. Then we will create an array of objects.

Program/Source Code:

The source code to create an array of objects is given below. The given program is compiled and executed successfully.

// Java program to create an array 
// of objects

class Sample {
  void sayHello() {
    System.out.println("Hello World");
  }
}

class Main {
  public static void main(String args[]) {
    Sample[] arrObj = new Sample[3];

    arrObj[0] = new Sample();
    arrObj[1] = new Sample();
    arrObj[2] = new Sample();

    arrObj[0].sayHello();
    arrObj[1].sayHello();
    arrObj[2].sayHello();
  }
}

Output:

Hello World
Hello World
Hello World

Explanation:

In the above program, we created a Sample class and public class Main. The Sample class contains a method sayHello(). The sayHello() method prints the "Hello World" message.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created an array of 3 objects. Then we called the sayHello() method of each object and printed the "Hello World" message.

Java Class and Object Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.