Menu

Java Foreach Loop

Another version of for, is the foreach. The keyword we use is stillĀ for, but when we want to iterate on the elements inside an array we can simply use it:

int[] arr = {2, 0, 1, 3};
for (int el : arr) {
    System.out.println(el);
}

This is a short version and equivalent to:

int[] arr = {1, 9, 9, 5};
for (int i = 0; i < arr.length; i++) {
    int el = arr[i];
    System.out.println(el);
}

Notice that if you want to use the index of the element inside the loop, you have to use the longer version and can’t use foreach.

Leave a Reply

Your email address will not be published. Required fields are marked *