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

Java provides multiple ways to iterate through an ArrayList. A traditional for-loop is useful when the index of elements is required. A while-loop offers more control over the iteration process, while the enhanced for-loop provides cleaner and more readable code when only element access is needed.

Java Solution:

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

public class ArrayListIterationExample {

    public static void main(String[] args) {

        List<String> technologies = new ArrayList<>();

        technologies.add("Java");
        technologies.add("Spring Boot");
        technologies.add("Hibernate");
        technologies.add("Microservices");

        // Using for-loop
        for (int index = 0; index < technologies.size(); index++) {
            System.out.println(technologies.get(index));
        }

        // Using while-loop
        int index = 0;
        while (index < technologies.size()) {
            System.out.println(technologies.get(index));
            index++;
        }

        // Using enhanced for-loop
        for (String technology : technologies) {
            System.out.println(technology);
        }
    }
}

Time Complexity: O(n), where n is the number of elements in the ArrayList because each element is visited once.

Space Complexity: O(1), since no additional space proportional to the input size is required.

Key Interview Points: • Use for-loop when index access is required. • Enhanced for-loop improves readability when indexes are not needed. • Iterator and ListIterator are other commonly used iteration mechanisms in Java collections.