Java ArrayList add() Method with Examples (original) (raw)

Last Updated : 14 Mar, 2026

The add() method in Java ArrayList is used to insert elements into the list dynamically. It allows adding elements either at the end of the list or at a specific index position.

import java.util.*;

public class GFG { public static void main(String[] args) {

    // Creating an empty ArrayList
    ArrayList<Integer> al = new ArrayList<>();

    // Use add() method to 
    // add elements in the list
    al.add(10);
    al.add(20);
    al.add(30);

    System.out.println("" + al);
}

}

`

Syntax of add(Object element)

public boolean add(Object element)

**Example 2: add(int index, Object element)

This method inserts the specified element at a given position in the ArrayList. It shifts the current element at that position and subsequent elements to the right.

Syntax of add(int index, Object element)

void add(int index, Object element)

**Parameters:

**Exception: Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 or index > size()).

Java `

import java.util.*;

public class GFG { public static void main(String[] args) {

    // Creating an empty ArrayList
    ArrayList<Integer> al = new ArrayList<>();

    // Use add() method to 
    // add elements in the list
    al.add(10);
    al.add(20);
    al.add(30);
    al.add(40);

    System.out.println("" + al);

    // Adding new element 
    // at index 2
    int i = 2;
    al.add(i, 21);

    System.out.println("" + al);
}

}

`

Output

[10, 20, 30, 40] [10, 20, 21, 30, 40]

**Note: