Java

var — Local Type Inference (Java 10+)

admin by @admin ADMIN
Jun 20, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`var` for local variables lets the compiler infer the type from the initializer. Reduces noise when the type is obvious from context — but you still get static typing.
Java
Raw
import java.util.*;

class Demo {
    void example() {
        var name = "Alice";                                  // String
        var n = 42;                                          // int
        var users = new HashMap<String, List<Integer>>();    // no diamond noise

        // The right-hand side dictates the type — both are correct
        Map<String, List<Integer>> longForm = new HashMap<>();
        var          shortForm = new HashMap<String, List<Integer>>();

        // In for-loops
        for (var entry : users.entrySet()) {                 // Map.Entry<String, List<Integer>>
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }

        // ✗ var is ONLY for local variables — not for fields, params, returns
        // ✗ var without initializer is a compile error
        // ✗ var = null is a compile error (no type to infer)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.