tags:

views:

67

answers:

3

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 the statement with an if and then return true and false appropriately?

+4  A: 

The expression is of boolean type, and is therefore suitable to be returned. You do not need to use an if statement.

Visage
Just to clarify @Visage's answer - "Yes, you can do the return you are doing, No, you do not need to do the if" :)
Rich
Thanks Rich. I've clarified.
Visage
A: 
itea
Zero is an even number.
Marcelo Cantos
I feel this is same as what the question is. But why to make the things complex. Anyways i%2 == 0 if i is even or i is 0. There is no second thought to add the conditions.
Multiplexer
Zero is neither even nor odd??? How's that? Of course, zero is even. http://en.wikipedia.org/wiki/Parity_of_zero
Grodriguez
+7  A: 

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;
Marcelo Cantos
@Multiplexer: I don't think bit operations on integers are much readable code.
Thilo
I dont think thats more readable at all. Maybe because I've never been a 'low level' coder down amongst the bits, but bitwise operations involve thinking, wheras the original is easy.
Visage
@Thilo, @Visage: Agreed. I wouldn't suggest for a moment that this is the most readable solution, but I consider it perfectly acceptable when it is the only bit of code you have to read inside a function called `areBothEven`. Though, I would prefer the name `bothAreEven`. Predicates should read like positive assertions, so that statements like `if (bothAreEven(x, y)) ...` read more naturally.
Marcelo Cantos