Java Stack Class
Java Stack Class
Introduction
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.
Class declaration
Following is the declaration for java.util.Stack class −
Class constructors
Stack()
1
This constructor creates an empty stack.
Class methods
Page 2 of 6
boolean empty()
1
This method tests if this stack is empty.
E peek()
2 This method looks at the object at the top of this stack without removing it
from the stack.
E pop()
3 This method removes the object at the top of this stack and returns that
object as the value of this function.
E push(E item)
4
This method pushes an item onto the top of this stack.
int search(Object o)
5
This method returns the 1-based position where an object is on this stack.
Methods inherited
This class inherits methods from the following classes −
java.util.Vector
java.util.Collection
java.util.Object
java.util.List
Example
The following program illustrates several of the methods supported by Stack collection −
Open Compiler
import java.util.*;
public class StackDemo {
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