Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post Decrement in Java [duplicate]

Tags:

java

int result = 5;    
result = result--;  
System.out.println(result);  

Why is the result equal to 5?

like image 988
ivan angelo Avatar asked May 10 '26 11:05

ivan angelo


2 Answers

Because the value of the expression result-- is the value of result before the decrement. Then result is decremented and finally the value of the expression is assigned to result (overwriting the decrement).

like image 148
Ted Hopp Avatar answered May 13 '26 00:05

Ted Hopp


This does nothing :

   result = result--;  

Because result-- returns the value of result before it is decremented (contrary to --result which returns the value of result after it is decremented). And as the part to the right of = is executed before the =, you basically decrement result and then, on the same line, set result to the value it had before the decrement, thus canceling it in practice.

So you could write

   result = --result;  

But if you want to decrement result, simply do

result--; 

(or --result; but it's very unusual and atypical to use it on its own, don't do it when you don't want to use the result of the expression but simply want to decrement)

like image 38
Denys Séguret Avatar answered May 13 '26 02:05

Denys Séguret



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!