In Java can I return a boolean value with the following:
public boolean areBothEven(int i, int j) {
return (i%2 == 0 && j%2 == 0);
}
Or do I need to surround 开发者_Python百科the statement with an if and then return true and false appropriately?
No, in fact doing stuff like return xxx ? true : false;
or if (xxx) return true; else return false;
is generally considered redundant and therefore bad style. In your case, you might even speed things up slightly by avoiding the &&
(which may incur a branch mis-prediction):
return (i | j)%2 == 0;
The expression is of boolean type, and is therefore suitable to be returned. You do not need to use an if statement.
The syntax is correct. But, zero is neither even nor odd, isn't it? So, may be
return i !=0 && j !=0 && i%2 == 0 && j%2 == 0;
精彩评论