Search code examples
compiler-errorsjava-8javajls

Is `1/0` a constant expression in Java?


As far as I understand the Java 8 JLS the expression (1/0) is considered a constant expression, but when I try to compile the following program with OpenJDK 8 I get an error

public class Switch {
    public static void main(String[] args) {
        switch(42) {
            case (1/0):
                return;
            default:
                return;
        }
    }
}

The error says (1/0) isn't a constant expression

Switch.java:4: error: constant expression required
            case (1/0):
                 ^
1 error

Am I missing something? Or is it a bug in OpenJDK 8?


Solution

  • 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.