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 does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- What are enhanced for loops in Java?ComputerScienceOne · Enhanced For Loops
- How are for loops structured and scoped in Java?ComputerScienceOne · Do-While Loops
- How does an enhanced for loop calculate the sum of integers in a Java list?ComputerScienceOne · Normalizing a Number
- How can you simulate a foreach loop when iterating over an array in C?ComputerScienceOne · Other Issues
- How can you iterate over indexed and associative arrays in PHP?ComputerScienceOne · Iteration
- How can you iterate through an array using foreach?ComputerScienceOne · Adding Elements
- How does PHP use foreach loops to iterate over array elements?ComputerScienceOne · Foreach Loops