Java Reference
In-Depth Information
can sometimes create problems in Java. It is sometimes easier to declare the variables
outside the block. If you declare a variable outside a block, you can use it both inside
and outside the block, and it will have the same meaning in both locations.
TIP: Declaring Variables in a
for
Statement
You can declare a variable (or variables) within the initialization portion of a
for
statement, as in the following:
int
sum = 0;
for
(
int
n = 1; n < 10; n++)
sum = sum + n;
If you declare
n
in this way, the variable
n
will be
local to the
for
loop
. This means
that
n
cannot be used outside the
for
loop. For example, the following use of
n
in the
System.out.println
statement is illegal:
for
(
int
n = 1; n < 10; n++)
sum = sum + n;
System.out.println(n);
//Illegal
Declaring variables inside a
for
loop can sometimes be more of a nuisance than a
helpful feature. We tend to avoid declaring variables inside a
for
loop except for very
simple cases that have no potential for confusion.
■
Self-Test Exercises
4. Write a method called
happyGreeting
that could be added to the class
DateSecondTry
in Display 4.2 . The method
happyGreeting
writes the string
"Happy Days!"
to the screen a number of times equal to the value of the
instance variable
day
. For example, if the value of
day
is
3
, then it should write
the following to the screen:
Happy Days!
Happy Days!
Happy Days!
Use a local variable.
Parameters of a Primitive Type
All the method definitions we have seen thus far had no parameters, which was
indicated by an empty set of parentheses in the method heading. A
parameter
is like
a blank that is filled in with a particular value when the method is invoked. (What we
are calling
parameters
are also called
formal parameters
.) The value that is plugged in for
parameter