I'm learning Java and the following things are a bit confusing for me. What I understood is:
Java Compiler → The Java compiler just converts
.javaprograms into.classfiles, which means converting our source code into bytecode (it is a list of op codes for the virtual machine (JVM) which makes Java platform-independent).Java Interpreter → merely "interprets" the code and does not transform it into native machine code. It executes each and every instruction of the byte code one-by-one as a command and carries it out, regardless how many time the same instruction occurs. That's why it's slow and Java introduces the JIT concept.
JIT Compiler → This also comes into play at execution time. The JIT compiler is able to improve performance by caching results of blocks of code that have been translated – compared to simply re-evaluating every line or operand in the bytecode each time it occurs.
Now I have several questions:
As my physical processor understands only native machine code, how does a Java program get executed using the JVM's interpreter? The interpreter doesn't convert bytecode to native machine code. Until and unless someone places the machine code into memory, the physical processor won't be able to execute it.
Supposing that somehow, the interpreter also converts bytecode to native machine code then a "block of code execution with caching (JIT) and line-by-line execution (interpreter)" is the only thing that differentiates the JIT and the interpreter?
If, at execution time, a JIT compiler translates bytecode to native machine code (for executing the program), why doesn't Java use ahead-of-time compilation? After generating the JVM-dependent bytecode (which in turn makes Java platform-independent), we could bring it to the target machine where we want to execute it and just translate it to native machine code (creating an
.exeor.outfile as is the case with C compilation). This could be possible because we have a specific JVM on every system. This would be much faster than using JIT compilation as it takes some time compiling and loading the program. It will still be platform-independent by just distributing bytecode (generated before the final translation from bytecode to machine code).