Search code examples
javaincrementprimitive

Is it ok to use increment operators with any primitive type?


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?


Solution

  • The ++ (prefix or postfix) is not something that just works on int and if you use it with other primitive types, this does not mean that there is an intermediate conversion to int 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 of number++ where number is a double, this means that the 1 is treated as a double.

    So, number++ works the same as number += 1D if number is a double. It is not necessary to do number += 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:

    double number = 0.5;
    number++;
    

    would result in number being 1.0 instead of 1.5, because the conversion would throw the decimals away. But, as you can see, this is not the case.