Search code examples
javajvm

How does Java solve portability?


The Java compiler converts Java code to bytecode and then the JVM converts the bytecode to machine instructions. As far as I have understood, JVMs are built for different platforms (processor + OS). Then how can we say that Java is platform independent? Ultimately, we require a JVM which is platform dependent?


Solution

  • As you have mentioned yourself, the JVM is platform-dependent. That's it - the JVM is platform-dependent, but not Java. After all, the JVM needs to be run in someway inside the native machine, so it must have to be specific to that platform.

    Java is portable in the sense that the compiled code is portable. For example, if you compare with C, both the C and Java source codes are portable, that means both of them provide source code portability. Once you have a source code written in a Windows PC, you can transfer that exact code in another Linux machine and both Java and C code will compile and run fine in both machines.

    But, what about object code portability?

    We know, when we compile a C code, it produces the machine readable object code. So, if you compile a C source code from one machine, then that object code may not be run from another machine if they are not compatible. But, in case of Java, if you compile a Java source code to bytecode from one machine, that bytecode can be run in any machine that runs the JVM.

    Another interesting fact, by successful compilation of a Java source code, we are also producing a bytecode for some unknown future CPU which doesn't even exist as JVM acts as a kind of virtual CPU.