By: aathishankaran Emailed: 1768 times Printed: 2515 times
Short-Circuit Logical Operator
Java provides two interesting Boolean operators not found in most other computer languages. These are secondary versions of the Boolean AND and OR operators, and are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. If operator results in false when A is false, no matter what B is. If you use the | | and && forms, rather than the | and & forms of these operators, java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly. For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:
if ( denom != 0
&& num / denom >10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception when denom is zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.
It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the 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 & ensures that the increment operation will be applied to e whether c is equal to 1 or not.
View Tutorial By: wizard at 2012-09-22 04:18:59
View Tutorial By: singh at 2012-10-26 11:57:11
View Tutorial By: Pankaj at 2013-09-14 05:48:47
Most Viewed Articles (in Java )
Most Emailed Articles (in Java)