Java Stack clear() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Inherited from Vector

Definition

In Java, clear() removes all elements from a Stack, leaving it empty with size 0. It is declared in the Collection interface, so the same call empties a Stack, an ArrayList, or an ArrayDeque.

In Vector, clear() simply calls removeAllElements(). Clearing keeps the same stack object, so every reference to it sees an empty stack, ready for new pushes immediately.

An instance method inherited from java.util.Vector (since Java 1.2). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.

Syntax

Call clear with no arguments.

Java
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.clear();                 // []
int n = stack.size();          // 0
stack.pop();                   // throws EmptyStackException
CallWhat it does
stack.clear()Removes every element.
stack.removeAllElements()The legacy Vector name; clear() calls it.
collection.clear()Works on any collection type.
stack.clear(); stack.trimToSize()Empties the stack and also shrinks its internal array.

clear() takes time proportional to the size, because each slot is set to null so the old objects can be garbage collected.

Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public void clear()

// body: removeAllElements();
// declared in java.util.Collection<E> and java.util.List<E>

Parameters

ParameterDescription
Noneclear() takes no parameters.

Return Value

Return ValueDescription
voidNothing. Afterwards isEmpty() is true.

Compare with Similar Methods

Related ways to empty a stack:

MethodHow it differs
removeAllElements()The same operation under Vector's original name.
setSize(0)Another way to empty the stack.
isEmpty()Returns true right after clear().
ArrayList.clear()The same call on a list.

Java Examples

Example 1 — The C Key on a Stack Calculator

A tiny RPN calculator pushes numbers, adds with +, and wipes everything with C.

Java
import java.util.Stack;

public class StackClearCalculator {
    public static void main(String[] args) {
        Stack<Integer> operands = new Stack<>();
        String[] keys = {"4", "9", "C", "2", "3", "+"};

        for (String key : keys) {
            if (key.equals("C")) {
                operands.clear();
                System.out.println("C pressed, stack: " + operands);
            } else if (key.equals("+")) {
                operands.push(operands.pop() + operands.pop());
                System.out.println("+ gives " + operands.peek());
            } else {
                operands.push(Integer.parseInt(key));
            }
        }
    }
}

How It Works

  1. Numbers are pushed. Pressing 4 and 9 puts two operands on the calculator's stack.
  2. C wipes them. clear() discards both operands in one call, and printing the stack shows [].
  3. A fresh start. 2 and 3 are pushed onto the same, now empty stack, and + pops both and pushes 5; the old 4 and 9 play no part.

Example 2 — Reuse One Stack for Every Input Line

Measure bracket nesting line by line with a single stack that is cleared before each line.

Java
import java.util.Stack;

public class StackClearReuse {
    public static void main(String[] args) {
        String[] lines = {"((a)", "(b))", "c()"};
        Stack<Character> open = new Stack<>();

        for (String line : lines) {
            open.clear();
            int maxDepth = 0;
            for (char ch : line.toCharArray()) {
                if (ch == '(') {
                    open.push(ch);
                    maxDepth = Math.max(maxDepth, open.size());
                } else if (ch == ')' && !open.isEmpty()) {
                    open.pop();
                }
            }
            System.out.println(line + ": max depth " + maxDepth + ", left open " + open.size());
        }
    }
}

How It Works

  1. One stack for all lines. The same open stack is reused, and clear() at the start of each line removes whatever the previous line left behind.
  2. Why it matters. The first line leaves one ( unclosed; without the clear(), that leftover would inflate the depth measured for the second line.
  3. Per-line results. Each line reports its own deepest nesting and how many brackets were still open when it ended; the extra ) in the second line is ignored.

Example 3 — What clear() Does to Capacity

Fill a buffer stack, clear it, then trim it, printing size and capacity each time.

Java
import java.util.Stack;

public class StackClearCapacity {
    public static void main(String[] args) {
        Stack<Integer> buffer = new Stack<>();
        for (int i = 0; i < 25; i++) {
            buffer.push(i);
        }
        System.out.println("full:    size " + buffer.size() + ", capacity " + buffer.capacity());

        buffer.clear();
        System.out.println("cleared: size " + buffer.size() + ", capacity " + buffer.capacity());

        buffer.trimToSize();
        System.out.println("trimmed: size " + buffer.size() + ", capacity " + buffer.capacity());
    }
}

How It Works

  1. Growth by doubling. Starting from 10, the internal array doubles to 20 and then to 40 while 25 numbers are pushed.
  2. clear() keeps the room. The size drops to 0, but in the JDK implementation the array keeps its 40 slots, ready for the next round of pushes.
  3. trimToSize() gives it back. Vector's trimToSize() shrinks the capacity to the current size, 0, for when memory matters more than speed.

Frequently Asked Questions

It removes every element, so size() becomes 0 and empty() returns true. The same stack object can be reused.
Yes. In Vector, clear() calls removeAllElements(). clear() is the name shared by all collections.
It releases the elements, but the internal array keeps its capacity. Call trimToSize() to shrink it.
peek() throws EmptyStackException because the stack is now empty.
Either works. clear() keeps the same object, which matters when other code holds a reference to it; a new Stack starts again with the default capacity.

Next: contains()

Check whether any element equals a value.

contains() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful