Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Java - Does returning a value break a 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 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

question from:https://stackoverflow.com/questions/10661081/java-does-returning-a-value-break-a-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...