Hi there,
I just want to have a confirmation. I have two
variables like this:
int i = 10;
double d = 10.1;
Now I test whether d is greater and do such a thing:
if (i<d)
greater_double();
else
smaller_or_equal_double();
My question is the following. Does Java internally
converts the int(eger) i to double before comparison
(as I assume it does) or might there be circumstances
where it did not in such a case?
Best regards,
Bart
Hendrik Maryns - 10 May 2006 13:27 GMT
Bart Rider schreef:
> Hi there,
>
[quoted text clipped - 13 lines]
> (as I assume it does) or might there be circumstances
> where it did not in such a case?
It does. See
http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#26917
HTH, H.
- --
Hendrik Maryns
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
liuyanbupt@gmail.com - 10 May 2006 13:34 GMT
I find the following statements in "The Java Language Specification
Third Edition":
-----------------------------------------------------------------------------------------------------------------
5.6.2 Binary Numeric Promotion
...
· If either operand is of type double, the other is converted to
double.
...
15.20.1 Numerical Comparison Operators <, <=, >, and >=
The type of each of the operands of a numerical comparison operator
must be a
type that is convertible (§5.1.8) to a primitive numeric type, or a
compile-time
error occurs. Binary numeric promotion is performed on the operands
(§5.6.2). If
the promoted type of the operands is int or long, then signed integer
comparison
is performed; if this promoted type is float or double, then
floating-point comparison
is performed.
-----------------------------------------------------------------------------------------------------------------
So, I think what you assumed is the right answer.
Thomas Fritsch - 10 May 2006 13:40 GMT
Bart Rider schrieb:
> I just want to have a confirmation. I have two
> variables like this:
[quoted text clipped - 11 lines]
> (as I assume it does) or might there be circumstances
> where it did not in such a case?
Just one addition to what the other posters correctly said:
You can check it by disassembling your java class with "javap -c ...".
There should be an "i2d" (int to double) instruction.

Signature
"Thomas:Fritsch$ops:de".replace(':','.').replace('$','@')
Patricia Shanahan - 10 May 2006 14:01 GMT
> Hi there,
>
[quoted text clipped - 16 lines]
> Best regards,
> Bart
The JLS requires the same answer as if the program did the conversion of
i to double followed by the comparison.
An optimizing compiler might not actually generate the conversion, if it
noticed that i<d is a constant expression, did the comparison at compile
time, found that is is always true, and collapsed the if statement.
Patricia