Java 10 LocalVariable Type-Inference


JDK 10 is type inference of local variables with initializers. This tutorial provides the details of LocalVariable Type-Inference with examples.

Java has now var style declarations. It allows you to declare a local variable without specifying its type.

var won’t work without the initializer:
var n; // error: cannot use 'var' on variable without initializer
Nor would it work if initialized with null:
var emptyList = null; // error: variable initializer is 'null'
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);
Application.java
var i;  //Invalid Declaration - - Cannot use 'var' on variable without initializer
         
var j = 10; //Valid Declaration
 
System.out.println(i); 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
Application.java
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) );





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition