Java Stack lastElement() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Inherited from Vector

Definition

In Java, lastElement() returns the element at index size() - 1 of a Stack: the top, the element pushed most recently. Nothing is removed.

It reads the same element as peek(). The difference shows on an empty stack: lastElement() throws NoSuchElementException (it is a Vector method), while peek() throws EmptyStackException.

An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.

Syntax

Call it with no arguments to read the top.

Java
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);                        // [1, 2, 3]
int top = stack.lastElement();        // 3, same as stack.peek()
stack.pop();
int newTop = stack.lastElement();     // 2
new Stack<Integer>().lastElement();   // throws NoSuchElementException
CallWhat it does
stack.lastElement()The top element (index size() - 1).
stack.peek()The same element; EmptyStackException when empty.
stack.firstElement()The other end: the bottom.
stack.get(stack.size() - 1)The same element through the List API.

lastElement is a constant-time read.

Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized E lastElement()

Parameters

ParameterDescription
NonelastElement() takes no parameters.

Return Value

Return ValueDescription
EThe top element, the one pushed most recently.

Compare with Similar Methods

Methods with similar names or results:

MethodHow it differs
peek()The same element; the Stack-style call with EmptyStackException.
firstElement()Reads the bottom instead.
pop()Returns the top and removes it.
lastIndexOf(o)Despite the similar name, it finds a position, not the top element.

Java Examples

Example 1 — Show the Latest Temperature Reading

Readings are pushed as they arrive; the latest one is the top.

Java
import java.util.Stack;

public class StackLastElementDemo {
    public static void main(String[] args) {
        Stack<Integer> readings = new Stack<>();
        readings.push(18);
        readings.push(21);
        readings.push(19);

        System.out.println("latest reading: " + readings.lastElement());
        System.out.println("peek agrees:    " + readings.peek());
        System.out.println("first reading:  " + readings.firstElement());
        System.out.println("all readings:   " + readings);
    }
}

How It Works

  1. Last pushed, last element. 19 was recorded most recently, so it sits at the highest index and lastElement() returns it.
  2. Same as peek. peek() reads the identical slot, so both lines print 19.
  3. The other end. firstElement() returns 18, the earliest reading, and the full list confirms the order 18, 21, 19.

Example 2 — Track the Current Document Version

A document's versions are a stack: undo pops one, a new edit pushes one.

Java
import java.util.Stack;

public class StackLastElementTracking {
    public static void main(String[] args) {
        Stack<String> versions = new Stack<>();
        versions.push("draft");
        versions.push("review");
        System.out.println("current: " + versions.lastElement());

        versions.pop();
        System.out.println("after undo: " + versions.lastElement());

        versions.push("final");
        System.out.println("after edit: " + versions.lastElement());
        System.out.println("versions: " + versions);
    }
}

How It Works

  1. Start at the newest version. review was pushed after draft, so it is the current version.
  2. Undo moves the top down. After pop() removes review, lastElement() reports draft without any extra bookkeeping.
  3. A new edit becomes the top. Pushing final makes it the last element; review is gone for good, as in a real editor's history.

Example 3 — Catch the Exception lastElement() Really Throws

A helper wraps lastElement(); compare it with peek() on the same empty stack.

Java
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
import java.util.Stack;

public class StackLastElementEmpty {
    static String topOf(Stack<String> s) {
        try {
            return s.lastElement();
        } catch (NoSuchElementException e) {
            return "(none: " + e.getClass().getSimpleName() + ")";
        }
    }

    public static void main(String[] args) {
        Stack<String> jobs = new Stack<>();
        System.out.println("lastElement: " + topOf(jobs));
        try {
            jobs.peek();
        } catch (EmptyStackException e) {
            System.out.println("peek:        (none: " + e.getClass().getSimpleName() + ")");
        }
        jobs.push("backup");
        System.out.println("lastElement: " + topOf(jobs));
    }
}

How It Works

  1. Catch what the method throws. topOf catches NoSuchElementException, the exception lastElement() uses for an empty stack.
  2. peek needs a different catch. The same empty stack makes peek() throw EmptyStackException; neither class extends the other, so one catch block would not cover both.
  3. The normal case. Once a job is pushed, topOf simply returns it: backup.

Frequently Asked Questions

The top element, the one pushed most recently. It is the same element peek() returns.
They read the same element. On an empty stack lastElement() throws NoSuchElementException and peek() throws EmptyStackException.
No. Use pop() to read and remove it.
No. lastElement() returns the top element; lastIndexOf(o) returns the index of the last occurrence of o.
peek() states the stack intent more clearly. lastElement() is useful when code treats the Stack as a Vector or List.

Next: lastIndexOf()

Position of the match closest to the top.

lastIndexOf() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful