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!

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay