Java Reference
In-Depth Information
How It Works
The example uses the code fragments that I discussed in the previous section so you can see from the
output that they work as described. One new capability introduced here is the use of the static toBin-
aryString() method that is defined in the Integer class. There's a static import statement for the name
of this method, so its use is not qualified by the class name in the example. The toBinaryString()
method produces a string containing a binary representation of the value of type int that is passed as the
argument to the method. You can see from the output for the value of selectBit3 that the string does
not include leading zeros. Obviously, the output would be better with leading zeros displayed but you
need to know more about handling strings to be able to fix this. By the end of Chapter 4, you will be in a
position to do so.
Using the Exclusive OR Operator
The ^ operator has the slightly surprising ability to interchange two values without moving either value
somewhere else. The need for this turns up most frequently in tricky examination questions. Suppose you
execute the following three statements with integer variables a and b :
a ^= b;
b ^= a;
a ^= b;
The effect of these statements is to interchange the values of a and b , but remember this works only for
integers. You can try this out with a couple of arbitrary values for a and b , 0b1101_0000_0000_1111 and
0b1010_1011_1010_1101 , respectively — again, I am just showing 16 bits for each variable. The first state-
ment changes a to a new value:
a 0b1101_0000_0000_1111
b 0b1010_1011_1010_1101
a from a^b0b0111_1011_1010_0010
The next statement calculates a new value of b using the new value of a :
a 0b0111_1011_1010_0010
b 0b1010_1011_1010_1101
b from b^a0b1101_0000_0000_1111
So b now has a value that looks remarkably like the value that a started out with. Let's look at the last
step, which calculates a new value for a using the new value of b :
a 0b0111_1011_1010_0010
b 0b1101_0000_0000_1111
a from a^b0b1010_1011_1010_1101
Lo and behold, the value of a is now the original value of b . When you get to do some graphics program-
ming later in the topic, you see that this application of the exclusive OR operator is quite useful.
Don't forget — all of these bitwise operators can be applied only to integers. They don't work with any
other type of value. As with the arithmetic expressions, the bitwise operations are carried out with 32 bits
for integers of type short and of type byte , so a cast to the appropriate type is necessary for the result of
the expression on the right of the assignment operator.
Search WWH ::




Custom Search