Java - The Stack Class
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines the following methods −
| Sr.No. | Method & Description |
|---|---|
| 1 | boolean empty()
This method tests if this stack is empty. |
| 2 | E peek()
This method looks at the object at the top of this stack without removing it from the stack. |
| 3 | E pop()
This method removes the object at the top of this stack and returns that object as the value of this function. |
| 4 | E push(E item)
This method pushes an item onto the top of this stack. |
| 5 | int search(Object o)
This method returns the 1-based position where an object is on this stack. |
Example
The following program illustrates several of the methods supported by this collection −
import java.util.*;
public 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");
}
}
}
This will produce the following result −
Output
stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack