Question

When I run the javac compiler on the following code -

void method() {
    final int x;
    x = 1;
    x = 1;  // (Intentional error)
}

I receive the following error -

..\src\pkgs\main\Main.java:60: error: variable x might already have been assigned
                x = 1;  // (Intentional error)
                ^

I wonder why this error message uses the word "might". Would a more accurate description use the word "has" instead, as in "has already been assigned"? Is there a particular reason why the compiler seems to use a kind of "vague description style" for this type of error? Thanks.

Was it helpful?

Solution

A final variable can only be assigned if it is definitely unassigned. That is, "might" is referring to the fact that the variable is not definitely unassigned:

Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs.

For instance, consider this code which makes the wording of "might" more clear:

final int x;
if (maybeTrueOrMaybeFalse()) {
   x = 1;
}
/* error: variable x might already have been assigned */
x = 1;

The standard Sun/Oracle javac compiler produces the same error message for the "might" (not definitely unassigned) and "has been" (definitely assigned) cases. A different compiler or code analysis tool could very well provide a different/refined message in the "has been" case.

OTHER TIPS

If you have initialized it when declaring, it would give you a precise message, e.g.

"The final local variable x cannot be assigned. It must be blank and not using a compound assignment"

final int x = 6;
// code
x = 4;

But, in your example, the final variable might have been initialized somewhere after it is declared and the compiler doesn't keep track of consecutive statements, otherwise it would be named "runner" and it just has the information that final variable x should not be initialized twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top