Why does it show Infinity instead of throwing the exception?
Integer Class :
public class Entier {
int A;
public Entier(int A){
this.A = A;
}
public double division(Entier diviseur){
return (double) this.A / diviseur.A;
}
}
TestDivision Class
public class TestDivision {
public static void main(String[] args) {
Entier compare = new Entier(5);
Entier comparant = new Entier(12);
Entier zero = new Entier(0);
System.out.println(
comparant.division(compare)
);
System.out.println(
comparant.division(zero)
);
System.out.println(1/0);
// 2.4
// Infinity
// throws ArithmeticException
}
}
I'm using Amazon Corretto JDK-17.
To understand the difference between your two cases, note that
is equivalent to
since casting takes precedence over division.
So although
A
is anint
you are doing a floating-point division that allows division by zero with a result of plus/minus infinity.To the contrary
1/0
is a pure integer-division that should give an integer-result, so infinity would not be valid and theArithmeticException
is thrown.