Java Reference
In-Depth Information
When declaring two or more variables of the same type using a comma-separated list,
you can give one or more of those variables an initial value. For example:
In this case, only b and c are initialized.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows vari-
ables to be initialized dynamically, using any expression valid at the time the variable is
declared. For example, here is a short program that computes the volume of a cylinder giv-
en the radius of its base and its height:
Here, three local variables— radius , height , and volume —are declared. The first two, ra-
dius and height , are initialized by constants. However, volume is initialized dynamically
to the volume of the cylinder. The key point here is that the initialization expression can use
any element valid at the time of the initialization, including calls to methods, other vari-
ables, or literals.
The Scope and Lifetime of Variables
So far, all of the variables that we have been using were declared at the start of the main(
) method. However, Java allows variables to be declared within any block. As explained
in Chapter 1 , a block is begun with an opening curly brace and ended by a closing curly
brace. A block defines a scope . Thus, each time you start a new block, you are creating a
Search WWH ::




Custom Search