Is 1/0 a legal Java expression?

前端 未结 8 1210
萌比男神i
萌比男神i 2020-11-27 16:47

The following compiles fine in my Eclipse:

final int j = 1/0;
// compiles fine!!!
// throws ArithmeticException: / by zero at run-time

Java

相关标签:
8条回答
  • 2020-11-27 17:42

    Since others already answered the legality of 1/0, let's move to the second question:

    • If this is legal, is there a good reason for it?
      • What good could this possibly serve?

    An answer could be:

    To tease a colleague of yours. ;o)

    When the colleague leaves the room with his computer left unlocked, sneak by and burry 1/0 somewhere deep into a static initializer of some class that is used early in the application. This way he will find out soon enough after (or even during) the deployment of the application by encountering the unusual ArithmeticException and he will probably scratch his head for a while. Using this fail-fast way you can ensure it's a relatively harmless joke.

    P.S.: It worked. ;o)

    0 讨论(0)
  • 2020-11-27 17:47

    It's legal because no where is it a given that the compiler is supposed to fold constant expressions at compile time.

    A "smart" compiler might compile:

    a = 1 + 2
    

    as

    a = 3
    

    But there's nothing that says the compiler HAS to do that. Other than that, 1/0 is a legal expression just like:

    int a;
    int b;
    
    a = a/b;
    

    is a legal expression.

    At RUNTIME it throws an exception, but that's a runtime error for a reason.

    0 讨论(0)
提交回复
热议问题