In this Program we are going to do check Stack is empty or not in Java.
Error Message:
Testing for empty stack
28 milliseconds
Catching EmptyStackException
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at com.lib.EmptyStackException.main(EmptyStackException.java:24)
Error Description:
In below program without checking the stack has elements or not we are going to pop the element,so we got an error.
package com.lib;
import java.util.Date;
import java.util.Stack;
public class EmptyStackException
{
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++)
{
s.pop();
}
s2 = System.currentTimeMillis();
System.out.println((s2 - s1) + " milliseconds");
}
}
Error Solution:
package com.lib;
import java.util.Date;
import java.util.Stack;
public class EmptyStackException
{
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++)
{
if(!s.isEmpty())
{
s.pop();
}
}
s2 = System.currentTimeMillis();
System.out.println((s2 - s1) + " milliseconds");
}
}
Output:
Testing for empty stack
25 milliseconds
Catching EmptyStackException
15 milliseconds
Post a comment
Please share your valuable feedback and share this article in social media.