Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the error in 'for' loop?

Tags:

java

for-loop

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?

like image 676
Ali Akber Avatar asked Dec 04 '25 13:12

Ali Akber


1 Answers

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 is false.

like image 139
arshajii Avatar answered Dec 07 '25 02:12

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!