What I am trying to do here out of flower1 and flower2, one is even and one is odd then return true. If both are even, return false. If both are odd, return false. When my code is:
public class OppositesAttract { public static boolean isLove(final int flower1, final int flower2) { if(flower1%2==0 && flower2%2==0){ return false; }else if(flower1%2!=0 && flower2%2!=0){ return false; } else if(flower1%2==0 || flower2%2==0){ return true; } } }
I get a “missing return statement” error. So I added:
public class OppositesAttract { public static boolean isLove(final int flower1, final int flower2) { if(flower1%2==0 && flower2%2==0){ return false; }else if(flower1%2!=0 && flower2%2!=0){ return false; } else if(flower1%2==0 || flower2%2==0){ return true; }else{ return true; } } }
Now, the code works but I do not understand why I have to add the additional return statement.
Advertisement
Answer
The compiler doesn’t know the first 3 terms cover all situations.
if(flower1%2==0 && flower2%2==0){ return false; } else if(flower1%2!=0 && flower2%2!=0){ return false; } else if(flower1%2==0 || flower2%2==0){ return true; }
to you this reads as: all options are covered. but the compiler just sees:
if (somethingThatMayBeTrue) { } else if (somethingElseThatMayBeTrue) { } else if (aThirdThingThatMayBeTrue) { } .... and what if none of them are?
You may know that the last else if should always be true (since you know they are not both uneven) but the compiler doesn’t generally try to understand your code.
in your case, the last clause (aThirdThingThatMayBeTrue, flower1%2==0 || flower2%2==0) is actually (somethingThatIsAlwaysTrueIfPreviousTermsAreFalse).
so you can treat it as such:
if(flower1%2==0 && flower2%2==0){ return false; } else if(flower1%2!=0 && flower2%2!=0){ return false; } else { return true; }