Java Hello World example on Linux

Objective

The objective is to write, compile and execute a basic Hello World java example program.

Requirements

The only requirement is installed java on your Linux system.

Conventions

  • # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ – given linux commands to be executed as a regular non-privileged user

Instructions

Check your Java Installation

Before you begin make sure that you already have Java installed on your system. The easiest way to confirm the Java installation is to check java version.

Write Java Hello World Program

The first step is to write simple Hello World Java program. Using any text editor create a new file HelloWorld.java with the following content:

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

Once ready the HelloWorld.java program should be located in your current working directory:

$ ls HelloWorld.java 
HelloWorld.java


Compile Java Program

Now that the coding part is behind us, the next step is to compile the Java Hello World program using the javac command line compiler. Open up terminal and enter:

$ javac HelloWorld.java

The above command should not produce any output and errors. The result will be a new Java HelloWorld.class file located within your current working directory:

$ ls
HelloWorld.class  HelloWorld.java

Run Java Program

The last step is to execute the newly compiled java program. To do so we run the java command with a single parameter which will be the name of our class HelloWorld:

$ java HelloWorld 
Hello World
Hello World Java program example on Linux

Hello World Java program example on Linux


Comments and Discussions
Linux Forum