How does a compiler decide on with unreachable code?
consider these
public class Test15 {
public static final boolean verdict = false;
public static final int verdictInt = 2;
public static void main(String[] args) throws IOException {
// case1
if (verdict) {
System.out.println(1);
} else {
System.out.println(2);
}// compiles
//case 2
int val = 5;
switch (val) {
case verdictInt:System.out.println(3);
break;
}// compiles
//case 3
while (false) {
}// does not compile
//case 4
return 6;
return 7;
//does not compile
}
}
So when the compiler decides that code is unreachable.Is it because of (for a lack of a better term) hard code(like case 4).Because as per my knowledge, verdict,verdictInt also qualify as compile time constants and according too. And as per my reading,being able to use the constant verdictInt as a switch case label indicates that it is a compile time constant.
Please let me know in case there are any basic flaws in my reasoning.
The Java Language Specification section on unreachable code is a good, but long read. I'll condense it into what translates for your question.
Case 1:
verdict
could be seen as a flag variable; it may or may not be used for debug purposes. If it is, then breaking compilation would result in a major design goal miss. The specification explicitly calls this out:Case 2:
Your
switch
statement can complete normally by the rules of the JLS:Your
switch
doesn't have adefault
label, so your switch can complete normally. It just falls out of the switch.Case 3:
This explicitly does not compile. Case 1 called some attention to it, but here it's spelled out, emphasis mine:
The condition expression is
false
, so you can't reach the contained statement, by definition.Case 4:
return
is a special case; it completes abruptly. Once a statement completes abruptly, any statements after that are not reachable by definition.