Sub topic 3
How the compiler infers the type
This chapter assumes you can declare local variables, know the difference between primitive and reference types, and have seen generic methods such as List.of. You should also have seen the basic var name = value; form from the previous chapter. Here the focus is the rule the compiler follows to pick the type, and the cases where that rule gives a result you may not expect.
The rule: the type of the initializer becomes the type of the variable
When the compiler sees var x = expression;, it works out the static type of expression and uses that type as the declared type of x. The result is the same as if you had written the type by hand. Nothing is decided at run time.
Three properties follow from this rule:
- The information flows in one direction only, from the initializer to the variable. The compiler never looks at later statements to refine the type.
- The inferred type is a compile-time type. It is the type of the expression, not the class of the object that happens to exist at run time.
- The variable's type is fixed for its whole scope.
Where the type comes from
Many kinds of expression have a type the compiler can determine on its own. The table lists common initializers and what var infers for them.
| Initializer | Inferred type | Reason |
|---|---|---|
| `String.valueOf(42)` | `String` | declared return type of the method |
| `"abc".length()` | `int` | declared return type of the method |
| `List.of(1, 2, 3)` | `List<Integer>` | generic method, type argument inferred from the arguments |
| `Map.of("Ada", 36)` | `Map<String, Integer>` | same |
| `new String[2][3]` | `String[][]` | array creation expression |
| `new ArrayList<String>()` | `ArrayList<String>` | class instance creation |
| `(long) 5` | `long` | cast expression |
| `5 / 2.0` | `double` | binary numeric promotion |
The next program puts several of these together. Every comment shows the type the compiler assigns.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class InferSources {
static List<String> loadNames() {
return new ArrayList<>(List.of("Ada", "Grace"));
}
public static void main(String[] args) {
var text = String.valueOf(42); // String
var length = text.length(); // int
var names = loadNames(); // List<String>
var numbers = List.of(1, 2, 3); // List<Integer>
var ages = Map.of("Ada", 36); // Map<String, Integer>
var total = numbers.stream().mapToInt(Integer::intValue).sum(); // int
var grid = new String[2][3]; // String[][]
System.out.println(text + " " + length);
System.out.println(names + " " + numbers + " " + ages);
System.out.println(total + " " + grid.length + "x" + grid[0].length);
}
}The program prints:
42 2
[Ada, Grace] [1, 2, 3] {Ada=36}
6 2x3The variable keeps its type
Because inference happens once, at the declaration, the variable is as strictly typed as one declared by hand. Assigning a value of another type is an error:
public class VarFixedType {
public static void main(String[] args) {
var count = 10; // int
count = count + 5; // fine, still an int
System.out.println(count);
// count = "ten"; // error: String cannot be converted to int
// count = 3.5; // error: possible lossy conversion from double to int
}
}This is the main difference from dynamically typed languages. A var variable never changes type, and it never "becomes" something else because of a later assignment.
Arithmetic, promotion, and the ternary operator
The inferred type of an arithmetic expression follows the normal Java rules. These rules can surprise you when the variable no longer has a visible type to remind you.
public class InferExpressions {
public static void main(String[] args) {
var a = 5 / 2; // int, value 2 (integer division)
var b = 5 / 2.0; // double, value 2.5
var c = 'a' + 1; // int, value 98, not a char
var d = 10L * 3; // long, value 30
var e = "n=" + 1; // String, value "n=1"
var flag = args.length == 0; // boolean
var mixed = flag ? 1 : 2.0; // double, because int and double are promoted
var boxed = Integer.valueOf(7); // Integer, not int
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + mixed + " " + boxed);
}
}With no command-line arguments this prints 2 2.5 98 30 n=1 1.0 7.
Two lines deserve attention. The expression 'a' + 1 is an int, because arithmetic on a char promotes it. The ternary flag ? 1 : 2.0 has type double even when flag is true, so the result prints as 1.0 and not 1. If you wrote var mixed = ... expecting an int, later code that assumed integer behavior would fail to compile or behave differently.
The static type, not the runtime class
The compiler can only know the static type of the initializer. If a method is declared to return Object, then var gives you an Object, whatever it returns at run time. The same is true when a method returns an interface type.
import java.util.ArrayList;
import java.util.List;
public class InferStaticType {
static Object pick() {
return "hello";
}
static List<String> makeList() {
return new ArrayList<>();
}
public static void main(String[] args) {
var o = pick(); // Object, even though it holds a String
// System.out.println(o.length()); // does not compile: Object has no length()
System.out.println(o);
var list = makeList(); // List<String>, not ArrayList<String>
// list.ensureCapacity(100); // does not compile: List has no ensureCapacity
list.add("x");
System.out.println(list);
}
}var does not make the code more flexible. It saves you from writing a type that the compiler already knows. If the type the compiler knows is broader than you wanted, you must change the initializer, for example by casting or by calling a method with a more specific return type, or you must write the explicit type.
Initializers that depend on a target type
Some expressions get their type partly from the place where they are used. These are called poly expressions. Lambdas, method references, and generic method calls are the main examples. When you write List<String> typed = Collections.emptyList();, the compiler uses List<String> as a target type and infers String as the type argument. With var there is no target type, so the compiler can only use what the expression itself provides.
import java.util.Collections;
import java.util.List;
public class InferNoTarget {
public static void main(String[] args) {
List<String> typed = Collections.emptyList(); // T inferred as String from the target
var untyped = Collections.emptyList(); // T has no constraint, so List<Object>
// String s = untyped.get(0); // does not compile: Object is not a String
Object first = untyped.size() > 0 ? untyped.get(0) : "none";
System.out.println(typed.size() + " " + first);
}
}The program prints 0 none. For untyped, nothing in the call constrains the type parameter, so the compiler picks Object. The code compiles, but untyped is much less useful than typed. The same effect applies to var x = List.of(); and to new ArrayList<>() with var. The generics chapter returns to this in detail.
Lambdas and method references have no standalone type at all, so they are rejected outright:
import java.util.function.Function;
public class InferLambdaRejected {
public static void main(String[] args) {
// var f = s -> s.length(); // error: cannot infer type for local variable f
Function<String, Integer> f = s -> s.length();
System.out.println(f.apply("four")); // 4
}
}The variable is not in scope in its own initializer
The compiler must determine the type before the variable exists, so the initializer cannot refer to the variable it declares.
public class InferSelfReference {
public static void main(String[] args) {
// var x = x + 1; // error: cannot use 'var' on self-referencing variable
var y = 1;
y = y + 1;
System.out.println(y); // 2
}
}A normal declaration such as int x = x + 1; fails too, but for a different reason: x is not definitely assigned. The var version fails earlier, because there is no type to give x at all.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `var` to see later assignments | The type is fixed at the declaration | Write the initializer so it already has the type you want |
| Using a ternary with mixed numeric types | Promotion gives the wider type, such as `double` | Make both branches the same type, or declare the type explicitly |
| Using a method that returns an interface type | Only interface methods are available | Call a method that returns the specific type, or declare it explicitly |
| Using `var` with `Collections.emptyList()` or similar | Type arguments default to `Object` | Give the call explicit type arguments, such as `Collections.<String>emptyList()` |
| Referring to the variable in its own initializer | Compile error | Declare it first, or restructure the code |
Summary of the rule
- The compiler computes the static type of the initializer and gives it to the variable.
- The type does not depend on later code, and it does not change.
- Expressions with their own type work well: method calls, constructors, casts, arithmetic, arrays.
- Expressions that need a target type either fail (lambdas, method references) or fall back to a broad type such as
Object(generic calls with unconstrained type arguments).
Exercise
For each declaration, state the inferred type: (1) var a = 7 / 2; (2) var b = 'x' + 'y'; (3) var c = args.length > 0 ? 1 : 2L; (4) var d = Collections.emptyList();
Show answer
(1) int, because both operands are int and the result is 2. (2) int, because adding two char values promotes them to int. (3) long, because the two branches are int and long and binary numeric promotion gives long. (4) List<Object>, because there is no target type to constrain the type argument.
Exercise
A method is declared as static Number parse(String s) and returns Integer.valueOf(s). After var n = parse("5");, why does n.intValue() compile but n.compareTo(3) not? What would you change if you needed compareTo?
Show answer
The inferred type is the declared return type, Number, not the runtime class Integer. Number declares intValue() but not compareTo. To use compareTo, change the method to return Integer, cast the result, or declare the variable as Integer explicitly.