Search code examples
javafor-loopcontinue

What will this continue cause the nested for-loop to do?


I've searched SO and can find questions addressing similar subjects, but nothing for this specific question and language. After reading some Q&A and not finding the answer, I searched , and and got zero results.

I've been asked this question in a university quiz:

If I have:

int n = 3;
   for (int i = 1; i <= n; i++)  {
      System.out.print(" x ");
        for (int j = 1; j <= n; j++)  {
         System.out.println(" x ");
           continue;
           //no content here
        }
     }

Without there being any content after the continue statement; how does this using continue affect this loop? Does it cause a break in the second loop of does the loop continue to iterate?


Solution

  • If there was a code under continue, it'll be a dead code (unreachable code).

    The way you wrote it, it has no effect since it's already the last line. The loop would have continued if there was no continue;.

    These two blocks of code have the same effect:

    for(int i = 0; i < 10; i++) {
       // .. code ..
    }
    

    for(int i = 0; i < 10; i++) {
       // .. code ..
       continue;
    }
    

    However, the below snippet has unreachable code:

    for(int i = 0; i < 10; i++) {
       // .. code ..
       continue;
       // .. unreachable code ..
    }