How Java is Platform independent

Why Java is known as  platform independent, whats the internal mechanism which enables this.

 

Most popular Operating Systems are
1. Windows
2. Ubuntu
3. Mac

 

By definition  Operating System is a resource allocator(basic essence of OS ). The real difference comes in the way they allocate resources , the algorithms and optimization each has done to allocate the resources( hard disk, CPU , RAM , network).
Depending on the way of allocating resource the System calls to interact with the Operating Systems are also different for different Operating System. The instructions they need to execute a task is also different.

 

The executable file that a OS can understand varies across OS.

  •  Windows : EXE file format
  • Ubuntu    : ELF file format

 

For a program to become a process, the program needs to be present in the format the OS understands.

Lets Take the case of C language.

  • A code written in C compiled in Windows will result in a executable which can never be understood by Ubuntu as the exe file format is different from ELF and vice versa.
  • A C library if it needs to be shared across multiple OS platforms , then the code needs to be compiled against the different OS.
  • Binary formed on one platform cannot be used on other.

[addToAppearHere]

How does JAVA manages to be OS independent.

1.  Java code is compiled  to create a .class file format.
2.  The class file format is neither EXE or ELF its a different file format .
3.  The Class file is consumed by the Java Virtual Machine which in turn generates platform dependent instructions.
4.  Java Virtual Machine is a abstraction over the actual machine and provides its own instruction set hence its known as Virtual Machine.
5.  Java Virtual Machine is a binary and is machine dependent. For windows JVM is a EXE file, for Linux JVM a ELF file.
6.  Java Virtual Machine takes .class file as input and generates instruction pertaining to the platform.
7.  JVM code has been compiled against the Different OS and on a given platform , the JVM binary specific to the platform needs to be used on that platform.
8.  JVM input instruction set is constant across all the platforms , the OS specific instructions generated by the JVM is different for different platform.
9.  SUN JVM is written in C while the Java Compiler is written in JAVA.

 

 

 

On Ubuntu JVM file Type is

file /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=8b0e245cdb52ffc478774ec7c54577531ecc9394, stripped