Bitwise AND : Bitwise Operators in Java Programming

Bitwise AND Operator is -

  1. Binary Operator as it Operates on 2 Operands.
  2. Denoted by - &
  3. Used for : Masking Bits.

Bitwise AND Summary Table :

A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

 

Live Example 1 : ANDing 42 and 15

class BitwiseAND{
  public static void main(String args[]){
  int num1 = 42;
  int num2 = 15;
  System.out.println("AND Result =" +(num1&num2));
  }
}
[468x60]

Output :

AND Result = 10

Explanation of Code :

Num1 : 00101010   42
Num2 : 00001111   15
======================
AND  : 00001010   10
  • 42 is represented in Binary format as -> 00101010
  • 15 is represented in Binary format as -> 00001111
  • According to above rule (table) we get 00001010 as final structure.
  • println method will print decimal equivalent of 00001010 and display it on screen.

Live Example 2 : ANDing Hex and Integer

class BitwiseAND{
  public static void main(String args[]){
  int num1 = 42;
  int num2 = 0xF;
  System.out.println("AND Result =" +(num1&num2));
  }
}
  • Code will also gives 10 as a result.
  • 0xF is hexadecimal number.
  • 0xF is first converted into “decimal“.(Decimal Equivalent : 15)
  • Again Same Operation will takes place as that of “Live Example 1“.
Step 1: Converting Hex to Decimal
Num2  : F  (Hex)
      : 15 (Decimal Equivalent)
Step 2: Converting Decimal to Binary
Num1  : 00101010   42
Num2  : 00001111   15
======================
AND   : 00001010   10
[468x60] Bitwise and Operator in Java Programming Language
Bitwise Logical Operators : AND | OR | NOT | XOR