Loops that cause unreachable code errors
The last loop does not compile because of “unreachable code”. The line System.out.println(y); can never be executed because the test condition is always false.
[sourcecode language=”java” toolbar=”false”]
for (int y=0; false ;y++){
System.out.println(y);
}
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
while (false) { x=3; }
[/sourcecode]
[sourcecode language=”java” toolbar=”false”]
for( int i = 0; false; i++) x = 3;
[/sourcecode]
NOTE THIS EXCEPTION:
[sourcecode language=”java” toolbar=”false”]
if(false){ x=3; }
[/sourcecode]
This code does not cause an unreachable code error.
In the following code snippet
[sourcecode language=”java” toolbar=”false”]
if(false){ x=3; }
[/sourcecode]
, although the body of the condition is unreachable, this is not an error because the JLS explicitly defines this as an exception to the rule. It allows this construct to support optimizations through the conditional compilation. For example,
[sourcecode language=”java” toolbar=”false”]
if(DEBUG){ System.out.println("beginning task 1"); }
[/sourcecode]
Here, the DEBUG variable can be set to false in the code while generating the production version of the class file, which will allow the compiler to optimize the code by removing the whole if statement entirely from the class file.
Leave a Reply