Short Circuit Operators

  • Short circuit operators are two types these are ||(OR) , && (AND).
  • These two will return the boolean values i.e., nothing but true or false.
  • ||(OR) - When two expressions are joined by using this operator(||), if any expression contains TRUE the output should be TRUE no need of checking second expression.
  • Only one condition is there when two expressions contains FALSE then that time it comes out from the loop.

/* Program for using Short circuit operator as OR(||) */

					
public class OrOperator { public static void main(String[] args) { int i = 3; int j = 4; if(i < j || i++ < j--) { System.out.println("True"+i+ ""+j); } else { System.out.println("False"); } } }

o/p: True 3 4

In the above example we are initializing i,j values as 3,4 and by using if condition we check i <j i.e.,3<4 it is True So it gives the output as “True” no need of checking second expression.
Because if any expression contains True the answer should be True. And if in case Two expressions contains False so it prints “Flase”.

  • &(AND)- When two expressions are joined by using this operator(&&), if any expression contains False then the JVM will Stops the execution directly it gives the answer as False.

/* Program for using Short circuit operator as AND(&&) */

					
public class AndOperator { public static void main(String[] args) { int i = 5; int j = 4; if(i < j && i++ < j--) { System.out.println("True"+i); System.out.println("True"+i+ ""+j); } else { System.out.println("False"); } } }

o/p: False

In the above example we are initializing the values for i and j and next we can check the condition as i <j. It returns False whenever JVM see False the execution will be stop and it returns the answer as False no need of checking second expression.

HTML Comment Box is loading comments...