Write a Java program to iterate an ArrayList using a for loop, a while loop and an enhanced for loop.

An ArrayList can be traversed with a classic index-based for loop, a while loop with a counter, or the enhanced for-each loop. All three visit the elements in insertion order.

Key Points

import java.util.ArrayList;
import java.util.List;

public class IterateArrayList {

    public static void main(String[] args) {
        List<String> langs = new ArrayList<>(List.of("Java", "Kotlin", "Scala"));

        System.out.println("-- for loop --");
        for (int i = 0; i < langs.size(); i++) {
            System.out.println(i + " -> " + langs.get(i));
        }

        System.out.println("-- while loop --");
        int i = 0;
        while (i < langs.size()) {
            System.out.println(langs.get(i));
            i++;
        }

        System.out.println("-- enhanced for loop --");
        for (String lang : langs) {
            System.out.println(lang);
        }
    }
}

Output

-- for loop --

0 -> Java

1 -> Kotlin

2 -> Scala

-- while loop --

Java

Kotlin

Scala

-- enhanced for loop --

Java

Kotlin

Scala

Good to Know

Java 8 added list.forEach(System.out::println) and streams. For a LinkedList, avoid the index-based loop: get(i) is O(n) there, which makes the whole loop O(n²).

Interviewers often follow up with "How do you remove elements while iterating?" Answer with Iterator.remove() or list.removeIf(...).

Interview Tip

A concise interview answer is

I can use an index-based for loop when I need the position, a while loop with a counter when the stop condition is custom, or the enhanced for loop for simple read-only traversal. All are O(n) for an ArrayList, and if I need to remove elements while looping I use an Iterator or removeIf().

Last updated: 11 November 2026

Previous question: Write a Java program to print the Fibonacci series using recursion.

Next question: Write a Java program to find the duplicate characters in a string.

More Java Coding Questions interview questions

All Java Coding Questions questions