Examples of ArrayList in Java

In this tutorial, you will learn how to create an array using ArrayList in Java.

To get started we need to add the following namespace:

import java.util.ArrayList;

1- ArrayList of String values

First, let’s create an ArrayList of String values:

import java.util.ArrayList;
public class ArrayListExample {

  public static void main(String[] args) {

    ArrayList < String > language = new ArrayList();

    language.add("C++");
    language.add("C#");
    language.add("JavaScript");
    language.add("Java");
    language.add("Julia");
    language.add("Ruby");
    for (String lang: language) {
      System.out.println(lang);
    }

  }
}

Output

C++
C#
JavaScript
Java
Julia
Ruby

2- ArrayList of Integer values

In the second example, we are going to create an ArrayList of integer values:

import java.util.ArrayList;
public class ArrayListExample {

  public static void main(String[] args) {

    ArrayList < Integer > number = new ArrayList();

    number.add(1);
    number.add(2);
    number.add(3);
    number.add(4);
    number.add(5);
    number.add(6);
    for (Integer num: number) {
      System.out.println(num);
    }

  }
}

Output

1
2
3
4
5
6

That’s all. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *