What is Deque.offerLast method in Java?
In this shot, we will discuss the Deque.offerLast method in Java, which is present in the Deque interface inside the java.util package.
Deque.offerLast is used to add or insert the given element in the last of the deque. The Deque.offerLast method does throw an exception if the adding element violates the restriction of the deque’s size, in which case it returns false.
Syntax
Deque.offerLast(element);
Parameter
The Deque.offerLast method takes an element that needs to be added in the end of the deque.
Return
The Deque.offerLast method returns a Boolean variable:
True: If the element is added in the deque.False: If the element is not added in the deque.
Code
Let’s take a look at the code snippet.
import java.util.*;class Solution3 {public static void main(String[] args) {Deque<Integer> dq= new ArrayDeque<>();dq.add(10);dq.add(20);dq.add(30);dq.add(40);dq.add(50);System.out.println("the elements of deque are:-\n"+dq);int x=60;dq.offerLast(x);System.out.println("deque after offerLast operation is:-\n"+ dq);}}
Explanation
- In line 1, we imported
java.util.*package to include theDequeinterface. - From lines 7 to 17, we initialized the object of deque of
Integertype and added elements 10, 20, 30, 40, and 50. - In line 19, we printed the elements of deque.
- In line 21, we initialized a variable
xof int type that is to be added at the end of the deque. - In line 23, we added
xin front of deque usingdeque.offerLast()method. - In line 25, we printed the deque after using the
offerLast()method.
In this way, we can use the Deque.offerLast method in Java.