You are currently viewing Create, Compile, and Run Your Hello World Java Application using a Terminal

Create, Compile, and Run Your Hello World Java Application using a Terminal

1. Introduction

If you are reading this article, it is because you have decided to learn to program in Java. This article will teach you how to write, compile, and run your Hello World Java program.
No prior knowledge of Java is required.

2. Prerequisites

To complete the following tutorial, you will need :

  • The Java SE Development Kit 17 (JDK 17): If you don’t have it already refer to this tutorial for the installation procedure.
  • IntelliJ IDEA: If you don’t have it already refer to this tutorial for the installation procedure.

Note: The screenshots provided in this tutorial are from a macOS environment. There is no big difference compared to other environments (Windows, Linux).

3. Create a New Folder

To organize your Java projects, we advise you to create a “java-projects” directory in your personal home space.
Create a “helloworld” subdirectory in the “java-projects” directory.

Open a Terminal and enter the following commands :

cd ~
mkdir java-projects
cd java-projects
mkdir helloworld
cd helloworld

`

helloworld_folder

4. Create the Java file

4.1. Create the file

Open your favorite text editor and create a new file. We are using TextEdit here.

helloworld_textedit

Copy/Paste the following code fragment into the file.

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

4.2. Save Your file

Save your file under the name “HelloWorld.java” in the “helloworld” directory previously created. Make sure you enter the name exactly as shown above because Java is strict about being case-sensitive.

helloworld_textedit_save

And that’s what your “helloworld” directory looks like after this step:

helloworld_save_folder

4.3. Compile the Java file

Open the terminal (or the command line if on Windows) and navigate to the “helloworld” directory.

cd ~/java-projects/helloworld

Compile your Java file

javac HelloWorld.java

If all goes well, you will see a file appear in the same directory under the name HelloWorld.class: This is the byte-code corresponding to your Java class.

helloworld_compile

4.4. Run the Java file

Run the following command to execute your Java application.

java -cp . HelloWorld

You will see the following output in your terminal or command line.

helloworld_run

That’s it! You’ve just run your first Java application.

5. Conclusion

In this tutorial, you learned how to create, compile, and execute your Hello World Java application from the Terminal.
In the next article, you will learn how to create the same application using an Integrated Development Environment (IDE).

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.

Leave a Reply