Compiling and Running a Simple Java Program

Are you new to Java and trying to learn how to compile and run a simple Java program? Look no further! In this tutorial, I will walk you through the steps to compile and run your first Java program, as well as troubleshoot any issues you may encounter along the way.

Before we begin, make sure that you have the Java Development Kit (JDK) installed on your machine. If you do not have the JDK installed, you can download it from the Oracle website.

Step 1: Create a Java source file

The first step is to create a new file with a .java extension that contains the Java source code. For this tutorial, we will create a simple program that prints “Hello, World!” to the console.

Open your text editor and enter the following code:

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

Save the file as in a convenient location on your machine.

Step 2: Compile the Java source file

To compile the Java source file, open the command prompt (on Windows) or terminal (on macOS or Linux), and navigate to the directory where you saved the file.

Then, enter the following command:


This will compile the file and create a new file called Main.class, which contains the bytecode version of the program.

Step 3: Run the Java program

To run the Java program, enter the following command:

java Main

This will execute the Main class, which will print “Hello, World!” to the console.

Troubleshooting: javac or java is not recognized

If you receive an error saying that the javac or java commands are not recognized, it means that the system cannot find the executables for these commands. This can happen if the PATH environment variable is not set correctly.

You can read my other post on How to solve error “javac or java is not recognized”.