I tried it out and it compiles without error. So I tried it out with some code in the while part and managed to crash the compiler (reported it on http://bugreport.java.com as suggested by the compiler)
The compiler doesn't execute the code so it doesn't know that the code in the body will always cause the loop to break. That is why it cannot flag the unreachable error.
The compiler can only look at the compile time constant values to determine unreachable code.
but if I add a System.out.println(); after the break the compiler complains about it as unreachable code.
good discussion by the way, but I have no problem to just accept that java doesn't accept unreachable code, exept of if(false){ ... }. And in real life I would never ever write such a silly peace of code as mentioned in my first post. But since we have to know every tiny silliness and exception for the exam, I am wondering if this is another exception of the rule, a bug in the compiler or something completely different I hadn't thought about it until now.
Even I have the doubt : if I add a System.out.println(); after the break the compiler complains about it as unreachable code.
so in that case, the compiler knows about the break causing an unreachable statement. then why will the while() in the question not become unreachable ?
the answer the third says, "You cannot have break or continue in an 'if' or 'else' block without being inside a loop." but then goes on to give an if/else with a label before it and a break inside...which does compile. So it seems you can do it outside a loop you just need a label that is in scope, i.e. a label for the if statement. Is that correct?
Correct. The first statement of the explanation is talking about just the break statement (which is applicable only in a loop). The exception to this rule is the "labeled break" statement, which is valid in an if statement.
If you like our products and services, please help us by posting your review here.