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.

1
  • 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. Commented Mar 17, 2013 at 7:13

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 For the update (I was about to added). One simple could it be a double loop.
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.

Comments

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?

Comments

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) {
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.