A Java stack is a last-in, first-out data structure. The first item removed from a stack is the item last added to the stack. A stack data structure adds new items to the end of the stack. Java stacks extend the Vector class.
In programming, a stack is a last-in, first-out data structure used to store data. Stacks are useful in a variety of cases. For example, if you want to test symmetry in a list or reverse the order of a list, you can use a stack.
The Java collection framework includes a class called stack that is used to build stacks in Java. This tutorial will discuss the basics of stacks in Java, how to create a stack, and the main methods the stack class offers. We’ll refer to examples throughout to reinforce how the stack class works.
Java Stacks
A Java stack stores elements in a last-in, first-out (LIFO) structure. This means that the element added to the top of the stack will be the first one removed from the stack.
One example of a stack in programming would be in a web browser’s page control features. When you visit a web page, your web browser adds it to a record of visited pages. This record is a stack.
Each time you visit a new web page during a browsing session, your browser adds a new entry to the browsing stack. If you want to return to the last page you visited (last-in), your browser will remove the most recent entry from the stack first (first-out). Here’s a table that shows an example stack:
Site Name |
google.com |
nytimes.com |
careerkarma.com |
This is our browsing history stack. We are currently on the google.com main page. Before the google.com page, we were on the New York Times main page. Before that, we were on the Career Karma main page.
google.com is at the top of the stack. The google.com site will be the first item our browser removes from the stack. This happens when we press the back arrow button to return to the last page we visited.
Another example of a stack in action is a pile of books. (Think of a stack of books!) If you want to look through a pile of books, you’ll go from the top book down. The last book you added to the stack will be the first one you look at—in other words, LIFO.
When you’re working with stacks, the last item in the list is considered at the top of the stack. To use our website example from above, google.com was the most recent site we visited, so it is at the top of our stack.
Create a Java Stack
Before we create a stack in Java, we have to import the java.util.Stack package. This package stores the stack data structure that we will use in this tutorial.
Here’s how to import the stack data structure:
import java.util.Stack;
Now that we’ve imported the stack package, we can create a Java stack. Here’s the syntax we used to create a stack in Java:
Stack<DataType> stack_name = new Stack<>();
Here are the main components of the Java stack syntax:
- Stack tells our program that we want to declare a stack.
- DataType is the type of data our stack will store.
- stack_name is the name of our stack.
- new Stack<>(); initializes a new Java stack.
If we wanted to create a stack called books
that stores strings, we could use this code:
Stack<String> books = new Stack<>();
We have created a new stack. This stack stores data in the last-in, first-out order.
A Note on the Deque Class
It’s worth noting that some programmers prefer to use the deque class instead of stack in Java.
Deques are double-ended queues. The advantage of a deque over a stack is that you can add and remove items from both ends of a deque. You cannot do this with a stack.
If you use stack-specific methods (discussed below), you’ll have to commit to using the stack class in your code. This can make it more difficult to scale a program. That said, stack still has a wide variety of uses in Java.
Java Stack Methods
The Java stack class includes a number of methods that you can use to manipulate data stored within a stack. These methods can be divided into the following two categories:
- Stack methods inherited from the vector class. The first methods stack offers are those inherited from the vector class. If you’re looking to learn more about these methods, research the “Java vector class”.
- Stack methods that are unique to stack. Stack also offers five additional methods that are unique to the class. We’ll discuss them below. They are:
- push()
- pop()
- peek()
- empty()
- search()
The push() and pop() operations are arguably the most commonly used. They let you add and remove items from a stack respectively.
Add Item to a Java Stack: push()
The push() method adds an item to a Java stack.
push() accepts one parameter: the item you want to add to your stack. For instance, suppose we are creating a stack that stores all the book titles in a library’s fiction section. We could use this code to add the first three book titles to the stack:
import java.util.Stack; class AddBooks { public static void main(String[] args) { Stack<String> books = new Stack<>(); books.push("Pride and Prejudice"); books.push("Nineteen Eighty-Four"); books.push("The Great Gatsby"); System.out.println(books); } }
Our code returns:
[Pride and Prejudice, Nineteen Eighty-Four, The Great Gatsby]
First, we import the Java stack module. Then we declare a class—called AddBooks—that stores the code for our program.
On the next line, we initialize a new stack—called books—that can store string values. We then use the push() method to add three books titles to our stack: Pride and Prejudice, Nineteen Eighty-Four, and The Great Gatsby. Finally, we print out the book titles in our books stack to the console.
Remove Item from a Java Stack: pop()
The pop()
method removes an element from the top of a stack. This method returns the element that you removed from the stack.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
Suppose we wanted to remove from our stack the entry for The Great Gatsby, which was the last book title we entered. We could add the following code to our program above to accomplish this task:
class RemoveBooks { public static void main(String[] args) { Stack<String> books = new Stack<>(); books.push("Pride and Prejudice"); books.push("Nineteen Eighty-Four"); books.push("The Great Gatsby"); String removed_book = books.pop(); System.out.println("Books: " + books); System.out.println("Removed book: " + removed_book); } }
Our code returns:
Books: [Pride and Prejudice, Nineteen Eighty-Four] Removed book: The Great Gatsby
In this example, our code removes the item on the top of the stack.
The item at the top of the stack is The Great Gatsby. Then, our program prints out the revised list of books preceded by Books: to the console. The title of the removed book preceded by Removed book: is also displayed on the console.
Retrieve First Object in Stack: peek()
When you’re working with stacks, you may want to retrieve the item at the top of the stack. That’s where the peek() method comes in. peek() accepts no parameters. It peeks at the top of the stack and returns the item it finds.
Suppose we want to find out which item is at the top of our stack, now that we have removed The Great Gatsby. We can use the following code to do so:
import java.util.Stack; class FindTopBook { public static void main(String[] args) { Stack<String> books = new Stack<>(); books.push("Pride and Prejudice"); books.push("Nineteen Eighty-Four"); String top_book = books.peek(); System.out.println("Book at top of stack: " + top_book); } }
Our code returns:
Book at top of stack: Nineteen Eighty-Four.
Our stack contains two items. Nineteen Eighty-Four is at the top of the stack, so when we use the peek() method, our program returns that book title.
Check if a Stack is Empty: empty()
The empty() method determines whether a stack is empty.
For instance, suppose we want to check whether our books stack is empty. We have been playing around with the data in our stack. Now we are not sure if the stack contains any more book titles.
We could use the following code to check if our stack is empty:
import java.util.Stack; class CheckBooksEmpty { public static void main(String[] args) { Stack<String> books = new Stack<>(); books.push("Pride and Prejudice"); books.push("Nineteen Eighty-Four"); String is_empty = books.empty(); System.out.println("Is the book stack empty? " + is_empty); } }
Our code returns:
Is the book stack empty? false
Our books stack contains two values, so it is not empty. Thus, books.empty() returns: false.
Search for an Element: search()
The search() method searches for an element in a stack.
search() accepts one parameter: the name of the item for which you want to search. It returns that item’s position in the stack.
Suppose we wanted to find out the position of Pride and Prejudice in our book titles stack. We could do so using this code:
import java.util.Stack; class FindPrideBookPosition { public static void main(String[] args) { Stack<String> books = new Stack<>(); books.push("Pride and Prejudice"); books.push("Nineteen Eighty-Four"); String find_book = books.search("Pride and Prejudice"); System.out.println("Position of 'Pride and Prejudice': " + find_book); } }
Our code returns:
Position of 'Pride and Prejudice': 1.
The first item in a stack has the position number 1,. Because Pride and Prejudice is first item in the stack, our program returns 1.
Conclusion
The Java stack class is used to create stacks with a LIFO structure. This tutorial discussed the basics of Java stacks and how you can create a stack. We also talked through the five methods used to retrieve and manipulate the contents of a stack.
Now you’re equipped with the knowledge you need to work with stacks like a professional Java developer. You can learn more about the Java programming language by reading our How to Learn Java guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.