Var in Java - JDK10 - Techonica Tutorials - All you Need to Know

Breaking

JAVA TUTORIALS ARE LIVE NOW

Monday, 26 March 2018

Var in Java - JDK10

Local Variable Type Inference

Where to use var? Where not to use Var?
Java 10 var
Java is no more a strongly typed language. It now uses local variable type inference like any other popular languages Scala, C# etc. Java was nearly the only popular statically typed language that has not embraced local variable type inference and finally in Java 10 it has embraced it.

Lets get started with a detailed video tutorial.

Local Variable Type Inference

Type inference is the ability of the java compiler to look at each method invocation and corresponding declaration to determine the type of arguments.

In Java 10, for local variable declaration with initializers, enhanced forEach indexes and index variables in traditional for loops allow the reserved type name 'var' to be used.

Few Examples.
var str= "Hello World";
var i=5;
var list = new ArrayList<Integer>();
list.add(5);
var stream = list.stream();
var itr = list.iterator();

for(var x: list)
    System.out.println(x);

Local variable declarations that lack initializers, declare multiple variables, have extra array dimension brackets or reference the variable being initialized are not allowed.

Few Examples
int i=8,j=5;
var p=4,y=8;
// var is not allowed in a compound declaration
String s=null;
var str = null; 
// compiler cannot infer the variable type from null
int out;
var in; 
// var cannot be used since the variable is not initialised

No comments:

Post a Comment