Java has always made you say things twice:
Map<String, List<Integer>> scores = new HashMap<String, List<Integer>>();
You already told the compiler the type on the right. Why repeat it on the left? Since Java 10 (JEP 286), you don’t have to:
var scores = new HashMap<String, List<Integer>>();
This is called local variable type inference. It’s been in the language since 2018, and it’s a normal part of everyday Java 21 code. Java 21 even uses it in its newest feature, record patterns. Here’s how var works and how to use it well.
What var does
When you write var, the compiler looks at the value on the right-hand side and uses its type as the variable’s type:
// Java 10+ · plain declarations
String name = "Prasad"; var name = "Prasad"; // String
int count = 0; var count = 0; // int
double price = 99.5; var price = 99.5; // double
long big = 10L; var big = 10L; // long
ArrayList<String> names = new ArrayList<String>();
var names = new ArrayList<String>(); // ArrayList<String>
Each pair compiles to exactly the same bytecode. var exists only in your source code. At runtime there’s no difference at all.
var is not dynamic typing
This is the most important thing to understand. Java with var is still statically and strongly typed. The type is fixed at compile time and never changes:
var count = 0; // count is an int, forever
count = "ten"; // compile error: String cannot be converted to int
That’s the big difference from JavaScript’s var or Python variables, where a variable can hold a number now and a string later. In Java, var just means “compiler, write the type for me”. Your IDE still shows the exact type when you hover over the variable, and autocomplete works as normal.
“var changes how much you type, not how typed your code is.”
Where you can use var
var works only for local variables that have an initializer:
// 1. Local variables
var orders = orderRepository.findAll();
// 2. Enhanced for loops: great with long Map.Entry types
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + " → " + entry.getValue());
}
// 3. Classic for loops
for (var i = 0; i < 10; i++) { ... }
// 4. try-with-resources
try (var reader = Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
}
// 5. Lambda parameters (Java 11+), useful when you need an annotation
BiFunction<Integer, Integer, Integer> add = (var x, var y) -> x + y;
Point 5 looks pointless until you need an annotation on a lambda parameter: (@NonNull var x, @NonNull var y) -> ... is allowed, while a bare (@NonNull x) isn’t.
Where you can’t use var
var is deliberately limited to local variables. It can’t be used for:
class OrderService {
var cache = new HashMap<String, Order>(); // ✗ fields
var findOrder(var id) { ... } // ✗ return types and method parameters
}
And even for a local variable, the compiler needs enough information on the right-hand side:
var x; // ✗ no initializer: nothing to infer from
var x = null; // ✗ null has no useful type
var arr = {1, 2, 3}; // ✗ array initializer needs a type: use new int[]{1, 2, 3}
var f = () -> 42; // ✗ a lambda needs a target type
var a = 1, b = 2; // ✗ only one variable per var declaration
The first four fail with “cannot infer type for local variable”; the last with “‘var’ is not allowed in a compound declaration”. The rule of thumb: the right-hand side must, on its own, tell you the type.
The traps
Trap 1: int, not Integer
If you used to write Integer count = 0, note that var count = 0 gives you a primitive int, not an Integer. The literal decides the type:
| You write | The type is |
|---|---|
var n = 10; |
int |
var n = 10L; |
long |
var n = 10.0; |
double |
var n = 10f; |
float |
var n = Integer.valueOf(10); |
Integer |
var c = 'a'; |
char |
Usually int is what you want anyway. But if you need long for big values (like a timestamp or a large ID), write 10L, or var will quietly give you an int.
Trap 2: the diamond turns into Object
The diamond operator <> infers type arguments from the left-hand side. With var there’s no left-hand type, so Java falls back to Object:
var list = new ArrayList<>(); // ArrayList<Object>: anything goes in
list.add("x");
list.add(42); // compiles, and you've lost type safety
var names = new ArrayList<String>(); // ✓ put the type on the right instead
When you use var, move the type argument to the right-hand side.
Trap 3: the concrete type, not the interface
List<String> names = new ArrayList<>(); // names is a List
var names = new ArrayList<String>(); // names is an ArrayList
With var, the variable gets the concrete class. Inside a short method that rarely matters. But it means you can’t later assign a LinkedList to that variable, and you might reach for ArrayList-only methods without noticing. For a field or a return type you’d use the interface, and var can’t be used there anyway.
When var makes code better, and when it doesn’t
The OpenJDK team published style guidelines along with the feature, and they boil down to this: use var when the type is obvious from the right-hand side, or the variable name tells the reader what they need.
Good uses:
var customer = new Customer("Asha"); // type is right there
var orders = new HashMap<CustomerId, List<OrderLine>>(); // saves a long repeat
var reader = Files.newBufferedReader(path); // name + method say enough
for (var entry : ordersByCustomer.entrySet()) { ... } // avoids Map.Entry<…, List<…>>
Questionable uses:
var result = service.process(data); // result of what type? Reader has to go look.
var x = calculate(); // vague name + hidden type = harder to read
In code review, a reader doesn’t have an IDE hover. If they can’t tell the type from the line itself, write the type out, or choose a more descriptive variable name.
var in Java 21: record patterns
Java 21’s record patterns let you unpack a record in an instanceof or a switch, and var works inside them too:
// Java 21
record Point(int x, int y) {}
if (obj instanceof Point(int x, int y)) { ... } // explicit types
if (obj instanceof Point(var x, var y)) { ... } // inferred: x and y are int
It’s the same idea: the compiler already knows the components are ints, so you can let it fill them in.
Key takeaways
varlets the compiler infer a local variable’s type from its initializer. Since Java 10, and standard in Java 21 code.- It’s still static typing: the type is fixed at compile time, and the bytecode is identical.
- Works for local variables,
forloops, try-with-resources, lambda parameters (Java 11+) and record patterns (Java 21). - Doesn’t work for fields, method parameters, return types,
null, array initializers or lambdas. - Watch the traps:
var n = 0is anint,new ArrayList<>()becomesArrayList<Object>, and you get the concrete type. - Use it when the type is obvious from the line. Spell the type out when it isn’t.
Frequently asked questions
What is var in Java?
A way to declare a local variable without writing its type. The compiler infers the type from the value you assign, for example var name = "Asha"; makes name a String.
Which Java version introduced var?
Java 10, through JEP 286. Java 11 extended it to lambda parameters. It’s available in every version since, including Java 17 and Java 21.
Does var make Java dynamically typed?
No. The type is decided once, at compile time, and can’t change. Assigning a value of another type is a compile error.
Does var affect performance?
No. The compiler replaces var with the actual type, so the bytecode is exactly the same as if you had written the type yourself.
Can I use var for class fields or method parameters?
No. var is only for local variables (and lambda parameters). Fields, method parameters and return types must declare their types explicitly.
Next in Modern Java: sealed classes, for type hierarchies the compiler can check. Or go back to the overview of all Java 21 features.
Comments