var in for Loops
Infer loop variable types.
var in Loops
var works naturally as the loop variable in both classic for loops and enhanced for-each loops. The compiler infers the type from the loop context.
Classic for Loop Counter
In a classic for loop, var infers the counter type from its initializer. Here var i = 0 infers int.
public class Main {
public static void main(String[] args) {
for (var i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
}
}All lessons in this course
- Using var for Locals
- When var Helps Readability
- var in for Loops
- Limitations of var