Java Reference
In-Depth Information
public class BreakDemo
{
public static void main(String[] args)
{
int number = 1;
char letter;
while(number < 10 )
{
System.out.println("number is: " + number);
number ++;
for (letter = 'A'; letter < 'G'; letter ++)
{
System.out.println(" letter is: " + letter);
if (letter == 'C')
break;
}
}
}
}
There are two loops in the BreakDemo.java program. The first one is a
while loop that displays the numbers 1 to 9. The second one, an inner
loop, displays the capital letters A to F. An if statement tests for the letter
C and executes a break in order to interrupt execution of the nested loop.
Because the break statement acts on the current loop level only, the outer
loop resumes counting numbers until the value 10 is reached.
Programmers note:
The break keyword can only be used inside a switch construct or in a
for, while, or do-while loop. An error results if the break keyword ap-
pears anywhere else in a Java program.
The continue keyword
The break statement can be used with either a switch or a loop construct.
The continue statement, on the other hand, works only in loops. The pur-
pose of continue is to bypass all statements not yet executed in the loop and
return immediately to the beginning of the loop.
The program named ContinueDemo.java contains a for loop designed
to display the letters A to D. The continue statement in this loop serves to
bypass the letter C, which is not displayed.
Search WWH ::




Custom Search