What is the Deque.offer() method in Java?
In this shot, we will discuss how to use the Deque.offer() method in Java.
The Deque.offer() method is present in the Deque interface inside the java.util package. It is used to insert a particular element in the deque without the violation of capacity restrictions.
Syntax
boolean offer(element)
Parameter
The Deque.offer() takes one parameter.
element: This is the element to be inserted.
Return value
The Deque.offer() method returns a boolean value:
True: When the element is inserted successfully in the deque.False: When the element is not inserted successfully in the deque.
Code
Let’s look at the below code snippet.
import java.util.*;class Main{public static void main(String[] args){Deque<Integer> d = new LinkedList<Integer>();if(d.offer(12))System.out.println("Element 12 is inserted.");elseSystem.out.println("No space in deque.");if(d.offer(21))System.out.println("Element 21 is inserted.");elseSystem.out.println("No space in deque.");if(d.offer(42))System.out.println("Element 42 is inserted.");elseSystem.out.println("No space in deque.");}}
Explanation
- In line 1, we imported the required package.
- In line 2, we made a
Mainclass. - In line 4, we made a
mainfunction. - In line 6, we declared a deque consisting of
Integertype elements. - From lines 8 to 19, we used the
Deque.offer()method to insert the elements into the deque if it is not full, and then display a successful insertion message. If the insertion is not done successfully, it displays a message saying the deque is full.
In this way, we can use the Deque.offer() method in Java.