Java 10 - Local Variable Type Inference


JEP 286 − Local Variable Type Inference

Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable using var and without specifying the type of it. The compiler infers the type of the variable using the value provided. This type inference is restricted to local variables.

Old way of declaring local variable.

String name = "Welcome to tutorialspoint.com";

New Way of declaring local variable.

var name = "Welcome to tutorialspoint.com";

Now compiler infers the type of name variable as String by inspecting the value provided.

Noteworthy points

  • No type inference in case of member variable, method parameters, return values.

  • Local variable should be initialized at time of declaration otherwise compiler will not be infer and will throw error.

  • Local variable inference is available inside initialization block of loop statements.

  • No runtime overhead. As compiler infers the type based on value provided, there is no performance loss.

  • No dynamic type change. Once type of local variable is inferred it cannot be changed.

  • Complex boilerplate code can be reduced using local variable type inference.

Map<Integer, String> mapNames = new HashMap<>();

var mapNames1 = new HashMap<Integer, String>();

Example

Following Program shows the use of Local Variable Type Inference in JAVA 10.

import java.util.List;

public class Tester {
   public static void main(String[] args) {
      var names = List.of("Julie", "Robert", "Chris", "Joseph"); 
      for (var name : names) {
         System.out.println(name);
      }
      System.out.println("");
      for (var i = 0; i < names.size(); i++) {
         System.out.println(names.get(i));
      }
   }
}

Output

It will print the following output.

Julie
Robert
Chris
Joseph

Julie
Robert
Chris
Joseph
Advertisements