Java Reference
In-Depth Information
In the above expression, i > 5 is evaluated first, and it returns true . Because the left-hand operand evaluated to
true , the right hand operand is not evaluated, and the expression ( i > 5 || j > 10) returns true .
Consider another example.
int i = 10;
int j = 15;
boolean b = (i > 20 || j > 10); // Assigns true to b
The expression i > 20 returns false . The expression reduces to false || j > 10. Because the left-hand operand
to || is false , the right-hand operand, j > 10 , is evaluated, which returns true and the entire expression returns true .
Logical OR Operator (|)
The logical OR operator ( | ) is used in the form
operand1 | operand2
The logical OR operator returns true if either operand is true . If both operands are false , it returns false . The
logical OR operator works the same way as the logical short-circuit OR operator, except for one difference. The logical
OR operator evaluates its right-hand operand even if its left-hand operand evaluates to true .
int i = 10;
int j = 15;
boolean b = (i > 5 | j > 10); // Assigns true to b
The expression i > 5 is evaluated first and it returns true . Even if the left-hand operand, i > 5 , evaluates to
true , the right-hand operand, j > 15 , is still evaluated, and the whole expression ( i > 5 | j > 10) returns true .
Logical XOR Operator (^)
The logical XOR operator ( ^ ) is used in the form
operand1 ^ operand2
The logical XOR operator returns true if operand1 and operand2 are different. That is, it returns true if one of the
operands is true , but not both. If both operands are the same, it returns false .
int i = 10;
boolean b;
b = true ^ true; // Assigns false to b
b = true ^ false; // Assigns true to b
b = false ^ true; // Assigns true to b
b = false ^ false; // Assigns false to b
b = (i > 5 ^ i < 15); // Assigns false to b
 
Search WWH ::




Custom Search