What is the Stack.elementAt method in Java?

The Stack class follows Last-In-First-Out (LIFO) principle. The element inserted first is processed last and the element inserted last is processed first. This class is present in the java.util package. This class extends the Vector class and implements some methods specific to Stack methods, like push and pop.

The above image shows how a stack will be. The new stone will be always kept at the top and the stone which is last kept will be taken first. The image is taken from here.

The elementAt method of the Stack class can be used to get the element at a specific index of the Stack object.

Syntax

public E elementAt(int index)

Parameters

This method’s argument is the index from which the element is to be fetched. The index should be positive and less than the size of the Stack object. Otherwise, an ArrayIndexOutOfBoundsException will be thrown.

index >= 0 && index < size()`

Return value

This method returns the element present at the passed index.

Code

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

Please click the “Run” button on the code section above to see how the elementAt method works.

Explanation

In the code above,

  • Line 5: We create an object for the Stack class with the name stack.

  • Lines 8 to 10: We add three elements (1,2,3) to the created stack object using the push method.

  • Lines 14 to 16: We used the elementAt method of the stack object to get the element present at the indices 0,1, and 2.

Free Resources