Sub topic 3
How the Compiler Infers the Type
This chapter assumes you know Java local variables, primitive and reference types, generics, the diamond operator (<>), and basic expressions. It also assumes you understand that Java is statically typed: the compiler checks types before the program runs.
The initializer determines the type
With var, the compiler reads the initializer on the right side of = and assigns a static type to the variable. The initializer is the expression that supplies the first value.
public class InferenceBasics {
public static void main(String[] args) {
var count = 10; // int
var label = "ready"; // String
var price = 12.50; // double
count = 20;
label = label.toUpperCase();
System.out.println(count);
System.out.println(label);
System.out.println(price);
}
}The compiler does not postpone the decision until runtime. After compilation, count has type int, label has type String, and price has type double. You cannot later assign a value of an incompatible type.
var count = 10;
// count = "ten"; // compile-time errorvar therefore removes repetition in the declaration. It does not remove type checking.
A type must be inferable from one initializer
The compiler needs one initializer with a usable type. These declarations fail because the compiler has no complete type to infer.
public class InferenceErrors {
public static void main(String[] args) {
// var missing; // no initializer
// var unknown = null; // null has no specific type
// var values = {1, 2, 3}; // array initializer has no target type
// var operation = () -> 42; // lambda has no target type
// var method = String::length; // method reference has no target type
}
}A lambda and a method reference are poly expressions. Their types come from a target type, such as a functional interface. Since var is waiting for the expression's type, it cannot provide that target type by itself.
Give the expression a target type first:
import java.util.function.IntSupplier;
public class TargetType {
public static void main(String[] args) {
IntSupplier operation = () -> 42;
var result = operation.getAsInt();
var values = new int[] {1, 2, 3};
System.out.println(result + values.length); // 45
}
}A declaration with var also has one variable name. This is invalid:
// var first = 1, second = 2;The expression's exact type matters
The compiler infers the type produced by the expression, including its generic arguments and concrete class.
| Declaration | Inferred type |
|---|---|
| `var n = 1;` | `int` |
| `var text = "Java";` | `String` |
| `var list = new ArrayList<String>();` | `ArrayList<String>` |
| `var item = new StringBuilder();` | `StringBuilder` |
The diamond operator can also affect the result. Without enough generic information, the diamond may infer Object.
import java.util.ArrayList;
public class GenericInference {
public static void main(String[] args) {
var mixed = new ArrayList<>();
mixed.add("text");
mixed.add(42); // allowed: mixed is ArrayList<Object>
var names = new ArrayList<String>();
names.add("Ada");
// names.add(42); // compile-time error
}
}Use explicit type arguments when the element type matters. This makes the inferred type both useful and clear.
Declared type and inferred type can differ
An explicit declaration can expose only an interface or superclass:
import java.util.ArrayList;
import java.util.List;
public class StaticTypeChoice {
public static void main(String[] args) {
List<String> declared = new ArrayList<>();
var inferred = new ArrayList<String>();
// declared.ensureCapacity(10); // List has no such method
inferred.ensureCapacity(10); // ArrayList does
}
}Both objects are ArrayList instances, but the variables have different static types. Choose var when the concrete type improves the code. Keep an explicit interface type when hiding the implementation is part of the design.
>callout note var infers a type once at compile time. It does not create a dynamically typed variable, and the variable's type does not change while the program runs. >```
Exercise
What is the inferred type of var values = new ArrayList<Integer>();, and why can values.add("7") not compile?
Show answer
The inferred type is ArrayList<Integer>. The initializer supplies that exact generic type, so add accepts Integer, not String.