How to use the Stack class in Java

The Stack data structure is based on the Last In First Out (LIFO) principle and in Java, it implements the Java List interface.

The basic operations supported by a stack are push and pop.

Push adds an element at the top of a stack.

1 of 3

Pop removes the topmost element of a stack.

1 of 3

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 EmptyStackException exception is thrown if we call the pop() 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 returns true if the stack is empty, otherwise, it returns false.

  • 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 class
class MyClass{
public static void main (String[] args)
{
// Creating a Stack
Stack<Integer> even = new Stack<>();
// pushing values in stack
even.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 stack
System.out.println("Print Stack before pop:");
System.out.println(even);
// returning the number at the top of the stack and removing it
System.out.println("pop => " + even.pop());
System.out.println("pop => " + even.pop());
System.out.println("pop => " + even.pop());
//printing the stack
System.out.println("Print Stack after pop:");
System.out.println(even);
// accessing the number at the top of the stack but not removing it
System.out.println("Number on top of the stack is => " + even.peek());
// checking if the stack is empty or not
System.out.println("Is stack empty? Ans:" + even.empty());
// checking the position of 8 in the stack
System.out.println("Position of 8 from the top is " + even.search(8));
// check if 20 exists in the stack
System.out.println("Position of 20 from the top is " + even.search(20));
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved