Java for Beginners · Module 1: Getting Started
🎯 Why Look Inside the JVM?
Think of a restaurant. The receptionist checks bookings and brings in guests (loading classes). The kitchen shelves and counters store ingredients and work in progress (memory). The chefs actually cook (execution engine). You can enjoy the meal without knowing the kitchen, but knowing it helps you understand mistakes, slow programs and strange errors like StackOverflowError.
1️⃣ The Big Picture
loads .class files, verifies them, prepares them
class info, constants, static data
all objects and arrays
one per thread: method calls, local variables
current instruction of each thread
for code written in C/C++
Interpreter · JIT compiler · Garbage Collector
Figure 1: The main parts of the JVM.
2️⃣ Class Loader Subsystem: Bringing Classes In
A class is loaded only when the program first needs it, not all at the start. Loading happens in three stages.
- Loading: read the
.classfile into memory. - Linking: verify the bytecode is valid and safe, prepare memory for static variables, and resolve references to other classes.
- Initialization: run static initializers and give static variables their values.
loads core classes such as String and Object
loads platform and extension modules
loads YOUR classes from the class path
Figure 2: Class loaders form a chain. A loader first asks its parent.
Program 1: Who loaded which class?
public class LoaderDemo {
public static void main(String[] args) {
System.out.println("String class loader : " + String.class.getClassLoader());
System.out.println("My class loader : " + LoaderDemo.class.getClassLoader().getName());
System.out.println("Current thread : " + Thread.currentThread().getName());
}
}
String class loader : null
My class loader : app
Current thread : main
Stringis a core class, loaded by the bootstrap loader. That loader is built into the JVM, so Java shows it asnull.- Your own class was loaded by the application loader, whose name is
app. - Your program starts in a thread named
main.
3️⃣ Runtime Data Areas: The JVM’s Memory
| Memory area | Holds | Shared? | Typical error |
| Heap | Objects and arrays | All threads | OutOfMemoryError |
| Method Area | Class data, constants, static variables | All threads | OutOfMemoryError |
| Java Stack | Method calls, local variables | One per thread | StackOverflowError |
| PC Register | Next instruction | One per thread | none |
Figure 5: JVM memory areas at a glance.
Stack and heap in action
Local variables of primitive types, like int count, live on the stack. Objects and arrays live on the heap. A variable that refers to an object only stores a reference (like an address) to it.
public class StackHeapDemo {
public static void main(String[] args) {
int count = 5; // primitive: lives on the stack
int[] marks = {70, 80, 90}; // array object: lives on the heap
int[] same = marks; // second reference to the SAME array
same[0] = 99;
System.out.println("count = " + count);
System.out.println("marks[0] = " + marks[0]);
System.out.println("same[0] = " + same[0]);
System.out.println("Same object? " + (marks == same));
}
}
count = 5
marks[0] = 99
same[0] = 99
Same object? true
5→→[ 99 | 80 | 90 ]both references point here
Figure 3: Two references (marks and same) point to one array on the heap. Changing it through either changes both.
same = markscopies the reference, not the array. Both names now point to one array.- Changing
same[0]also changesmarks[0], because there is only one array. marks == samecompares references, and they are equal.
When the stack runs out
Each method call adds a frame to the stack. If a method keeps calling itself forever, the stack fills up and Java throws StackOverflowError.
public class DeepRecursion {
static int depth = 0;
static void dive() {
depth++;
dive();
}
public static void main(String[] args) {
try {
dive();
} catch (StackOverflowError e) {
System.out.println("Stack is full: StackOverflowError caught");
System.out.println("Went deeper than 1000 calls? " + (depth > 1000));
}
}
}
Stack is full: StackOverflowError caught
Went deeper than 1000 calls? true
dive()has no stopping condition, so it calls itself until the stack is full.tryandcatchlet the program handle the error instead of crashing. You will study this in Lesson 28.- We print only whether it went deeper than 1000 calls, because the exact depth changes from computer to computer.
Garbage collection
You never free memory in Java. The Garbage Collector in the execution engine finds objects that nothing refers to any more, and frees their heap space automatically. This removes a whole class of C-style bugs such as forgetting free().
4️⃣ Execution Engine and the JIT Compiler
The execution engine runs your bytecode. It has three parts: the interpreter, the JIT compiler and the garbage collector.
The interpreter starts running at once, which is why Java programs start quickly. But interpreting is slow if the same code runs many times. So the JVM watches. When a method or loop runs again and again (it becomes hot), the JIT (Just-In-Time) compiler translates it into machine code of your computer and stores it. From then on the fast version runs.
runs bytecode line by line; starts instantly
a method or loop is used again and again
next calls run the fast native version
Figure 4: How the JIT compiler speeds up the parts of a program that matter most.
Program 2: A loop that becomes hot
public class HotLoop {
static long work(int n) {
long total = 0;
for (int i = 0; i < n; i++) {
total += (long) i * i % 7;
}
return total;
}
public static void main(String[] args) {
long result = 0;
for (int round = 0; round < 200; round++) {
result += work(100_000);
}
System.out.println("Result = " + result);
}
}
Result = 39999800
workis called 200 times and loops 100,000 times each, so the JVM treats it as hot.- You can watch the JIT with
java -XX:+PrintCompilation HotLoop. Lines like the following appear (the numbers will differ on your computer):
35 6 % 3 HotLoop::work @ 4 (29 bytes)
36 7 3 HotLoop::work (29 bytes)
37 9 4 HotLoop::work (29 bytes)
- The method name
HotLoop::workshows it was compiled. The number before the bytes (3, then 4) is the optimisation level: higher means faster machine code.
⚠️ Common Confusions
| Wrong idea | Truth |
|---|---|
| “Objects are stored on the stack” | Objects live on the heap; only references live on the stack |
| “Java has no memory management” | The JVM manages it with the garbage collector |
| “JIT compiles the whole program at start” | It compiles only hot code, while the program runs |
| “StackOverflowError means the computer is out of memory” | Only the thread’s stack is full, usually from endless recursion |
| “All classes load when the program starts” | Classes load when first needed |
❓ Frequently Asked Questions
Q1. Why does the first run feel slower than later runs of the same code?
The JIT needs time to find hot code and compile it. This is called warm-up.
Q2. Can I force garbage collection?
You can ask with System.gc(), but the JVM decides. Normally you never need it.
Q3. Where do static variables live?
Their class data lives in the Method Area (in modern JVMs called Metaspace), and objects they refer to live on the heap.
Q4. Is each thread’s stack separate?
Yes. Every thread has its own stack, so local variables are not shared between threads.
✅ Key Takeaways
- The JVM has a class loader, memory areas and an execution engine.
- Classes are loaded when needed: loading, linking, initialization.
- Stack: method calls and local variables. Heap: objects and arrays.
- Variables for objects hold references; copying a reference does not copy the object.
- The garbage collector frees unused objects automatically.
- The JIT compiler turns hot bytecode into fast machine code while the program runs.
🎓 Practice questions: (1) Name the three parts of the JVM. (2) What is the difference between the stack and the heap? (3) Why doesString.class.getClassLoader()printnull? (4) What causesStackOverflowError? (5) In your own words, what does the JIT compiler do, and why is it called “just in time”?
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java