Compiling and running Java programs
Now that we have our first program written, let’s discuss how we can compile and run it. We will cover the basics of the compilation process, the role of the JVM, and how to compile and run Java code using the command line and an IDE.
Understanding the compilation process
The source code is written in a human-readable format using the Java programming language. Or at least, we hope that this is your opinion after this book. Before the code can be executed, it must be transformed into a format that the computer can understand. You already know that Java is a compiled language and that this process is called compilation.
During compilation, the Java compiler (javac) converts the source code (.java
files) into bytecode (.class
files). Once the bytecode is generated, it can be executed by the JVM. We have already learned that the JVM is the bytecode executer and that every platform has its own custom JVM enabling the WORA feature of Java.
Compiling the code with javac on the command line
To compile a Java program using the command line, follow these steps:
- Open a terminal (Command Prompt on Windows, Terminal on macOS or Linux).
- Navigate to the directory containing your Java source code file (for example, the directory of your previously created
HelloWorld.java
file). In case you don’t know how to do that, this can be done with thecd
command, which stands for change directory. For example, if I’m in a directory calleddocuments
and I want to step into the subfolder calledjava programs
, I’d run thecd "java programs"
command. The quotes are only needed when there are spaces in the directory name. It’s beyond the scope of this book to explain how to change directories for any platform. There are many excellent explanations for every platform on how to navigate the folder structure using the command line on the internet. - Once you’re in the folder containing the Java file, enter the following command to compile the Java source code:
javac HelloWorld.java
If the compilation is successful, a new file with the same name but a
.class
extension (for example,HelloWorld.class
) will be created in the same directory. This file contains the bytecode that can be executed by the JVM.
Let’s see how we can run this compiled code.
Running the compiled code with Java on the command line
To run the compiled Java program, follow these steps:
- In the terminal, make sure you are still in the directory containing the
.
class
file. - Enter the following command to execute the bytecode:
java HelloWorld
The JVM will load and run the bytecode, and you should see the output of your program. In this case, the output will be as follows:
Hello world!
It’s pretty cool that we can write Java in Notepad and run it on the command line, but the life of a modern-day Java developer is a lot nicer. Let’s add IDEs to the mix and see this for ourselves.