How computers run programs
As developers, we often use high-level languages like Java, PHP, JavaScript, etc., to write our programs.
In computers, the CPU is the component responsible for executing or running instructions we write. Unfortunately, it does not understand any high-level languages.
The only language that the CPU can understand is the machine language. It looks like this:
000101110011
11001111011000
010110010110110
As you can see, it is a sequence of binary instructions (0s and 1s) which are executed by a computer’s processor.
One other thing you need to know about machine language is that it is tied to the hardware. So, each computer has its own machine language.
Given the complexity of machine language, we build translators that convert programs written in a high-level language to machine language.
The JVM in a nutshell
Now that we have a good understanding of how a computer executes a program, let’s discuss the Java virtual machine.
The first thing to know is that JVM is a computer (or a machine), but not your typical machine. This computer does not exist as actual hardware, and does not even have an operating system. It is a hypothetical computer platform.
Next, as discussed above, a computer needs a machine language to execute programs, so the JVM also has its own machine language which is called Java bytecode. It is the role of the JVM to convert the bytecode into machine language for the actual computer (or hardware).
The JVM is part of the Java Running Environment (JRE).
Note: The JVM was originally for the Java language, but it has evolved to support many other languages like Scala, Groovy, and Kotlin, mainly.
In short, this is how it works:
How does the JVM work?
The JVM works in three primary stages:
-
Compilation: Java source code (.java) is compiled into bytecode (.class file) by the Java Compiler (javac). The bytecode is a platform-independent code that can be executed by any JVM.
-
Loading: The class loader in the JVM loads the compiled bytecode into memory.
-
Execution: The bytecode is executed by the JVM’s interpreter or Just-In-Time (JIT) compiler, which converts bytecode into native machine code specific to the underlying platform.
So, once a Java program is compiled, it can be run on almost any computer as long as it has a JRE (which also simulates the JVM). This is why the Java slogan is:
Write once, run anywhere (WORA)
Let’s see it in practice. Make sure you have a Java programming environment and that you can access these commands:
javac
(pronounced “java-see”): the Java compiler
java
: the Java bytecode interpreter