Why do the following raise an error?
for(; 0 ;) System.out.println("guess"); // or
for(;false;) System.out.println("guess"); // or
for(; 1 ;) System.out.println("guess");
But the following runs okay (infinitely):
for(;true;) System.out.println("guess");
Why does it work for true but not for false?
The condition (i.e. the bit between the ;s) must be a boolean, so this immediately rules out the first and third variants in your first snippet.
Now, the second variant, in which you have used a boolean, doesn't compile because the compiler realizes that the loop will never be entered and hence issues an error:
Untitled.java:3: error: unreachable statement
for(;false;) System.out.println("guess");
^
1 error
Note that the JLS mandates that errors be issued for unreachable statements (see §14.21):
It is a compile-time error if a statement cannot be executed because it is unreachable.
...
The contained statement is reachable iff the
forstatement is reachable and the condition expression is not a constant expression whose value isfalse.
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