What is the Stack.removeElementAt() 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 removeElementAt method of the Stack class can be used to remove the element at a specific index of the stack object. The elements after the index will be shifted one index downward. The size of the stack also decreases by 1.

Syntax

public void removeElementAt(int index)

Argument

The index of the element is to be removed. The index should be positive and less than the size of the stack object. Otherwise, ArrayIndexOutOfBoundsException will be thrown.

index >= 0 && index < size()

This method doesn’t return any value.

Code

Click the “Run” button below and see how the removeElementAt() method works.

import java.util.Stack;
class RemoveElementAt {
public static void main( String args[] ) {
// Creating a Stack
Stack<Integer> stack = new Stack<>();
// Adding elememts to the Stack
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The stack is: " + stack);
// Removing the element at index 1
stack.removeElementAt(1);
System.out.println("\nAfter removing the element at index 1, the stack is: " + stack);
}
}

Explanation

In the code above:

  • In line 5, we created a Stack object.

  • In lines 8 to 10, we added three elements (1,2,3) to the created stack object using the push method.

  • In line 14, we used the removeElementAt() method of the stack object to remove the element present at index 1.

Free Resources