How to add element in ArrayList : add() Method Example

This is a tutorial for adding an element to the ArrayList in java. The method signature of add method is

public boolean add(Object element)

According to Oracle docs, ArrayList appends the specified element to the end of the list.


add() method example in java



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



        //ArrayList<String> Declaration
        ArrayList<String> al= new ArrayList<String>();
        //add method for String ArrayList
        al.add("California");
        al.add("New York");
        al.add("Boston");
        al.add("San jose");
        al.add("San Francisco");
        System.out.println("Elements of ArrayList of String Type: "+al);

        //ArrayList<Integer> Declaration 
        ArrayList<Integer> arrlist = new ArrayList<Integer>();
        //add method for Integer ArrayList
        arrlist.add(12);
        arrlist.add(3);
        arrlist.add(9);
        arrlist.add(96);
        arrlist.add(8);
        System.out.println("Elements of ArrayList of Integer Type: "+arrlist);
    }
}


Output


Elements of ArrayList of String Type: [California, New York, Boston, San jose, San Francisco]
Elements of ArrayList of Integer Type: [12, 3, 9, 96, 8]




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry