🧠 Java Memory Management Architecture
public class Student {
private String name; // Instance variable
private int age; // Instance variable
private static int count = 0; // Static variable
public Student(String name, int age) {
this.name = name;
this.age = age;
count++;
}
public void displayInfo() {
String message = "Student Info"; // Local variable
int tempAge = this.age; // Local variable
System.out.println(message + ": " + name + ", " + tempAge);
}
}
public class Main {
public static void main(String[] args) {
int num = 42; // Local primitive
Student student1 = new Student("Alice", 20); // Reference variable
Student student2 = new Student("Bob", 22); // Reference variable
}
}🥞 STACK MEMORY
🏔️ HEAP MEMORY
📚 METHOD AREA
🔍 Key Memory Management Concepts:
Stack Memory: Each thread has its own stack. When a method is called, a new frame is pushed onto the stack containing local variables, method parameters, and return addresses. Primitive variables store actual values, while reference variables store memory addresses pointing to objects in the heap.
Heap Memory: Shared among all threads, the heap stores all objects and their instance variables. Objects are allocated here during runtime using the 'new' keyword. The heap is divided into Young Generation (Eden, Survivor spaces) and Old Generation for garbage collection optimization.
Method Area: Stores class-level data including class metadata, method bytecode, static variables, and the constant pool. This area is shared among all threads and loaded when classes are first referenced.
Memory Flow: When you create an object, the reference variable goes on the stack, but the actual object is allocated in the heap. The reference variable contains the memory address where the object is stored in the heap.