# How do you add an element to a list in Java?

JavaObject Oriented ProgrammingProgramming

We can use add() methods of List to add elements to the list.

## 1. Use add() method without index.

boolean add(E e)

Appends the specified element to the end of this list (optional operation).

### Parameters

• e − Element to be appended to this list.

### Throws

• UnsupportedOperationException − If the add operation is not supported by this list.

• ClassCastException − If the class of the specified element prevents it from being added to this list.

• NullPointerException − If the specified element is null and this list does not permit null elements.

• IllegalArgumentException − If some property of this element prevents it from being added to this list.

## 2. Use add() with index parameter to add an element at particular location.

void add(int index, E element)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

### Parameters

• index − Index at which the specified element is to be inserted.

• element − Element to be inserted.

### Throws

• UnsupportedOperationException − If the add operation is not supported by this list.

• ClassCastException − If the class of the specified element prevents it from being added to this list.

• NullPointerException − If the specified element is null and this list does not permit null elements.

• IllegalArgumentException − If some property of this element prevents it from being added to this list.

• IndexOutOfBoundsException − If the index is out of range (index < 0 || index > size()).

## Example

Following is the example showing the usage of add() methods −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
System.out.println("List: " + list);
System.out.println("List: " + list);
try {
} catch(IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}

## Output

This will produce the following result −

List: [1, 2, 3, 5, 6]
List: [1, 2, 3, 4, 5, 6]
java.lang.IndexOutOfBoundsException: Index: 7, Size: 6
at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:22)