Interview Q&A · Java · 4 questions in this topic
JVM, Bytecode & Class Loading — Java Interview Q&A
How source becomes bytecode, how the JVM executes it, and the difference between loading a class at compile time and finding it at runtime. Part of Core Java Basics · 294 questions in the Java bank.
What is the JIT compiler?
Answer
The Just-In-Time (JIT) compiler is part of the JVM that converts bytecode into native machine code while the program runs. Rather than compiling everything up front, it focuses on "hot" methods that execute frequently and optimises them using runtime profiling information, which lets Java approach native performance while keeping the portability of bytecode.
Key points
- 1HotSpot uses an interpreter for cold code and tiered JIT compilation for hot code.
- 2It can inline methods, remove dead code and unbox values based on observed runtime types.
- 3JIT-compiled code is discarded and recompiled as the program’s behaviour changes.
What is bytecode?
Answer
Bytecode is the instruction set stored in a compiled .class file. It is machine-independent and understood by the JVM rather than by the CPU directly. It is a compact, stack-based intermediate representation that the interpreter and JIT compiler execute.
Example
javac Hello.java # source -> bytecode (Hello.class) java Hello # bytecode -> execution by the JVM
When is ClassNotFoundException raised?
Answer
ClassNotFoundException is a checked exception thrown when the JVM cannot find a class that the running code explicitly asks for by its string name — for example Class.forName("com.example.Foo"), ClassLoader.loadClass(...), or when deserializing an object whose class is not on the classpath. It means the class could not be located at runtime even though the code compiled.
Example
try { Class<?> c = Class.forName("com.example.Missing"); } catch (ClassNotFoundException e) { // class not on the classpath }
When is NoClassDefFoundError raised?
Answer
NoClassDefFoundError is an Error (not an exception) thrown when a class that was present at compile time cannot be found or initialised at runtime. A common cause is a class that fails in its static initialiser the first time it is loaded; subsequent attempts to use it throw NoClassDefFoundError. It is usually a deployment/classpath problem rather than something to catch in application code.
Key points
- 1Unlike ClassNotFoundException, it is an Error and typically not caught.
- 2Frequently follows a previous ExceptionInInitializerError.
- 3Fixes are environmental: correct the classpath, packaging or dependency versions.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission