The Java Lesson 7: Bitwise operations with good examples, click here! Page 4
JavaFAQ Home » Java Lessons by Jon Huhtala
The Java Lesson 7
Bitwise operations: overview with detailed examples
1. Logical bitwise operations
2. The complement operator
3. Bitwise shift operations
4. Bitwise assignment operations andr review questions
Bitwise assignment
operations
int x = 23; x <<=
2; System.out.println("Now x is " + x);
will display "Now x is 92" because 0000 0017 shifted 2 bits to the left becomes 0000 005C.
byte x =
127; x = 256; System.out.println("Now x is " + x);
will display "Now x is 127" because 7F OR 0000
0100 results in 0000 017F
(decimal 383) but only the rightmost 8
bits are assigned to byte variable
x.
More practice
The Java ranch tutorial Cat and Mouse Games with
Bits ends with an applet you can use to practice bitwise operations.
Review questions

If x is short variable with
a decimal value of 27, what data type
and decimal value will result from executing the following expression?
x & 8

a short with a value of 8

an int with a value of 8

a short with a value of 27

an int with a value of 27

a short with a value of 19

If someNumber is an int
variable having some value, what value will it have after executing the
following statement?
someNumber ^= someNumber;

the statement will not
compile

the statement will compile
but an error will occur at run time

0

1

the value cannot be
determined from the information given

If amount is a short
variable with a decimal value of 6,
which of the following statements will multiply amount by four and store the result in a short variable named newAmount? (choose two)

newAmount = (short) (amount << 2);

newAmount = amount << 2;

newAmount = (short) (amount >> 2);

newAmount = amount >> 2;

newAmount = (short) (amount << 34);

If x is an int variable with
an initial value of 7, what value will
it have after executing the following?
x >>>= (x ^ 6);

0

3

14

448

the statement will not
compile
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!

