Nested if conditions can cause side effects sometime. When there is an if condition in your program and there is more than one condition with a conditional operator like AND or OR then you need to be aware that there could be a side effect(depending on what you have in that condition). In case of Java, during run time the JVM (Java Virtual Machine) could bypass a second condition based on the result of the first condition because logically it does not make sense to evaluate the second condition. Say for example you have a condition like the one below.
if(x > 50 && y < 20)
In case of an AND condition, if the first condition evaluates to be false then there is no point in evaluating the second condition becuase the result is going to be anyway false. So in the above program statement if
x had a value of
30 then the condition
y < 20 will not be evaluated at all. Similarly in case of an OR condition if the first condition evaluated to be true then there is no point in evaluating the second condition because anyway the result will be a true.
So where does the side effect come into picture? Side effect comes into picture if you are combining assignment and coniditions together. Look at the below example.
if (x > 50 && (y=y*2) < 2)
If the first condition is true then whatever you expected would be correct. Now if
x has a value of
30 then the second condition that includes an assignment of
y=y*2 will never take place, and if you didn’t know this then you would be under the assumption that whatever code that executes after the if statement will use a
y*2 value for
y. In software programming terms, this is called as short circuiting. So beware of the side effects of short circuiting when you are having nested conditions.