Stack in java

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. With the release of JDK 5, Stack was retrofitted for generics and is declared as shown here:

class Stack<E>

Here, specifies the type of element stored in the stack.

To put an object on the top of the stack, call push( ). To remove and return the top element, call pop( ). An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty. You can use peek( ) to return, but not remove, the top object. The empty( ) method returns true if nothing is on the stack. The search( ) method determines whether an object exists on the stack and returns the number of pops that are required to bring it to the top of

 Method Description
 boolean empty( )Returns true if the stack is empty, and returns false if the stack
   contains elements.
 E peek( ) Returns the element on the top of the stack, but does not remove it.
 E pop( ) Returns the element on the top of the stack, removing it in the
 E push(E element)Pushes element onto the stack. element is also returned.
 int 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.
The Methods Defined by Stack

Demonstrate the Stack class

import java.util.*;

class StackDemo {

static void showpush(Stack<Integer> st, int a) { st.push(a);

System.out.println("push(" + a + ")"); System.out.println("stack: " + st);


static void showpop(Stack<Integer> st) { System.out.print("pop -> "); Integer a = st.pop(); System.out.println(a); System.out.println("stack: " + st);


public static void main(String args[]) { Stack<Integer> st = new Stack<Integer>();

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");




Leave a Comment