Your text editor needs undo - the most recent action should be undone first. That's a stack (LIFO). Your print queue processes jobs in order - first submitted, first printed. That's a queue (FIFO).

Undo with a stack

Push actions and pop to undo.

StackUndo.java
Replay: real traced execution (multi-file project)
import java.util.ArrayDeque;
import java.util.Deque;

public class StackUndo {
    public static void main(String[] args) {
        // Undo history using a stack
        Deque<String> undoHistory = new ArrayDeque<>();
        String currentText = "";

        System.out.println("=== Text Editor with Undo ===\n");

        // Perform actions (each saves state to undo stack)
        currentText = performAction(undoHistory, currentText, "Hello");
        currentText = performAction(undoHistory, currentText, " World");
        currentText = performAction(undoHistory, currentText, "!");

        // Perform more actions
        currentText = performAction(undoHistory, currentText, " How");
        currentText = performAction(undoHistory, currentText, " are");
        currentText = performAction(undoHistory, currentText, " you?");

        System.out.println("Current text: \"" + currentText + "\"");
        System.out.println("Undo stack size: " + undoHistory.size());

        // Undo operations
        System.out.println("\n=== Performing Undo ===");

        currentText = undo(undoHistory, currentText);
        currentText = undo(undoHistory, currentText);

        System.out.println("\nAfter 2 undos: \"" + currentText + "\"");

        // Undo more actions
        currentText = undo(undoHistory, currentText);
        currentText = undo(undoHistory, currentText);
        System.out.println("After more undos: \"" + currentText + "\"");
    }

    static String performAction(Deque<String> history, String current, String addition) {
        history.push(current);  // Save current state
        String newText = current + addition;
        System.out.println("Action: Add \"" + addition + "\" → \"" + newText + "\"");
        return newText;
    }

    static String undo(Deque<String> history, String current) {
        if (!history.isEmpty()) {
            String previous = history.pop();  // Get previous state
            System.out.println("Undo: \"" + current + "\" → \"" + previous + "\"");
            return previous;
        } else {
            System.out.println("Nothing to undo!");
            return current;
        }
    }
}
  1. undoHistory ← [], currentText ← (empty)

    5public class StackUndo {6    public static void main(String[] args) {7        // Undo history using a stack  //#?stack8        Deque<String> undoHistory→ [] = new ArrayDeque<>();9        String currentText→ (empty) = "";10        11        System.out.println("=== Text Editor with Undo ===\n");12        13        // Perform actions (each saves state to undo stack)14        currentText = performAction(undoHistory[], currentText(empty), "Hello");15        currentText = performAction(undoHistory, currentText, " World");
    output=== Text Editor with Undo ===
  2. newText ← Hello

    pass 1 of 6
    40static String performAction(Deque<String> history[], String current(empty), String additionHello) {41    history.push(current(empty));  // Save current state  //#?push42    String newText→ Hello = current(empty) + additionHello;43    System.out.println("Action: Add \"" + additionHello + "\" → \"" + newTextHello + "\"");44    return newTextHello;45}
    outputAction: Add "Hello" → "Hello"
    All 6 passes — pass 1 is the card above
    passhistorycurrentadditionnewText
    1[](empty)HelloHello
    2[]Hello WorldHello World
    3[Hello, ]Hello World!Hello World!
    4[Hello World, Hello, ]Hello World! HowHello World! How
    5[Hello World!, Hello World, Hello, ]Hello World! How areHello World! How are
    6[Hello World! How, Hello World!, Hello World, Hello, ]Hello World! How are you?Hello World! How are you?
  3. currentText ← Hello

    13// Perform actions (each saves state to undo stack)14currentText→ Hello = performAction(undoHistory[], currentText, "Hello");15currentText = performAction(undoHistory[], currentTextHello, " World");16currentText = performAction(undoHistory, currentText, "!");
  4. undoHistory ← [Hello, ], currentText ← Hello World

    14currentText = performAction(undoHistory, currentText, "Hello");15currentText→ Hello World = performAction(undoHistory→ [Hello, ], currentText, " World");16currentText = performAction(undoHistory[Hello, ], currentTextHello World, "!");
  5. undoHistory ← [Hello World, Hello, ], currentText ← Hello World!

    15currentText = performAction(undoHistory, currentText, " World");16currentText→ Hello World! = performAction(undoHistory→ [Hello World, Hello, ], currentText, "!");1718// Perform more actions19currentText = performAction(undoHistory[Hello World, Hello, ], currentTextHello World!, " How");  //@var=_,!20currentText = performAction(undoHistory, currentText, " are");  //@var=_,!
  6. undoHistory ← [Hello World!, Hello World, Hello, ], currentText ← Hello World! How

    18// Perform more actions19currentText→ Hello World! How = performAction(undoHistory→ [Hello World!, Hello World, Hello, ], currentText, " How");  //@var=_,!20currentText = performAction(undoHistory[Hello World!, Hello World, Hello, ], currentTextHello World! How, " are");  //@var=_,!21currentText = performAction(undoHistory, currentText, " you?");  //@var=_,!
  7. undoHistory ← [Hello World! How, Hello World!, Hello World, Hello, ]

    19currentText = performAction(undoHistory, currentText, " How");  //@var=_,!20currentText→ Hello World! How are = performAction(undoHistory→ [Hello World! How, Hello World!, Hello World, Hello, ], currentText, " are");  //@var=_,!21currentText = performAction(undoHistory[Hello World! How, Hello World!, Hello World, Hello, ], currentTextHello World! How are, " you?");  //@var=_,!
  8. undoHistory ← [Hello World! How are, Hello World! How, Hello World!, Hello World, Hello, ]

    20currentText = performAction(undoHistory, currentText, " are");  //@var=_,!21currentText→ Hello World! How are you? = performAction(undoHistory→ [Hello World! How are, Hello World! How, Hello World!, Hello World, Hello, ], currentText, " you?");  //@var=_,!2223System.out.println("Current text: \"" + currentTextHello World! How are you? + "\"");24System.out.println("Undo stack size: " + undoHistory.size());2526// Undo operations  //#?undo27System.out.println("\n=== Performing Undo ===");2829currentText = undo(undoHistory[Hello World! How are, Hello World! How, Hello World!, Hello World, Hello, ], currentTextHello World! How are you?);30currentText = undo(undoHistory, currentText);
    outputCurrent text: "Hello World! How are you?"
    Undo stack size: 6
    
    === Performing Undo ===
  9. static String undo(Deque<String> history, String current)

    pass 1 of 4
    47static String undo(Deque<String> history[Hello World! How are, Hello World! How, Hello World!, Hello World, Hello, ], String currentHello World! How are you?) {48    if (!history.isEmpty()) {  //#?isempty
    All 4 passes — pass 1 is the card above
    passhistorycurrent
    1[Hello World! How are, Hello World! How, Hello World!, Hello World, Hello, ]Hello World! How are you?
    2[Hello World! How, Hello World!, Hello World, Hello, ]Hello World! How are
    3[Hello World!, Hello World, Hello, ]Hello World! How
    4[Hello World, Hello, ]Hello World!
  10. previous ← Hello World! How are

    pass 1 of 4
    47static String undo(Deque<String> history, String current) {48    if (!history.isEmpty()) {  //#?isempty49        String previous→ Hello World! How are = history.pop();  // Get previous state50        System.out.println("Undo: \"" + currentHello World! How are you? + "\" → \"" + previousHello World! How are + "\"");51        return previousHello World! How are;52    } else {
    outputUndo: "Hello World! How are you?" → "Hello World! How are"
    All 4 passes — pass 1 is the card above
    passcurrentprevious
    1Hello World! How are you?Hello World! How are
    2Hello World! How areHello World! How
    3Hello World! HowHello World!
    4Hello World!Hello World
  11. undoHistory ← [Hello World! How, Hello World!, Hello World, Hello, ]

    29currentText→ Hello World! How are = undo(undoHistory→ [Hello World! How, Hello World!, Hello World, Hello, ], currentText);30currentText = undo(undoHistory[Hello World! How, Hello World!, Hello World, Hello, ], currentTextHello World! How are);
  12. undoHistory ← [Hello World!, Hello World, Hello, ], currentText ← Hello World! How

    29currentText = undo(undoHistory, currentText);30currentText→ Hello World! How = undo(undoHistory→ [Hello World!, Hello World, Hello, ], currentText);3132System.out.println("\nAfter 2 undos: \"" + currentTextHello World! How + "\"");3334// Undo more actions35currentText = undo(undoHistory[Hello World!, Hello World, Hello, ], currentTextHello World! How);  //@var=_,!36currentText = undo(undoHistory, currentText);  //@var=_,!
    output
    After 2 undos: "Hello World! How"
  13. undoHistory ← [Hello World, Hello, ], currentText ← Hello World!

    34// Undo more actions35currentText→ Hello World! = undo(undoHistory→ [Hello World, Hello, ], currentText);  //@var=_,!36currentText = undo(undoHistory[Hello World, Hello, ], currentTextHello World!);  //@var=_,!37System.out.println("After more undos: \"" + currentText + "\"");  //@var=_,!
  14. undoHistory ← [Hello, ], currentText ← Hello World

    35    currentText = undo(undoHistory, currentText);  //@var=_,!36    currentText→ Hello World = undo(undoHistory→ [Hello, ], currentText);  //@var=_,!37    System.out.println("After more undos: \"" + currentTextHello World + "\"");  //@var=_,!38}
    outputAfter more undos: "Hello World"

push() adds to top, pop() removes from top. Last in, first out.

stack LIFO collection: last in, first out. Use `Deque` interface in modern Java.

Check before popping

Avoid errors by checking if stack is empty.

StackEmpty.java
Replay: real traced execution (multi-file project)
import java.util.ArrayDeque;
import java.util.Deque;

public class StackEmpty {
    public static void main(String[] args) {
        Deque<String> browserHistory = new ArrayDeque<>();

        System.out.println("=== Browser History (Back Button) ===\n");

        // Visit some pages
        visitPage(browserHistory, "google.com");
        visitPage(browserHistory, "github.com");
        visitPage(browserHistory, "stackoverflow.com");

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

        // Go back (pop pages)
        System.out.println("\n=== Going Back ===");

        goBack(browserHistory);
        goBack(browserHistory);
        goBack(browserHistory);
        goBack(browserHistory);  // Try to go back when empty!

        // Empty stack operations
        System.out.println("\n=== Empty Stack Demo ===");
        Deque<Integer> emptyStack = new ArrayDeque<>();

        System.out.println("Stack empty? " + emptyStack.isEmpty());
        System.out.println("Size: " + emptyStack.size());

        // Safe methods that return null instead of throwing
        System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());
        System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());

        // Dangerous methods (would throw NoSuchElementException)
        // emptyStack.pop();     // Throws!
        // emptyStack.getFirst(); // Throws!
    }

    static void visitPage(Deque<String> history, String url) {
        history.push(url);
        System.out.println("Visiting: " + url);
    }

    static void goBack(Deque<String> history) {
        if (history.isEmpty()) {
            System.out.println("Can't go back - no history!");
        } else {
            String page = history.pop();
            System.out.println("Back from: " + page);

            if (history.isEmpty()) {
                System.out.println("  (Reached start of history)");
            } else {
                System.out.println("  Now at: " + history.peek());
            }
        }
    }
}
  1. browserHistory ← []

    5public class StackEmpty {6    public static void main(String[] args) {7        Deque<String> browserHistory→ [] = new ArrayDeque<>();8        9        System.out.println("=== Browser History (Back Button) ===\n");10        11        // Visit some pages12        visitPage(browserHistory[], "google.com");13        visitPage(browserHistory, "github.com");
    output=== Browser History (Back Button) ===
  2. browserHistory ← [google.com]

    pass 1 of 3
    11    // Visit some pages12    visitPage(browserHistory→ [google.com], "google.com");13    visitPage(browserHistory[google.com], "github.com");14    visitPage(browserHistory, "stackoverflow.com");15    16    System.out.println("History stack: " + browserHistory);17    System.out.println("Stack size: " + browserHistory.size());18    19    // Go back (pop pages)  //#?back20    System.out.println("\n=== Going Back ===");21    22    goBack(browserHistory);23    goBack(browserHistory);24    goBack(browserHistory);25    goBack(browserHistory);  // Try to go back when empty!26    27    // Empty stack operations  //@var=!,_28    System.out.println("\n=== Empty Stack Demo ===");29    Deque<Integer> emptyStack = new ArrayDeque<>();30    31    System.out.println("Stack empty? " + emptyStack.isEmpty());32    System.out.println("Size: " + emptyStack.size());33    34    // Safe methods that return null instead of throwing35    System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());  //#?safe36    System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());37    38    // Dangerous methods (would throw NoSuchElementException)39    // emptyStack.pop();     // Throws!40    // emptyStack.getFirst(); // Throws!41}4243static void visitPage(Deque<String> history[], String urlgoogle.com) {44    history.push(urlgoogle.com);45    System.out.println("Visiting: " + urlgoogle.com);46}
    outputVisiting: google.com
    All 3 passes — pass 1 is the card above
    passhistoryurlbrowserHistoryemptyStack
    1[]google.com[] [google.com]
    2[google.com]github.com[google.com] [github.com, google.com]
    3[github.com, google.com]stackoverflow.com[github.com, google.com] [stackoverflow.com, github.com, google.com][]
  3. static void goBack(Deque<String> history)

    pass 1 of 4
    48static void goBack(Deque<String> history[stackoverflow.com, github.com, google.com]) {49    if (history.isEmpty()) {  //#?check
    All 4 passes — pass 1 is the card above
    passhistorybrowserHistoryemptyStack
    1[stackoverflow.com, github.com, google.com][stackoverflow.com, github.com, google.com] [github.com, google.com]
    2[github.com, google.com][github.com, google.com] [google.com]
    3[google.com][google.com] []
    4[][][]
  4. page ← stackoverflow.com

    pass 1 of 3
    50    System.out.println("Can't go back - no history!");51} else {52    String page→ stackoverflow.com = history.pop();53    System.out.println("Back from: " + pagestackoverflow.com);
    outputBack from: stackoverflow.com
    All 3 passes — pass 1 is the card above
    passpagebrowserHistoryemptyStack
    1stackoverflow.com[stackoverflow.com, github.com, google.com] [github.com, google.com]
    2github.com[github.com, google.com] [google.com]
    3google.com[google.com] [][]
  5. browserHistory ← [github.com, google.com]

    pass 1 of 2
    22    goBack(browserHistory→ [github.com, google.com]);23    goBack(browserHistory[github.com, google.com]);24    goBack(browserHistory);25    goBack(browserHistory);  // Try to go back when empty!26    27    // Empty stack operations  //@var=!,_28    System.out.println("\n=== Empty Stack Demo ===");29    Deque<Integer> emptyStack = new ArrayDeque<>();30    31    System.out.println("Stack empty? " + emptyStack.isEmpty());32    System.out.println("Size: " + emptyStack.size());33    34    // Safe methods that return null instead of throwing35    System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());  //#?safe36    System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());37    38    // Dangerous methods (would throw NoSuchElementException)39    // emptyStack.pop();     // Throws!40    // emptyStack.getFirst(); // Throws!41}4243static void visitPage(Deque<String> history, String url) {44    history.push(url);45    System.out.println("Visiting: " + url);46}4748static void goBack(Deque<String> history) {49    if (history.isEmpty()) {  //#?check50        System.out.println("Can't go back - no history!");51    } else {52        String page = history.pop();53        System.out.println("Back from: " + page);54        55        if (history.isEmpty()) {56            System.out.println("  (Reached start of history)");57        } else {58            System.out.println("  Now at: " + history.peek());59        }
    output  Now at: github.com
  6. browserHistory ← [google.com]

    pass 2 of 2
    22    goBack(browserHistory);23    goBack(browserHistory→ [google.com]);24    goBack(browserHistory[google.com]);25    goBack(browserHistory);  // Try to go back when empty!26    27    // Empty stack operations  //@var=!,_28    System.out.println("\n=== Empty Stack Demo ===");29    Deque<Integer> emptyStack = new ArrayDeque<>();30    31    System.out.println("Stack empty? " + emptyStack.isEmpty());32    System.out.println("Size: " + emptyStack.size());33    34    // Safe methods that return null instead of throwing35    System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());  //#?safe36    System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());37    38    // Dangerous methods (would throw NoSuchElementException)39    // emptyStack.pop();     // Throws!40    // emptyStack.getFirst(); // Throws!41}4243static void visitPage(Deque<String> history, String url) {44    history.push(url);45    System.out.println("Visiting: " + url);46}4748static void goBack(Deque<String> history) {49    if (history.isEmpty()) {  //#?check50        System.out.println("Can't go back - no history!");51    } else {52        String page = history.pop();53        System.out.println("Back from: " + page);54        55        if (history.isEmpty()) {56            System.out.println("  (Reached start of history)");57        } else {58            System.out.println("  Now at: " + history.peek());59        }
    output  Now at: google.com
  7. browserHistory ← []

    23    goBack(browserHistory);24    goBack(browserHistory→ []);25    goBack(browserHistory[]);  // Try to go back when empty!26    27    // Empty stack operations  //@var=!,_28    System.out.println("\n=== Empty Stack Demo ===");29    Deque<Integer> emptyStack = new ArrayDeque<>();30    31    System.out.println("Stack empty? " + emptyStack.isEmpty());32    System.out.println("Size: " + emptyStack.size());33    34    // Safe methods that return null instead of throwing35    System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());  //#?safe36    System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());37    38    // Dangerous methods (would throw NoSuchElementException)39    // emptyStack.pop();     // Throws!40    // emptyStack.getFirst(); // Throws!41}4243static void visitPage(Deque<String> history, String url) {44    history.push(url);45    System.out.println("Visiting: " + url);46}4748static void goBack(Deque<String> history) {49    if (history.isEmpty()) {  //#?check50        System.out.println("Can't go back - no history!");51    } else {52        String page = history.pop();53        System.out.println("Back from: " + page);54        55        if (history.isEmpty()) {56            System.out.println("  (Reached start of history)");57        } else {
    output  (Reached start of history)
  8. emptyStack ← []

    24    goBack(browserHistory);25    goBack(browserHistory[]);  // Try to go back when empty!26    27    // Empty stack operations  //@var=!,_28    System.out.println("\n=== Empty Stack Demo ===");29    Deque<Integer> emptyStack→ [] = new ArrayDeque<>();30    31    System.out.println("Stack empty? " + emptyStack.isEmpty());32    System.out.println("Size: " + emptyStack.size());33    34    // Safe methods that return null instead of throwing35    System.out.println("pollFirst() on empty: " + emptyStack.pollFirst());  //#?safe36    System.out.println("peekFirst() on empty: " + emptyStack.peekFirst());37    38    // Dangerous methods (would throw NoSuchElementException)39    // emptyStack.pop();     // Throws!40    // emptyStack.getFirst(); // Throws!41}4243static void visitPage(Deque<String> history, String url) {44    history.push(url);45    System.out.println("Visiting: " + url);46}4748static void goBack(Deque<String> history) {49    if (history.isEmpty()) {  //#?check50        System.out.println("Can't go back - no history!");51    } else {
    outputCan't go back - no history!
    
    === Empty Stack Demo ===
    Stack empty? true
    Size: 0
    pollFirst() on empty: null
    peekFirst() on empty: null

Always check isEmpty() before pop() to avoid exceptions.

Process tasks in order

Use a queue for first-come, first-served processing.

QueueTasks.java
Replay: real traced execution (multi-file project)
import java.util.LinkedList;
import java.util.Queue;

public class QueueTasks {
    public static void main(String[] args) {
        // Task queue - process in order received
        Queue<String> taskQueue = new LinkedList<>();

        System.out.println("=== Task Queue System ===\n");

        // Add tasks to queue
        System.out.println("Adding tasks:");
        taskQueue.offer("Process order #101");
        System.out.println("  Added: Process order #101");

        taskQueue.offer("Send confirmation email");
        System.out.println("  Added: Send confirmation email");

        taskQueue.offer("Update inventory");
        System.out.println("  Added: Update inventory");

        // Add more tasks
        taskQueue.offer("Generate report");
        taskQueue.offer("Notify warehouse");
        taskQueue.offer("Archive order");
        System.out.println("  Added 3 more tasks...");

        System.out.println("\nQueue: " + taskQueue);
        System.out.println("Tasks pending: " + taskQueue.size());

        // Process tasks in order
        System.out.println("\n=== Processing Tasks ===");

        int taskNum = 1;
        while (!taskQueue.isEmpty()) {
            String task = taskQueue.poll();  // Remove from front
            System.out.println(taskNum + ". " + task + " ✓");
            taskNum++;
        }

        System.out.println("\n=== All tasks completed! ===");
        System.out.println("Queue empty: " + taskQueue.isEmpty());
    }
}
  1. taskQueue ← [], taskNum ← 1

    5public class QueueTasks {6    public static void main(String[] args) {7        // Task queue - process in order received  //#?queue8        Queue<String> taskQueue→ [] = new LinkedList<>();9        10        System.out.println("=== Task Queue System ===\n");11        12        // Add tasks to queue  //#?offer13        System.out.println("Adding tasks:");14        taskQueue.offer("Process order #101");15        System.out.println("  Added: Process order #101");16        17        taskQueue.offer("Send confirmation email");18        System.out.println("  Added: Send confirmation email");19        20        taskQueue.offer("Update inventory");21        System.out.println("  Added: Update inventory");22        23        // Add more tasks24        taskQueue.offer("Generate report");     //@var=_,!25        taskQueue.offer("Notify warehouse");    //@var=_,!26        taskQueue.offer("Archive order");       //@var=_,!27        System.out.println("  Added 3 more tasks...");  //@var=_,!28        29        System.out.println("\nQueue: " + taskQueue[Process order #101, Send confirmation email, Update inventory, Generate report, Notify warehouse, Archive order]);30        System.out.println("Tasks pending: " + taskQueue.size());31        32        // Process tasks in order  //#?process33        System.out.println("\n=== Processing Tasks ===");34        35        int taskNum→ 1 = 1;36        while (!taskQueue.isEmpty()) {
    output=== Task Queue System ===
    Adding tasks:
      Added: Process order #101
      Added: Send confirmation email
      Added: Update inventory
      Added 3 more tasks...
    
    Queue: [Process order #101, Send confirmation email, Update inventory, Generate report, Notify warehouse, Archive order]
    Tasks pending: 6
    
    === Processing Tasks ===
  2. task ← Process order #101, taskNum ← 2

    pass 1 of 6
    35int taskNum = 1;36while (!taskQueue.isEmpty()) {37    String task→ Process order #101 = taskQueue.poll();  // Remove from front38    System.out.println(taskNum1 + ". " + taskProcess order #101 + " ✓");39    taskNum→ 2++;40}
    output1. Process order #101 ✓
    All 6 passes — pass 1 is the card above
    passtasktaskNum
    1Process order #1011 2
    2Send confirmation email2 3
    3Update inventory3 4
    4Generate report4 5
    5Notify warehouse5 6
    6Archive order6 7
  3. System.out.println(" === All tasks completed! ===");

    42    System.out.println("\n=== All tasks completed! ===");43    System.out.println("Queue empty: " + taskQueue.isEmpty());44}
    output
    === All tasks completed! ===
    Queue empty: true

offer() adds to back, poll() removes from front. First in, first out.

queue FIFO collection: first in, first out. Use `Queue` interface.

Peek without removing

Look at the top/front element without removing it.

PeekOperations.java
Replay: real traced execution (multi-file project)
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class PeekOperations {
    public static void main(String[] args) {
        // Stack peek
        Deque<String> stack = new ArrayDeque<>();
        stack.push("Bottom");
        stack.push("Middle");
        stack.push("Top");

        System.out.println("=== Stack Peek ===");
        System.out.println("Stack: " + stack);
        System.out.println("peek(): " + stack.peek());  // Look at top
        System.out.println("Stack after peek: " + stack);
        System.out.println("(Unchanged - peek doesn't remove!)");

        // Queue peek
        Queue<String> queue = new LinkedList<>();
        queue.offer("First");
        queue.offer("Second");
        queue.offer("Third");

        System.out.println("\n=== Queue Peek ===");
        System.out.println("Queue: " + queue);
        System.out.println("peek(): " + queue.peek());  // Look at front
        System.out.println("Queue after peek: " + queue);
        System.out.println("(Unchanged - peek doesn't remove!)");

        // Practical: Preview before processing
        System.out.println("\n=== Practical Use: Preview Next Item ===");

        Queue<String> printQueue = new LinkedList<>();
        printQueue.offer("Document1.pdf (5 pages)");
        printQueue.offer("Photo.jpg (1 page)");
        printQueue.offer("Report.docx (20 pages)");

        System.out.println("Print queue has " + printQueue.size() + " jobs");
        System.out.println("Next up: " + printQueue.peek());

        // Process with confirmation
        System.out.println("\n--- Processing ---");
        while (!printQueue.isEmpty()) {
            String next = printQueue.peek();  // Preview
            System.out.println("Printing: " + next);
            printQueue.poll();  // Now remove
        }

        // Compare peek vs poll
        System.out.println("\n=== peek() vs poll() ===");
        Queue<Integer> nums = new LinkedList<>();
        nums.offer(1);
        nums.offer(2);
        nums.offer(3);

        System.out.println("Queue: " + nums);
        System.out.println("peek() returns: " + nums.peek() + ", queue now: " + nums);
        System.out.println("poll() returns: " + nums.poll() + ", queue now: " + nums);
        System.out.println("poll() returns: " + nums.poll() + ", queue now: " + nums);
    }
}
  1. stack ← [], queue ← [], printQueue ← []

    6public class PeekOperations {7    public static void main(String[] args) {8        // Stack peek  //#?peekStack9        Deque<String> stack→ [] = new ArrayDeque<>();10        stack.push("Bottom");11        stack.push("Middle");12        stack.push("Top");13        14        System.out.println("=== Stack Peek ===");15        System.out.println("Stack: " + stack[Top, Middle, Bottom]);16        System.out.println("peek(): " + stack.peek());  // Look at top17        System.out.println("Stack after peek: " + stack[Top, Middle, Bottom]);18        System.out.println("(Unchanged - peek doesn't remove!)");19        20        // Queue peek  //#?peekQueue21        Queue<String> queue→ [] = new LinkedList<>();22        queue.offer("First");23        queue.offer("Second");24        queue.offer("Third");25        26        System.out.println("\n=== Queue Peek ===");27        System.out.println("Queue: " + queue[First, Second, Third]);28        System.out.println("peek(): " + queue.peek());  // Look at front29        System.out.println("Queue after peek: " + queue[First, Second, Third]);30        System.out.println("(Unchanged - peek doesn't remove!)");31        32        // Practical: Preview before processing  //#?preview33        System.out.println("\n=== Practical Use: Preview Next Item ===");34        35        Queue<String> printQueue→ [] = new LinkedList<>();36        printQueue.offer("Document1.pdf (5 pages)");37        printQueue.offer("Photo.jpg (1 page)");38        printQueue.offer("Report.docx (20 pages)");39        40        System.out.println("Print queue has " + printQueue.size() + " jobs");41        System.out.println("Next up: " + printQueue.peek());42        43        // Process with confirmation44        System.out.println("\n--- Processing ---");45        while (!printQueue.isEmpty()) {
    output=== Stack Peek ===
    Stack: [Top, Middle, Bottom]
    peek(): Top
    Stack after peek: [Top, Middle, Bottom]
    (Unchanged - peek doesn't remove!)
    
    === Queue Peek ===
    Queue: [First, Second, Third]
    peek(): First
    Queue after peek: [First, Second, Third]
    (Unchanged - peek doesn't remove!)
    
    === Practical Use: Preview Next Item ===
    Print queue has 3 jobs
    Next up: Document1.pdf (5 pages)
    
    --- Processing ---
  2. next ← Document1.pdf (5 pages)

    pass 1 of 3
    44System.out.println("\n--- Processing ---");45while (!printQueue.isEmpty()) {46    String next→ Document1.pdf (5 pages) = printQueue.peek();  // Preview47    System.out.println("Printing: " + nextDocument1.pdf (5 pages));48    printQueue.poll();  // Now remove49}
    outputPrinting: Document1.pdf (5 pages)
    All 3 passes — pass 1 is the card above
    passnext
    1Document1.pdf (5 pages)
    2Photo.jpg (1 page)
    3Report.docx (20 pages)
  3. nums ← []

    51    // Compare peek vs poll  //#?compare52    System.out.println("\n=== peek() vs poll() ===");53    Queue<Integer> nums→ [] = new LinkedList<>();54    nums.offer(1);55    nums.offer(2);56    nums.offer(3);57    58    System.out.println("Queue: " + nums[1, 2, 3]);59    System.out.println("peek() returns: " + nums.peek() + ", queue now: " + nums[1, 2, 3]);60    System.out.println("poll() returns: " + nums.poll() + ", queue now: " + nums→ [2, 3]);61    System.out.println("poll() returns: " + nums.poll() + ", queue now: " + nums→ [3]);62}
    output
    === peek() vs poll() ===
    Queue: [1, 2, 3]
    peek() returns: 1, queue now: [1, 2, 3]
    poll() returns: 1, queue now: [2, 3]
    poll() returns: 2, queue now: [3]

peek() returns the element without removing it. Useful for inspection.

peek Look at top (stack) or front (queue) without removing.

Reverse a list with stack

Use a stack to reverse element order.

ReverseList.java
Replay: real traced execution (multi-file project)
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;

public class ReverseList {
    public static void main(String[] args) {
        // Reverse a list using a stack
        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        System.out.println("=== Reversing a List ===");
        System.out.println("Original: " + numbers);

        // Push all elements onto stack
        Deque<Integer> stack = new ArrayDeque<>();
        for (int num : numbers) {
            stack.push(num);
        }

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

        // Pop all elements back into list
        List<Integer> reversed = new ArrayList<>();
        while (!stack.isEmpty()) {
            reversed.add(stack.pop());
        }

        System.out.println("Reversed: " + reversed);

        // Reverse a string using stack
        System.out.println("\n=== Reversing a String ===");
        String original = "Hello World";

        Deque<Character> charStack = new ArrayDeque<>();
        for (char c : original.toCharArray()) {
            charStack.push(c);
        }

        StringBuilder reversedString = new StringBuilder();
        while (!charStack.isEmpty()) {
            reversedString.append(charStack.pop());
        }

        System.out.println("Original: \"" + original + "\"");
        System.out.println("Reversed: \"" + reversedString + "\"");

        // Palindrome check using stack
        System.out.println("\n=== Palindrome Check ===");
        checkPalindrome("radar");
        checkPalindrome("hello");
        checkPalindrome("A man a plan a canal Panama");
    }

    static void checkPalindrome(String input) {
        // Clean string: lowercase, letters only
        String clean = input.toLowerCase().replaceAll("[^a-z]", "");

        Deque<Character> stack = new ArrayDeque<>();
        for (char c : clean.toCharArray()) {
            stack.push(c);
        }

        StringBuilder reversed = new StringBuilder();
        while (!stack.isEmpty()) {
            reversed.append(stack.pop());
        }

        boolean isPalindrome = clean.equals(reversed.toString());
        System.out.println("\"" + input + "\" → " +
            (isPalindrome ? "Palindrome ✓" : "Not palindrome"));
    }
}
  1. numbers ← [1, 2, 3, 4, 5], stack ← []

    8public class ReverseList {9    public static void main(String[] args) {10        // Reverse a list using a stack  //#?reverse11        List<Integer> numbers→ [1, 2, 3, 4, 5] = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));12        13        System.out.println("=== Reversing a List ===");14        System.out.println("Original: " + numbers[1, 2, 3, 4, 5]);15        16        // Push all elements onto stack17        Deque<Integer> stack→ [] = new ArrayDeque<>();18        for (int num : numbers) {
    output=== Reversing a List ===
    Original: [1, 2, 3, 4, 5]
  2. for (int num : numbers)

    pass 1 of 5
    17Deque<Integer> stack = new ArrayDeque<>();18for (int num1 : numbers[1, 2, 3, 4, 5]) {19    stack.push(num1);20}
    All 5 passes — pass 1 is the card above
    passnum
    11
    22
    33
    44
    55
  3. reversed ← []

    22System.out.println("Stack (top first): " + stack[5, 4, 3, 2, 1]);2324// Pop all elements back into list25List<Integer> reversed→ [] = new ArrayList<>();26while (!stack.isEmpty()) {
    outputStack (top first): [5, 4, 3, 2, 1]
  4. original ← Hello World, charStack ← []

    30System.out.println("Reversed: " + reversed[5, 4, 3, 2, 1]);3132// Reverse a string using stack  //#?string  //@var=!,_33System.out.println("\n=== Reversing a String ===");34String original→ Hello World = "Hello World";3536Deque<Character> charStack→ [] = new ArrayDeque<>();37for (char c : original.toCharArray()) {
    outputReversed: [5, 4, 3, 2, 1]
    
    === Reversing a String ===
  5. for (char c : original.toCharArray())

    pass 1 of 11
    36Deque<Character> charStack = new ArrayDeque<>();37for (char cH : original.toCharArray()) {38    charStack.push(cH);39}
    All 11 passes — pass 1 is the card above
    passc
    1H
    2e
    3l
    4l
    5o
    6
    7W
    8o
    9r
    10l
    11d
  6. reversedString ← (empty)

    41StringBuilder reversedString→ (empty) = new StringBuilder();42while (!charStack.isEmpty()) {
  7. System.out.println("Original: \"" + original + "\"");

    46System.out.println("Original: \"" + originalHello World + "\"");47System.out.println("Reversed: \"" + reversedStringdlroW olleH + "\"");4849// Palindrome check using stack  //#?palindrome50System.out.println("\n=== Palindrome Check ===");51checkPalindrome("radar");52checkPalindrome("hello");
    outputOriginal: "Hello World"
    Reversed: "dlroW olleH"
    
    === Palindrome Check ===
  8. clean ← radar, stack ← []

    pass 1 of 3
    56static void checkPalindrome(String inputradar) {57    // Clean string: lowercase, letters only58    String clean→ radar = input.toLowerCase().replaceAll("[^a-z]", "");59    60    Deque<Character> stack→ [] = new ArrayDeque<>();61    for (char c : clean.toCharArray()) {
    All 3 passes — pass 1 is the card above
    passinputcleanstack
    1radarradar[]
    2hellohello[]
    3A man a plan a canal Panamaamanaplanacanalpanama[]
  9. for (char c : clean.toCharArray())

    pass 1 of 31
    60Deque<Character> stack = new ArrayDeque<>();61for (char cr : clean.toCharArray()) {62    stack.push(cr);63}
    31 passes — pass 1 is the card above
    passc
    1r
    2a
    3d
    4a
    5r
    6h
    7e
    8l
    9l
    ⋯ 20 more passes ⋯
    30m
    31a
  10. reversed ← (empty)

    65StringBuilder reversed→ (empty) = new StringBuilder();66while (!stack.isEmpty()) {
  11. isPalindrome ← true

    50    System.out.println("\n=== Palindrome Check ===");51    checkPalindrome("radar");52    checkPalindrome("hello");53    checkPalindrome("A man a plan a canal Panama");54}5556static void checkPalindrome(String input) {57    // Clean string: lowercase, letters only58    String clean = input.toLowerCase().replaceAll("[^a-z]", "");59    60    Deque<Character> stack = new ArrayDeque<>();61    for (char c : clean.toCharArray()) {62        stack.push(c);63    }64    65    StringBuilder reversed = new StringBuilder();66    while (!stack.isEmpty()) {67        reversed.append(stack.pop());68    }69    70    boolean isPalindrome→ true = clean.equals(reversed.toString());71    System.out.println("\"" + inputradar + "\" → " + 72        (isPalindrometrue ? "Palindrome ✓" : "Not palindrome"));73}
    output"radar" → Palindrome ✓
  12. reversed ← (empty)

    65StringBuilder reversed→ (empty) = new StringBuilder();66while (!stack.isEmpty()) {
  13. isPalindrome ← false

    51    checkPalindrome("radar");52    checkPalindrome("hello");53    checkPalindrome("A man a plan a canal Panama");54}5556static void checkPalindrome(String input) {57    // Clean string: lowercase, letters only58    String clean = input.toLowerCase().replaceAll("[^a-z]", "");59    60    Deque<Character> stack = new ArrayDeque<>();61    for (char c : clean.toCharArray()) {62        stack.push(c);63    }64    65    StringBuilder reversed = new StringBuilder();66    while (!stack.isEmpty()) {67        reversed.append(stack.pop());68    }69    70    boolean isPalindrome→ false = clean.equals(reversed.toString());71    System.out.println("\"" + inputhello + "\" → " + 72        (isPalindromefalse ? "Palindrome ✓" : "Not palindrome"));73}
    output"hello" → Not palindrome
  14. reversed ← (empty)

    65StringBuilder reversed→ (empty) = new StringBuilder();66while (!stack.isEmpty()) {
  15. isPalindrome ← true

    52    checkPalindrome("hello");53    checkPalindrome("A man a plan a canal Panama");54}5556static void checkPalindrome(String input) {57    // Clean string: lowercase, letters only58    String clean = input.toLowerCase().replaceAll("[^a-z]", "");59    60    Deque<Character> stack = new ArrayDeque<>();61    for (char c : clean.toCharArray()) {62        stack.push(c);63    }64    65    StringBuilder reversed = new StringBuilder();66    while (!stack.isEmpty()) {67        reversed.append(stack.pop());68    }69    70    boolean isPalindrome→ true = clean.equals(reversed.toString());71    System.out.println("\"" + inputA man a plan a canal Panama + "\" → " + 72        (isPalindrometrue ? "Palindrome ✓" : "Not palindrome"));73}
    output"A man a plan a canal Panama" → Palindrome ✓

Push all items, then pop them - they come out in reverse order.

Exercise: PriorityQueueDemo.java

Explore PriorityQueue: elements ordered by priority, not arrival