javaunreachable-code

Why this code is showing "unreachable code" error?? And how can I fix it?


public class Array {
    public static void main(String[] args) {        
        int[] arr= {5,6,9,-5,-2,4,-3,1,-1};
        
        int i=0;
        int n=arr.length;
        int j=n-1;
        while(true) 
            while(arr[i]>0 && i<j) {
                while(arr[j]<0 && i<j) {
                    if(i<j) {
                        int temp=arr[i];
                        arr[i]=arr[j];
                        arr[j]=temp;
                        i++;
                        j--;
                    }else 
                        break;
                }
                
            }
        for(int x=0;x<arr.length;x++) {
            System.out.print(arr[x]+" "); //unreachable code
        }
    }
}

Why this code is showing "unreachable code" error? And How can I fix it? how can I solve this error please help?


Solution

  • break leaves the nearest innermost loop it is in, in your case while(arr[j]<0 && i<j). That means your while(true) is an infinite loop.

    You can fix this by either maintaining a flag that will trigger an outer break:

    boolean goOn = true;
    while(goOn) 
        while(goOn && arr[i]>0 && i<j) {
            while(goOn && arr[j]<0 && i<j) {
                if(i<j) {
                    int temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                    i++;
                    j--;
                }else  {
                    goOn = false;
                    break;
                }
            }
            
        }
    for(int x=0;x<arr.length;x++) {
        System.out.print(arr[x]+" "); //unreachable code
    }
    

    or create a label and break there:

    while(true) 
        while(arr[i]>0 && i<j) {
            while(arr[j]<0 && i<j) {
                if(i<j) {
                    int temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                    i++;
                    j--;
                }else  {
                    break exit;
                }
            }
            
        }
    exit:
    for(int x=0;x<arr.length;x++) {
        System.out.print(arr[x]+" "); //unreachable code
    }
    

    The latter is a feature that is rarely used in Java.