The following statement throws java.lang.ArithmeticException: / by zero as obvious.
System.out.println(0/0);
because literal 0 is considered an int literal and division by zero is not allowed in integer arithmetic.
The following case, however, does not throw an exception, for example java.lang.ArithmeticException: / by zero .
int a = 0; double b = 6.199; System.out.println((b/a));
Infinity displayed.
The following statement creates NaN (Not a Number) without exception.
System.out.println(0D/0); //or 0.0/0, or 0.0/0.0 or 0/0.0 - floating point arithmetic.
In this case, both operands are considered double.
Similarly, the following operators do not make an exception.
double div1 = 0D/0; //or 0D/0D double div2 = 0/0D; //or 0D/0D System.out.printf("div1 = %s : div2 = %s%n", div1, div2); System.out.printf("div1 == div2 : %b%n", div1 == div2); System.out.printf("div1 == div1 : %b%n", div1 == div1); System.out.printf("div2 == div2 : %b%n", div2 == div2); System.out.printf("Double.NaN == Double.NaN : %b%n", Double.NaN == Double.NaN); System.out.printf("Float.NaN == Float.NaN : %b%n", Float.NaN == Float.NaN);
They make the following conclusion.
div1 = NaN : div2 = NaN div1 == div2 : false div1 == div1 : false div2 == div2 : false Double.NaN == Double.NaN : false Float.NaN == Float.NaN : false
They all return false. Why is this operation (division by zero) allowed with floating point or double precision numbers?
By the way, I can understand that floating point numbers (double precision numbers) have their own values, which are positive infinity, negative infinity, and not a number ( NaN ) ...
java arithmeticexception dividebyzeroexception
Tiny Oct 18 '12 at 12:05 2012-10-18 12:05
source share