Grokking Java Interview Questions
Vote

0% completed

​

From Source Code to a Running Program

What happens between writing a .java file and running it?

What is bytecode, and how can you read it?

What does the JIT compiler do?

Why is Java called both compiled and interpreted?

Predict the Output

Key Takeaways

The method below computes the total of one order line in cents.

static int total(int delivery, int price, int quantity) { return delivery + price * quantity; }

No processor can execute this text. It is translated once before the program starts, and a frequently used method is translated again while the program runs. The sections that follow trace both translations. They cover the steps from a .java file to a running program, the bytecode in between, the work of the JIT compiler, and the reason why Java is called both compiled and interpreted.

What happens between writing a .java file and running it?

Level: Junior

The compiler javac translates the source file into class files, and the JVM loads these classes, checks them, and executes their bytecode. Bytecode is the instruction set of the JVM. At first the JVM interprets the instructions one by one, and later it compiles the frequently used methods to machine code.

Suppose the method is part of a class named Receipt. Two commands start the process:

javac Receipt.java java Receipt

The work happens in five steps:

  1. Compile. javac checks the syntax and the types, and it writes Receipt.class.
  2. Load. The java command starts a JVM, which finds Receipt.class and reads it.
  3. Verify. The JVM checks that the bytecode is valid, for example that no instruction treats an int as a reference.
  4. Interpret. The JVM executes the bytecode of main, and then of each method that is called.
  5. Compile again. The just-in-time compiler, called the JIT compiler, translates frequently used methods to machine code in the background.

Steps 2 and 3 apply to the other classes of the program as well, and each one is usually loaded when the program first needs it.

Receipt.java is compiled by javac to Receipt.class before the program starts. While the program runs, the JVM loads and verifies the class, the interpreter executes its bytecode, and the JIT compiler translates frequently used methods to machine code.
Receipt.java is compiled by javac to Receipt.class before the program starts. While the program runs, the JVM loads and verifies the class, the interpreter executes its bytecode, and the JIT compiler translates frequently used methods to machine code.

Look at the two panels. The left panel happens once, usually on the machine of a developer or a build server. The right panel happens in each run, and the class file connects the two.

Common mistake: Saying that javac produces machine code. The output of javac is bytecode, and the JIT compiler produces machine code later, inside the running JVM.

Follow-up questions

1. How many class files does one source file produce?

<details><summary>Show answer</summary>

It produces at least one class file for each class, interface, enum, and record in it, including nested and anonymous ones. We compiled a file that declares a class with a nested class, a nested record, and an anonymous class, and javac wrote four class files. A lambda in the same file added none. The compiler can also add a class of its own, and it did so in our test for a switch on an enum from another file.

</details>

2. Can you run a source file without calling javac?

<details><summary>Show answer</summary>

Yes, since Java 11 the command java Receipt.java compiles and runs a single source file. The launcher compiles the file in memory, writes no class file, and runs the bytecode in the same JVM. Since Java 22, it also compiles the other source files that the program uses. This form suits small programs and scripts.

</details>

What is bytecode, and how can you read it?

Level: Mid-level

Bytecode is a sequence of small instructions for an imaginary processor that computes with a stack, and the command javap -c prints it. The JVM implements this processor in software. Each instruction starts with one byte that names the operation.

The compiled method total contains six instructions. The output below is from javap -c Receipt, shortened to this method.

static int total(int, int, int); Code: 0: iload_0 1: iload_1 2: iload_2 3: imul 4: iadd 5: ireturn

The number before each instruction is its position in bytes. The letter i at the start of these six names means that the instruction works on int values. The parameters are stored in numbered slots called local variables: delivery is 0, price is 1, and quantity is 2.

The instructions compute on the operand stack, a small stack that belongs to the frame of the method call. An iload instruction pushes a local variable onto it. The instructions imul and iadd remove the top two values and push the product or the sum. Finally, ireturn returns the top value to the caller.

The program below is a tiny interpreter for these six instructions. It prints the stack after each step, with the top value first, for a delivery of 200 cents and three apples at 120 cents.

Java
Java

. . . .
iload_0 -> stack [200] iload_1 -> stack [120, 200] iload_2 -> stack [3, 120, 200] imul -> stack [360, 200] iadd -> stack [560] result = 560
The operand stack after each instruction. iload_0 pushes 200, iload_1 pushes 120, iload_2 pushes 3, imul replaces 3 and 120 with 360, iadd replaces 360 and 200 with 560, and ireturn returns 560.
The operand stack after each instruction. iload_0 pushes 200, iload_1 pushes 120, iload_2 pushes 3, imul replaces 3 and 120 with 360, iadd replaces 360 and 200 with 560, and ireturn returns 560.

Notice the column for imul. The source text puts the multiplication after the addition sign, but the bytecode multiplies first. The compiler has already applied operator precedence.

Common mistake: Expecting the local variables of a method to appear by name in javap -c. The instructions use slot numbers. By default, javac does not store the names of local variables in the class file.

Follow-up questions

1. What is the constant pool of a class file?

<details><summary>Show answer</summary>

It is a numbered table of names, strings, and larger numbers to which the class refers. An instruction refers to an entry by its number. In the main method of Receipt, the call to total is invokestatic #13, and entry 13 names the class, the method, and the types (III)I. The command javap -v prints the whole table.

</details>

2. Which instructions call a method?

<details><summary>Show answer</summary>

Five instructions do: invokestatic, invokevirtual, invokeinterface, invokespecial, and invokedynamic. The first four call a static method, a method chosen by the class of the object, a method of an interface, and a constructor or superclass method. The fifth lets code written in Java choose the target at run time, and javac uses it for lambdas.

</details>

What does the JIT compiler do?

Level: Senior

The JIT compiler translates frequently executed methods from bytecode to machine code while the program runs, and it uses measurements of that run to optimize them. These measurements are called the profile. They include how often each branch was taken, and which classes the objects at a method call had.

HotSpot has two JIT compilers. C1 compiles quickly and produces simple code. C2 compiles more slowly and produces faster code. Using both in sequence is called tiered compilation, and it has five levels:

LevelCodeCollects a profile
0InterpreterCounters, and a profile in some cases
1C1, full optimizationNo
2C1Counters only
3C1Yes
4C2No, it uses the profile

A method usually moves from level 0 to 3 to 4. The log below is from a loop that calls total one million times. The JVM option -Xlog, with the tags jit and compilation at the level debug, prints it. It is shortened to the lines for total.

77 3 HotLoop::total (6 bytes) 78 4 HotLoop::total (6 bytes) 77 3 HotLoop::total (6 bytes) made not entrant

The first number identifies the compilation, and the second is the level. The last line means that new calls no longer enter the level 3 code, because the level 4 code has replaced it.

By default, 200 calls are enough for HotSpot to request level 3, and 5,000 further calls are enough for level 4. Both counts include only calls, and a method with loops can qualify earlier. The program below applies these two thresholds to one million calls.

Java
Java

. . . .
call 200: interpreter -> C1 code with profiling call 5200: C1 code with profiling -> C2 code after 1000000 calls: C2 code

The program is a model. The real JVM reads the counters at intervals, compiles in the background, and raises the thresholds when many methods wait for a compiler. It also skips the second threshold for a method with nothing to measure, and total, which has no branches and no calls, is such a method. The period before the important methods reach their final level is called warm-up.

The most important optimization is inlining, which replaces a method call with the body of the called method. The call itself disappears, and the compiler can then optimize both methods together. By default, C2 considers a method of up to 35 bytes of bytecode for inlining. At a frequent call, the limit is 325 bytes on the machine used here.

Common mistake: Measuring a method with a short loop and a clock. The first calls run in the interpreter, so such a measurement mixes several levels of code and says little about the program after warm-up.

Follow-up questions

1. What is deoptimization?

<details><summary>Show answer</summary>

Deoptimization returns a running method from compiled code to the interpreter. C2 makes assumptions from the profile, for example that a call always reaches the same class. The machine code contains a check for such an assumption. When the check fails, the JVM continues in the interpreter. It can also discard that code and later compile the method again with the new profile.

</details>

2. Why does the JVM not compile every method before it starts?

<details><summary>Show answer</summary>

Compilation costs time and memory, and no profile exists before the program runs. Many methods run once or never, so compiling them would delay the start without any benefit. A compiler that works before the first run also cannot know which branches and which classes are frequent.

</details>

Why is Java called both compiled and interpreted?

Level: Mid-level

Java source code is compiled to bytecode, and the bytecode is then interpreted, with the frequent parts compiled to machine code during the run. Both words are correct, and each describes a different step.

StepWhenInputOutput
javacBefore the runSource textBytecode
InterpreterDuring the runBytecodeNone, it executes directly
JIT compilerDuring the runBytecode and profileMachine code in memory

Splitting the work in this way has a cost and a benefit. A program starts slower than one that is already machine code, because classes are loaded and interpreted first. In return, one class file runs on every platform, and the machine code is made for the processor and the data of the current run.

Some tools move work to an earlier time, which is called ahead-of-time compilation. GraalVM Native Image compiles a whole application to an executable file. Project Leyden added a cache to Java 24 that holds classes already loaded and linked in an earlier run.

Common mistake: Saying that Java is slow because it is interpreted. After warm-up, the frequently used methods of a long-running program are executed as optimized machine code.

Follow-up questions

1. Can HotSpot run with only the interpreter?

<details><summary>Show answer</summary>

Yes, the option -Xint disables both JIT compilers. The command java -Xint -version then reports "interpreted mode" where it normally reports "mixed mode". The results of a program do not change, but a program that computes a lot becomes much slower. The option helps to find out whether a failure is caused by compiled code.

</details>

2. Does javac optimize the code?

<details><summary>Show answer</summary>

It does very little, and it leaves almost all optimization to the JIT compiler. One exception is required by the language: javac computes constant expressions itself. The expression 60 * 60 * 24 becomes the single number 86400 in the class file. The JIT compiler knows the processor and the profile, so it can make better decisions about everything else.

</details>

Predict the Output

Some of the concatenations below are computed by javac, and one is computed while the program runs. Write down the five lines before you press Run.

Java
Java

. . . .
<details><summary>Show answer</summary>

The program prints true, false, true, order 10001, and order 1001. The expression "man" + "go" contains only literals, so javac stores the result "mango" in the class file, and equal string constants refer to one object. The expression part + "go" contains a variable that is not final, so the JVM creates a new string at run time. The operator == compares references and returns false, while equals() compares characters and returns true. The operator + works from left to right, so "order " + 1000 + 1 appends 1000 and then 1. The parentheses in the last line add the numbers first.

</details>

Key Takeaways

  • javac translates source text to bytecode, and the JVM loads, verifies, and executes it.
  • Bytecode computes with an operand stack, and javap -c prints its instructions.
  • HotSpot interprets first, compiles with C1 to collect a profile, and then compiles with C2.
  • Inlining removes a method call and allows further optimization.
  • Deoptimization returns a method to the interpreter when an assumption fails.
  • javac computes constant expressions and leaves other optimization to the JIT compiler.

Step 2 of the first list, loading a class, was described in a single sentence. The lesson Class Loading and Initialization divides it into smaller steps and shows when each one runs.

Reading Progress

0%


Vote for new content

On This Page

What happens between writing a .java file and running it?

What is bytecode, and how can you read it?

What does the JIT compiler do?

Why is Java called both compiled and interpreted?

Predict the Output

Key Takeaways