Sub topic 5
Where `var` Is Rejected and Why
This chapter assumes that you know basic Java declarations, primitive and reference types, generics, enhanced for loops, try-with-resources, and lambda expressions. The key idea is that var needs enough information at the declaration site to infer one fixed static type.
The initializer must reveal a type
A declaration such as var count = 10; works because the initializer has the type int. The compiler records that type. Later, count cannot refer to a different kind of value.
var does not mean “choose a type later.” It means “let the compiler write the type here during compilation.”
public class RejectionExamples {
public static void main(String[] args) {
var count = 10;
count = 20;
// count = "twenty"; // Compile-time error: count is still an int
var numbers = new int[] {1, 2, 3};
System.out.println(count);
System.out.println(numbers.length);
}
}The following declarations are rejected because the compiler cannot determine a usable type:
| Declaration | Why it is rejected |
|---|---|
| `var value;` | There is no initializer to inspect. |
| `var value = null;` | `null` has no specific reference type. |
| `var values = {1, 2, 3};` | An array initializer needs a declared array type. |
| `var action = () -> 42;` | A lambda needs a target functional-interface type. |
| `var length = String::length;` | A method reference also needs a target type. |
| `var a = 1, b = 2;` | One `var` declaration can contain only one variable. |
| `var values[] = new int[3];` | Array brackets cannot appear after a `var` variable name. |
Use an explicit type when the initializer cannot provide the missing information:
import java.util.function.IntSupplier;
import java.util.function.ToIntFunction;
public class ExplicitTypes {
public static void main(String[] args) {
int[] values = {1, 2, 3};
IntSupplier action = () -> 42;
ToIntFunction<String> length = String::length;
System.out.println(values[0]);
System.out.println(action.getAsInt());
System.out.println(length.applyAsInt("Java"));
}
}A lambda is compatible with many possible interfaces. For example, () -> 42 could be an IntSupplier, a Callable<Integer>, or another interface with a matching method. Without a target type, var cannot select one.
Contexts where `var` is not a type
var is restricted to local variable declarations. It cannot declare fields, method parameters, constructor parameters, or method return types.
public class NotLocalDeclarations {
// var field = 10; // Invalid field declaration
// public var createValue() { // Invalid return type
// return 10;
// }
// public void print(var value) { // Invalid parameter type
// }
}These restrictions preserve clear class and method contracts. A public method's parameter and return types are part of the API that other code uses. var is intended for local implementation details, where the initializer is nearby.
var is allowed in certain local contexts: ordinary local variables, enhanced for variables, basic for variables, and try-with-resources variables. The initializer or loop source supplies the needed type.
flowchart TD
A[var declaration] --> B{Is it local?}
B -->|No| C[Rejected: field, parameter, or return type]
B -->|Yes| D{Can the compiler infer one type?}
D -->|No| E[Rejected: missing or ambiguous target type]
D -->|Yes| F[Accepted with a fixed static type]Common mistakes
A null initializer can be assigned to many reference types, so it does not identify one type:
// var item = null; // Invalid
String item = null; // ValidAn array initializer has the same issue. The compiler needs to know whether the elements form an int[], String[], or another array type:
var ids = new int[] {1, 2, 3}; // Valid
int[] otherIds = {1, 2, 3}; // Also validWhen var is rejected, the solution is not to force inference. Supply the type that communicates your intention.
Exercise
Why does var supplier = () -> 42; fail, while IntSupplier supplier = () -> 42; compiles?
Show answer
A lambda has no standalone type. It needs a target functional-interface type, and IntSupplier provides that target.