Java has been progressively working on reducing the verbosity from syntax. First it was Diamond operator, and now it is var
(local variable type – JEP 286) to declare variables in java. When you are using var
to declare the variable, basically, instead of declaring a variable type, it assumes its type from what it is being set to. e.g.
var str = "Hello world"; //or String str = "Hello world";
In above example, in first statement, you are setting a String
to variable str
so it is implicitly assumed to be of String
type. First statement is essentially equivalent to second statement in above example.
var
declaration and initialization at same time
When using var
, you must initialize the variable at same place. You cannot put declaration and initialization at different places. If you do not initialize the variable in place, then you will get compilation error – Cannot use 'var' on variable without initializer
.
var i; //Invalid Declaration - - Cannot use 'var' on variable without initializer var j = 10; //Valid Declaration System.out.println(i);
var
is not keyword
Though look like, var
is not a reserved java keyword. So you can create variables with name ‘var’ – It is allowed.
var var = 10; //Valid Declaration int var = 10; //Also valid Declaration
var
usage
Using var
is restricted to – local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.
Usage allowed as :
- Local variables with initializers
- Indexes in the enhanced for-loop
- Locals declared in a traditional for-loop
var blogName = "howtodoinjava.com"; for ( var object : dataList){ System.out.println( object ); } for ( var i = 0 ; i < dataList.size(); i++ ){ System.out.println( dataList.get(i) ); }
Usage NOT allowed as :
- Method parameters
- Constructor parameters
- Method return types
- Class fields
- Catch formals (or any other kind of variable declaration)
public class Application { //var firstName; //Not allowed as class fields //public Application(var param){ //Not allowed as parameter //} /*try{ } catch(var ex){ //Not allowed as catch formal }*/ /*public var demoMethod(){ //Not allowed in method return type return null; }*/ /*public Integer demoMethod2( var input ){ //Not allowed in method parameters return null; }*/ }
var
is not backward compatible
As this is new language feature, code written using var
will not be compiled in lower JDK versions (less then 10). So use this feature only when you are sure about it.
var
does not impact performance
Remember, in Java, the types are not inferred at runtime but at compile time. That means the resulting bytecode is the same as with explicit type declaration – it does include the information about the type. That means no extra processing at runtime.
Happy Learning !!
Leave a Reply