Java Program to Print Message Using Class

You are currently viewing Java Program to Print Message Using Class

Java program to print message using class

// Creating method in same class (public class)
// in which main method exists.

import java.util.*;

class HelloWorld {
  public void dispMessage() {
    System.out.println("Hello World.");
  }

  //Main method
  public static void main(String s[]) {
    //creat object of HelloWorld Class
    HelloWorld obj = new HelloWorld();
    obj.dispMessage();
  }
}
// Creating method in other (external) class

import java.util.*;

//class to print message
class ShowMessage {
  public void dispMessage() {
    System.out.println("Hello World.");
  }
}

//public class
public class HelloWorld {
  //main method
  public static void main(String[] s) {
    //create object of ShowMessage class.
    ShowMessage obj = new ShowMessage();
    obj.dispMessage();
  }
}

Output

Compile: javac HelloWorld.java 
Run: java HelloWorld 

Output: Hello World.
Compile: javac HelloWorld.java 
Run: java HelloWorld 

Output: Hello World.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply