Phewz
Phewz

Reputation: 3

Java multiply long and float number, which datatype is the result?


can someone explain why 'c' has to be a double although "0.2f" is defining it as float?
I thought the 'f' stands for a float number.
Sorry if this is a stupid question but I am wondering..

    a = 4294967296L;
    b = 'n';
    c = (3.1415926 * 0.2f) * a;

=>

    long a = 4294967296L;
    char b = 'n';
    float c = (3.1415926 * 0.2f) * a;

change 'c' to double =>

    long a = 4294967296L;
    char b = 'n';
    double c = (3.1415926 * 0.2f) * a;

Upvotes: 0

Views: 3494

Answers (3)

salembo
salembo

Reputation: 11

In your example you are using three kind of types: a double, a float and a long. So because of it you have to declare c as a double since double is bigger than float but if you just use

long a = 4294967296L;
char b = 'n';
float c =  0.2f * a;

then c can only be float and not long because declaring c as long will make lose precision to the result and you're program won't compile

Upvotes: 0

Henry
Henry

Reputation: 43738

That's because 3.1415926 is a double constant. So the expression (3.1415926 * 0.2f) gives a double result which when multiplied by a long is still double.

Btw. if you wanted to multiply by pi, better use Math.PI.

Upvotes: 3

chenchuk
chenchuk

Reputation: 5742

This is because the default type for floating point number is double by the compiler (so the 3.14 consider as double):

// cant compile  3.14 is double and double*something = double
float c = (3.1415926 * 0.2f) * 4294967296L;

// this is ok ( 3.14 is now float and not double.
float c = (3.1415926f * 0.2f) * 4294967296L;

Upvotes: 0

Related Questions