Java Program to Add Elements into an ArrayList

In the previous article, we have seen Java Program to Sort an ArrayList

In this article we are going to see various methods in which we can add elements into an ArrayList in Java programming language.

Java Program to Add Elements into an ArrayList

ArrayList has add() method by using which we can add elements into an arraylist.

Approach:

  • Create an arraylist.
  • Add individual elements into the arraylist by using the add( ) library function.
  • Display the list and add some more elements to the list.
  • Then display the new list again.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Creating an empty ArrayList
        ArrayList<String> arr = new ArrayList<String>();
        // Adding elements to the arrayList
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        // Displaying the list
        System.out.println("Current List "+arr);
        // Adding a new element to the existing list
        arr.add("New Element");
        // Displaying the list
        System.out.println("After adding a new element "+arr);
    }
}
Output:

Current List [One, Two, Three]
After adding a new element [One, Two, Three, New Element]

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: