Search code examples
javajvmjavac

Why do we need the Java compiler when we have the JVM?


Just a question of curiosity that I came up with when I was reading the JVM introduction.

Why do we need the Java compiler when we have the universal, platform-independent Java Virtual Machine? I mean, consider Python, which has an interactive shell that reads the source code line by line and then execute it without having to compile the source code beforehand, why can't JVM be designed to be able to read .java files directly like that of Python and then execute it?

If that's not the case, can someone please explain the significance of Java compiler?


Solution

  • Java could indeed have been created where you ship source everywhere (as one typically does with JavaScript). But as a design choice, Gosling et. al. decided to ship bytecode instead, which is created from the source by the Java compiler. There are several objective reasons for doing so:

    • Bytecode is smaller than source code.
    • Bytecode is harder to reverse-engineer than source code (though only slightly).
    • Bytecode is harder to modify than source code.
    • Using bytecode means the JVM doesn't have to have the Java compiler in it (reducing footprint, which was more important in ~1995 than it is now)
    • Compiling takes non-trivial time (and non-trivial memory use). Compiling to bytecode preserves Run Everywhere(tm) without that startup impact.

    Again, though, it was just a design decision they took. Microsoft took the same decision with .Net.