Today I have seen this type of loops that I have never done, apparently they are bucles
with names. Does anyone know how this works and what this type of loop is called, thank you very much for helping.
What does the program print next?
class LoopTest{
public static void main(String args[]) {
int counter = 0;
outer:
for (int i = 0; i < 3; i++) {
middle:
for (int j = 0; j < 3; j++) {
inner:
for (int k = 0; k < 3; k++) {
if (k - j > 0) {
break middle;
}
counter++;
}
}
}
System.out.println(counter);
}
}
They are called labels, they are used to control which loop you want to make
break
orcontinue
when they are nested.You can see more examples here
In Java they are called tags. They can be used in nested loops for better control.
It is a label for the instruction
break
( orcontinue
, which is another similar instruction): imagine that you are looking for an element in a very large array of 10,000 elements. The element you're looking for is at position 4, for example, but you don't know it beforehand, so you loop through the array until you find it:He
break
causes us to break out of the loop, avoiding 9995 more iterations that we don't care about. But what if you have nested loops? Do you want to stop executing the internal or the external? Well, with that label you choose the loop you want to stop executing.