Java Utility Library

Java Stack - lastElement() Method



The java.util.Stack.lastElement() method returns the last element (top element) of the stack.

Syntax

public E lastElement()

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


Parameters

No parameter is required.

Return Value

Returns the last element of the stack.

Exception

Throws NoSuchElementException, if the stack is empty.

Example:

In the example below, the java.util.Stack.lastElement() method is used to display the content of the stack.

import java.util.*;

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

    //populating stack
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);

    System.out.print("MyStack contains: ");
    while(MyStack.size() != 0) {
      System.out.print(MyStack.lastElement()+ " ");
      MyStack.pop();
    }
  }
}

The output of the above code will be:

MyStack contains: 40 30 20 10 

❮ Java.util - Stack