Which of the following code snippets will compile without any errors?
Answer 1: while (false) { x=3; }
Explanation
while (false) { x=3; } is a compile-time error because the statement x=3; is not reachable;
I get a compile time error that states "x cannot be resolved". I do not get any compile time message stating the code is unreachable.
when I add the following line of code before this:
Never mind.... I got that compiler error. There was another compiler error having to do with a duplicate definition of "x" in my code that was being flagged first by the compiler....
The explanation says that "for( int i = 0; false; i++) x = 3; is also a compile time error because x= 3 is unreachable.", so, why the option is marked as correct (whith no compile errors).
I think, that the explanation is not very clear, especially the connection between
for( int i = 0; i< 0; i++) x = 3;
and
for( int i = 0; false; i++) x = 3;
is not obvious (for me).
I think, that the clue is that the compiler checks only compile-time constants:
for example:
This is OK:
boolean b = false;
for (int i = 0; b; i++) {x = 3;};
and this is unreachable code:
final boolean b = false;
for (int i = 0; b; i++) {x = 3;};
So, here:
for( int i = 0; i< 0; i++) x = 3;
because "i" is not a compile-time constant, the compiler will not check (or can not see?) unreachable code (however it is obvious for a human-eye to
detect unreachable code)
Technically, both contain unreachable statements and should not compile but the first one i.e. if(false) { } is made an exception. It is allowed explicitly by Java specification to allow conditional compilation, which is useful for writing log statements such as: