Sub topic 10
No runtime cost and no dynamic typing
This chapter assumes you can declare local variables, read a basic stack trace and run javac and java from a terminal. You should also know the difference between a variable's declared type and the class of the object it refers to. Earlier chapters covered the syntax of var. This one covers what var does not do, which clears up two common misunderstandings: that it costs something at run time, and that it makes Java dynamically typed.
What happens at compile time
var is an instruction to the compiler. When javac reads var count = 10;, it works out the type of the initializer (int), and it treats the declaration as if you had written int count = 10;. After that point the compiler no longer sees var. The class file it writes has no trace of the keyword.
Two consequences follow from this:
- The JVM executes the same instructions it would for an explicit declaration. There is nothing to interpret or look up at run time.
- Everything the compiler checks for an explicit type, it checks for the inferred one.
Checking the bytecode yourself
You can verify this with javap, the class file disassembler that ships with the JDK. Write two classes that differ only in how the variable is declared.
import java.util.ArrayList;
public class Explicit {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Ada");
System.out.println(names.size());
}
}import java.util.ArrayList;
public class Inferred {
public static void main(String[] args) {
var names = new ArrayList<String>();
names.add("Ada");
System.out.println(names.size());
}
}Compile both with debug information and disassemble them:
javac -g Explicit.java Inferred.java
javap -c -l Explicit
javap -c -l InferredThe -c option prints the instructions. The -l option prints the line number table and the local variable table. The instruction sequences are the same: a new of java/util/ArrayList, an invokevirtual for add, and an invokevirtual for size. The local variable table lists names with the descriptor Ljava/util/ArrayList; in both classes. The class Inferred never mentions var anywhere in its bytecode.
A class file records the type of a local variable only for debuggers and only when you compile with -g. Neither affects program behavior.
No performance difference
Because the bytecode matches, var has no run-time cost. It does not box values, add casts, or add indirection. The one place where performance might differ is the choice of type that var infers, and that is a type you could have written yourself.
public class VarNoBoxing {
public static void main(String[] args) {
var total = 0; // int, not Integer
for (var i = 0; i < 1_000; i++) {
total += i;
}
System.out.println(total); // 499500
}
}Both total and i are primitive int variables. Boxing would only occur if the initializer's type were Integer, for example var boxed = Integer.valueOf(0);. In that case the variable is an Integer for the same reason Integer boxed = Integer.valueOf(0); would be.
Static typing is unchanged
A variable declared with var has exactly one type for its whole lifetime. It is fixed at the declaration and cannot change later. This is the most important difference between Java's var and the variable declarations in dynamically typed languages such as JavaScript or Python.
public class VarFixedType {
public static void main(String[] args) {
var value = 10; // int
value = 20; // fine
// value = "twenty"; // error: incompatible types: String cannot be converted to int
// value = 20L; // error: incompatible types: possible lossy conversion from long to int
System.out.println(value);
}
}The two commented-out assignments are rejected by javac with the same messages you would get if you had written int value = 10;. The assignment value = 20L shows that ordinary conversion rules still apply. A long does not narrow to int without a cast.
Method calls are also checked at compile time against the inferred type:
import java.util.ArrayList;
public class VarMethodCheck {
public static void main(String[] args) {
var names = new ArrayList<String>();
names.add("Ada");
// names.add(42); // error: incompatible types: int cannot be converted to String
// names.fly(); // error: cannot find symbol
System.out.println(names.get(0).length()); // 3
}
}The call names.get(0).length() compiles because the compiler knows get returns String. It would not know that if var meant "any type".
Comparison with dynamic typing
| Question | Java `var` | Dynamically typed variable |
|---|---|---|
| When is the type decided? | At compile time, from the initializer | At run time, from the current value |
| Can the variable later hold a different type? | No | Yes |
| Where is a wrong method call reported? | Compile error | Run-time error |
| Does the class file record the type? | Yes, as a concrete type | Not applicable |
| Can a variable exist without an initializer? | No, with `var` | Yes |
The last row is why var x; is rejected. The compiler has nothing to infer from, and Java has no later point at which it would decide.
The variable is not Object
A frequent misreading is that var means "some kind of Object". It does not. The inferred type is as specific as the initializer's type, which is often more specific than what you would normally write.
import java.util.ArrayList;
import java.util.List;
public class VarVsDeclared {
public static void main(String[] args) {
List<String> declared = new ArrayList<>();
var inferred = new ArrayList<String>();
System.out.println(declared.getClass().getName()); // java.util.ArrayList
System.out.println(inferred.getClass().getName()); // java.util.ArrayList
inferred.ensureCapacity(100); // compiles: the static type is ArrayList<String>
// declared.ensureCapacity(100); // does not compile: the static type is List<String>
}
}The run-time class of the object is java.util.ArrayList in both cases, because new ArrayList creates it. What differs is the static type, which controls which members the compiler lets you use. With var, the static type matches the initializer's type, so ensureCapacity is visible.
Reassignment and polymorphism
Because the static type is the initializer's type, a later assignment must fit that type. It does not need to fit a supertype you had in mind.
public class VarPolymorphism {
interface Shape { double area(); }
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
}
public static void main(String[] args) {
Shape declared = new Circle(1);
declared = new Square(2); // fine: both are Shapes
var inferred = new Circle(1);
// inferred = new Square(2); // error: incompatible types: Square cannot be converted to Circle
System.out.println(declared.area() + " " + inferred.area());
}
}This example uses records, so it needs Java 16 or later. If you want the variable to be reassignable to different subtypes, declare it with the supertype. This is a case where an explicit type is the right choice and var would not work.
Where the inferred type can change
The inferred type is computed every time you compile. If the initializer is a method call and the method's return type changes, the inferred type changes with it, and no source line in the caller changes.
public class VarEvolution {
static java.util.List<String> load() {
return new java.util.ArrayList<>();
}
public static void main(String[] args) {
var items = load(); // today: List<String>
items.add("a");
System.out.println(items);
}
}If a maintainer later changes load() to return ArrayList<String>, then items becomes an ArrayList<String> after recompilation. The call items.add("a") is then compiled as an invokevirtual on the class instead of an invokeinterface on the interface. For most code this is harmless. It can matter in two situations:
- A later line in the caller starts compiling against a different overload, because the static type now matches a more specific method.
- A caller compiled earlier against the old return type is a different class file from one compiled now. Recompile callers when you change signatures, as you would anyway.
With an explicit declaration like List<String> items = load();, the variable keeps its declared type while the method changes underneath it. This is one more case where an explicit type documents an intent that var leaves implicit.
Types that cannot be written down
There is one place where var gives you something an explicit declaration cannot. Some types have no name you can write, such as the type of an anonymous class instance. var captures the exact type, so its members are available.
public class VarAnonymous2 {
public static void main(String[] args) {
var counter = new Object() {
int hits = 0;
void hit() { hits++; }
};
counter.hit();
counter.hit();
System.out.println(counter.hits); // 2
}
}This is still compile-time inference. The compiler knows the anonymous class and its members. The bytecode refers to that class by its generated name, such as VarAnonymous2$1.
Common errors and what they mean
- "Cannot infer type for local variable" means the compiler has nothing to infer from, as in
var x;orvar y = null;. This is not a limitation of the type system, since Java would need to guess. - "Incompatible types" after a
vardeclaration means you assigned a value that does not fit the inferred type. Check the type the initializer produces, then either change the value or declare the type explicitly. - A method is "not found" on a
varvariable usually means the inferred type is narrower or different than you assumed, for examplevar x = 1;givesint, which has no methods. - A
varvariable of typeArrayList<Object>usually comes fromnew ArrayList<>()with no type argument. The diamond has no target type undervar, so it infersObject.
Exercise
A colleague says that var data = 5; followed by data = "five"; will work, because var lets the variable hold whatever you give it. Is that correct? Explain what the compiler does and what error you would see.
Show answer
It is not correct. At compile time the compiler infers int from the literal 5, so data is an int for its whole lifetime. The assignment data = "five"; is rejected with an error such as "incompatible types: String cannot be converted to int". The variable is statically typed exactly as if int data = 5; had been written, and nothing about var appears in the bytecode.
Exercise
You write var list = new ArrayList<String>(); and your teammate writes List<String> list = new ArrayList<>();. Both objects have the same run-time class. Name one operation that compiles for one variable but not the other, and say why.
Show answer
list.ensureCapacity(100) compiles only with var. The static type of the var variable is ArrayList<String>, which has ensureCapacity. The static type of the teammate's variable is List<String>, which does not. The run-time class (java.util.ArrayList) is identical, so the difference lies only in what the compiler allows.