50

I'm writing some code that basically follows the following format:

public static boolean isIncluded(E element) {
    Node<E> c = head;
    while (c != null) {
        if (cursor.getElement().equals(element)) {
            return true;
        }
        c = c.getNext();
    }
    return false;
}

The code will search for an element in a list of nodes. However, my question is that if the while loop does find the element where the if-statement says it should return true, will it simply return true and break the loop? Furthermore, if it does then break the loop will it then carry on through the method and still return false, or is the method completed once a value is returned?

Thanks

0

5 Answers 5

108

Yes*

Yes, usually (and in your case) it does break out of the loop and returns from the method.

An Exception

One exception is that if there is a finally block inside the loop and surrounding the return statement then the code in the finally block will be executed before the method returns. The finally block might not terminate - for example it could contain another loop or call a method that never returns. In this case you wouldn't ever exit the loop or the method.

while (true)
{
    try
    {
        return;  // This return technically speaking doesn't exit the loop.
    }
    finally
    {
        while (true) {}  // Instead it gets stuck here.
    }
}
1
  • 3
    even if there is no return inside try block, your logic will get struck in finally
    – divine
    Jun 27, 2017 at 15:08
23

Return does break the loop and returns from the entire method immediately. The only code that will be executed on the way out is the body of a finally clause and the release of any synchronized statement.

18

I should also add that if you want to break the current iteration of the loop, and instantly start the next one, you can use:

continue;

As it seems nobody has suggested it.

1
  • @hobbyist : Please give one example as your answer is not clear to me. Oct 18, 2021 at 13:58
10

Yes.

Anyway, for questions as short as this, I think you would be better (and get an earlier answer) just trying it by yourself.

3
  • 13
    @duffymo But once it's on SO, it has two advantages: 1) it is quicker to lookup for others, and 2) it illuminates edge cases and further discourse. Jul 16, 2014 at 2:48
  • @JoshPinter It is also a good candidate for QA, where you yourself provide the answer.
    – cst1992
    Feb 7, 2017 at 9:41
  • @cst1992 I was doing that past day, but recently I start to get downvotes for that, as people say "OK and now what the problem if you solved it?" so... Mar 27, 2019 at 14:06
2

Return whenever called exits a method from wherever it is and returns a value to the caller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.