Unreachable Code in Java
It may sound stupid, but seriously, how helpful is it to have a compiler complaining about code which is unreachable ? Well, a lot.
Java comes with a promise of writing code which is easily understood and thus leading to easy maintainability. Not sure what I am referring to ? Think pointers. Pointers in programming language though made languages powerful ( C and C++) , It is a difficult situation to handle, ever for the experienced developers ( A developer is like "Hey hang on I see pointer to pointer to pointer, gotta understand this first" ) , Well Java did solve the problem.
The same is true about unreachable code. Java also came up with promise to handle unreachable code.
Let's explore a few of the possible cases when we might see unreachable code.
return ;
System.out.println("");
// if you return, how would the print do anything at all
boolean status=false;
if(x){
return true;
}else{
return false;
}
return status;
// well, with the if and else you covered all the branches , what would you do with something after?
Java, being intelligent here, tries to say that you actually have covered all the possible scenarios when you want to return true or false, having a default return is unnecessary. But consider this following code snippet.
boolean status=false;
if(x){
return true;
}else{
if(y){
System.out.println("something to do here");
}
}
return status;
// Do you think you covered all the branches ?
The above code is just fine.
Let's analyze the following two code snippets: the if block and the while block
// the if with false
if(false){
System.out.println("some");
}
// the while with false
while(false){
System.out.println("falsing");
}
Here, the if statement works without issues, but the while with false, will not work. It will complain about unreachable code.
Let’s explore more.
for(int i=0;i<10;i++){
System.out.println("do this ");
continue;
System.out.println("do this, don't see why");//what’s the point here?
}
But should I be stupid If I write this below ? No, there is nothing stupid about it. There are chances when the print code executes.
for(int i=0;i<10;i++){
System.out.println("do this ");
if(i==2){
continue;
}
System.out.println("I see a chance of running,so no stupidity");
}
Or how about this?
for(int i=0;i<10;i++){
System.out.println("do this ");
if(i==2){
continue;
}else{
break;
}
System.out.println("do this, and think");
}
Well it is unreachable, there is no case why you see the sys out should print.
for(int i=0;i<10;i++){
System.out.println("do this ");
if(i==2){
continue;
}else{
System.out.println("i am doing just fine here");
}
System.out.println("do this");
}
Now you know how awful it is to right code that is unreachable. It is completely unnecessary. It adds overheads to code generation and optimization phases of a compiler. Java is good enough to point out portions of your code that are unreachable. This helps the programmer to correct his logic as well as to improve compute performance!