How to Use Stack in Java: Syntax, Example, and Tips
In Java, you can use the
Stack class from java.util to store elements in a last-in, first-out (LIFO) order. Use push() to add items, pop() to remove the top item, and peek() to view the top item without removing it.Syntax
The Stack class is a generic class that stores elements in a LIFO order. You create a stack by declaring Stack<Type> stack = new Stack<>();. Use push(element) to add an element, pop() to remove and return the top element, and peek() to see the top element without removing it.
java
import java.util.Stack; Stack<Integer> stack = new Stack<>(); stack.push(10); // Add 10 to stack int top = stack.peek(); // Look at top element int removed = stack.pop(); // Remove top element
Example
This example shows how to create a stack, add elements, check the top element, and remove elements in Java.
java
import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.push("Apple"); stack.push("Banana"); stack.push("Cherry"); System.out.println("Top element: " + stack.peek()); while (!stack.isEmpty()) { System.out.println("Popped: " + stack.pop()); } } }
Output
Top element: Cherry
Popped: Cherry
Popped: Banana
Popped: Apple
Common Pitfalls
One common mistake is calling pop() or peek() on an empty stack, which throws an EmptyStackException. Always check isEmpty() before these calls. Another pitfall is confusing Stack with other collections; remember it follows LIFO order.
java
import java.util.Stack; public class StackPitfall { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); // Wrong: popping without checking if empty // int value = stack.pop(); // Throws EmptyStackException // Right: check before popping if (!stack.isEmpty()) { int value = stack.pop(); System.out.println("Popped: " + value); } else { System.out.println("Stack is empty, cannot pop."); } } }
Output
Stack is empty, cannot pop.
Quick Reference
- push(E item): Add item to top
- pop(): Remove and return top item
- peek(): Return top item without removing
- isEmpty(): Check if stack is empty
- search(Object o): Find position of item from top
Key Takeaways
Use java.util.Stack to store elements in last-in, first-out order.
Always check isEmpty() before calling pop() or peek() to avoid exceptions.
Use push() to add, pop() to remove, and peek() to view the top element.
Stack methods like search() help find elements relative to the top.
Stack is useful for undo features, expression evaluation, and backtracking.