0

In evaluating the expression (x==y && a<b) the Boolean expression x==y is evaluated first and then a<b is evaluated. True or False????

Please explain the working for the same. I quite confused for this if expression.

1
  • 1
    Yes, although a < b is only evaluated if x == y is true.
    – Jon Skeet
    Apr 29, 2015 at 5:39

6 Answers 6

2

For && (Conditional-And) :-

x==y will evaluates first and if that comes true then it will evaluates a<b. as Conditional-And evaluate from left to right.

And if you use only & operatore :- (And Operator)

In this case both the condition will be evaluated. irrespective of first condition (Left Condition) fail or pass.

2

&& operator evaluates from left to right

If first evaluates x==y first and then a<b, however there is a catch here. If x==y evaluates to false, anyway the whole expression tends to go false, hence a<b wont be evaluated. This is the basic optimization we get when we use &&.

If you want the other expression to be evaluated even though the first expression tends to false, we could use & like

  (x==y & a<b)

Check the following examples:

 int x=10,y=9,count=0;
    if(x==y && ++count == 0){
        System.out.println("true");
    }
    System.out.println(count);

Output would be 0 in this case

 int x=10,y=9,count=0;
    if(x==y & ++count == 0){
        System.out.println("true");
    }
    System.out.println(count);

Output would be 1 in this case. Check the operator carefully, we used &

0

x==yis evaluated and only if it was true, will a<b be evaluated

0

&& (as AND) and || (as OR) evaluate left expression first and only if it is needed, continue evaluating the second expression.

For example:

  • False && Anything will always return False without evaluating the secong expression.
  • True || Anything will always return True

You can also use & and |, which evaluates both expressions. (If the second expression throws exception, the evaluation will fail.) If you need faster and more secure evaluation, use && and ||.

0

The && will evaluate from left to right. The left expression to the operator && is evalutaed first, if it execute to false then the right expression is never evaluated and if the left expression is true than the right expression is evaluated.

0

&& is processed left-to-right. If first argument is false then other arguments are ignored. It will process arguments on right if and only if all the arguments on the left are true. It is known as short-circuiting.

In your case, if x==y is false then a<b will not be evaluated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.