View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Stack and Queue in Java: Key Concepts, Differences and Applications

Updated on 28/04/20256,135 Views

When working with data structures in Java, two essential structures you'll frequently encounter are Stack and Queue. Both are used to organize and manage data, but they operate on different principles. 

A Stack follows the Last-In, First-Out (LIFO) approach, where the last element added is the first one removed. In contrast, a Queue follows the First-In, First-Out (FIFO) method, where elements are processed in the order they arrive. Java provides built-in support for both structures through the java.util package. 

In this blog, we will explore Stack and Queue in Java Programming language, their implementation, key methods, and real-world applications.

Level up your coding skills with upGrad’s Software Engineering Course. Start your journey today!

What is Stack in Java?

A Stack in Java is a linear data structure that follows the Last-In, First-Out (LIFO) principle. This means the last element added to the stack is the first one removed. Think of a stack like a pile of plates—you add plates on top and remove the topmost plate first.

In Java, the Stack class is a part of the java.util package and extends the Vector class.

Step into the future of tech with these top-rated software engineering courses:

How to Implement Stacks in Java?

You can easily implement a stack in Java using the built-in Stack class from the java.util package.

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Stack elements: " + stack);
    }
}

Output:

Stack elements: [10, 20, 30]

Explanation:

Here, a stack of integers is created. Elements are added using the push() method.

Also read: Stack and Heap Memory in Java: Key Differences Explained

Methods in Stack Class

The Stack class provides several important methods to perform various operations:

1. push(E item)

  • Adds an item to the top of the stack.
stack.push(40);

2. pop()

  • Removes and returns the top element of the stack.
int removedElement = stack.pop();
System.out.println("Removed Element: " + removedElement);

3. peek()

  • Returns the top element without removing it from the stack.
int topElement = stack.peek();
System.out.println("Top Element: " + topElement);

4. size()

  • Returns the number of elements in the stack.
System.out.println("Stack Size: " + stack.size());

5. empty()

  • Checks if the stack is empty.
System.out.println("Is Stack Empty? " + stack.empty());

Must explore: Array in Java: Types, Operations, Pros & Cons

Applications of Stack in Java

Stacks are widely used in many real-world and programming scenarios:

1. Expression Evaluation

Stacks are used to evaluate mathematical expressions like postfix or prefix efficiently.

2. Syntax Parsing

Compilers use stacks to parse syntax and validate expressions in programming languages.

3. Undo Mechanism in Editors

Text editors implement undo features by pushing user actions onto a stack.

4. Backtracking Algorithms

Stacks help in backtracking solutions, like navigating mazes or solving puzzles such as Sudoku.

5. Function Call Management (Call Stack)During method execution, Java uses a call stack to manage method invocation and return order.

Also check: String in Java

Introduction to Java Queue

A Queue in Java is another linear data structure that follows the First-In, First-Out (FIFO) principle. This means the first element inserted into the queue is the first one to be removed, similar to people standing in a queue at a ticket counter.

In Java, the Queue is an interface available in the java.util package. It can be implemented using classes like LinkedList, PriorityQueue, and others.

Must explore: Types of Linked List

How to Implement Queue in Java?

You can implement a queue in Java using the LinkedList class, which implements the Queue interface.

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();

        queue.add("Alisha");
        queue.add("Diksha");
        queue.add("Sunny");

        System.out.println("Queue elements: " + queue);
    }
}

Output:

Queue elements: [Alisha, Diksha, Sunny]

Explanation:

Here, a queue of strings is created. Elements are added using the add() method.

Also read: Linked List vs Array: Differences, Types, and Advantages

Common Methods in Queue Interface

While not explicitly in your original outline, it's helpful to quickly mention the key methods:

  • add(E e): Inserts an element into the queue.
  • remove(): Removes and returns the head of the queue.
  • peek(): Returns the head of the queue without removing it.
  • isEmpty(): Checks if the queue is empty.

Must Read: Doubly Linked List Data Structures: A Complete Guide

Applications of Queue in Java

1. Task Scheduling Queues manage processes in operating systems by scheduling tasks based on their arrival time.

2. Print Queue Management Printers use queues to manage multiple print jobs, processing them in the order they are received.

3. Breadth-First Search (BFS) in Graphs BFS algorithm in graph traversal uses a queue to explore nodes level by level.

4. Handling Requests in Web Servers Web servers queue incoming client requests and process them sequentially to ensure proper load handling.

5. Message Queues in Messaging Systems Messaging platforms use queues to store and deliver messages reliably between distributed systems and applications.

Difference Between Stack and Queue in Java

Feature

Stack in Java

Queue in Java

Principle

Last-In, First-Out (LIFO)

First-In, First-Out (FIFO)

Insertion Method

push()

add() or offer()

Deletion Method

pop()

remove() or poll()

Access Method

peek() (top element)

peek() (front element)

Java Class/Interface

Stack class (extends Vector)

Queue interface (implemented by classes like LinkedList, PriorityQueue)

Order of Processing

Last inserted element is processed first

First inserted element is processed first

Applications

Expression evaluation, recursion, undo operations

Scheduling, print queues, task management

Package

java.util

java.util

Must read: Recursion in Data Structures: Types, Algorithms, and Applications

Final Thoughts

Understanding Stack and Queue in Java is crucial for mastering data structures and algorithms. Both structures solve different types of problems—Stacks for LIFO based solutions and Queues for FIFO based problems. Java makes it easy by providing built-in support through its rich set of classes and interfaces.

If you're serious about improving your programming skills, practicing problems involving Stack data structure in Java and Queue data structure in Java is a must!

FAQs

1. How does Stack follow the LIFO principle in Java?

In Java, a Stack follows the Last-In, First-Out (LIFO) principle by removing the last element inserted first. When you push elements onto the stack, they are added at the top, and when you pop, the topmost element is the one that's removed.

2. How can you implement a custom Stack in Java?

You can implement a custom Stack in Java using arrays or linked lists. By manually managing the top pointer and creating methods like push(), pop(), and peek(), you can recreate the core functionality of Java's built-in Stack class.

3. Can a Stack be empty in Java, and how to check it?

Yes, a Stack can be empty in Java. You can use the empty() method of the Stack class, which returns true if the stack contains no elements and false otherwise. It’s a simple way to avoid underflow errors.

4. How does Queue follow the FIFO principle in Java?

A Queue follows the First-In, First-Out (FIFO) principle, meaning the first element inserted is the first to be removed. In Java, methods like add() or offer() insert elements at the end, and remove() or poll() remove from the front.

5. Which classes implement the Queue interface in Java?

The Queue interface in Java is implemented by several classes like LinkedList, PriorityQueue, ArrayDeque, and ConcurrentLinkedQueue. Each class has its own behavior, but all maintain the basic FIFO principle while handling elements.

6. What is the difference between add() and offer() in Java Queue?

Both add() and offer() methods insert elements into a Queue. However, add() throws an exception if the queue is full, while offer() returns false without throwing an error, making offer() safer for capacity-restricted queues.

7. Can you use a Stack to reverse a string in Java?

Yes, you can use a Stack to reverse a string. Push each character of the string onto the stack, and then pop them off one by one. Since Stack follows LIFO, it naturally gives the reversed order of characters.

8. How is a Stack used in expression evaluation?

Stacks are crucial for evaluating postfix and prefix expressions. They temporarily hold operands and operators, allowing for the correct order of operations to be maintained without the need for parentheses, simplifying complex calculations programmatically.

9. What happens if you pop from an empty Stack in Java?

If you call pop() on an empty Stack, Java throws an EmptyStackException. It's important to always check if the stack is empty using the empty() method before popping an element to avoid runtime errors.

10. How is a Queue used in Breadth-First Search (BFS)?

In BFS algorithms, a Queue is used to keep track of nodes to visit next. Nodes are added to the queue when discovered and removed once visited, ensuring that nodes are explored level by level, not depth-first.

11. Can you implement both Stack and Queue using Deque in Java?

Yes, you can use a Deque (Double-Ended Queue) to implement both Stack and Queue behaviors. Deque allows insertion and removal from both ends, supporting LIFO operations like a stack and FIFO operations like a queue efficiently.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.