Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is Deque.offerFirst() method in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we will discuss the Deque.offerFirst() method in Java. The Deque.offerFirst() method is present in the Deque interface inside the java.util package.

The Deque.offerFirst() method is used to add or insert the given element in the front of the deque. It throws an exception if the adding element violates the restriction of size of the deque.

Syntax

Deque.offerFirst(element);

Parameters

The Deque.offerFirst() method takes an element that need to be added in the front of the deque.

Return value

The Deque.offerFirst() method returns a boolean variable :

  • true: If the element is added in the deque.
  • false: If the element is not added in the deque.

Example

Let’s look at the code snippet below.

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 ele=60;
dq.offerFirst(ele);
System.out.println("deque after offerFirst operation is:-\n"+ dq);
}
}
Using Deque.offerFirst() method in Java

Explanation

  • In line 1, we import the java.util.* package to include the Deque interface.
  • From line 7 to 17, we initialize a deque of Integer type and added the elements 10, 20, 30, 40, 50 in the deque.
  • In line 19, we print the elements of deque.
  • In line 21, we initialize a variable ele of int type that is to be added in the front of the deque.
  • In line 23, we add ele in front of the deque using the Deque.offerFirst() method.
  • In line 25, we print the deque after using the offerFirst() method.

In this way, we use the Deque.offerFirst() method in Java.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring