Reputation: 53
I had the following lines of code
boolean b = false;
for (int i = 0; b; i++) {}
it executes well
now if I replace above code with
for (int i = 0; false; i++) {}
it gives -> java.lang.Error: Unresolved compilation problem: Unreachable code
why? please help.
Upvotes: 0
Views: 2060
Reputation: 11209
Sure! the loop body will never execute due to a false condition. As a result, the body of the loop and i++ is indeed unreachable. What's the point of doing that anyway?
Upvotes: 0
Reputation: 213331
Basically b
in your first code is not a compile time constant expression, whereas false
is. If you change the boolean variable in your first code to:
final boolean b = false;
it will too fail to compile, because now it's a constant expression, as value of b
can't be changed later on.
Upvotes: 8
Reputation: 16536
Compiler won't complain if you use a variable for the condition as it doesn't check which value will have when execution reach the loop (that's a work for the runtime), as opposite to hardcode a false
value.
Upvotes: 2
Reputation: 44448
The second parameter of your foreach loop is a condition. While this condition is true
, the loop will execute. If you give false
as the parameter, it will never execute and thus the code in it is unreachable.
The reason the first one works and the second doesn't is because the compiler didn't check the value (or can't sufficiently derive it) of b
, yet when you plainly use false
the condition is not ambiguous.
Upvotes: 4