Java offer()

arisdelaCruz1413618857's avatar
Published Aug 24, 2025
Contribute to Docs

The .offer() method is part of the Java Queue interface and inserts an element at the end of the queue. It returns true if the element was added successfully, or false if the queue is at capacity and cannot accept new elements.

Unlike the add() method, which throws an exception when the queue is full, .offer() fails, making it useful when there is a need to handle capacity limits without triggering exceptions.

  • 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.offer(element)

Parameters:

  • element: The element to be inserted into the queue.

Return value:

  • Returns true if the element was added successfully, false if the queue is full.

The .offer() method is non-blocking, meaning it returns immediately if the queue is full. Instead of throwing an exception when capacity is reached, it returns false, making it safer for capacity-aware operations. Its behavior may vary between bounded and unbounded queue implementations.

Example: Using .offer() in a Print Job Queue System

In this example, a bounded queue with capacity two demonstrates how .offer() returns true when adding elements within capacity and false when the queue is full:

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class PrintJobQueue {
public static void main(String[] args) {
Queue<String> printQueue = new ArrayBlockingQueue<>(2); // capacity of 2
boolean added = printQueue.offer("Document1");
System.out.println("Added Document1: " + added);
added = printQueue.offer("Document2");
System.out.println("Added Document2: " + added);
// Attempt to add another job to a full queue
added = printQueue.offer("Document3");
System.out.println("Added Document3: " + added);
}
}

The output generated by this code is:

Added Document1: true
Added Document2: true
Added Document3: false

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