Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bytecode interpreter

Tags:

java

i know that java programs are first compiled and a bytecode is generated which is platform independent. But my question is why is this bytecode interpreted in the next stage and not compiled even though compilation is faster than interpretation in general??

like image 435
isha Avatar asked Sep 14 '25 04:09

isha


2 Answers

You answered your own question. Byte code is platform independent. If the compiled code was executed then it would not work on every OS. This is what C does and it is why you have to have one version for every OS.

As others have suggested, the JVM does actually compile the code using JIT. It is just not saved anywhere. Here is a nice quote to sum it up

In a bytecode-compiled system, source code is translated to an intermediate representation known as bytecode. Bytecode is not the machine code for any particular computer, and may be portable among computer architectures. The bytecode may then be interpreted by, or run on, a virtual machine. The JIT compiler reads the bytecodes in many sections (or in full rarely) and compiles them interactively into machine language so the program can run faster

like image 187
Amir Raminfar Avatar answered Sep 16 '25 18:09

Amir Raminfar


The Java bytecode normally is compiled via Just-In-Time (JIT) compilation.

So you still end up with fully compiled native code being executed, the only difference is that this native code is generated by the JVM at runtime, rather than being statically generated at the time the source code is compiled (as would happen with C/C++).

This gives Java two big advantages:

  • By delaying the compilation until runtime, the bytecode remains fully portable across platforms
  • In some cases the JIT compiler can actually generate more optimised native code because it is able to exploit statistics gathered by examining the execution parths of the code at runtime.

The downside, of course, is that the JIT compiler needs to do it's work at application start-up, which explains why JVM applications can have a slightly long start-up time compared to natively compiled apps.

like image 37
mikera Avatar answered Sep 16 '25 16:09

mikera