In this code there will be an unreachable code compiler error as "last" won't be reached if something happens and the if loop runs. Well unreachable statements are interesting and here we have to see the compiler's point of view. Compiler sees that the break is reachable but if it breaks a loop always which has some statements then those statements won't be reached.
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
ash aj wrote:The compiler does not give "unreachable" compiler error for the second code fragment i.e.
even though the code in if block and the sysout will never get executed. Why the complier is not able to detect this? What are the rules through which compiler detects the unreachable code?
Take a look at the link provided by Ninad again (second response).
A special rule applies for "if" statements -- basically, if the "if" statement is reachable, then it will be assumed that the code can complete. Meaning that the block inside the statement will run, regardless of the fact that the condition is always false.
This rule is needed in place of conditionally compile code, such as those needed for debugging statements.
So... since, the "if" can complete, the "break" is reachable, and hence, the code after the "while" loop is reachable.