Stack is a legacy synchronized class. ArrayDeque is faster and is what the Javadoc recommends for LIFO use - push, pop and peek work on the head.
Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
stack.push("third");
System.out.println("peek = " + stack.peek());
System.out.println("pop = " + stack.pop());
System.out.println("remaining (top first) = " + stack);
peek = third
pop = third
remaining (top first) = [second, first]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30