4

Possible Duplicate:
Why doesn't a Java constant divided by zero produce compile time error?

String s1="hi"+"Ram"

is a constant expression and evaluated at compile time.but a constant Divide by zero is also a constant expression and evaluated at run time why ?

Community
  • 1
  • 1
Neeraj singh
  • 257
  • 1
  • 8
  • 18
  • 2
    http://stackoverflow.com/questions/4980360/why-doesnt-a-java-constant-divided-by-zero-produce-compile-time-error – kosa Sep 14 '12 at 19:02

2 Answers2

1

A constant value MAY be computed at compile time, if the compiler can maintain the same semantics as if it were done at run time. If not (eg, the case of divide by zero) then it defers the computation to run time. For more info read JLS 15.28.

Tushar Paliwal
  • 301
  • 4
  • 11
0

Your string can be optimized with no change in the working of the class. That's the reason why it can be evaluated at compile time.

The expression 1.0/0.0 isn't an error, as long as you don't evaluate it, but it can't be evaluated at compile time, because this would change the meaning (it would make an error from a perfectly valid (as long as not evaluated) expression. I agree that a smart compiler could prevent you to do this, but the spec would have to allow it.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758