Stack Operations in Java: Explanation & Practice

Use Stack for LIFO operations

Problem summary

Create a Stack, push elements, and demonstrate LIFO behavior.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        // Push: 1, 2, 3
        // Pop and print all elements
    }
}

Expected output and test cases

  • LIFO order
    3
    2
    1

Hints

  1. push() to add to top
  2. pop() to remove from top
  3. peek() to see top without removing

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler