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


we know int++ increase variable value 1, say:

int number = 0; int temp = number + 1; number = temp; 

this allowed other primitive types too:

double number = 0d; number++; 

so, wondering if code above executed as:

double number = 0d; double temp = number + 1d; number = temp; 

or:

double number = 0d; int temp = number + 1; number = temp; 

in second case, should prefer double += 1d instead?

the ++ (prefix or postfix) not works on int , if use other primitive types, not mean there intermediate conversion int , back.

see java language specification:

as jls says, binary numeric promotion applied variable , value 1. in case of number++ number double, means 1 treated double.

so, number++ works same number += 1d if number double. not necessary number += 1d explicitly.

note: if there intermediate conversion int , back, suggest in question, expect that:

double number = 0.5; number++; 

would result in number being 1.0 instead of 1.5, because conversion throw decimals away. but, can see, not case.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -