The Stack
class is a
The firstElement()
method of the Stack
class returns the first element present in the Stack
object.
public E firstElement();
This method doesn’t take any parameters.
The firstElement()
method returns the first element of the Stack
object. If the Stack
object is empty, then NoSuchElementException
is thrown.
import java.util.Stack;class FirstElementExample {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// add elememtsstack.push(1);stack.push(2);stack.push(3);System.out.println("The stack is: " + stack);// Print first elementSystem.out.println("The first element of the stack is : " + stack.firstElement());}}
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
.