# Thread: Boolean Logic

1. Member
Join Date
Jun 2011
Posts
3
Rep Power
0

## Boolean Logic

So why is it that in C++ you can have the code:

Java Code:
```int x = 0x40000000;
int y = 0x20000000;
int z = x|y;

if (z & 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.
Last edited by DaveC; 06-15-2011 at 05:18 AM.

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
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.

 You can't overload operators.
Last edited by pbrockway2; 06-15-2011 at 05:40 AM.

3. 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++.

4. Member
Join Date
Jun 2011
Posts
3
Rep Power
0
Originally Posted by pbrockway2
Or use enums.
Sorry, enums?
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.
Last edited by DaveC; 06-15-2011 at 06:07 AM.

5. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12
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).

Java 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));
}
}```

6. Member
Join Date
Jun 2011
Posts
3
Rep Power
0
Ah, thank you much, pbrockway2. This will do just fine.

7. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•