Java offer()
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.
Syntax
queue.offer(element)
Parameters:
element: The element to be inserted into the queue.
Return value:
- Returns
trueif the element was added successfully,falseif 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 2boolean 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 queueadded = printQueue.offer("Document3");System.out.println("Added Document3: " + added);}}
The output generated by this code is:
Added Document1: trueAdded Document2: trueAdded Document3: false
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