THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

and behavior are supported by the declared entity. The other attributes of a variable include annotations and
modifiers. Annotations can be applied to any variable declaration and are discussed in Chapter 15.


[6] Type variables are not storage locations and are excluded from this discussion. They apply
only to generic type declarations and are discussed in Chapter 11.

7.3.1. Field and Local Variable Declarations


Fields and local variables are declared in the same way. A declaration is broken into three parts: modifiers,
followed by a type, followed by a list of identifiers. Each identifier can optionally have an initializer
associated with it to give it an initial value.


There is no difference between variables declared in one declaration or in multiple declarations of the same
type. For example:


float x, y;


is the same as


float x;
float y;


Any initializer is expressed as an assignment (with the = operator) of an expression of the appropriate type.
For example:


float x = 3.14f, y = 2.81f;


is the same as the more readable


float x = 3.14f,
y = 2.81f;


is the same as the preferred


float x = 3.14f;
float y = 2.81f;


Field variables are members of classes, or interfaces, and are declared within the body of that class or
interface. Fields can be initialized with an initializer, within an initialization block, or within a constructor, but
need not be initialized at all because they have default initial values, as discussed on page 44. Field
initialization and the modifiers that can be applied to fields were discussed in Chapter 2.


Local variables can be declared anywhere within a block of statements, not just at the start of the block, and
can be of primitive or reference type. As a special case, a local variable declaration is also permitted within
the initialization section of a for loopsee "for" on page 236. A local variable must be assigned a value before

Free download pdf