Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Exception: / by zero only works on integers in Java

Why such different answers on dividing a number by zero:

My code:

class Test {
  public static void main(String[] args){

    int a = (int)(3/0.0F);
    System.out.println(a);

    System.out.println(3/0.0F);

    System.out.println(3/0);
  }
}

Output:

2147483647
Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero

Every time I divide a number by an integer (byte, short, int, long) it throws ArithmeticException, which is not the case when done with real numbers (float, double). Why?

like image 985
Himanshu Aggarwal Avatar asked Feb 27 '26 16:02

Himanshu Aggarwal


1 Answers

From JLS §15.17.2:

  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

with the exception that:

if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

like image 86
Nir Alfasi Avatar answered Mar 01 '26 12:03

Nir Alfasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!