add values to arraylist java code example

Example 1: add value with n variable with Arraylist in java

Scanner in = new Scanner(System.in);
int n = 5;
ArrayList<String> addName = new ArrayList<>();
for(int i = 0; i < n; i++){
  addName.add(in.nextLine());
}

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);

Example 3: append to arraylist by index java

arrlist.add(2,25);
// .add(index, content)

Tags:

Java Example