← Back to Core Java Course | Chapter 11: Collections | Lesson 14 of 17

Java Stack & Queue

Working with Stack (LIFO)

Stack (a legacy Vector subclass) provides LIFO (last-in, first-out) behavior through push() and pop() — the most recently added element is always the first one removed, like a stack of plates.

Example: Working with Stack (LIFO)

java
import java.util.Stack;
public class Main {
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(1);
		stack.push(2);
		System.out.println(stack.pop()); // 2: last in, first out
	}
}

Stack Search and Size

Stack also supports search() to find an element's 1-based distance from the top, and size()/isEmpty() for capacity checks — useful when you need to inspect the stack without popping through it.

Example: Stack Search and Size

java
import java.util.Stack;
public class Main {
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<>();
		stack.push(10);
		stack.push(20);
		System.out.println(stack.search(10)); // 1-based distance from top
		System.out.println(stack.size());
	}
}

Working with Queue (FIFO)

Queue provides FIFO (first-in, first-out) behavior through offer() and poll() — the first element added is always the first one removed, like people waiting in line.

Example: Working with Queue (FIFO)

java
import java.util.Queue;
import java.util.LinkedList;
public class Main {
	public static void main(String[] args) {
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		System.out.println(queue.poll()); // 1: first in, first out
	}
}

Modern Stack and Queue with Deque

ArrayDeque is generally preferred over the older Stack and LinkedList-as-queue for both roles today, since it's faster and was explicitly designed as a modern double-ended queue implementation.

Example: Modern Stack and Queue with Deque

java
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
	public static void main(String[] args) {
		Deque<Integer> deque = new ArrayDeque<>(); // preferred over Stack/LinkedList
		deque.push(1);
		deque.push(2);
		System.out.println(deque.pop());
	}
}

Handling Queue Edge Cases

Calling pop()/poll() on an empty stack or queue either throws an exception or returns null depending on which method you use — check isEmpty() first, or use the peek/poll variants that return null instead of throwing.

Example: Handling Queue Edge Cases

java
import java.util.Queue;
import java.util.LinkedList;
public class Main {
	public static void main(String[] args) {
		Queue<Integer> queue = new LinkedList<>();
		System.out.println(queue.poll()); // null: empty queue, no exception
		System.out.println(queue.isEmpty());
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.