The
offer(E e) method of
Queue Interface inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. This method is preferable to
add() method since this method does not throws an exception when the capacity of the container is full since it returns false.
Syntax:
boolean offer(E e)
Parameters: This method accepts a mandatory parameter
e which is the element to be inserted in the Queue.
Returns: This method returns true on successful insertion else it returns false.
Exceptions: The function throws four exceptions which are described as below:
- ClassCastException: when the class of the element to be entered prevents it from being added to this container.
- IllegalArgumentException: when some property of the element prevents it to be added to the queue.
- NullPointerException: when the element to be inserted is passed as null and the Queue's interface does not allow null elements.
Below programs illustrate offer() method of Queue:
Program 1: With the help of
LinkedBlockingDeque.
Output:
The Queue is not full and 10 is inserted
The Queue is not full and 15 is inserted
The Queue is not full and 25 is inserted
The Queue is full
Queue: [10, 15, 25]
Program 2: With the help of
ConcurrentLinkedDeque.
Output:
The Queue is not full and 10 is inserted
The Queue is not full and 15 is inserted
The Queue is not full and 25 is inserted
The Queue is not full and 20 is inserted
Queue: [10, 15, 25, 20]
Program 3: With the help of
ArrayDeque.
Output:
The Queue is not full and 10 is inserted
The Queue is not full and 15 is inserted
The Queue is not full and 25 is inserted
The Queue is not full and 20 is inserted
Queue: [10, 15, 25, 20]
Program 4: With the help of
LinkedList.
Output:
The Queue is not full and 10 is inserted
The Queue is not full and 15 is inserted
The Queue is not full and 25 is inserted
The Queue is not full and 20 is inserted
Queue: [10, 15, 25, 20]
Below programs illustrate
exceptions thrown by this method:
Program 5: To show
NullPointerException.