naman_rai
naman_rai

Reputation: 3

use of break in java

For nested loops, when I use continue with labels it gives me an error during compilation saying that the declared loop is not present.

Particularly for this case, the error message being displayed is: Second is not a loop label.

Here's the piece of code I have written to demonstrate my problem:

//using break as a form of GOTO 
class demo
{

    public static void main(String [] args)
    {   
        boolean b=false;
        First:{
            Second:{
                Third:{
                        System.out.println("Before BReak");
                        if(b)                               
                        continue Third;                 
                        else
                        break Second;
                    }
                    System.out.println("THis won't execute");
                }
                System.out.println("THis too won't Execute");
            }
    }   

}

Upvotes: 0

Views: 106

Answers (3)

Aukta
Aukta

Reputation: 413

you Can use Label statement without loop only with break and not with continue

  • for using continue you would require a loop

  • an example of the label statement without a loop and break statement:

    sumBlock: {

         if (a < 0) {
                break sumBlock;
            }
    
            if (b < 0) {
                break sumBlock;
            }
            return a + b;
        }
    

Upvotes: 0

user5134904
user5134904

Reputation:

This results in compilation error in Java, because there is no loop. continue makes sense only when there is the loop

Upvotes: 0

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

As you're not in a loop of some sort, you can't use continue.

From the docs:

The continue statement skips the current iteration of a for, while , or do-while loop

Upvotes: 3

Related Questions