Here is a Java Program to Demonstrate the Stack class.
Output of Above Java Program
stack: Stack@19821f
push(42)
stack: Stack@19821f
push(66)
stack: Stack@19821f
push(99)
stack: Stack@19821f
pop -> 99
stack: Stack@19821f
pop -> 66
stack: Stack@19821f
pop -> 42
stack: Stack@19821f
pop -> Stack underflow.
0
stack: Stack@19821f
import java.util.*; class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } }
Output of Above Java Program
stack: Stack@19821f
push(42)
stack: Stack@19821f
push(66)
stack: Stack@19821f
push(99)
stack: Stack@19821f
pop -> 99
stack: Stack@19821f
pop -> 66
stack: Stack@19821f
pop -> 42
stack: Stack@19821f
pop -> Stack underflow.
0
stack: Stack@19821f