Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Var keyword in Java

Tags:

java

var

With Java 10 or +, we can use var keyword for declaration. At initialization, a type is going to be inferred by the compiler.

What happens when the class I instantiate and assign to the variable declared with var, is the implementation of the interface? which type is it going to be inferred, Interface or the implementation?

like image 692
Harold Ibouanga Avatar asked Dec 22 '22 17:12

Harold Ibouanga


1 Answers

My 2 cents to correct the question and answers:

  1. The var is NOT a Java keyword. It's a reserved type name. It seems not a big difference but in fact, it IS:
var var = 0;

Here var is a variable name too, so the var can be used as a type name, but there is no restriction like for regular keyword (i.e. we can have a variable named var too).

  1. The actual type of the variable IS decided by the Java compiler on the line where the variable declared, at compile-time, but the type is NOT actually the exact implementation you use on the right side of the expression. See this code:
var i = true ? Integer.valueOf(1) : "ABC";

The Java compiler needs to pick a type for variable i which will satisfy both branches. It could be a) Object, b) Serializable, c) Comparable, or combinatioin, or all three. We don't care and don't know.

like image 50
Barat Sahdzijeu Avatar answered Jan 05 '23 17:01

Barat Sahdzijeu