AI Hints
Home›Java Tutorial›What an Array Is, Creating Arrays and Looping Over Arrays
Java · Lesson 48 of 120

Looping Over Arrays

Visit every box.

⏱ 2 min read▶ Video at 1:00:09🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Arrays and for loops are best friends. A for loop can visit every box, one by one, using the index.

  • Arrays + for loops
  • Visit every box
  • One by one

Index by index

I starts at zero, the first index. The loop runs while I is less than the length. Inside, planets, square bracket I, is the current planet. The same pattern adds up all the steps. Run it. Each planet with its index, and twenty nine thousand, one hundred steps.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] planets = {"Mercury", "Venus", "Earth", "Mars"};
        for (int i = 0; i < planets.length; i++) {
            System.out.println(i + ": " + planets[i]);
        }
        int[] steps = {4200, 8100, 6500, 10300};
        int total = 0;
        for (int i = 0; i < steps.length; i++) {
            total += steps[i];
        }
        System.out.println("Total steps: " + total);
    }
}
Output
0: Mercury
1: Venus
2: Earth
3: Mars
Total steps: 29100

Changing and reversing

A loop can change every box, here doubling each price. Another loop counts down, from the last index to zero, to print the array backwards. Run it. Sixteen, ten, six.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] prices = {3, 5, 8};
        for (int i = 0; i < prices.length; i++) {
            prices[i] = prices[i] * 2;
        }
        for (int i = prices.length - 1; i >= 0; i--) {
            System.out.print(prices[i] + " ");
        }
        System.out.println();
    }
}
Output
16 10 6

The standard loop

Start at zero. Stop before the length. Use I as the index. This loop shape is so common, you'll write it without thinking.

keyvalue
Startint i = 0
Stopi < arr.length
Stepi++
Usearr[i]

Summary

A for loop from zero to length minus one visits every box. It can read, change, or reverse an array. Next, an easier loop for reading arrays.

Key takeaways
  • i from 0
  • i < length
  • arr[i]
Next up: The Enhanced for Loop — for each value