Skip to content
66 changes: 66 additions & 0 deletions content/java/concepts/queue/terms/offer/offer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
Title: 'offer()'
Description: 'Inserts the specified element into the queue if possible without violating capacity limits.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Tags:
- 'Elements'
- 'Queues'
CatalogContent:
- 'learn-java'
- 'paths/computer-science'
---

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 gracefully, making it useful when there is a need to handle capacity limits without triggering exceptions.

## Syntax

```pseudo
queue.offer(element)
```

**Parameters:**

- `element`: The element to be inserted to 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:

```java
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:

```shell
Added Document1: true
Added Document2: true
Added Document3: false
```