Menu
Topics Index
...
`

Stack - Java Example Program


Stack
import java.util.Stack;

class StackTest
{
    public static void main(String arg[])
    {
        Stack<Integer> st = new Stack<Integer>();
        System.out.println("Is empty stack: " + st.empty());
        
        System.out.println("Stack A: " + st);
        st.push(42);
        System.out.println("Stack B:" + st);
        st.push(64);
        System.out.println("Stack C: " + st);
        st.pop();
        System.out.println("Stack D: " + st);
        st.push(96);
        System.out.println("Stack E: " + st);
        
        System.out.println("Peek integer: " + st.peek());
        System.out.println("Position: " + st.search(42));
        
        st.pop();
        System.out.println("Stack F: " + st);
        st.pop();
        System.out.println("Stack G: " + st);
    
    }
}
OUTPUT

Is empty stack: true
Stack A: []
Stack B: [42]
Stack C: [42, 64]
Stack D: [42]
Stack E: [42, 96]
Peek integer: 96
Position: 2
Stack F: [42]
Stack G: []

DESCRIPTION

In this program, stack is created, checked for empty then adds two integers, pops top element and again adds one integer and then returns peek integer, position of 42 and pops twice.

THINGS TO TRY
  • Try for the below code.
    st.add(1);
    st.add(10);
    st.add(100);
    System.out.println("Stack Elements : " + st);
The output for the above code is Stack Elements : [1, 10, 100], since Stack class extends Vector class, methods of Vector class are applicable for Stack class as well.
  • Try for the below code :
    Stack<Integer> st = new Stack<Integer>();
    st.add(10);
    st.add(100);
    st.remove(10);
    System.out.println("Stack Elements : " + st);
    The above code throws java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10, since here remove method accepts the argument as index value.
  • Try for the below code :
    Stack<String> st = new Stack<String>();
    st.add("Merit");
    st.add("Campus");
    System.out.println("Stack Elements : " + st);
    st.remove("Merit");
    System.out.println("Stack Elements after removing Merit : " + st);
    The output for the above code is :
    Stack Elements : [Merit, Campus]
    Stack Elements after removing Merit : [Campus]

    Here the remove method accepts the argument as an object, so the element Merit is removed from the Stack.

© meritcampus 2019

All Rights Reserved.

Open In App