Java .add()

guicarminati's avatar
Published Aug 22, 2025
Contribute to Docs

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.

  • 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

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 => 8
System.out.println("The elements in the queue are: " + myQueue);
// adding 3 to myQueue
boolean 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 => 3
System.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: true
The elements in the queue are: [5, 2, 11, 7, 8, 3]

Visual representation of the .add() method:

A diagram showing the addition of an item to a queue. The top row displays a queue with the numbers 5, 2, 11, 7, and 8. Below, the code "queue_name.add(3);" is shown, with an arrow pointing to the end of the queue. The bottom row shows the updated queue: 5, 2, 11, 7, 8, 3, illustrating that the number 3 was added to the end of the queue.

All contributors

Contribute to 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