adding a value to an arraylist java code example

Example 1: insert element into arraylist java

ArrayList<String> arrayList = new ArrayList<>();
// Adds element at the back of the list
arrayList.add("foo");
arrayList.add("bar");
// Result = ["foo", "bar"]

// Adds element at the specified index
arrayList.add(1, "baz");
// Result = ["foo", "baz", "bar"]

Example 2: how to add to an arraylist java

import java.util.ArrayList;
public class Details {
    public static void main(String[] args) {

        //ArrayList<String> Declaration
        ArrayList<String> al= new ArrayList<String>();
        //add method for String ArrayList
        al.add("Ram");
        al.add("Shyam");
        al.add("CPS");
        al.add("John");
        al.add("Steve");
        System.out.println("Elements of ArrayList of String Type: "+al);