β˜• Java

JDK vs JRE vs JVM β€” Complete Explanation

A deep-dive guide to understanding Java Development Kit, Java Runtime Environment, and Java Virtual Machine β€” covering JVM architecture, class loader, JIT compiler, garbage collector, heap & stack memory, and bytecode execution flow.

πŸ“…

Last Updated

March 2026

⏱️

Read Time

22 min

🎯

Level

Beginner to Intermediate

Overview β€” JDK, JRE, and JVM

One of the most frequently asked questions in every Java interview β€” and one of the most confused topics for beginners β€” is: "What is the difference between JDK, JRE, and JVM?" These three terms are at the heart of how Java works, and understanding them clearly will give you a solid foundation for everything else in Java.

In simple terms: JVM is the engine that runs your Java program. JRE is the environment that provides JVM + standard libraries to run it. JDK is the complete toolkit that includes JRE + developer tools to write, compile, and run Java programs. The relationship is: JDK βŠ‡ JRE βŠ‡ JVM.

TermFull FormOne-Line Purpose
JVMJava Virtual MachineExecutes Java bytecode on any platform
JREJava Runtime EnvironmentProvides the environment to RUN Java apps (JVM + Libraries)
JDKJava Development KitProvides tools to WRITE, COMPILE, and RUN Java apps (JRE + Dev Tools)

Real-World Analogy β€” Kitchen, Restaurant & Chef

Before going deep into technical details, let us understand JDK, JRE, and JVM through a simple real-world analogy that makes these concepts unforgettable.

Java ComponentKitchen AnalogyRole
JVMThe Oven / StoveThe actual machine that does the cooking (execution). It runs the recipe (bytecode).
JREThe Full KitchenOven + all utensils, ingredients shelf, pantry. Everything needed to COOK (run) a dish.
JDKKitchen + Chef ToolsFull kitchen + chef's knife set, recipe book, measuring tools. Everything needed to CREATE + COOK dishes.
Bytecode (.class)The RecipePlatform-neutral instructions that any oven (JVM) can follow to produce the same dish.
Java Source (.java)Raw Recipe DraftThe human-readable recipe written by the developer, before it is converted to standard format.

Key insight: A diner (end user) only needs the kitchen (JRE) to enjoy the food (run the app). Only the chef (developer) needs the full kitchen + chef tools (JDK) to create new dishes.

What is JVM β€” Java Virtual Machine?

The Java Virtual Machine (JVM) is an abstract computing machine β€” a software layer that acts as a virtual computer inside your real computer. It is the core reason Java is platform-independent. The JVM does not care whether the underlying hardware is Windows, Linux, or macOS β€” it provides a uniform execution environment for Java bytecode.

The JVM performs four primary responsibilities every time a Java program runs:

πŸ“₯
Load Code

The Class Loader reads .class bytecode files from disk, network, or memory and loads them into the JVM's Runtime Data Areas.

βœ…
Verify Code

The Bytecode Verifier checks every loaded .class file for structural validity, type safety, and security violations β€” before a single instruction executes.

⚑
Execute Code

The Execution Engine (Interpreter + JIT Compiler) translates bytecode instructions into native machine code and runs them on the host CPU.

πŸ—‘οΈ
Manage Memory

The Garbage Collector automatically allocates memory for new objects on the Heap and reclaims memory from objects that are no longer reachable.

Important: The JVM itself is platform-specific β€” there is a different JVM implementation for Windows, Linux, and macOS. But the bytecode it executes is platform-neutral. This is the magic of WORA β€” the bytecode is universal, only the JVM varies.

β˜• JavaJVM Demo β€” Runtime Properties
public class JVMInfo {
    public static void main(String[] args) {
        // JVM and Java version info
        System.out.println("Java Version  : " + System.getProperty("java.version"));
        System.out.println("JVM Name      : " + System.getProperty("java.vm.name"));
        System.out.println("JVM Version   : " + System.getProperty("java.vm.version"));
        System.out.println("JVM Vendor    : " + System.getProperty("java.vm.vendor"));
        System.out.println("Java Home     : " + System.getProperty("java.home"));
        System.out.println("OS Name       : " + System.getProperty("os.name"));
        System.out.println("OS Arch       : " + System.getProperty("os.arch"));

        // Memory info
        Runtime rt = Runtime.getRuntime();
        System.out.println("Max Heap      : " + (rt.maxMemory()  / 1024 / 1024) + " MB");
        System.out.println("Total Heap    : " + (rt.totalMemory()/ 1024 / 1024) + " MB");
        System.out.println("Free Heap     : " + (rt.freeMemory() / 1024 / 1024) + " MB");
        System.out.println("CPU Cores     : " + rt.availableProcessors());
    }
}

Output

Java Version : 21.0.2 JVM Name : OpenJDK 64-Bit Server VM JVM Version : 21.0.2+13 JVM Vendor : Eclipse Adoptium Java Home : /usr/lib/jvm/java-21-openjdk-amd64 OS Name : Linux OS Arch : amd64 Max Heap : 3924 MB Total Heap : 256 MB Free Heap : 244 MB CPU Cores : 8

JVM Architecture β€” Deep Dive

The JVM is not a single monolithic program β€” it is a carefully designed system of three interconnected subsystems. Understanding this architecture is crucial for writing performant Java code and for cracking advanced Java interviews.

1. Class Loader Subsystem
Bootstrap ClassLoaderExtension ClassLoaderApplication ClassLoaderLoading β†’ Linking β†’ Initialization
2. Runtime Data Areas (JVM Memory)
Method Area (Class Metadata)Heap Area (Objects & Arrays)Stack Area (Method Frames)PC Register (per thread)Native Method Stack
3. Execution Engine
Interpreter (bytecode β†’ instructions)JIT Compiler (hot code β†’ native)Garbage Collector (memory reclaim)
Native Method Interface (JNI)
Connects JVM to native C/C++ librariesUsed by java.io, java.net, javax.crypto
Native Method Libraries
OS-level libraries (.dll on Windows, .so on Linux)Hardware-level operations

Architecture Diagram

Class Loader Subsystem β€” How Java Loads Classes

The Class Loader Subsystem is the first stage of JVM execution. When your Java program starts, the JVM does not load all classes at once β€” it uses lazy loading, loading classes only when they are first needed. The Class Loader performs three phases:

PhaseWhat HappensExample
1. LoadingReads the .class file binary from source (disk, network, JAR) and creates a Class object in Method Area memory.HelloWorld.class is read from disk into JVM memory
2. LinkingThree sub-steps: Verification (bytecode validity check) β†’ Preparation (static variables allocated with default values) β†’ Resolution (symbolic references replaced with direct memory references).static int count gets default value 0 in memory
3. InitializationStatic initializers and static variable assignments execute in top-to-bottom order. This is when static blocks run.static { System.out.println("Class loaded!"); } executes

Three Types of Class Loaders β€” Delegation Hierarchy

Class LoaderLoads FromResponsibility
Bootstrap ClassLoaderJDK rt.jar / jmods (JDK 9+)Loads core Java classes: java.lang.Object, java.lang.String, java.util.*
Extension ClassLoaderjdk/lib/ext directory or java.ext.dirsLoads extension classes β€” security, XML, crypto APIs (Java 8 and earlier)
Application ClassLoaderApplication classpath (-cp or CLASSPATH env var)Loads YOUR application classes and third-party library classes (from Maven/Gradle)

Delegation Model: When a class needs to be loaded, the Application ClassLoader first delegates to the Extension ClassLoader, which delegates to the Bootstrap ClassLoader. Only if the parent cannot find the class does the child attempt to load it. This prevents malicious code from replacing core Java classes like java.lang.String.

β˜• JavaClassLoader Demo
public class ClassLoaderDemo {
    public static void main(String[] args) {

        // Bootstrap ClassLoader loads java.lang.String
        // Returns null because Bootstrap CL is native (C++)
        System.out.println("String ClassLoader    : " +
            String.class.getClassLoader());

        // Application ClassLoader loads user-defined classes
        System.out.println("This class ClassLoader : " +
            ClassLoaderDemo.class.getClassLoader());

        // Parent ClassLoader chain
        ClassLoader cl = ClassLoaderDemo.class.getClassLoader();
        System.out.println("Parent ClassLoader    : " + cl.getParent());
        System.out.println("Grandparent CLoader   : " + cl.getParent().getParent());
    }
}

Output

String ClassLoader : null This class ClassLoader : jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7 Parent ClassLoader : jdk.internal.loader.ClassLoaders$PlatformClassLoader@1b6d3586 Grandparent CLoader : null

Runtime Data Areas β€” JVM Memory Model

The JVM divides memory into five distinct Runtime Data Areas. Understanding which data lives where is essential for writing memory-efficient Java programs and diagnosing OutOfMemoryError and StackOverflowError issues.

πŸ—οΈ
Method Area (Metaspace)

Shared across all threads. Stores class-level data: class name, parent class, method bytecode, static variables, constant pool. In Java 8+, this is called Metaspace and is in native memory (not JVM heap). StackOverflow in Metaspace is possible if too many classes are loaded dynamically.

πŸ“¦
Heap Area

Shared across all threads. This is where ALL objects and arrays are allocated (created with 'new'). Divided into Young Generation (Eden + Survivor spaces) and Old Generation. Managed by the Garbage Collector. OutOfMemoryError: Java heap space occurs when Heap is full.

πŸ“š
Stack Area (JVM Stack)

One Stack per thread. Stores method call frames β€” each frame contains: local variables, operand stack, and reference to constant pool. LIFO structure β€” frames are pushed on method call and popped on method return. StackOverflowError occurs with infinite recursion.

πŸ”’
PC Register (Program Counter)

One PC Register per thread. Stores the address of the currently executing bytecode instruction. When a thread switches between methods, the PC Register saves the return address so execution can resume correctly.

πŸ”Œ
Native Method Stack

One per thread. Used when Java code calls native methods (C/C++ code via JNI). Similar to JVM Stack but for native code execution. Used internally by java.io for file I/O and java.net for networking.

Heap Memory β€” Young & Old Generation

Heap RegionSub-RegionDescriptionGC Type
Young GenerationEden SpaceAll new objects are first created here.Minor GC (fast)
Young GenerationSurvivor 0 (S0)Objects that survived one GC cycle move here from Eden.Minor GC (fast)
Young GenerationSurvivor 1 (S1)Objects alternate between S0 and S1 across GC cycles.Minor GC (fast)
Old GenerationTenured SpaceLong-lived objects (survived multiple GC cycles) are promoted here.Major GC (slow)
Non-HeapMetaspaceClass metadata, static variables, constant pool. Replaced PermGen in Java 8.GC on class unload
β˜• JavaHeap vs Stack β€” Memory Demo
public class MemoryDemo {

    // Instance variable β€” stored in HEAP (part of the object)
    int instanceVar = 100;

    public static void main(String[] args) {

        // Local primitive β€” stored in STACK
        int localVar = 50;

        // Object reference 'obj' β€” stored in STACK
        // Actual MemoryDemo object β€” stored in HEAP
        MemoryDemo obj = new MemoryDemo();

        // String literal β€” stored in String Pool (part of Heap)
        String name = "Java";

        // 'new' String β€” always creates a new object in Heap
        String name2 = new String("Java");

        System.out.println("localVar   : " + localVar);          // Stack
        System.out.println("instanceVar: " + obj.instanceVar);   // Heap
        System.out.println("name == name2: " + (name == name2)); // false (different objects)
        System.out.println("name.equals: " + name.equals(name2));// true (same content)
    }
}

Output

localVar : 50 instanceVar: 100 name == name2: false name.equals: true

Execution Engine β€” Interpreter vs JIT Compiler

The Execution Engine is the heart of the JVM β€” it is responsible for actually running your Java bytecode. It has two strategies for executing bytecode, and understanding both explains why Java's performance has improved dramatically over the years.

ComponentStrategySpeedWhen UsedCharacteristic
InterpreterReads and executes bytecode one instruction at a timeSlow (starts fast)All code initiallySimple, no optimization, immediate startup
JIT CompilerCompiles frequently-used bytecode to native machine codeVery FastHot code (called many times)Slower startup but faster sustained execution
C1 CompilerLight optimization JIT (client compiler)MediumEarly hot detectionFaster compilation, moderate optimization
C2 CompilerAggressive optimization JIT (server compiler)FastestHeavily repeated codeSlower compilation, maximum performance
GraalVM JITNext-gen JIT written in Java itself (Java 21+)ExcellentModern enterprise workloadsBetter optimizations, supports native image

How JIT Works: The JVM starts by interpreting all bytecode. It counts how many times each method is called. When a method crosses the invocation threshold (default: 10,000 times), the JIT compiler compiles it to native machine code. Future calls execute the native code directly β€” bypassing the interpreter entirely. This is why Java applications get faster over time the longer they run.

β˜• JavaJIT Effect β€” Performance Demo
public class JITDemo {
    public static void main(String[] args) {

        // First run β€” JVM interprets bytecode (slower)
        long start1 = System.nanoTime();
        long result1 = computeSum(1_000_000);
        long time1 = System.nanoTime() - start1;

        // Second run β€” JIT has compiled computeSum to native code (faster)
        long start2 = System.nanoTime();
        long result2 = computeSum(1_000_000);
        long time2 = System.nanoTime() - start2;

        System.out.println("Result 1 : " + result1);
        System.out.println("Time 1   : " + time1 / 1_000_000 + " ms (interpreted)");
        System.out.println("Result 2 : " + result2);
        System.out.println("Time 2   : " + time2 / 1_000_000 + " ms (JIT compiled)");
    }

    static long computeSum(int n) {
        long sum = 0;
        for (int i = 1; i <= n; i++) sum += i;
        return sum;
    }
}

Output

Result 1 : 500000500000 Time 1 : 12 ms (interpreted) Result 2 : 500000500000 Time 2 : 1 ms (JIT compiled)

Garbage Collector β€” Automatic Memory Management

Java's Garbage Collector (GC) is one of its most celebrated features. Unlike C and C++ where developers manually allocate and free memory (malloc/free), Java's GC automatically identifies and reclaims memory occupied by objects that are no longer reachable from any live thread. This prevents the two most common memory bugs: memory leaks (forgetting to free) and dangling pointers (freeing and then using).

How Garbage Collection Works β€” Mark & Sweep

  • β–Ά

    Phase 1 β€” Mark: The GC starts from GC Roots (active thread stacks, static variables, JNI references) and marks every reachable object in the Heap by traversing all references.

  • β–Ά

    Phase 2 β€” Sweep: All objects NOT marked as reachable are considered garbage. The GC reclaims their memory.

  • β–Ά

    Phase 3 β€” Compact (optional): Some GC algorithms compact live objects together to eliminate fragmentation, making future allocations faster.

GC AlgorithmIntroducedBest ForStop-the-World?Java 21 Default?
Serial GCJava 1Single-threaded / small appsYes (long pause)❌ No
Parallel GCJava 5Throughput-focused batch processingYes (shorter pauses)❌ No
G1GCJava 7General-purpose β€” balanced latency/throughputMinimal pausesβœ… Yes (Default)
ZGCJava 11Ultra-low latency (sub-millisecond pauses)Mostly concurrentβœ… Available
Shenandoah GCJava 12Low-latency, large heapsMostly concurrentβœ… Available
Epsilon GCJava 11Performance testing (no GC β€” intentional)N/A❌ Dev/Test only
β˜• JavaGC Demo β€” Eligible for Collection
public class GCDemo {
    String name;

    GCDemo(String name) {
        this.name = name;
        System.out.println("Created: " + name);
    }

    @Override
    protected void finalize() {
        // Called by GC before reclaiming memory (deprecated in Java 9+)
        System.out.println("GC collected: " + name);
    }

    public static void main(String[] args) throws Exception {
        GCDemo obj1 = new GCDemo("Object-A");  // obj1 β†’ Heap
        GCDemo obj2 = new GCDemo("Object-B");  // obj2 β†’ Heap

        obj1 = null;  // Object-A is now unreachable β†’ eligible for GC
        obj2 = null;  // Object-B is now unreachable β†’ eligible for GC

        System.gc();  // Request GC (JVM may or may not run it immediately)
        Thread.sleep(1000);
        System.out.println("Main method ends.");
    }
}

Output

Created: Object-A Created: Object-B GC collected: Object-B GC collected: Object-A Main method ends.

What is JRE β€” Java Runtime Environment?

The Java Runtime Environment (JRE) is the minimum software package required to run a pre-compiled Java application. It is a superset of the JVM β€” meaning it contains the JVM plus the standard Java class libraries that Java programs depend on.

JRE ComponentDescription
JVMThe Java Virtual Machine β€” executes bytecode
java.lang packageCore language classes: Object, String, Math, System, Thread, Exception
java.util packageCollections, Date, Scanner, Random, Optional
java.io packageFile I/O, Streams, Readers, Writers
java.net packageNetworking: Socket, URL, HttpURLConnection
java.util.concurrentThread pools, locks, atomic variables
java.sql packageJDBC API for database connectivity
javax.* packagesExtended APIs: crypto, XML, net, naming
rt.jar / modulesPre-compiled bytecode of all standard library classes

Who needs JRE? End users who want to run a Java application (like a JAR file) but do not intend to develop Java programs. However, since Java 9 the standalone JRE is no longer distributed β€” you install the JDK instead, or create a custom minimal runtime using jlink.

What is JDK β€” Java Development Kit?

The Java Development Kit (JDK) is the complete toolkit for Java development. It is a superset of the JRE β€” it contains everything in the JRE plus a set of command-line developer tools. If you are a Java developer, you always install the JDK. As of Java 9, Oracle no longer ships a separate JRE β€” only the JDK.

The JDK is available from multiple vendors, all based on the same OpenJDK source code:

  • β–Ά

    Eclipse Temurin (Adoptium): Most popular free OpenJDK build. Recommended for most developers.

  • β–Ά

    Oracle JDK 21: Free under NFTC license. Same codebase as OpenJDK with Oracle-specific monitoring tools.

  • β–Ά

    Amazon Corretto: Free OpenJDK with long-term AWS support. Best for AWS deployments.

  • β–Ά

    Microsoft OpenJDK: Free, optimized for Azure and Windows environments.

  • β–Ά

    GraalVM CE: Free OpenJDK + native image compilation + polyglot runtime.

JDK Developer Tools β€” Complete Reference

The JDK includes a rich set of command-line tools in its bin/ directory. Every Java developer should know these tools β€” especially javac, java, javap, jdb, and jar.

ToolCommandPurposeExample Usage
Java CompilerjavacCompiles .java source files to .class bytecodejavac HelloWorld.java
Java LauncherjavaStarts JVM and runs a compiled .class / .jar filejava HelloWorld | java -jar app.jar
Java DisassemblerjavapDisassembles .class files β€” shows bytecode or method signaturesjavap -c HelloWorld.class
Java DebuggerjdbCommand-line debugger for Java programsjdb HelloWorld
Javadoc GeneratorjavadocGenerates HTML API documentation from /** */ commentsjavadoc -d docs HelloWorld.java
JAR TooljarCreates, lists, and extracts JAR archive filesjar cf app.jar *.class
JVM MonitorjconsoleGUI tool to monitor JVM memory, threads, and GCjconsole (connects to running JVM)
Flight RecorderjfrRecords JVM performance data for analysisjfr print recording.jfr
Module TooljmodCreates .jmod files for Java 9+ module systemjmod create --class-path mods/ mymod.jmod
Runtime ImagejlinkCreates custom minimal JRE images for distributionjlink --add-modules java.base --output myruntime
Native ImagejpackagePackages Java apps as native installers (.exe, .dmg)jpackage --type exe --input out/ --main-jar app.jar
Key & Cert ToolkeytoolManages cryptographic keys and certificates (SSL/TLS)keytool -genkeypair -alias mykey

javap β€” Inspect Bytecode Like a Pro

πŸ’» Terminaljavap β€” View Bytecode Instructions
# Compile the class first:
javac HelloWorld.java

# View method signatures (no bytecode):
javap HelloWorld

# View full bytecode disassembly:
javap -c HelloWorld

# View detailed bytecode + constant pool:
javap -verbose HelloWorld

Output

Compiled from "HelloWorld.java" public class HelloWorld { public HelloWorld(); public static void main(java.lang.String[]); } // javap -c output (bytecode): public static void main(java.lang.String[]); Code: 0: getstatic #7 // Field java/lang/System.out 3: ldc #13 // String Hello, World! 5: invokevirtual #15 // Method println:(String)V 8: return

JDK βŠ‡ JRE βŠ‡ JVM β€” Architecture Diagram

The diagram below shows the nested relationship between JDK, JRE, and JVM β€” from the outermost developer toolkit down to the innermost execution engine.

JDK β€” Java Development Kit (Outermost)
javac (Compiler)javap (Disassembler)jdb (Debugger)javadoc (Doc Generator)jar (Archiver)jconsole (Monitor)jlink (Runtime Builder)jpackage (Native Packager)
JRE β€” Java Runtime Environment
java.lang (Object, String, System, Thread)java.util (Collections, Scanner, Optional)java.io (File, InputStream, OutputStream)java.net (Socket, URL, HttpClient)java.util.concurrent (ThreadPool, Locks)java.sql (JDBC β€” Database Connectivity)javax.* (Crypto, XML, Naming)
JVM β€” Java Virtual Machine (Innermost)
Class Loader SubsystemMethod Area (Metaspace)Heap (Young + Old Generation)JVM Stack (per thread)PC Register (per thread)InterpreterJIT Compiler (C1 + C2)Garbage Collector (G1GC / ZGC)

Architecture Diagram

JDK vs JRE vs JVM β€” Master Comparison Table

This is the definitive comparison table for JDK, JRE, and JVM β€” covering every angle that can be asked in interviews.

ParameterJVMJREJDK
Full NameJava Virtual MachineJava Runtime EnvironmentJava Development Kit
Primary PurposeExecutes Java bytecodeProvides runtime to run Java appsProvides tools to develop & run Java
ContainsInterpreter, JIT, GC, Memory MgrJVM + Java Class LibrariesJRE + javac, javap, jdb, javadoc, jar...
Includes JVM?βœ… It IS the JVMβœ… Yesβœ… Yes
Includes javac?❌ No❌ Noβœ… Yes
Includes Libraries?❌ No (only executes)βœ… Yes (java.lang, java.util...)βœ… Yes (same as JRE)
Platform Specific?βœ… Yes (different per OS)βœ… Yes (bundles OS-specific JVM)βœ… Yes (different per OS)
Who Needs It?Runtime engine (internal)End users running Java appsDevelopers writing Java apps
File SizeSmallest (~40 MB)Medium (~200 MB)Largest (~300-400 MB)
Can Compile Code?❌ No❌ Noβœ… Yes (javac compiler)
Can Run Code?βœ… Yes (its only job)βœ… Yesβœ… Yes
Shipped Separately?No (part of JRE)Merged into JDK since Java 9βœ… Yes β€” download from adoptium.net
Current Version 202621.0.xPart of JDK 21JDK 21 LTS (recommended)

End-to-End Bytecode Execution Flow

Let us trace the complete journey of a Java program β€” from the moment you type source code to the moment output appears on screen. Every step maps to a specific JVM component.

πŸ“ Developer writesHelloWorld.java
javac command
βš™οΈ javac CompilerCompiles .java β†’ .class
generates
πŸ“¦ Bytecode FileHelloWorld.class (platform-neutral)
java command
πŸ“₯ Class LoaderLoads .class into Method Area
bytecode loaded
βœ… Bytecode VerifierSecurity & structural check
verified βœ“
🧠 InterpreterExecutes bytecode line-by-line
hot path detected
πŸ”₯ JIT CompilerCompiles hot code β†’ native
native compile
πŸ’» Native Machine CodeRuns directly on CPU
executes
πŸ—‘οΈ Garbage CollectorReclaims unused Heap memory
memory freed
πŸ–¨οΈ OutputHello, World!

Code Execution Flow β€” from source to output

Heap vs Stack Memory β€” Key Differences

Understanding the difference between Heap and Stack memory is critical for Java performance tuning, debugging OutOfMemoryError, and interview success.

ParameterStack MemoryHeap Memory
What is storedMethod call frames, local primitives, object referencesAll objects and arrays (created with 'new')
ScopeOne Stack per thread β€” thread-privateShared across ALL threads
Memory structureLIFO (Last In, First Out)No fixed structure β€” managed by GC
SizeSmall (default: 256KB–1MB per thread)Large (configurable: -Xmx, default 1/4 RAM)
Allocation speedVery fast (pointer increment)Slower (GC must manage)
LifetimeMethod frame lives until method returnsObject lives until GC collects it
Memory managementAutomatic (LIFO pop on return)Automatic (Garbage Collector)
Error when fullStackOverflowError (infinite recursion)OutOfMemoryError: Java heap space
Tuning flag-Xss256k (stack size per thread)-Xmx2g (max heap), -Xms512m (initial heap)
Access speedFastestSlower than Stack
Exampleint x = 5; String ref = ...;new Student(); new int[1000];
β˜• JavaStackOverflow vs OutOfMemory Demo
public class MemoryErrors {

    // Causes StackOverflowError β€” infinite recursion fills the Stack
    static void infiniteRecursion() {
        infiniteRecursion();  // calls itself forever
    }

    // Causes OutOfMemoryError β€” filling the Heap with objects
    static void fillHeap() {
        java.util.List<byte[]> list = new java.util.ArrayList<>();
        while (true) {
            list.add(new byte[1024 * 1024]);  // add 1MB chunks
        }
    }

    public static void main(String[] args) {
        try {
            infiniteRecursion();
        } catch (StackOverflowError e) {
            System.out.println("Caught: " + e.getClass().getSimpleName());
        }

        try {
            fillHeap();
        } catch (OutOfMemoryError e) {
            System.out.println("Caught: " + e.getClass().getSimpleName());
        }
    }
}

Output

Caught: StackOverflowError Caught: OutOfMemoryError

JDK vs JRE vs JVM β€” Interview Questions

These are the most commonly asked interview questions on JDK, JRE, JVM, and Java memory model β€” from fresher to mid-level positions.

Practice Questions β€” Test Your Knowledge

Test your understanding of JDK, JRE, and JVM concepts. Try answering each question before revealing the answer.

1. A user wants to run a pre-compiled Java .jar application but does not want to develop Java programs. What is the minimum they need to install?

Easy

2. Why does the JVM return 'null' when you call String.class.getClassLoader()?

Medium

3. What is the difference between Minor GC and Major GC?

Medium

4. Java is called 'interpreted' by some and 'compiled' by others. Who is right?

Medium

5. If you create 100 threads in a Java application, how many JVM Stacks are there?

Medium

6. What is the String Pool and which JVM memory area does it belong to?

Hard

7. What is 'stop-the-world' in Java GC? Why is it a problem?

Hard

8. What does the -Xmx and -Xms JVM flag do? Give a practical example.

Hard

Conclusion β€” JDK vs JRE vs JVM Summary

You now have a thorough understanding of the three pillars of the Java platform. Let us consolidate everything with a final cheat-sheet summary:

What You LearnedKey Takeaway
JVMExecution engine β€” loads, verifies, and runs bytecode. Platform-specific but executes platform-neutral bytecode.
JREJVM + Class Libraries. Minimum needed to RUN a Java app. No compiler included.
JDKJRE + Dev Tools (javac, jdb, javadoc, jar...). Required to DEVELOP Java apps. Always install JDK.
Class Loader3 phases: Loading β†’ Linking (Verify+Prepare+Resolve) β†’ Initialization. 3 loaders: Bootstrap, Platform, App.
JVM MemoryMethod Area (class metadata), Heap (objects), Stack (method frames), PC Register, Native Method Stack.
JIT CompilerCompiles frequently-executed bytecode to native machine code. Java gets faster the longer it runs.
Garbage CollectorAutomatic memory management. Mark β†’ Sweep β†’ Compact. Default: G1GC. Ultra-low latency: ZGC.
Heap vs StackStack: thread-private, LIFO, local vars β†’ StackOverflowError. Heap: shared, objects β†’ OutOfMemoryError.
BytecodePlatform-neutral intermediate format. Compiled once by javac, runs everywhere via any JVM.
WORAJVM is platform-specific; bytecode is platform-neutral. JVM bridges the gap on every OS.

With this understanding of Java's internals, you are now ready to move forward with confidence. The next chapter covers Java Syntax β€” variables, operators, control flow, and the rules that govern every line of Java code you write. β˜•

Frequently Asked Questions (FAQ) β€” JDK vs JRE vs JVM