var Keyword (Java 10+)
Local variable type inference: what the compiler infers, where var is allowed and where it is not.
#Introduction
The var keyword was introduced in Java 10 to reduce boilerplate code. Many developers misunderstand var. One of the biggest misconceptions is:
"var makes Java dynamically typed."This is false. Java is still a statically typed language. The compiler simply infers the type from the assigned value.
var name = "John";The compiler internally treats it as:
String name = "John";The type is decided at compile time, not runtime.
#What is Type Inference?
Type inference means the compiler automatically determines the variable's type.
var age = 25; // compiler infers: int age = 25;
var salary = 55000.50; // compiler infers: double salary = 55000.50;#Why was var Introduced?
Before Java 10:
HashMap<String, List<Employee>> employeeMap =
new HashMap<>();Very long. Using var:
var employeeMap =
new HashMap<String, List<Employee>>();Cleaner and easier to read.
#Examples
| You write | Compiler sees |
|---|---|
var x = 10; | int x = 10; |
var price = 250.75; | double price = 250.75; |
var language = "Java"; | String language = "Java"; |
var active = true; | boolean active = true; |
var list = new ArrayList<String>(); | ArrayList<String> list = new ArrayList<>(); |
var employees = new HashMap<Integer, Employee>(); | HashMap<Integer, Employee> employees = new HashMap<>(); |
#How the Compiler Infers Type
var number = 100;#Java is Still Statically Typed
var number = 10;
number = 20; // Validvar number = 10;
number = "Java"; // Compilation ErrorReason: the compiler already determined that number is an int.
#var with Objects
var employee = new Employee();
// compiler: Employee employee = new Employee();#var with Streams
Without var:
Stream<String> stream = list.stream();Using var:
var stream = list.stream();Cleaner code.
#var with Lambda Expressions
Java 11 introduced support for var in lambda parameters.
(var name) -> name.toUpperCase()More useful when annotations are needed:
(@NotNull var name) -> name.toUpperCase();#Where Can var Be Used?
Local Variables ✅
var x = 10;Inside Loops ✅
for (var i = 0; i < 5; i++) {
System.out.println(i);
}Enhanced for Loop ✅
for (var employee : employees) {
}Try-with-Resources ✅
try (var reader =
new BufferedReader(new FileReader("test.txt"))) {
}#Where var Cannot Be Used?
Instance Variables ❌
class Employee {
var id = 10; // Compilation Error
}Static Variables ❌
static var count = 0; // Compilation ErrorMethod Parameters ❌
public void display(var name) { // Compilation Error
}Method Return Type ❌
public var getName() { // Compilation Error
}Without Initialization ❌
var number; // Compilation ErrorThe compiler cannot infer the type.
Multiple Variables ❌
var a = 10, b = 20; // Compilation ErrorDeclare them separately.
Null Assignment ❌
var obj = null; // Compilation ErrorThe compiler cannot determine the type. Correct:
Object obj = null;#Type Inference Examples
| Declaration | Inferred type |
|---|---|
var number = 10; | int |
var number = 10L; | long |
var number = 10.5; | double |
var ch = 'A'; | char |
var flag = false; | boolean |
#var with Generics
Without var:
Map<String, List<Employee>> employees =
new HashMap<>();Using var:
var employees =
new HashMap<String, List<Employee>>();Much easier to read.
#Readability
Good example — the type is obvious:
var employees = repository.findAll();Bad example — the reader has no idea what type result is:
var result = process(data);#Performance
#Reflection
var employee = new Employee();Reflection still reports Employee, because var exists only at compile time.
#Real Project Examples
// Spring Boot
var response = restTemplate.getForObject(...);
// Repository
var users = userRepository.findAll();
// Streams
var names = employees.stream();
// Complex generic types
var cache = new ConcurrentHashMap<String, List<Employee>>();#Advantages
- Less boilerplate
- Better readability for obvious types
- Easier refactoring
- Cleaner generic declarations
- Modern coding style
#Disadvantages
- Can reduce readability if the type isn't obvious.
- Beginners may not understand the inferred type.
- Cannot be used everywhere.
#Interview Questions
Q1What is var?
A keyword for local variable type inference.
Q2Which Java version introduced var?
Java 10.
Q3Is Java dynamically typed because of var?
No. Java remains statically typed.
Q4Can var be used for fields?
No. Only local variables.
Q5Can var be assigned null?
No. The compiler cannot infer the type.
Q6Can we change the type later?
No.
var x = 10;
x = "Java"; // Compilation ErrorQ7Does var affect JVM performance?
No. It is purely a compile-time feature.
Q8Can var be used in loops?
Yes — both traditional and enhanced for loops.
Q9Can var be used in lambda expressions?
Yes, from Java 11.
Q10When should we use var?
Use it when the type is obvious from the right-hand side and it improves readability.
#Common Mistakes
- Assuming
varmeans dynamic typing. - Using
varwhere the inferred type is unclear. - Declaring
varwithout initialization. - Trying to use
varfor class fields. - Assigning
nullto avarvariable.
#Best Practices
- Use
varonly for local variables. - Use
varwhen the inferred type is obvious. - Avoid
varif it hurts readability. - Continue using explicit types in public APIs.
- Prefer clarity over shorter code.
#Quick Revision
#Interview Cheat Sheet
| Question | Answer |
|---|---|
| Java Version | Java 10 |
| Dynamic Typing? | No |
| Runtime Performance? | No Difference |
| Fields Supported? | No |
| Method Parameters? | No |
| Local Variables? | Yes |
| Loops? | Yes |
| Lambda Parameters? | Yes (Java 11+) |
#Chapter Summary
After completing this chapter, you should be able to:
- Explain what
varis and how type inference works. - Understand where
varcan and cannot be used. - Differentiate between compile-time type inference and dynamic typing.
- Use
vareffectively in Spring Boot and enterprise applications. - Apply best practices to improve readability while avoiding common mistakes.
- Confidently answer Java 10+ interview questions related to
var.