Saturday, April 22, 2017

Java - Example for Bitwise Operators

Copy and paste the following Java program in Test.java file and compile and run this program −

Example

public class Test {

public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c
= a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );

c
= a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );

c
= a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );

c
= ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );

c
= a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );

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

c
= a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}
This will produce the following result −

Output

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15

No comments:

Post a Comment

150+java interview questions and answers

Java Platform 1 . Why is Java so popular? 2 . What is platform independence? 3 . What is bytecode? 4 . Compare JDK vs JVM vs JRE 5 ....