Write a Java program to Clear all elements from a queue


The Java code defines a class ClearQueue with a method clearQueue that clears all elements from a given Queue of integers.

  • The clearQueue method takes a Queue named queue as input and calls the clear() method on the queue. This method clears all elements from the queue, making it empty.
  • In the main method, a Queue named queue is created using the LinkedList implementation of the Queue interface. Integers are added to the queue using the offer() method.
  • The original queue is printed using System.out.println().
  • The clearQueue method is then called with the queue as an argument, which clears all elements from the queue.
  • Finally, the cleared queue is printed using System.out.println().

Source Code

import java.util.*;
 
public class ClearQueue
{
	public static void clearQueue(Queue<Integer> queue)
	{
		queue.clear();
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);
		queue.offer(4);
		queue.offer(5);
 
		System.out.println("Original Queue : " + queue);
		clearQueue(queue);
		System.out.println("Cleared Queue : " + queue);
	}
}
 

Output

Original Queue : [1, 2, 3, 4, 5]
Cleared Queue : []

Example Programs