Java never lets a program read a local variable that has not been given a value, and
never lets a final variable be assigned twice. The compiler proves both
with a flow analysis called definite assignment (JLS chapter 16). The analysis
is deliberately simple: it does not evaluate conditions, except for constant
expressions, so it can reject code that would in fact be safe.
The two rules
| Rule | Applies to | Error when broken |
|---|---|---|
| A variable must be definitely assigned (DA) before every read | Local variables, and blank final fields in constructors and initialisers | “variable might not have been initialized” |
A final variable must be definitely unassigned (DU) before every assignment | Blank final local variables and fields | “variable might already have been assigned” |
Fields that are not blank finals, array components and parameters always have a
value, so they are not checked. A read means any use of the variable’s name except as
the left side of a simple = assignment.
int x;
if (flag) x = 1;
System.out.println(x); // error: x might not have been initialized
int y;
if (flag) y = 1; else y = 2;
System.out.println(y); // fine: assigned on both branches
final int z;
z = 1;
z = 2; // error: z might already have been assigned
Conditions and boolean operators
For boolean expressions the analysis tracks two states: what is assigned when the expression is true, and when it is false (JLS 16.1):
a && b: a variable is DA when true if it is DA afteraor afterbwhen they are true; DA when false only if it is DA whenais false and whenbis false.a || b: the mirror image.!a: swaps the two states.- The constant
truecounts as assigning every variable “when false”, because that case cannot happen;falsethe same “when true”.
int n;
if (s != null && (n = s.length()) > 0) {
use(n); // fine: n is assigned when the condition is true
}
int k;
while (true) {
k = read();
if (k >= 0) break;
}
use(k); // fine: the loop only ends through the break, after k = read()
Statements
| Statement | A variable is DA after it when |
|---|---|
if (e) S1 else S2 | DA after S1 and after S2 |
if (e) S | DA after S and DA after e when false |
while (e) S | DA after e when false, and before every break out of the loop |
do S while (e); | DA after e when false, and before every break |
switch | DA at the end of every rule or the last group, and before every break; for a switch without a default that is not exhaustive, also DA after the selector |
try … catch | DA after the try block and after every catch block |
try … finally | DA after the try (and catches), or DA after the finally block |
A statement that cannot complete normally (return, throw, break, continue, yield) | Always: every variable counts as DA (and DU) after it, since nothing follows |
Inside a catch block, a variable assigned in the try block is not DA,
because the exception may have come first. A final variable assigned in
a loop body is not DU on the next iteration, so it cannot be assigned there.
Switch expressions and yield
A variable is DA after a switch expression if it is DA before every
yield and at the end of every expression rule; for a boolean switch
expression, the analysis tracks the true and false states of each result, as for
? :.
final String kind;
switch (code) {
case 1 -> kind = "one";
case 2 -> kind = "two";
default -> throw new IllegalArgumentException();
}
use(kind); // fine: every path assigns kind exactly once
Blank final fields
- A blank
finalstatic field must be DA at the end of the static initialisers and static field initialisers, in textual order, and DU before its one assignment. - A blank
finalinstance field must be DA at the end of every constructor that does not start withthis(…), taking the instance initialisers into account. A constructor that callsthis(…)must not assign it, since the other constructor already does. - Inside the constructors and initialisers, a blank final field may be read, by its
simple name or as
this.x, only once it is DA. Reading it from a method that the constructor calls is not checked, and can see the default value. - A lambda body in a constructor or initialiser may read a blank final field only if it is DA before the lambda expression.
class Temperature {
private final double kelvin;
Temperature(double celsius) {
if (celsius < -273.15) throw new IllegalArgumentException();
kelvin = celsius + 273.15; // assigned exactly once on every normal path
}
Temperature() { this(20); } // must not assign kelvin
}
Lambdas, inner classes and effectively final
A local variable used in a lambda body, a local or anonymous class, or a
switch guard must be DA before that body, and must be
final or effectively
final. A variable declared without an initialiser can still be effectively final
if it is DU before each assignment:
String msg;
if (ok) msg = "done"; else msg = "failed"; // assigned once on each path
Runnable r = () -> System.out.println(msg); // fine: msg is effectively final
The complete rules (16.1 to 16.9)
In the table, “V is [un]assigned” means both statements hold separately, for “definitely assigned” and for “definitely unassigned”. “When true” and “when false” apply to boolean expressions: the state after evaluating it to that value.
| JLS | Construct | Rule |
|---|---|---|
| 16.1.1 | Boolean constant expression | V is [un]assigned after a constant true when false, and after a constant false when true (both vacuously). After a constant when it has its own value, V is [un]assigned iff it is [un]assigned before it |
| 16.1.2 | a && b | When true: as after b when true. When false: V is [un]assigned after a when false and after b when false. Before a: as before the expression. Before b: as after a when true |
| 16.1.3 | a || b | When false: as after b when false. When true: after a when true and after b when true. Before b: as after a when false |
| 16.1.4 | !a | When true: as after a when false. When false: as after a when true. Before a: as before !a |
| 16.1.5 | a ? b : c | Boolean b and c: when true, after b when true and after c when true; when false, likewise. Other b and c: after b and after c. Before a: as before the expression; before b: after a when true; before c: after a when false |
| 16.1.6 | switch expression | Before the selector: as before the expression. Guards: after the selector. With boolean results and statement groups, V is DA when true iff DA after every yield expression when true (and DU likewise, adding DU before the yield). With switch rules, each rule’s expression, or each yield in its block, or a throw, must satisfy the same. Non-boolean results: V is [un]assigned before every yield that may exit and after every rule’s expression, block or throw. Group and rule starts: as after the selector, and after the preceding group’s last statement for groups other than the first |
| 16.1.7 | Other boolean expressions | After e when true and when false: as after e |
| 16.1.8 | a = b, a op= b | DA after iff a is V or V is DA after b. DU after iff a is not V and V is DU after b. Before a: as before the expression; before b: after a |
| 16.1.9 | ++a, --a, a++, a-- | DA after iff a is V or V is DA after the operand. DU after iff a is not V and DU after the operand |
| 16.1.10 | Other expressions | No subexpressions: V after as before. Otherwise V after is V after the rightmost immediate subexpression. Each subexpression’s “before” is the state after the one to its left, or before the expression for the leftmost. Method arguments and array dimensions follow the same left-to-right pattern, after a primary target or a qualifying object |
| 16.1.10 | Lambda expression | V after as V before. V is DA before the body iff DA before the lambda. No rule lets V be DU before a lambda body |
| 16.2.1 | Empty statement | V after as V before |
| 16.2.2 | Block | Empty: V after as before. Otherwise V after as after the last statement, and each statement’s “before” as after the previous one; the first as before the block. A blank final member field is DA before a method body and before any class declared in its scope. A local declared by a statement is DU, not DA, before the body containing it. V is DA before bodies of a class C’s methods and initialisers iff DA before C |
| 16.2.3 | Local class or interface | V after as V before |
| 16.2.4 | Local variable declaration | Without initialisers: V after as before. With some: DA after iff DA after the last initialiser or the last is in V’s declarator; DU after iff DU after the last initialiser and the last is not in V’s declarator. An initialiser’s “before” is after the one to its left |
| 16.2.5 | L: S | V after iff V after S and V [un]assigned before every break that may exit it. Before S: as before the statement |
| 16.2.6 | Expression statement e; | V after as after e; before e as before |
| 16.2.7 | if (e) S and with else T | if: V after iff after S and after e when false. if-else: after S and after T. Before S: after e when true; before T: after e when false |
| 16.2.8 | assert e1 [: e2] | DA after iff DA before. DU after iff DU before and DU after e1 when true. Before e2: after e1 when false |
| 16.2.9 | switch statement | V after iff V [un]assigned before every break that may exit; after every rule’s expression, block or throw; after the last block statement of the last group if any; and, if the switch is not exhaustive or ends with a label before }, after the selector. Selector, guards, rule bodies and groups: as for the expression form |
| 16.2.10 | while (e) S | V after iff after e when false and V [un]assigned before every break targeting it. DA before e: DA before the statement. DU before e: DU before the statement, and DU after S and before every continue, assuming DU before e. Before S: after e when true |
| 16.2.11 | do S while (e); | V after iff after e when false and before every break. DA before S: DA before the statement. DU before S: DU before the statement, and DU after e when true, assuming DU before S. Before e: after S and before every continue |
| 16.2.12 | for (init; e; update) S | V after iff (no condition, or after e when false) and before every break. DA before e: after init. DU before e: DU after init and, assuming DU before e, DU after update. Before S: after e when true, or, with no condition, before the condition part. Before update: after S and before every continue. The init and update parts run their statements in order; an empty part leaves V as it was. The enhanced for needs no rules of its own |
| 16.2.13 | break, yield, continue, return, throw | V is vacuously [un]assigned after any of these, since none completes normally. Before the expression in yield e, return e or throw e: as before the statement |
| 16.2.14 | synchronized (e) S | V after iff after S. Before S: after e |
| 16.2.15 | try | Before the try block: as before the statement. DA before a catch block: DA before the try block. DU before a catch block: DU after the try block, before every return, after every throw e, after every assert, and before every break and continue in it that leaves the statement. Without finally: V after iff after the try block and every catch block. With finally: DA after iff (after the try block and every catch block) or after the finally block; DU after iff DU after the finally block; DA before finally: DA before the try; DU before finally: the catch conditions and DU after every catch block |
| 16.3 | Parameters | Formal and exception parameters are DA and not DU before the body |
| 16.4 | Array initialiser | Empty: V after as before. Otherwise V after as after the last element, and each element’s “before” as after the one to its left |
| 16.5 | Enum constant | V before the first argument: before the constant; each other argument: after the one to its left. V is DA before a constant’s class body iff DA after its last argument, or before the constant if there are none |
| 16.6 | Anonymous class | V is DA before the class iff DA after the creation expression that declares it |
| 16.7 | Member class | A blank final field of C is DA before any member class of C. For a class C within V’s scope, V is DA before a member class of C iff DA before C |
| 16.8 | Static initialisers | For a class C in V’s scope, V is DA before an enum constant or static variable initialiser of C iff DA before C. A blank static final field of C is DU before the leftmost static initialiser; each later one is as after the previous. A blank static final field from a superclass is DA and not DU |
| 16.9 | Constructors | For a class C in V’s scope, V is DA before a constructor or instance variable initialiser of C iff DA before C. A blank final field of C is DU before any constructor. Before the leftmost instance initialiser: DU iff DU after every superclass constructor call; DA iff every constructor has an explicit invocation and V is DA after every superclass call; later ones follow on. A superclass’s blank final field is DA before every instance initialiser. Inside a constructor: the prologue, constructor invocation and epilogue run in order. Before a call’s argument list: after the qualifier if there is one. After a super call a blank final of the superclass is DA; other variables are as after the argument list. After a this(…) call the blank finals of C and its superclasses are DA |