Reputation: 13
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++;
}
}
Upvotes: 1
Views: 3425
Reputation: 44408
Remove the keyword final
. You cannot assign a value to the variable which is final
over again and again. You can not initialize the final
value in the for
or while
loop defined outside of the scope loop. Even the loop is called once, the compiler doesn not know in advance how many times the cycle would be called.
Upvotes: 3
Reputation: 28279
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.
Upvotes: 1
Reputation: 11
when you have instance variable declared
final int x;
x is assigned to 0. and final tag won't allow it to be changed.
while(y<=1) {
x=10; //Compile time error; even loop iterate only once.
y++;
}
inside while loop, you assign x to 10 which disobey the final rule.
Upvotes: 0
Reputation: 2343
In java, a final variable is a constant so you can not change its value. In your code above, x is final variable and I see that you are trying to change value of x. So you got compiler time error.
Upvotes: 1