Which to prefer add() or offer() to add items in Java Queue?

(Last Updated On: February 25, 2019)

Both java queue add () and offer () methods are available in the Queue interface and are used to add elements to the queue. Preference will be given to java queue Offer() method. add() internally just call offer() method and does nothing extra. And also, add () method throws exception “java.lang.IllegalStateException: Queue full” at the moment queue is full whereas offer() method will return a Boolean value false for the same in case the queue is of restricted capacity.

So, rather than handling the exception it is better to use Boolean values. Restricted queue means queue has some upper bond limit and further elements cannot be added.

For example, let’s have a java blocking queue and restrict it for containing 2 elements only. If we add one more element using add() method, then it will throw exception and with offer() method, a returned Boolean value that is false.

Example:

 

Recommended another interview question that is Java BlockingQueue interface with producer consumer design pattern

Notes:

You might be wondering, why two methods offer () and add () are available for the same operation.

Add() internally just call offer() method and does nothing extra. Since, Queue is an interface which extends Collection interface and collection interface has add() method.

So, all the methods declared in collection interface must be reflected in Queue interface too. That’s the only reason for having add() in the Queue besides offer().