-2

Got a practice question, and I have the below code:

while (false) { x=3; } 

The x=3 is unreachable code, and I don't really understand why. There is a similar section of code:

if (false) { x=3; } 

which is perfectly valid.

May be a bit of a noob question, or may be I'm just missing something, but if you could help me understand why that'd be great, thanks!

I am asking specifically about the difference between the if and while statement, because the same line of code changed to if, is valid and will compile.

9
  • Code is unreachable means the compiler deemed it that there cannot be no path to statement x=3; because while ( false )can never be true Commented Aug 9, 2016 at 11:32
  • The kicker is: neither can if(false). The real question is: why does the compiler not have problems with the if statement. Commented Aug 9, 2016 at 11:34
  • 1
    And for the second part of the question, refer to stackoverflow.com/a/8570302/1743880 Commented Aug 9, 2016 at 11:34
  • 1
    And refer to stackoverflow.com/questions/20299914/… also Commented Aug 9, 2016 at 11:35
  • 1
    Please refer to the above questions also. They explain this behaviour both for if and while statements, by referencing the Java specification. See stackoverflow.com/questions/20299914/… Commented Aug 9, 2016 at 11:37

1 Answer 1

1

Read below article it will answer your question: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21

while statement can complete normally iff at least one of the following is true:

o The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

o There is a reachable break statement that exits the while statement.

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.