When there is some statement written after the infinite loop, that statement becomes the unreachable code. For ex:
for(;;)
{
}
Sytem.out.println("Test-1"); //unreachable code
But I am facing some difficulty here.
Look at the two code snippets below:
Code snippet1:
for(final int z=4;z<6;)
{
}
System.out.println("Test-2"); //unreachable code
Here, The last statement must be unreachable because the loop is infinite and the output is as expected.
Code Snippet2:
final int z=4;
for(;;)
{
if(z<2)
break;
}
System.out.println("Test-3"); //not unreachable
Conceptually, the for loop in above code is also infinite since z is final and if(z<2)
is determined at compile time only.The if condition will never be true and the loop will never break.
But, the Last statement in above code is not unreachable.
Questions:
Why this is happening ?
Can anyone tell me the exact rules by which we can see whether code is unreachable or not.
The key phrase in http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21 is:
Hence the compiler does not evaluate
z<2
in yourif()
statement, and does not know that it will never evaluate totrue
.This defines unreachable code as far as the Java spec is concerned. It's important that compilers adhere to to the spec, because changing the rules could make code that used to compile fail to compile.
However, compilers are free to give warnings rather than compilation errors.
If I type the following code into Eclipse:
... I get the warning "Dead code". The compiler knows the code can't be reached - but it can't refuse to compile, because the code is not formally "unreachable" according to the Java spec.
From http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21