Local Variable Type Inference or LVTI in Java 10


Type inference in Java refers to the automatic detection of the variable’s datatype. This automatic detection usually happens at compile time. It is a feature of Java 10 and it allows the developer to skip declaring the type that is associated with the local variables. Local variables are those which are defined inside a method, initialization block, in for-loops, etc. The type would be usually identified by JDK.

Upto Java 9, the following syntax was used to define local variable of a class type −

class_name variable_name = new class_name(Arguments);

This way, the type of the object would be specified on the right hand side of the declaration.

Instead, LVTI or local variable type inference was introduced in Java 10, which could be used to declare local variables, without specifying the datatype of the variable. The keyword ‘var’ could be put before declaring local variables.

Following is an example −

Example

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String ap[]) {
      List<Map> my_data = new ArrayList<>();
   }
}

The above code can be re-written as −

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String ap[]) {
      var my_data = new ArrayList<>();
   }
}

Below is a demonstration while using LVTI to iterate through a ‘for’ loop −

public class Demo {
   public static void main(String a[]) {
      int[] my_arr = new int[5];
      my_arr = { 56, 78, 90, 32, 12 } ;
      for (var x : my_arr)
         System.out.println(x + "
");    } }

Output

56
78
90
32
12

A class named Demo contains the main function. An integer array is defined, and elements are put in the array. To iterate through the elements in the array, the ‘var’ keyword is used, and the elements are printed on the screen.

Updated on: 14-Sep-2020

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements