Java / JVM Architecture (Java21) Interview questions
1. What is the Java Virtual Machine (JVM)?
The Java Virtual Machine (JVM) is the runtime engine that loads compiled .class files, verifies their bytecode, and executes it on the underlying operating system and hardware. It sits between compiled bytecode and the native machine, which is exactly what gives Java its "write once, run anywhere...
2. What are the main components of JVM architecture?
JVM architecture breaks down into a small set of subsystems that work together to run a .class file: the Class Loader Subsystem , the Runtime Data Areas , and the Execution Engine , plus the native bridge that connects it to the platform. Class Loader Subsystem - loads, links, and initializes cla...
3. What is the Class Loader subsystem in JVM?
The Class Loader subsystem is the part of the JVM responsible for locating a class's bytecode and bringing it into the runtime, in three ordered phases: loading , linking , and initialization . Loading reads the .class file bytes (from the classpath, a JAR, or a network location) and creates a co...
4. What are the types of class loaders in JVM?
The JVM uses a small hierarchy of class loaders, each responsible for a different part of the classpath, and each (except the Bootstrap loader) has a parent it can delegate to. Class Loader Loads Bootstrap ClassLoader Core JDK classes ( java.lang.* , java.util.* ) from the JDK's own modules, impl...
5. What is the Runtime Data Area in JVM?
The Runtime Data Areas are the memory regions the JVM sets up to run a program, created when the JVM starts (or per thread) and torn down when the JVM, or that thread, exits. Area Shared or per-thread? Method Area Shared across all threads Heap Shared across all threads JVM Stack Per-thread PC Re...
6. What is the Method Area in JVM?
The Method Area is a shared memory region that stores per-class structures: the runtime constant pool, field and method data, method bytecode, and static variables. Every loaded class has exactly one entry here, created during the loading phase and populated further during linking and initializat...
7. What is the Heap memory in JVM?
The Heap is the shared runtime area where every object and array created with new actually lives, regardless of which thread created it. It is divided generationally into a Young Generation (Eden plus two Survivor spaces) for newly created objects, and an Old (Tenured) Generation for objects that...
8. What is the JVM Stack?
The JVM Stack is a per-thread memory area holding a stack of frames , one for every method currently being executed by that thread. Each frame stores the method's local variables array, its operand stack for intermediate computation, and a reference back to the constant pool of its class for reso...
9. What is the PC (Program Counter) Register?
The PC Register is a small, per-thread register that holds the address of the JVM instruction the thread is currently executing. As a thread steps through bytecode, the PC Register is updated after every instruction so execution can resume at the right place, which matters particularly when a thr...
10. What are Native Method Stacks?
Native Method Stacks are per-thread memory areas used specifically when a thread executes a native (non-Java) method, typically C or C++ code reached through the Java Native Interface (JNI) . They exist separately from the regular JVM Stack because native code frames follow the calling convention...
11. What is the Execution Engine in JVM?
The Execution Engine is the component that actually runs the bytecode sitting in the runtime data areas, turning it into real behavior on the CPU. It is made up of three cooperating parts: an Interpreter that executes bytecode instruction by instruction, a JIT compiler that compiles frequently ru...
12. What is the Interpreter in the execution engine?
The Interpreter reads compiled bytecode one instruction at a time and executes it directly, without producing any native machine code first. This makes program startup fast, since there is no compilation delay, but it makes repeated execution of the same code slower - every time a loop or frequen...
13. Define JVM, JRE, and JDK?
These three terms describe increasingly larger packages, each one containing the one before it. Term What it is JVM The runtime engine that executes bytecode; it does not include libraries or development tools. JRE JVM plus the core class libraries needed to run (but not build) Java applications....
14. What is bytecode in Java?
Bytecode is the platform-independent instruction set that the javac compiler produces from Java source code and stores in .class files. It is not tied to any specific CPU - instead, any JVM that implements the JVM specification can load and run it, which is what makes a compiled class portable ac...
15. What is the purpose of the Java Native Interface (JNI)?
The Java Native Interface (JNI) lets Java code call functions written in native languages like C or C++, and lets native code call back into Java objects and methods. It is used when an application needs to reach platform-specific APIs the JDK does not expose, reuse an existing native library, or...
16. What are the types of garbage collectors available in Java 21?
Java 21 ships five HotSpot garbage collectors that a developer can select with a command-line flag. Collector Enable flag Focus Serial GC -XX:+UseSerialGC Single-threaded, small heaps Parallel GC -XX:+UseParallelGC Multi-threaded, throughput G1 GC -XX:+UseG1GC Balanced pause/throughput (default) ...
17. What is the purpose of the Just-In-Time (JIT) compiler?
The JIT compiler exists to remove the repeated-interpretation cost of "hot" bytecode - methods or loops that execute far more often than the rest of the program. HotSpot profiles execution counts at runtime and, once a method crosses an invocation threshold, compiles its bytecode directly into na...
18. What are the types of JIT compilers in HotSpot JVM?
HotSpot ships two distinct JIT compilers, historically tied to the "client" and "server" JVM builds, though modern JVMs use both together. Compiler Characteristics C1 (Client) Compiles quickly, applies lighter optimizations, favors fast warm-up. C2 (Server) Compiles slower, applies aggressive opt...
19. What is Metaspace, and how does it differ from PermGen?
Metaspace is the HotSpot implementation of the Method Area used since Java 8, storing class metadata such as the runtime constant pool, field/method data, and bytecode. It replaced PermGen ("Permanent Generation"), which lived inside the fixed-size heap in Java 7 and earlier and was a frequent so...
20. Why is the Metaspace stored in native memory instead of the heap?
Moving class metadata out of the heap and into native memory decouples its size from the fixed heap boundaries that caused PermGen's tight, hard-to-tune limits. Because Metaspace lives in native memory, it can grow and shrink dynamically based on actual class-loading demand, rather than requiring...
21. How does class loading follow the delegation model?
When a class loader is asked to load a class, it does not immediately try to load it itself - it first delegates the request up to its parent class loader. Following the hierarchy described earlier, an Application ClassLoader request first goes to the Platform ClassLoader, which in turn defers to...
22. Why do we use the parent delegation model in class loading?
Parent delegation exists mainly for security and consistency , not performance. Security-wise, it stops untrusted or application-supplied code from shadowing core classes - if you defined your own java.lang.String , delegation ensures the Bootstrap ClassLoader's trusted version is still the one f...
23. What is the difference between Class.forName() and ClassLoader.loadClass()?
Both methods load a class dynamically by name, but they differ in how much of the class lifecycle they trigger and which loader they default to. Class.forName(name) loader.loadClass(name) Loads, links, and initializes the class by default Only loads (and links); does not initialize Uses the calle...
24. What happens when a NoClassDefFoundError occurs versus ClassNotFoundException?
These sound similar but represent different failure moments in the class lifecycle. ClassNotFoundException NoClassDefFoundError Checked exception Unchecked Error Thrown by dynamic loading calls like Class.forName() or loadClass() when the class truly cannot be found Thrown by the JVM when a class...
25. Explain the lifecycle of a class in JVM (loading, linking, initialization)?
A class moves through three ordered stages before any of its code can run, all triggered lazily on first active use. flowchart TD A[Loading] --> B[Linking] B --> B1[Verification] B --> B2[Preparation] B --> B3[Resolution] B1 --> C[Initialization] B2 --> C B3 --> C C --> D[Use: instances created, ...
26. Explain the internal working of the linking phase (verification, preparation, resolution)?
Verification runs the bytecode through the JVM's structural checks - stack map validation, type safety of operations, and ensuring branches only jump to valid instructions - so that malformed or maliciously crafted class files are rejected before they can run. Preparation then allocates memory fo...
27. What is the difference between Young Generation and Old Generation in heap memory?
The heap is split generationally based on how long objects tend to live, which lets the collector treat them differently. Young Generation Old (Tenured) Generation Holds newly created objects (Eden + two Survivor spaces) Holds objects that survived enough Young GC cycles Collected frequently via ...
28. Why does the JVM use generational garbage collection?
Generational collection is built on an empirical observation called the weak generational hypothesis : most objects die young, and the few that survive tend to live a very long time. By segregating new objects into a small Young Generation, the collector can run frequent, cheap Minor GCs that onl...
29. Explain the execution flow of a Minor GC vs Major GC?
A Minor GC collects only the Young Generation, while a Major GC , often triggered together with what's called a Full GC, also collects the Old Generation. flowchart TD A[Object allocated in Eden] --> B{Eden fills up} B --> C[Minor GC: copy live objects Eden to Survivor] C --> D{Object survives en...
30. What is the difference between Serial GC and Parallel GC?
Both are older, simpler stop-the-world collectors, but they differ in how many threads do the collection work. Serial GC Parallel GC Single thread performs the entire collection Multiple threads collect Young and Old generations in parallel -XX:+UseSerialGC -XX:+UseParallelGC Best for small heaps...
31. How does G1 GC organize heap memory into regions?
Unlike Serial or Parallel GC, which use one large contiguous Young space and one large contiguous Old space, G1 ("Garbage First") GC divides the whole heap into many equally-sized regions , typically between 1MB and 32MB depending on heap size. Each region is dynamically labeled as Eden, Survivor...
32. What is Generational ZGC introduced in Java 21, and how does it differ from G1?
Generational ZGC , finalized in Java 21 via JEP 439 , made ZGC's generational mode the default, replacing the earlier single-generation ZGC as the out-of-the-box behavior when -XX:+UseZGC is set. Like G1, it now separates young and old objects to exploit the weak generational hypothesis, collecti...
33. Why should you choose ZGC over G1 for low-latency applications?
Choose ZGC when an application has a hard latency ceiling, such as a trading system or a real-time bidding service, where even occasional pauses in the tens-of-milliseconds range, which G1 can hit under heap pressure, would violate a service-level requirement. ZGC's concurrent marking and relocat...
34. What is the difference between stop-the-world pauses and concurrent GC phases?
Garbage collectors mix two kinds of work, and the balance between them is what defines a collector's pause-time behavior. Stop-the-world (STW) Concurrent All application ("mutator") threads are paused Application threads keep running alongside GC work Used when the heap must be in a guaranteed-co...
35. How does escape analysis enable stack allocation optimizations?
Escape analysis is a C2 JIT optimization that determines whether an object created inside a method can ever be referenced, or "escape," outside that method or thread. void compute () { // 'point' never leaves this method or gets stored anywhere else Point point = new Point( 1 , 2 ); int sum = poi...
36. What is the JVM Code Cache, and why can it become a problem?
The Code Cache is the native-memory region where the JIT compiler stores the compiled native machine code it generates for hot methods, separate from both the heap and Metaspace. It has a fixed maximum size controlled by -XX:ReservedCodeCacheSize , with tiered compilation enabled the default is t...
37. How does tiered compilation work in HotSpot JVM?
Tiered compilation , the default since Java 8, runs a method through up to five execution levels instead of jumping straight from interpreted to fully optimized code. Level What runs 0 Interpreter 1-3 C1, with increasing amounts of profiling instrumentation 4 C2, fully optimized using data gather...
38. What are OSR (On-Stack Replacement) compilations, and when do they happen?
On-Stack Replacement (OSR) lets the JVM swap a method that is currently executing in the interpreter for a JIT-compiled version, mid-execution, without waiting for that method call to return first. It exists specifically for long-running loops: a method's normal invocation counter only increments...
39. Explain the internal working of the JVM stack frame during method invocation?
Each time a method is invoked, the JVM pushes a new frame onto the calling thread's JVM Stack, and pops it off when the method returns or throws. Frame component Purpose Local variable array Stores method parameters and local variables, indexed by slot number Operand stack Working space for inter...
40. What is the difference between StackOverflowError and OutOfMemoryError?
Both are serious runtime failures, but they come from exhausting different memory areas for different reasons. StackOverflowError OutOfMemoryError The per-thread JVM Stack runs out of space Heap, Metaspace, or native memory runs out of space Usual cause: deep or infinite recursion Usual causes: m...
41. How do Virtual Threads (Project Loom) change the JVM's threading model in Java 21?
Virtual threads , finalized in Java 21 via JEP 444 , add a second kind of Thread that the JVM itself schedules, instead of mapping every Thread 1:1 onto a heavyweight OS thread. A virtual thread's stack and execution state are represented as a JVM-managed continuation stored on the heap, which st...
42. Why doesn't a blocked virtual thread block its carrier platform thread?
When a virtual thread calls a blocking operation the JDK has been updated to recognize, most blocking I/O, Thread.sleep , and many java.util.concurrent locks, the JDK's internal code, rather than simply blocking the OS thread, unmounts the virtual thread's continuation from its current carrier th...
43. What is the difference between platform threads and virtual threads at the JVM level?
The two thread types differ in how the JVM represents and schedules them, not in the public API a developer writes against. Platform Thread Virtual Thread 1:1 wrapper around an OS thread JVM-managed continuation, not tied 1:1 to an OS thread Fixed, relatively large stack, often around 1MB, reserv...
44. Explain the execution flow of a virtual thread when it performs a blocking I/O call?
sequenceDiagram participant VT as Virtual Thread participant Sched as JVM Scheduler participant Carrier as Carrier Thread participant IO as I/O Subsystem VT->>Carrier: Mounted, running normally VT->>IO: Issue blocking read() Carrier->>Sched: Unmount VT continuation, park it Sched->>Carrier: Assig...
45. How does Class Data Sharing (CDS) improve JVM startup performance?
Class Data Sharing (CDS) pre-processes class metadata into a shared archive file, by default classes.jsa , ahead of time, so the JVM doesn't have to repeat that work on every single startup. Normally, loading a class means reading its bytes from a JAR or the filesystem, running the bytecode verif...
46. What is Application Class Data Sharing (AppCDS), and how does it differ from default CDS?
Default CDS, enabled automatically since JDK 12, only archives the JDK's own bootstrap classes - it says nothing about the application's own classes or its third-party libraries. AppCDS extends the same mechanism to cover application and library classes too, so the parsing and verification saving...
47. When should you choose AOT-style CDS archives versus JIT warm-up in a production deployment?
The choice comes down to whether your workload's cost is dominated by startup latency or by sustained steady-state throughput . CDS/AppCDS archives trade a build-time packaging step, generating and shipping the .jsa file alongside your application, for a much faster cold start, since class parsin...
48. How can you optimize JVM heap tuning using ergonomics vs manual flags?
JVM ergonomics is the set of default heuristics that pick a garbage collector and heap sizing automatically based on the detected number of CPUs and available memory - for example, by default HotSpot sets initial heap size to roughly 1/64th of physical memory and max heap size to roughly 1/4th, a...
49. How do you troubleshoot a memory leak caused by classloader references (classloader leaks)?
A classloader leak shows up as steadily growing Metaspace, or heap, usage across repeated operations that should be memory-neutral - most classically, redeploying a web application to the same application server without ever restarting the JVM, eventually producing OutOfMemoryError: Metaspace . T...
50. Explain the internal working of safepoints and why the JVM needs them?
A safepoint is a point during execution where every application thread has reached a state with a known, globally consistent set of live object references - a state the JVM can safely inspect or modify without risking a torn or inconsistent view of the heap and stacks. The JVM needs this guarante...