Local Variable Type Inference (var) example

In this post under Java language, I will introduce you to Local Variable Type Inference (also called var variable) added in Java 10.

Before java 10, any variable declared should be accompained with the data type as shown below

	int sum;
	float salary;
	String name;

As shown in the above code, the “int” is the datatype and “sum” is the variable name, “float” is the datatype and “salary” is the variable name, and “String” is the datatype and “name” is the variable name.

From Java 10 onwards, we can declare a variable without a datatype.

If we don’t mention the datatype how the compiler will infer the type. To solve this problem it is required that when we declare the variable we also initialize it.

Compiler will infer the datatype from the initialized value.

We have modified the previous code as shown below.

	var sum = 10;
	var salary = 1000.00
	var name = "John Doe"

As you can see, we have replaced the “int” datatype with keyword “var” and then the usually variable name followed by the value. Similarly for “salary” and “name”.

So in our example, compiler will infer that the datatype is “int” for variable “sum” from the initialized value 10. Compiler will infer that the datatype for variable “salary” is float and the datatype for variable “name” is String.

Few things to remember when declaring the var variable.

  1. The var variable declaration is allowed only for local variable i.e., inside a method, constructor, static, and non-static block.
  2. You should initialize the variable when declaring it
  3. var is not allowed in multi variable declaration.
  4. The var variable declaration is not allowed for class fields (static or non-static), constructor parameters, method parameters.
  5. Once a var variable type is inferred by the compiler using the initialized value, you can change the var variable value to another value of same datatype and not of different datatype. In the above example we can change the value “sum” to 5 as that is also an int datatype but we cannot change the value of “sum” to 10.0 as that will try to change the datatype of “sum” from “int” to “float” which is not allowed.

In this way we can declare and use var variables.

Below is the complete code for your reference

Main class

package core.language;
public class LVTIExample1 {
{
var i = 10;
System.out.println("i: " + i);
}
static {
var j = 20;
System.out.println("j: " + j);
}
public LVTIExample1() {
var k = 30;
System.out.println("k: " + k);
}
public static void main(String[] args) {
var l = 40;
System.out.println("l: " + l);
LVTIExample1 l1 = new LVTIExample1();
l1.display();
}
public void display() {
var m = 50;
System.out.println("m: " + m);
}
}

Below is the output

Output

j: 20
l: 40
i: 10
k: 30
m: 50

Leave a Reply