JAVA – return statement within the for loop

javareturn

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

Best Solution

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