0

Why does following java code not give compilation error for "Unreachable Code" ? It can be easily seen that code will never enter "Line 1" and "Line 2" blocks whatever is the value of flag.

    final boolean flag = true;
    if (flag) {
        System.out.println();
    } else if(flag) {    //Line 1
        System.out.println();
    } else if (!flag) {
        System.out.println();
    } else { //Line 2
        System.out.println();
    }
GregT
  • 1,039
  • 4
  • 14
  • 34
Pankaj Bansal
  • 889
  • 1
  • 12
  • 37
  • `flag` as `final`. – SatyaTNV Dec 19 '17 at 09:19
  • hmm . .. missed that. – Stultuske Dec 19 '17 at 09:21
  • 1
    Nothing wrong with the question IMHO, but the duplicate has the answer. Java's definition of reachability is somewhat arbitrary. – Bathsheba Dec 19 '17 at 09:22
  • Because the compiler doesn't contain the logic to search for that. It can find some cases of unreachable code, but you can easily fool it as you see. It's not useful to write that logic, because if a programmer writes like that by mistake, then all the compiler errors in the world won't be of much help. – Kayaman Dec 19 '17 at 09:22
  • @Bathsheba "Nothing wrong with being lazy let others do your research IMHO" fixed it for you :) – Tom Dec 19 '17 at 09:25

0 Answers0