Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to loop through an array with the index

Short answer

An ordinary for loop gives you both the index and the value:

void main() {
    String[] fruits = {"apple", "banana", "cherry"};
    for (int i = 0; i < fruits.length; i++) {
        IO.println(i + ": " + fruits[i]);
    }
}

Output:

0: apple
1: banana
2: cherry

Values only

If you do not need the index, for-each is shorter and keeps you from getting the bounds wrong:

void main() {
    String[] fruits = {"apple", "banana", "cherry"};
    for (String fruit : fruits) {
        IO.println(fruit);
    }
}

Output:

apple
banana
cherry

With a stream

IntStream.range() walks the indexes in stream style:

void main() {
    String[] fruits = {"apple", "banana", "cherry"};
    IntStream.range(0, fruits.length)
            .filter(i -> i % 2 == 0)
            .forEach(i -> IO.println(i + " " + fruits[i]));
}

Output:

0 apple
2 cherry

Backwards

To iterate backwards, start at length - 1:

void main() {
    int[] numbers = {1, 2, 3};
    for (int i = numbers.length - 1; i >= 0; i--) {
        IO.print(numbers[i] + " ");
    }
    IO.println();
}

Output:

3 2 1

Common mistake

Using the condition i <= length. The last index of an array is length - 1:

void main() {
    int[] numbers = {1, 2, 3};
    for (int i = 0; i <= numbers.length; i++) {
        IO.println(numbers[i]);
    }
}

Output:

1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Functions used in this recipe

  • IntStream.range() — Creates a stream of integers from a range.
  • for — A loop with a counter, or iteration over every element of an array or collection (for-each).
  • Iterable — The interface of everything that a for-each loop can iterate over.

Thanks for reading!

Donate to the site — we work hard for you.