We all know that int++ will increase the variable value by 1, that is to say:
int number = 0;
int temp = number + 1;
number = temp;
This is allowed by the other primitive types too:
double number = 0D;
number++;
So, I was wondering if the code above will be executed as:
double number = 0D;
double temp = number + 1D;
number = temp;
Or:
double number = 0D;
int temp = number + 1;
number = temp;
In the second case, should we prefer double += 1D instead?
The
++(prefix or postfix) is not something that just works onintand if you use it with other primitive types, this does not mean that there is an intermediate conversion tointand back.See the Java Language Specification:
As the JLS says, binary numeric promotion is applied to the variable and the value
1. In case ofnumber++wherenumberis adouble, this means that the1is treated as adouble.So,
number++works the same asnumber += 1Difnumberis adouble. It is not necessary to donumber += 1Dexplicitly.Note: If there would be an intermediate conversion to
intand back, as you suggest in your question, then you would expect that:would result in
numberbeing1.0instead of1.5, because the conversion would throw the decimals away. But, as you can see, this is not the case.