Java Stack Class: A Beginner's Guide

Introduction

Hello there, future Java developers! Today, we're going to dive into the fascinating world of the Java Stack class. Don't worry if you've never written a line of code before – I'll be your friendly guide on this exciting journey.

Java - Stack Class

Imagine you're organizing your books. You pile them up, one on top of the other. The last book you put on the pile is the first one you'll pick up when you need it. That's exactly how a Stack works in Java! It's a "Last-In-First-Out" (LIFO) data structure, and it's incredibly useful in programming.

Class Declaration

Let's start with the basics. In Java, the Stack class is part of the java.util package. To use it, you need to import it like this:

import java.util.Stack;

The Stack class extends the Vector class and implements interfaces like List, Collection, Iterable, Cloneable, and Serializable. Don't worry if these terms sound like alien language right now – we'll get there!

Class Constructors

The Stack class has only one constructor:

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

Here, 'E' is a placeholder for the type of elements you want to store in your stack. It could be Integer, String, or any other object type. For example:

Stack<Integer> numberStack = new Stack<Integer>();
Stack<String> bookStack = new Stack<String>();

In the first line, we're creating a stack that will hold integers. In the second, we're making a stack for strings – perfect for our book pile analogy!

Class Methods

Now, let's look at the main methods of the Stack class. I'll present them in a table for easy reference:

Method Description
push(E item) Adds an item to the top of the stack
pop() Removes and returns the top item from the stack
peek() Returns the top item without removing it
empty() Checks if the stack is empty
search(Object o) Searches for an object and returns its position

Let's break these down with some examples:

push(E item)

Stack<String> bookStack = new Stack<String>();
bookStack.push("Java for Beginners");
bookStack.push("Data Structures in Java");

Here, we're adding books to our stack. "Data Structures in Java" is now on top of "Java for Beginners".

pop()

String topBook = bookStack.pop();
System.out.println("Removed book: " + topBook);

This removes "Data Structures in Java" from the top of the stack and returns it.

peek()

String nextBook = bookStack.peek();
System.out.println("Next book to read: " + nextBook);

This tells us the top book without removing it – in this case, "Java for Beginners".

empty()

if (bookStack.empty()) {
    System.out.println("No more books to read!");
} else {
    System.out.println("You still have books to read!");
}

This checks if our stack is empty. It's like checking if we've finished all our books!

search(Object o)

int position = bookStack.search("Java for Beginners");
if (position != -1) {
    System.out.println("Book found at position: " + position);
} else {
    System.out.println("Book not found in the stack.");
}

This searches for a book in our stack. Remember, the position is counted from the top, and the top item is at position 1.

Methods Inherited

The Stack class also inherits methods from its parent class, Vector, and the interfaces it implements. Some useful inherited methods include:

  • size(): Returns the number of elements in the stack
  • contains(Object o): Checks if an object is in the stack
  • clear(): Removes all elements from the stack

Example

Let's put it all together with a fun example. Imagine we're keeping track of our pancake stack!

import java.util.Stack;

public class PancakeStack {
    public static void main(String[] args) {
        Stack<String> pancakes = new Stack<>();

        // Making pancakes
        pancakes.push("Plain");
        pancakes.push("Blueberry");
        pancakes.push("Chocolate Chip");

        System.out.println("Pancake stack: " + pancakes);

        // Eating the top pancake
        String eatenPancake = pancakes.pop();
        System.out.println("Yum! Just ate a " + eatenPancake + " pancake.");

        // Checking the next pancake
        System.out.println("Next pancake is: " + pancakes.peek());

        // Adding more pancakes
        pancakes.push("Banana");

        // Checking stack size
        System.out.println("Number of pancakes left: " + pancakes.size());

        // Searching for a pancake
        int position = pancakes.search("Plain");
        if (position != -1) {
            System.out.println("Plain pancake is " + position + " from the top.");
        } else {
            System.out.println("No plain pancakes left!");
        }
    }
}

Output

When you run this code, you'll see something like this:

Pancake stack: [Plain, Blueberry, Chocolate Chip]
Yum! Just ate a Chocolate Chip pancake.
Next pancake is: Blueberry
Number of pancakes left: 3
Plain pancake is 3 from the top.

And there you have it! You've just learned the basics of the Java Stack class. Remember, like stacking pancakes or books, a Stack in Java follows the "Last-In-First-Out" principle. It's a powerful tool that you'll find useful in many programming scenarios.

Keep practicing, and soon you'll be stacking and unstacking data like a pro! Happy coding, and may your stacks always be full of delicious pancakes... I mean, useful data!

Credits: Image by storyset