Unreachable statement error in Java


how to fix Unreachable statement error in Java
Java Unreachable statement is an error according to the Java Language Spec . This error means that the control flow of your program can't get to that statement, but you assume that they would be. The compiler analyzes the flow, and reports these statements to you as error messages. It is a reliable indicators of logical error in your program. These statements might be unreachable mostly because of the following reasons:
  1. Return statement
  2. Infinite loop

Return statement

public bool myMessage() { return true; /* The implementation goes here */ }
In the above example, the return function will terminate your method, meaning no line of code past it will be executed . If you want your print to go through, you should move it above the return statement. If you keep any statements after the return statement those statements are unreachable statements by the controller. By using return statement we are telling control should go back to its caller explicitly .

Infinite loop

for(;;){ break; System.out.print("inside infinite loop"); }


java infinite loop The compiler is giving you an Unreachable statement error because your System.out.print("inside infinite loop"); code can never be reached with. When the compiler compiles the whole body of code and make byte code according to your code, it smarter enough to detects unreachable code and also dead code. So, immediate break in the for-loop makes unreachable other statements. When the compiler reports an unreachable statement , it typically points you to the statement. When that happens, you can follow the flow of control from top to bottom to discover why the statement can never be reached. There are quite strict rules when statements are reachable in java. These rules are design to be easily evaluated and not to be 100% accurate. It should prevent basic programming errors. To reason about reachability in java you are restricted to these rules, common logic does not apply. So here are the rules from the Java Language Specification 14.21. Unreachable Statements.