2

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

5 Answers 5

3

'return' exits the function returning whatever value you return. The last return is never reached so it won't return the default value.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So it doesn't matter the 'return' is in a loop or not.
It does, if it is prime then it returns false, exiting the whole function. break would just exit the for loop (this would always return true if you did this). return is more powerful returning a value to the parent/calling function.
1

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.

1 Comment

I did.0-true 1-true 2-true 3-true 4-false 5-true 6-false 7-true 8-false 9-false 10-false
1

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.

Comments

0

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.