Sample code:
Compilation error:
The final local variable flag may already have been assigned
final boolean flag;
while (flag = false) { // I am using = instead of == just to test it
System.out.println("inside loop");
}
Compilation error:
Unreachable code
final boolean flag = false;
while (flag) {
System.out.println("inside loop");
}
I know:
- The local variable must be initialized before its first use.
- As per the coding standard the final local variable must be initialized at the time of declaration.
Questions:
- What is the difference between these statements? As per my understanding both are same.
- Why first sample code doesn't talk about unreachable code. The second compilation error is clear to me.
If works fine with if
condition
final boolean flag;
if (flag = false) { // no compilation error
System.out.println("inside if block");
}
If works fine if I add a break
statement in the while
loop that ensures the compiler that the final
local variable can be initialize just one in its life.
final boolean flag;
while (flag = false) {
System.out.println("inside if block");
break;
}