In Latest version of Java programming language var keyword is widely used because any assigned value to var variable automatically scans the data type and then able to operate. The best practice of var keyword in java is that where inferred type is possible otherwise it would be bad practice.
Table of Contents
What is var in Java?
The “var” is introduced in Java 10. “var” is not a keyword, its a reserved word. As in most of the programming languages like Javascript, Go, C#, Kotlin, Swift already available. The main reason to introduce var keyword in java is Type Inference. This feature is called Local Type Inference Type (LVTI).
Type Inference means automatically detect the type of an expression. By using var keyword in java looks like very cleaner and also more readable.
Can a var be null?
In Short, var in java cannot be null. Because null is a literal which doesn’t have any data type or return type. We can see in the below java program.
For Eg:
package com.programming.seekho;
public class VarKeywordWithNull {
public static void main(String[] args) {
String name = null;
//var cannot be used as without initialization
var n ;
//var cannot be used as null
var names = null;
System.out.println(name);
}
}
Also, if we talk about var initialization, var cannot be declared without value. As we can see in the above program.
With primitive data type, we can initialize a variable in static context without value but var variable cannot.
For eg:
int n; // We can write like this
var n; // We can’t write like this.

Which type of value can be assigned in var variable type in Java?
We can assign any type of value, but keep in mind “var” is reserved word. It is not any data type or return type. We can also write like
var var = “John”;
as shown in below example
package com.programming.seekho;
package com.programming.seekho;
public class VarKeywordDemo {
public static void main(String[] args) {
var bool = true;
var ch = 'c';
var num = 10;
var longNum = 20L;
var floatNum = 40f;
var doubleNum = 30.888d;
var name = "Rohan";
var var = "John";
System.out.println("bool : "+bool);
System.out.println("ch : "+ch);
System.out.println("num : "+num);
System.out.println("longNum : "+longNum);
System.out.println("floatNum : "+floatNum);
System.out.println("doubleNum : "+doubleNum);
System.out.println("name : "+name);
System.out.println("var : "+var);
}
}
Output
bool : true
ch : c
num : 10
longNum : 20
floatNum : 40.0
doubleNum : 30.888
name : Rohan
var : John
With the above program, we can say that var variable can assign any type of value which supports type inference. As we can see in the program in var variable boolean, int, float, double, String type easily assigned.
Java var keyword best practice
You can use var in various scenario which is in the following:
- When type is clear from context. It makes code more cleaner and readable.
- Java var should not be used more with primitive types that reduces the readability.
- Should be used descriptive variable name because it can reduce the loss of data.
- Should be avoid to use var with complex expression because it might not be consistent in result
We are providing some examples
Employee.java
package com.programming.seekho;
public class Employee {
private Integer id;
private String name;
private String email;
private Integer phone;
private Integer age;
private Integer salary;
public Employee(Integer id, String name, String email, Integer phone, Integer age, Integer salary) {
this.id = id;
this.name = name;
this.email = email;
this.phone = phone;
this.age = age;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getPhone() {
return phone;
}
public void setPhone(Integer phone) {
this.phone = phone;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return id + "\t" + name + "\t" + email + "\t" + phone + "\t" + age + "\t" + salary;
}
}
EmployeeUtility.java
package com.programming.seekho;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class EmployeeUtility {
//Creating list of employees
List<Employee> list = Arrays.asList(new Employee(1, "rajesh", "rajesh@gmail.com", 1111111, 18, 20000),
new Employee(2, "ramesh", "ramesh@gmail.com", 2222222, 20, 40000),
new Employee(3, "suraj", "suraj@gmail.com", 3333333, 40, 50000),
new Employee(4, "anil", "anil@gmail.com", 4444444, 30, 30000),
new Employee(5, "john", "john@gmail.com", 5555555, 50, 60000));
//Get employee names in capital letters
public List<String> getAllEmployeeInCapitalLetters(){
return list.stream().map(e -> e.getName().toUpperCase()).toList();
}
//Get Employee with maximum salary
public Employee getMaxSalaryEmployee(){
return list.stream().collect(Collectors.maxBy(Comparator.comparing(s -> s.getSalary()))).get();
}
//Get Employees in descending order
public List<Employee> getEmployeeInDescOrder(){
return list.stream().sorted(Comparator.comparing(Employee::getName).reversed()).toList();
}
}
VarKeywordWithCustomObject .java
package com.programming.seekho;
public class VarKeywordWithCustomObject {
public static void main(String[] args) {
EmployeeUtility empUtil = new EmployeeUtility();
//Employee names in capital letters
System.out.println("Employees name in capital letters");
var namesInUpperCase = empUtil.getAllEmployeeInCapitalLetters();
namesInUpperCase.forEach(System.out::println);
//Employee with maximum salary
System.out.println("Employee with maximum salary");
var employeeWithMaxSalary = empUtil.getMaxSalaryEmployee();
System.out.println(employeeWithMaxSalary);
//Employee in descending order
System.out.println("Employee in descending order");
var employeeInDescOrder = empUtil.getEmployeeInDescOrder();
employeeInDescOrder.forEach(System.out::println);
}
}
Output
Employees name in capital letters
RAJESH
RAMESH
SURAJ
ANIL
JOHN
Employee with maximum salary
5 john john@gmail.com 5555555 50 60000
Employee in descending order
3 suraj suraj@gmail.com 3333333 40 50000
2 ramesh ramesh@gmail.com 2222222 20 40000
1 rajesh rajesh@gmail.com 1111111 18 20000
5 john john@gmail.com 5555555 50 60000
4 anil anil@gmail.com 4444444 30 30000
In the above example, We have made Employee class in which some properties are declared. In EmployeeUtility class created some method for doing some operation with lambda expression and stream. And at last, VarKeywordWithCustomObject class in which I want to fetch data in this class from utility class methods and assigning to var keyword and we have clearly seen that methods result easily assigned to var.
So from above program we have learnt that we can use var with custom object also.
How can we use java var with collections?
We can use var with collections also. So here we have created the objects of some collections like Arraylist, Set and Map and assigned to var keyword.
package com.programming.seekho;
import java.util.*;
public class VarKeywordWithCollections {
public static void main(String[] args) {
//ArrayList<String> names = new ArrayList<>();
var names = new ArrayList<>();
names.add("Ramesh");
names.add("John");
names.add("Doe");
names.add("Brian");
System.out.println(names);
var list = Arrays.asList("Ramesh","Kumar","Sunny", "john");
System.out.println(list);
var set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
System.out.println(set);
var map = new HashMap<>();
map.put(10,"Raju");
map.put(20,"Mukesh");
map.put(30,"Kamla");
map.put(40,"Kamlesh");
System.out.println(map);
}
}
Output
[Ramesh, John, Doe, Brian]
[Ramesh, Kumar, Sunny, john]
[1, 2, 3, 4]
{20=Mukesh, 40=Kamlesh, 10=Raju, 30=Kamla}
How can we use java var with Lambda Expression?
The var cannot be used with lambda expression. In below example, Predicate is a functional interface which know predicate has boolean valued function so with predicate we can write lambda exression but var is not a functional interface so it cannot be use with lambda expression.
Please keep in mind that Lambda expression always used with Functional lnterface. So var is not used with lambda expressions.
package com.programming.seekho;
import java.util.function.Predicate;
public class VarKeywordWithLambdaExp {
public static void main(String[] args) {
Predicate<Integer> evenNumber = a -> a % 2 == 0;
System.out.println(evenNumber.test(10));
// var cannot be used with lambda expression
// var evenNumber1 = a -> a % 2 == 0;
// System.out.println(evenNumber1);
}
}
Can we use var as generic type?
No we cannot use Java var as generic type nor with generic type. In below example we can see that both statement 1 and statement 2 is not valid.
//var can not be used as generic type
var<String> words1 = Arrays.asList("Programming", "Seekho", "Blog"); //stmt 1
System.out.println(words1);
//var can not be used with generic type
var<var> words2 = Arrays.asList("Programming", "Seekho", "Blog"); //stmt 2
System.out.println(words2);
Can we use Java var as instance variable?
No, Java var cannot be used as instance variable at class level but we can use in method as shown in below examples. In main method we can declare var variable locally.
package com.programming.seekho;
public class VarKeywordAsInstanceVariable {
//var cannot be used as instance variable at class level
//var n = 20;
public static void main(String[] args) {
var num = 21;
System.out.println(num);
}
}
How can we use java var with Stream API?
The Java var can be used with Stream API also as shown in below example.
package com.programming.seekho;
import java.util.Arrays;
import java.util.List;
public class VarKeywordWithStreamAPI {
public static void main(String[] args) {
List<String> list = Arrays.asList("Anamika", "Anil", "John", "Bhimraj");
var sortedName = list.stream().sorted().toList();
sortedName.forEach(System.out::println);
}
}
Output
Anamika
Anil
Bhimraj
John
Conclusion
In this article we have learnt concept of var which is introduced in Java 10. How var keyword actually work, where to use and how to use. I hope you will like this article.
Thanks!
1 thought on “Java var keyword best practice”