Explain short circuit operators in JAVA

Circuit operators

circuit operators in JAVA

  • Java provides two interesting Boolean operators not found in many other computer languages. These are secondary versions of the Boolean AND and OR operators, and are known as shortcircuit logical operators.
  • 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 you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone.
  • This is very useful when the right-hand operand depends on the value of the left one 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 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.

All of the above are circuit operators


Download the Android app to get all Government Job Notifications on your Mobile.
Download Now
Important: Please always Check and Confirm the above details with the official Advertisement / Notification.
Previous Post Next Post