|
| 1 | +--- |
| 2 | +Title: 'offer()' |
| 3 | +Description: 'Inserts the specified element into the queue if possible without violating capacity limits.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Elements' |
| 9 | + - 'Queues' |
| 10 | +CatalogContent: |
| 11 | + - 'learn-java' |
| 12 | + - 'paths/computer-science' |
| 13 | +--- |
| 14 | + |
| 15 | +The **`.offer()`** method is part of the Java [`Queue`](https://www.codecademy.com/resources/docs/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. |
| 16 | + |
| 17 | +Unlike the [`add()`](https://www.codecademy.com/resources/docs/java/queue/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. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +queue.offer(element) |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `element`: The element to be inserted into the queue. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +- Returns `true` if the element was added successfully, `false` if the queue is full. |
| 32 | + |
| 33 | +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. |
| 34 | + |
| 35 | +## Example: Using `.offer()` in a Print Job Queue System |
| 36 | + |
| 37 | +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: |
| 38 | + |
| 39 | +```java |
| 40 | +import java.util.Queue; |
| 41 | +import java.util.concurrent.ArrayBlockingQueue; |
| 42 | + |
| 43 | +public class PrintJobQueue { |
| 44 | + public static void main(String[] args) { |
| 45 | + Queue<String> printQueue = new ArrayBlockingQueue<>(2); // capacity of 2 |
| 46 | + |
| 47 | + boolean added = printQueue.offer("Document1"); |
| 48 | + System.out.println("Added Document1: " + added); |
| 49 | + |
| 50 | + added = printQueue.offer("Document2"); |
| 51 | + System.out.println("Added Document2: " + added); |
| 52 | + |
| 53 | + // Attempt to add another job to a full queue |
| 54 | + added = printQueue.offer("Document3"); |
| 55 | + System.out.println("Added Document3: " + added); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +The output generated by this code is: |
| 61 | + |
| 62 | +```shell |
| 63 | +Added Document1: true |
| 64 | +Added Document2: true |
| 65 | +Added Document3: false |
| 66 | +``` |
0 commit comments