Java ArrayBlockingQueue add() Method

The add() method of ArrayBlockingQueue() appends the defined element at the tail end of the queue if the queue's capacity allows it.

The method returns true on successful insertion and throws an IllegalStateException if queue doesn't has enough capacity.

Syntax:

Parameters:

e - This is the element to be added.

Specified By:

The add() method of class ArrayBlockingQueue is specified by:

  1. add() method in interface Queue<E>
  2. add() method in interface Collection<E>
  3. add() method in interface BlockingQueue<E>

Override:

The add() method of class ArrayBlockingQueue overrides the add() method of class AbstractQueue<E>.

Throws:

The add() method throws :

NullPointerException - If the element defined is null.

IllegalStateException - If the queue is full.

Return Value:

The add() method returns true(as defined by Collection.add(E)).

Example 1

Output:

After adding 1 to the queue :
[1]

After adding 2 to the queue :
[1, 2]

After adding 3 to the queue :
[1, 2, 3]

After adding 4 to the queue :
[1, 2, 3, 4]

After adding 5 to the queue :
[1, 2, 3, 4, 5]

Example 2

Output:

1 Lower case = aman
  Upper case = AMAN

2 Lower case = bhavika
  Upper case = BHAVIKA

Example 3

Output:

71018
8000
1178
1190
Max number = 71018
Min number = 1178

Example 4

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ArrayBlockingQueue.checkNotNull(ArrayBlockingQueue.java:150)
	at java.util.concurrent.ArrayBlockingQueue.offer(ArrayBlockingQueue.java:325)
	at java.util.AbstractQueue.add(AbstractQueue.java:95)
	at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
	at com.javaTpoint.ArrayBlockingQueue_addMethodExample4.main(ArrayBlockingQueue_addMethodExample4.java:16)

If any specified element in the queue is null, it will give you NullPointerException as shown above.