Concept

How can you iterate over Java arrays?

ComputerScienceOne / Basic Usage

"Using the .length property you can design a for loop that increments an index variable to iterate over the elements in an array.\n\nint arr[] = new int[5];\n\nfor(int i=0; i<arr.length; i++) {\n\narr[i] = 5 * i;\n\n}\n\nThe for loop above initializes the variable i to zero, corresponding to the first element in the array. The continuation condition specifies that the loop continues while i is strictly less than the size of the array denoted using the arr.length property. This for loop iteration is idiomatic when processing arrays. In addition, Java (as of version 5) supports foreach loops that allow you to iterate over the elements of an array without using an index variable. Java refers to these loops as “enhanced for loops,” but they are essentially foreach loops.\n\nfor(int a : arr) {\n\nSystem.out.println(a);\n\n}\n\nThe syntax still uses the keyword for, but instead of an index variable, it specifies the type and a the loop-scoped variable identifier followed by a colon and the array that you want to iterate over. Each iteration of the loop updates the variable a to the next value in the array."

Related Ideas

How can you iterate over Java arrays? | ComputerScienceOne | Bifalgorithm | Bifalgorithm