Java Reference
In-Depth Information
A Note on Unreachable Code
It is possible to have a while loop whose body never gets executed:
8. int x = 0;
9. while(x > 0) {
10. System.out.println(“Not here”);
11. }
However, you cannot write code that is unreachable or a compiler error is generated. For
example, the following code does not compile:
17. while(false) {
18. System.out.println(“Not here.”);
19. }
The difference between these two while loops is that the compiler knows on line 17 that
line 18 will never execute. The compiler cannot make the same assumption about the
while loop on line 9 because x is a variable. Line 17 generates the following compiler
error:
WhileLoop.java:17: unreachable statement
while(false) {
^
While we are on the subject, an if-then statement can contain unreachable code. For
example, the following statements compile fi ne:
21. if(false) {
22. System.out.println(“Unreachable”);
23. }
Java allows you to write unreachable if statements to simplify debugging code. I could
easily change the statement on line 21 to if(true) to test something and then change
it back to if(false) in production. Better yet, I could use a static final boolean that
could be defi ned in one place and used anywhere in my program.
You can write infi nite while loops and while loops that never execute.
Next we discuss do statements, which are similar to while loops except the body of a
do-while loop is guaranteed to execute at least one time.
Search WWH ::




Custom Search