user3463561
user3463561

Reputation: 1

What does the colon do in Java?

public void go(){
    String o = "";
    z:
    for (int x = 0; x<3; x++) {
        for (int y = 0; y<2;y++) {
            if (x==1) 
                break;
            if (x==2 && y==1)
                break z;
            o = o + x+y;
        }
    }

    System.out.println(o);
}

Upvotes: 0

Views: 1281

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

It a label for a directed break (or a directed continue). See comments added below:

public void go(){
    String o = "";
    z:                       // <=== Labels the loop that follows
    for (int x = 0; x<3; x++) {
        for (int y = 0; y<2;y++) {
            if (x==1) 
                break;       // <=== Not directed, only breaks the inner loop
            if (x==2 && y==1)
                break z;     // <=== Directed break, breaks the loop labelled with `z`
            o = o + x+y;
        }
    }

    System.out.println(o);
}

Upvotes: 3

Christian
Christian

Reputation: 1586

Basically it is a jump mark. See here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html (there is a jump mark called search implemented and explained)

Upvotes: 0

Muhammad Kashif Nazar
Muhammad Kashif Nazar

Reputation: 23845

It's a label. You can use continue keyword to skip the current iteration and to reach to this point, also skipping the innermost loop.

Upvotes: 0

Slimu
Slimu

Reputation: 2371

This is a syntax a bit similar to old goto instructions. When a break occurs, you will exit from the loop right after the "z", in this case the most outer for loop. This works also with continue statements.

Upvotes: 0

Related Questions