What is the Stack.lastElement method in Java?

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 lastElement() method of the Stack class returns the last element present in the Stack object.

Syntax

public E lastElement();

This method doesn’t take any arguments.

Return value

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

Code

import java.util.Stack;
class StackLastElementExample {
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 last element
System.out.println("The last element of the stack is : " + stack.lastElement());
}
}

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 lastElement method on the stack object to get the last element.

stack.lastElement();

The code will return 3.

Free Resources