Jan 24, 2026
## Chapter 19: JVM Basics (The "Engine Room")
The JVM (Java Virtual Machine) is the engine that runs your code. You don't need to be an expert, but you should know how it manages your memory.
### 1. Stack vs Heap
**Example 1: Where does it go? (Basic)**
```java
int x = 10; // Stored in STACK (Fast, temporary)
Student s = new Student(); // Object stored in HEAP (Big warehouse)
```
### 2. Common Student Mistake: The Infinite Loop/Recursion
**Example 2: StackOverflowError**
```java
void hello() {
hello(); // Calling itself forever
}
```
*Teacher's Note:* Every time you call a method, a "plate" is added to the Stack. If you keep adding plates without removing them, the stack falls over. That's a `StackOverflowError`.
### 3. Out of Memory
**Example 3: The Warehouse is Full (Explanation)**
```java
List<byte[]> list = new ArrayList<>();
while(true) {
list.add(new byte[1000000]); // Adding huge chunks forever
}
```
*Teacher's Note:* If you keep creating objects in the Heap and never let go of them, the JVM runs out of space. This is an `OutOfMemoryError`.
### 4. Real-Life Example: Garbage Collection
**Example 4: The Cleaning Crew**
Imagine a restaurant. When a customer (variable) leaves the table, the waiter (Garbage Collector) cleans the table (frees memory) so new customers can sit. In Java, this happens automatically!
### 5. Future Hint
**Example 5: Tuning the JVM (Future Hint)**
When you run a big app (like Minecraft or a server), you can tell the JVM exactly how much memory to use with flags like `-Xmx2G` (use 2GB of memory). Professional Java devs spend a lot of time "tuning" these settings.