Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Wed Jun 05, 2013 9:30 am
by Crashtest
Is there some easy way to determine what type will a result of mathematical expression be? Like here, because it's divided by 4.0, it returns double. Are there some other simple rules to remember?

Re: About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Thu Jun 06, 2013 6:05 am
by admin
There can be only four return types in case of numeric - int, long, float, and double.
The type of the expression will be the largest required. i.e. if the largest constituent in long, then the return type will be long.

For example:

long x = 10L;
int p = x/2; //will not work because x/2 is long
long p = x/2.0; //will not work because x/2.0 is now double

The return type of an expression is never a byte, char, short. For example,
byte x = 10;
byte p = x*1; //will not work because x*1 is an int.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Thu Jun 06, 2013 8:18 am
by Crashtest
Thank you, finally this is clear. I have not found this anywhere before and yet it is so simple.

Re: About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Tue Dec 31, 2019 9:22 am
by robinzclark
You say that "There can be only three return types in case of numeric - int, long, float, and double." That is FOUR types, right? How do you know when float will be returned versus when double will be returned?

Re: About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Tue Dec 31, 2019 10:00 am
by admin
Yes, I should have written four above (corrected). Thanks for pointing it out.
float will be returned when the largest component of an expression is a float, for example:
int a = 1;
float b = 2.0f;
double d = 2.0;
float c = a*b; //valid, a*b will return a float because the larget component of a*b is b, which is a float.
float x = a*d; //invalid because a*d will return a double

Paul.

Re: About Question enthuware.ocajp.i.v7.2.1154 :

Posted: Thu Jan 02, 2020 8:41 am
by robinzclark
Thank you Paul that is a great explanation.