adsense


Showing posts with label JAVA EXCEPTION EMPTY STACK EXCEPTION. Show all posts
Showing posts with label JAVA EXCEPTION EMPTY STACK EXCEPTION. Show all posts

Thursday, 29 October 2015

JAVA EXCEPTION EMPTY STACK EXCEPTION PAGE 127

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA EXCEPTION EMPTY STACK EXCEPTION





Java Examples - Empty stack exception


Problem Description:
How to handle the empty stack exception ?
Solution:
This example shows how to handle the empty stack exception by using s.empty(),s.pop() methods of Stack class and System.currentTimeMillis()method of Date class .
import java.util.Date;
import java.util.EmptyStackException;
import java.util.Stack;

public class ExceptionalTest {
   public static void main(String[] args) {
      int count = 1000000;
      Stack s = new Stack();
      System.out.println("Testing for empty stack");
      long s1 = System.currentTimeMillis();
      for (int i = 0; i <= count; i++)
      if (!s.empty())
         s.pop();
      long s2 = System.currentTimeMillis();
      System.out.println((s2 - s1) + " milliseconds");
      System.out.println("Catching EmptyStackException");
      s1 = System.currentTimeMillis();
      for (int i = 0; i <= count; i++) {
         try {
            s.pop();
         }
         catch (EmptyStackException e) {
         }
      }
      s2 = System.currentTimeMillis();
      System.out.println((s2 - s1) + " milliseconds");
   }
}
Result:
The above code sample will produce the following result.
Testing for empty stack
16 milliseconds
Catching EmptyStackException
3234 milliseconds