Java Reference
In-Depth Information
12.
One final line will be output to the console indicating the end of the program.
13.
If you executed the
for
loops in the other Try It Out exercises in this chapter, you'll notice that
they all produce the same output. For these simple examples, the loops can be used somewhat
interchangeably, with some small adaptations. You will encounter situations in the later chapters
that are more suited to one type of loop over others.
comparing for and while loops
As you've seen through the examples and exercises in the previous sections,
for
and
while
loops
can both be used to obtain the same outcome. So how do you know which one to use?
For some problems, this will simply be a matter of preference. Some programmers tend to use
for
loops, except when a situation really demands a
while
loop. Others prefer
while
loops and include
for
loops only when needed. Many programmers, through practice and experience, learn a certain
feeling for which one is best suited for the problem at hand, and you will too.
In general, keep in mind the following points:
➤
If you are iterating over a collection, consider a
for
loop first.
➤
If you know the number of loops in advance, consider a
for
loop first.
➤
If you don't know the number of iterations, but the number will depend on a certain condi-
tion, consider a
while
loop first.
When making your decision, simplicity and clarity are important considerations. You want a solu-
tion that's the simplest to code, for your own sake, and clearest to read and understand, for yourself
and others who will have to maintain or reuse your code later.
creating switches
Earlier in this chapter, you learned that if-then statements are one of the basic control structures.
Now you will see
switch
statements, which function in a similar way to if-then statements, but with
a different syntax. They are particularly useful when you have several
else
clauses. A
switch
state-
ment evaluates a single variable and, depending on its value, executes a certain block of code. The
general syntax of a basic
switch
statement is as follows:
switch (/*variable*/ {
case 1: /*execute these statements*/; break;
case 2: /*execute these statements*/; break;
default: /*execute these statements*/;
}
The variable that's evaluated can be a primitive
byte
,
short
,
char
, or
int
, as well as enumerated
types and
String
. The
switch
checks the value of the variable for a match in one of the cases. If
they are equal, the statements in that
case
will be executed.
Search WWH ::
Custom Search