After reading and talking about Java 10s new reserved type name var
(JEP 286: Local-Variable Type Inference), one question arose in the discussion.
When using it with literals like:
var number = 42;
is number
now an int
or an Integer
? If you just use it with comparison operators or as a parameter it usually doesn't matter thanks to autoboxing and -unboxing.
But due to Integer
s member functions it could matter.
So which type is created by var
, a primitive int
or class Integer
?
var
asks the compiler to infer the type of the variable from the type of the initializer, and the natural type of 42
is int
. So number
will be an int
. That is what the JLS example says:
var a = 1; // a has type 'int'
And I would be surprised if it worked any other way, when I write something like this, I definitely expect a primitive.
If you need a var
as boxed primitive, you could do:
var x = (Integer) 10; // x is now an Integer