Java Operator
Java Operator
== Equal to x == y
!= Not equal x != y
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
Sample Code for Logical:
Logical and. && Logical or. ||
Sample: Sample:
int x = 5; int x = 5;
System.out.println(x > 3 && x < 10); // returns true System.out.println(x > 3 || x < 4); // returns true
because 5 is greater than 3 AND 5 is less than 10 because one of the conditions are true (5 is greater than
3, but 5 is not less than 4)
Logical not. !
Sample:
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false
because ! (not) is used to reverse the result
Java Bitwise Operator
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they
will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
Operator Description Example
| (bitwise or) Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is set in one operand but
^ (bitwise XOR) (A ^ B) will give 49 which is 0011 0001
not both.
Binary Left Shift Operator. The left operands value is moved left
<< (left shift) A << 2 will give 240 which is 1111 0000
by the number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved right
>> (right shift) A >> 2 will give 15 which is 1111
by the number of bits specified by the right operand.
Shift right zero fill operator. The left operands value is moved right
>>> (zero fill
by the number of bits specified by the right operand and shifted A >>>2 will give 15 which is 0000 1111
right shift)
values are filled up with zeros.
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 >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );