Please got through the following code snippet.
class NanTest {
public static void main ( String args [ ] ) {
int intX = 10 ; // line 1
float floatX = 10 ; // line 2
double doubleX = floatX / 0 ; // line 3
double doubleY = intX / 0 ; // line 4
System . out . println ( doubleX == doubleY ) ; // line 5
}
}
It throws exception on line 4 but not on line 3.
Could anyone please explain this.
> It throws exception on line 4 but not on line 3.
> Could anyone please explain this.
Did you try to display the value of doubleX?
Floating point division never results in an exception. In this case,
you get Infinity.
Integer division by 0 results in an exception.
See JLS 15.17.2:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#45471
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
> Please got through the following code snippet.
>
[quoted text clipped - 11 lines]
> It throws exception on line 4 but not on line 3.
> Could anyone please explain this.
http://java.sun.com/developer/TechTips/1998/tt0722.html#tip2
> Please got through the following code snippet.
>
[quoted text clipped - 11 lines]
> It throws exception on line 4 but not on line 3.
> Could anyone please explain this.
Line 4 is an int division by zero, and there is no way to represent the
result as an int, so it throws an exception.
Line 3 is a float division by zero, and there is a value,
Float.POSITIVE_INFINITY, that represents the result of dividing a
positive float by a zero float.
Patricia
Lew - 30 Sep 2006 04:54 GMT
>> class NanTest {
>>
[quoted text clipped - 9 lines]
>> It throws exception on line 4 but not on line 3.
>> Could anyone please explain this.
> Line 4 is an int division by zero, and there is no way to represent the
> result as an int, so it throws an exception.
>
> Line 3 is a float division by zero, and there is a value,
> Float.POSITIVE_INFINITY, that represents the result of dividing a
> positive float by a zero float.
http://docs-pdf.sun.com/800-7895/800-7895.pdf
and
http://docs.sun.com/source/806-3568/ncg_goldberg.html
The latter is the HTML form of the former.
- Lew