Sub topic 9
var is a reserved type name, not a keyword
What you should already know
This chapter assumes you can declare local variables and know what var does at a basic level: it infers the static type of a local variable from its initializer. It also assumes you know that a Java identifier is any name you choose for a variable, method, class or package. The question here is a narrower one. What kind of word is var to the compiler, and what does that mean for existing code?
Keyword versus reserved type name
Java has a fixed list of keywords such as class, if, int and for. You can never use a keyword as a name. You can't write int class = 1; or a method called for.
var is not on that list. The Java Language Specification calls it a restricted identifier. In everyday terms, it is a reserved type name. The compiler gives var special meaning only when it appears where a type is expected. In every other position it is an ordinary identifier.
This matters because var arrived in Java 10, long after millions of lines of Java existed. Making it a true keyword would have broken any program that used var as a variable name, and that is a very natural name. The designers chose a rule that breaks as little as possible: you can't name a type var, but you can still name everything else var.
What is still allowed
The following code is legal, even though it looks confusing:
public class Config {
private final String var;
Config(String var) {
this.var = var;
}
String var() {
return var;
}
public static void main(String[] args) {
var config = new Config("value");
var var = config.var();
System.out.println(var.length()); // 5
}
}This one class uses var in four ways:
- A field called
var. - A constructor parameter called
var. - A method called
var(). - A local variable declared as
var var. The firstvaris the type position, so the compiler infersString. The second is the variable's name.
When the compiler reads var var = config.var();, it checks where each var appears. In the type position it applies the inference rule. In the name position it treats var as an identifier.
A second small program shows the same rule with reassignment and a method call:
public class VarNames {
static int var(int var) {
return var + 1;
}
public static void main(String[] args) {
var var = 10; // type int, name var
var = var(var); // method call, then assignment
System.out.println(var); // 11
}
}Package names follow the same rule. A package called var is legal, though nobody should create one.
What is rejected
The compiler rejects var wherever it would be used as the name of a type. That covers declaring a type and also several places where you might expect to write a type.
// None of these compile:
// class var {} // type declaration
// interface var {} // type declaration
// enum var { A } // type declaration
// record var(int x) {} // type declaration (Java 16+)
// @interface var {} // annotation type declaration
// class Box<var> {} // type parameter named var
// var[] arr = new int[3]; // var used as an array element type
// List<var> list = null; // var as a type argument
// Object o = (var) "x"; // var in a cast
// var field = 1; // field type (inside a class body)
// var method() { return 1; } // return type
// void m(var p) {} // method parameter typeThe compiler reports these with messages like "'var' not allowed here" or "'var' is not allowed here as of release 10". The wording differs between compiler versions.
The table groups the rules by where the word var appears.
| Position of `var` | Legal? | Meaning |
|---|---|---|
| Type of a local variable with an initializer | Yes | Inference |
| Type of a for, enhanced-for or try-with-resources variable | Yes | Inference |
| Parameter type in a lambda | Yes | Inference (all or none) |
| Name of a local variable, field, parameter or method | Yes | Plain identifier |
| Name of a package | Yes | Plain identifier |
| Name of a class, interface, enum, record or annotation type | No | Rejected |
| Name of a type parameter | No | Rejected |
| Type of a field, method parameter or return value | No | Rejected |
| Array element type, type argument or cast target | No | Rejected |
A useful way to remember it: var is accepted as a local type only where the compiler can infer the answer from an initializer or a lambda target. It is accepted as a name anywhere except where the name would define a new type.
Why this design and not a keyword
A new keyword breaks old code. Java kept source compatibility as a goal, so the designers looked for the smallest possible break. They weighed two facts:
- Java naming conventions say variables and methods start with a lowercase letter and types start with an uppercase letter. Code that follows them has no type called
var. - Plenty of real code has a variable, parameter or method called
var, for example in scripting-style code, or a field namedvarin a class modeling a variable.
Reserving var only as a type name breaks the first group (rare) and keeps the second group working (common). The same approach was reused later for words like yield, record, sealed and permits. Each is a contextual keyword that has special meaning only in certain positions.
Breaking old code
If your project contains a type named var, upgrading the source level to Java 10 or later makes it fail to compile. The type declaration is the error, not the places that use it.
// Compiles with --release 8 (possibly with a warning).
// Fails with --release 10 or later.
class var {
int x;
}The fix is to rename the class. Following the convention of capitalized type names (Var, Variable) avoids the problem entirely. Var with a capital V is a different identifier and is always legal.
Code that only uses var as a variable or method name needs no change.
Interaction with other modifiers
Because var takes the place of a type, everything that normally goes before a type still works:
import java.util.List;
public class VarModifiers {
public static void main(String[] args) {
final var names = List.of("a", "b"); // final applies as usual
@SuppressWarnings("unused")
var unused = names.size(); // annotations are allowed
System.out.println(names); // [a, b]
}
}With final var, the compiler infers the type and also forbids reassignment. Without final, a var variable can be reassigned, but only to a value compatible with its inferred type. The word var has no effect on mutability.
Common mistakes
- Treating
varas a type you can use anywhere. It is only a placeholder for local inference. It is not a type likeObjectand it is not a dynamic type. - Writing
varfor a field. Fields have no initializer-based inference in Java, so the compiler rejects it. Use the explicit type. - Naming a class
varin legacy code and expecting an upgrade to work. Rename the class first. - Assuming
var var = ...is an error. It is legal, though poor style. - Using
varas a generic type parameter name.class Box<var>is rejected. Use a conventional name likeT.
Exercises
Exercise
Which of these declarations does the compiler reject on Java 17? (a) int var = 5; (b) String var() { return "x"; } (c) class var {} (d) var var = 5;
Show answer
Only (c). A class named var declares a type with a restricted name. The other three use var as a variable name, a method name, and a type-then-name pair, and all of them are legal.
Exercise
A legacy file contains public class var { } and also uses a variable named var elsewhere. After moving the build to Java 17, which of the two must you change, and why?
Show answer
You must rename the class. A type declaration cannot be named var as of Java 10. The variable named var can stay, because var is an ordinary identifier in a name position.
Exercise
Why did the Java designers make var a reserved type name instead of a full keyword?
Show answer
A full keyword would have broken every existing program that used var as a variable, parameter, field or method name, which is common. Reserving it only as a type name breaks only code that defines a type called var, which is rare because Java types conventionally start with an uppercase letter.
Exercise
Explain what each var means in var var = "hello";, and give the type of the variable.
Show answer
The first var is in the type position, so the compiler infers the type from the initializer. The second var is the variable's name, an ordinary identifier. The variable's type is String.