int result = 5;
result = result--;
System.out.println(result);
Why is the result equal to 5?
int result = 5;
result = result--;
System.out.println(result);
Why is the result equal to 5?
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).
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)
Very valid question!
Your code doesn't work since result--
is performed only after the substitution =
. Your code would work had you used prefix operator:
result = --result;
However that doesn't make any sense as you can simply write:
--result;
For a more thorough explanation see this question/answers on how prefix/postfix operators work on Java.
This is confusing construct. Its the same as
int tmp = result;
result--;
result = tmp;
You are using the post-decrement operator. This is because you are writing result--
but not --result
. The value of the expression result--
is a copy of result
, it is defined before the decrementing. That's why it's called post-decrement.
After the value of the expression result--
is defined, result
is decremented. But: Right after this, the value of result
is overriden by the value of the result--
expression (result = 5
), which was 5.
result-- is post decrement.. which means that the value is first assigned to result and then decremented.
you might find this answer helpful.
I believe what you want to do is :
int result = 5;
result--;
System.out.println(result);
change to prefix increment to get desired result, or remove the assignment statement:
int result = 5;
result = --result;
System.out.println(result);
try
result=--result; it will print 4, and you will come to the understanding of what is the diffrence between c-- and --c