# Adding elements in the middle of an ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

Elements can be added in the middle of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String args[]) throws Exception {
List aList = new ArrayList();
System.out.println("The ArrayList elements are: " + aList);
}
}

## Output

The ArrayList elements are: [Apple, Melon, Mango, Guava, Banana]

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified position in the ArrayList, including in the middle. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
System.out.println("The ArrayList elements are: " + aList);