Bitwise and Ternary Operator in Java
In this class, We discuss Bitwise and Ternary Operator in Java.
The reader should have prior knowledge of logical operators. Click Here.
Bitwise Operators:
Bitwise AND – &
Bitwise OR – |
Bitwise XOR – ^
The above three are used as bitwise operators.
The below diagram shows the tables for bitwise operators.
The bitwise AND will be 1 if both the bits are 1.
The bitwise OR will be 1 if any of the bits is 1.
The bitwise exclusive OR will be one. If the two are opposite bits.
Example:
int a=5, b=3, c;
c= a&b;
System.out.println(c);
The above statement will display 1.
5 in binary 00101
3 in binary 00011
After AND 00001
The bitwise AND operation is done from the least significant bit.
The least significant bits of 5 AND 3 are 1 AND 1 = 1
Similarly, other bits.
Similarly, the bitwise operation is done for OR and XOR.
c=a|b will output 7.
c=a^b will output 6.
Ternary Operator:
Variable = Expression1 ? Expression2 : Expression3
The above is the syntax for the ternary operator.
Example:
a=5, b=3
c = a>b ? a+b : a-b
System.out.println(c) will display 8
The condition in expression 1 is true. Expression2 will evaluate and assign to c; otherwise, expression3 will be assigned to c.
In our example condition is true, so a+b is 8.
The value 8 is assigned to variable c.