Short-Circuit Logical Operator

By: aathishankaran Viewed: 153135 times  Printer Friendly Format    


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.



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Fantastic work guys
View Tutorial          By: wizard at 2012-09-22 04:18:59

2. uses the short circuited (conditional) logical AND
View Tutorial          By: Java Training at 2012-10-22 09:42:36

3. thanx to schildt
View Tutorial          By: singh at 2012-10-26 11:57:11

4. Exact copy of JAVA the complete reference -Herbert
View Tutorial          By: a at 2013-01-31 15:50:58

5. Above explanation is given in complete reference j
View Tutorial          By: Pankaj at 2013-09-14 05:48:47

6. You can find more information from this article
View Tutorial          By: jexper at 2014-08-15 10:29:37

7. http://java.meritcampus.com/core-java-topics/opera
View Tutorial          By: meritcampus at 2016-02-15 12:03:17

8. Lorenton
View Tutorial          By: Lorenton at 2017-06-21 17:14:57

9. Jasonmef
View Tutorial          By: Jasonmef at 2017-06-25 18:31:23

cannot update times viewed