Infinity or exception in Java when divide by 0?

Java Programming Java 8Object Oriented Programming

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.

raja
Published on 19-Sep-2018 11:18:11
Advertisements