In Java, I am dividing by zero, which obviously does not produce a number.
public class tempmain {
public static void main(String args[])
{
float a=3/0;
System.out.println(a);
}
}
I expect the output to be "NaN", but it shows the following error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at tempmain.main(tempmain.java:6)
Is there any way (apart from if(denominator==0)
) by which NaN can be displayed?
You are getting the unexpected ArithmeticException because of the way that your numeric literals 3 and 0 are treated. They are interpreted as integers, despite the fact that you assign a
to be a float. Java will interpret 3
as an integer, 3f
as a float and 3.0
or 3d
as a double. The division is performed as integer division and the result cast to a float. To see another interesting other effect of this - try float a = 1/3
and inspect a
- you will find it is 0.0, rather than 0.3333.... as you might expect.
To get rid of the Exception - change
float a = 3/0;
for
float a = 3f/0;
As others have noted in comments and answers, if you then print a
, you will see Infinity
rather than NaN
. If you really want to print NaN in this case, you can test a for being infinite i.e.
if (Float.isInfinite(a)) {
System.out.println("I want to print Infinity as NaN");
}
but I'd recommend against it as highly misleading - but I suspect that's not what you meant anyway