Write a Java program to check whether a queue is empty or not
The Java code defines a class named Check_EmptyNot that demonstrates how to check if a queue is empty or not using the isEmpty() method from the Queue interface. Here's a step-by-step explanation of the code:
- Import statements: The code imports the necessary classes to work with queues and lists from the java.util package.
- Check_EmptyNot class: This is the main class that contains the main method.
- Queue instantiation: The code creates two queues, queue_list and emp_list, using the LinkedList class. One queue contains elements of type String, and the other contains elements of type Integer.
- Adding elements to the first queue: The code adds some string elements to the queue_list using the add method.
- Printing the first queue: The code prints the elements of the first queue using System.out.println.
- Checking if the first queue is empty: The code uses the isEmpty() method to check if the queue_list is empty. The result is stored in the boolean variable isEmpty.
- Printing the result for the first queue: Based on whether the queue is empty or not, the code prints the appropriate message.
- Printing the second queue: The code prints the elements of the emp_list queue. This queue is empty since we haven't added any elements to it.
- Checking if the second queue is empty: The code uses the isEmpty() method to check if the emp_list is empty again and stores the result in the boolean variable isEmpty.
- Printing the result for the second queue: Based on whether the emp_list queue is empty or not, the code prints the appropriate message.
Source Code
import java.util.LinkedList;
import java.util.Queue;
public class Check_EmptyNot
{
public static void main(String[] args)
{
Queue <String> queue_list = new LinkedList <>();
Queue <Integer> emp_list = new LinkedList <>();
queue_list.add("Yellow");
queue_list.add("Green");
queue_list.add("Pink");
queue_list.add("Black");
queue_list.add("Blue");
queue_list.add("White");
System.out.println("First Queue Elements : " + queue_list);
// Check if the queue is empty
boolean isEmpty = queue_list.isEmpty();
if (isEmpty)
{
System.out.println("The First Queue is Empty");
}
else
{
System.out.println("The First Queue is Not Empty");
}
System.out.println("Second Queue Elements : " + emp_list);
isEmpty = emp_list.isEmpty();
if (isEmpty)
{
System.out.println("The Second Queue is Empty");
}
else
{
System.out.println("The Second Queue is Not Empty");
}
}
}
Output
First Queue Elements : [Yellow, Green, Pink, Black, Blue, White]
The First Queue is Not Empty
Second Queue Elements : []
The Second Queue is Empty