Java Hello World Program Example

In this example, we will create a step by step simple Hello World Java program and then we will run it. We will demonstrate this example using NotePad editor.

1. Create a Source File

Let's first, start the editor. You can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code:
/**
 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}
Before saving a file, let's create a directory named myapplication C drive. Now save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first, choose the File > Save As menu item. Then, in the Save As dialog box: 
By looking into the above source code, let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
  • class keyword is used to declare a class in java.
  • public keyword is an access modifier which represents visibility. It means it is visible to all.
  • static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory.
  • void is the return type of the method. It means it doesn't return any value.
  • main represents the starting point of the program.
  • String[] args is used for command line argument. We will learn it later.
  • System.out.println() is used print statement.

2. Compile the Source File into a .class File

To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is myapplication on the C drive, type the following command at the prompt and press Enter:
cd C:\myapplication
Now the prompt should change to C:\myapplication>.
Now you are ready to compile. At the prompt, type the following command and press Enter.
javac HelloWorldApp.java
Now that you have a HelloWorldApp.class file, you can run your program.

3. Run the Program

In the same directory, enter the following command at the prompt:
java HelloWorldApp
You should see the following on your screen:
C:\myapplication>java HelloWorldApp
Hello World!


Comments