ConcurrentLinkedDeque offer() method in Java with Examples

The java.util.concurrent.ConcurrentLinkedDeque.offer() method is an inbuilt method in Java which inserts the specified element, passed as a parameter, to the deque.
Syntax:
public boolean offer(E elem)
Parameters: The method accepts a parameter elem which species the element to be inserted to the deque.
Return Value: The function returns True if the element is successfully added into the deque and returns False otherwise.
Exception: The function throws a NullPointerException if the passed parameter is NULL.
Below programs illustrate the ConcurrentLinkedDeque.offer() method:
Program 1:
// Java Program to Demonstrate offer()// method of ConcurrentLinkedDeque import java.util.concurrent.*; class GFG { public static void main(String[] args) { // Creating an empty Deque ConcurrentLinkedDeque<String> cld = new ConcurrentLinkedDeque<String>(); // Add elements into the Deque cld.add("Welcome"); cld.add("To"); cld.add("Geeks"); cld.add("4"); cld.add("Geeks"); // Displaying the Deque System.out.println("ConcurrentLinkedDeque: " + cld); // Insert an element using offer() if (cld.offer("GFG")) { // Displaying message System.out.println("Element Inserted"); } else { // Displaying message System.out.println("Element not Inserted"); } // Displaying the Deque System.out.println("ConcurrentLinkedDeque: " + cld); }} |
Output:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks] Element Inserted ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks, GFG]
// Java Program to Demonstrate offer()// method of ConcurrentLinkedDeque import java.util.concurrent.*; class GFG { public static void main(String[] args) { // Creating an empty Deque ConcurrentLinkedDeque<String> cld = new ConcurrentLinkedDeque<String>(); // Add elements into the Deque cld.add("Welcome"); cld.add("To"); cld.add("Geeks"); cld.add("4"); cld.add("Geeks"); // Displaying the Deque System.out.println("ConcurrentLinkedDeque: " + cld); try { // Insert null element using offer() cld.offer(null); } catch (Exception e) { System.out.println(e); } }} |
Output:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks] java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html#offer-E-



