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 onint
and if you use it with other primitive types, this does not mean that there is an intermediate conversion toint
and 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++
wherenumber
is adouble
, this means that the1
is treated as adouble
.So,
number++
works the same asnumber += 1D
ifnumber
is adouble
. It is not necessary to donumber += 1D
explicitly.Note: If there would be an intermediate conversion to
int
and back, as you suggest in your question, then you would expect that:would result in
number
being1.0
instead of1.5
, because the conversion would throw the decimals away. But, as you can see, this is not the case.