To understand the above concept, first of all let us know what exactly do we mean by platform.
A platform is a hardware or software environment in which a program runs. In general, it can be described as a combination of operating system and the underlying hardware. Some of the most popular platforms are Windows, Mac, Linux etc.,
A java platform differs from most other platforms in that its a software only platform that runs on other hardware based platforms.
The java platform consists of two components:
1) Java Virtual Machine (JVM)
2) Application programming interface (API)
JVM is a virtual machine which is capable of executing a form of instruction set called as byte code. Hence it is termed as the execution component of the java platform.It is mostly implemented to run on other operating systems but can also be implemented to run directly on hardware. The implementation of JVM as a piece of software is different for different platforms. That is JVM for Windows is different from JVM for Linux. Thus, we can say that JVM is platform dependent.
JVM is generally distributed with a set of standard class libraries that implements the java Application programming Interface (API). This API is a set of ready-made software components that provide many useful capabilities to perform common tasks.
JVM and the standard class libraries that implements the java API bundled together is called as Java Runtime Environment (JRE).
Whenever you compile a java source file, the output will be a .class file. This class file does not contain code that is native to the processor. Instead , it contains an intermediate language called as ‘Byte Code’. This Byte Code is nothing but a set of instructions that the JVM is capable of executing. It is independent from any operating system and hardware. Each Byte Code instruction is one byte in length although some require parameters making them multi byte instructions.
The use of byte code as an intermediate language allows java programs to run on any platform which has a JVM and thus making it platform independent. So, its like this:
1)I write java source code and compile it using javac.
2)The java compiler generates a .class file which contains byte code.
3)Now, I can take this class file and execute it on a Linux machine which has a JVM for it. I can also take the same class file and execute it on a Windows machine which has a different implementation of JVM specifically for it.
So, here I am writing and compiling the code only once but was able to execute it on multiple platforms which has a JVM. Thus, we can say that Java is platform independent and Write Once Run Anywhere (WORA) goal has been achieved.
- The use of java byte code as an intermediate language along with JVM which is capable of executing it is what makes java platform independent.
- Remember that JVM is platform dependent and each OS has a different implementation of JVM.