Java Reference
In-Depth Information
C H A P T E R 5
Control Flow, Looping, and
Branching
Control flow, looping, and branching are fundamental concepts in all programming. Control flow
consists of running different code under different conditions. Looping consists of running the same code
(though often with different values or different objects each time) until some condition has been met.
Branching consists of doing something else when some condition has been detected. The thread that
ties them all together is detecting conditions.
Control Flow
Java offers two constructs for controlling the flow of a program.
if and if - else
switch
Note try-catch blocks offer a form of control flow, because you can try something and then do something else
if the first thing you tried throws an exception. However, because that mechanism relies on catching exceptions,
it's not really a control flow mechanism. Because exceptions happen only when something goes wrong, they
shouldn't be thought of (and certainly shouldn't be used for) branching.
if and if-else Statements
You've already seen some examples of if statements, but let's examine another. Let's start with a sample
that's about as simple as it can be, as shown in Listing 5-1.
Search WWH ::




Custom Search