Reputation: 3800
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
?
Upvotes: 2
Views: 231
Reputation: 2929
Java requires a boolean as second parameter in your loop header, it evaluates the statement and if the statement returns true the jvm will run the code of the loop-body, not the body will be skipped.
0 and 1 are obviously no booleans nor do they define a statement which could be evaluated (like x < y) and since java is a static and strong typed language (unlike Python or Perl) it cannot cast an int to a boolean, so it crashes.
Edit: If you provide "false" as statement the JVM will notice that the loop-body never can be reached, this will cause a runtime-error.
Upvotes: 1
Reputation: 6005
Unlike C, in Java, true
and false
correspond to boolean
type values, where 1 and 0 to int
(in fact, in C there is no boolean
declarative type, and boolean checks are done based on integer comparisons. In Java, things are distinct).
Upvotes: 0
Reputation: 129497
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
for
statement is reachable and the condition expression is not a constant expression whose value isfalse
.
Upvotes: 8