In this section, we will explore the Stack data structure in Java. A stack is a collection that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are used in various applications, such as expression evaluation, backtracking algorithms, and function call management in programming languages.
Key Concepts
- LIFO Principle: The last element added is the first one to be removed.
- Basic Operations:
- Push: Add an element to the top of the stack.
- Pop: Remove the top element from the stack.
- Peek: View the top element without removing it.
- isEmpty: Check if the stack is empty.
- size: Get the number of elements in the stack.
Using Stack in Java
Java provides a built-in Stack
class as part of the java.util
package. Below is an example of how to use the Stack
class in Java.
Example Code
import java.util.Stack; public class StackExample { public static void main(String[] args) { // Create a stack Stack<Integer> stack = new Stack<>(); // Push elements onto the stack stack.push(10); stack.push(20); stack.push(30); // Display the stack System.out.println("Stack: " + stack); // Peek at the top element int topElement = stack.peek(); System.out.println("Top element: " + topElement); // Pop an element from the stack int poppedElement = stack.pop(); System.out.println("Popped element: " + poppedElement); // Display the stack after popping System.out.println("Stack after pop: " + stack); // Check if the stack is empty boolean isEmpty = stack.isEmpty(); System.out.println("Is stack empty? " + isEmpty); // Get the size of the stack int size = stack.size(); System.out.println("Stack size: " + size); } }
Explanation
-
Creating a Stack:
Stack<Integer> stack = new Stack<>();
This line creates a new stack that will hold
Integer
values. -
Pushing Elements:
stack.push(10); stack.push(20); stack.push(30);
These lines add the elements
10
,20
, and30
to the stack. -
Displaying the Stack:
System.out.println("Stack: " + stack);
This line prints the current elements in the stack.
-
Peeking at the Top Element:
int topElement = stack.peek(); System.out.println("Top element: " + topElement);
The
peek
method returns the top element without removing it. -
Popping an Element:
int poppedElement = stack.pop(); System.out.println("Popped element: " + poppedElement);
The
pop
method removes and returns the top element of the stack. -
Checking if the Stack is Empty:
boolean isEmpty = stack.isEmpty(); System.out.println("Is stack empty? " + isEmpty);
The
isEmpty
method checks if the stack has no elements. -
Getting the Size of the Stack:
int size = stack.size(); System.out.println("Stack size: " + size);
The
size
method returns the number of elements in the stack.
Practical Exercises
Exercise 1: Reverse a String Using Stack
Problem: Write a program to reverse a string using a stack.
Solution:
import java.util.Stack; public class ReverseString { public static void main(String[] args) { String input = "Hello, World!"; String reversed = reverseString(input); System.out.println("Reversed string: " + reversed); } public static String reverseString(String str) { Stack<Character> stack = new Stack<>(); for (char ch : str.toCharArray()) { stack.push(ch); } StringBuilder reversed = new StringBuilder(); while (!stack.isEmpty()) { reversed.append(stack.pop()); } return reversed.toString(); } }
Exercise 2: Check for Balanced Parentheses
Problem: Write a program to check if a string containing parentheses is balanced.
Solution:
import java.util.Stack; public class BalancedParentheses { public static void main(String[] args) { String input = "((()))"; boolean isBalanced = checkBalancedParentheses(input); System.out.println("Is balanced: " + isBalanced); } public static boolean checkBalancedParentheses(String str) { Stack<Character> stack = new Stack<>(); for (char ch : str.toCharArray()) { if (ch == '(') { stack.push(ch); } else if (ch == ')') { if (stack.isEmpty()) { return false; } stack.pop(); } } return stack.isEmpty(); } }
Common Mistakes and Tips
- Forgetting to Check if the Stack is Empty: Always check if the stack is empty before calling
pop
orpeek
to avoidEmptyStackException
. - Using the Wrong Data Type: Ensure that the stack is declared with the correct data type to avoid
ClassCastException
.
Conclusion
In this section, we covered the basics of the Stack data structure in Java, including its key operations and practical applications. We also provided example code and exercises to help reinforce the concepts. Understanding stacks is essential for solving various algorithmic problems and managing function calls in programming. In the next section, we will explore another important data structure: Queue and Deque.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection