Skip to content

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

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 queue’s Offer() method. The add() method internally just call the offer() method and does nothing extra.

And also, the add () method throws exception “java.lang.IllegalStateException: Queue full“, at the moment queue is full, whereas the offer() method returns 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. Note that the restricted queue means, the 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 the add() method, then it will throw an exception, and with the offer() method, a returned Boolean value false.

Example:

public class AddOfferTest {

	public static void main(String[] args) {	
		
		//Restricted queue with capacity of 2 elements
		BlockingQueue Q_Offer = new ArrayBlockingQueue(2);	//Only 2 elements can be added	
		
		boolean value = false;
		value =	Q_Offer.offer(5);
		System.out.println("Offer Returned Value:"+value);
		value =	Q_Offer.offer(10);
		System.out.println("Offer Returned Value:"+value);
		value =	Q_Offer.offer(15);
		System.out.println("Offer Returned Value:"+value);	// here it returns false.
	
		//Add() test
		BlockingQueue Q_Add = new ArrayBlockingQueue(2);
		Q_Add.add(5);
		Q_Add.add(10);
		Q_Add.add(15); //here exception occurs :java.lang.IllegalStateException: Queue full		

	}
}

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 the collection interface has add() method.

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


Published inJava Collections

One Comment

  1. Nana

    Another important reason also is;
    Where you expect an add method on a queue to work but you aren’t sure, you may use add() method which throws an exception if your expectation fails. If you use the offer() method and the addition doesn’t work, you may not know unless you explicitly get the returned value, which is a false

Comments are closed.