# Stacks

A Stack is a collection that allows you to access the elements in the reverse order in which they were added to the collection.

Journeyman · Java · Updated November 16, 2026

By Gregor Dzierzon

A `Stack` is a collection that allows you to access the elements in the reverse order in which they were added to the collection.

It is a Last-In-First-Out (**LIFO**) type of list. Instead of accessing elements by their ordinal position, we remove the top item.

To add a new item you `push(item)` it to the top of the stack. To remove an item, you `pop()` it off the top of the stack.

```java
Stack<String> players = new Stack<>();

players.push("Emily");
players.push("Lucas");
players.push("Sophia");
players.push("Mason");

while(!players.isEmpty())
{
    String player = players.pop();
    System.out.println(player);
}
```

![A stack is last in, first out: Mason was pushed last, so pop() returns him first](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/09/5e1688c9cfca4c92b14eead2f333fe12.png "A stack is last in, first out: Mason was pushed last, so pop() returns him first")

## Do it: an Undo button for a notes app

A notes app has an **Undo** button. Each time you type, the app remembers the text you had before; Undo brings that text back. Press it again, and it goes one more step back. The most recent change comes back first, so the app keeps its history in a stack.

`Notes` already has:

- `history`: a `Stack<String>` of the texts you had before each change, empty at first.
- `text`: the note's text now, `""` (empty) at first, with `getText()`.

`type` gets one value:

- `words`: the words to add to the end of the note, a `String`, such as `"Buy milk"`.

For example:

```java
Notes notes = new Notes();
notes.type("Buy milk");
notes.type(", eggs");
notes.type(", jam");
notes.undo();
```

| Step | `text` after it | `history`, top first |
|---|---|---|
| Start | `""` | (empty) |
| `type("Buy milk")` | `"Buy milk"` | `""` |
| `type(", eggs")` | `"Buy milk, eggs"` | `"Buy milk"`, `""` |
| `type(", jam")` | `"Buy milk, eggs, jam"` | `"Buy milk, eggs"`, `"Buy milk"`, `""` |
| `undo()` | `"Buy milk, eggs"` | `"Buy milk"`, `""` |

So `notes.getText()` is `"Buy milk, eggs"`.

**Your job:** write the two methods of the class `Notes`.

- `type(String words)`: push the text you have now onto `history`, then add `words` to the end of `text`.
- `undo()`: take the most recent text off `history`, and make it the text.
- When `history` is empty, `undo()` does nothing: the text stays as it is, with no error.

Practiced live on the lesson page: write the Java right there and check it.

## Cheat sheets

- [Queues and Stacks](https://www.ask-codey.com/cheat-sheets/types-of-collections-queues-cheat-sheet)

Source: https://www.ask-codey.com/lessons/types-of-collections-stacks
