In this tutorial, you will learn about call stack in Java, and how a call stack is created for each method call, with examples.

Java Call stack and Stack frame

Java call stack contains stack frames . Stack frame contains the information regarding method and its variables(variables local to the method). A stack frame is added to the call stack when the execution enters the method. And the stack frame is removed, from the call stack, for a method, if the execution is done in the method. Consider the below example:

Example

In the following example, we call a method from inside another method, and observe the call stack in the eclipse IDE.

ADVERTISEMENT

CallStackDemo.java

package com.tutorialkart.java;

public class CallStackDemo {
 
	public static void main(String[] args) {
		int a=0,b=1;
		new CallStackDemo().method1(b);
		System.out.println("End of main");
	}
 
	public void method1(int b){
		System.out.println("In method1. Value recieved : "+b);
		method2(b);
	}
 
	public void method2(int b){
		System.out.println("In method2. Value recieved : "+b);
		method3();
	}
 
	public void method3(){
		System.out.println("In method3");
	}
}

Let us debug the above program in eclipse. Debug perspective in eclipse lets us observe the call stack and the variables stored in each stack frame:

Java Call Stack - Tutorialkart.com
Java Call Stack – execution paused at line 6 in main method
call stack_2 - www.tutorialkart.com
Call Stack when execution paused at line 11 in main method
Call Stack when execution paused at line 16 in main method