Lesson 6.4 Java Jumps
Java's selection and iteration statements are called flow-of-control statements because they provide a highly structured method of conditionally and repeatedly executing a particular section of code.
In days past, however, before the control structures we use today, programmers still needed the equivalent of if statements and loops. Rather than relying on built-in language features, though, those iron-age programmers constructed their own flow of control statements, using the jump.
The jump statement often uses another name; even programmers who have never heard of the jump have heard of its nom de plum, the goto statement. The goto is one of Java's fifty reserved words, but it isn't actually implemented as part of the language.
When it comes to loop control, however, Java hasn't abandoned the jump altogether. Java has two statements--break and continue--that let you do your jumping in a controlled fashion.
The break Statement
The break statement is used in two different circumstances, but both circumstances are quite similar.
The break statement allows you to jump out of:
- a switch statement [as you saw earlier]
- a loop
When a break statement is encountered in the body of a loop, your program jumps to the statement immediatly following the loop body, as you can see in the illustration shown here. Any remaining statements within the loop body are skipped. The test expression is not re-evaluated; the termination occurs regardless of the value the test expression would have.
Although it can be misused, allowing you to write code that is as convoluted as any produced by the goto statement, the break can sometimes be used to make your loops simpler and clearer. Here's an example, BreakFor.java, that shows how the break statement can be used to simulate a sentinel loop that chops off the first sentence [ending with a period] in a String, and displays it in a TextField. Note that the loop bounds does not need to test for the sentinel value.
|
Using the break Statement
|
| String str = myTF.getText(); String ans = "";
char ch; for (int i = 0; i < str.length(); i++)
{
ch = charAt(i);
if (ch == '.')
break;
ans += ch;
}
myTF.setText(ans);
Type some sentences into the TextField below and press ENTER.
|
The continue Statement
The continue statement is a jump statement like break, but unlike break, the continue jumps back to the loop condition.
Exactly what that means depends upon the loop you're using:
- For the while loop and the do-while loop, the continue statement jumps to the boolean test, skipping backward [while] or forward [do-while] as necessary.
- With the for loop, control jumps to the update expression.

Converting Numbers
Here is an example that shows you how to use the continue statement with a for loop. The applet, ContinueFor.java, allows you to type an integer number into a TextField, using commas, like this:
2,345,567
The Integer.parseInt() method is unable to convert such a String containing commas, but you can easily do it yourself by following this simple algorithm.
- Using a loop, step through each character in the String If the character is not a digit, then use the continue statement to jump to the next repetition in the loop. Convert the digit character to a binary number by subtracting the character '0'. [Remember that '0' has a numeric (Unicode) value of 48 decimal, while 0 has a numeric value of 0. If you subtract '0' from '0', the result is a binary 0; if you subtract '0' from '1', the result is a binary 1, and so on.]
- As each digit is encountered, multiply the sum of all converted digits [val in the example shown here] by 10, and add the newly converted digit.
Here's the algorithm written in Java. See the entire ContinueFor.java applet.
|
Using continue with a for Loop
|
String str = numTF.getText();
int val = 0;
for (int i = 0; i < str.length(); ++i)
{
char ch = str.charAt(i); if (! Character.isDigit(ch))
continue;
val = val * 10;
val += (ch - '0');
}
numTF.setText("" + val);
Type an integer into the TextArea, using the format, 999,999,999 and press ENTER.
|
Nested Loops
When you put one if statement inside the body of another if statement, you have a nestedif statement. You can do the same thing with loops. As you'd expect, these are called nested loops. When you stick one loop inside another loop, the first loop encountered is called the outer loop, and the next is called the inner loop.
Here's an example of a pair of nested for loops that print a multiplication table. This is taken from the applet Times.java.
|
A Nested Loop
|
for (outer = 1; outer <= 10; ++outer)
{
for (inner = 1; inner <= 10; ++inner)
{
int product = inner * outer;
if (product < 10)
output.appendText(" " + product)
else if (product < 100)
output.appendText(" " + product)
else
output.appendText(" " + product);
}
output.appendText("");
}
|
With a the nested loops shown here, every repetition of the outer loop contains ten repetitions of the inner loop. Everytime the outer loop goes round once, the inner loop goes through it's entire set of repetitions.
Labeled break and continue
One of the problems with nested loops, is that the break and continue statements stop "working." Actually, they don't stop working, exactly; they just don't work quite the way you'd like. Here's the problem.
Both break and continue work on the current loop. That means, when you are in an inner loop, a break statement only exits the inner loop; it doesn't get you out of the outer loop. Java has a facility to address this deficiency, called the labeled break and the labeled continue. Here's how they work:
- Before each loop, add a label. A label is simply an identifier that ends in a colon.
- Inside the loop, use the name of the label, along with the keyword break or continue, to jump to the loop following the label.
Here's an example:
|
Labeled break and continue
|
| int count = 0;
Outer: // label ends with a colon
for (int outer = 1; outer < 1000; outer++)
{
for(int inner = 1; inner < 1000; inner++)
{
count++;
if ( inner % 2 == 0 ) continue;
if ( inner % 201 == 0 ) break;
if ( outer % 25 == 0 ) continue Outer;
if ( outer % 51 == 0 ) break Outer;
}
}
|
Can you follow the flow of control in this nested loop? Let's analyze it:
- The outer loop goes from 1 to 999, and for every revolution of the outer loop, the inner loop should also go around 999 times. If there were no breaks or continues, then the loop would repeat 998,001 times. In the inner loop, every even value (inner % 2 == 0) uses continue to skip back to the update expression of the inner loop. However, when inner reaches 201 (an odd number) break ends the inner loop. The inner loop, then, never executes more than 201 times per revolution of the outer loop. On the 25th repetition of the outer loop, there is a labeled continue. The target of this continue is the label Outer. This causes a jump to the expression outer++, [after updating count] and the 25th and 50th iterations of the inner loop are skipped.
- Finally, on the 51st repetition of the outer loop, the labeled break is encountered. This jumps to the statement following the closing brace of the loop labeled by Outer.
The result? The variable count records 201 iterations of the inner loop times 48 iterations of the outer loop, plus 3 entries to the inner loop with early exit [two continue Outer and one breakOuter]. The final total for count is 9,648 instead of 998,001.
Something to Talk About
The ContinueFor program converts text into numbers, but it only works for integers. What changes would have to be made to the code so that it would correctly process decimal-format floating-point numbers, in addition to integer numbers? (You don't have to actually write the code.)
Please continue to the next section of this lesson.
|