Search code examples
javajavac

Local variable might already have been assigned


I know there are a couple of questions on stackoverflow dealing with the problem of already initialized variables but I could not find anything answering my question with regards of local variables. Consider the following excerpt:

public class Test {


    public static void main() {
        final int i;

        try {
            i = computeI();
        } catch (Exception e) {
            i = 5;
        }
    }


    private static int computeI() throws Exception {
        return 3;
    }
}

The java compiler (openjdk-8-jdk) tells me i = 5 Variable i might already have been initialized but there is no way where i could have been assigned.

Question: Is there a way how i could have been initialized that a do not know of (since it's a local variable another thread cannot interfere to my knowledge). If not, why does the compiler issue this warning?


Solution

  • Java compiler follows Java Language Specification.

    Your question is answered by the following parts of the spec:

    https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4

    https://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html#jls-16.2.15

    Basically there are no rules describing types of Exceptions that you catch and location of assignment within try block.

    Also imagine if an Error happened inside try block (will not be caught by catch Exception), then i will still be unassigned after try statement. So even if the compiler was smart enough to see that i is unassigned in the catch block it would still need to complain about unassigned final variable.