Infinity or exception in Java when divide by 0?


Consider the following code snippet where we divide a number by 0.

Example

 Live Demo

public class Tester{
   public static void main(String[] args) {
      double d = 100;
      System.out.println(d/0);
   }
}

Output

Infinity

Now consider the following code snippet.

Example

 Live Demo

public class Tester{
   public static void main(String[] args) {
      int d = 100;
      System.out.println(d/0);
   }
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Tester.main(Tester.java:5)

As you've noted, the Infinity vs ArithmeticException, a different result for similar divide by zero program. The difference lies in floating point arithmetic used in first program and integer arithmetic used in second program.

Updated on: 23-Jun-2020

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements