Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java post increment and pre increment

Tags:

java

increment

The following code in Java:

int a = 0, b = 0, c = 0;
boolean d = (a++ > 0 && b-- < 0) || --c < 0;

results in the values:

a = 1, b = 0, c = -1 and d = true

I don't understand why a is = 1, because it is a post-increment and should also react the same way that value b does. Also, if I change the b-- to --b it still has no effect on the value of b.

What is the best way of understanding this logic?

like image 465
shomsky Avatar asked Jun 22 '26 04:06

shomsky


1 Answers

a++ > 0 returns false, since a++ return the previous value of a (0).

Therefore b-- < 0 is not evaluated at all, since && is a short circuiting operator. The right operand is only evaluated if the left operand is true.

--c < 0 is evaluated, since the first operand of the || operator is false, so the second operand must be evaluated.

After d is evaluated, the value of a is 1, since a was incremented. b remains 0, since b-- wasn't executed. c is -1 since --c was executed. And d is true since --c < 0 is true.

like image 180
Eran Avatar answered Jun 23 '26 19:06

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!