Aneesh
Aneesh

Reputation: 1733

Extremely weird behaviour of return statement : Java

OK I have a weird problem. The code is as follows : The method name is returnMultiPartHeading

if (recursionCount > 6 || i == list.size() - 1)
            return -1;
        multiPartHeading = multiPartHeading + " " + list.get(i + 1).getText();
        Token token = new Token();
        token.setText(multiPartHeading);
        if (isHeadingType(token)) {
            System.out.println("found " + multiPartHeading);
            System.out.println("returning ...");
            System.out.println("I is " + (i + 1));
            return (i + 1);
        } else {
            returnMultiPartHeading(list, i + 1, multiPartHeading,
                    ++recursionCount);

        }
        System.out.println("returning -1");
        return -1;
    }

The output is for a sample run is :

found xyz
returning...
I is 2
returning -1

why is this happening?? the if (isHeadingType(token)) evaluates to true , prints the two messages and then it totally skips the return i+1 and goes to return -1 instead. In the place I called it, I get -1 as the returned value instead of getting 2. Why is this happening?? Never saw this behaviour.

Upvotes: 0

Views: 94

Answers (3)

Maxim Efimov
Maxim Efimov

Reputation: 2737

Looks like two calls are performed, the first wrote

found xyz
returning...
I is 2

and the second

returning -1

as it is a recursive method I think thats the reason

Upvotes: 2

Nikhil
Nikhil

Reputation: 2308

The if block is the second recursive call, which returns to the first recursive call, which was probably called by the else block. In the else block you do not return the value. Hence it skips out and returns -1.

Upvotes: 1

Andrzej Doyle
Andrzej Doyle

Reputation: 103787

It's because in your else block, you don't actually return the result of the recursive call. You just call the method, ignore its result, and then fall through to the section below (with the return -1).

You need to change your else block to

else {
     return returnMultiPartHeading(list, i + 1, multiPartHeading,
                ++recursionCount);
}

(assuming that your method really is called returnMultiPartHeading, which somehow doesn't sound right)

Upvotes: 5

Related Questions