Search code examples
javaif-statementreturn

Java is asking to return a value even when the value is returned in the if-else ladder


I was trying to code AVL tree in java and something has just shaken my understanding of basic programming. Why does Java force me to return a value when I already have a return statement in the else block of the if-else ladder. I tried debugging and it works as expected, it never goes to the returns statement outside the if-else blocks. I have been working on java and never realized this. I am not even sure if this was always there or is it something new? I also read a few blogs which say that you don't have to return a value if you have returned it from the else block.

The error which I get is I skip the last return statement.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    This method must return a result of type AVLNode

https://javahungry.blogspot.com/2019/12/missing-return-statement-in-java.html checkout the last example on this link.

public class AVL 
{
    AVLNode root;
    
    private AVLNode insert ( AVLNode current,int val)
    {
        if ( current == null)
        {
            return new AVLNode(val, 0, null, null);
        }
        else if ( val < current.val)
        {
            current.left = insert ( current.left, val);
        }
        else if ( val > current.val)
        {
            current.right = insert ( current.right, val);
        }
        else
        {
            return current;
        }
        return current;     // I don't want to return you ////      
    }


public void  add ( int val)
    {
        this.root = insert ( this.root, val);
    }

Solution

  • The reason you get this error is because if you didn't have the final return statement, and ended up inside one of the if blocks, you'd never hit the else and therefore never hit a return statement.

    Try stepping through the code with any case where current.val and val are both specified, but are two different values, for example current.val = 2 and val = 1.

    In this case the execution will skip over the first if (because current is not null), and then go into the second if block (because val > current.val). Because one of the if conditions has been met, we will skip over the following else if and the else, and hit the final return statement. If that statement weren't there, we'd never return anything.

    The reason this is different from the example you cite is because that example has a return in both the if and the else blocks, so whatever happens you always encounter a return statement. You could achieve the same by adding return current; inside both else if blocks, although it's far cleaner just to have the single return at the end.

    Basically, if you have a collection of if...else if...else if...else the execution will only ever visit one of the blocks. Whichever path through the code gets executed must always have a return.