user2044187
user2044187

Reputation: 107

Using label and break in if-else statement

I have this code which generates random number from an array, at a particular condition (when x and y both are equal to zero). I want the control to jump to the label. But the control never jumps to the label in any condition. I wanted to know that whether I am doing it right or not?

int[] arr = {0, 1, 2};    
Random rn = new Random();
label: {
    //some code
    if (x != 0 && y !=0) {
        //some code
    } else {
        break label;
    }
}

Upvotes: 3

Views: 17418

Answers (5)

Adeeb
Adeeb

Reputation: 1261

I suggest that you use a recursive function.

public void work(){
    // some code
    if (x != 0 && y != 0) {
        //some code
    } else {
        work();
    }
} 

You cannot use break without loops

Upvotes: 1

rath
rath

Reputation: 4089

Without examining whether you should, yes, you can use labeled statements with if in Java. According to the 1.7 specification

The Identifier is declared to be the label of the immediately contained Statement. [...] identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

It goes on (emphasis added)

If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

So if you break an if block (remember a block is a statement), you can exit the if body. Let's test it:

public static void main(String[] args) {
    if (true) label: {
        if (args != null)
            break label;
        System.out.println("doesn't get here");
    }
    System.out.println("Outside of labeled block");
}

Output:

Outside of labeled block

Upvotes: 14

Brian Roach
Brian Roach

Reputation: 76918

The break statement breaks loops and does not transfer control to the label.

Using a label with break is for when you have inner and outer loops. An unlabeled break breaks the inner most loop (the one you are in) whereas a labeled break allows you to specify an outer loop.

See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Specifically the BreakWithLabelDemo

Upvotes: 2

sp00m
sp00m

Reputation: 48837

Try to Avoid using labels. What you could do there, is:

while(true) {
    if(x == 0 && y == 0) {
        break;
    }
    // some stuff with x and y
}

Upvotes: 2

Miquel
Miquel

Reputation: 15675

As far as I know, labels cannot be used arbitrarily around {}, you need to do them to mark a for, while or do-while loop

Upvotes: -1

Related Questions