Java var Keyword

By Arvind Rai, October 30, 2020
This page will walk through Java var keyword example. Java has introduced local variable type inference as var keyword in Java 10. With type inference, compiler can figure out the static types and we don’t have to write them. The var reduces the boilerplate of repeating code. Using var is not necessary, it depends on our team members whether they prefer it or not. Using var reduces the code maintenance but sometimes it increases the code readability time because it hides the type parameter.
In Java 11, we can use var with lambda expression. The local variable of lambda expression can optionally be declared with var keyword.
Here on this page we will discuss using var keyword in our code. We will also discuss its limitations.

Initializing Local Variables


1. Suppose we have a list of string.
List<String> strList = List.of("A", "B", "C"); 
Using var keyword, we can write it as following.
var strList = List.of("A", "B", "C");
strList.forEach(s -> System.out.println(s)); 
The output will be A, B and C.
2. Find the example for list of integer.
List<Integer> list = List.of(10, 20, 30); 
With var :
var list = List.of(10, 20, 30); 
3. Using generics we initialize list, suppose for class City, as following.
List<City> list = new ArrayList<>(); 
With var :
var list = new ArrayList<City>(); 
4. Find the Map initialization using generics.
Map<Integer, City> map = new HashMap<>(); 
With var :
var map = new HashMap<Integer, City>(); 
5. Map of List without var:
Map<Integer, List<City>> map = new HashMap<>(); 
With var :
var map = new HashMap<Integer, List<City>>(); 
6. A Map of Map is initialized as following.
Map<Integer, Map<String, City>> map = new HashMap<>(); 
The same can be achieved using var keyword.
var map = new HashMap<Integer, Map<String, City>>(); 
7. Find the object initialization of a class as City.
City city = new City(); 
With var :
var city = new City(); 
8. Find the example with Map.Entry
Without var keyword.
Map<String, List<String>> teamToEmp = new HashMap<>();
teamToEmp.put("Java", List.of("Mahesh", "Suresh"));
teamToEmp.put("Angular", List.of("Krishn", "Deepak"));
for (Map.Entry<String, List<String>> empInTeam : teamToEmp.entrySet()) {
  List<String> emps = empInTeam.getValue();
  emps.forEach(e -> System.out.println(e));
} 
Find the code with var keyword.
var teamToEmp = new HashMap<String, List<String>>();
teamToEmp.put("Java", List.of("Mahesh", "Suresh"));
teamToEmp.put("Angular", List.of("Krishn", "Deepak"));
for (var empInTeam : teamToEmp.entrySet()) {
  var emps = empInTeam.getValue();
  emps.forEach(e -> System.out.println(e));
} 

With Lambda Expression

Since Java 11, var keyword can also be used in lambda expression as local variable.
1.
Stream.of(2, 3, 4, 5).filter((var n) -> n % 2 == 0)
  .forEach((var e) -> System.out.println(e)); 
Using var in lambda expression is optional.
2.
Predicate<Integer> isEven = (var num) -> num % 2 == 0;
System.out.println(isEven.test(12)); //true 
3.
BiFunction<Integer, Integer, Integer> sum  = (var num1, var num2) -> num1 + num2;  
System.out.println(sum.apply(20, 15)); //35 

Note: We cannot mix 'var' and 'no var'.
(var x, y) -> x + y //invalid
(var x, int y) -> x + y //invalid 

With Try-With-Resources

Here we will use var with Try-With-Resources.
Without var, we write Try-With-Resources code as below.
Path path = Paths.get("D:/test/myfile.txt");
try (Stream<String> lines = Files.lines(path)) {
  lines.forEach(l -> System.out.println(l));
} catch (IOException e) {
  e.printStackTrace();
} 
With var :
Path path = Paths.get("D:/test/myfile.txt");
try (var lines = Files.lines(path)) {
  lines.forEach((var l) -> System.out.println(l));
} catch (IOException e) {
  e.printStackTrace();
} 

With Anonymous Class

In anonymous class we can add fields and methods but we will not be able to write its name. We can use var keyword to assign anonymous class and use it.
Find the anonymous class.
 Object myTeam = new Object() {
  String name = "Java Team";
  int noOfEmp = 10;
}; 
We cannot access fields of above anonymous class and below line will not compile.
System.out.println("name = " + myTeam.name + ", No of Emp = " + myTeam.noOfEmp); //Compile error 
Now use var to assign the anonymous class.
var myTeam = new Object() {
  String name = "Java Team";
  int noOfEmp = 10;
}; 
And then we can access myTeam.name and myTeam.noOfEmp fields with no compile error.

Limitations

1. The var keyword is used only for local variables. We cannot use it with fields and method signature.
public String getUserData(var list) { } //Compile error 
2. Local variable without initialization is not allowed.
var num; //Compile error 
3. Local variable cannot be initialized with null.
var ob = null; //Compile error 
4. Class level fields with var are not allowed.
public class Test {
  private var list = new ArrayList<String>();  //Compile error
} 

References

Local Variable Type Inference
Java 10 Local Variable Type Inference
JDK 11 Release Notes
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us