Stack Class in Java – GeeksforGeeks

 

Java Collection framework provides a Stack class that models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search, and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.

The below diagram shows the hierarchy of the Stack class

 

 

Stack Class in Java

The class supports one default constructor Stack() which is used to create an empty stack

Declaration:

public class Stack<E> extends Vector<E>

All Implemented Interfaces:

  • Serializable: It is a marker interface that classes must implement if they are to be serialized and deserialized.
  • Cloneable: This is an interface in Java which needs to be implemented by a class to allow its objects to be cloned.
  • Iterable<E>: This interface represents a collection of objects which is iterable — meaning which can be iterated.
  • Collection<E>: A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired.
  • List<E>: The List interface provides a way to store the ordered collection. It is a child interface of Collection.
  • RandomAccess: This is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.

How to Create a Stack?

In order to create a stack, we must import java.util.stack package and use the Stack() constructor of this class. The below example creates an empty Stack.

Stack<E> stack = new Stack<E>();

Here E is the type of Object.

Example: 

Java




  

import java.io.*;

import java.util.*;

  

class Test

{   

    

    static void stack_push(Stack<Integer> stack)

    {

        for(int i = 0; i < 5; i++)

        {

            stack.push(i);

        }

    }

      

    

    static void stack_pop(Stack<Integer> stack)

    {

        System.out.println("Pop Operation:");

  

        for(int i = 0; i < 5; i++)

        {

            Integer y = (Integer) stack.pop();

            System.out.println(y);

        }

    }

  

    

    static void stack_peek(Stack<Integer> stack)

    {

        Integer element = (Integer) stack.peek();

        System.out.println("Element on stack top: " + element);

    }

      

    

    static void stack_search(Stack<Integer> stack, int element)

    {

        Integer pos = (Integer) stack.search(element);

  

        if(pos == -1)

            System.out.println("Element not found");

        else

            System.out.println("Element is found at position: " + pos);

    }

  

  

    public static void main (String[] args)

    {

        Stack<Integer> stack = new Stack<Integer>();

  

        stack_push(stack);

        stack_pop(stack);

        stack_push(stack);

        stack_peek(stack);

        stack_search(stack, 2);

        stack_search(stack, 6);

    }

}



Output:

Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found

Performing various operations on Stack class

1. Adding Elements: In order to add an element to the stack, we can use the push() method. This push() operation place the element at the top of the stack.

java-collection-framework-fundamentals-self-paced

Java




import java.io.*;

import java.util.*;

  

class StackDemo {

    

      

    public static void main(String[] args)

    {

  

        

        Stack stack1 = new Stack();

  

        

        

        Stack<String> stack2 = new Stack<String>();

  

        

        stack1.push(4);

        stack1.push("All");

        stack1.push("Geeks");

  

        stack2.push("Geeks");

        stack2.push("For");

        stack2.push("Geeks");

  

          

        System.out.println(stack1);

        System.out.println(stack2);

    }

}



 Output:

[4, All, Geeks]
[Geeks, For, Geeks]

2. Accessing the Element: To retrieve or fetch the first element of the Stack or the element present at the top of the Stack, we can use peek() method. The element retrieved does not get deleted or removed from the Stack. 

Java




import java.util.*;

import java.io.*;

  

public class StackDemo {

  

      

    public static void main(String args[])

    {

        

        Stack<String> stack = new Stack<String>();

  

        

        stack.push("Welcome");

        stack.push("To");

        stack.push("Geeks");

        stack.push("For");

        stack.push("Geeks");

  

        

        System.out.println("Initial Stack: " + stack);

  

        

        System.out.println("The element at the top of the"

                           + " stack is: " + stack.peek());

  

        

        System.out.println("Final Stack: " + stack);

    }

}



Output:

Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

3. Removing Elements: To pop an element from the stack, we can use the pop() method. The element is popped from the top of the stack and is removed from the same.

Java




import java.util.*;

import java.io.*;

  

public class StackDemo {

    public static void main(String args[])

    {

        

        Stack<Integer> stack = new Stack<Integer>();

  

        

        stack.push(10);

        stack.push(15);

        stack.push(30);

        stack.push(20);

        stack.push(5);

  

        

        System.out.println("Initial Stack: " + stack);

  

        

        System.out.println("Popped element: "

                           + stack.pop());

        System.out.println("Popped element: "

                           + stack.pop());

  

        

        System.out.println("Stack after pop operation "

                           + stack);

    }

}



Output:

Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

 Methods in Stack Class 

METHOD

DESCRIPTION

empty()

It returns true if nothing is on the top of the stack. Else, returns false.

peek()

Returns the element on the top of the stack, but does not remove it.

pop()

Removes and returns the top element of the stack. An ‘EmptyStackException’ 

An exception is thrown if we call pop() when the invoking stack is empty.

push(Object element)

Pushes an element on the top of the stack.

search(Object element)

It determines whether an object exists in the stack. If the element is found,

It returns the position of the element from the top of the stack. Else, it returns -1.

Methods inherited from class java.util.Vector

Note: Please note that the Stack class in Java is a legacy class and inherits from Vector in Java. It is a thread-safe class and hence involves overhead when we do not need thread safety. It is recommended to use ArrayDeque for stack implementation as it is more efficient in a single-threaded environment.

Java




  

import java.util.*;

  

class GFG {

    public static void main (String[] args) {

        Deque<Character> stack = new ArrayDeque<Character>();

        stack.push('A');

        stack.push('B');

        System.out.println(stack.peek());

        System.out.println(stack.pop());

    }

}



Output: 

B
B

My Personal Notes

arrow_drop_up