-2

If dead codes are illegal in java, why does the following code compile fine without any compile time error :

int i= 5;

while (i<2) {
  //some code here
}

Since the while condition is not getting satisfied, it will never go into the loop, so I assume this should be dead code. But it is getting compiled perfectly.

gudok
  • 4,029
  • 2
  • 20
  • 30
  • anything that is syntactically correct will be compiled fine, dead codes are of logical concern. – jack jay Dec 05 '17 at 14:49
  • what if some client code the compiler has no knowledge of increments `i`? compiler is not omnipotent. –  Dec 05 '17 at 14:49
  • 2
    Closely related: https://stackoverflow.com/questions/13235559/why-does-the-java-compiler-not-understand-this-variable-is-always-initialized - make the variable `final` and it won't compile any more. – assylias Dec 05 '17 at 14:50
  • A good IDE should show a warning at least, but the java compiler doesn't care if you do that. – xander Dec 05 '17 at 14:51
  • A good IDE has no reason to show any warnings, there is nothing to warn about in this code. –  Dec 05 '17 at 14:52
  • @JarrodRoberson Well IntelliJ does: "Condition 'i<2' is always 'false'". Also I know some programming languages that show a compiler warning for "unreachable code". – xander Dec 05 '17 at 14:56
  • Why do you think that code containing "dead code" shouldn't compile? Do you know the difference between "dead code" and "unreachable code"? https://stackoverflow.com/questions/22802698/whats-the-difference-between-dead-code-and-unreachable-code – Tom Dec 05 '17 at 14:57
  • @xander A compiler shows an error for unreachable code. You're talking about dead code. – Tom Dec 05 '17 at 14:57
  • @xander - in what context? local variable yes, instance variable nope, the code in the question is not specific. –  Dec 05 '17 at 15:14
  • @JarrodRoberson I was just talking about the example in the question, with a local variable. – xander Dec 05 '17 at 15:15

2 Answers2

3

Java has a very tightly defined set of rules for defining reachability at compile time. (Note that a program can never know in full generality.)

Your case is not one of those, so compilation passes.

(It would be annoying if the reachability rules were constantly changing as that would cause code to break on successive version updates.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Java cannot determine the value of a variable in general without simply running the program. If it runs your program, it risks failing to terminate. So there is no general way to determine whether or not that loop will always run or not. There will always be cases that the compiler gets wrong, so it uses basic heuristics to handle the easy cases and leaves it at that.

Further reading

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 1
    Not really - the rules are very clearly defined. Whether they should be different is another discussion. – assylias Dec 05 '17 at 14:54