Java: Variable assignment issue

just a quick question and I'm probably gonna feel stupid for asking but still would like to know why it is so...!

Anyways, quick example:

x is a double.

double conversion = (x-32)*5/9;

This does the maths just fine.

double  conversion = (x-32)*(5/9);

This isn't fine because the (5/9) is being treated as an int, thus result is overall 0.

double  conversion = (x-32)*(5f/9f);

This does the maths just fine, as it explicitly makes the 5/9 values a float.

So my question is: Why does the first equation work perfectly fine? ( double conversion = (x-32)*5/9; )

Why isn't the 5/9 being made a 0 if it were an int supposedly? What makes the 5/9 different from (5/9) ?

Jon Skeet
people
quotationmark

The difference is between whether you do the multiplication first or the division first - and what the types of those operations are.

This:

(x - 32) * 5 / 9

is equivalent to:

((x - 32) * 5) / 9

So if the type of x is double, then the type of x - 32 is double, so the 5 is promoted to double, the multiplication is done in double arithmetic, giving a double result, and then the division is also done in double arithmetic.

Even if x is an integer type, you're doing the multiplication first, which will presumably give you a value bigger than 9 (in your test case), leaving you with a non-zero result. For example, if x is 45, then x-32 is 13, (x - 32) * 5 is 65, and the overall result is 7, then converted to 7.0 on assignment. That's not the same result you'll get if x is a double with the value 45.0, but it's still better than multiplying by 0...

people

See more on this question at Stackoverflow