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

Moderator: admin

Post Reply
Zagrafh
Posts: 1
Joined: Fri May 06, 2016 12:35 pm
Contact:

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

Post by Zagrafh » Thu Jun 16, 2016 1:40 pm

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");

admin
Site Admin
Posts: 8621
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin » Thu Jun 16, 2016 3:52 pm

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
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests