Open In App

How to Declare an ArrayList with Values in Java?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




//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:

  • In the above example, from the java.util package we have imported the ArrayList class.
  • Then, we have declared an ArrayList with the name arrayList and it stores the integer objects.
  • After that we have used the add() method to add elements to ArrayList.
  • At last, it prints all the values to an ArrayList.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads