Why is Java Platform Independent?

A programming language is said to be platform independent when a program or application written in it i.e. its source code can run on any operating system or platform, irrespective of where it was developed and compiled. We can define platform as the sum of hardware and software that provides an environment for the program to run. So, what makes Java Platform independent?

A program written in any language is in a human readable form. It may contain words, phrases etc which machines do not understand. For any source code to be understood by machines, it needs to be translated to a language understood by machines i.e. machine-level language. This is the job of a compiler, which converts the code written in high level language into a machine level language code. This code is either executed by the CPU directly or it may be an intermediate code that is interpreted by a virtual machine (as in case of Java). This intermediate representation in Java is in the form of Java Byte Code.

How Java works?

In order to understand its functionality, let us first see the case of C or C++. In case of C or C++, when you create a program and compile it, the compiler generates an .exe file which can only run on the operating system on which it has been created, making it operating system dependent. So, when you try to run it on another operating system, it will not run on it as it is operating system dependent and is not compatible with any other operating system.

However, whenever a program is written in Java, the javac compiler compiles it and makes a .class file or the byte code. This byte code is not native to the machine (unlike C or C++ compiler) on which it has been created. It is a non-executable code which needs an interpreter to execute it on any machine. Once interpreted by an interpreter, the program or application can run and the desired output can be obtained on any platform or operating system.

java file compilation to bytecode

How is Java Platform Independent?

When you install JDK on your system, JVM also gets installed on your system automatically. For every operating system a separate JVM is available which is capable of reading any .class file or the byte code. So, whenever a .class file is created by our Java compiler, it can be read by any JVM on any operating system. Hence, Java language becomes platform independent and it is termed as portable software.

Java Platform Independent -JVM Platform Dependent

In Java JVM always depends on the operating system – so if you are running Mac OS X you have a different JVM than if you are running Windows or any other operating system. Downloads of various JVM’s corresponding to different operating systems are available where we can select the JVM according to the operating system we are running. These are the reasons that we can say that JVM is platform dependent but it can interpret any byte code and Java language is platform independent.