EMZETT.
Login

Index

In short: The counter variable a loop or array access uses to count through the current position — starting at 0 by default in Java.

In more detail: Arrays and most collections in Java are zero-based: the first element sits at index 0, the last at length - 1. Access outside this range (e.g. arr[arr.length]) throws an ArrayIndexOutOfBoundsException at runtime.

In Depth

int[] numbers = {10, 20, 30, 40, 50};
 
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Index " + i + ": " + numbers[i]);
}
 
// Iterating backwards - index starts at the end
for (int i = numbers.length - 1; i >= 0; i--) {
    System.out.println(numbers[i]);
}
 
// "Off-by-one" error: one of the most common sources of error for beginners
for (int i = 0; i <= numbers.length; i++) { // <= instead of < !
    System.out.println(numbers[i]); // throws an ArrayIndexOutOfBoundsException at i == 5
}

The “off-by-one” error (confusing < and <= in the exit condition) is one of the most common beginner mistakes when working with indices: because the last valid element sits at length - 1 (not at length), the condition has to be i < length, not i <= length. With for-each loops (for (int number : numbers)), this problem disappears entirely, because no index is maintained manually — but then you also don’t have direct access to the position of the current element if you need it (in that case, only the classic index-based loop or an additional manual counter remains).

Index in collections vs. arrays

Unlike arrays, Set and Map (from the collections framework) have NO index access, since these data structures don’t guarantee a fixed order. List, by contrast, behaves index-wise like an array, but uses methods instead of square brackets:

List<String> list = new ArrayList<>(List.of("a", "b", "c"));
String second = list.get(1); // "b" - index access via get(), not list[1]
list.set(1, "B");              // replace the element at index 1
int position = list.indexOf("c"); // 2 - find the position of a known value

There’s no ArrayIndexOutOfBoundsException for List — instead, get() throws an IndexOutOfBoundsException (the shared superclass of both more specific exceptions) for an invalid index, which shows that Java deliberately distinguishes between the historically older array access and the later-introduced Collections framework, even though both are conceptually zero-indexed.

See also: For Loop, Arrays, Exceptions