class MethodCallingStack{
public static void MyMethod(){
System.out.println("Start MyMethod()");
int x;
x=200;
System.out.println("End MyMethod()");
}
public static void main(String args[]){
System.out.println("Start main()");
int x;
x=100;
System.out.println("End main()");
}
}
What is the Stack memory?
Stack memory is a temporary memory area used to store method calls and local variables. Every time a method runs, Java creates a stack frame for that method. Variables like int x = 100; are stored in stack memory. When the method finishes, its data is removed automatically from the stack.
What is the Heap Memory?
Heap memory is used to store objects and arrays created using the new keyword. Heap memory is shared by all methods in the program. For example, in Student s = new Student();, the object is stored in heap memory, while the reference variable s is stored in stack memory. Heap memory keeps objects until they are removed by Java’s Garbage Collector.
Working of Method Calling Stack!
This program explains how the method calling stack works in Java. When the program starts, the main() method is loaded into stack memory, and the local variable x = 100 is stored inside the main() stack frame. If MyMethod() is called, a new stack frame is created above the main() frame, and its local variable x = 200 is stored there. Each method has its own separate variables in the stack memory. When a method finishes, its stack frame is removed automatically. This program does not create any objects, so heap memory is not used here.
Top comments (2)
Great breakdown of stack versus heap memory in Java. The example with
int x = 100andint x = 200in separate stack frames really shows how method-specific variables work. How do you handle questions about memory management in interviews? I've mostly used LeetCode for DSA, but I'm using PracHub to prep for these more technical questions, and their explanations have been solid.Thanks! Happy the explanation helped. 😊
For memory management interview questions, I mostly study basic topics like stack memory, heap memory, garbage collection, object references, and method calling. Most interviewers want to see if you understand the concepts clearly.
LeetCode is very good for DSA practice. But learning Java concepts like JVM memory, OOP, multithreading, and collections is also important. PracHub sounds useful for learning these theory topics. Small coding examples also help a lot in interviews.