What is the Stack.removeAllElements method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

The removeAllElements method of the Stack class removes all the elements present in the Stack object.

Syntax

public void removeAllElements()

This method doesn’t take any arguments and doesn’t return a value.

Code example

import java.util.Stack;
class RemoveAll {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.add(1);
stack.add(2);
stack.add(3);
System.out.println("The stack is: " + stack);
stack.removeAllElements();
System.out.println("After clearing the stack is : " + stack);
}
}

Click the Run button on the code section above to see how the removeAllElements method works.

Explanation

In the code above:

  • Line 5: We create a Stack object.

  • Lines 8 to 10: We use the add method to add three elements (i.e. 1, 2, and 3) to the Stack object, as shown in the output of line 12.

  • Line 14: We use the removeAllElements method to remove all the elements present in the Stack object.

  • Line 15: After we call the removeAllElements method, the Stack object is empty.

Free Resources