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

  1. LIFO Principle: The last element added is the first one to be removed.
  2. 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

  1. Creating a Stack:

    Stack<Integer> stack = new Stack<>();
    

    This line creates a new stack that will hold Integer values.

  2. Pushing Elements:

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

    These lines add the elements 10, 20, and 30 to the stack.

  3. Displaying the Stack:

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

    This line prints the current elements in the stack.

  4. 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.

  5. 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.

  6. 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.

  7. 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 or peek to avoid EmptyStackException.
  • 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

Module 2: Control Flow

Module 3: Object-Oriented Programming

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

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved