Write a Java program to Accessing the head of the queue using peek() methods


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and access the element at the head of the queue without removing it using the peek() method. The peek() method returns the head element of the queue, or null if the queue is empty.

  • A Queue interface is implemented using the LinkedList class to create a queue to store strings.
  • Several elements ("Blue", "White", "Black", "Orange", "Pink", "Yellow") are added to the queue using the offer() method.
  • The current elements in the queue are printed using System.out.println().
  • The peek() method is used to access the element at the head of the queue without removing it. The value is stored in the headElement variable.
  • The element at the head of the queue is printed if it is not null, indicating that the queue is not empty. If it is null, a message is printed indicating that the queue is empty.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class RemoveElement
{
        public static void main(String[] args)
	{
		Queue<String> queue = new LinkedList<>();
		queue.offer("Blue");
		queue.offer("White");
		queue.offer("Black");
		queue.offer("Orange");
		queue.offer("Pink");
		queue.offer("Yellow");
 
		System.out.println("Queue Elements : "+queue);
 
		// Access the element at the head of the queue using peek()
		String headElement = queue.peek();
 
		if (headElement != null)
		{
			System.out.println("Element at the head of the Queue : " + headElement);
		}
		else
		{
			System.out.println("The queue is Empty");
		}
    }
}

Output

Queue Elements : [Blue, White, Black, Orange, Pink, Yellow]
Element at the head of the Queue : Blue

Example Programs