AI Hints
Home›Java Tutorial›The Enhanced for Loop, The Arrays Class and Searching an Array
Java · Lesson 49 of 120

The Enhanced for Loop

For each value.

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

When you just want to read every value, and don't need the index, Java has a shorter loop. It's called the enhanced for loop, or for each.

  • Read every value
  • No index needed
  • for each

for each value

Read the colon as, in. For each string fruit, in fruits. Java hands you each value, one at a time. The same works for numbers, here adding up prices. Run it. Each fruit, and a total of four point five.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "cherry"};
        for (String fruit : fruits) {
            System.out.println("I like " + fruit);
        }
        double[] prices = {1.20, 0.80, 2.50};
        double total = 0;
        for (double p : prices) {
            total += p;
        }
        System.out.println("Total: " + total);
    }
}
Output
I like apple
I like banana
I like cherry
Total: 4.5

It cannot change the array

The loop variable is a copy of each value. Changing n doesn't change the array. Run it. The numbers are still one, two, three. To change an array, use the normal for loop, with an index.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        for (int n : nums) {
            n = n * 10;
        }
        System.out.println(nums[0] + " " + nums[1] + " " + nums[2]);
    }
}
Output
1 2 3

Which loop

Use the enhanced for loop to read every value. It's shorter, and you can't get the index wrong. Use the classic for loop when you need the index, want to change values, or go backwards.

for each

  • Read every valueNo indexCan't go wrong

Classic for

  • Need the indexChange valuesBackwards or skipping

Summary

For each, type, value, colon, array, visits every value. It's simple, but read only. Next, the Arrays helper class.

Key takeaways
  • for (T x : arr)
  • Read-only
  • No index
Next up: The Arrays Class — sort, print, fill