What actually makes Java platform independent, and where does the platform-specific part of the system really live?
Java is platform independent because your source code is turned into an intermediate bytecode format, and not into machine instructions for one particular processor and operating system. The compiler javac produces class files, and the specification of the Java Virtual Machine describes those files byte for byte, so a class file produced on Windows is exactly the same as one produced on Linux or on macOS.
When the program runs, the JVM on that machine either interprets the bytecode or compiles it into native instructions for the local processor with a method called just in time compilation.
The platform specific part therefore lives entirely inside the JVM, which is a native program that talks to the operating system. It is the JVM that knows how to open a socket, start another process or read a file. Your bytecode holds no such knowledge at all. It only makes calls into the Java class library, and the native methods inside that library are the layer that finally reaches the operating system.
public class Main {
public static void main(String[] args) {
// The source has no system specific calls in it at all.
// All of the platform knowledge lives in the JVM and the class library.
System.out.println("os.name : " + System.getProperty("os.name"));
System.out.println("os.arch : " + System.getProperty("os.arch"));
System.out.println("file.sep : " + System.getProperty("file.separator"));
System.out.println("jvm : " + System.getProperty("java.vm.name"));
System.out.println("class file : CA FE BA BE, the same bytes on every platform");
}
}
There are two honest warnings to give. The portability is at the bytecode level and not at the source level. The same bytecode runs everywhere, but the same source code may not compile everywhere if it reaches for platform specific APIs. And the JVM itself is not portable, because it is a native program, so you still need a JVM build for every operating system and processor that you want to support.
The next question in this topic looks at how to keep the platform decision out of your own code.