How do I write Hello World program in Java?

Hello World is a classic program example to start with when we begin to learn a new programming language. The main purpose is to know the basic syntax of the language. Below is the Java version of a Hello World program, it simple enough to start.

package org.kodejava.example.basic;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");

The code contains one class called HelloWorld, we declare a class using the class keyword. A main(String[] args) method with a public static void signature and an argument of string array is a special method in Java class. This method is the execution entry point of every Java application. When a class have this method it will be executable. And finally in the body of the method we have a single line of code that write a Hello World string to the console.

The HelloWorld class must be saved in a file named, the class file name is case sensitive. In the example we also define a package name for the class. In this case the must be placed in a org.kodejava.example.basic directory.

To run the application we need to compile it first. I assume that you have your Java in your path. To compile it type:

javac -cp .

The compilation process will result a file called HelloWorld.class, this is the binary version of our program. As you can see that the file ends with .class extension because Java is everything about class. To run it type the command bellow, class name is written without it extension.

java -cp . org.kodejava.example.basic.HelloWorld

And you will see a string Hello World! is printed out in the console as the output of your first Java program, the HelloWorld program.

To install Java Development Kit (JDK) and configure Java environment you can see the following tutorial:

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply