Search code examples
javacompiler-errorsfinal

Final variable assignment error


I dont know if this is a stupid question or not but please try to answer it.

public static void main(String[] args){
    int i=0;
    final int x;
    if(i==0){
        x=1;
        System.exit(0); 
    }
    x=2;
}

I have a final variable x.

Now to assign a value to x i have an if statement that assigns it and the exits the program.

Now the last statement is never reached and thus this program should compile logically.

x will have value 1 or 2 depending on the if statement. If the 'if' is true the last statement is not reached and if it is false the 'x=1' statement is never reached.

So why is this giving me a compile error of 'local' variable has been initialized?

EDIT:

yes i do obviously know that a final statement can be assigned only once.

what my doubt was that only one of those statements will be reached during execution so looking at it that way the program would have only one assignment statement.


Solution

  • x will have value 1 or 2 depending on the if statement. If the 'if' is true the last statement is not reached and if it is false the 'x=1' statement is never reached.

    This is not true, since you DONT have if followed by else.

    Also, Since System.exit(0) is merely a function call and not a different code path, the Java compiler assumes the code after it, to be very much reachable. See this thread for more clarity

    As far as the final variable is concerned, it cannot be assigned twice.

    The below code would work without error, since i==0 can be either true or false, and x gets assigned only once

        int i=0;
        final int x;
        if(i==0){
            x=1;
            System.exit(0); 
        }
        else {
            x=2;
        }