Why does the Java compiler not understand this variable is always initialized?

As part of aiming for portability, there is a very specific set of rules for what a compiler should accept and what it should reject. Those rules both permit and require only a limited form of flow analysis when determining whether a variable is definitely assigned at its use.

See the Java Language Specification Chapter 16. Definite Assignment

The critical rule is the one in 16.2.7. if Statements, “if (e) S” case. The rule for being definitely assigned expands to:

V is assigned after if (e) S if, and only if, V is assigned after S and V is assigned after e when false.

y is the relevant V. It is unassigned before the if statement. It is indeed assigned after S, y = {y=-1;} but there is nothing making it assigned when x>100 is false.

Thus y is not definitely assigned after the if statement.

A more complete flow analysis would determine that the condition x>100 is always true, but the compiler is required by the JLS to reject the program based on these specific rules.

The final variable is fine. The rule is actually: –

“It is a compile-time error if a final variable is assigned to unless
it is definitely unassigned (ยง16) immediately prior to the
assignment.”

The declaration leaves it definitely unassigned, and even the limited flow analysis can determine that x is still definitely unassigned at the assignment.

Leave a Comment