How to use the Stack class in Java
Pop removes the topmost element of a stack.
Declaring a Stack in Java
To declare Stack in Java, first, start with keyword stack, followed by angle brackets,<>, that contain the data type of the stack elements. Then write the name of the stack and at last, write the keyword new to allocate memory to the newly created stack.
The syntax for declaring a Stack in Java is: <stack>. The keyword, followed by the angle brackets contain the data type of the stack elements.
Stack<dataType> stackName = new Stack<>();
Methods in the Stack class
-
push():
The
push()method pushes an element, that is passed as the parameter, on the top of the stack. -
pop():
The
pop()method removes and returns the top element of the stack.An
EmptyStackExceptionexception is thrown if we call thepop()method on an empty stack. -
peek():
The
peek()method returns the element on the top of the stack but does not remove it. -
empty():
The
empty()method returnstrueif the stack is empty, otherwise, it returnsfalse. -
search(Object element):
The
search()method determines whether an object, which is the input parameter of the function, exists in the stack or not.If the element is found, it returns the position (as an
integer) of the element from the top of the stack otherwise it returns -1.
Example
Below is an example for implementing the Stack class in Java:
import java.util.*; //importing the stack classclass MyClass{public static void main (String[] args){// Creating a StackStack<Integer> even = new Stack<>();// pushing values in stackeven.push(0);even.push(2);even.push(4);even.push(6);even.push(8);even.push(10);even.push(12);even.push(14);even.push(16);//printing the stackSystem.out.println("Print Stack before pop:");System.out.println(even);// returning the number at the top of the stack and removing itSystem.out.println("pop => " + even.pop());System.out.println("pop => " + even.pop());System.out.println("pop => " + even.pop());//printing the stackSystem.out.println("Print Stack after pop:");System.out.println(even);// accessing the number at the top of the stack but not removing itSystem.out.println("Number on top of the stack is => " + even.peek());// checking if the stack is empty or notSystem.out.println("Is stack empty? Ans:" + even.empty());// checking the position of 8 in the stackSystem.out.println("Position of 8 from the top is " + even.search(8));// check if 20 exists in the stackSystem.out.println("Position of 20 from the top is " + even.search(20));}}
Free Resources