Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java coding: How to use "&" and "|" ?
So in my textbook, it covers the "And" and "or" for Boolean expressions which are "&&" and "||" but I've come across a single "&" and "|" and it doesn't entirely describe what they do.
I'm kind of confused and explanations online don't seem to suffice.
Could anyone explain what they are and give a basic example of when/how to use them?
2 Answers
- ChrisLv 74 years ago
Those operate on the individual bits.
&& and || are used to combine boolean values, as in, "true" and "false".
& and | are used to combine the bits of integers.
As an example, 7 is 111, and 3 is 11 or 011.
So 7 & 3 is 3, since the leftmost bit is zero for 3.
But 7 | 3 is 7, since all bits are one for 7.
It's not always one number or the other though.
12 is 1100.
3 is 0011.
Thus 12 & 3 is 0, since none of the four bits is 1 for both numbers.
12 | 3 however is 15, since every bit is 1 in at least one number.
The next question is: when do we actually USE them?
One example is a situation where we only care about certain bits. For instance each odd number has its rightmost bit set to 1. Which means the expression x & 1 is 1 if x is odd, 0 if x is even.
Another use case is flags; each bit can be considered a variable, so we can introduce constants like Player.IS_MALE or Player.IS_NPC and set them to numbers like 1, 2, 4, 8, 16, etc.
That way we can combine the bits using |:
Player player = new Player("Guy", Player.IS_MALE | Player.IS_NPC);
Assuming that Player.IS_MALE is 4, or 100, and assuming that Player.IS_NPC is 16, or 10000, we are passing 20 to the constructor, or 10100.
So a single parameter is used to convey multiple true/false choices.
Inside the constructor, we can read the individual bits using
if (x & Player.IS_MALE > 0) ...
- Maverick MentholLv 54 years ago
& and | can be used in logical statements as well, HOWEVER it does not short circuit. Unlike the && and || operators. For example given:
false && BOOLEAN, we know the result is false, we don't need to know what the other boolean value is.
Given:
true || BOOLEAN, the same is true, any value OR'd with true is true.
The & and | are bitwise operators, they perform their respective operations on a bit by bit basis. When used for logical operations they DO NOT use short circuit evaluation, meaning they evaluate all expression, performing correct precedence (I believe & is higher up than | ), and evaluating like so.
Pretty sure this is how the bitwise ones work on booleans as well..