11

Possible Duplicate:
Is Java a Compiled or an interpreted programming language?

Why is Java both compiled and interpreted language?

We first compiles the java program using javac(compiling) and the run the program using java(interpreting). What is the advantage of that?

Also, where does JIT role come into the picture?

Community
  • 1
  • 1
Anand
  • 20,708
  • 48
  • 131
  • 198
  • I think this answer should help http://stackoverflow.com/a/1326084/846476 – RNJ Sep 05 '12 at 18:11
  • @RNJ you're right - it's an exact dup - voting to close – Nir Alfasi Sep 05 '12 at 18:12
  • @MichaelPetrotta that's off topic but in short, I expect the OP to update the question with the solution he found and accept his own answer (in case all the other answers were not useful) - in order to "give back" to the community. – Nir Alfasi Sep 05 '12 at 18:23
  • I went through the link for which my questions is termed as duplicate.In that, there is a statement"The current version of Sun HotSpot JVM uses a technique called Just-in-time (JIT) compilation to compile the bytecode to the native instructions understood by the CPU on the fly at run time." I was under the impression that JVM is an interpreter but it suggests it further compiles the byte code. I am confused. Also it is written that it does it on the fly at runtime. Can somebody explain this also? – Anand Sep 05 '12 at 18:32
  • Can somebody please answer my comment? – Anand Sep 05 '12 at 18:59
  • @Anand: Does [this](https://stackoverflow.com/a/36394113/1835769) answer your comment? – displayName Apr 26 '19 at 19:53

3 Answers3

6

Compile once and run anywhere is one of the reasons.

JVM is OS specific. So, JVM interprets compiled .class (byte code) file and converts into machine specific instruction set.

kosa
  • 65,990
  • 13
  • 130
  • 167
6

The Java compiler typically compiles source code into an intermediate language, expressed generically as "byte code". That itself is not machine code for your native hardware, but in a sense it is "machine" code for the Java virtual machine.

The benefit of this separation is that (in theory) you can implement a VM on many different platforms, but all of them will be able to run the same compiled Java byte code.

A just-in-time compiler is part of a hypothetical VM, and actually translates bits of byte code dynamically into real, native machine code, as and when needed. This grew out of the observation that running a Java program purely in a VM was a lot slower than equivalent native code. JIT compilation has made the Java VM competitive in terms of performance when compared to natively compiled code.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2
  1. Java is "compiled" into byte code
  2. The byte code is "interpreted" as the program executes
  3. A JIT compiler and "precompile" byte code into native machine code, optimizing execution time

Here is an article giving more details about Java JIT:

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134