Page 1 of 1

About Question enthuware.ocajp.i.v7.2.849 :

Posted: Thu Jun 16, 2016 1:40 pm
by Zagrafh
Hello, having some problems with the "unreachable code" topic :
public class TestClass {
public static void main(String[] args) throws Exception {
String[] sa = {"a", "b", "c"};
for(String s :sa){
if("b".equals(s)) continue;
System.out.println(s);
if("b".equals(s)) break;
System.out.println(s+" again");
}
}
}
In the 2nd iteration , when "b".equals(s) is true , the if executes "continue" , right? so it goes to the 3rd iteration, but...

why isn“t the rest of the code unreachable, ending in a compilation fail ?:
System.out.println(s);
if("b".equals(s)) break;
System.out.println(s+" again");

Re: About Question enthuware.ocajp.i.v7.2.849 :

Posted: Thu Jun 16, 2016 3:52 pm
by admin
Because the compiler doesn't execute any code. It doesn't know that "b".equals(s) is true. It is the JVM that executes the code.
Here is a good discussion about unreachable code: http://www.coderanch.com/t/662554/ocajp ... hable-code