Java 101: How to Compile and Run a Java program

In the previous article, we looked at how to install JDK on our computer and essentially, get our computer ready for Java development work.
In this article, we will look at how to compile and run our first Java program. Let’s dive in.

How to compile a Java program

Java is a compiled language. i.e. every Java program that you write has to go through a compilation step before it can be run (i.e. executed)
Java programs can be compiled using the java compiler. Java compilers are bundled with the Java Development Kit or JDK that we installed in the previous article.
Java compiler can be invoked using the javac command.

The syntax of the javac command is –

javac <java_source_file name with .java extension>

Example

Let’s compile a Java source file called Hello.java. Code for Hello.java

class Hello {
	
}

In this example, the Hello.java file contains a simple Hello class with an empty body which is a syntactically and semantically valid source code.
Let’s assume this file is in D:\misc\JavaQBank folder on our machine.

We can compile Hello.java as follows –

D:\misc\JavaQBank> javac Hello.java

Output:

In this case, the source code has been compiled successfully without any error.
Whenever the Java compiler encounters a syntactically wrong source code, the javac command will return a failure with description of the errors it encountered.

If you look in our D:\misc\JavaQBank folder now, you’ll see a Hello.class file. This is the output of the compilation step and contains the "byte code" that the Java runtime can use to "run"or execute our program. We’ll see how to run a Java program in the next section.

How to run a Java program

Once we have compiled our program, we can use the java command to execute that program. java invokes the Java runtime or JRE which loads and runs our program.

Syntax for running a Java program using the JRE is –

java <bytecode_name>

As an example, let’s run the following Java program –

class RunJavaProg {
    public static void main(String[] args) {
        System.out.println("Java program runs...");
    }
}

First, we need to compile the above java class as shown in the following.

javac RunJavaProg.java

Output:

If you inspect the folder where RunJavaProg.java source code resides, you’ll notice that another file has been created with the extension .class. If your source code has syntax errors, the Java compiler will raise errors and you need to fix them before moving forward.
This .class file contains Java Bytecode.

Let’s run the program as shown in the following.

java RunJavaProg

Output:

As you can see above, we were able to successfully run the program which then printed a line on the console.

Summary

In this article, we looked how to compile and run a Java program.

Related