DEV Community

Deepikandas
Deepikandas

Posted on

#10 Known is a drop! Var Inference Type in JAVA

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:

Top comments (0)