Labels are names of locations within a program. They can be used to alter the flow of control and should be used sparingly. In the previous example, we were unable to break out of the inner most loop using the break statement. However, labels can be used to break us out of more than one loop.
In the following example, we place a label in front of the outer loop. In the inner loop, we execute the break statement when i
is larger than 0 effectively terminating the outer loop after the sum has been calculated for the first row. A label consists of a name followed by a colon:
outerLoop: for(int i = 0; i < 2; i++) { int sum = 0; for(int element : matrix[i]) { sum += element; if(i > 0) { break outerLoop; } } System.out.println("Sum of row " + i + " is " +sum); }
The output of this sequence is as follows:
Sum of row 0 is 3
We can also use the continue statement with labels for a similar effect.