Could someone tell me why the value of a is not changing in the following code?
int a = 10;
System.out.print( (a < 5) && (++a==11));
System.out.println(a);
You're seeing "short circuit evaluation" in action. The second part of the boolean expression (++a==11)
is never evaluated, because (a < 5)
is false. In this case, the JVM knows that the whole expression is false before it evaluates (++a==11)
, so it skips it entirely.
This is also a great example of why such "side effects" are bad in logical tests: you're mutating the values you're evaluating in an unpredictable way. In a non-trivial program, you don't necessarily know whether (a < 5)
is true, so it's difficult to know whether a
will be incremented or not.