Java has finally introduced “var” as reserved type name with jdk10.
Till jdk9, we had to declare the Type explicitly like below code snippet:
String name = "Name"; int num = 5;
How ever with jdk10, explicit Type declaration is not required, we can use “var” instead and jdk will infer to proper type base on the assigned value, as shown below:
var name = "Kusum"; // "name" variable is assign the value Kusum // so, the compiler will treat the variable as String. var number = 5; // "number" variable is assigned the value 5 // so, the compiler will treat the variable as Integer.
var can be used in following scenario:
1) Local variable
var name = "Kusum";
2) for loop(Enhanced and traditional)
List<String> list = List.of("a", "b", "c"); for(var str : list) { System.out.print(str); }
3) Non-denotable type: These type exist within program, but there is no explicit name for those type. Anonymous classes are one of the Non – denoatbale type.
When we add a field to a anonymous class, there is no way to access the field outside the that class
Object info = new Object() { String name = "kusum"; }; System.out.print(info.name);
The above code will not work, as there is no field named “name” in Object class and it will throw an exception.
We can modify the above code to use “var”, and then we will be able to access the name property:
var info = new Object() { String name = "kusum"; }; System.out.print(info.name);
The above code work because, now the type of info variable is of the anonymous class we created.
Var can not be used for following:
- Class variable/fields: Class variable can be created without assigning any value to it and the compiler will assign the default value of the type to the variable. But if use “var” as type and does not assign any value, it will not compile.
- return type of method declaration: A method will not be able to decide the return type by itself.
- type of parameter: Method parameter can not define what type to expect so it will create ambiguity
- with null assignment to local variable: There can be multiple object which can be assigned as null, so it will create ambiguity.
- with lambda assignment: allowed from jdk11
var with Generics
List<String> list1 = new ArrayList<>(); var list2 = new ArrayList<>(); var list3 = new ArrayList<String>();
All above three lists are different.
- list1 has reference type List of String and holds the object of ArrayList of String.
- list2 has reference type var, so it will become ArrayList, but as no Type is mentioned, it will be a ArrayList of Object type.
- list3 will be ArrayList of String.
As it is reserved type name and not a keyword, var can be used as variable name, but it is not recommended.