The var keyword can only be used for local variables inside methods, constructors, or initializer blocks. It can’t be used for fields or parameters. Additionally, the variable must be initialized immediately so the compiler can determine its type—null alone is not sufficient.
public class VarExample {
// ❌ Not allowed: var cannot be used for fields
// var field = 10;
public static void main(String[] args) {
// ✅ Allowed: local variable with initializer
var message = "Hello, var!";
System.out.println(message);
// ❌ Not allowed: var without initializer
// var number; // Error: cannot infer type
// ❌ Not allowed: var with null only
// var data = null; // Error: null has no type
}
// ❌ Not allowed: var as method parameter
// public void greet(var name) { }
// ✅ Allowed: inside initializer block
{
var count = 5;
System.out.println("Count: " + count);
}
}