Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question regarding unreachable statement errors

Given this snippet of code, containing a class TestClass with its method loopTest(), which is our main focus:

public class TestClass{
   public void loopTest(){
      int x = 0;
      loop: for (int i = 1; i < 5; i++){
         for (int j = 1; j < 5; j++){
            System.out.println(i);
            if (x == 0) {  continue loop;  }
            System.out.println(j);
         }
      }
   }
}

Running this code in IntelliJ IDEA doesn’t return any compilation errors, but successfully returns an output. My question would be: why isn’t this an unreachable statement?

Running the loop after removing the if (x == 0) statement (but keeping the continue loop; as seen below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

loop: for (int i = 1; i < 5; i++){
         for (int j = 1; j < 5; j++){
            System.out.println(i);
            continue loop;
            System.out.println(j);
         }
      }

(…) would return such an error, because the last sout would never be printed. Why doesn’t this also happen in the first case? I’m pretty confident this isn’t some runtime problem, because the compiler definitely sees that integer x is initialized at the beginning of the method, but the loop never reaches the second statement.

>Solution :

This is because the compiler has limits on how deep the analysis goes.

if (false) System.out.println("never");

is fine for example because these conditions aren’t checked. The compiler assumes that conditionals can be true even if that’s impossible in practice.

Code after an unconditional continue, return, break are known to be unreachable without further analysis.

Newer languages can do that kind of analysis and I think tools like SonarLint could find that as well. Even Java at runtime might optimize that code away but I guess the age / state of static code analysis at the time when Java was formalized is responsible for this behavior.

The if (false) trick is also a fairly common way to disable code for quick testing so adding this now could break a lot of code and I guess that makes it unlikely to get added as a language / compiler feature although it’s perfectly doable nowadays.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading