For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
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!
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:
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
The Stack class provides several important methods to perform various operations:
stack.push(40);
int removedElement = stack.pop();
System.out.println("Removed Element: " + removedElement);
int topElement = stack.peek();
System.out.println("Top Element: " + topElement);
System.out.println("Stack Size: " + stack.size());
System.out.println("Is Stack Empty? " + stack.empty());
Must explore: Array in Java: Types, Operations, Pros & Cons
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
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
While not explicitly in your original outline, it's helpful to quickly mention the key methods:
Must Read: Doubly Linked List Data Structures: A Complete Guide
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.
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
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.