DEV Community

Cover image for Java Quickies. The Call Stack
Tristan Elliott
Tristan Elliott

Posted on • Edited on

Java Quickies. The Call Stack

Introduction

  • This series is going to be dedicated to the basic understanding of Java. When ever I find myself asking, "How does this work ?". I will create a blog post and put it here. This series will not be in order so feel free to read what ever post you find most relevant. All my references for this blog post can be found HERE

What is the call stack?

  • Now my reasoning for looking up what the call stack is, was actually recursion. If you try to learn recursion like I am currently trying to do, you will eventually run into the words call stack. In recursion all the previous method calls are stored inside the call stack. With that being said, we can get back to the question at hand. What is a call stack? Well, it is what a program uses to keep track of its method calls and is made up of stack frames, one stack frame for each method call. So when we call a method it gets added to the call stack. Also, notice the stack part of call stack. This tells us that the call stack operates on the basic stack principles of `first-in-last-out'. That is why you will often read the terminology of popping and pushing to the call stack.

What is stored in the stack frames?

  • As I mentioned earlier the call stack is actually made up of stack frames, one for each method call. But what do these stack frames actually contain? Well, they mainly consist of 4 things:

  • 1) Local Variables(variables inside of methods)

  • 2) Arguments passed into the method

  • 3) Information about the caller's stack frame

  • 4) The return address. This is usually somewhere in the middle of the caller's code

  • Each method call creates its own stack frame, which takes up space on the call stack. This becomes especially important when dealing with recursion which deals exclusively with repeated method calls. If you have too many stack frames added to the call stack you will get a stack overflow which is an common logic error in recursion.

Conclusion

  • Now I hope we can both use this information to tackle recursion.
  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.
  • Also make sure to checkout my YouTube channel for more programming tutorials.

Top comments (0)