Open In App

Stack get() method in Java with Example

Improve
Improve
Like Article
Like
Save
Share
Report

The Java.util.Stack.get() method is used to fetch or retrieve an element at a specific index from a Stack.

Syntax:

Stack.get(int index)

Parameters: This method accepts a mandatory parameter index which is of integer data type. It specifies the position or index of the element to be fetched from the Stack.

Return Value: The method returns the element present at the position specified by the parameter index.

Below programs illustrate the Java.util.Stack.get() method:

Program 1:




// Java code to illustrate get() method
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // Use add() method to add elements in the Stack
        stack.add("Geeks");
        stack.add("for");
        stack.add("Geeks");
        stack.add("10");
        stack.add("20");
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Fetching the specific element from the Stack
        System.out.println("The element is: "
                           + stack.get(2));
    }
}


Output:

Stack: [Geeks, for, Geeks, 10, 20]
The element is: Geeks

Program 2:




// Java code to illustrate get() method
import java.util.Stack;
  
public class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // Use add() method to add elements in the Stack
        stack.add("1");
        stack.add("2");
        stack.add("3");
        stack.add("10");
        stack.add("20");
  
        // Displaying the Stack
        System.out.println("Stack: "
                           + stack);
  
        // Fetching the specific element from the Stack
        System.out.println("The element is: "
                           + stack.get(4));
    }
}


Output:

Stack: [1, 2, 3, 10, 20]
The element is: 20


Last Updated : 24 Dec, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads