Understanding the for each (Enhanced for loop) in Java

0
1755
The normal for loop make you feel sick? You want to write your code that looks like a “pro” or want to show your friend a for loop that took them a while to understand or maybe never understand. Welcome to the Enhanced for loop aka for each.

Understanding the for each (Enhanced for loop) in Java

First, consider the original for loop:

int[] ints = new int[5];
for (int i = 0; i < ints.length; i++){
    ints[i] = i;
}

In the code snippet above, we create a new array of int with the length of 5. We then loop through the array and assign each element with the i.

Now let print the array using for loop again

for (int i = 0; i < ints.length; i++) {
    System.out.println(ints[i]);
}

0
1
2
3
4

In both cases, we assess the value of each element by the index of i.

So, whenever you want to loop through an array for doing something (add, remove, print, modify value) you always have to create a new variable “int i = 0”, then compare it to the length of the array, then add the “i” by one after each iteration. Such a great effort to make a simple task done.

Here come the Enhanced for loop

see the code first and I will explain later:

for (int i: ints) {
    System.out.println(i);
}

0
1
2
3
4

Great, we had the same output, with less of code and most important, it looks like “Pro”. But do you understand how it works?

This kind of for loop is also called for Each, means it will do something for each of element inside the array that you want to loop through.

Inside the parenthesis

  • First, you need to declare the datatype. This should be the same data type of the elements inside the array you want to iterate.
  • Second, you define the name of each element in each iteration.
  • Third, you put in the array you want to loop through.

So, more detail, in the first loop, the element ints[0] will be named as “i” and then we print it by the code inside for loop. Next loop the element ints[1] will be named as “i” again and print, so on and so forth.

How to use for Each with reference datatype.

You have an array of the Class Doctor and want to print the name of each doctor?

for (Doctor d : doctors) {
    System.out.printf(d.getName());
}

Inside the parenthesis, you declare the datatype is Doctor, the name of each element for each iteration is “d” and the array you want to loop is doctors

When should you use Enhanced for loop?

Remember, you can not use this kind of loop to initiate the value of element inside the array or add a new element to the array. The for Each only works when your array has something inside and you want to print out or modify each of the elements. That why it is called “for Each”. Do something for each element inside the array.

LEAVE A REPLY

Please enter your comment!
Please enter your name here