List get() method in Java with Examples
The get() method of List interface in Java is used to get the element present in this list at a given specific index.
Syntax :
E get(int index) Where, E is the type of element maintained by this List container.
Parameter : This method accepts a single parameter index of type integer which represents the index of the element in this list which is to be returned.
Return Value: It returns the element at the specified index in the given list.
Errors and exception : This method throws an IndexOutOfBoundsException if the index is out of range (index=size()).
Below programs illustrate the get() method:
Program 1 :
// Java code to demonstrate the working of // get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); System.out.println("List: " + arr); // element at index 2 int element = arr.get(2); System.out.println("The element at index 2 is " + element); } } |
List: [10, 20, 30, 40] The element at index 2 is 30
Program 2 : Program to demonstrate the error.
// Java code to demonstrate the error of // get() method in List import java.util.*; public class GFG { public static void main(String[] args) { // creating an Empty Integer List List<Integer> arr = new ArrayList<Integer>(4); // using add() to initialize values // [10, 20, 30, 40] arr.add(10); arr.add(20); arr.add(30); arr.add(40); try { // Trying to access element at index 8 // which will throw an Exception int element = arr.get(8); } catch (Exception e) { System.out.println(e); } } } |
java.lang.IndexOutOfBoundsException: Index: 8, Size: 4
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int)
Recommended Posts:
- List contains() method in Java with Examples
- List add(E ele) method in Java with Examples
- List add() Method in Java with Examples
- List retainAll() Method in Java with Examples
- List addAll() Method in Java with Examples
- File list() method in Java with Examples
- Collections list() method in Java with Examples
- List listIterator() Method in Java with Examples
- List sublist() Method in Java with Examples
- List removeAll() method in Java with Examples
- List lastIndexOf() Method in Java with Examples
- List indexOf() Method in Java with Examples
- List equals() Method in Java with Examples
- List hashCode() Method in Java with Examples
- List isEmpty() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


