Java - Does returning a value break a loop?

前端 未结 5 1580
时光说笑
时光说笑 2020-12-02 10:42

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

public static boolean isIncluded(E element) {
    Node c = head;
    while (c !=         


        
相关标签:
5条回答
  • 2020-12-02 11:05

    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.

    0 讨论(0)
  • 2020-12-02 11:07

    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.
        }
    }
    
    0 讨论(0)
  • 2020-12-02 11:15

    Yes.

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

    0 讨论(0)
  • 2020-12-02 11:19

    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.

    0 讨论(0)
  • 2020-12-02 11:22

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

    0 讨论(0)
提交回复
热议问题