Java program to iterate over an arraylist

http‮w//:s‬ww.theitroad.com

To iterate over an ArrayList in Java, you can use a for loop or a for-each loop. Here are examples of both methods:

Method 1: Using a for loop

import java.util.ArrayList;

public class ArrayListIteration {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");
        list.add("Date");

        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            System.out.println(str);
        }
    }
}

In the above example, we define an ArrayList of String type with four elements. We use a for loop to iterate over the elements of the list.

Inside the loop, we use the get() method of the ArrayList class to get the element at the current index i. We store the element in a String variable str. Finally, we print the element to the console using the System.out.println() method.

After running the above code, the output would be:

Apple
Banana
Cherry
Date

Method 2: Using a for-each loop

import java.util.ArrayList;

public class ArrayListIteration {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");
        list.add("Date");

        for (String str : list) {
            System.out.println(str);
        }
    }
}

In the above example, we define an ArrayList of String type with four elements. We use a for-each loop to iterate over the elements of the list.

Inside the loop, we use the : operator to iterate over each element of the list. We store the element in a String variable str. Finally, we print the element to the console using the System.out.println() method.

After running the above code, the output would be:

Apple
Banana
Cherry
Date

This program iterates over the ArrayList and prints each element to the console using a for loop and a for-each loop.