Question

Please check below codes ...

    // this will produce java.lang.ArithmeticException: / by zero
    System.out.println(1 / 0);
    // this will produce Infinity result
    System.out.println(1.1 / 0);

I assume Integer arithmetic will always throws java.lang.ArithmeticException: / by zero. If so , I guess the first statement or System.out.println(Integer.parseInt("1") / 0); should produce compile-time exception. But I didn't get any compile time errors or warnnings on my Eclipse IDE. Or may be I am wrong.
Any suggestions ?

Was it helpful?

Solution

Integer.parseInt("1") will only be executed at runtime. The compiler doesn't know if the parse operation would even succeed.

Depending on the compiler 1/0 might get optimized at compile time and the compiler might just write the result into the compiled code. Hence it would throw the exception right there. However, if that calculation isn't optimized, the compiler wouldn't know the result of that operation until it is executed.

Btw, my Eclipse compiler doesn't seem to do that (I didn't check the settings yet) and compiles 1/0 just fine.

UPDATE

Although 1/0 would be a constant expression which can be evaluated at compile time, the compiler might still opt to ignore that and compile the code.

Here's some a similar question with some more info: Why doesn't a Java constant divided by zero produce compile time error?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top