Open In App

How to Declare an ArrayList with Values in Java?

ArrayList is simply known as a resizable array. Declaring an ArrayList with values is a basic task that involves the initialization of a list with specific elements. It is said to be dynamic as the size of it can be changed. Proceeding with the declaration of ArrayList, we have to be aware of the concepts of Arrays and Lists in Java programming.

In this article, we will learn to declare an ArrayList with values in Java.



Program to declare an ArrayList with Values

It is the easiest and most direct method to add values while declaration. There is a basic way to declare an ArrayList with values is by Adding elements one by one by using the add() method.

Syntax:

ArrayList<Integer> arrayList = new ArrayList<>();arrayList.add(1);arrayList.add(2);

Below is the implementation of Declare an ArrayList with Values in Java:






//Java program to declare an ArrayList with values 
//importing util package to use the methods 
import java.util.*;
  
public class GFG {
    public static void main(String[] args) {
          
        // Declare and initialize ArrayList using Arrays.asList
        ArrayList<Integer> arrayList = new ArrayList<>();
  
    //Adding Values to the ArrayList
    arrayList.add(5);
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(4);
      
  
  
        // Print ArrayList
        System.out.println("ArrayList: " + arrayList);
    }
}

Output
ArrayList: [5, 1, 2, 4]



Explanation of the above Program:

Article Tags :