Classes/Objects  «Prev 


Java Bitwise Operators

Operator Description Example Result Computation
~ Bitwise complement. ~3 -4 ~3=~(00000011)=(11111100)=-4
& Bitwise AND 3 & 5 1 3 & 5=(00000011) & (00000101)=(00000001)=1
| Bitwise OR 3 | 4 7 3 | 4=(00000011) | (00000100)=(00000111)=7
^ Bitwise exclusive OR 5 ^ 4 1 5 ^ 4=(00000101) ^ (00000100)=(00000001)=1
<< Left shift. 3 << 3 24 3 << 3=(00000011) << 3=(00011000)=24
>> Signed right shift -6 >> 2 -2 -6 >> 2=(11111000) >> 2=(11111110)=-2
>>> Unsigned right shift. 6 >>> 2 1 6 >>> 2=(00000110) >>> 2=(00000001)=1

public class BitwiseOperators {
  public static void main(String args[]) {
    System.out.println(~3 );
    System.out.println(3 & 5);
    System.out.println(3 | 4);
    System.out.println(5 ^ 4);
    System.out.println(3 << 3);
    System.out.println(-6 >> 2);	  
    System.out.println(6 >>> 2);	     
  }
}
Program Output
-4
1
7
1
24
-2
1

Logical Operators

The exam objectives specify six "logical" operators (&, |, ^, !, &&, and ||). Some Oracle documentation uses other terminology for these operators, but for our purposes and in the exam objectives, these six are the logical operators.

Bitwise Operators

Of the six logical operators listed above, three of them (&, |, and ^) can also be used as "bitwise" operators. Bitwise operators were included in previous versions of the exam, but they are NOT on the Java 6 or Java 7 exam.
Here are several legal statements that use bitwise operators:
byte b1 = 6 & 8;
byte b2 = 7 | 9;
byte b3 = 5 ^ 4;
System.out.println(b1 + " " + b2 + " " + b3);

Bitwise operators compare two variables bit-by-bit and return a variable whose bits have been set based on whether the two variables being compared had respective bits that were either both "on" (&), one or the other "on" (|), or exactly one "on" (^). By the way, when we run the preceding code, we get

0 15 1