0

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.

4
  • 1
    Probably because javac doesn't extrapolate b in first case Commented Oct 5, 2013 at 12:26
  • 2
    Why do you want either of these useless loops in your code to start with? Commented Oct 5, 2013 at 12:27
  • To partly explain this, the Java compiler (and the JVM's verifier, in a separate step) must trace the possible execution paths of code and determine all of the values that each variable can have at each point in the program. (This is done much more strictly than with other languages, for system integrity reasons.) If code is unreachable it can (though not in this case) create conflicts where meaningful data flow analysis cannot occur. So these situations are diagnosed as errors in all cases. Commented Oct 5, 2013 at 12:38
  • @JonSkeet I found this in an interview. Commented Oct 5, 2013 at 13:27

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

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.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.