Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

data structures

How to use the Stack class in Java

Educative Answers Team

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.


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

    //printing the stack
    System.out.println("Print Stack before pop:");
    // 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:");
    // 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 " +;
    // check if 20 exists in the stack
    System.out.println("Position of 20 from the top is " +;


data structures
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring