Difference between add() and offer() methods in Queue in Java
Last Updated :
17 Nov, 2022
Add() and Offer() are the methods used for adding the elements in the Queue. But both have their main function and they treat the elements differently.
add() method in Java:
It Inserts the specified element to the end of the queue if there is space, returning true upon success and throwing an IllegalStateException if no space is currently available. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false.
Exceptions: This method throws 5 exceptions listed below as follows:
- UnsupportedOperationException: if the add operation is not supported by this collection
- ClassCastException: if the class of the specified element prevents it from being added to this collection
- NullPointerException: if the specified element is null and this collection does not permit null elements
- IllegalArgumentException: if some property of the element prevents it from being added to this collection
- IllegalStateException: if the element cannot be added at this time due to insertion restrictions
Below is the Implementation of add() method in java:
Java
// add() method:
import java.util.*;
public class Main {
public static void main(String[] args)
{
// Creating Queue using the LinkedList
Queue<Integer> numbers = new LinkedList<>();
// Insert element at the rear of the queue
// using add method
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("Queue using add method: "
+ numbers);
}
}
OutputQueue using add method: [1, 2, 3]
If the element cannot be added at this time due to insertion restrictions:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<String> nums = new ArrayList<String>();
// Adding Elements
nums.add("CS");
nums.add("Mech");
nums.add("Electrical");
Iterator<String> itr = nums.iterator();
itr.remove();
}
}
Output:
Exception in thread "main" java.lang.IllegalStateException
at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:1010)
at GFG.main(GFG.java:13)
Offer() method in Java:
It Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception.
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 three exceptions which are described 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 is the Implementation of offer() method in java:
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
// Creating Queue using the LinkedList
Queue<Integer> numbers = new LinkedList<>();
// Insert element at the rear
// of the queue using offer
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
numbers.offer(4);
System.out.print("Queue using offer method: "
+ numbers);
}
}
OutputQueue using offer method: [1, 2, 3, 4]
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Declaration for priority Queue
Queue<String> str = new PriorityQueue<String>();
// Adding Elements
str.offer("CS");
str.offer("Mechanical");
str.offer("Electrical");
str.offer("Civil");
System.out.print(str);
}
}
Output[CS, Civil, Electrical, Mechanical]
Difference between add() and offer() method in java
Sl. No. | add() | offer() |
---|
1 | add() will throw an IllegalStateException if no space is currently available in the Queue, otherwise add method will return true. | offer() method will return false if the element cannot be inserted due to capacity restrictions. |
2 | add() method comes from the Collections framework. | offer() method comes from the queue. |
3 | add() method always returns true. | offer() method always returns false. |
4 | add() method throws an exception when no addition is possible in queue. | offer() method throws true or false if addition is done in the queue. |
Similar Reads
Difference Between poll() and remove() method of Queue Interface in Java
The queue is a data structure that stores elements in a first-in, first-out (FIFO) order. It can be used to implement a priority queue or as a basic synchronization primitive. The remove() method removes an element from the head of this queue and returns it. The poll() method blocks until one or mor
4 min read
Differences between wait() and join() methods in Java
The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution. wait() is mainly used for shared resources, a thread notifies other waiting thread when a resou
2 min read
Difference between PriorityQueue and Queue Implementation in Java
Java Queue InterfaceThe Java.util package has the interface Queue, which extends the Collection interface. It is employed to preserve the components that are handled according to the FIFO principle. It is an ordered list of items where new elements are added at the end and old elements are removed f
5 min read
Difference between ExecutorService execute() and submit() method in Java
The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads and that determine the shutdown status. In this art
4 min read
Queue offer() method in Java
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 s
5 min read
Difference between a Static Queue and a Singly Linked List
Static Queue: A queue is an ordered list of elements. It always works in first in first out(FIFO) fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which m
15+ min read
Difference between the Constructors and Methods
Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways. Constructors: Constructors ar
3 min read
List add(int index, E element) method in Java
The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list. Implementation:Java// Java code to illustrate add(int index, E elements) import java.util.*; public class ArrayListDemo { public static void main(String[] args)
2 min read
Difference between Array, Queue and Stack
Array: An Array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of
3 min read
Queue add() method in Java
The add(E e) method of Queue Interface inserts the element passed in the parameter to the end of the queue if there is space. If the Queue is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion. Syntax: boolea
4 min read