DevNotes
Support
Core Java · Chapter 12

var Keyword (Java 10+)

Local variable type inference: what the compiler infers, where var is allowed and where it is not.

◷ 6 min read§ 25 sections? 11 interview questions{ } 32 code examples

#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.

Java
var name = "John";

The compiler internally treats it as:

Java
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.

Java
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:

Java
HashMap<String, List<Employee>> employeeMap =
        new HashMap<>();

Very long. Using var:

Java
var employeeMap =
        new HashMap<String, List<Employee>>();

Cleaner and easier to read.

#Examples

You writeCompiler 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

Java
var number = 100;
100
int literal
Variable type = int
Once inferred, the type can never change

#Java is Still Statically Typed

Java
var number = 10;
number = 20;       // Valid
Java
var number = 10;
number = "Java";   // Compilation Error

Reason: the compiler already determined that number is an int.

#var with Objects

Java
var employee = new Employee();
// compiler: Employee employee = new Employee();

#var with Streams

Without var:

Java
Stream<String> stream = list.stream();

Using var:

Java
var stream = list.stream();

Cleaner code.

#var with Lambda Expressions

Java 11 introduced support for var in lambda parameters.

Java
(var name) -> name.toUpperCase()

More useful when annotations are needed:

Java
(@NotNull var name) -> name.toUpperCase();

#Where Can var Be Used?

Local Variables ✅

Java
var x = 10;

Inside Loops ✅

Java
for (var i = 0; i < 5; i++) {
    System.out.println(i);
}

Enhanced for Loop ✅

Java
for (var employee : employees) {
}

Try-with-Resources ✅

Java
try (var reader =
        new BufferedReader(new FileReader("test.txt"))) {

}

#Where var Cannot Be Used?

Instance Variables ❌

Java
class Employee {
    var id = 10;   // Compilation Error
}

Static Variables ❌

Java
static var count = 0;   // Compilation Error

Method Parameters ❌

Java
public void display(var name) {   // Compilation Error
}

Method Return Type ❌

Java
public var getName() {   // Compilation Error
}

Without Initialization ❌

Java
var number;   // Compilation Error

The compiler cannot infer the type.

Multiple Variables ❌

Java
var a = 10, b = 20;   // Compilation Error

Declare them separately.

Null Assignment ❌

Java
var obj = null;   // Compilation Error

The compiler cannot determine the type. Correct:

Java
Object obj = null;

#Type Inference Examples

DeclarationInferred 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:

Java
Map<String, List<Employee>> employees =
        new HashMap<>();

Using var:

Java
var employees =
        new HashMap<String, List<Employee>>();

Much easier to read.

#Readability

Good example — the type is obvious:

Java
var employees = repository.findAll();

Bad example — the reader has no idea what type result is:

Java
var result = process(data);

#Performance

#Reflection

Java
var employee = new Employee();

Reflection still reports Employee, because var exists only at compile time.

#Real Project Examples

Java
// 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.

Java
var x = 10;
x = "Java";   // Compilation Error
Q7Does 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 var means dynamic typing.
  • Using var where the inferred type is unclear.
  • Declaring var without initialization.
  • Trying to use var for class fields.
  • Assigning null to a var variable.

#Best Practices

  • Use var only for local variables.
  • Use var when the inferred type is obvious.
  • Avoid var if it hurts readability.
  • Continue using explicit types in public APIs.
  • Prefer clarity over shorter code.

#Quick Revision

var
Compile-Time
Type Inference
Allowed
Local Variables
Loops
Try-With-Resources
Not allowed
Fields
Parameters
Return Types

#Interview Cheat Sheet

QuestionAnswer
Java VersionJava 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 var is and how type inference works.
  • Understand where var can and cannot be used.
  • Differentiate between compile-time type inference and dynamic typing.
  • Use var effectively 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.