A stack is a data structure with LIFO (Last In, First Out), meaning the element that joins last is retrieved first. In Java, Stack is a generic class that implements this stack data structure. In this tutorial, we’ll learn more about Stacks in Java!
The first thing you need to know is that the Stack class extends the Vector class. It’s thread-safe, so manipulating elements in a Stack will be slower than with an ArrayDeque.
You can create a new Stack object as follows:
|
1 |
Stack<String> stack = new Stack<>(); |
You can add new elements using the push() method, remove and retrieve elements using the pop() method, and retrieve elements without removing them using the peek() method.
For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.huongdanjava.java; import java.util.Stack; public class Application { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("Khanh"); stack.push("Huong Dan Java"); stack.stream().forEach(System.out::println); System.out.println("Pop: " + stack.pop()); stack.stream().forEach(System.out::println); System.out.println("Peek: " + stack.peek()); stack.stream().forEach(System.out::println); } } |
In the example above, I added two elements, then retrieved and removed one element using the pop() method, and finally used the peek() method to retrieve one element without removing it. You will see that my stack still has one element left, as follows:

You can also use the search() method to search for an element in the stack or the size() method to check its size!
You can watch the video here.
