Java Utility Library

Java Stack - clear() Method



The java.util.Stack.clear() method is used to clear all elements of the stack. This method makes the stack empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.Stack.clear() method is used to clear all elements of the stack called MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<String> MyStack = new Stack<String>();

    //populating stack
    MyStack.push("Alpha");
    MyStack.push("Coding");
    MyStack.push("Skills");

    //printing stack
    System.out.println("Before applying clear() method.");
    System.out.println("MyStack contains: " + MyStack);

    MyStack.clear();

    //printing stack
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MyStack contains: " + MyStack);   
  }
}

The output of the above code will be:

Before applying clear() method.
MyStack contains: [Alpha, Coding, Skills]

After applying clear() method.
MyStack contains: []

❮ Java.util - Stack