# Boolean Logic

• 06-15-2011, 04:09 AM
DaveC
Boolean Logic
So why is it that in C++ you can have the code:

Code:

```int x = 0x40000000; int y = 0x20000000; int z = x|y; if (z & y)     Print("Z masks Y");```
But a similar check ( the "z & y" part ) in java forces you to have booleans ("found int but expected boolean") to do the algebra? I know they're boolean operators. Is there another way to do comparisons like that? In the program I'm writing I was planning to use certain integers (like x and y here) to flag for certain properties, but found Java won't let you.

Additionally, is it possible to overload operators if I can't get the comparisons to work this way (i.e. the functionality isn't already there in another form)? I'd like to overload the "&" operator to do this if it can't; I know the method to do so.
• 06-15-2011, 04:37 AM
pbrockway2
C's if allows an int expression: it is tested for ==0 ("false") or !=0 ("true"). Java doesn't do this, perhaps to avoid mistakenly writing if(a=b) when you mean if(a==b) but in any event "if" is treated as something that acts on a boolean and boolean expression you must give it.

Consider (a&b)==0, (a|b)!=0, (a&b)==a etc. Or use enums or BitSet.

• 06-15-2011, 04:43 AM
Junky
It's amazing how many people moan about how Java doesn't do what C/C++ does. Well if it could then it wouldn't be Java it would be C/C++.
• 06-15-2011, 04:43 AM
DaveC
Quote:

Originally Posted by pbrockway2
Or use enums.

Sorry, enums?
Quote:

Originally Posted by Junky
It's amazing how many people moan about how Java doesn't do what C/C++ does. Well if it could then it wouldn't be Java it would be C/C++.

I'm not moaning. I didn't know; that's why I asked, and find it rather rude that instead of trying to help me you troll the thread.
• 06-15-2011, 05:02 AM
pbrockway2
Quote:

Sorry, enums?
Instead of taking a bunch of things you might want to signal and assigning them int numbers (1, 2, 4, 8, ...) then shifting and anding etc, you can create an enum and then use an instance of EnumSet (like a bitset but strongly typed).

Code:

```import java.util.EnumSet; public enum TeaAdditives {             WATER, MILK, LEMON, SUGAR;             public static void main(String[] args) {         EnumSet<TeaAdditives> order = EnumSet.of(MILK, SUGAR);                         System.out.println("Has sugar: " + order.contains(SUGAR));         System.out.println("Has lemon: " + order.contains(LEMON));     } }```
• 06-15-2011, 05:06 AM
DaveC
Ah, thank you much, pbrockway2. This will do just fine.
• 06-15-2011, 05:11 AM
pbrockway2
You're welcome.