Java Reference
In-Depth Information
Listing 4-18. Bitwise Exclusive OR operator (^)
Byte byte1 = Byte.parseByte("01010101", 2); // byte1 = 85
Byte byte2 = Byte.parseByte("00111111", 2); // byte2 = 63
int result = byte1 ^ byte2; // result = 106
The value of result is 106 because taking the bits where either bit in the compared values is 1 gives a
binary result of 01101010 , which happens to be the binary representation of 106.
Bitwise Inclusive OR Operator (|)
The bitwise Inclusive OR operator (|) compares two binary values and sets each bit to 1 if either bit is 1.
Again, examples make the best explanations for this kind of thing (see Listing 4-19).
Listing 4-19. Bitwise Inclusive OR operator (|)
Byte byte1 = Byte.parseByte("01010101", 2); // byte1 = 85
Byte byte2 = Byte.parseByte("00111111", 2); // byte2 = 63
int result = byte1 | byte2; // result = 127
The value of result is 127 because taking the bits where either bit is 1 in the compared values is 1
gives a binary result of 01101010 , which happens to be the binary representation of 127.
You might ask when anyone would ever use these bitwise operators. They have a number of useful
applications, actually. Game developers often use bitwise operations for high-speed graphics
processing. Again, imagine a game in which two objects merge somehow (maybe shooting a blue object
with a red bullet makes the object turn purple). The bitwise and operator ( & ) provides a high-speed way
to determine the new color. The bitwise operators are also often used to see which combination of
mouse buttons have been pressed or to see whether a mouse button has been held down while the
mouse was moved (creating a drag operation). So they might seem like oddball operators, but they
definitely have their uses.
Logical AND Operator (&&)
The logical AND operator ( && ) returns true if both arguments are true and false if either one is false. It's
most often used within if statements but is handy anywhere you need to be sure that two boolean values
are true. Also, the logical AND operator is one of the most-often used operators. If we had a nickel for
every time we typed && ....
Listing 4-20 is an example.
Listing 4-20. Logical AND operator (&&)
if (2 > 1 && 1 > 0) {
System.out.println("Numbers work as expected");
}
In that code snippet, we have three operators. Thanks to operator precedence, the two comparison
operators ( > ) get evaluated before the logical AND operator ( && ), so we don't need parentheses to make
things work correctly (though you might want parentheses for clarity, depending on your coding style).
Also, you can chain multiple logical AND operators (and most other operators), as shown in Listing
4-21.
Search WWH ::




Custom Search