The Enhanced For Loop In Java

The Enhanced For Loop In Java

The Java enhanced for loop was introduced in Java 5. It's a simpler way to iterate through all the collection of elements. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array / collection without explicitly expressing how one goes from element to element.

Enhanced for loop in java example

Let's consider an example to calculate the sum of the integers in an array,

Standard version

int sum(int[] a) {
   int sum=0;
   for(int i=0;i<a.length();i++) sum+=a[i];
   return sum;
}
Enhanced version

int sum(int[] a) {
    int sum = 0;
    for (int i : a) sum += i;
    return sum;
}

Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element. In all other cases, the "standard" for loop should be preferred.
The introduction of enhanced for loop in java did not end support to the standard version. Hence there will be no problem to use the Standard for loop if you wish to.

0 comments:

Post a Comment

Please DO NOT SPAM. You're not allowed to use links in comments unless it's necessary.

I Appreciate your valuable Feedback.

Regards,

www.TricksStar.com