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 (0)