Write a Java program to add elements to Queue using add() and offer() methods


The Java code demonstrates how to use the add() and offer() methods to add elements to a queue using the LinkedList class. Both add() and offer() methods are used to add elements to the end of the queue, but they behave slightly differently when the queue is full. Here's a brief explanation of the code:

  • The Queue interface is implemented using the LinkedList class, creating a queue to store strings.
  • The add() method is used to add elements to the queue. In this case, "Orange", "Yellow", and "Green" are added using add().
  • The offer() method is used to add elements to the queue. In this case, "Pink", "Black", "Blue", "White", and "Red" are added using offer().
  • The System.out.println() statements are used to print the queue after adding elements, showing the contents of the queue.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class AddOfferMethods
{
	public static void main(String[] args)
	{
		Queue <String> queue_list = new LinkedList <>();
 
		// Add elements to the queue using add()
		queue_list.add("Orange");
		queue_list.add("Yellow");
		queue_list.add("Green");
		System.out.println("Queue after adding elements using add() : " + queue_list);
 
		// Add elements to the queue using offer()      
		queue_list.offer("Pink");
		queue_list.offer("Black");
		queue_list.offer("Blue");
		queue_list.offer("White");
		queue_list.offer("Red");
		System.out.println("Queue after adding elements using offer() : " + queue_list);
	}
}

Output

Queue after adding elements using add() : [Orange, Yellow, Green]
Queue after adding elements using offer() : [Orange, Yellow, Green, Pink, Black, Blue, White, Red]

Example Programs