0Pricing
Java Academy · Lesson

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

  1. Using var for Locals
  2. When var Helps Readability
  3. var in for Loops
  4. Limitations of var
← Back to Java Academy