Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as logical short circuit operators. As the previous table shows, the OR operator returns true when A is true, regardless of what B.
Similarly, the AND operator results in false when A is false, regardless of what B. is. If you use the forms || and && , not forms | and & these operators, Java will not try to evaluate only the right operand. This is very useful when the right operand depends on whether the left operand is true or false for proper operation.
For example, the following code snippet shows how you can use a logical evaluation of a short circuit to make sure that the division operation is valid before it is evaluated:
if ( denom != 0 && num / denom >10)
Since the short-circuited AND ( && ) form is used, there is no risk of throwing an exception at runtime to zero. If this line of code was written using a single AND version, both sides would have to be evaluated, which would throw a runtime exception when denom is zero.
Standard practice is to use the AND and OR short-circuit forms in cases involving Boolean logic, leaving single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:
if ( c==1 & e++ < 100 ) d = 100;
Here, using a single & , the increment to e operation will be performed if c is 1 or not.
Dileep Kumar Jul 24 '13 at 19:07 2013-07-24 19:07
source share