This is explained by the Unreachable Statements part of the Java Language Specification.
There are quite a few rules, with an interesting special case. This is a compile time error :
while (false) {
// this code is unreachable
String something = "";
}
while this is not :
if (false) {
// this code is considered as reachable
String something = "";
}
The given reason is to allow some kind of conditional compilation, like :
static final boolean DEBUG = false;
...
if (DEBUG) { x=3; }
So in your case :
private void check(){
if(true)
return;
// NO compilation error
// this is conditional code
// and may be omitted by the compiler
String a = "test";
}
is not an error because of the special if
treatment, using while
instead is not accepted :
private void check(){
while(true)
return;
// "Unreachable statement" compilation error
String a = "test";
}
This is also en error :
private void check(){
if(true)
return;
else
return;
// "Unreachable statement" compilation error
String a = "test";
}
if(true)
in order to deduct the assignment isn't reachable. This simple case can be implemented, but it doesn't make much sense since the general case is probably equivalent to the halting problem. A cut had to be made somewhere. Doing this at the syntax level gives most benefit for little work – Comancheanif (DEBUG) { someDebugCode(); }
, whereDEBUG
is a constant defined as eithertrue
orfalse
. If it isfalse
the whole if body is unreachable but you don't want to be forced to remove it. – Teratoid