What is JVM (Java Virtual Machine)

Chamal Weerasinghe
3 min readApr 29, 2021
Photo by Campbell on Unsplash

“Adaptability is the simple secret of survival.” — Jessica Hagedorn

Have you ever wondered what is the secret behind that Java’s “Write once, Run Anywhere”? and its platform Independence? This is all about it!

We know that a program written by C, C++ creates an executable file (.exe in windows, .sh in Linux) this file cannot run on the different OS it can only run on the suitable platform which is compiled.

Compilation process of C++ (Limited to only one platform after compilation)

But when it comes to Java, We write the source code first (*.java) and compile it then we get a byte code (*.class), this class file can run on Windows, Linux, Unix, or even macOS, the only prerequisite is installing Java on these platforms. No compilation process again and again on Java, just take the class file and run.

Same compiled Java File Running on Multiple OS
Same Compiled Java File Running on Different OS

But we know that the architecture of the OS is completely different from one another, for example, process management is done a different way in Linux than it is in Windows. But JVM manages to run the same compiled program in different OS.

The truth behind the JVM is it is actually a specification, which provides the what to do approach to run the program written in JVM compatible language (Java, Kotlin, Scala, Ballerina). It does not say exactly how it should be done on a different platform, and “Virtual” means which it does not really exist.

The magic actually happens inside the JRE (Java Runtime Environment). Unlike the JVM, JRE is the implementation of the specifications to execute a program. also, JRE is highly platform-dependent, the JRE which we are using on Linux cannot be installed on Windows or macOS. This is where it decides how a given (*.class) file should run on the selected platform, the magic behind the “Write Once, Run Anywhere” comes with the JRE. The image below it shows the installation options provided for the Oracle JDK on different platforms.

Different Installation Options for Different OS —Image From Oracle

So, How Java gets its independence from the platform, is that providing different implementations/runtime environments for different platforms.
When we want to run the program (using the “java” command) it starts a platform-dependent application-based virtual machine using JRE implementation for the particular OS.

References

Introduction to JVM: https://www.youtube.com/watch?v=bUtIIWbaFKc

--

--