Stacks in Java

Introduction

Greetings! Today, we're drawing back the curtains on Stacks in Java, a crucial data structure. A stack is like a pile of dishes: you add a dish to the top (Last In) and take it from the top (First Out). This Last-In, First-Out (LIFO) principle exemplifies the stack. Java executes stacks effortlessly using the Stack class from the java.util package. This lesson will illuminate the stack data structure, its operations, and their applications in Java. Are you ready to start?

Utilizing Stacks in Java

To create a stack, Java employs a built-in data structure known as a Stack. For the Push operation, we use push(), which adds an element at the stack's end. For the Pop operation, there's the pop() function that removes the last element, simulating the removal of the 'top' element in a stack. Here's how it looks:

import java.util.Stack;

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

        // Push operations
        stack.push("John");
        stack.push("Mary");
        stack.push("Steve");

        stack.pop(); // Pop operation removes 'Steve'
        System.out.println(stack); // Outputs: [John, Mary]
    }
}

In the example provided, we push 'John', 'Mary', and 'Steve' into the stack and then pop 'Steve' from the stack.

Advanced Stack Operations

Stack operations go beyond merely push and pop. For example, to verify if a stack is empty, we can use the empty() method. If it returns true, that means the stack is empty. Conversely, if it returns false, we can infer the stack is not empty. To peek at the top element of the stack without popping it, we use the peek() method.

Here's an example:

public class StackOperations {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("Steve");
        stack.push("Sam");
        
        System.out.println(stack.peek()); // Outputs: 'Sam'

        System.out.println(stack.empty()); // Outputs: false
        stack.pop(); // Remove 'Sam'
        stack.pop(); // Remove 'Steve'
        System.out.println(stack.empty()); // Outputs: true
    }
}

In this example, 'Sam' is added (pushed), and then the topmost stack element, which is 'Sam', is peeked.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal