230

In the past I have used C++ as a programming language. I know that the code written in C++ goes through a compilation process until it becomes object code "machine code".

I would like to know how Java works in that respect. How is the user written Java code run by the computer?

1
  • 18
    C++ could be interpreted. There are a few C interpreter out there. Commented Aug 25, 2009 at 5:36

9 Answers 9

288

Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.

Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)

It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.

To summarize, depending on the execution environment, bytecode can be:

  • compiled ahead of time and executed as native code (similar to most C++ compilers)
  • compiled just-in-time and executed
  • interpreted
  • directly executed by a supported processor (bytecode is the native instruction set of some CPUs)
4
  • 26
    Actually, some HotSpot JVMs start out by interpreting bytecodes, and only compiles them to native code after they have figured out what is worth compiling, and gathered some stats on how the code is being run; e.g. to figure out the most common path taken in each conditional branch.
    – Stephen C
    Commented Aug 25, 2009 at 4:51
  • 2
    Hence the term 'Hotspot' :) It does it to what is running often, to gain an optimisation.
    – Noon Silk
    Commented Aug 25, 2009 at 4:53
  • 4
    You can switch the interpreter off in HotSpot with -Xcomp. Worth trying on an application to see what a bad idea it is. Commented Aug 25, 2009 at 5:33
  • 1
    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
    Commented Sep 5, 2012 at 18:41
134

enter image description here

Code written in Java is:

  • First compiled to bytecode by a program called javac as shown in the left section of the image above;
  • Then, as shown in the right section of the above image, another program called java starts the Java runtime environment and it may compile and/or interpret the bytecode by using the Java Interpreter/JIT Compiler.

When does java interpret the bytecode and when does it compile it? The application code is initially interpreted, but the JVM monitors which sequences of bytecode are frequently executed and translates them to machine code for direct execution on the hardware. For bytecode which is executed only a few times, this saves the compilation time and reduces the initial latency; for frequently executed bytecode, JIT compilation is used to run at high speed, after an initial phase of slow interpretation. Additionally, since a program spends most time executing a minority of its code, the reduced compilation time is significant. Finally, during the initial code interpretation, execution statistics can be collected before compilation, which helps to perform better optimization.

6
  • Is it due to cached bytecode that Java uses a lot of memory? Commented Jul 2, 2017 at 23:22
  • 3
    @sedulam: A 'lot of memory' is a fuzzy statement. Java's memory management is pretty straightforward - The three generations is what the JVM uses for creation and maintenance of its objects. This another SO answer may be useful for you. Commented Jul 2, 2017 at 23:27
  • With above explanation, theoretically, C++ compiled code shall always be faster than logically similar java code since there will always be some portion of .class file that JIT decides not to transform to machine code. In other words, java can never catch bare metal execution speed that C++ has demonstrated. Is this correct assumption?
    – DevdattaK
    Commented Nov 26, 2017 at 17:37
  • 1
    @DevdattaK your assumption is discussed in this wiki page en.m.wikipedia.org/wiki/Java_performance?wprov=sfla1 In short, it is not always true. Commented Oct 1, 2018 at 11:56
  • 1
    @PedroGordo - Actually no. The real reason is that Java is garbage collected with all objects allocated in the GC'd heap. Garbage collectors need a lot of (extra) memory in order to run efficiently. It is a trade-off. (You can run the GC more often and use less space, but you spend more CPU cycles on running the GC. And since the cost of running the GC is proportional to the amount of non-garbage ... you lose.) The memory to hold the bytecodes is a tiny proportion of the total memory usage of a typical Java application.
    – Stephen C
    Commented Aug 2, 2022 at 12:01
79

The terms "interpreted language" or "compiled language" don't make sense, because any programming language can be interpreted and/or compiled.

As for the existing implementations of Java, most involve a compilation step to bytecode, so they involve compilation. The runtime also can load bytecode dynamically, so some form of a bytecode interpreter is always needed. That interpreter may or may not in turn use compilation to native code internally.

These days partial just-in-time compilation is used for many languages which were once considered "interpreted", for example JavaScript.

4
  • 9
    Also, Google's V8 JavaScript Execution Engine doesn't just do partial just-in-time compilation. It always compiles to native code, in fact, V8 doesn't even have an interpreter. It has only the compiler (similar to Maxine, but unlike Maxine V8 has only one compiler). All three of these examples (GCJ, Maxine and V8) prove your point even more strongly: there is no such thing as an interpreted language or a compiled language. A language isn't interpreted or compiled. A language just is (That's actually a quote by Shriram Krishnamurthi). Commented Aug 25, 2009 at 14:08
  • 5
    Why are you talking about javascript in a java question? Commented Jan 24, 2015 at 11:37
  • 2
    @KorayTugay Just as an example. I certainly don't want to imply that Java and Javascript have anything in common other than the first four letters of their name.
    – starblue
    Commented Nov 7, 2017 at 9:50
  • Would at least a difference in interpreted and compiled language not mean that a compiled language binary cannot have it's execution flow changed at any time, while a interpreted language is very obedient to some of the current workings of functions? Libraries in C is option while in other languages you can't have an array object without a C binary extension that can be updated or be completely different code on another platform. The Scripting language will be able to run on both while the compiled language would need a different binary to be run Commented Jan 16, 2018 at 18:18
58

Java is compiled to bytecode, which then goes into the Java VM, which interprets it.

7
  • 39
    ... but not strictly accurate.
    – Stephen C
    Commented Aug 25, 2009 at 4:46
  • 4
    JVM might choose not to "interpret" bytecode. It can JIT compile it and execute it directly. Commented Aug 25, 2009 at 4:47
  • 1
    JIT isn't technically executing it directly. It's just remembering how it was executed.
    – cletus
    Commented Aug 25, 2009 at 4:49
  • Mehrdad: Agreed, I didn't describe the possibly JIT operations here, as I consider that up to the JVM, and I was keeping my answer simple anyway :)
    – Noon Silk
    Commented Aug 25, 2009 at 4:52
  • 7
    cletus: After JIT, it'll be directly executed. JIT is reading a piece of bytecode (e.g. a complete method) and compiling down to machine code and jumping to it. Commented Aug 25, 2009 at 4:53
19

Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.

14

Kind of both. Firstly java compiled(some would prefer to say "translated") to bytecode, which then either compiled, or interpreted depending on mood of JIT.

2
  • 43
    That's an advanced piece of software, to have developed moods :)
    – Thorarin
    Commented Aug 25, 2009 at 5:05
  • 7
    The JIT is indeed a very sophisticated piece of software, that can do optimizations based on runtime information (like a profiler), which an ahead-of-time compiler can't do (because it doesn't have information on the runtime behaviour of a program ahead of time). But it probably doesn't really have moods... :-)
    – Jesper
    Commented Aug 25, 2009 at 7:25
11

Java does both compilation and interpretation,

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then interprets / executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .class.

When the program is to be run, the bytecode is converted the bytecode may be converted, using the just-in-time (JIT) compiler. The result is machine code which is then fed to the memory and is executed.

Javac is the Java Compiler which Compiles Java code into Bytecode. JVM is Java Virtual Machine which Runs/ Interprets/ translates Bytecode into Native Machine Code. In Java though it is considered as an interpreted language, It may use JIT (Just-in-Time) compilation when the bytecode is in the JVM. The JIT compiler reads the bytecodes in many sections (or in full, rarely) and compiles them dynamically into machine code so the program can run faster, and then cached and reused later without needing to be recompiled. So JIT compilation combines the speed of compiled code with the flexibility of interpretation.

An interpreted language is a type of programming language for which most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions. The interpreter executes the program directly, translating each statement into a sequence of one or more subroutines already compiled into machine code.

A compiled language is a programming language whose implementations are typically compilers (translators that generate machine code from source code), and not interpreters (step-by-step executors of source code, where no pre-runtime translation takes place)

In modern programming language implementations like in Java, it is increasingly popular for a platform to provide both options.

3
  • Should be “the bytecode may be converted” rather than “is converted”. The Java specs define bytecode. Whether that bytecode is run (a) directly in hardware, (b) through an interpreter, (c) compiled beforehand, or (d) partially compiled on-the-fly at runtime are all left as implementation details. Note that all four of those options have indeed been used by various real-world Java implementations. Commented Apr 4, 2018 at 22:29
  • Thanks for pointing this out. So what happens if the bytecode is not converted to machine code ? I can think of a scenario where the bytecode is the native instruction set for some processors and then there is no need for a conversion. Or am I missing something.
    – prime
    Commented Apr 5, 2018 at 3:45
  • Click the link I gave for Jazelle DBX (Direct Bytecode eXecution) technology, where a subset of JVM bytecode is the native machine instructions of the CPU (kinda-sorta). Without that, you get machine code generated from bytecode (a) from the interpreter (on the fly), (b) from the compiler ahead of time, or (c) on-the-fly with a just-in-time compiler (interpreted at first, and then sometimes compiled and cached during execution). Commented Apr 5, 2018 at 4:49
-3

Java is a byte-compiled language targeting a platform called the Java Virtual Machine which is stack-based and has some very fast implementations on many platforms.

2
  • 1
    What does "byte-compiled" mean?
    – Jesper
    Commented Aug 25, 2009 at 7:25
  • 2
    @Jesper: "Byte-compiled" usually means "compiled to bytecode". "Bytecode" is a general term that covers any sort of non-textual intermediate code (generally not machine-executable). Commented Aug 27, 2009 at 5:07
-3

Quotation from: https://blogs.oracle.com/ask-arun/entry/run_your_java_applications_faster

Application developers can develop the application code on any of the various OS that are available in the market today. Java language is agnostic at this stage to the OS. The brilliant source code written by the Java Application developer now gets compiled to Java Byte code which in the Java terminology is referred to as Client Side compilation. This compilation to Java Byte code is what enables Java developers to ‘write once’. Java Byte code can run on any compatible OS and server, hence making the source code agnostic of OS/Server. Post Java Byte code creation, the interaction between the Java application and the underlying OS/Server is more intimate. The journey continues - The enterprise applications framework executes these Java Byte codes in a run time environment which is known as Java Virtual Machine (JVM) or Java Runtime Environment (JRE). The JVM has close ties to the underlying OS and Hardware because it leverages resources offered by the OS and the Server. Java Byte code is now compiled to a machine language executable code which is platform specific. This is referred to as Server side compilation.

So I would say Java is definitely a compiled language.