To determine Infinity or Exception in Java?
Consider two programs in Java:
Program 1:
public class Demo
{
public static void main(String[] args)
{
double a = 1;
System.out.println(a/0);
}
}
Output of Program 1:
Infinity
Program 2:
public class Demo
{
public static void main(String[] args)
{
int a = 1;
System.out.println(a/0);
}
}
Output of Program 2:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Demo.main(Demo.java:8)
Explanation:
In first program a double value is divided by 0 and in second program an integer value is divide by 0 but the output differs giving infinity in first program while an exception in second program. This is because an ArithmeticException is thrown in case of integer division but in case of float/double division by 0 it implements the floating point arithmetic algorithm which specifies a special values like Not a number OR infinity for divided by zero cases as per IEEE 754 standards.
0 Comment(s)