A Stack in Java is a collection (or group) of elements stored in the last in first out (LIFO) order. In other words, a stack is a data structure that stores data in last-in, first-out fashion.
This means an element that is stored as a last element into the stack, will be the first element to be removed from the stack. Only the top element on the stack is accessible at a given time.
When an element (object) is inserted into the stack, it is called push operation. We can create a stack of any type of elements.
When an element is removed from the stack, it is called pop operation.
When an element is searched in the stack, it is called operation.
Insertion and deletion of elements take place only from one side of the stack, traditionally called the top of the stack. That is, new elements are added to the top of the stack, and elements are removed from the top of the stack.
Therefore, stack is called last-in, first-out data structure. A typical example of stack in java is shown in the below figure.
As you can see in the above figure, we have added three elements A, B, and C into the stack. When they are removed from the stack, we obtain elements C, B, and A fashion. This fashion is called Last-In, First-Out data structure.
Let’s understand it with realtime examples to clear more.
Realtime Example of Stack in Java
1. A realtime example of stack is a stack of books as shown in the below figure. We can not take a book from the stack without removing books that are first stacked on top of it.
2. A second real-time example of stack is a pile of plates in a cafeteria where last washed plate will be out first for use.
3. Similarly, a DVD disk holder where CDs are arranged in such that the last CD will be out first for use. This is also an example of stack.
Stack class was introduced in Java 1.0 version. It is present in java.util.Stack<E> package. This class is now considered as legacy class in java because it is not consistent with Java Collections Framework.
Java API recommends using Java ArrayDeque class at the place of stacks. ArrayDeque provides all the normal functionality of a stack and it is consistent with the JCF.
Hierarchy of Java Stack Class
Java Stack class extends vector class that extends AbstractList class. It implements List interface and RandomAccess interface. Stack class also implements Serializable and Cloneable interfaces.
The hierarchy diagram of stack in java is shown in the below figure.
Stack Class declaration
Stack is a generic class in java that has the following declaration in a general form:
public class Stack<E> extends Vector<E>
Here, E represents the type of elements that stack can hold.
Features of Stack class
There are several features of stack in Java that are as follows:
1. Stack is a group of elements with “last-in, first-out” retrieval.
2. In the Java stack, all operations take place at the top of the stack.
3. Push operation inserts an element to the top of stack.
4. Pop operation removes an element from the stack and returns it.
5. Stack class is synchronized. That means it is thread-safe.
6. Null elements are allowed into the stack.
7. Duplicate elements are allowed into the stack.
Constructor of Stack Class in Java
Stack class has provided only one constructor that is as follows:
1. Stack(): This constructor is used to create an empty stack object. The general form to create a stack object is as follows:
Stack<E> stack = new Stack<E>(); For example: Stack<Integer> stack = new Stack<Integer>(); // It will store only Integer type objects.
Stack Methods in Java
In addition to methods that inherit from vector class, stack class has five additional methods of its own. They are as follows:
1. boolean empty(): This method is used to check the stack is empty or not. It returns true if and only if stack contains no elements (objects). Otherwise, it returns false.
2. E peek(): This method is used to retrieve the top-most element from the stack without removing it.
3. E pop(): The pop() method is used to pop (remove) the top-most element from the stack and returns it.
4. E push(E obj): This method pushes an element obj onto the top of the stack and returns that element (object).
5. int search(Object obj): This method returns the position of element obj from the top of stack. If the element is not present in the stack, it returns -1.
Java Stack Example Programs
Let’s take some example programs to perform the various operations based on the stack class methods in java.
1. Adding Elements: Using push() method, we can add elements to the stack. The push() method places the element at the top of stack.
Program source code 1:
import java.util.Stack; public class StackEx { public static void main(String[] args) { // Create an empty stack that contains String objects. Stack<String> st = new Stack<>(); // Checks that stack is empty or not. boolean empty = st.empty(); System.out.println("Is stack empty: " +empty); // Adds elements to the top of stack using push() method. st.push("Sunday"); st.push("Monday"); st.push("Tuesday"); st.push("Wednesday"); st.push("Thursday"); st.push("Friday"); st.push("Saturday"); // Displaying elements from the stack. System.out.println("Elements of Stack: " +st); } }
Output: Is stack empty: true Elements of Stack: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
2. Accessing Element: Using peek() method, we can retrieve or fetch an element at the top of stack without removing it. We will also serach the position of an element into the stack using search() method. Look at the source code below.
Program source code 2:
import java.util.Stack; public class StackEx2 { public static void main(String[] args) { // Create an empty stack that contains Integer objects. Stack<Integer> st = new Stack<>(); st.push(25); st.push(30); st.push(35); st.push(40); st.push(45); st.push(50); // Displaying elements from the stack. System.out.println("Elements of Stack: " +st); // Retrieving element at the top of stack. Object peekElement = st.peek(); System.out.println("Element at the top of stack: " +peekElement); // Find the position of element into the stack. System.out.println("Position of element 50: " +st.search(50)); System.out.println("Position of element 80: " +st.search(80)); } }
Output: Elements of Stack: [25, 30, 35, 40, 45, 50] Element at the top of stack: 50 Position of element 50: 1 Position of element 80: -1
3. Removing Elements: Using pop() method, we can pop an element from the stack in java.
Program source code 3:
import java.util.Stack; public class StackEx3 { public static void main(String[] args) { // Create an empty stack that contains Integer objects. Stack<Integer> st = new Stack<>(); st.push(25); st.push(30); st.push(35); st.push(40); st.push(45); st.push(50); // Displaying elements from the stack. System.out.println("Elements of Stack: " +st); // Removing elements from the stack one by one. while(st.size() > 0){ System.out.println("Removed element: " +st.pop()); } System.out.println("Is stack empty: " +st.empty()); } }
Output: Elements of Stack: [25, 30, 35, 40, 45, 50] Removed element: 50 Removed element: 45 Removed element: 40 Removed element: 35 Removed element: 30 Removed element: 25 Is stack empty: true
Program source code 4:
import java.util.Stack; public class StackEx4 { public static void main(String[] args) { Stack<Integer> st = new Stack<>(); st.push(25); st.push(30); st.push(35); st.push(40); st.push(45); System.out.println("Original elements of stack: " +st); System.out.println("Pop element: " +st.pop()); System.out.println("Elements of stack after removing: " +st); System.out.println("Push element: " +st.push(50)); System.out.println("Elements of stack after adding: " +st); } }
Output: Original elements of stack: [25, 30, 35, 40, 45] Pop element: 45 Elements of stack after removing: [25, 30, 35, 40] Push element: 50 Elements of stack after adding: [25, 30, 35, 40, 50]
Explanation:
Look at the above figure to understand push and pop operations in java stack more clearly.
Hope that this tutorial has covered important points related to stack class in java with realtime examples and programs with diagrams. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ What is Hashtable in Java