Sub topic 8
Inferred type versus declared type
This chapter assumes you can read basic Java, know the difference between a class and an interface, and have seen var declarations in earlier chapters. You should also be comfortable with method overloading and with List<String> versus ArrayList<String>. The chapter covers what type a var variable gets, how that differs from the type you would have written yourself, and which bugs and surprises follow.
The rule: var takes the initializer's static type
When you write an explicit declaration, you choose two things separately. You choose the type of the variable, and you choose the object assigned to it. The two can differ.
List<String> declared = new ArrayList<>();Here the variable type is List<String> and the object is an ArrayList<String>. The compiler only lets you use members of List<String> through this variable.
With var you give up the first choice. The compiler computes the static type of the initializer expression and uses that as the variable's type.
var inferred = new ArrayList<String>();The expression new ArrayList<String>() has the static type ArrayList<String>, so inferred is an ArrayList<String>. The variable is not dynamically typed. It has one fixed type from the declaration onward, as if you had written that type yourself.
The key point is this: the inferred type is the static type of the initializer expression. It is not the interface you might have preferred, and it is not a general supertype.
Seeing the difference in code
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DeclaredVsInferred {
public static void main(String[] args) {
List<String> declared = new ArrayList<>();
var inferred = new ArrayList<String>();
inferred.ensureCapacity(100); // compiles: ArrayList has this method
// declared.ensureCapacity(100); // does not compile: List has no such method
declared = new LinkedList<>(); // compiles: any List<String> fits
// inferred = new LinkedList<String>();
// error: LinkedList<String> cannot be converted to ArrayList<String>
System.out.println(declared.getClass().getSimpleName()); // LinkedList
System.out.println(inferred.getClass().getSimpleName()); // ArrayList
}
}The var variable sees more members, because ArrayList has methods that List lacks. It also accepts fewer values, because only an ArrayList<String> or a subclass can be assigned to it. The declared variable is the reverse: fewer members, but more flexibility.
This has a design consequence. A common guideline is to program to an interface, for example to declare a field or parameter as List rather than ArrayList. For fields, parameters and return types, var is not allowed, so the guideline still applies there. For local variables the scope is small, and the flexibility of a wider type matters less. If you want a local to be typed as an interface, write the interface.
Static type versus runtime type
The inferred type is always a compile-time notion. It comes from the declared types in the code, never from what object happens to exist when the program runs.
This matters when the initializer is a method call. The static type of a call is the method's declared return type, even if the method actually returns something more specific.
import java.util.ArrayList;
import java.util.List;
public class StaticVsRuntime {
static List<String> loadNames() {
return new ArrayList<>(List.of("Ada", "Grace"));
}
public static void main(String[] args) {
var result = loadNames(); // List<String>
System.out.println(result.getClass().getSimpleName()); // ArrayList
// result.ensureCapacity(10); // does not compile
System.out.println(result); // [Ada, Grace]
}
}At runtime result refers to an ArrayList. The compiler does not look inside loadNames, so it only knows the signature promises a List<String>. The same applies to factory methods such as List.of(...), Map.of(...) and Optional.of(...). You get the type in the signature, not the hidden implementation class.
Inference follows the code when it changes
A var variable tracks the initializer. If someone edits a method's return type, the type of every var variable that calls it changes silently.
Suppose loadNames() is changed to return ArrayList<String>. Every var result = loadNames(); now has type ArrayList<String>. Most code keeps compiling. Code that relied on the old type may not, for example result = anotherList; where anotherList is a LinkedList<String>. With explicit types, the declaration stays List<String> and the change has no effect on callers.
Neither behavior is always better. The silent change is convenient during refactoring, because you do not have to edit each declaration. It is a risk when you want the variable's type to stay stable.
Overload resolution sees the inferred type
Because the variable's type differs from what you might have written, overload resolution can pick a different method.
public class OverloadPick {
static void show(Object o) { System.out.println("Object: " + o); }
static void show(String s) { System.out.println("String: " + s); }
public static void main(String[] args) {
Object declared = "hello";
var inferred = "hello";
show(declared); // Object: hello
show(inferred); // String: hello
}
}Both variables hold the same String object. Overload resolution happens at compile time and uses the variable's static type, so declared picks show(Object) and inferred picks show(String). Replacing an explicit declaration with var can therefore change which method runs. This is rare in practice, but it is a real behavior change that tests would need to catch.
Primitives and numeric promotion
For primitives, the inferred type is exactly the type of the expression. You saw this with literals in an earlier chapter. The same logic applies to compound expressions, where the type depends on promotion rules rather than on the operands you can see.
public class TernaryPromotion {
public static void main(String[] args) {
boolean flag = true;
var number = flag ? 1 : 2.0; // double, because int is promoted
System.out.println(number); // 1.0
}
}The conditional expression flag ? 1 : 2.0 has type double. The result prints 1.0 even though the branch taken was the int literal. With var there is no explicit type to remind you of this. If you wanted an int, the compiler will not warn you.
Once the type is fixed, assignments are checked against it. After var x = 10; you cannot later write x = 3.5;, because x is an int and narrowing a double needs a cast.
Types you cannot write down
Usually the inferred type is one you could also have written, such as ArrayList<String>. Sometimes the compiler infers a type that has no name in source code. These are called non-denotable types. Two cases matter here.
Anonymous classes. The type of new Object() { int x = 3; } is the anonymous class itself, so var keeps access to its members. The next chapters cover this in detail.
Intersection types. If a conditional expression mixes unrelated types, the result type is the least upper bound of both, which can be an intersection of several types.
public class MixedTernary {
public static void main(String[] args) {
boolean flag = false;
var mixed = flag ? 1 : "one"; // an intersection of Object, Serializable and Comparable
System.out.println(mixed); // one
System.out.println(mixed.hashCode() != 0);
}
}You can call methods that all the component types share, such as hashCode() and toString(). You could not declare this variable with an explicit type except by choosing a supertype like Object. Here var carries more type information than a declaration you would normally write, though in this example it is rarely useful.
Wildcards and capture
If the initializer's type involves a wildcard such as ? extends Number, the compiler creates a temporary capture type for the unknown type argument. Capture types cannot be written, so var replaces them with their upper bound. The language specification calls this upward projection.
import java.util.List;
public class WildcardProjection {
public static void main(String[] args) {
List<? extends Number> numbers = List.of(1, 2, 3);
var first = numbers.get(0); // Number
System.out.println(first.intValue()); // 1
}
}The variable first has type Number, which is what you would have written. You do not need to handle capture types yourself.
Choosing between the two
Use these criteria when you decide whether a local variable should be var or have an explicit type.
| Situation | Better choice | Reason |
|---|---|---|
| You want to call methods that exist only on the concrete class | `var` | The variable has the concrete type, so those methods are visible. |
| You may reassign the variable to a different implementation | Explicit interface type | A `var` variable accepts only the initializer's type and its subtypes. |
| The initializer is a call to a method with a clear, stable return type | Either | The inferred type equals the declared return type. |
| You want a refactoring to leave the variable's type unchanged | Explicit type | `var` follows any change to the initializer's type. |
| Overload choice depends on the variable's type | Explicit type | `var` can select a more specific overload than you expect. |
| The type name is long and repeated in the initializer, such as `new HashMap<String, List<Integer>>()` | `var` | The type is still visible on the right side. |
Common errors
- Expecting an interface type. Writing
var items = new ArrayList<String>();and then passingitemsaround as if it were declaredList<String>works, but reassigning it to anotherListdoes not. - Reading the right-hand side as the runtime type. For
var x = factory();the type is whateverfactory()declares, not what it returns. - Missing a promotion. Conditional expressions and arithmetic can widen the type. Check the type when mixing
int,longanddouble. - Hiding a type change. A signature change in a called method changes your variable's type. Review call sites when you change return types.
Exercise
Given List<String> a = new ArrayList<>(); var b = new ArrayList<String>();, which of these statements compile: a.ensureCapacity(5);, b.ensureCapacity(5);, a = new LinkedList<>();, b = new LinkedList<>();? Explain each.
Show answer
Only b.ensureCapacity(5); and a = new LinkedList<>(); compile. The variable a has static type List<String>, which has no ensureCapacity, so the first statement fails. The variable b has the inferred type ArrayList<String>, which has that method, so the second compiles. A LinkedList is a List<String>, so the third compiles. It is not an ArrayList<String>, so the fourth fails.
Exercise
Method static Collection<String> fetch() returns an ArrayList<String> at runtime. What is the type of var x = fetch();, and can you call x.get(0)?
Show answer
The type is Collection<String>, taken from the method's declared return type. You cannot call x.get(0), because Collection has no get method. The runtime class is ArrayList, but the compiler does not use it for inference.
Exercise
What does this program print, and why? boolean f = true; var v = f ? 1 : 2.0; System.out.println(v);
Show answer
It prints 1.0. A conditional expression with an int and a double operand has type double through numeric promotion, so v is a double and the int value 1 is converted to 1.0.