You can use an enhanced for loop, also called a for-each loop, to read each element in an array.
In this example, you will loop through an array of programming language names and print each name.
Source code
public class ArrayLoopExample {
void main() {
String[] languages = {"Java", "Python", "JavaScript"};
for (String language : languages) {
IO.println(language);
}
IO.println("Total languages: " + languages.length);
}
}
Explanation
The following statement creates an array containing three strings:
String[] languages = {"Java", "Python", "JavaScript"};
String[] means that the variable holds an array of strings. Each value inside the braces is an element of the array.
The enhanced for loop reads the elements in their array order:
for (String language : languages) {
IO.println(language);
}
On each iteration, language holds the next element:
| Iteration | Value of language |
|---|---|
| 1 | "Java" |
| 2 | "Python" |
| 3 | "JavaScript" |
The loop ends after processing the last element. You do not need to manage an index or write a condition to stop the loop.
Finally, the program prints the number of elements using the array’s length field:
IO.println("Total languages: " + languages.length);
Use length without parentheses when working with arrays.
Run the example
Compile and run the file:
javac ArrayLoopExample.java
java ArrayLoopExample
Output
Java
Python
JavaScript
Total languages: 3
Use an enhanced for loop when you need to read each element. If you need the position of an element or want to replace values in the array, use an index-based for loop.
