Sub topic 2
Declaring Variables with var
What this chapter assumes
You should already be comfortable declaring local variables with explicit types such as int, String, and List<String>. You should also know the basics of generics, the diamond operator <>, enhanced for loops, and lambdas. This chapter covers the var declaration itself: its syntax, what it does, and what it does not do. Later chapters cover the inference rules, the allowed and rejected contexts, and style guidance in more depth.
The starting point: an explicit type on every local
Before Java 10, every local variable needed a type written on the left side of the declaration:
ArrayList<Integer> scores = new ArrayList<Integer>();The type appears twice. The diamond operator (Java 7) removed the repetition on the right side, but the left side still had to name the type in full. For long generic types this adds noise without adding information, because the initializer already says what the variable holds.
Java 10 added var so you can leave the type out when the compiler can work it out from the initializer:
var scores = new ArrayList<Integer>();The syntax
A var declaration has the same shape as any local declaration. You write var where the type would go, then a name, then = and an initializer.
import java.util.ArrayList;
import java.util.HashMap;
public class VarBasics {
public static void main(String[] args) {
var count = 10; // int
var name = "Ada"; // String
var scores = new ArrayList<Integer>(); // ArrayList<Integer>
scores.add(count);
var byName = new HashMap<String, Integer>();
byName.put(name, scores.get(0));
System.out.println(byName); // {Ada=10}
}
}The compiler gives each variable the static type of its initializer. count is an int, name is a String, and scores is an ArrayList<Integer>. The call scores.get(0) returns an Integer because the compiler knows the element type, exactly as it would with an explicit declaration.
You can combine var with the final modifier and with annotations on local variables:
public class VarFinal {
public static void main(String[] args) {
final var limit = 5;
// limit = 6; // does not compile: limit is final
var total = 0;
for (var i = 0; i < limit; i++) {
total += i;
}
System.out.println(total); // 10
}
}The final modifier works as usual. The variable total is not final, so you can assign to it again. Only the type is inferred. Everything else about the variable follows the normal rules.
The variable still has a fixed static type
var does not make Java dynamically typed. The compiler decides the type once, at the declaration, and checks every later use against it.
public class VarStaticType {
public static void main(String[] args) {
var count = 10;
count = 20; // fine: int to int
// count = "twenty"; // does not compile: String cannot be converted to int
// count = 2.5; // does not compile: possible lossy conversion from double to int
System.out.println(count); // 20
}
}Compare this with var in JavaScript, or with auto in C++ and let in Rust. In JavaScript, var means no static type at all. In Java, the type exists and is checked. You just did not write it. A good mental model is that the compiler takes your source and fills in the type for you, then compiles the result.
The initializer is the only source of the type
The compiler infers the type from the initializer only. It does not look at how the variable is used later. This is why the following does not work:
public class VarNoLookahead {
public static void main(String[] args) {
// var total; // does not compile: cannot infer type, no initializer
// total = 10;
}
}Some languages infer a type from later assignments. Java does not. If you cannot write an initializer, write the type explicitly.
The initializer can be any expression with a type: a literal, a constructor call, a method call, an arithmetic expression, or a ternary.
import java.util.List;
public class VarInitializers {
public static void main(String[] args) {
var text = String.valueOf(42); // String, from a method return type
var sum = 3 + 4; // int, from arithmetic
var size = List.of("a", "b").size(); // int
var label = size > 1 ? "many" : "one"; // String
System.out.println(text + sum + size + label); // 4272many
}
}Two cases fail even though they have an initializer. A void method call has no value to take a type from, and a variable cannot refer to itself in its own initializer:
public class VarBadInitializers {
static void log() { }
public static void main(String[] args) {
// var result = log(); // does not compile: void has no type to infer
// var x = x + 1; // does not compile: self-referencing variable
}
}var is a reserved type name, not a keyword
var is not a keyword in the strict sense. It is a reserved type name. The compiler treats it specially only where a type is expected in a local variable declaration. This was done so that old code using var as an identifier would keep compiling.
- You can still name a variable, method, or package
var. - You cannot name a class, interface, enum, or type parameter
var.
public class VarAsName {
public static void main(String[] args) {
var var = "legal but confusing"; // type position is var, name is var
System.out.println(var);
}
}This compiles, but you should never write it. The point is that adding var in Java 10 did not break existing programs. Only code that had a type named var broke, and Java naming conventions made those very rare.
No runtime cost and no change in semantics
var exists only in source code. The compiler replaces it with the inferred type, so the bytecode for var count = 10; is the same as for int count = 10;. There is no extra object, no reflection, and no runtime lookup. You can confirm this by compiling a class and running javap -c on it. The instructions are identical in both versions.
Two consequences follow:
- Performance does not change.
varis purely a source-level convenience. - Debuggers and
javap -lshow the real inferred type, so you can always find out what the compiler chose. In an IDE, hovering over the variable shows it too.
Common errors
| Mistake | Example | Why it fails |
|---|---|---|
| No initializer | `var a;` | Nothing to infer from |
| Initializer is `null` | `var b = null;` | `null` has no usable type |
| Reassigning another type | `var n = 1; n = "x";` | The static type is fixed as `int` |
| Self-reference | `var x = x + 1;` | The type of `x` is needed to compute its own type |
| `void` initializer | `var r = log();` | `void` is not a type of a value |
| Naming a class `var` | `class var {}` | `var` is a reserved type name |
The first, second, and last rows are covered further in later chapters on rejected contexts.
Summary of the rules
varreplaces the type in a local variable declaration, and the compiler infers it from the initializer.- The variable has a fixed static type from that point on, and the compiler checks every later use against it.
- An initializer is required, and it must have a usable type.
finaland annotations still work, and only the type is inferred.varis a reserved type name, so it is not allowed as a class name but is allowed as a variable name.- The bytecode is the same as with an explicit type.
Exercise
Given var n = 5;, does the statement n = 5.5; compile? Explain what the compiler does with this declaration, and say what the bytecode would look like compared to int n = 5;.
Show answer
It does not compile. The compiler infers int from the literal 5 and fixes it as the static type of n. Assigning the double value 5.5 to an int is a possible lossy conversion, which is an error. The bytecode is the same as for int n = 5;, because var exists only in source code.
Exercise
Which of these declarations compile? (a) var a = new ArrayList<String>(); (b) var b; (c) var c = 1; c = 2; (d) final var d = "x"; (e) var e = System.out.println("hi");
Show answer
(a), (c), and (d) compile. (b) has no initializer, so there is nothing to infer from. (e) fails because println returns void, which gives the compiler no type for the variable.