Java – does the return value break the loop?

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 searches for elements in the node list However, my question is, if the while loop does find the element that the if statement says it should return true, will it return true and break the loop? In addition, if it does then interrupt the loop, it will continue through the method and still return false, or will the method complete once the value is returned?

thank you

Solution

Yes*

Yes, usually (in your case) it breaks through the loop and returns from the method

One exception

One exception is that if the loop has a finally block and contains a return statement, the code in the finally method block will be executed before the method returns A finally block may not terminate - for example, it may contain another loop or call a method that never returns In this case, you will never exit a loop or method

while (true)
{
    try
    {
        return;  // This return technically speaking doesn't exit the loop.
    }
    finally
    {
        while (true) {}  // Instead it gets stuck here.
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>