How should I understand this Java compiler behaviour?
while (true) return;
System.out.println("I love Java");
// Err: unreachable statement
if (true) return;
System.out.println("I hate Java");
// OK.
Thanks.
EDIT:
I find out the point after a few minutes:
In the first case compiler throws error because of infinite loop. In both cases compiler does not think about the code inside the statement consequent.
EDIT II:
What impress me on javac now is:
if (true) return; // Correct
}
while (true) return; // Correct
}
It looks like javac knows what is inside both loop and if consequent, but when you write another command (as in the first example) you get non-equivalent behaviour (which looks like javac forgot what is inside loop/if).
public static final EDIT III:
As the result of this answer I may remark (hopefully correct):
Expressions as if (arg) { ...; return;}
and while (arg) { ...; return;}
are equivalent both semantically and syntactically (in bytecode) for Java iff argv
is non-constant (or effectively final type) expression. If argv
is constant expression bytecode (and behaviour) may differs.
Disclaimer
This question is not on unreachable statements but different handling of logically equivalent expressions such as while true return
and if true return
.