Java Reference
In-Depth Information
The following BreakDemo program contains a while loop with a break in it.
Study the program and see if you can determine how many times the while
loop executes.
public class BreakDemo
{
public static void main(String [] args)
{
int k = 1;
while(k <= 10)
{
System.out.println(k);
if(k == 6)
{
break;
}
k++;
}
System.out.println(“The final value of k is “ + k);
}
}
It looks as though the while loop will execute 10 times, since k starts at 1 and
the Boolean expression has k less than or equal to 10; however, when k is 6, the
break occurs, the loop terminates, and flow of control jumps down to the
println() that displays the final of value of k. This final value is 6, as you can
see by the output in Figure 3.6.
A common use of the break keyword is in while loops that execute indefi-
nitely, or at least until a problem arises. For example, consider the following
while loop:
while(true)
{
try
{
//Perform certain tasks.
}catch(IOException e)
{
break;
}
}
At first glance, this while loop looks like an infinite loop. Theoretically, it
could run forever if no IOException occurs; however, if an IOException does
occur while performing the certain tasks, the catch block will execute and the
break will cause the loop to terminate. (Try/catch blocks are discussed in
detail in Chapter 11, “Exception Handling.”)
Search WWH ::




Custom Search