Demonstrate the bitwise logical operators : Bitwise Operators « Operators « Java Tutorial






public class MainClass {
  public static void main(String args[]) {
    String binary[] = {
      "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
      "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
    };
    int a = 3; // 0 + 2 + 1 or 0011 in binary
    int b = 6; // 4 + 2 + 0 or 0110 in binary
    int c = a | b;
    int d = a & b;
    int e = a ^ b;
    int f = (~a & b) | (a & ~b);
    int g = ~a & 0x0f;
   
    System.out.println("        a = " + binary[a]);
    System.out.println("        b = " + binary[b]);
    System.out.println("      a|b = " + binary[c]);
    System.out.println("      a&b = " + binary[d]);
    System.out.println("      a^b = " + binary[e]);
    System.out.println("~a&b|a&~b = " + binary[f]);
    System.out.println("       ~a = " + binary[g]);
  }
}
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100








3.5.Bitwise Operators
3.5.1.The Bitwise Operators can be applied to the integer types, long, int, short, char, and byte.
3.5.2.The Bitwise Logical Operators
3.5.3.Bitwise AND (&)
3.5.4.Bitwise OR (|)
3.5.5.Bitwise XOR (^)
3.5.6.Left shift (<<)
3.5.7.Bitwise complement (~): inverts ones and zeros in a number
3.5.8.Demonstrate the bitwise logical operators
3.5.9.All bitwise operators in action
3.5.10.Bitwise Operator Assignments
3.5.11.The Left Shift
3.5.12.Left shifting as a quick way to multiply by 2
3.5.13.The Right Shift
3.5.14.The Unsigned Right Shift
3.5.15.Signed shift to the right
3.5.16.Unsigned shifting a byte value.
3.5.17.Convert a number to negative and back
3.5.18.Performing Bitwise Operations on a Bit Vector
3.5.19.Converting Between a BitSet and a Byte Array
3.5.20.Returns a byte array of at least length 1
3.5.21.Use bitwise operator to create hash code
3.5.22.Operations on bit-mapped fields.
3.5.23.Represents a collection of 64 boolean (on/off) flags.