Java Stack

Jakob Jenkov
Last update: 2020-05-21

The Java Stack class, java.util.Stack, is a classical stack data structure. You can push elements to the top of a Java Stack and pop them again, meaning read and remove the elements from the top of the stack.

The Java Stack class actually implements the Java List interface, but you rarely use a Stack as a List - except perhaps if you need to inspect all elements currently stored on the stack.

Please note, that the Java Stack class is a subclass of Vector, an older Java class which is synchronized. This synchronization adds a small overhead to calls to all methods of a Stack. Additionally, the Vector class uses several older (no longer recommended) parts of Java, like the Enumeration which is superseded by the Iterator interface. If you want to avoid these issues you can use a Java Deque as a stack instead.

Java Stack Tutorial Video

If you prefer video, I have a Java Stack tutorial video here: Java Stack Tutorial Video.

Java Stack Video Tutorial

Java Stack Basics

A Stack is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again. This is also referred to as the "Last In First Out (LIFO)" principle. In contrast, a Java Queue uses a "First In First Out (FIFO)" principle, where elements are added to the end of the queue, and removed from the beginning of the queue.

Create a Stack

To use a Java Stack you must first create an instance of the Stack class. Here is an example of creating a Java Stack instance:

Stack stack = new Stack();

Create a Stack with a Generic Type

You can set a generic type on a Stack specifying the type of objects the Stack instance can contain. You specify the stack type when you declare the Stack variable. Here is an example of creating a Java Stack with a generic type:

Stack<String> stack = new Stack<String>();

The Stack created above can only contain String instances.

Using a generic type on your Stack instances is recommended as it simplifies your code (no casts needed when accessing objects on the Stack), and decreases the risk that you push an object of the wrong type on the Stack.

Push Element on Stack

Once you have a Java Stack instance, you can push elements to the top of the Stack. The elements you push onto the Stack must be Java objects. Thus, you actually push objects to the Stack.

You push elements onto a Java Stack using its push() method. Here is an example of pushing an element (object) onto a Java Stack:

Stack<String> stack = new Stack<String>();

stack.push("1");

This Java example pushes a Java String with the text 1 onto the Stack. The String 1 is then stored at the top of the Stack.

Pop Element From Stack

Once an element has been pushed onto a Java Stack, you can pop that element from the Stack again. Once an element is popped off the Stack, the element is removed from the Stack. The top element of the Stack is then whatever element that was pushed onto the Stack just before the element just popped.

You pop an element off a Java Stack using the pop() method. Here is an example of popping an element off a Stack using the pop() method:

Stack<String> stack = new Stack<String>();

stack.push("1");

String topElement = stack.pop();

Once an element is popped off a Stack, the element is no longer present on the Stack.

Peek at Top Element of Stack

The Java Stack class has a method called peek() which enables you to see what the top element on the Stack is, without popping off the element. Here is an example of peeking at the top of a Java Stack:

Stack<String> stack = new Stack<String>();

stack.push("1");

String topElement = stack.peek();

After running this Java example the topElement variable will contain the String object 1 which was pushed onto the Stack just before peek() was called. The String object is still present on the Stack after calling peek().

Search the Stack

You can search for an object on the stack to get it's index, using the search() method. The object's equals() method is called on every object on the Stack to determine if the searched-for object is present on the Stack. The index you get is the index from the top of the Stack, meaning the top element on the Stack has index 1.

Here is how you search a Stack for an object:

Stack<String> stack = new Stack<String>();

stack.push("1");
stack.push("2");
stack.push("3");

int index = stack.search("3");     //index = 3

Stack Size

You can obtain the size of a Java Stack, meaning the number of elements currently stored on the Stack, via the Stack size() method. Here is an example of obtaining the size of a Java Stack via its size() method:

Stack<String> stack = new Stack<String>();

stack.push("1");
stack.push("2");
stack.push("3");

int size = stack.size();

After running this code the size variable will contain the value 3, since the Stack in the example contains 3 elements at the time its size() method is called.

Iterate Elements of Stack

You can iterate the elements of a Java Stack by obtaining a Java Iterator from the Stack. You obtain an Iterator by calling the Stack iterator() method. Here is an example of obtaining an Iterator from a Java Stack and iterating it:

Stack<String> stack = new Stack<String>();

stack.push("123");
stack.push("456");
stack.push("789");

Iterator iterator = stack.iterator();
while(iterator.hasNext()){
    Object value = iterator.next();
}

Process Stack Using Stream

It is also possible to process the elements on a Java Stack via the Java Stream API. You do so by first obtaining a Stream from the Stack via the stream() method.

Once you have obtained a Stream from the Stack, you can process the elements in the stream. Here is an example of obtaining a Stream from a Stack and processing the elements:

Stack<String> stack = new Stack<String>();
stack.push("A");
stack.push("B");
stack.push("C");

Stream stream = stack.stream();

stream.forEach((element) -> {
    System.out.println(element);  // print element
});

Notice, that this example uses a Java Lambda as parameter to the Stream.forEach() method. The lambda just prints out the element to System.out

Reverse List Using Stack

You can use a Java Stack to reverse a Java List. You do so by pushing all the elements from the List onto the Stack, starting with the element with index 0, then 1 etc. Each element is removed from the List, then pushed onto the Stack. Once all the elements are on the Stack, you pop the elements off one by one and add them back to the empty list. Here is an example of reversing a Java List using a Java Stack:

List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list);

Stack<String> stack = new Stack<String>();
while(list.size() > 0) {
    stack.push(list.remove(0));
}

while(stack.size() > 0){
    list.add(stack.pop());
}

System.out.println(list);

Use a Java Deque as a Stack

As mentioned at the top of this Java Stack tutorial, you can use a Java Deque as a stack too. The Java Deque tutorial also shows how you can do that - but I will show you a short example here too:

Deque<String> dequeAsStack = new ArrayDeque>String>();

dequeAsStack.push("one");
dequeAsStack.push("two");
dequeAsStack.push("three");

String one   = dequeAsStack.pop();
String two   = dequeAsStack.pop();
String three = dequeAsStack.pop();

As you can see, it looks pretty similar to using a regular Java Stack.

Stack Use Cases

A Stack is really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next