THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

it is used.[7] There is no default initialization value for local variables because failure to assign a starting value
for one is usually a bug. The compiler will refuse to compile code that doesn't ensure that assignment takes
place before a variable is used:


[7] In technical terms there is a concept of a variable being "definitely assigned." The compiler
won't allow the use of a local variable unless it can determine that it has been definitely
assigned a value.

int x; // uninitialized, can't use
int y = 2;
x = y * y; // now x has a value
int z = x; // okay, safe to use x


Local variables cease to exist when the flow of control reaches the end of the block in which they were
declaredthough any referenced object is subject to normal garbage collection rules.


Apart from annotations, the only modifier that can be applied to a local variable is final. This is required
when the local variable will be accessed by a local or anonymous inner classsee also the discussion of final
variables below.


7.3.2. Parameter Variables


Parameter variables are the parameters declared in methods, constructors, or catch blockssee "try, catch, and
finally" on page 286. A parameter declaration consists of an optional modifier, a type name, and a single
identifier.


Parameters cannot have explicit initializers because they are implicitly initialized with the value of the
argument passed when the method or constructor is invoked, or with a reference to the exception object
caught in the catch block. Parameter variables cease to exist when the block in which they appear
completes.


As with local variables, the only modifiers that can be applied to a parameter are annotations, or the final
modifier.


7.3.3. final Variables


The final modifier declares that the value of the variable is set exactly once and will thereafter always have
the same valueit is immutable. Any variablefields, local variables, or parameterscan be declared final.
Variables that are final must be initialized before they are used. This is typically done directly in the
declaration:


final int id = nextID++;


You can defer the initialization of a final field or local variable. Such a final variable is called a blank final. A
blank final field must be initialized within an initialization block or constructor (if it's an instance field) while
a blank final local variable, like any local variable, must be initialized before it is used.


Blank final fields are useful when the value of the field is determined by a constructor argument:


class NamedObj {

Free download pdf