0

I don't know interpret this code:

t:
while (true) {
    break t;
}

Can you help me?

3 Answers3

2

This construct called a "labeled break" and can be used to simultaneously break out of multiple nested loops.

To quote an example from an Oracle tutorial:

search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length;
             j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search;
            }
        }
    }

Here, an unlabeled break (i.e. simply break) would only terminate the inner loop, whereas break search terminates both loops at once.

See Is using a labeled break a good practice in Java? for a relevant debate.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

It's just a label that you place anywhere and then you can "break" or "continue" depending on your conditions.It can be used in nested if-else with for loopings in order to break several loops. Here break t; simply means break out from the while loop that is labelled as t.

It's useful for breaking out of nested loops

suvojit_007
  • 1,690
  • 2
  • 17
  • 23
0

This is called a 'level', the alternative to 'goto' in other languages. Although 'goto' is a reserved word in Java, it is not used in the language; Java has no goto. However, it does have something that looks a bit like a jump tied in with the break and continue keywords: a level.

A label is an identifier followed by a colon, like this: label1:

The only place a label is used in Java is right before an iteration statement. The reason to put a label before an iteration is if you’re going to nest another iteration or a switch inside it. That’s because the break and continue keywords will normally interrupt only the current loop, but when used with a label, they’ll interrupt the loops up to where the label exists:

label1:
outer-iteration {
    inner-iteration {
    //...
    break; // (1)
    //...
    continue; // (2)
    //...
    continue label1; // (3)
    //...
    break label1; // (4)
    }
}

In (1), the break breaks out of the inner iteration and you end up in the outer iteration. In (2), the continue moves back to the beginning of the inner iteration. But in (3), the continue label1 breaks out of the inner iteration and the outer iteration, all the way back to label1. Then it does in fact continue the iteration, but starting at the outer iteration. In (4), the break label1 also breaks all the way out to label1, but it does not re-enter the iteration. It actually does break out of both iterations.

Hope this help!!!

hardeep thakur
  • 311
  • 3
  • 9