Sub topic 2
Where `var` Is Rejected and Why
Assume you know local variables, primitive and reference types, generics, enhanced for loops, and lambda expressions. Java's var uses compile-time type inference. The compiler chooses one static type from the initializer, and that type cannot change later.
Where `var` Is Rejected and Why
var requires one variable and an initializer whose type the compiler can determine immediately. It cannot replace every type declaration.
public class VarRejected {
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 needs a type
// var action = () -> 42; // lambda needs a target type
// var method = String::length; // method reference needs a target type
// var a = 1, b = 2; // multiple declarators
// var text[] = new String[2]; // brackets cannot follow the name
var values = new int[] {1, 2, 3};
System.out.println(values.length);
}
}var is also restricted to local variables, loop variables, and try-with-resources variables. It cannot declare fields, method parameters, or return types because those declarations need an explicit type in the class or method interface.
Literals and Primitive Types
The literal determines the inferred primitive type. Integer literals are int by default, and decimal literals are double by default.
| Declaration | Inferred type |
|---|---|
| `var count = 1;` | `int` |
| `var total = 1L;` | `long` |
| `var ratio = 1.5;` | `double` |
| `var small = (byte) 1;` | `byte` |
Use a suffix or cast when the default type is not suitable.
Generics and the Diamond Operator
var preserves the type produced by the initializer. With the diamond operator and no target type, an empty generic constructor commonly infers Object.
var mixed = new java.util.ArrayList<>();
mixed.add("text");
mixed.add(42); // allowed: ArrayList<Object>
var names = new java.util.ArrayList<String>();
// names.add(42); // rejected: requires StringWrite the type argument when it matters to correctness or readability.
Inferred Type Versus Declared Type
The variable's static type can be more specific than an interface type you would otherwise declare.
var list = new java.util.ArrayList<String>();
list.ensureCapacity(10); // available on ArrayList
java.util.List<String> other = new java.util.ArrayList<>();
// other.ensureCapacity(10); // unavailable through ListExercise
Why does var item = null; fail to compile?
Show answer
null can represent many reference types, so it does not provide one type for the compiler to infer.