Jump Statements in Java
In Java, control flow statements order statements. Using decision-making, looping, and branching, control flow statements, including jump statements. The primary jump statements in Java are break
, continue
, and return
. This response will focus on the break
and continue
statements, detailing their functionalities, including their use with labels, and providing code examples with corresponding outputs.
Break statement
In Java, the break
statement has three primary functions:
- Terminating a switch statement: This is a common use, where
break
causes execution to exit the entireswitch
block and resume at the statement immediately following it. Execution would “fall through” to latercase
labels if there was nobreak
. - Exiting a loop: The innermost
for
,while
, ordo-while
loop can be forced to end immediately by using an unlabelledbreak
, avoiding the loop’s conditional test and any remaining code in the loop body. At the statement that comes after the loop, control then returns.Break
is utilised when a unique circumstance necessitates an early exit, even if loops normally end according to their conditional expression. - Acting as a “civilized” form of goto: Java lacks a
goto
statement due to its tendency to encourage unstructured code that is challenging to read and maintain. A labelledbreak
, on the other hand, offers a means of transferring control out of one or more enclosing code blocks.
A label (any valid Java identifier) must be placed at the beginning of the block of code you want to break out of in order to use a labelled break
. The break
statement must be enclosed in the labelled block, although it need not be the block that encloses it right away. Control is passed to the end of the designated block upon the execution of a labelled break
.
Unlabeled Example (Exiting Loop):
When the search value is obtained, this example shows how to break
out of a for
loop.
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break; // Terminates the for loop
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Output:
Found 12 at index 4
When 12
is located at index 4
, the for
loop in this output stops iterating, and the program prints the outcome.
Labeled Example (Exiting Nested Loops):
This software searches a two-dimensional array using nested for
loops. The outer for
loop (labelled search
) ends with a labelled break
after the value has been located.
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search: // Label for the outer loop
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search; // Breaks out of the 'search' labeled loop
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Output:
Found 12 at 1, 0
When 12
is discovered, break search
exits both inner and outer loops and calls the statement after the search
labelled block.
Continue statement
The continue
statement is used to skip the current iteration of a for, while, or do-while loop and immediately proceed to the next iteration. It does not terminate the loop entirely, unlike break
.
- An unlabelled
continue
in afor
loop jumps control straight to the update expression, which is followed by an evaluation of the conditional expression before to the subsequent iteration. Continue
gives the Boolean expression that governs the loop direct control inwhile
anddo-while
loops.
To bypass the current iteration of an outer loop that has the designated label, use a labelled continue
. After that, control shifts to the labelled outer loop’s iteration expression (for a for
loop) or conditional expression (for a while
/do-while
).
Unlabeled Example:
This application counts ‘p’s in a string. Continue
skips the loop body for that iteration and proceeds to the next character if the current character is not ‘p’.
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue; // Skips the rest of this iteration if not 'p'
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Output:
Found 9 p's in the string.
The count would be off if the continue
statement were eliminated because all characters would be processed.
Labeled Example:
In this example, a substring inside another text is found using stacked loops. The continue test
essentially moves to the next beginning location in searchMe
when a mismatch is detected, skipping the remainder of the current iteration of the test
labelled outer loop.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test: // Label for the outer loop
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test; // Skips to the next iteration of the 'test' labeled loop
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Output:
Found it
This output demonstrates that the substring was successfully located by the software. The continue test
makes sure that the full substring comparison for the current i (outside loop iteration) is dropped and the outer loop advances to the following iteration in the event of a character mismatch within the inner while
loop.
In Conclusion
Break
and continue
are effective methods for managing the execution of loops. break
exits a loop, while continue
skips to the next iteration. Both offer more precise control over program flow and can be extended to outer loops or blocks by using labels.