DEV Community

Neema Rajasree Soman
Neema Rajasree Soman

Posted on

Divide By Zero

Mathematically, any number when divided by zero is not defined. However in Java programming, the division by zero usually gets related to an Exception, which is ArithmeticException.

For example:

public class DivisionByZero {

   public static void main(String[] args){
      System.out.println( 5 / 0 );
   }

}
Enter fullscreen mode Exit fullscreen mode

The above code snippet gives us a ArithmeticException as below:

Exception in thread "main" java.lang.ArithmeticException: divide by zero

This could lead most of us to the assumption that whenever we divide a number by zero in Java we get the ArithmeticException, but that isn't the case.

What if the datatype of the number being divided by zero is float or double?

Let's check out,

public class DivisionByZero {

   public static void main(String[] args){
      System.out.println( 5.0f / 0);
      System.out.println( 6.0d / 0);
      System.out.println( 0f / 0);
      System.out.println( -7.0f / 0);
   }

}
Enter fullscreen mode Exit fullscreen mode

When the above code gets executed no exception will be thrown, rather we get the below output:

Infinity
Infinity
NaN
-Infinity
Enter fullscreen mode Exit fullscreen mode

So why didn't the division by zero with float or double values didn't throw any exception.

It's because, in Java division of an integer by 0 is not covered by the IEEE 754 standards therefore generates an ArithmeticException. In case of division of float or double values Java follows the IEEE 754 standards and have special numeric values that represent the result of such operations such as NaN, Infinity & -Infinity.

So to summarize, In Java values such as Nan & Infinity are available only for floating-point numbers ( As per the IEEE 754 standards), therefore the division by zero operation on floating-point numbers is allowed. Since no special values like Nan are aligned to integer, the division by zero results in ArithmeticException.

Hope this article is useful. Thanks!

Top comments (0)