Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 795
mark Avatar asked May 18 '12 23:05

mark


People also ask

Does returning break the loop?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

What happens when you return a value in Java?

What is a return statement in Java? In Java programming, the return statement is used for returning a value when the execution of the block is completed. The return statement inside a loop will cause the loop to break and further statements will be ignored by the compiler.

Is return a break statement?

Answer 533416ba631fe960060022a4 No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.

What happens when a return statement inside a for loop is executed?

What happens when a return statement inside a for loop is executed? The program immediately quits the current method.


2 Answers

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.     } } 
like image 151
Mark Byers Avatar answered Sep 24 '22 04:09

Mark Byers


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.

like image 25
Keith Randall Avatar answered Sep 23 '22 04:09

Keith Randall