FSB FSB - 3 days ago 6
Java Question

Java boolean method needs extra return statement?

I am starting with java and while I was writing a way to identify whether a number was prime I wrote a method like this

public static boolean checkPrime(int n){

int x = 2;

while (((n % x) != 0) && (n > x)){
x = x + 1;
}

if(((n % x) == 0) && (n == x)){
return !Prime;
}
else if(((n % x) == 0) && (n > x)){
return Prime;
}
else {
return Prime;
}
}


What I couldn't figure out was the necessity of the last else statement. If I do not put it, I get an error message. However I don't think it is necessary since all possibilities are covered by the previous loops, with their respecting return statements. Or am I missing something?

Answer

You don't need the else. What you are being told by the compiler is the method must return SOMETHING. Your last else block could replaced by this:

return PrimeOrNot;

In fact, your method could look like this:

public static boolean checkPrime(int n){
    int x = 2;
    while (((n % x) != 0) && (n > x)){
        x = x + 1;
    }
    if(((n % x) == 0) && (n == x)){     
        return !(PrimeOrNot);
    }
    return (PrimeOrNot);
}

In any case your very last statement block cannot be an else if.

Comments