Before directly jumping to the reason first, we must understand how Java actually works and what are the component available in Java. So that we can easily understand how Java is a platform independent language.
We all know that Java is a widely used programming language and probably, it is the first choice of large enterprise companies for the last 2 decades and so on. The main reason Java is so popular even in 2022 is that Java is everywhere. Whether it is in web applications or smartphones or in smartwatches or IoT devices Java is available everywhere.
How Java execution work?
When we compile a Java source code using the javac
command the compiler generates a .class
file.
JVM interprets the class file into machine code and the magic happens as an output.
Now, the question may come What is JVM?
The JVM is the main pillar of Java that makes it so popular and platform independent. JVM is platform dependent but it is available in all the machines where JRE is installed.
Java has three important components:
JDK | JDK provides all the tools that are needed to develop Java applications. |
JRE | JRE creates a runtime environment so that JVM does its work based on the specification defined. |
JVM | JVM is an abstract machine so it does nothing without JRE. It comes along with JRE installation. |
The post difference between JDK, JRE and JVM explains in detail if you want to learn in depth.
JDK, JRE, and JVM are platform dependent this is because the execution of each operating system is different. But,
Java is platform independent because:
- Java compiler
javac
compiles the Java code and generates.class
file. - The .class file is a bytecode that does not understand by the Operating System.
- JVM converts bytecode to machine code (binary) so that computer can understand it.
- JVM is available in every machine where JRE is installed. Any valid bytecode is interpreted by JVM irrespective of the operating system.
This is the reason that we say Java is platform independent.
Conclusion
Java is not platform independent itself. The bytecode makes Java a platform independent language. An intermediate code bytecode is understood by JVM only. The JVM is available for all platforms. This is the reason that we say Java is a platform independent programming language.