Sub topic 5
Where var is rejected and why
This chapter assumes you can declare local variables, write array initializers, and read basic lambda syntax. You should also know that var infers a variable's type at compile time. Here you will learn which declarations the compiler refuses, which error message each one produces, and how to fix them.
The rule behind every rejection
The compiler infers the type of a var variable from its initializer. It reads the initializer expression and takes that expression's type. It does not look at how the variable is used later, and it does not look at the surrounding context.
Almost every rejection follows from that. The compiler turns var down in two situations:
- There is no initializer, or the initializer does not give the compiler a usable type on its own.
- The position is not a local variable declaration, so
varhas nothing to infer.
Quick reference
| Declaration | Compiler message (abridged) |
|---|---|
| `var a;` | cannot use 'var' on variable without initializer |
| `var b = null;` | variable initializer is 'null' |
| `var c = {1, 2, 3};` | array initializer needs an explicit target-type |
| `var d = () -> 42;` | lambda expression needs an explicit target-type |
| `var e = String::length;` | method reference needs an explicit target-type |
| `var f = 1, g = 2;` | 'var' is not allowed in a compound declaration |
| `var h[] = new int[3];` | 'var' is not allowed as an element type of an array |
| `var i = i + 1;` | cannot use 'var' on self-referencing variable |
| `var j = voidMethod();` | variable initializer is 'void' |
The exact wording varies between JDK versions, but the reasons stay the same.
No initializer
var a;
a = 10;You might expect the compiler to look ahead and see that a receives an int. It does not. Inference works from the declaration alone. The compiler would otherwise have to analyze every assignment and every branch, and different assignments could suggest different types. Java avoids that by requiring the initializer at the point of declaration.
The fix is to give the variable an initializer, or to write the type yourself:
int a;
a = 10;This also covers the common pattern where you declare a variable before a switch or try block and assign it inside. For that pattern, keep the explicit type.
null and void
null belongs to every reference type, so it tells the compiler nothing about which type you want. A void method call has no value at all, so there is no type to take.
var b = null; // error
var j = System.out.println("hi"); // error: initializer is 'void'If you really want a typed variable that starts as null, state the type:
String name = null;
var alsoName = (String) null; // compiles, but the explicit declaration is clearerThe cast version is legal. In practice, String name = null; is easier to read.
Array initializers
The braces form {1, 2, 3} is not an expression on its own. It is a shorthand that is only valid in a declaration with an array type already written, or after new int[]. With var there is no array type written, so the compiler has nothing to apply the shorthand to.
var c = {1, 2, 3}; // error
var ok = new int[] {1, 2, 3}; // int[]The form var c[] = ... and the form var[] c = ... are both rejected. var stands for the whole type, so it cannot be an array element type. Let the initializer decide whether the variable is an array.
Lambdas and method references
A lambda such as () -> 42 has no type of its own. Its type comes from a target type, such as Supplier<Integer> or Callable<Integer>, that the surrounding context provides. The same lambda body fits several functional interfaces. A var declaration supplies no target type, so the compiler cannot pick one. Method references behave the same way.
The fixes are to declare the functional interface, or to cast the lambda so the cast supplies the target type:
import java.util.function.Function;
import java.util.function.Supplier;
public class VarFixes {
public static void main(String[] args) {
Supplier<Integer> d = () -> 42;
var d2 = (Supplier<Integer>) () -> 42; // legal, but the first form is easier to read
Function<String, Integer> e = String::length;
var f = 1;
var g = 2;
var ok = new int[] {1, 2, 3};
String name = null;
System.out.println(d.get() + d2.get()); // 84
System.out.println(e.apply("hello")); // 5
System.out.println(f + g + ok.length); // 6
System.out.println(name); // null
}
}Prefer the explicit declaration for lambdas. The cast compiles, but it adds noise and saves nothing.
Several declarators on one line
var f = 1, g = 2; // errorJava allows int f = 1, g = 2; because both variables share one declared type. With var, each initializer could produce a different type, so the compiler would have to decide how to combine them. The language rules this out. Declare each variable on its own line.
Self-reference
var i = i + 1; // error: cannot use 'var' on self-referencing variableTo infer the type of i, the compiler must first type the initializer. The initializer mentions i, whose type is not known yet. Even in an ordinary int i = i + 1; the variable would be unassigned at that point. With var, the compiler stops earlier, because the type itself depends on the type.
Positions where var cannot appear
var is only for local variables. That means ordinary local declarations, both kinds of for loop variable, and try-with-resources variables. Lambda parameters are a separate case, covered in a later chapter. Everywhere else it is rejected with "'var' is not allowed here".
import java.util.List;
public class VarPositions {
// var field = 10; // error: fields need explicit types
// static var make() { return 1; } // error: return types need explicit types
// static void use(var x) { } // error: method parameters need explicit types
public static void main(String[] args) {
// List<var> items = null; // error: var is not a type argument
// try { } catch (var e) { } // error: catch parameters need explicit types
var items = List.of("a", "b");
System.out.println(items);
}
}The reasons differ by position:
- Fields, method parameters, and return types form the public contract of a class. Callers and other source files depend on them. Inferring them from a method body or a field initializer would make the contract change whenever the code behind it changed.
- Type arguments such as
List<var>would require inference of a part of a type, andvaronly stands for a whole type. - Catch parameters may use a multi-catch such as
catch (IOException | SQLException e). There is no single initializer to infer a type from.
Note that var is not rejected in an enhanced for or in try-with-resources. Those are allowed contexts, because each has an expression the compiler can read the type from.
Inference that succeeds but surprises you
Some declarations compile without complaint but give a different type than you intended. These are the quieter failure mode.
import java.util.ArrayList;
public class VarSurprise {
public static void main(String[] args) {
var list = new ArrayList<>(); // ArrayList<Object>, not a compile error
list.add("text");
list.add(42); // also compiles
System.out.println(list); // [text, 42]
var total = 0; // int
// total = 1.5; // would not compile: double to int loses precision
}
}With no target type, new ArrayList<>() infers ArrayList<Object>. The compiler then accepts anything you add. Write new ArrayList<String>() when you want a typed list.
The same applies to numeric literals. var total = 0; is an int. If you later want to store a long or a double, the compiler reports an error at the assignment, and the declaration is the real cause. Write 0L or 0.0 when you need another type.
Fixing a rejected declaration
When the compiler rejects a var, use this order:
- Check whether the position is allowed at all. If it is a field, parameter, or return type, use an explicit type.
- Check whether you can write an initializer that carries the type, such as
new int[] {...}ornew ArrayList<String>(). - If the initializer needs a target type, as lambdas and method references do, declare the type explicitly.
- If you are declaring before assigning, declare the type explicitly.
Exercise
Each line below fails to compile. For each one, say why, and give a corrected line that keeps the intended meaning. 1) var count; count = 5; 2) var names = {"Ada", "Alan"}; 3) var greet = name -> "Hello " + name; 4) var x = 1, y = 2;
Show answer
1) There is no initializer, so nothing can be inferred. Write int count = 5;.
2) An array initializer needs an explicit array type. Write var names = new String[] {"Ada", "Alan"};.
3) A lambda needs a target type that var does not provide. Write Function<String, String> greet = name -> "Hello " + name;.
4) var does not allow multiple declarators. Write var x = 1; and var y = 2; on separate lines.