What is wrong with this java for loop condition?

1.

for (int i = 0; (boolean)true; i++) { } 

2.

 for (int i = 0; (boolean)false; i++) { } 

3.

 boolean t=false; for (int i = 0; t; i++) { } 

The first for the cycle compiles and starts, and the second for the cycle compilation fails with error . He says the Unreachable Statement . And the third for the loop compiles and runs.

+4
source share
4 answers

The first cycle is an endless cycle. Since the condition is always true and will always be fulfilled.

I like to write:

 int i=0; while(true) i++; 

As you can see, the condition is always true , and nothing changes this value.

The second cycle is Unreachable code , since the code fragment below this cycle will never be reached ( false always false, and you never change it). Therefore, he is superfluous.

See chapter 14.21. Inaccessible Messages

Since Java knows that the programmer is human :), he notifies you of this to prevent errors.

Note that while(false) or the second loop that you are different from if(false)... since while(false) (or the loop you have) does not make sense, because the code below will not execute . I do not like if(false) , which may have else , so the compiler does not complain in this case.


Regarding the OP update:

In the third case, there will be no compilation error, since false assigned to the variable, in which case the variable can be redefined to have true in it. Thus, the compiler does not raise an error. Note that if a variable is declared final , then an error will occur in the compiler, since this variable can never be assigned to a new value, so the code below the for loop will not be available.

+4
source

In the second for loop, the condition is always false , so the for block (even if it is empty) will never be executed (this is unreacheable ).

As in this case:

 if (false) { } 
0
source
  for (int i = 0; <This_has_to_be_true>; i++) 

The second part of the for loop must be true to execute the loop. Since you manually configure it always to phase, the loop will never work, so the code inside it is not available.

0
source

The compiler tells you that the code inside the second loop (even if empty) will never be reached and will not be executed, because the condition is always false .

By the way, why are you still trying to do this?

0
source

All Articles