Write a Java program to insert an element into the array list at the first position


The program starts by creating an ArrayList of String type named list_Str and adding seven elements to it using the add() method of ArrayList. The elements added to the list are "Apple", "Banana", "Cherry", "Pineapple", "Guava", "Papaya" and "Plum". Then, the program prints the elements of the list using the println() method of System.out object.

After that, the program inserts two elements into the list at specific positions using the add() method. The first element, "Mango", is inserted at index 0, which means it will become the first element of the list. The second element, "Strawberry", is inserted at index 5, which means it will become the sixth element of the list. Finally, the program prints the updated elements of the list using the println() method of System.out object.

Source Code

import java.util.*;
class Insert_Element
{
	public static void main(String[] args)
	{
		List<String> list_Str = new ArrayList<String>();
		list_Str.add("Apple");
		list_Str.add("Banana");    
		list_Str.add("Cherry");
		list_Str.add("Pineapple");
		list_Str.add("Guava");
		list_Str.add("Papaya");
		list_Str.add("Plum");
		System.out.println(list_Str);
		list_Str.add(0, "Mango");
		list_Str.add(5, "Strawberry");
		System.out.println(list_Str);
	}
}

Output

[Apple, Banana, Cherry, Pineapple, Guava, Papaya, Plum]
[Mango, Apple, Banana, Cherry, Pineapple, Strawberry, Guava, Papaya, Plum]

Example Programs