Write a Java program to check whether a Stack collection is empty or not


The code demonstrates how to check if a stack is empty or not in Java using the empty method of the Stack class. Let's break down the code:

  • The code starts by importing the necessary libraries: java.io.* and java.util.* .
  • The Chek_EmptyNot class is defined, serving as the entry point of the program.
  • In the main method, two stack objects are created using the raw Stack class: stck_list and stck_list2. Again, it is recommended to use generics for type safety.
  • Several strings, namely "Red," "Pink," "Yellow," and "Blue," are pushed onto stck_list using the push method.
  • The empty method is used to check if stck_list2 is empty. If it is empty, the code prints "Stack List 2 is Empty." Otherwise, it prints "Stack List 2 is Not Empty."
  • The empty method is used again to check if stck_list is empty. If it is empty, the code prints "Stack List 1 is Empty." Otherwise, it prints "Stack List 1 is Not Empty."

Source Code

import java.io.*;
import java.util.*;
public class Chek_EmptyNot
{
	public static void main(String[] args)
	{
		Stack stck_list = new Stack();
		Stack stck_list2 = new Stack();
 
		stck_list.push("Red");
		stck_list.push("Pink");
		stck_list.push("Yellow");
		stck_list.push("Blue");
 
		if (stck_list2.empty())
		{
			System.out.println("Stack List 2 is Empty");
		}
		else
		{
			System.out.println("Stack List 2 is Not Empty");
		}
 
		if (stck_list.empty())
		{
			System.out.println("Stack List 1 is Empty.");
		}
		else
		{
			System.out.println("Stack List 1 is Not Empty.");
		}
	}
}

Output

Stack List 2 is Empty
Stack List 1 is Not Empty.