The get() method of List interface in Java is used to get the element present in this list at a given specific index.
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 :
List: [10, 20, 30, 40] The element at index 2 is 30
Program 2 : Program to demonstrate the error.
java.lang.IndexOutOfBoundsException: Index: 8, Size: 4
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.