DEV Community

Cover image for Java Quickie. Stack
Tristan Elliott
Tristan Elliott

Posted on • Edited on

Java Quickie. 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.

What is a Stack?

  • In computer science, a stack is a data type that serves as a collection of elements, with two main operations:

1) push: adds a element to the collection.

1) pop: removes the most recently added element.

  • Another defining trait of a Stack is that it operates on the LIFO(last in, first out) principle. Which means the last element added to the stack is the first element to be removed. A good mental model to have when thinking about Stacks is a stack of books. The only way to get to the book on the bottom is to remove all of the books above it.

Stack in Java

  • I first want to point out that there is nothing really too different when it comes to Stacks in Java. The underlying idea is the same, a Stack operates on the LIFO principle and has the push and pop operations. The implementation just becomes less abstract.

  • In Java a Stack is implemented as the call stack. Which is a temporary piece of memory that stores local variables, arguments passed into the method, information about the caller's stack frame(explained later) and the return address(where the program should return to). Each thread in Java has its own call stack and the call stack gets created the same time as the thread. The call stack actually stores frames and a frame is what stores all the extra information. A new frame is created each time a method is invoked and the frame is destroyed when the method invocation completes. Only one frame, the frame of the executing method is active at any given time.

  • So basically, when a method is called, a frame is created with all the necessary information and gets pushed to the top of the call stack. Once the method invocation is finished, the frame is then automatically popped from the stack and destroyed.

Conclusion

  • 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.

Top comments (0)