Search code examples
javareturnjava-11

How does the compiler find the missing return statement?


I have a function to find an element in an array (Binary search). I get an error saying that there is a 'missing return statement'. (Commented part)

How does the compiler understand that a return statement is missing?

How does the compiler find all the execution paths, when only 'if's are used. There is no else-if being implemented

public static int rank(int key, int []a, int lo, int hi)
    {
        if(lo>hi) return -1;
        int mid= lo+(hi-lo)/2;
        if(key<a[mid]) return rank(key,a,lo,mid-1);
        if(key>a[mid]) return rank(key,a,mid+1,hi);
        //else return mid;
    }

Solution

  • How does the compiler find all the execution paths?

    It is not very clever about it, it cannot detect branches that can logically never be reached, it just wants all branches to end in a return. See this other question for a case where that is not "clever enough".

    In your case, it sees that it might be possible that none of the if conditions becomes true, so that you fall through to the end of the method and it wants to see a return there.

    In your case, that reasoning is also correct: As far as I can tell, it might very well fall through all the branches.