Java Reference
In-Depth Information
The main difference in using a continue statement inside a for loop and a while loop is the place where the
control is transferred. Inside a for loop, control is transferred to the expression-list, and in a while loop, the control is
transferred to the condition-expression. This is why a for -loop statement cannot always be converted to a while -loop
statement without modifying some logic.
An unlabeled continue statement always continues the innermost for loop, while loop, and do-while loop. If
you are using nested loop statements, you need to use a labeled continue statement to continue in the outer loop. For
example, you can rewrite the snippet of code that prints lower half of the 3x3 matrix using a continue statement
as shown:
outer: // The label "outer" starts here
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print(i + "" + j);
System.out.print("\t");
if (i == j) {
System.out.println(); // Print a new line
continue outer; // Continue the outer loop
}
}
} // The label "outer" ends here
An Empty Statement
An empty statement is a semicolon by itself. An empty statement does nothing. If an empty statement does not
do anything, why do we have it? Sometimes a statement is necessary as part of the syntax of a construct. However,
you may not need to do anything meaningful. In such cases, an empty statement is used. A for loop must have a
statement associated with it. However, to print all integers between 1 and 10 you can only use initialization,
condition-expression, and expression-list parts of a for -loop statement. In this case, you do not have a statement to
associate with the for -loop statement. Therefore, you use an empty statement in this case, as shown:
for(int i = 1; i <= 10; System.out.println(i++))
; // This semicolon is an empty statement for the for loop
Sometimes an empty statement is used to avoid double negative logic in the code. Suppose noDataFound is a
boolean variable. You may write a snippet of code as shown:
if (noDataFound)
; // An empty statement
else {
// Do some processing
}
The above if-else statement can be written without using an empty statement, like so:
if (!noDataFound) {
// Do some processing
}
 
Search WWH ::




Custom Search