Java Utility Library

Java Stack - elementAt() Method



The java.util.Stack.elementAt() method returns element at the specified index in the stack.

Syntax

public E elementAt(int index)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number of the element in the stack.

Return Value

Returns element at the specified index in the stack.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Example:

In the example below, the java.util.Stack.elementAt() method is used to get the value of element at the specified index in the stack.

import java.util.*;

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

    //populating stack
    MyStack.add(10);
    MyStack.add(20);
    MyStack.add(30);
    MyStack.add(40);
    MyStack.add(50);

    //printing stack using get() method
    System.out.print("MyStack contains:"); 
    for(int i = 0; i < MyStack.size(); i++) {
      System.out.print(" " + MyStack.elementAt(i));
    }
  }
}

The output of the above code will be:

MyStack contains: 10 20 30 40 50

❮ Java.util - Stack