Adding Optional Labels Flashcards
Define an optional label !
In Java, an optional label is a way to identify a loop or a block of code, allowing you to break or continue from that specific loop. Labels are particularly useful in nested loops when you want to control the flow from the inner loop to an outer loop
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break outerLoop; // Exits the outer loop
}
System.out.println(“i: “ + i + “, j: “ + j);
}
}
Describe its use case with an example !
int[][] myComplexArray= {{5,2,1,2},{0,6,3,8},{8,2,6,4}};
INNER_LOOP : for(int[] mySimpleArray : myComplexArray) {
OUTER_LOOP : for(int i=0;i<mySimpleArray.length;i++) {
System.out.print(mySimpleArray[i]+”\t”);
}
System.out.println();
}
When dealing with one loop, they add no value, but as we’ll see in the next section, they are extremly useful in nested environments
Give conditions that need to be satisfied by an optional label in order to compile successfully
For an optional label in Java to compile successfully, the following conditions must be met:
Valid Identifier: The label must be a valid Java identifier (starts with a letter, dollar sign, or underscore, followed by letters, digits, dollar signs, or underscores).
Followed by a Colon: The label must be followed by a colon (:) to distinguish it from other statements.
Placement: The label must precede a loop (like for, while, or do) or a block of code (enclosed in curly braces {}).
Unique in Scope: The label should be unique within its scope to avoid ambiguity.