Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING


// reset now for the next comparison
now = System.currentTimeMillis();
} while (!connected && now < oneMinuteFromStart);
if (connected) {
System.out.println("Connected to the mail server");
} else {
System.out.println("Timed out while trying to connect to the mail server");
}

In a do-while loop with a break statement, we can skip the overhead of the comparison. If our code
happens to work the first time, we're done. That's a tiny optimization, but it's good practice to take
advantage of that kind of thing whenever you can, because those little bits of time add up after a while.

Branching


The if and switch constructs are not strictly branching structures (though developers often speak of
them as such). Strictly speaking, branching means “jumping” from one place in a program to another
place in the same program. Some languages (such as Assembler) make extensive use of this kind of
branching. Java uses the concept much more sparingly. The Java community regards arbitrarily jumping
to some other point in the code to be at odds with the principles of object-oriented development. It's
generally thought that object-oriented code that has to rely on jumping around is bad object-oriented
code. Consequently, Java has no goto statement, and the Java community is careful about using the
break and continue keywords.
Java offers three branching statements:


  • break

  • continue

  • return


The break Statement


Many programming languages offer some form of break statement, because the need to stop the current
execution path when some condition is met is a common problem. The break statement without a label
moves the execution point (the bit of code the program is currently running) to the next statement that
is outside of whatever structure contains the break statement. The only structures that can contain break
statements are for, while, and do-while loops and switch statements.
The break statement has two forms, one (the most commonly used form) without a label and one
with a label. We see several examples of break statements throughout this chapter. A break statement
with a label breaks an outer loop, meaning that it is useful only within nested loops. As an example,
suppose we search a chessboard to find a particular piece (say the black king). We might implement the
search as a loop going left to right with a loop going across the board. (By the way, if we search for the
position of a chess piece this way, we have a badly designed program; each piece should be an object,
and we find its location by examining its properties, but this idea will do for an example as in Listing
5-16.)
Free download pdf