+ 12

Is this right way according to which the && operator works?

In Java, for a few days I have noticed that whenever I call an If-Else statement to check a particular condition with two conditions separated by an && operator, the compiler does not check the second condition if the first condition is true. For example, int x=0,y=0; if((++x>1)&&(++y>1)) x++; This ends up with the value of x being 1 and y being 0. And if, int x=0,y=0; if((++x>=1)&&(++y>=1)) x++; This ends up with the value of x being 2 and y being 1. I hope it's clear to you, if not then ask in the comments

9th Mar 2019, 10:32 AM
Jaagrav
Jaagrav - avatar
2 Answers
+ 12
It's normal because if the first check return false, there's no need to check the second (because logical and "&&" is true only if all conditional checks are true => ++x > 1 means 1 > 1 it is obviously false and no need to check the second condition. This is called "short-circuit"). In the second example in the conditional check is included "=" so => x >= 1 is true x becomes 1, y >= 1 is true => y becomes 1 the conditional check is true ( true && true return true) and x++ is evaluated => x is now 2. Hope it helps you.
9th Mar 2019, 10:46 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
It's normal because if the first check return false, there's no need to check the second (because logical and "&&" is true only if all conditional checks are true => ++x > 1 means 1 > 1 it is obviously false and no need to check the second condition. This is called "short-circuit"). In the second example in the conditional check is included "=" so => x >= 1 is true x becomes 1, y >= 1 is true => y becomes 1 the conditional check is true ( true && true return true) and x++ is evaluated => x is now 2. Hope it helps you.
18th Mar 2019, 12:21 AM
Lai Zeng