-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Learn Java with Projects
By :

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.
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.
To compile a Java program using the command line, follow these steps:
HelloWorld.java
file). In case you don’t know how to do that, this can be done with the cd
command, which stands for change directory. For example, if I’m in a directory called documents
and I want to step into the subfolder called java programs
, I’d run the cd "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.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.
To run the compiled Java program, follow these steps:
.
class
file.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.