Stacks and queues in Java are linear data structures. A stack follows LIFO (Last In, First Out), while a queue follows FIFO (First In, First Out). They are widely used in algorithms, memory management, and scheduling tasks.
In today’s world of scalable applications, understanding stacks and queues is essential. Whether you’re building fintech transaction systems or climate‑tech simulations, these structures help manage data efficiently.
Key Takeaways of Stacks and Queues in Java
- Stack → LIFO, used in undo operations, recursion.
- Queue → FIFO, used in scheduling, messaging systems.
- Java Implementation →
Stackclass,Queueinterface (LinkedList,PriorityQueue). - Real‑World Use → Task scheduling, memory management, customer service systems.
What is a Stack in Java?
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element added is the first one removed. Stacks are commonly used in recursion, undo operations, and expression evaluation.
Code Example:
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
// Push elements
stack.push(10);
stack.push(20);
stack.push(30);
// Pop element
int popped = stack.pop();
System.out.println("Stack after pop: " + stack);
System.out.println("Popped element: " + popped);
}
}
What is a Queue in Java?
A queue is a linear data structure that follows the FIFO (First In, First Out) principle. The first element added is the first one removed. Queues are widely used in scheduling, messaging systems, and order processing.
Code Example:
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
// Enqueue elements
queue.add(10);
queue.add(20);
queue.add(30);
// Dequeue element
int removed = queue.poll();
System.out.println("Queue after poll: " + queue);
System.out.println("Removed element: " + removed);
}
}

When Should You Use Stack vs Queue?
- Stack →
- Best for recursive calls (tracking function execution).
- Useful in undo features (like Ctrl+Z in editors).
- Ideal for expression evaluation (parsing).
- Queue →
- Best for order processing (e.g., customer service systems).
- Useful in task scheduling (CPU scheduling, print jobs).
- Ideal for message handling (chat applications, event queues).
What are the types of Linked lists in Java? Know more!
Stacks and Queues in Java Basics Code
java
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
public class StacksAndQueuesExample {
public static void main(String[] args) {
// Stack example
Stack stack = new Stack<>();
// Pushing elements into the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Popping elements from the stack
System.out.println("Stack elements:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
// Queue example
Queue queue = new LinkedList<>();
// Adding elements to the queue
queue.add(10);
queue.add(20);
queue.add(30);
// Removing elements from the queue
System.out.println("Queue elements:");
while (!queue.isEmpty()) {
System.out.println(queue.remove());
}
}
}
Explanation of the Code
This code is a simple demonstration of how Stacks and Queues in Java. Let’s break it down step-by-step:
- We import necessary classes from the Java library: `Stack`, `LinkedList`, and `Queue`.A Stack object is created to store integer elements. Stacks operate in a LIFO (Last In, First Out) manner.We push elements `10`, `20`, and `30` into the stack. They are added at the top.We then pop elements off the stack, one by one, printing them. The elements are displayed in reverse order, demonstrating the LIFO principle. Similarly, a Queue object is instantiated using a `LinkedList`, which operates in a FIFO (First In, First Out) fashion.We add the same elements to the queue and remove them, printing each one. They appear in the same order they were added, following FIFO logic.
Output
Stack elements:
30
20
10
Queue elements:
10
20
30

Comparison of Stacks and Queues in Java
| Feature | Stack (LIFO) | Queue (FIFO) |
|---|---|---|
| Principle | Last In First Out | First In First Out |
| Use Cases | Undo, recursion | Scheduling, messaging |
| Java Support | Stack class | Queue interface |
| Pros | Simple, efficient | Maintains order |
| Cons | Limited use cases | Can be slower with large data |
Real-Life Applications of Stacks and Queues in Java
- Google Search Autocomplete
Google uses queues to manage and process search queries efficiently. When users input characters, a queue collects these as tasks to find matching queries. This ensures quick response time even with millions of simultaneous searches.
import java.util.LinkedList;
import java.util.Queue;
public class SearchAutocomplete {
public static void main(String[] args) {
Queue queryQueue = new LinkedList<>();
queryQueue.add("java tutorials");
queryQueue.add("java streams");
queryQueue.add("java collections");
while (!queryQueue.isEmpty()) {
System.out.println("Processing query: " + queryQueue.poll());
}
}
}
// Output:
// Processing query: java tutorials
// Processing query: java streams
// Processing query: java collections
- Spotify Song Playback
Spotify implements a stack to maintain a user’s playback history. This lets you go back to previous songs by popping songs off the stack, ensuring listeners can enjoy a seamless music experience.
import java.util.Stack;
public class SongPlayback {
public static void main(String[] args) {
Stack playbackStack = new Stack<>();
playbackStack.push("Song A");
playbackStack.push("Song B");
playbackStack.push("Song C");
while (!playbackStack.isEmpty()) {
System.out.println("Playing: " + playbackStack.pop());
}
}
}
// Output:
// Playing: Song C
// Playing: Song B
// Playing: Song A
- Amazon Order Processing
Amazon utilizes queues to manage orders. Each order enters the queue and is processed in the same order, ensuring first-in, first-out service, which is crucial for fair and efficient handling of customer purchases.
import java.util.LinkedList;
import java.util.Queue;
public class OrderProcessing {
public static void main(String[] args) {
Queue orderQueue = new LinkedList<>();
orderQueue.add("Order 1");
orderQueue.add("Order 2");
orderQueue.add("Order 3");
while (!orderQueue.isEmpty()) {
System.out.println("Processing: " + orderQueue.poll());
}
}
}
// Output:
// Processing: Order 1
// Processing: Order 2
// Processing: Order 3
Stacks and Queues in Java- Interview Questions Guide
If you’re diving into Java and grappling with Stacks and Queues, you might come across a few recurring questions that pop up in forums like Reddit and Quora. Let’s dive straight into those questions without over-complicating things and see if we can’t clear the air a bit. Here’s a list of the most frequent queries, with straightforward answers to guide you along your coding journey:
- How can I implement a basic stack using an array in Java?
Sure, here’s a simple stack implementation using an array:
class Stack {
int top;
int[] arr;
int capacity;
Stack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
void push(int x) {
if (top == capacity - 1) throw new StackOverflowError("Stack is full");
arr[++top] = x;
}
int pop() {
if (top == -1) throw new RuntimeException("Stack is empty");
return arr[top--];
}
} - What is the difference between a stack and a queue?
Stacks operate on Last In, First Out (LIFO) principles, while queues operate on First In, First Out (FIFO) principles. Imagine a stack as a pile of plates where you always take the top plate. In contrast, think of a queue like a line of customers in a coffee shop—first to line up is the first served! - When would you use a stack over a queue?
Use a stack when you need to reverse items, like undo operations in editors, or handle recursive function calls. Queues are better suited for processing items in order, like in task scheduling or print queue tasks. - Can you demonstrate a simple queue using a linked list in Java?
Absolutely, here’s a basic example:
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class Queue {
Node front, rear;
Queue() {
front = rear = null;
}
void enqueue(int key) {
Node temp = new Node(key);
if (rear == null) {
front = rear = temp;
return;
}
rear.next = temp;
rear = temp;
}
int dequeue() {
if (front == null)
throw new RuntimeException("Queue is empty");
int item = front.data;
front = front.next;
if (front == null)
rear = null;
return item;
}
} - How do stacks help in expression evaluation?
Stacks can evaluate expressions by handling operators and operands efficiently. They’re particularly useful for managing the precedence of operators and processing postfix or prefix expressions. - Can you explain the time complexities of stack operations?
Sure, typical operations like push and pop in a stack are O(1) since they involve adding or removing an item from the top. It makes stacks highly efficient for such operations.
I hope this clears up some of the fog around stacks and queues in Java. They’re fundamental concepts that, once grasped, open the door to many different coding applications. Keep exploring and don’t shy away from experimenting with your own code!
Experience the future of coding with our AI-powered Java online compiler. Instantly write, run, and test your code, harnessing the power of AI for real-time feedback and enhanced learning. Dive into seamless coding with minimal effort, letting technology streamline your programming journey and bring your Java projects to life.
Conclusion
Stacks and Queues in Java sharpen programming skills, offering mastery over essential data structures. Why not tackle it yourself? Imagine the sense of achievement! For more on Java and other languages like Python and C++, check out Newtum. Dive into coding magic today!
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.