Java Reference
In-Depth Information
Now that you have been introduced to lists, loops, and logic, you can make a computer
decide whether to repeatedly display the contents of an array.
You learned how to declare an array variable, assign an object to it, and access and
change elements of the array. With the
if
and
switch
conditional statements, you can
branch to different parts of a program based on a Boolean test. You learned about the
for
,
while
, and
do
loops, and you learned that each enables a portion of a program to be
repeated until a given condition is met.
It bears repeating: You'll use all three of these features frequently in your Java programs.
You'll use all three of these features frequently in your Java programs.
Q I declared a variable inside a block statement for an
if
. When the
if
was
done, the definition of that variable vanished. Where did it go?
A
In technical terms, block statements form a new
lexical scope
. This means that if
you declare a variable inside a block, it's visible and usable only inside that block.
When the block finishes executing, all the variables you declared go away.
It's a good idea to declare most of your variables in the outermost block in which
they'll be needed—usually at the top of a block statement. The exception might be
simple variables, such as index counters in
for
loops, where declaring them in the
first line of the
for
loop is an easy shortcut.
Q Why can't I use
switch
with strings?
A
Strings are objects in Java, and
switch
works only for the primitive types
byte
,
char
,
short
, and
int
. To compare strings, you have to use nested
if
statements,
which enable more general expression tests, including string comparison.
Review today's material by taking this three-question quiz.
Questions
1.
Which loop is used to execute the statements in the loop at least once before the
conditional expression is evaluated?
a.
do
-
while
b.
for
c.
while