What is the Stack.firstElement method in Java?

Overview

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

The firstElement() method of the Stack class returns the first element present in the Stack object.

Syntax

public E firstElement();

Parameters

This method doesn’t take any parameters.

Return value

The firstElement() method returns the first element of the Stack object. If the Stack object is empty, then NoSuchElementException is thrown.

Code

import java.util.Stack;
class FirstElementExample {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The stack is: " + stack);
// Print first element
System.out.println("The first element of the stack is : " + stack.firstElement());
}
}

Explanation

In the code above, we create a Stack object and use the push method to add three elements, 1, 2, and 3. We then call the firstElement method on the stack object to get the first element.

stack.firstElement();

The code above will return 1.