Hi all,

I just want to point out an interesting fact when casting int values.
In pdf document "Working with built-in Java classes", page48, it says:

int      numInt1 = 1;
int      numInt2 = 2;
//result is implicitly casted to type double
double   numDouble = numInt1/numInt2;

We might expect that the result numDouble now contains the value of
0.5, because there was an implicit casting to double. But that's not
correct!
numInt1/numInt2 is a division of int-values, which results also in an
int-value of 0. This result is implicitly casted to a double-value of
0.0!
So if we want to get the correct result, we have to force the division
to be made with values of type double.

It would be enough to explicitly cast numInt1:
double   numDouble = (double)numInt1/numInt2;

But don't write:
double numDouble = (double) (numInt1 / numInt2);

This would evaluate to 0.0! The term in parenthesis would be
calculated first (integer!) with result 0. Afterwards we would cast to
double, but the result then remains 0.0!

Excuse me for writing such a long text on this simple problem. But it
took me quite a long time to find this error in my program.

Have fun,
Rita

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to