Java var with Generics: Type Inference Explained
Understand how Java's var keyword infers generic types, including the diamond operator, generic method calls, anonymous classes, and common pitfalls.

When you use var in Java, the compiler infers the variable's type from its initializer. This works with generics too, but the inferred type is not always what you might expect. For example, var list = new ArrayList<String>(); infers ArrayList<String>, while var list = new ArrayList<>(); infers ArrayList<Object> because the diamond operator has no target type to guide it. This article explains how var interacts with generic type inference, where it works well, and where it can cause subtle problems.
How var Infers Generic Types
The var keyword, introduced in Java 10, performs local variable type inference. The compiler looks at the initializer expression and derives the variable's type from it. When the initializer is a generic type, the inferred type includes the full generic signature.
var strings = new ArrayList<String>();
var map = new HashMap<String, Integer>();Here, strings is ArrayList<String> and map is HashMap<String, Integer>. This is straightforward because the explicit type arguments are present in the constructor call. The compiler uses the exact generic type from the expression, preserving type safety.
However, var does not change how generics are resolved. It only hides the explicit type declaration. The underlying type is exactly what the initializer produces. This means you cannot use var to bypass generic type checking—the compiler still enforces the inferred type at compile time.
var with the Diamond Operator
The diamond operator (<>) relies on target type inference to determine its type arguments. In an assignment such as List<String> list = new ArrayList<>();, the expected variable type tells the compiler what the diamond should resolve to. With var, there is no target type: the initializer is the only source of information, so the compiler falls back to the most general type, Object.
var list = new ArrayList<>(); // Inferred as ArrayList<Object>This is a common pitfall. If you intended to create a List<String> but use the diamond operator with var, you end up with ArrayList<Object>. You can still add a String, but retrieving it returns Object and requires a cast. The compile-time safety you expect from generics is lost.
To avoid this, provide explicit type arguments when using var with a generic constructor:
var list = new ArrayList<String>(); // CorrectThe diamond operator can still work when it has a target type from another part of the expression, such as a method parameter. But var itself never supplies that target type. For example, var list = List.of("a", "b"); infers List<String> because List.of's type parameter is inferred from its arguments, not because of diamond inference.
var with Generic Method Calls
When you call a generic method, the compiler infers the type arguments from the method arguments and the assignment context. With var, the assignment context is absent, so the compiler relies solely on the method arguments. This usually works well because the arguments provide enough information.
var list = Collections.emptyList(); // Inferred as List<Object>Here, Collections.emptyList() is generic, but without a target type, the compiler infers Object. The result is List<Object>, which may not be what you want. To get List<String>, provide a type witness or assign to a typed variable:
var list = Collections.<String>emptyList(); // Explicit type witnessThis is less common because most generic methods infer from their arguments. For example, Arrays.asList("a", "b") infers List<String> because the arguments are strings. The problem arises when the method has no arguments or when the type cannot be determined from the arguments alone.
Another example is Optional.empty(). With var, it infers Optional<Object>, which is rarely useful. You must specify the type explicitly:
var empty = Optional.<String>empty(); // Optional<String>When using var with generic method calls, consider whether the inferred type is the one you need. If not, either provide a type witness or use an explicit type declaration.
var with Anonymous Classes and Generics
Anonymous classes can implement or extend generic types. When you use var with an anonymous class, the inferred type is the anonymous class itself, not the named generic supertype.
var comparator = new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareTo(b);
}
};Here, comparator's static type is the anonymous class, not Comparator<String>. Because that class is still a subtype of Comparator<String>, assigning it to a Comparator<String> variable works without a cast. The practical difference is that any additional members declared inside the anonymous class are directly accessible through var; a declaration typed as Comparator<String> would hide those members.
A related case is an anonymous subclass of a generic class:
var list = new ArrayList<String>() {}; // Anonymous subclass of ArrayList<String>The inferred type is the anonymous subclass, not ArrayList<String>. The variable is still compatible with List<String>, so passing it to a method that expects List<String> works. But the static type is not exactly ArrayList<String>, which can matter for overload resolution or for code that relies on the named type.
In practice, using var with anonymous classes is rare and often unnecessary. It can obscure the actual type and make the code harder to read. Prefer explicit types when dealing with anonymous classes that have complex generic relationships.
Limitations and Edge Cases of var with Generics
The most significant limitation is the loss of target type inference. Because var does not provide a target type, any generic expression that relies on an assignment context infers Object or the most general type. This includes the diamond operator, no-argument generic methods, and some builder patterns.
var is limited to local variable declarations (including enhanced-for loop variables and try-with-resources) and, in Java 11+, lambda parameters. It cannot be used for fields, method parameters, or return types.
var also does not support array initializers. You cannot write var arr = {1, 2, 3}; because the array initializer requires a target type.
Lambdas and method references require an explicit functional interface target. A lambda expression or method reference has no standalone type, so var cannot infer one. The following are all compile-time errors:
var f = s -> s.length(); // error
var g = (String s) -> s.length(); // error
var m = String::length; // errorUse an explicit functional interface type instead:
Function<String, Integer> f = s -> s.length();This is a limitation of lambda and method-reference typing, not of generics, but it often appears when you are trying to write concise generic code.
When to Use var vs Explicit Types with Generics
The decision to use var with generics should be based on readability and maintainability. Use var when the generic type is obvious from the initializer and the explicit type would add noise. For example:
var list = new ArrayList<String>(); // Clear from the right side
var map = Map.of("key", 1); // Map<String, Integer> is clearAvoid var when the inferred type is not the one you want, or when the initializer is complex enough that the explicit type helps the reader. This includes cases where the diamond operator is used, where generic methods have no arguments, or where the type is not immediately obvious from the right side.
A good rule of thumb: if the explicit type would be longer than the initializer and the initializer clearly shows the generic type, var improves readability. If the type is ambiguous or the initializer is a method call with an unclear return type, stick with explicit types.
Maintainability and Readability Considerations
Using var with generics can improve or harm maintainability depending on context. When the generic type is long, such as Map<String, List<Map<Integer, String>>>, var reduces clutter and makes the code easier to scan. However, it also hides the type from the reader, forcing them to look at the initializer to understand the variable's type.
In code reviews, var can make diffs harder to read because the type is not immediately visible. This is especially true when the initializer is a complex expression. For generic types, the explicit type often conveys more information than the expression itself.
Consider using var only when the initializer is a constructor call with explicit type arguments or a simple factory method like List.of. For anything else, weigh the benefit of brevity against the cost of reduced clarity. If your team values explicit types for maintainability, use var sparingly with generics.
var with Wildcard Types
Wildcard types, such as List<? extends Number>, interact with var in a specific way. When you use var with an expression that has a wildcard type, the inferred type preserves the wildcard. For example:
var numbers = getNumbers(); // Suppose getNumbers() returns List<? extends Number>Here, numbers is List<? extends Number>. This is correct and maintains the wildcard constraint. However, you cannot add elements to numbers because the wildcard prevents modification. This is the same behavior as with an explicit type, so var does not change the semantics.
One subtlety is that var can hide the wildcard, making it less obvious that the list is read-only. If you later try to add an element, the compiler error might be confusing because the variable's type is not visible. In such cases, an explicit type can serve as a reminder of the wildcard restriction.
var with Generic Arrays and Varargs
Java does not allow direct creation of generic arrays (new T[]), but you can have variables of generic array types through unchecked casts or varargs. var preserves the array type of the initializer just as it preserves any other type.
If a method returns String[], var infers String[]. For a generic method such as <T> T[] makeArray(), an unconstrained call without a target type infers Object[] because no target type or arguments supply a more specific T.
For varargs methods, the same inference rules apply. For example, Arrays.asList(T... a) infers its element type from the arguments. var list = Arrays.asList("a", "b"); is List<String>, while var list = Arrays.asList(); is List<Object>.
In general, var does not add new capabilities for arrays and generics; it only hides the type. Use explicit types when dealing with arrays and generics to avoid ambiguity.
Compatibility and Compiler Behavior
var is available from Java 10 onward. If your codebase targets an older version, you cannot use it. When using var with generics, the compiler performs the same type inference as it would for an explicit type. There is no runtime cost; var is purely a compile-time feature.
Practical Example: Building a Generic Collection
To see how var and generics work together, consider a method that builds a map of lists:
public Map<String, List<Integer>> buildMap() {
var result = new HashMap<String, List<Integer>>();
for (int i = 0; i < 10; i++) {
result.computeIfAbsent("key" + i, k -> new ArrayList<>());
}
return result;
}Here, var declares result as HashMap<String, List<Integer>>. The diamond inside the lambda (new ArrayList<>()) is not affected by var; it gets its type argument from computeIfAbsent's method signature. The mapping function returns ? extends List<Integer>, so the diamond infers ArrayList<Integer>.
By contrast, var list = new ArrayList<>(); outside any target-type context infers ArrayList<Object>. The difference is not a special rule for var; it is simply whether the diamond has a target type independent of the local variable declaration.
var with Generic Builder Patterns
Builder patterns often use generics to preserve a fluent API's type. When the builder's generic argument is explicit, var works as expected:
var builder = new GenericBuilder<String>().withValue("test");If GenericBuilder<T> has a method withValue(T value) that returns GenericBuilder<T>, the inferred type is GenericBuilder<String>. This is correct and preserves the generic type.
Self-referential generic builders can produce complex inferred types, so consider using an explicit type when the initializer makes the type hard to read. In most cases, using var only with clearly typed builder calls is the safer option.
Final Technical Consideration: Type Erasure and var
Type erasure removes generic type information at runtime. var does not affect erasure; it is a compile-time construct. The bytecode produced by var is identical to what you would get with an explicit type. This means there is no performance impact or runtime overhead.
However, because var hides the type, it can sometimes mask the effects of erasure. For example, if you use var to hold a generic list and later check list instanceof ArrayList<String>, the compiler rejects the check because generic types cannot be used with instanceof. This is a limitation of generics, not var. But with var, the error message might be less clear because the variable's type is not visible.
To avoid confusion, use explicit types when you need to perform runtime type checks or when the code relies on the exact generic type. var is best used when the type is obvious and no runtime type reflection is needed.
Summary
In short, using var with generics is convenient when the generic type is explicit in the initializer or supplied by a method's type parameters. It becomes problematic when you rely on target type inference, as with the diamond operator or no-argument generic methods. Understanding that distinction helps you use var without sacrificing type safety or readability.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.