Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement in Java [closed]

Tags:

java

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

Why is the result equal to 5?

like image 367
ivan angelo Avatar asked Jun 18 '12 16:06

ivan angelo


People also ask

What is the decrement operator in Java?

In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1.

How do you decrement an int in Java?

Decrement Operator // declare variable int x; // assign value x = 10; // decrease value by 1 x = x - 1; To achieve the same result we use the decrement operator -- . So, decrement operator -- decreases the value of a variable by 1. In the following example we are decreasing the value of x by 1.

What happens when you decrement a variable?

The decrement operator is represented by two minus signs in a row. They would subtract 1 from the value of whatever was in the variable being decremented. The precedence of increment and decrement depends on if the operator is attached to the right of the operand (postfix) or to the left of the operand (prefix).


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 122
Ted Hopp Avatar answered Oct 18 '22 17:10

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 Oct 18 '22 16:10

Denys Séguret