What is var?
var is a Java keyword that allows the compiler to automatically infer the type of a local variable from its initializer.
var is not a type itself.
Must be initialized at declaration
Only allowed for local variables inside methods, loops, etc.
Cannot infer null alone
Cannot be used for class fields, method parameters, or uninitialized variables
var is a keyword introduced in Java 10
Type Cast allowed in var?
When using var, numeric literals default to int; to infer long, short, or byte, you must provide an explicit suffix (L) or cast, because the compiler cannot guess which smaller type you intend.
Who Assigns Memory for var?
var is just a compiler feature
It does not create a new kind of variable.
The compiler infers the actual type of the variable from the initializer.
Memory allocation is still handled by the JVM based on the inferred type:

Using var in a pattern matching switch
You can declare the case variable with var, and the compiler will infer the type from the runtime object.
Example:
Object obj = "Hello";
switch (obj) {
case var s -> System.out.println(s); // ✅ var inferred as String
default -> System.out.println("Other");
}
Here, s will be inferred as String because obj is a String at runtime.
var is just a syntactic sugar for type inference.
Rules and behavior
var works only with pattern matching switch (Java 17+)
It can’t be used inside old-style switch statements
“If your switch returns a value, you can use var for the variable that receives it.”




Top comments (0)