Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Enhanced for Statement
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Let's examine another type of loop. The "enhanced for" statement, or the "for-each" loop, looks at each element of an array in order, which allows the loop to automatically avoids errors such as going past the last index of an array. Let's revisit the same goal as in the example on previous page, but try it now with the for-each loop.
EnhancedForLoopExample.java
package exlcode;
public class EnhancedForLoopExample {
public static int[] exampleVariableOne = {0, 1, 2, 3, 4, 5, 6, 7, 8};
public static int sum = 0;
public static void main(String[] args) {
// simplifies the for loop and creates simple code
// 1D array
for (int count : exampleVariableOne) {
sum += exampleVariableOne[count];
}
System.out.println(sum);
}
}
The syntax for an "enhanced for statement" is as follows, for(datatype variablename : arrayname). The "datatype" and "variablename" is what you would put in the first section of a for loop, the loop control variable. This creates a new variable that only exists within the "for-each" loop. It is used as the index when accessing the elements of the array.
The "for-each" loop is used when you want to loop through each and every element of the array without missing out an index or accidentally exceeding the last index of the array. When you code a program that only accesses certain elements inside an array, you can still use the "for-each" loop. However, as it requires an extra if statement to do so, you may choose to use a regular for loop with incrementing/decrementing variables as shown in past topics.