Arrays in Java V: Iteration

Java provides multiple mechanisms for array iteration. In the last lesson we saw that it is quite cumbersome to manipulate each element individually. Iteration mechanisms are much simpler to use and can be quite useful not only in terms of runtime efficiency but also for increasing maintainability of code.

Ways of Iterating over Java Arrays

To iterate over a Java array you can use –

  1. The traditional for loop
  2. The for-each mechanism introduced in Java 5 (Tiger)
  3. The while loop
  4. The do-while loop

We have already covered all these loops in a generic context. If you have followed the above lessons, you should have absolutely no trouble in applying these loops to Java arrays.

Java Array Iteration Example

Code below demonstrates usage of all of these loops –

The output of the above program is

Conluding Java Arrays

We have discussed Java arrays in five lessons – What are Java ArraysDeclaration and Initialization of Java ArraysMultidimensional Arrays in JavaManipulating individual elements of array and this lesson on iteration.

The reason for being so thorough with Arrays is not because Arrays are a popular data structure. In fact, apart from the String[] in the main method you might never encounter any arrays. Using Java arrays is not encouraged because Java has another data structure called ArrayList which has the same runtime characteristic and does not suffer from size restrictions.

The main reason for being thorough with arrays is that a surprising chunk of job interview questions are based on arrays. This is the simplest data structure and everyone should be able to solve proramming problems on arrays. If somebody doesn’t they are likely to get weeded out of the process pretty soon. Arrays are therefore a good filtering mechanism. They are especially effective in Java because arrays in Java are not so popular. An average Java programmer does not deal with arrays on a day to day basis. So, discussing Java arrays has proven to be very effective at spotting unprepared (and probably non-serious) job candidates. If somebody claims to be a Java programmer, they need to back it up with a sound theoretical knowledge and practical applications of concepts.

Leave a comment

Your email address will not be published.