3

The following code compiles successfully:

int x;
if(true)
  x=3;
System.out.println(x);

Does that mean the if condition is evaluated at compile time? If so why does the following code not throw Unreachable Statement error?

if(true)
  return;
return;  //No error

What's the difference?

Edit: Please note that my query is different as I am not comparing 'if' with 'while'. Rather I am comparing the same if(true) statement in two different situations, in the first one it appears to be evaluated at compile time, while in the 2nd case, it appears to be evaluated at runtime.

paidedly
  • 1,413
  • 1
  • 13
  • 22
  • This is explained in [Rahul's](http://stackoverflow.com/a/20299955/438154) answer in the duplicate. – Sotirios Delimanolis Jun 08 '15 at 14:51
  • 1
    The how is the compiler sure that x will be initialized before it is printed? Thus, it should be a compile time error. – paidedly Jun 08 '15 at 14:53
  • It's special-cased to not be a compile-time error, as a convenience. It's in [JLS 14.21](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.21) -- search for "one might expect." You can verify the behavior by compiling a simple `if (true) System.out.println("A"); else System.out.println("B");` and then running the resulting class file through `javap -c` to see the bytecode. – yshavit Jun 08 '15 at 14:55
  • The answer is [here](http://stackoverflow.com/a/20299947/4454454) – MaxZoom Jun 08 '15 at 14:57

0 Answers0