In this source code example, we will show you how to use var in for loops in Java.
The var keyword was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context.
Java var in for loop
import java.util.List;
public class Main {
public static void main(String[] args) {
// explicit type
System.out.println("Explicit type:");
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
// using var
System.out.println("\n\nLVTI:");
for (var i = 0; i < 5; i++) { // 'i' is inferred of type int
System.out.print(i + " ");
}
List<Player> players = List.of(new Player(), new Player(), new Player());
System.out.println("\n\nExplicit type:");
for (Player player : players) {
System.out.print(player + " ");
}
System.out.println("\n\nLVTI:");
for (var player : players) { // 'player' is inferred of type Player
System.out.print(player + " ");
}
}
}
class Player{
}
Output:
Explicit type:
0 1 2 3 4
LVTI:
0 1 2 3 4
Explicit type:
P89_VarForLoops.src.modern.challenge.Player@2c7b84de P89_VarForLoops.src.modern.challenge.Player@3fee733d P89_VarForLoops.src.modern.challenge.Player@5acf9800
LVTI:
P89_VarForLoops.src.modern.challenge.Player@2c7b84de P89_VarForLoops.src.modern.challenge.Player@3fee733d P89_VarForLoops.src.modern.challenge.Player@5acf9800
Comments
Post a Comment