In Java, firstElement() returns the element at index 0 of a Stack: the bottom of the stack, which is the oldest element still stored. Nothing is removed.
The name can mislead on a stack: "first" means first in the vector, not the next element to come off. The next one to come off is the top, which peek() and lastElement() return.
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 index 0.
Java
Stack<String> stack = new Stack<>();
stack.push("oldest");
stack.push("middle");
stack.push("newest"); // [oldest, middle, newest]
String bottom = stack.firstElement(); // "oldest"
String top = stack.peek(); // "newest"
new Stack<String>().firstElement(); // throws NoSuchElementException
Call
What it does
stack.firstElement()
The bottom element (index 0).
stack.get(0)
The same element; an index exception when empty.
stack.lastElement()
The other end: the top.
stack.isEmpty() ? null : stack.firstElement()
A read that gives null for an empty stack.
firstElement is a constant-time read of index 0.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized E firstElement()
firstElement(): NoSuchElementException
peek(): EmptyStackException
get(0): an index exception
How It Works
Vector's exception.firstElement() on an empty stack throws NoSuchElementException from java.util, which needs its own import.
Stack's exception.peek() reports the same situation with EmptyStackException, a separate class, so a catch for one does not catch the other.
The List way.get(0) fails with an index exception instead; the program prints fixed text so the output does not depend on the exact subclass or message.
Frequently Asked Questions
The bottom element at index 0, which is the oldest element still on the stack. It is not the next element pop() would return.
firstElement() reads the bottom; peek() reads the top. On an empty stack firstElement() throws NoSuchElementException while peek() throws EmptyStackException.
java.util.NoSuchElementException.
They return the same element. On an empty stack, get(0) throws ArrayIndexOutOfBoundsException instead of NoSuchElementException.
No. To remove the bottom element use remove(0) or removeElementAt(0).