0Pricing
Java Academy · Lesson

var in for Loops

Infer loop variable types.

var in for Loops is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);
        }
    }
}

for-each Over a List

In an enhanced for loop, var infers the element type from the collection. Here each name is a String.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        var names = List.of("Ann", "Ben", "Cara");
        for (var name : names) {
            System.out.println(name);
        }
    }
}

for-each Over an Array

The same works for arrays. The element type is inferred from the array type.

public class Main {
    public static void main(String[] args) {
        var scores = new int[]{90, 85, 78};
        var total = 0;
        for (var s : scores) {
            total += s;
        }
        System.out.println("Total: " + total);
    }
}

Iterating a Map's Entries

When iterating map entries, var spares you from writing the verbose Map.Entry type.

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        var ages = Map.of("Ann", 30, "Ben", 25);
        for (var entry : ages.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

Inferred Element Methods

Because the element type is known, you can call its methods inside the loop with full compile-time checking.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        var words = List.of("red", "green");
        for (var w : words) {
            System.out.println(w.toUpperCase() + " (" + w.length() + ")");
        }
    }
}

Nested Loops

You can use var in nested loops too, keeping each counter declaration short.

public class Main {
    public static void main(String[] args) {
        for (var i = 1; i <= 3; i++) {
            for (var j = 1; j <= 3; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println();
        }
    }
}

Counting Down

The inferred type follows the initializer, so a decreasing loop works the same way.

public class Main {
    public static void main(String[] args) {
        for (var n = 5; n >= 1; n--) {
            System.out.println(n);
        }
        System.out.println("Liftoff");
    }
}

var With long Counters

If you need a long counter, use a long literal in the initializer so var infers the wider type.

public class Main {
    public static void main(String[] args) {
        var sum = 0L;
        for (var i = 1L; i <= 1000000L; i++) {
            sum += i;
        }
        System.out.println(sum);
    }
}

Readability in Loops

Loops are one of the clearest places to use var because the type is obvious from the collection or initializer. The code stays concise and safe.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        var temps = List.of(20, 22, 19, 25);
        var max = Integer.MIN_VALUE;
        for (var t : temps) {
            if (t > max) max = t;
        }
        System.out.println("Max: " + max);
    }
}

Index and Value Together

You can combine a classic indexed loop with var to read both position and value from a list.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        var items = List.of("a", "b", "c");
        for (var i = 0; i < items.size(); i++) {
            System.out.println(i + ": " + items.get(i));
        }
    }
}

Quick Check

In for (var name : names) where names is a List<String>, what type is name?

Recap

You learned var in loops:

  • Classic loops: infers the counter type from its initializer
  • for-each: infers the element type from the collection or array
  • Spares verbose types like Map.Entry
  • Use long literals (e.g. 0L) for long counters
  • Loops are an ideal place for var

Frequently asked questions

Is the “var in for Loops” lesson free?

Yes — the full text of “var in for Loops” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “var in for Loops”?

Infer loop variable types. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “var in for Loops” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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