Controlling the flow of execution is a crucial aspect to make decisions and manage loops effectively. This blog takes us through the concepts of nested loops, the power of optional labels and break statements in guiding the flow of execution.
Table of Contents
1. Nested Loops
Nested loops are a fascinating construct, a loop within another loop. They allow developers to tackle complex scenarios and iterate through multidimensional structures effortlessly. Let’s explore an example a nested loops:
public class NestedLoopExample {
public static void main(String[] args) {
// Array of arrays
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int[] singleArray : multiArray) {
for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
System.out.print(innerElement + " ");
}
System.out.println();
}
}
}
output:
1 2 3
4 5 6
7 8 9
- Initialization: We start with the same 2D array (
multiArray
) as before. - Outer Loop (
for (int[] singleArray : multiArray) { ... }
):- The outer loop is a for-each loop, iterating over the rows of the 2D array.
- In each iteration, it assigns an inner array to the variable
singleArray
.
- Inner Loop (
for (int j = 0; j < singleArray.length; j++) { ... }
):- The inner loop is a regular for loop, iterating over the elements of the current row (
singleArray
). - In each iteration, it gets the
j
-th element and assigns it toinnerElement
.
- The inner loop is a regular for loop, iterating over the elements of the current row (
- Printing (
System.out.print(innerElement + " ");
):- Within the inner loop, we print each
innerElement
followed by a space, creating a horizontal line of elements for each row.
- Within the inner loop, we print each
- Move to the Next Line (
System.out.println();
):- After printing the elements of each row, we move to the next line using
System.out.println()
.
- After printing the elements of each row, we move to the next line using
- Repeat: The outer loop continues to the next iteration until all rows and elements are processed.
2. Optional Labels
Optional labels in Java provide a powerful mechanism to control the flow of execution, especially when dealing with nested loops. A label is a single identifier followed by a colon (:
), acting as a pointer to the head of a statement. Let’s enhance our nested loop example by adding optional labels:
public class NestedLoopWithLabelsExample {
public static void main(String[] args) {
// Array of arrays
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
INNER_LOOP: for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
System.out.print(innerElement + " ");
}
}
System.out.println();
}
}
}
- Outer Loop (
OUTER_LOOP: for (int[] singleArray : multiArray) { ... }
):- The outer loop is a for-each loop, iterating over the rows of the 2D array.
- It is labeled as
OUTER_LOOP
.
- Inner Loop (
INNER_LOOP: for (int j = 0; j < singleArray.length; j++) { ... }
):- The inner loop is a regular for loop, iterating over the elements of the current row (
singleArray
). - It is labeled as
INNER_LOOP
.
- The inner loop is a regular for loop, iterating over the elements of the current row (
Labels follow the same rules for formatting as identifiers. For readability, they are commonly expressed using uppercase letters with underscores between words
3. The break Statement
The break
statement is used to terminate the nearest enclosing loop or switch statement. It unconditionally transfers control to the statement immediately following the terminated loop or switch. If you add an optional label to the break statement it will break the loop that is labeled by that optional label
example without optional label:
public class BreakWithoutLabelExample {
public static void main(String[] args) {
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
if (innerElement == 5) {
break;
}
System.out.print(innerElement + " ");
}
System.out.println();
}
}
}
output:
1 2 3
4
7 8 9
- This example terminates the inner loop when
innerElement
is 5. TheOUTER_LOOP
label is not used, so the break affects the nearest enclosing loop, which is the inner loop.
example with optional label:
public class BreakContinueExample {
public static void main(String[] args) {
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
INNER_LOOP: for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
if (innerElement == 5) {
break OUTER_LOOP;
}
System.out.print(innerElement + " ");
}
System.out.println();
}
}
}
output:
1 2 3
4
In this example, the break
statement is used in combination with the optional label OUTER_LOOP
, resulting in both loops being exited when the innerElement
is 5.
4. The continue Statement
The continue
statement is used to skip the rest of the code inside a loop for the current iteration and jump to the next iteration. If you add an optional label to the continue
statement, it wil skip the rest of the code inside the loop that is labeled by the optional label for the current iteration and jump to the next iteration
example without optional label:
public class ContinueWithoutLabelExample {
public static void main(String[] args) {
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
if (innerElement == 5) {
continue;
}
System.out.print(innerElement + " ");
}
System.out.println();
}
}
output:
1 2 3
4 6
7 8 9
- The Continue Statement without Label skips the rest of the inner loop for the current iteration when
innerElement
is 5. TheOUTER_LOOP
label is not used, so the continue affects the nearest enclosing loop, which is the inner loop.
example with optional label:
public class ContinueWithOuterLabelExample {
public static void main(String[] args) {
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
if (innerElement == 5) {
continue OUTER_LOOP;
}
System.out.print(innerElement + " ");
}
System.out.println();
}
}
}
output:
1 2 3
4 7 8 9
The Continue Statement with Label skips the rest of the outer loop for the current iteration when innerElement
is 5. The OUTER_LOOP
label is used, so the continue affects the labeled enclosing loop, which is the outer loop.
5. The return Statement
The return
statement is used to explicitly return from a method. It can also be used to terminate the execution of a method prematurely. Here’s an updated example with the return
statement
public class ReturnStatementExample {
public static void main(String[] args) {
int[][] multiArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
OUTER_LOOP: for (int[] singleArray : multiArray) {
for (int j = 0; j < singleArray.length; j++) {
int innerElement = singleArray[j];
if (innerElement == 5) {
return;
}
System.out.print(innerElement + " ");
}
System.out.println();
}
System.out.println("This line will not be printed if 5 is encountered.");
}
}
output:
1 2 3
4
The return statement exits the entire program when innerElement
is 5. The OUTER_LOOP
label is not necessary in this case, as the return
statement exits the method and, consequently, the entire program.