Stack in Java


A stack class is provided by the Java collection framework and it implements the Stack data structure. The stack implements LIFO i.e. Last In First Out. This means that the elements pushed last are the ones that are popped first.

The following are some of the methods.

Sr.NoMethods & Description
1boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
2Object peek( )
Returns the element on the top of the stack, but does not remove it.
3Object pop( )
Returns the element on the top of the stack, removing it in the process.
4Object push(Object element)
Pushes the element onto the stack. Element is also returned.
5int search(Object element)
Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned.

A program that demonstrates stack in Java is given as follows −

Example

 Live Demo

import java.io.*;
import java.util.*;
public class Example {
   public static void main (String[] args) {
      Stack<Integer> s = new Stack<Integer>();
      s.push(5);
      s.push(1);
      s.push(9);
      s.push(4);
      s.push(8);
      System.out.print("The stack is: " + s);
      System.out.print("
The element popped is: ");       Integer num1 = (Integer) s.pop();       System.out.print(num1);       System.out.print("
The stack after pop is: " + s);       Integer pos = (Integer) s.search(9);       if(pos == -1)       System.out.print("
The element 9 not found in stack");       else       System.out.print("
The element 9 is found at position " + pos + " in stack");    } }

Output

The stack is: [5, 1, 9, 4, 8]
The element popped is: 8
The stack after pop is: [5, 1, 9, 4]
The element 9 is found at position 2 in stack

Now let us understand the above program.

Five elements are pushed into the stack. Then the stack is displayed. After that the top element is popped and that is displayed. The code snippet that demonstrates this is given as follows −

Stack<Integer> s = new Stack<Integer>();
s.push(5);
s.push(1);
s.push(9);
s.push(4);
s.push(8);
System.out.print("The stack is: " + s);
System.out.print("
The element popped is: "); Integer num1 = (Integer) s.pop(); System.out.print(num1); System.out.print("
The stack after pop is: " + s);

After that, the element 9 is searched in the stack. If it is there, its position is displayed otherwise it is displayed that element is not in stack. The code snippet that demonstrates this is given as follows.

Integer pos = (Integer) s.search(9);
if(pos == -1)
System.out.print("
The element 9 not found in stack"); else System.out.print("
The element 9 is found at position " + pos + " in stack");

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements