CKTIS / Java
var — local variable type inference
`var` lets the compiler infer a local variable's type from its initializer. The type remains static and does not change with later assignments. In Java SE 21, `var` is a contextual keyword, not a type name.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
var name = expression;
final var name = expression;
for (var element : iterable) { ... }
(var x, var y) -> expressionIn Java SE 21, var is a contextual keyword, not a universal type or a form of dynamic typing. In a local declaration, the compiler determines the type from the initializer expression: var count = 3; produces type int. Later assignments must be compatible with that type. var alone does not mean final; final var prevents reassignment.
It can be used in local declarations in blocks, basic for headers and try-with-resources headers, and for the iteration variable in an enhanced for loop. It cannot replace a field type, method return type, or method or constructor parameter type. In an enhanced for loop, the type comes from the iterated source rather than an explicit initializer.
An ordinary declaration with var must declare one variable with an initializer. var x;, var x = null;, var a = 1, b = 2; and var a = {1, 2}; are invalid; an array can be written as var a = new int[]{1, 2};. You cannot add [] after the variable name or reference the variable in its own initializer. A bare lambda or method reference without a target type is also insufficient as an initializer.
A separate use is lambda parameters: (var x, var y) -> x + y. Their types come from the target functional interface. All parameters must use var; it cannot be mixed with omitted or explicit types. In the example, count has type int and label has type String; the program should print count=5.
Examples
public class VarExample {
public static void main(String[] args) {
var count = 3;
count += 2;
final var label = "count";
System.out.println(label + "=" + count);
}
}Result
count=5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.