Java .add()
The .add() method is a built-in method of the Queue interface in Java that inserts an element at the back of the queue. It returns true if the element is successfully added. Unlike .offer(), which returns false if the insertion fails, .add() throws an Exception. This method is commonly used with implementations such as LinkedList and ArrayDeque.
Syntax
queue_name.add(E element);
Parameters:
The .add() method requires an element as a parameter. The E is the type of the element parameter, which is the type of elements held in the queue_name collection.
Return value:
The .add() method returns true upon success. If the queue has a capacity limit and is full, .add() throws an IllegalStateException.
Example
In this example, a Queue in Java is created using LinkedList, elements are added to it, and then the .add() method is used to insert an additional element at the end of the queue:
import java.util.*;class JAVA {public static void main(String args[]){Queue<Integer> myQueue = new LinkedList<Integer>();myQueue.add(5);myQueue.add(2);myQueue.add(11);myQueue.add(7);myQueue.add(8);// myQueue before adding 3: 5 => 2 => 11 => 7 => 8System.out.println("The elements in the queue are: " + myQueue);// adding 3 to myQueueboolean success = myQueue.add(3);System.out.println("3 inserted at the back of the queue: " + success);// myQueue after adding 3: 5 => 2 => 11 => 7 => 8 => 3System.out.println("The elements in the queue are: " + myQueue);}}
The output generated by this code is:
The elements in the queue are: [5, 2, 11, 7, 8]3 inserted at the back of the queue: trueThe elements in the queue are: [5, 2, 11, 7, 8, 3]
Visual representation of the .add() method:

Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours