Skip to main content
Published on

Stack Class in Java

Share:

Introduction

The stack data structure is one of the most essential in computer science. In Java, the Stack class provides an efficient implementation of this type of structure.

Characteristics of the Stack Class

  1. LIFO (Last In - First Out): The main characteristic of the stack is that the last element inserted is the first to be removed.
  2. Dynamic: The Stack class grows and shrinks dynamically as elements are added or removed.
  3. Fundamental methods: push(), pop() and peek() are the most commonly used methods in a stack.

When to Use the Stack Class?

The stack is generally used in situations where the processing order needs to follow the LIFO rule. Some typical applications include:

  • Validating expressions with balanced parentheses.
  • Implementing "undo" functions in editors.
  • Page navigation in web browsers (back and forward buttons).
  • Converting infix expressions to postfix.
package com.caffeinealgorithm.programaremjava;

import java.util.Stack;

public class StackClass {
  private Stack<Integer> stack = new Stack<>();
  private int multiplier = 10, number = 1;

  public void Run() {
    for (int index = 1; index <= 5; index++) {
      stack.push(number);
      number *= multiplier;
    }

    printStack();

    System.out.printf("\nRemoving the number %d from the stack with the pop() method.\n\n", stack.pop());

    printStack();

    System.out.printf("\nThe next number to be removed from the stack is %d.", stack.peek());
  }

  private void printStack() {
    for (int number : stack)
      System.out.println(number);
  }
}

/*
  1
  10
  100
  1000
  10000

  Removing the number 10000 from the stack with the pop() method.

  1
  10
  100
  1000

  The next number to be removed from the stack is 1000.
*/

Additional Methods of the Stack Class

  • isEmpty(): Returns true if the stack is empty.
  • search(Object o): Returns the position of an object in the stack, with the count starting from the top (element 1 is the top).
  • size(): Returns the number of elements in the stack.
  • clear(): Removes all elements from the stack.

Limitations and Considerations

While the Stack class is useful, in many modern scenarios it is preferable to use the Deque class instead of Stack due to its greater flexibility and ability to be used both as a stack and as a queue.

Conclusion

The Stack class is a vital and classic implementation of the stack data structure in Java. Knowing how and when to use it is crucial for many algorithms and applications. Learning its methods and characteristics is an essential step toward becoming a competent Java developer.

Happy coding!