Declaring simple for loops using explicit types is a trivial task, as follows:
// explicit type
for (int i = 0; i < 5; i++) {
...
}
Alternatively, we can use an enhanced for loop:
List<Player> players = List.of(
new Player(), new Player(), new Player());
for (Player player: players) {
...
}
Starting with JDK 10, we can replace the explicit types of the variables, i and player, with var, as follows:
for (var i = 0; i < 5; i++) { // i is inferred of type int
...
}
for (var player: players) { // i is inferred of type Player
...
}
Using var can be helpful when the type of a looped array, collection, and so on is changed. For example, by using var, both versions of the following array can be looped without specifying the explicit type:
// a variable 'array' representing an int[]
int[] array = { 1, 2, 3 };
// or the same variable, 'array', but representing a String[]
String[] array = {
"1", "2", "3"
};
// depending on how 'array' is defined
// 'i' will be inferred as int or as String
for (var i: array) {
System.out.println(i);
}