The length attribute allows you to set the number of times the loop should run as you iterate through the members of the array using the for loop.
Every entry in the cars array is output in the example that follows:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Additionally, there is a “for-each” loop that can only be used to iterate through array elements:
for (type variable : arrayname) {
...
}
The “for-each” loop in the example below outputs each element in the cars array:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
The previous example might be understood as follows: print the value of i for each String element (named i, as in index) in vehicles.
When comparing the for loop with for-each loop, you will see that the for-each approach is more readable, easier to implement, and does not require a counter (by using the length property).
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.