0

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);
jjanaskie
  • 29
  • 1

1 Answers1

0

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.

3bh
  • 806
  • 1
  • 6
  • 12
  • Please just vote to close duplicate questions instead of wasting your time answering them. :) – Roddy of the Frozen Peas Oct 16 '19 at 23:14
  • Ironically, there is a comment on the most popular answer on the question this duplicates complaining that that one is a duplicate... to repeat the reply: "I don't have time to search for duplicates of questions asked by other people, so I only close as duplicate if I know a specific question that this is a duplicate of. Otherwise, answering often takes much less time." :) We can certainly all help keep the site clean and free of duplicates, and we can also answer the question. – 3bh Oct 16 '19 at 23:18
  • The duplicate answers the question. you could spend your time answering an already answered question... or you can help someone who doesn't have an answer. – Roddy of the Frozen Peas Oct 17 '19 at 00:50