Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compile time unreachable code error

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.

like image 902
Nitin Avatar asked Jul 16 '26 08:07

Nitin


2 Answers

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);
like image 136
Luiggi Mendoza Avatar answered Jul 17 '26 20:07

Luiggi Mendoza


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.

like image 36
rgettman Avatar answered Jul 17 '26 21:07

rgettman



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!