- Prerequisites
- 1.1 Generic Types · 2.2 Wildcards
- Covers
- Target typing · Diamond operator · Method inference
- Related
- B1V1 2.3 Variables (var) · B1V3 Lambdas · 8.4 Relationship with Lambdas (B1V1)
On this page
1Concept / Definition
Type inference is the compiler's ability to work out type arguments that the programmer does not write. It uses the types of method arguments, the target type expected by the context, and declared bounds, and chooses the most specific types that make the expression valid. Inference is why most generic code in modern Java contains very few explicit type arguments.

2Why It Exists
Generic code without inference is verbose and repetitive. Before Java 7, every constructor call repeated the type arguments, as in Map<String, List<Order>> m = new HashMap<String, List<Order>>();, and generic methods with empty argument lists, such as Collections.emptyList(), often needed explicit witnesses to compile when passed as arguments. Each repetition is a place where the two sides can drift apart during a refactoring.
Inference became essential with Java 8. A lambda such as o -> o.total() has no type of its own; the compiler gives it one from the target, a functional interface type. APIs built from many small generic methods, such as streams, Comparator.comparing and Collectors, are usable only because the compiler infers their type arguments across nested calls. Inference keeps the safety of generics while letting the code say only what the reader needs.
3Core Concepts
Target typing
The target type is the type an expression is expected to have from its context: the type of the variable it is assigned to, the parameter it is passed to, or the return type of the method it is returned from. List<String> names = List.of(); infers E = String from the target even though no argument mentions String. Since Java 8, target typing also flows into nested method calls (poly expressions), and it is the only way a lambda gets its type.

Diamond operator
new ArrayList<>() asks the compiler to infer the constructor's type arguments from the target type or the constructor arguments. Introduced in Java 7, extended to anonymous classes in Java 9 (when the inferred type is denotable). Diamond is not the same as a raw type: omitting <> entirely creates a raw ArrayList with unchecked warnings.

Method inference
For a generic method call, the compiler collects constraints from each argument and the target type, then solves them. Collections.max(List.of(3, 7)) infers T = Integer; Arrays.asList(1, 2.5) infers a type compatible with both Integer and Double — an intersection such as Number & Comparable<…>. When inference picks an unhelpful type, an explicit type witness fixes it: Collections.<Number>emptyList() or List.<Number>of(1, 2).
4How It Works Internally
For each generic method or constructor call, javac creates an inference variable for every type parameter and collects constraints. Each argument contributes one: Integer must be compatible with E. The target type contributes another when the call is a poly expression, that is, when it appears in an assignment, a method argument or a return statement. Declared bounds such as T extends Comparable<? super T> are added too. The constraints are reduced to bounds on each variable, and a type is chosen that satisfies all of them; if none exists, the error lists the conflicting bounds.

When the arguments alone fix the variable from below and there is no target, javac takes their least upper bound. For Integer and Double that is not just Number but an intersection of Number, Comparable<...> and, since Java 12, Constable and ConstantDesc, which is why var mixed = List.of(1, 2.5) has a type nobody can write (Figure 4).
Lambdas and method references are special. An implicitly typed lambda such as o -> o.total() cannot be checked until its parameter types are known, so it adds no constraints until the target type has fixed them; an exact method reference such as Order::total, or a lambda with declared parameter types, can contribute at once. A receiver expression, the part before the dot in comparing(...).reversed(), never sees the target type of the whole chain, which is the root of the comparator problem in section 6.
5APIs / Features / Syntax
A few syntax forms drive inference or override it. They have arrived gradually, and each Java version has extended where inference applies:
| Form | Example | Since |
|---|---|---|
| Diamond on a constructor | new HashMap<>() | Java 7; anonymous classes Java 9 |
| Generic method inference | List.of("a", "b") | Java 5; target typing in arguments Java 8 |
| Explicit type witness | List.<Number>of(1, 2) | Java 5 |
| Lambda typed by its target | Function<String, Integer> f = s -> s.length() | Java 8 |
| Explicitly typed lambda parameters | (Order o) -> o.total() | Java 8 |
| Local variable type inference | var orders = new ArrayList<Order>() | Java 10 |
| var in lambda parameters | (var a, var b) -> a + b | Java 11 |
// diamond (Java 7)
Map<String, List<Order>> byCustomer = new HashMap<>();
// method inference, and an explicit type witness
List<String> names = List.of("ann", "bob");
List<Number> nums = List.<Number>of(1, 2);
// a lambda typed by its target, and one with an explicit parameter type
Function<String, Integer> len = s -> s.length();
Comparator<Order> byCents = Comparator.comparing((Order o) -> o.cents());
// var in lambda parameters (Java 11), var for a local variable (Java 10)
BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
var orders = new ArrayList<Order>();var is a different mechanism from generic inference: it takes the variable's type from its initialiser, and it never looks at later uses. That is why var and the diamond combine badly, since neither side then provides type arguments, while var with an explicit new ArrayList<Order>() is fine.
6Practical Examples
Example 1 — Inference in everyday code
Problem. Typical service code builds collections, comparators and anonymous classes. The comments show what the compiler infers and where it needs help.
// Target typing
List<String> empty = Collections.emptyList(); // T = String from target
Comparator<Order> c = Comparator.comparing(Order::total); // T = Order from target
// Diamond
Map<String, List<Order>> byCustomer = new HashMap<>();
Comparator<String> byLength = new Comparator<>() { // Java 9+
public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); }
};
// Method inference and type witnesses
var mixed = List.of(1, 2.5); // List<Number & Comparable<…>> — hard to name
List<Number> nums = List.of(1, 2.5); // clearer: target type drives inference
List<Number> alsoNums = List.<Number>of(1, 2); // explicit witness
// Where inference needs help: chained generic calls
Comparator<Order> byTotalThenId =
// explicit lambda parameter type
Comparator.comparing((Order o) -> o.total())
// needed because chaining loses the target
.thenComparing(Order::id);
Compiled on its own, the failing line produces two errors: "cannot find symbol: method total(), location: variable o of type Object", and "incompatible types: Comparator<Object> cannot be converted to Comparator<Order>". The first shows that T became Object; Figure 5 shows why.
Example 2 — Mini program: sorting and grouping orders
Problem. A report sorts orders by value, highest first and then by id, and groups their ids by customer. The program shows the three ways to make the comparator chain compile, and one inference result that is legal but probably not intended.
public class OrderSorting {
record Order(long id, String customer, int cents) {}
public static void main(String[] args) {
List<Order> orders = List.of(new Order(1, "asha", 4_500),
new Order(2, "ben", 1_200), new Order(3, "asha", 4_500),
new Order(4, "chen", 9_900));
// 1. a method reference is exact: T = Order even without a target
Comparator<Order> byCents =
Comparator.comparing(Order::cents).reversed();
// 2. a lambda in a chain needs a typed parameter ...
Comparator<Order> typed = Comparator.comparing((Order o) -> o.cents())
.reversed().thenComparing(Order::id);
// 3. ... or a type witness on the first call
Comparator<Order> witness =
Comparator.<Order, Integer>comparing(o -> o.cents()).reversed();
System.out.println("sorted ids: "
+ orders.stream().sorted(typed).map(Order::id).toList());
List<Long> firsts = Stream.of(byCents, typed, witness)
.map(c -> orders.stream().sorted(c).findFirst().get().id())
.toList();
System.out.println("first by each comparator: " + firsts);
// 4. diamond and target typing build nested types
Map<String, List<Long>> idsByCustomer = new TreeMap<>();
for (Order o : orders)
idsByCustomer.computeIfAbsent(o.customer(), k -> new ArrayList<>())
.add(o.id());
System.out.println("by customer: " + idsByCustomer);
// 5. var with diamond has no target: ArrayList<Object>
var anything = new ArrayList<>();
anything.add(orders.getFirst().id());
anything.add("not an id"); // compiles
System.out.println("var + diamond: " + anything);
}
}sorted ids: [4, 1, 3, 2]
first by each comparator: [4, 4, 4]
by customer: {asha=[1, 3], ben=[2], chen=[4]}
var + diamond: [1, not an id]Why it behaves this way. Order::cents is an exact method reference, so comparing can infer T = Order from it, even as the receiver of reversed(). The lambda version needs (Order o), or the witness <Order, Integer>; all three comparators agree that order 4 comes first. In the grouping loop, new ArrayList<>() inside the lambda is inferred from computeIfAbsent's return type, List<Long>, which in turn comes from the declared map. The last line is the trap of section 7: with var and a diamond, nothing supplies a type argument, so the list is an ArrayList<Object> and accepts a String among the ids.
Example 3 — An overload that defeats inference
Problem. A utility class offers each(items, Function) to map and each(items, Consumer) to act on each element. Callers passing a lambda get a compile error.
public class AmbiguousOverload {
static void each(List<String> items, Function<String, Integer> f) { }
static void each(List<String> items, Consumer<String> action) { }
public static void main(String[] args) {
each(List.of("a", "bb"), s -> s.length()); // which overload?
}
}AmbiguousOverload.java:13: error: reference to each is ambiguous
each(List.of("a", "bb"), s -> s.length()); // which overload?
^
both method each(List<String>,Function<String,Integer>) in AmbiguousOverload
and method each(List<String>,Consumer<String>) in AmbiguousOverload match
1 errorThe lambda s -> s.length() is compatible with both interfaces: as a Function it returns the length, and as a Consumer the expression is evaluated and its value discarded. Because the lambda is implicitly typed, javac cannot use its body to choose, so both methods are applicable and neither is more specific. Giving the operations different names removes the ambiguity:
public class OverloadFix {
static <R> List<R> mapEach(List<String> items, Function<String, R> f) {
List<R> out = new ArrayList<>();
for (String s : items) out.add(f.apply(s));
return out;
}
static void forEachItem(List<String> items, Consumer<String> action) {
for (String s : items) action.accept(s);
}
public static void main(String[] args) {
List<Integer> lengths = mapEach(List.of("a", "bb"), s -> s.length());
System.out.println(lengths);
forEachItem(List.of("a", "bb"), s -> System.out.println("item " + s));
}
}[1, 2]
item a
item bbExecutorService.submit has the same shape, overloaded for Runnable and Callable<T>, and works because a lambda with no parameters counts as explicitly typed, so javac may compare the return types and prefers Callable for a lambda that returns a value. New APIs should not rely on such rules.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Omitting <> (new ArrayList()) instead of using the diamond | Creates a raw type: checking is switched off silently, with only an unchecked warning | Always write new ArrayList<>() |
| var combined with the diamond (var list = new ArrayList<>()) | Infers ArrayList<Object>; any value is accepted (Example 2) | Give the type on one side: var list = new ArrayList<Order>() |
| Chained generic calls that lose the target type | comparing(o -> o.total()).reversed() fails: o is inferred as Object | Use a method reference, a typed lambda parameter or a type witness (Figure 5) |
| Inferred intersection types in public APIs (returning var-inferred List.of(1, 2.5)) | Callers cannot name the type, and a change to the arguments changes the API | Declare the type explicitly: List<Number> |
| Overloads that take different functional interfaces of the same arity | Lambdas become ambiguous at every call site (Example 3) | Use different method names, such as map and forEach |
8Performance & Production Considerations
Inference costs nothing at run time: it only decides which type arguments are written into the erased code, and the bytecode is the same as if the types had been written by hand. The cost is at compile time and in people's time. Long stream pipelines and deeply nested generic calls can make javac noticeably slower and produce error messages pages long, in which the first line that mentions an inference variable is usually the useful one. Splitting a long chain into named intermediate variables makes both the compiler and the reader faster.
Inference also affects compatibility. Adding an overload to a published API can make existing callers' lambdas ambiguous, so a change that is binary compatible breaks their source at the next build. Changing a return type from List<Order> to Collection<Order> can change what callers' var declarations infer. Treat new overloads that take functional interfaces as API changes, and compile representative client code against each release.
9Architecture & Design Considerations
Good generic APIs are designed to infer well: parameters ordered so that the most informative argument comes first, lambda-accepting methods with specific functional interface types, and overloads that do not create ambiguity for lambdas (for example two overloads taking Function and Consumer with the same arity). Inference-friendly APIs let callers write concise code without witnesses or casts.
10Interview Questions & Answers
What does the diamond operator do?
It lets the compiler infer the type arguments of a constructor call from the target type or constructor arguments: Map<String, Integer> m = new HashMap<>(); It was introduced in Java 7 and extended to anonymous classes in Java 9. Writing new HashMap() without the brackets is not the same: it creates a raw type.
What is target typing?
Using the type expected by the context — assignment target, method parameter or return type — to infer type arguments or the type of a lambda or method reference. A lambda has no type of its own, so target typing is the only way it gets one; List<String> names = List.of() uses it to infer E = String with no arguments at all.
What is the difference between new ArrayList<>() and new ArrayList()?
The first infers type arguments and is fully checked. The second creates a raw type, turning off generic checking and producing unchecked warnings. Raw types exist only for compatibility with code written before Java 5, so new code should always use the diamond.
What is a type witness and when do you need one?
An explicit type argument on a generic method call, like Collections.<Number>emptyList(). It is needed when inference lacks information or picks an unwanted type, commonly in chained calls where the target type does not reach the inner call. Witnesses are rarer since Java 8, because target types now flow into method arguments.
Why does Comparator.comparing(o -> o.total()).reversed() fail to compile?
The target type applies to the result of reversed(), not to comparing(...), so comparing has no target to infer T from and treats o as Object. Typing the lambda parameter or using a method reference such as Order::total fixes it. A lambda with declared parameter types, or the witness Comparator.<Order, Integer>comparing(...), also works (Example 2).
How do API design choices affect type inference for callers?
Overloads taking different functional interfaces with the same arity can make lambdas ambiguous; putting type-determining parameters first and using specific functional interfaces helps inference; and returning exact types keeps chained calls inferable. Test APIs with lambdas and method references at call sites. Test with implicitly typed lambdas in particular, because they are the first to become ambiguous.
Is var the same thing as generic type inference?
No. var (Java 10) infers the type of a local variable from its initialiser, and nothing else: var orders = new ArrayList<Order>() declares an ArrayList<Order>. Generic inference works out the type arguments of a method or constructor call from the arguments and the target type. The two interact: with var there is no target type, so var list = new ArrayList<>() gives the diamond nothing to infer from and produces ArrayList<Object>.
What does this program print?
public class VarQuiz {
public static void main(String[] args) {
var list = new ArrayList<>();
list.add(1);
list.add("two");
System.out.println(list + " " + list.get(1).getClass().getSimpleName());
var names = new ArrayList<String>();
names.add("ann");
System.out.println(names.get(0).toUpperCase());
}
}It prints [1, two] String, then ANN. The first var has a diamond and no target, so the list is an ArrayList<Object>, and both an Integer and a String are accepted. In the second, the type argument is written on the right, so names is an ArrayList<String> and get(0) returns a String without a cast.
Which overload does each call choose? What does this program print?
public class OverloadQuiz {
static void show(Object o) { System.out.println("Object " + o); }
static void show(List<String> l) { System.out.println("List<String> "+ l); }
public static void main(String[] args) {
show(Collections.emptyList()); // inferred from the parameter
Object o = Collections.emptyList();
show(o); // static type Object
show(Collections.<Integer>emptyList()); // witness: List<Integer>
}
}It prints List<String> [], then Object [], then Object []. In the first call, emptyList() is a poly expression: for show(List<String>) javac can infer T = String, so both overloads are applicable, and the List<String> one is more specific. In the second call the argument is a variable of static type Object, so only show(Object) applies. In the third, the witness fixes the type as List<Integer>, which is not a List<String>, so again only show(Object) applies.
What does the compiler infer for List.of(1, 2.5) when there is no target type, and why?
The arguments give the lower bounds Integer and Double for E, and with no target the compiler chooses their least upper bound. That is not simply Number: both classes also implement Comparable and, since Java 12, Constable and ConstantDesc, so E becomes an intersection of those types (Figure 4). The code works, but the type cannot be written down, which is why a declared target such as List<Number> nums = List.of(1, 2.5) is clearer.
A library release adds an overload process(List<String> items, Consumer<String> action) next to process(List<String> items, Function<String, String> f). Clients now fail to compile. What happened, and how do you fix it?
Client lambdas such as s -> s.trim() are compatible with both interfaces, and because they are implicitly typed, javac cannot use their bodies to decide, so the call is ambiguous (Example 3). The change was binary compatible, so already compiled clients still run, but every rebuild fails. Fix it in the library: rename the new method, for example forEachItem, and deprecate nothing. Clients can work around it with a cast or a typed lambda, but they should not have to. Add client-style compile tests with lambdas to the library build.
What guidelines would you set for var in a large codebase?
Use var where the initialiser makes the type obvious, such as var orders = new ArrayList<Order>() or var stream = Files.lines(path), and in long generic declarations where the type adds noise. Avoid it where the type is the important information, such as the result of a call returning an interface or a numeric type where int versus long matters, and never combine it with the diamond. The benefit is shorter code that is easier to refactor; the cost is that a reader without an IDE sees less. Let reviewers ask for an explicit type wherever they had to look it up.
You are defining standards for a platform SDK used by many teams. How do you make its generic APIs inference-friendly?
Design for the call site. Put the argument that fixes the type first, so a lambda later in the list is checked against known types; prefer method names over overloads for different functional interfaces; accept specific functional interfaces rather than one general one; return exact, nameable types, never intersections or wildcards; and avoid APIs that need a type witness for common uses. Enforce it with a compile-test suite written in client style, with implicitly typed lambdas, method references and var, which runs on every SDK release next to a binary-compatibility check.
Some teams want every type written out for readability; others rely on inference everywhere. Where do you land for long-lived enterprise code?
Types in signatures are contracts and stay explicit: fields, parameters, return types and public APIs. Inside method bodies, inference removes repetition and makes refactoring cheaper, and the diamond and lambdas are simply idiomatic Java. The risk lies in long chains and var with non-obvious types, where a reader must reconstruct what the compiler inferred. A practical rule is explicit at boundaries, inferred inside, and a named variable whenever a chain needs a comment or a type witness to be understood.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Inference combines argument types, the target type and bounds.
- Diamond infers constructor type arguments; omitting it creates raw types.
- Lambdas get their type only from the target.
- Chained calls can lose the target; use typed lambda parameters or witnesses.