Java var Keyword
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.
Contents
Initializing Local Variables
1. Suppose we have a list of string.
List<String> strList = List.of("A", "B", "C");
var
keyword, we can write it as following.
var strList = List.of("A", "B", "C"); strList.forEach(s -> System.out.println(s));
2. Find the example for list of integer.
List<Integer> list = List.of(10, 20, 30);
var
:
var list = List.of(10, 20, 30);
City
, as following.
List<City> list = new ArrayList<>();
var
:
var list = new ArrayList<City>();
Map
initialization using generics.
Map<Integer, City> map = new HashMap<>();
var
:
var map = new HashMap<Integer, City>();
Map
of List
without var
:
Map<Integer, List<City>> map = new HashMap<>();
var
:
var map = new HashMap<Integer, List<City>>();
Map
of Map
is initialized as following.
Map<Integer, Map<String, City>> map = new HashMap<>();
var
keyword.
var map = new HashMap<Integer, Map<String, City>>();
City
.
City city = new City();
var
:
var city = new City();
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)); }
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));
var
in lambda expression is optional.
2.
Predicate<Integer> isEven = (var num) -> num % 2 == 0; System.out.println(isEven.test(12)); //true
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 usevar
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(); }
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 usevar
keyword to assign anonymous class and use it.
Find the anonymous class.
Object myTeam = new Object() { String name = "Java Team"; int noOfEmp = 10; };
System.out.println("name = " + myTeam.name + ", No of Emp = " + myTeam.noOfEmp); //Compile error
var
to assign the anonymous class.
var myTeam = new Object() { String name = "Java Team"; int noOfEmp = 10; };
myTeam.name
and myTeam.noOfEmp
fields with no compile error.
Limitations
1. Thevar
keyword is used only for local variables. We cannot use it with fields and method signature.
public String getUserData(var list) { } //Compile error
var num; //Compile error
var ob = null; //Compile error
var
are not allowed.
public class Test { private var list = new ArrayList<String>(); //Compile error }
References
Local Variable Type InferenceJava 10 Local Variable Type Inference
JDK 11 Release Notes