Retrieve the value of an element in ArrayList in Java

The get(int index) is used to get the value of an item in the ArrayList. We need to specify the position at the time of calling the method that returns the existing value in the specified position.

public Element get(int index): This method throws the exception IndexOutOfBoundsException if index is less than 0 or larger than the current list size ( 0 <= index <= list size).

Here is a simple example that shows how to retrieve objects from ArrayList using the get(int index).

import java.util.ArrayList; 

public class ArrayListGet{

public static void main(String[] args) {

// Create an ArrayList< String>
ArrayList< String> arraylist = new ArrayList< String> ();

//add strings to ArrayList
arraylist.add("e1");
arraylist.add("e2");
arraylist.add("e3");
arraylist.add("e4");

System.out.println("element at position 0: "+arraylist.get(0));
System.out.println("element at position 2: "+arraylist.get(2));

System.out.println("get all items from ArrayList");
for(int i = 0; i< arraylist.size(); i++)
System.out.println(arraylist.get(i));
}
}
Run:

item at position 0: e1
item at position 2: e3
get all items from ArrayList
e1
e2
e3
e4