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

1.1k views Asked by At

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?

3

There are 3 answers

0
Jesper On BEST ANSWER

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.

0
nv3 On

Don't worry. The compiler knows how to best increment int, float or double types. It will generate efficient code for each case. If you look at the generated assembler code it will most like be the same code generated for:

doubleVar++;
++doubleVar;
doubleVar += 1;
doubleVar += 1.0;

But be aware that for class types things are much more complex. There, the operator+ or operator+= overloads are used. Generally, the post-increment operations are more time consuming as the objects state has to be saved before the increment. Therefore you should get used to always use the pre-increment version, even for the scalar types -- except you really need a post-increment operation.

0
SubOptimal On

The code

double number = 0D;
number++;

is executed as

double number = 0D;
number = number + 1D;

the generated bytecode

// double number = 0D;
0: dconst_0
1: dstore_1

// number + 1D
2: dload_1
3: dconst_1
4: dadd

// number =
5: dstore_1