tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Stack > Empty Stack

Empty Stack 

The following example shows how to empty the Stack and handle EmptyStackException. Stack provides the following APIs,

public E push(E paramE)
 - Pushes an element onto the top of stack. 

public synchronized E pop()
 - Removes the element at top of stack. Throws 'EmptyStackException' if Stack is empty.
 
public synchronized E peek()
 - Returns the object at top of stack without remove it from stack.
   Throws 'EmptyStackException' if Stack is empty. 
  
public boolean empty()
 - Returns true if the stack is empty otherwise false.   


File Name  :  
com/bethecoder/tutorials/utils/stack/EmptyStack.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.stack;

import java.util.EmptyStackException;
import java.util.Stack;

public class EmptyStack {

  /**
   @param args
   */
  public static void main(String[] args) {

    Stack<String> stack = new Stack<String>();
    stack.push("ONE");
    stack.push("TWO");
    stack.push("THREE");
    stack.push("FOUR");
    System.out.println("Stack : " + stack);
    System.out.println();
    
    //Empty stack
    while (!stack.isEmpty()) {
      System.out.println("Popped : " + stack.pop());
    }
    
    System.out.println();
    System.out.println("Stack : " + stack);
    
    //Invoking peek/pop on empty stack throws 'EmptyStackException' 
    try {
      stack.pop();
    catch (EmptyStackException e) {
      System.out.println(e);
    }
    
    try {
      stack.peek();
    catch (EmptyStackException e) {
      System.out.println(e);
    }
    
  }

}
   

It gives the following output,
Stack : [ONE, TWO, THREE, FOUR]

Popped : FOUR
Popped : THREE
Popped : TWO
Popped : ONE

Stack : []
java.util.EmptyStackException
java.util.EmptyStackException



 
  


  
bl  br