4

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 loop compiles & runs, but the second for loop compilation fails with error. It says Unreachable Statement. And the third for loop compiles & runs.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 2
    Now if you add `final` in front of `boolean t=false;` it won't compile again. It's all about what compiler can guarantee. – Bhesh Gurung Mar 17 '13 at 07:13

4 Answers4

4

The first loop is infinite loop. Since the condition is always true, and will always be satisfied.

It's like writing:

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

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

The second loop is Unreachable code since the piece of code below this loop will never be reached (false is always false and you never change it). So it's redundant.

See Chapter 14.21. Unreachable Statements

Since Java knows that the programmer is human :) it notifies you about this to prevent mistakes.

Note that while(false) or the second loop you have differ from if(false)... since while(false) (or the loop you have) doesn't make sense because the code below it will no be execute. Not like if(false) that might have else, so the compiler doesn't complain about it in this case.


Regarding the OP update:

In the third case there will be no compilation error since the false value is assigned to the variable and in this case, the variable can be re-assigned to have true value in it. So the compiler doesn't arise an error. Note that if the variable is declared as final then the compiler will arise an error since this variable can be never assigned to a new value, thus the code below the for loop will be unreachable.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

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

Like in this case :

if (false) {
}
gontard
  • 28,720
  • 11
  • 94
  • 117
0
 for (int i = 0; <This_has_to_be_true>; i++)

The second part of the for loop has to be true for the loop to execute. Since you're manually setting it to be always fase, the loop will never run, hence the code inside it is unreachable.

Vaishak Suresh
  • 5,735
  • 10
  • 41
  • 66
0

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

BTW, why are you trying to do this anyway?

tocker
  • 1,752
  • 1
  • 11
  • 9