Saturday, 13 February 2016

How to Loop Through An Array in Java with Example

There are multiple ways to loop over an array in Java e.g. you can use a for loop, an enhanced for loop, a while loop or a do-while loop. Since while and do-while needs a condition to terminate they often depend upon the content of the array e.g. stop when the current element is null or even or odd etc. If you just want to iterate over an array to access each element e.g. loop over an array and print each entry then you should use either for loop or the enhanced for loop. The traditional for loop uses a counter and allows you to iterate until the last element is reached i.e. counter is equal to the length of the array while enhanced for loop maintains that counter internally, allowing you to iterate without worrying about counts. This results in clean code and it also eliminates the possibility of one-off errors. In this article, I'll show you 2 ways to iterate over an array, first by using traditional for loop and second by using enhanced for loop of Java 1.5.
Read more »

No comments:

Post a Comment