The
Stack
class is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The lastElement()
method of the Stack
class returns the last element present in the Stack
object.
public E lastElement();
This method doesn’t take any arguments.
The lastElement()
method returns the last element of the Stack
object. If the Stack
object is empty, then NoSuchElementException
is thrown.
import java.util.Stack;class StackLastElementExample {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 last elementSystem.out.println("The last element of the stack is : " + stack.lastElement());}}
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
.