2

I am getting compile time "unreachable code" error on below line in my program:

System.out.println("i =" + i + ", j = " + j);

public static void main(String[] args) { int i = 0, j = 5; tp: for (;;) { i++; for (;;) { if (i > --j) { break tp; } } System.out.println("i =" + i + ", j = " + j); } } 

kindly help me out to find the exact cause for this. Thanks in advance.

3 Answers 3

7

Let's analyze this code:

tp: for (;;) //<-- similar to while(true) { i++; //increases i by 1 for (;;) //<-- similar to while(true) { if (i > --j) { //decreases j and compares its value against i break tp; //breaks tp, which means breaking the outer for loop } } //while(true) above //if break gets executed, it breaks this for loop //so this line can never be executed System.out.println("i =" + i + ", j = " + j); } 

Easiest solution:

Move System.out.println("i =" + i + ", j = " + j); outside the outer for loop.

tp: for (;;) { i++; for (;;) { if (i > --j) { break tp; } } } System.out.println("i =" + i + ", j = " + j); 
Sign up to request clarification or add additional context in comments.

3 Comments

@Diego No, because the outer loop can be exited if i > --j becomes true.
@Diego it is not. Since break tp; get's executed, the outer for loop stops, so the next statement after it, which is System.out.println(...);, gets executed with no problems.
oh I see, I thought it would restart the outer for. I guess I have to review how that labels work on Java. Thanks!
3

The System.out.println code can't be reached ever, even if i is greater than j. The only break sends you breaking out of the outer for loop. The System.out.println statement is after the inner for loop, but in the inner for loop, you either keep looping, decrementing j, or you break the outer loop. There is no way to reach the println statement.

To print what i and j are after the loop ends, move the System.out.println call after the ending brace of the outer for loop.

Comments

1

The inner loop is an infinite loop. The only way to exit it is when i > --j is true, but this will break the outer loop (due to the call of break tp;) and the program will immediately execute the next code after the outer loop. That means there is no condition where the inner loop terminates "normally" so the next code after it can run.

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.