Java Utility Library

Java Stack - firstElement() Method



The java.util.Stack.firstElement() method returns the first element (bottom element) of the stack.

Syntax

public E firstElement()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the first element of the stack.

Exception

Throws NoSuchElementException, if the stack is empty.

Example:

In the example below, the java.util.Stack.firstElement() method is used to get the value of first element of the stack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<String> MyStack = new Stack<String>();

    //populating stack
    MyStack.push("Alpha");
    MyStack.push("Coding");
    MyStack.push("Skills");

    //checking stack
    System.out.println("First Element of Stack is: " + MyStack.firstElement());
  }
}

The output of the above code will be:

First Element of Stack is: Alpha

❮ Java.util - Stack