Search⌘ K
AI Features

Stack in Java

Explore the stack data structure in Java by learning its core principles and operations such as push, pop, and peek. Understand the last in, first out concept and how stacks handle overflow through custom implementations and practical examples.

Introduction to stack

A stack is an abstract data type or interface that extends the Collection interface in Java. It’s similar to the queue, though they differ in how they remove elements.

A stack uses the last in, first out (LIFO) method. This means when we perform deletion, the last element that was inserted is removed first. In a queue, the opposite happens. A queue works on the first in, first out (FIFO) algorithm.

This lesson will mainly concentrate on the Stack interface and its implementations.

Using the push() and pop() methods

Let’s start with some stack algorithms. The following program shows all the necessary algorithms for stacks.

Java
import java.util.Stack;
//StackExamples
class Main{
public static void main(String[] args) {
Stack<Integer> lists = new Stack<>();
lists.push(10);
lists.push(11);
lists.push(12);
lists.push(13);
lists.push(14);
System.out.println("Here are all the elements after they're pushed.");
for (int i = 0; i < 5; i++){
System.out.println(lists.get(i));
}
System.out.println("The last element of the stack: " + lists.lastElement());
System.out.println("Now we are going to remove one element.");
lists.pop();
System.out.println("Here are all the elements after one is popped.");
for (int i = 0; i < 4; i++){
System.out.println(lists.get(i));
}
System.out.println("The last element is gone! The last one will always be out first.");
System.out.println("For this reason, it is called last in, first out (LIFO)");
}
}

In the output, we can see how stacks work.

Here are all the elements after they're
...