Java Reference
In-Depth Information
int
counter
;
String
s
;
A variable declaration can also include an
initializer
: an expression that specifies an
initial value for the variable. For example:
int
i
=
0
;
String
s
=
readLine
();
int
[]
data
=
{
x
+
1
,
x
+
2
,
x
+
3
};
// Array initializers are discussed later
The Java compiler does not allow you to use a local variable that has not been ini‐
tialized, so it is usually convenient to combine variable declaration and initialization
into a single statement. The initializer expression need not be a literal value or a
constant expression that can be evaluated by the compiler; it can be an arbitrarily
complex expression whose value is computed when the program is run.
A single variable declaration statement can declare and initialize more than one
variable, but all variables must be of the same type. Variable names and optional ini‐
tializers are separated from each other with commas:
a
x
int
i
,
j
,
k
;
float
x
=
1.0
,
y
=
1.0
;
String
question
=
"Really Quit?"
,
response
;
Variable declaration statements can begin with the
final
keyword. This modifier
specifies that once an initial value is specified for the variable, that value is never
allowed to change:
final
String
greeting
=
getLocalLanguageGreeting
();
We will have more to say about the
final
keyword later on, especially when talking
about the immutable style of programming.
C programmers should note that Java variable declaration statements can appear
anywhere in Java code; they are not restricted to the beginning of a method or block
of code. Local variable declarations can also be integrated with the
initialize
portion
of a
for
loop, as we'll discuss shortly.
Local variables can be used only within the method or block of code in which they
are defined. This is called their
scope
or
lexical scope
:
void
method
()
{
// A method definition
int
i
=
0
;
// Declare variable i
while
(
i
<
10
)
{
// i is in scope here
int
j
=
0
;
// Declare j; the scope of j begins here
i
++;
// i is in scope here; increment it
}
// j is no longer in scope;
System
.
out
.
println
(
i
);
// i is still in scope here
}
// The scope of i ends here