Java Deque getFirst() getLast() Methods Tutorial

In this section we will learn what the Deque getFirst() and getLast() methods are and how to use them in Java.

What is Java Deque getFirst() Method?

The Java Deque getFirst() method is used to get the first element (the head element) of a Deque object.

Java getFirst() Method Syntax:

E getFirst()

getFirst() Method Parameters:

The method does not take an argument.

getFirst() Method Return Value:

The return value of this method is the head element of a Deque object.

getFirst() Method Exceptions:

NoSuchElementException: We get this exception if the target Deque object was in fact empty!

Example: using Deque getFirst() method

import java.util.Deque;
import java.util.ArrayDeque;
class Main{
    public static void main(String[] args) {
        Deque<Integer> deque = new ArrayDeque<>();
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(0);
        deque.add(10);

        System.out.println("The first element of the Deque object is: "+deque.getFirst());
    }
        
}

Output:

The first element of the Deque object is: 1

What is Java Deque getLast() Method?

The Java Deque getLast() method is used to get the last (tail) element of a Deque object.

Java getLast() Method Syntax:

E getLast()

getLast() Method Parameters:

The method does not take an argument.

getLast() Method Return Value:

The return value of this method is the last (tail) element of the target Deque object.

getLast() Method Exceptions:

NoSuchElementException: We get this exception if the target Deque object was in fact empty!

Example: using Deque getLast() method

import java.util.Deque;
import java.util.ArrayDeque;
class Main{
    public static void main(String[] args) {
        Deque<Integer> deque = new ArrayDeque<>();
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(0);
        deque.add(10);

        System.out.println("The first element of the Deque object is: "+deque.getLast());
    }
        
}

Output:

The last element of the Deque object is: 10

Leave a Reply