Local Variable Type Interference – A Quick Look

May 09, 2022
xblog LocalVariable

Java local interference

JDK 10 introduced various new features, the most visible enhancement among them was the introduction of Java local inference of variables. It is a feature that allows Java developers to skip the type declaration associated with local variables. It is usually defined inside method definitions, initialization blocks, for-loops, and other blocks like if-else, and the type is inferred by the JDK. With Java local interference, the data type will, then, be decided by the compiler at compile-time, based on the data assigned to the variable.

Until Java 9, developers had to mention the type of the local variable explicitly and make sure that it is compatible with the value, it is initialized with.


See this simple line of code below:

var output_msg = "declaring a local variable in Java 9";

The data type of output_msg is not provided. Instead, it is marked as a var. Now the compiler will infer the type of output_msg from the type of the value assigned to it.

new java job roles

Here the data type of output_msg would be String.

Why was Java local interference needed?

The following two examples demonstrate the Java 9 approach that will be later used to explain the need for this feature:

1. import java.util.ArrayList;
2. import java.util.List;
3. class class01 {
4.     public static void main(String a[])
5.      {
6.         List<Map> myData = new ArrayList<>();
7.      }
8.  }
10. class class02 {
11.     public static void main(String a[])
12.     {
13.         String str = " Hello World";
14.     }
15.  }

It works just fine, right? and this is how things have been since the beginning but there is one slight issue that had some room for improvement. When you create an object, it is very obvious that if the type of the object is mentioned at the right side of the expression, so mentioning the same thing before the name of the variable makes it redundant.

Along with this, you can observe it from the second example, you can see that it is very clear that after the ‘=’ sign, it is a string being enclosed in double inverted commas. Therefore, removing the datatype can eliminate the redundancy and make variable declaration shorter, and more convenient.

How to declare variables using Java local interference?

As mentioned in the very first example, it is quite simple. Instead of mentioning the variable datatype on the leftmost side, before the variable, you can use the keyword ‘var’. see this comparison below,

1. // Normal variable declaration
2. import java.util.ArrayList;
3. import java.util.List;
4. class class01 {
5.     public static void main(String ap[])
6.      {
7.         List<Map> data = new ArrayList<>();
8.      }
9.  }


Can be written as:

1. // Java code for local variable
2. import java.util.ArrayList;
3. import java.util.List;
4. class class01 {
5.     public static void main(String ap[])
6.     {
7.         var data = new ArrayList<>();
8.     }
9.  }

Use cases of Java local interference for variable declaration

Following are the possible scenarios where it is permitted to use Java local interference:

· Inside a static/instance initialization block

1. class example01 {
2.     static
3.     {
4.         var x = " Java local interference ";
5.         System.out.println(x)'
6.     }
9.     public static void main(String[] ax)
10.     {
11.     }
12. }

The output will be:

     Java local interference

· For declaring a simple local variable

1.  class example02 {
2.     public static void main(String a[])
3.       {
4.         var x = " Java local interference ";
5.         System.out.println(x)
6.       }
7.   }

      The output will be:

   Java local interference

· As an iteration variable in a loop

1.  // with an enhanced for-loop
3.  class example03a {
4.      public static void main(String a[])
5.      {
6.          int[] myArr = new int[5];
7.          arr = { 1, 2, 3, 4, 5};
8.          for (var i : myArr)
9.              System.out.println(i + ", ");
10.     }
11. }
14. // OR with a simple for-loop
15. class examplw03b {
16.     public static void main(String a[])
17.     {
18.         int[] myArr = new int[5];
19.         arr = { 1, 2, 3, 4, 5 };
20.         for (var i = 0; i < 5; i++)
21.             System.out.println(myArr[i] + ", ");
22.     }
23. }

The output will be:

1, 2, 3, 4, 5,

· As a return value in a method or from another method

1. class example04 {
2.     int func01()
3.     {
4.         var num = 100;
5.         return num;
6.     }
7.     public static void main(String a[])
8.     {
9.         var num = new example04().func01();
10.        System.out.println(“The return value is”, num);
11.     }

The output will be:

The return value is 100

Illegal Use of Java local interference

Following are the certain cases where the declaration of local variables using Java local interference will result in an error :

· Using with class fields

1. class example01 {
2.     var x = 2; }

The error output on the screen:

Error: class variables can't be declared using 'var'. Datatype needs to be explicitly mentioned

· Cannot be used for uninitialized local variables

1. class example 2 {
2.     public static void main(String a[])
3.     {
4.         var x;
5.     }
6.  }

The output will be:

Error: cannot use 'var' on variable without initializer

· Cannot be used as a parameter or a return type for any methods

1. class example03 {
2.     public var showResult(var num)
3.     {
4.     }
5.  }

The output will be:

Error: can't use 'var' on method parameters
Error: Method return type can't be var

· Cannot be used with non-denotable types

If you attempt to use var with the anonymous class instance, it will output an unexpected result, for instance see this code demonstration:

1. public void VarInitWithAnonymous () {
2.     var obj01 = new Object() { };
3.     assertFalse(obj01.getClass().equals(Object.class));
4.  }

Now, if you try to assign another Object to obj01, it will result in a compilation error. This is because the inferred type of obj isn’t Object.

Obj01 = new Object();

This will be the output:

Error: Object cannot be converted to <anonymous Object>

· A variable cannot be initialized with ‘NULL’

1. class example04 {
2.     public static void main(String a[])
3.     {
4.         var i = NULL;
5.     }


Error: variable initializer is 'null'

Guidelines for Java local interference

It is to be noted that var is not a keyword. It is a reserved type name, just like float or int. This ensures backward compatibility for programs where you have used var  may be as a function or to name a variable

There is also no runtime overhead in using var. and it surely does not make Java a dynamically typed language. The type of the variable is still inferred at compile time and cannot be changed later.


In this article, the new Java 10 local variable type inference is demonstrated with several examples. It is a good improvement over the previous declaration method to remove redundancy and make your code shorter. Although you need to follow the guidelines and prevent using any illegal method to apply var.

new Java jobs



Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Candidate signup

Create a free profile and find your next great opportunity.


Employer signup

Sign up and find a perfect match for your team.


How it works

Xperti vets skilled professionals with its unique talent-matching process.


Join our community

Connect and engage with technology enthusiasts.