Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
Explain the JVM Memory Model: Heap vs. Stack vs. Metaspace.
junior LevelCode ExampleMemory ManagementData Structures
In Simple Words:
- Stack Memory: Thread-private, stores method call frames, primitive local variables, and object references. Allocation and deallocation are instantaneous as methods push and pop.
- Heap Memory: Shared across all threads, stores all Java object instances and arrays. Managed by the Garbage Collector (Young Gen: Eden + Survivor S0/S1, and Old/Tenured Gen).
- Metaspace: Native OS memory (replacing PermGen in Java 8+) that stores class metadata, method bytecode, and static constant pools. Scales dynamically unless bounded by
-XX:MaxMetaspaceSize.
java
public class MemoryDemo {
// Stored in Heap inside the MemoryDemo instance
private String instanceData = "Heap Data";
public void executeProcess() {
// 'localValue' and the reference 'demoRef' are stored on the thread Stack
int localValue = 42;
MemoryDemo demoRef = new MemoryDemo(); // New object instance allocated on the Heap
}
}