Is `1/0` a constant expression in Java? [duplicate]

The compiler is doing constant folding (precomputing trivial literal expressions). This is a case where the expression “completes abruptly”, to use the JLS verbiage, disqualifying it from meeting the definition of “constant expression”. So it’s not a bug, it’s consistent with the JLS.

And yes, the expression doesn’t evaluate to a value either (warning the user trying to do something like this that the result will not be a constant expression), but the compiler doesn’t know that until it tries. Not evaluating to a value and completing abruptly would seem to go hand-in-hand.

Adding a variable declaration like

int x = 1 / 0;

doesn’t cause a compiler error, it’s the switch that forces the expression to be evaluated at compile time.

By the way I checked that this happens for version 7 of the Oracle and IBM JDKs too, it’s not OpenJDK or JDK8 specific.

Leave a Comment