What are some unique ways in Java to loop through an array?



This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

This is my answer to this question on Quora.

Kenny Yu mentioned the standard ways to loop through an array. A unique way, I suppose, is to use recursion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
    int[] array = {4,65,2,34,25,25,43,63,654,635,6};
    loopRecursively(array,0);
}

public static void loopRecursively(int[] array, int i) {
    System.out.println(array[i]);

    i++;

    if(i < array.length) {
        loopRecursively(array, i);
    }
}

However, recursion is well understood. It’s unique in the sense you shouldn’t use it (at least in this case).

Also, although not an array, you can use the forEach method in that is new for Java 8 Lists / Iterables:

1
2
3
List list = Arrays.asList(4,65,2,34,25,25,43,63,654,635,6);

list.forEach(element -> System.out.println(element));

Leave a Reply

Note that comments won't appear until approved.