In this post, we’ll discover how to get started with Java, the fundamental terms, and the process of compilation and execution of a simple Java application.
There are several steps for creating a Java application.
The first step is to write some Java code in the text editor of your choice. Then this code has to be transformed into another format that can be executed by your computer which is conducted by a special piece of software called a compiler.
The file produced by your compiler is called an executable or binary file which can be understood by a computer. This file is not in human readable format whereas source code is in human readable format. This code contains a special binary code called byte code.
Once the compilation produces a binary file we can execute this binary file.
Compilation and execution needs require two specific pieces of software that are part of the Java development kit, also known as JDK.
You can download JDK versions for your operating system by following this link or following the instructions from the docs.
Java application is compiled and run with the help of the tools provided by the Java Development Kit(JDK) and we have to keep in mind that downloading Java means downloading JDK. It is officially distributed by the OpenJDK and by Oracle.
You may have heard about Java Runtime Environment(JRE) which is a subset of a JDK that only contains the tools to run a Java application and it cannot be used to compile our Java application. It is not distributed by OpenJDK or Oracle anymore.
The above figures describe the compilation and execution of a Java application and introduce us to the new term Java Virtual Machine(JVM).
Java Virtual Machine is a runtime environment in which Java bytecode can be executed.
Let’s look at the below image in more detail to understand JDK, JRE, and JVM.
Let’s implement the simple program to see the compilation and execution process.
A Java class must be saved in a file that has the same name as your class with the extension .java
. This is mandatory and is very convenient because you do not need to open a file to know what class is written in it.
// java program to see compilation and execution process
public class HelloWorld {
public static void main(String... args) {
System.out.println("Hello World");
}
}
Step 1: Let us create a text file of the same name as our class i.e. HelloWorld in this scenario and save it in a .java extension.
Step 2: Let us compile our Java application with the below command in our terminal.
javac HelloWorld.java
This will generate the HelloWorld.class file, commonly known as byte code.
Step 3: Lastly execute our byte code to convert it into native machine code with the following command.
java HelloWorld
//output:- Hello World
We’ve covered the compilation and execution of a Java application.