Skip to content
Advertisement

Variable might be assigned in loop?

I don’t know why the code is not compiling when final variable is initialized in loop and loop iterate only one time? Is Loop is somehow running more than one time and multiple assignments is done to variable x?

public static void main(String args[]) {

    int y;
    final int x;
    y=1;
    while(y<=1) {
        x=10;       //Compile time error; even loop iterate only once.
        y++;
    }
}

Advertisement

Answer

The compiler does not care how many times the code in the loop will be executed at run time. To prevent re-assignments that might happen, it is not allowed to assign final variables in a loop.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement