A stack is a type of linear data structure utilized for storing a group of items following the Last-In-First-Out (LIFO) principle. In the realm of Java programming, stacks are essential components supporting various algorithms and software applications. Within the Java Collection framework, numerous interfaces and classes are available for managing collections of items, including the Stack class. This class offers functionalities like push, pop, search, among others.
Within this segment, we will explore the Java Stack class, its functionalities, and create the stack data structure in a Java application. Prior to delving into the Java Stack class, let's first take a brief look at the operational mechanism of a stack.
Stack
The stack data structure is characterized by two fundamental operations: pushing and popping. Pushing involves adding an element to the stack, while popping involves removing an element from the top of the stack. Think of it as a vertical stack of plates where you can only interact with the top plate. Elements can be pushed onto the stack or popped off it. The last item added is the first one to be removed. Now, let's explore the functionalities of pushing and popping in a stack.
We will add the following numbers to the stack in this order: 20, 13, 89, 90, 11, 45, and 18.
Let's remove (pop) 18, 45, and 11 from the stack.
An empty stack refers to a stack that contains no elements. In such a case, the value of the top variable is set to -1 to indicate that the stack is empty.
When we push an element into the stack the top is increased by 1 . In the following figure,
- Push 12, top=0
- Push 6, top=1
- Push 9, top=2
Decreasing the top value by 1 occurs when an element is popped from the stack. In the illustration below, the value 9 has been popped.
The table presented below displays various values of the "top" property.
Java Stack Class
The Stack class in Java is part of the Collection framework and is an extension of the Vector class. Additionally, it implements various interfaces such as List, Collection, Iterable, Cloneable, and Serializable. This class is designed to represent a Last In First Out (LIFO) stack of objects. By utilizing generics, the Stack class can accommodate elements of various data types. The example in the main method showcases the usage of the Stack class with integer elements; however, it is adaptable to work with any other data type effortlessly.
Stack Class Constructor
The Stack class is equipped with a single default constructor responsible for generating an empty stack.
public Stack()
Creating a Stack
To initiate the creation of a stack in Java, begin by importing the java.util package and then instantiate an object of the Stack class.
Stack stk = new Stack();
Stack<type> stk = new Stack<>();
The type parameter indicates the data type of the stack, such as Integer, String, and so on.
Methods of the Stack Class
The stack allows us to execute operations such as push, pop, peek, and search. In Java, the Stack class offers a set of five primary methods to carry out these actions. Additionally, it inherits all the methods from the Java Vector class.
| Method | Modifier and Type | Method Description |
|---|---|---|
| empty() | boolean | The empty() method checks the stack is empty or not. |
| push(E item) | E | The push() method pushes (insert) an element onto the top of the stack. |
| pop() | E | The pop()method removes an element from the top of the stack and returns the same element as the value of that function. |
| peek() | E | The peek()method looks at the top element of the stack without removing it. |
| search(Object o) | int | The search() method searches the specified object and returns the position of the object. |
Stack Class empty Method
The empty function in the Stack class is utilized to determine whether the stack is empty. When the stack is devoid of any elements, the function will yield true, otherwise, it will yield false. Alternatively, the isEmpty function in the Vector class can also be employed for the same purpose.
Syntax
public boolean empty()
The function returns a boolean value indicating whether the stack is empty or not, returning true if it is empty and false if it is not.
In this instance, we have instantiated a Stack class object. Subsequently, we have called the empty function twice. Upon the initial invocation, it yields true as no elements have been pushed into the stack. Following this, elements are added to the stack. Upon calling the empty function again, it returns false as the stack is no longer devoid of elements.
Example
import java.util.Stack;
public class Main
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
Stack Class push Method
The function adds an element to the top of the stack, functioning similarly to the addElement(item) method in the Vector class. It requires the item parameter to push onto the stack.
Syntax
public E push(E item)
Argument: A value that is to be added to the top of the stack.
Output:
The function yields the parameter passed to it as an argument.
Stack Class pop Method
The function eliminates an item from the top of the stack and then returns that specific item. It raises an EmptyStackException when the stack is devoid of any elements.
Syntax
public E pop()
Output:
"Returns: This function retrieves and provides the object located at the top of the stack."
In this Java tutorial, we will create a stack implementation and demonstrate the functionality of push and pop operations.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
//creating an object of Stack class
Stack <Integer> stk = new Stack<>();
System.out.println("stack: " + stk);
//pushing elements into the stack
pushelmnt(stk, 20);
pushelmnt(stk, 13);
pushelmnt(stk, 89);
pushelmnt(stk, 90);
pushelmnt(stk, 11);
pushelmnt(stk, 45);
pushelmnt(stk, 18);
//popping elements from the stack
popelmnt(stk);
popelmnt(stk);
//throws exception if the stack is empty
try
{
popelmnt(stk);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
//performing push operation
static void pushelmnt(Stack stk, int x)
{
//invoking push() method
stk.push(new Integer(x));
System.out.println("push -> " + x);
//prints modified stack
System.out.println("stack: " + stk);
}
//performing pop operation
static void popelmnt(Stack stk)
{
System.out.print("pop -> ");
//invoking pop() method
Integer x = (Integer) stk.pop();
System.out.println(x);
//prints modified stack
System.out.println("stack: " + stk);
}
}
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
Stack Class peek Method
The method peek retrieves the highest element from the stack without eliminating it, enabling us to examine the element at the top of the stack without altering the stack's content. This method accesses the topmost element in the stack and raises an EmptyStackException error if the stack is devoid of elements.
Syntax
public E peek()
Output: This function retrieves the elements at the top of the stack.
Let's see an example of the peek method.
Example
import java.util.Stack;
public class StackPeekMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
// pushing elements into Stack
stk.push("Apple");
stk.push("Grapes");
stk.push("Mango");
stk.push("Orange");
System.out.println("Stack: " + stk);
// Access element from the top of the stack
String fruits = stk.peek();
//prints stack
System.out.println("Element at top: " + fruits);
}
}
Output:
Stack: [Apple, Grapes, Mango, Orange]
Element at the top of the stack: Orange
Stack Class search Method
The function searches for an item within the stack starting from the top position. It takes a parameter indicating the item to be searched for and then provides the position of the item in the stack, with the numbering starting from 1. The element at the very top of the stack is considered to be at a distance of 1.
Returns: It returns the object location from the top of the stack. If it returns -1, it means that the object is not on the stack.
Syntax
public int search(Object o)
Argument: o represents the object that needs to be searched.
Output: The function returns the position of the object at the top of the stack. If the return value is -1, it indicates that the object is not present on the stack.
Let's see an example of the search method.
Example
import java.util.Stack;
public class StackSearchMethodExample
{
public static void main(String[] args)
{
Stack<String> stk= new Stack<>();
//pushing elements into Stack
stk.push("Mac Book");
stk.push("HP");
stk.push("DELL");
stk.push("Asus");
System.out.println("Stack: " + stk);
// Search an element
int location = stk.search("HP");
System.out.println("Location of Dell: " + location);
}
}
Output:
Stack: [Mac Book, HP, DELL, Asus]
Location of Dell: 3
Java Stack Operations
Size of the Stack
The size of the stack can also be determined by utilizing the size function within the Vector class. This function provides the count of elements present in the stack, representing its total size.
Syntax
public int size()
Let's consider an illustration demonstrating the utilization of the size function from the Vector class.
Example
import java.util.Stack;
public class Main
{
public static void main (String[] args)
{
Stack stk = new Stack();
stk.push(22);
stk.push(33);
stk.push(44);
stk.push(55);
stk.push(66);
// Checks the Stack is empty or not
boolean rslt=stk.empty();
System.out.println("Is the stack empty or not? " +rslt);
// Find the size of the Stack
int x=stk.size();
System.out.println("The stack size is: "+x);
}
}
Output:
Is the stack empty or not? false
The stack size is: 5
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using three different methods are as follows:
- Using iterator Method
- Using forEach Method
- Using listIterator Method
Using the iterator Method
The iterator method is part of the Iterator interface. It is used to retrieve an iterator that allows traversing the elements within the stack. Prior to employing the iterator method, ensure to import the java.util.Iterator package.
Syntax
Iterator<T> iterator()
Let's perform an iteration over the stack.
Example
import java.util.Iterator;
import java.util.Stack;
public class Main
{
public static void main (String[] args)
{
//creating an object of Stack class
Stack stk = new Stack();
//pushing elements into stack
stk.push("BMW");
stk.push("Audi");
stk.push("Ferrari");
stk.push("Bugatti");
stk.push("Jaguar");
//iteration over the stack
Iterator iterator = stk.iterator();
while(iterator.hasNext())
{
Object values = iterator.next();
System.out.println(values);
}
}
}
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Using the forEach Method
Java offers a forEach function for looping through elements, which is specified in the Iterable and Stream interface.
Syntax
default void forEach(Consumer<super T>action)
We will loop through the stack by utilizing the forEach function.
Example
import java.util.*;
public class Main
{
public static void main (String[] args)
{
//creating an instance of Stack class
Stack <Integer> stk = new Stack<>();
//pushing elements into stack
stk.push(119);
stk.push(203);
stk.push(988);
System.out.println("Iteration over the stack using forEach() Method:");
//invoking forEach() method for iteration over the stack
stk.forEach(n ->
{
System.out.println(n);
});
}
}
Output:
Iteration over the stack using forEach() Method:
119
203
988
Using listIterator Method
The function provides a list iterator that traverses the elements in the specified list sequentially, beginning from the indicated position in the list. It moves through the stack in a top-to-bottom fashion.
Syntax
ListIterator listIterator(int index)
Argument: The function processes an argument called index.
Output the following: This function provides a list iterator that iterates over the elements in order.
Error: An IndexOutOfBoundsException is raised when the index is not within the valid range.
We will traverse the stack by employing the listIterator function.
Example
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;
public class Main
{
public static void main (String[] args)
{
Stack <Integer> stk = new Stack<>();
stk.push(119);
stk.push(203);
stk.push(988);
ListIterator<Integer> ListIterator = stk.listIterator(stk.size());
System.out.println("Iteration over the Stack from top to bottom:");
while (ListIterator.hasPrevious())
{
Integer avg = ListIterator.previous();
System.out.println(avg);
}
}
}
Output:
Iteration over the Stack from top to bottom:
988
203
119
Java stack MCQ
- Which of the following best describes the behavior of the push(E item) method in Java's Stack class?
- Adds the specified element to the top of the stack.
- Removes the specified element from the stack.
- Retrieves but does not remove the top element of the stack.
- Returns the number of elements in the stack.
The functionality of the push(E item) function in the Stack class of Java involves appending the given element to the top of the stack.
- What outcome is expected from the code snippet below?
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int top = stack.pop();
- top will be 1.
- top will be 2.
- top will be 0.
- Compilation error.
Explanation: The pop method in Java's Stack class removes and returns the top element of the stack, so top will be assigned the value 2.
- Which of the following methods in Java's Stack class returns the element at the top of the stack without removing it?
- push(E item)
- pop
- peek
- isEmpty
Explanation: The peek method in Java's Stack class retrieves but does not remove the top element of the stack.
- What is the time complexity of the push(E item) method in Java's Stack class?
- O(1)
- O(log n)
- O(n)
- O(n^2)
Explanation: The push(E item) method in Java's Stack class has a time complexity of O(1) as it simply adds the specified element to the top of the stack.
- When should the isEmpty method in Java's Stack class be used?
- To add an element to the top of the stack.
- To remove an element from the stack.
- To check if the stack is empty before performing a pop operation.
- To retrieve but not remove the top element of the stack.
The isEmpty function within the Stack class in Java is utilized to verify whether the stack is empty prior to executing actions such as pop, in order to prevent occurrences of exceptions such as EmptyStackException.