Java Utility Library

Java Stack - get() Method



The java.util.Stack.get() method returns the element at specified index of the stack.

Syntax

public E get(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 the element at specified index of the stack.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Example:

In the example below, the java.util.Stack.get() method returns element at specified index of 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.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);
    MyStack.push(50);

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

The output of the above code will be:

MyStack contains: 10 20 30 40 50

❮ Java.util - Stack