Bitwise Operator In Java Example

Chapter: Operators Last Updated: 16-06-2017 09:13:03 UTC

Program:

            /* ............... START ............... */
                
public class JavaBitwiseOperatorExample {
	public static void main(String args[]) {
		int a = 30;
		int b = 20;
		int c = 0;

		c = a & b;
		System.out.println("a & b = " + c);

		c = a | b;
		System.out.println("a | b = " + c);

		c = a ^ b;
		System.out.println("a ^ b = " + c);

		c = ~a;
		System.out.println("~a = " + c);

		c = a << 2;
		System.out.println("a << 2 = " + c);

		c = a >> 2;
		System.out.println("a >> 2  = " + c);

		c = a >>> 2;
		System.out.println("a >>> 2 = " + c);
	}
}
                /* ............... END ............... */
        

Output

a & b = 20
a | b = 30
a ^ b = 10
~a = -31
a << 2 = 120
a >> 2  = 7
a >>> 2 = 7

Notes:

  • Bitwise operator works on bits and performs bit-by-bit operation.
  • The unary bitwise complement operator "~" inverts a bit pattern.
  • The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right.
  • The bitwise & operator performs a bitwise AND operation.
  • The bitwise ^ operator performs a bitwise exclusive OR operation.
  • The bitwise | operator performs a bitwise inclusive OR operation.
  • The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

Tags

Bitwise Operator, Java

Similar Programs Chapter Last Updated
Java Left Shift Operator Operators 04-09-2018
Java Addition Operator Operators 18-05-2017
Java Right Shift Operator Operators 13-12-2016
Prefix Operator In Java Example Operators 19-06-2016
Logical Operators In Java Example Operators 17-06-2016
Operator Precedence In Java Examples Operators 17-06-2016
Ternary Operators In Java Example Operators 15-07-2016
Relational Operators In Java Example Operators 11-06-2016
Modulus Operators In Java Example Operators 15-07-2016
Increment And Decrement In Java Example Operators 15-07-2016
Boolean Operator In Java Example Operators 15-07-2016
Assignment Operation In Java Example Operators 06-04-2016
Arithmetic Operation In Java Example Operators 11-06-2016

1