Monday, August 13, 2018

Learn Java 10 Local variables Type Inference tutorials with examples

In this tutorial, We are going to learn the Java 10 feature -  Local variables Type Inference.JDK Enhancement Proposal(JEP) 286 is a new feature in Java 10

Local variable type inference introduction

Java 10 Local variable type inference examples
type inference is automatic detection of a data type by the compiler based on the initialized value. With Java 10, it was introduced for local variables. This feature is already there in other languages like Scala, javascript, and c#. Let us see how this works with previous Java versions. Normally local Variables will be declared as follows, in the following example, created an ArrayList with holding strings in Java 5 and 6 versions.
List<string> lists=new ArrayList<string>();
There are two parts here, Left-hand side and right-hand side of the equal operator
The left-hand side is a variable declaration, with a data type that variable holds Right-hand side is initialized, Variable is initialized with a possible data type that holds. 

This article, we are going to discuss how we can short the local variable declaration.

 In Java 7, Diamond operators introduced, Allows to have empty brackets without type and variables were declared as below Before Java 7, ArrayList of string can be declared as follows
List<string> lists=new ArrayList<string>();
with Java 7, using Diamond operators, Reduced the code in such way that right-hand side is initialized without data type, and data type is inferred from the left-hand side.
List<String> lists=new ArrayList<>();
with Java 10, this simplified and reduced code, as well as type safety, still works. we can rewrite same as below
var lists=new ArrayList<String>();
The compiler assumes that left-hand side type is inferred as type from the right-hand side, if no type in the right-hand side, It will treat as type as Object.

How compiler interprets var types?

whenever local type variable encountered, first it checks the right-hand side of an equal symbol ie initializer, find out the type of the initializer and assign this type to a variable.

var Examples with usages

In this below section, usage of var with examples are posted.

Basic Type inference example

In the below example local string is declared and initialized with string constant literal value. Another local variable is declared and used to store the result of lowercase of a string. Type is not declared. The compiler automatically inferred the type from its value.
public class LocalVariableTypeInferenceHelloWorld {
 public static void main(String[] args) {
  var str = "THIS IS STRING"; // equals to String str= "THIS IS STRING";
  var lowerCaseString = str.toLowerCase(); // equals to String lowerCaseString = str.toLowerCase();
  System.out.println(lowerCaseString);
  System.out.println(lowerCaseString.getClass().getTypeName());
 }
}
and output is
this is string
java.lang.String

Type safety with var example 

 In the below example, created local String variable. assigned the same local variable with an integer. This gives compilation error
var str = "test string"; // equals to String str= "test string";
str=10;
The compiler still works with type safety Index.

For Loop local variable type inference example 

Declared index variables in for loop as like below.
 for (var i = 1; i <= 10; i++) {
            var temp= i* 2; // equals to Integer temp=i* 2;
            System.out.println(temp);
        }
        

For each local variable type inference example

local variables can be inferred with var reserved word as like below Declared variable for iteration during for each iteration
import java.util.ArrayList;
public class ForEachVarDemo {
 public static void main(String[] args) {
  var list = new ArrayList<String>();
  list.add("abc");
  list.add("def");
  list.add("ggg");
  for (var str : list) {
   var upperString = str.toUpperCase(); // equal to String upperString = str.toUpperCase();
   System.out.println(upperString);
  }
 }
}

return value from and in Method

 In a method, declared a local variable and returned to the caller. And also returned value is stored in another local variable.
public class MethodLocalVarDemo {
 public static void main(String[] args) {
  var number1 = 30;
  var number2 = 50;
  var output = sum(number1, number2);
  System.out.println(output);
 }
 private static Integer sum(Integer number1, Integer number2) {
  var result = number1 + number2;
  return result;
 }
}

local variable for storing Ternary Operator result

local variables are stored for the result of ternary operator evaluation, in the below example, the result is inferred as String
 var result = true? "true": "false";
System.out.println(result); 

Declare a local variable for Streams

var is used to assign not only data types but also inferring streams. here is below example var stream example.
var list = new ArrayList<String>();
  list.add("abc");
  list.add("def");
  list.add("ggg");
  var stream = list.stream();
  stream.forEach((string) -> {
   System.out.println(string);
  });

Compilation Errors

Local variables also have a lot of limitations and restrictions on the usage of this. The below cases all gives compilation errors.

No Local variable without an initializer

 var str;
Here local variable is declared but not initialized, it gives compilation error like 'Cannot use 'var' on a variable without initializer'.

No variable initialized with a null value

var str=null;
if var variable initialized with a null value, Compiler gives error - Cannot infer type for local variable initialized to 'null'.

No Multiple or compound variables declaration

multiple local variables declarations are not allowed
var m=5,n=2,p=3;  // not allowed
int m=5,n=2,p=3;  //  allowed
if we declared multiple local variables, It gives var' is not allowed in a compound declaration'.

No Local var array initializer

 An array declared like below not allowed for local variables.
var arrayDemo = { 61 , 14 };
the above line of code gives error Array initializer needs an explicit target-type

Not class instance variables

instance variables or class variables declared with local variables are not allowed.
public class ClassLocalDemo {
 var memberVariable=10;
 public static void main(String[] args) {
 }
}

No Method arguments/parameters

local variables are not declared in the method signature.
public class ClassLocalDemo {
 public static void main(String[] args) {
 }
 public static void method(var parame) {
 }
}

No var in Method return type 

method return type should not be var word and throws a compilation error
public static var method() {
 }

No var declaration in a catch block 

var is not allowed catch block as like below
try {
   // code
   } catch (var e) {
       }

Lambda expression needs an explicit target-type

 the below lambda expression var initialization throws an error. Like the diamond operator, right-hand side, Need target data type to work
var helloString = () -> "teststring";  

Constructor arguments not allowed 

var should not be used with constructor arguments as like below
public class Demo {
 public Demo(var a) {
  
 }
}

Advantages 

  • boilerplate code
  • readability and less typing
Disadvantages
local variables declaration and diamond operator in Java 7 collides and confusion the developers.

var reserved word 
var is not a keyword and reserved word. We can not give the name of a variable and methods with the word 'var' those are not valid.

Please like or share it on facebook/twitter. and also subscribe to our blog for latest posts

Related article


EmoticonEmoticon