In Java, a stack is a data structure that follows the LIFO (Last In, First Out) principle. This means the most recently added element is the first one to be removed.
1. Using java.util.Stack
Java provides a built-in Stack
class in java.util
package.
Example:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Stack: " + stack);
// Peek at the top element
System.out.println("Top element: " + stack.peek());
// Pop elements
System.out.println("Popped: " + stack.pop());
System.out.println("Stack after pop: " + stack);
// Check if empty
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
Output:
Stack: [10, 20, 30]
Top element: 30
Popped: 30
Stack after pop: [10, 20]
Is stack empty? false
2. Common Methods in Stack
push(E item)
→ Inserts an item onto the top of the stack.pop()
→ Removes and returns the top item.peek()
→ Returns the top item without removing it.isEmpty()
→ Returnstrue
if stack is empty.search(Object o)
→ Returns 1-based position from top of stack (or -1 if not found).
3. Implementing Stack with Deque
(Recommended)
Although Stack
is available, it’s considered legacy. It’s better to use Deque
(like ArrayDeque
) for stack operations.
Example with ArrayDeque
:
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeStackExample {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(100);
stack.push(200);
stack.push(300);
System.out.println("Stack: " + stack);
System.out.println("Top: " + stack.peek());
System.out.println("Popped: " + stack.pop());
System.out.println("Stack after pop: " + stack);
}
}