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: meritcampus at 2016-02-15 12:03:17
4. You can find more information from this article
View Tutorial By: jexper at 2014-08-15 10:29:37
5. Above explanation is given in complete reference java writer Schildt.
View Tutorial By: Pankaj at 2013-09-14 05:48:47
6. Exact copy of JAVA the complete reference -Herbert schildt
BUY THE BOOK.. arse..
View Tutorial By: a at 2013-01-31 15:50:58
8. uses the short circuited (conditional) logical AND operator to avoid division by zero:
View Tutorial By: Java Training at 2012-10-22 09:42:36
Most Viewed Articles (in Java )
Latest Articles (in Java)
Comment on this tutorial
- Data Science
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews