Is Java compiled or interpreted?
Java is both: the compiler javac turns source into bytecode before the program runs, and the JVM compiles hot bytecode into machine code while the program runs.
How it runs your code
javac does almost no optimizing. The JVM starts the program on the bytecode and watches which methods run often. It compiles those methods into machine code with a JIT compiler. HotSpot, the JVM in OpenJDK, has two JIT compilers, a first tier and a second tier, and the default uses both. With the JIT off, the JVM never makes machine code.
Does that make Java slow?
Nearly all of Java's speed comes from the JIT. With the full JIT, the class version of our program allocated about 0 bytes per call, because HotSpot saw that the Order object never left the method and removed it. The plain-function version still allocated 56 bytes per call.
What we measured
One small program, an order with items, a coupon, a discount and tax, written as an average programmer would write it. Times are nanoseconds per call.
| Setting | Class code | Plain functions |
|---|---|---|
| JIT off (-Xint) | 3,235 | 2,464 |
| First-tier JIT only | 212 | 128 |
| Second-tier JIT only | 48 | 35 |
| Full JIT (default) | 40 | 23 |
Java with the JIT off is slower than CPython on this program. Nobody runs Java that way, and that is the point: the JIT is where the speed comes from. Runs used OpenJDK 21 with JMH, three forks of five one-second iterations.
Questions
Is Java an interpreted language?
Not as a whole. javac compiles source to bytecode, and the JVM compiles hot bytecode to machine code. With the JIT off, using the -Xint flag, the JVM runs bytecode without making machine code.
Does Java compile to machine code?
javac produces bytecode. The JVM compiles hot bytecode to machine code with its JIT. GraalVM Native Image can also compile a Java program ahead of time into a native executable.
Why is Java fast if it runs on a virtual machine?
Because of the JIT. In our test the full JIT took the class version of the program from 3,235 ns to 40 ns per call.
What is the JVM?
The Java Virtual Machine runs bytecode. HotSpot is the JVM in OpenJDK, and it includes the JIT compilers.
Related
Is Kotlin compiled? · Is C# compiled? · Is JavaScript compiled? · Compiled vs interpreted · Why optimization decides speed