Bits of Java – Episode 2: The var keyword

In this episode I would like to talk about the var keyword, which has been introduced in Java 10, and can be used instead of the type under certain conditions.

When declaring a variable in Java, we need to specify what type of variable we want, right?

Well, we could have also used var, instead of specifying the type:

This does not mean Java has become like JavaScript, for instance, where the type of var is inferred at runtime and a variable can change its type. What is happening here is that the compiler infers the type of our variables from the initialization. If it cannot infer the type, then we would get a compiler error. And once the type has been inferred, that variable cannot change it.

The fact that the type is inferred at compiling time is basically the reason why the use of var has some limitations.

  • You cannot declare and initialize the variable in two separate statements:

  • You cannot use var for instance and class variables, but only for local variables (indeed the use of var is also called local variable type inference):

  • You cannot declare var as parameter of a method or a constructor signature:

    but, pay attention:

  • You cannot use var in a multi variable declaration statement:

  • You cannot assign null to var when declaring it, without explicitly specifying its type:

  • After declaring a var, its value can change, but its type cannot:

Another interesting fact about var is that, being introduced only in Java 10, it is not included in the list of reserved keyword, namely it is allowed to call a variable var.

On the other hand, var is a reserved type name, so it cannot be used as name for a class, a type, an interface or an enum.

I hope you learned something new today! In the next post we will talk about one of the key features of Java: garbage collection.

By Ilenia Salvadori