If I write
private void check(){
if(true)
return;
String a = "test";
}
Above code works normally, but if I write
private void check(){
return;
String a = "test";
}
The compiler/gradle in Android studio doesn't let this one through even though it's the same, and it says that the code after return in example 2 is unreachable.
I don't have any issues regarding this but I am eager to know why?
By definition, an unreachable statement is the one that will not be executed by a compiler when you run ready-to-deploy code. An unreachable code return statement is typically a sign of a logical error within the program.
These statements might be unreachable because of the following reasons: Have a return statement before them: When a return statement gets executed, then that function execution gets stopped right there. Therefore any statement after that wont get executed. This results in unreachable code error.
Unreachable Code Causes: Programming errors while developing complex conditional branches. Incomplete unit testing because of which unreachable code was undetected. Redundant code that developer forgot to delete. The code that might be programmatically correct but won't be executed at any point of time due to the input data ...
However, on a higher level, it is theoretically impossible to build a perfect unreachable code detector (which raises a compiler error at all unreachable code and doesn’t raise any error at reachable code) as that would be equivalent to solving the Halting problem.
javac
compiler does very little optimizations, so it simply does not "see" that if(true)
is always true
(but you should get a warning); but C1/C2 JIT compilers will - so that code will simply be a return
, without an if statement.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With