I have a simple question about the "return" statement. Example is in the code. I always think the isPrime(n) is always "true". Because the "return true;" is at the end of the method, it should over-write previous returns. Any one can help? The codes are running perfect, producing the right results.
private boolean isPrime(int n) {
for(int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
'return' exits the function returning whatever value you return. The last return is never reached so it won't return the default value.
No, a second return
does not override an earlier one, it is never even reached. Control leaves the method immediately upon return
.
(The only way for that not to happen would be to have a second return
inside of a finally
block. That would indeed change the return value. But is is highly discouraged)
No, once you return from a method, you're done. If you want to convince yourself, insert print statements, or run it through a debugger.
Functions don't fully execute and then return, they can exit at any point during the execution with a return statement.
So if a number is found to n % i == 0
then the subroutine will return false and exit.
If the function completed the for
loop and never resolved the if
statement it returns true and exits.
If if (n % i == 0)
is true it executes return false;
and will exit the method. return true;
will only be reached if return false;
can't be executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.