How to create your first Java Program

This post summarizes how to create your first program in Java programming language without an IDE.

Steps to create your first Java Program

This section summarizes how to create your first Java Program.

1. Ensure you have an OpenJDK Implementation installed

You need to install a OpenJDK in your computer in order to be able to compile and execute your Java program.

To check whether the OpenJDK is already installed, open a terminal in your OS (it could be Command Prompt / cmd in Windows or terminal in macOS and LInux), type this and then press Enter:

javac

If you get a long text explaining javac options, that good news! Just skip to step 2.

If you get a message like “command not found”, it means that an OpenJDK is not installed or it is not configured properly.

If you need to install OpenJDK and you are a Windows and macOS, I would recommend to download and run the Temurin JDK installer.

If you need to install OpenJDK and your are a Linux user, I would recommend to install the standard OpenJDK from your favourite package manager. If you are using apt, just open a terminal and type:

sudo apt install openjdk-8-jdk

You may substitute the number (8) by the OpenJDK version you want to install.

2. Create the Java source code file

You must use a text editor (like Notepad in Windows or CotEditor in macOS) or a Java IDE to create the source code file.

The content of the file could be a simple program. In this example we are making a Hello World program, that just displays the text “Hello, World!” when run from a command line terminal.

Enter this code in your text editor:

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

Save the file as “HelloWorld.java”.

Capitalization for both the source code and file name is important.

3. Compile code

Open the command line or terminal and go to the path where the file is located, using the cd command.

Type this and press Enter:

javac HelloWorld.java

If no output is displayed, this is good news, as it means that no errors have been encountered.

You may check that a HelloWorld.class file has been generated in the same folder. This file contains the Java bytecode, it means, the code executable by the Java Virtual Machine (JVM) that comes with the OpenJDK I mentioned in the first step.

4. Run the program

Now we are running the program from the terminal. You need to be in the same folder where the Class file has been created. If you did nothing after the previous step, you should be already there.

Using the terminal again, type:

java HelloWorld

The expected output is:

Hello, World!

And that’s all! Congratulations, you have created your first Java program.

You might also be interested in…

External References

Leave a Reply

Your email address will not be published. Required fields are marked *