Java Reference
In-Depth Information
An object's lifetime ranges from its creation via the new operator until the moment
whenitisremovedfrommemorybythegarbagecollector.Itsscopedependsonvarious
factors,suchaswhenitsreferenceisassignedtoalocalvariableortoafield.Idiscuss
fields later in this chapter.
The lifetime of a field depends upon whether it is an instance field or a class field. If
the field belongs to an object, it comes into existence when the object is created and
dieswhentheobjectdisappearsfrommemory.Ifthefieldbelongstoaclass,thefield
beginsitsexistencewhentheclassisloadedanddisappearswhentheclassisremoved
frommemory.Aswithanobject,afield'sscopedependsuponvariousfactors,suchas
whetherthefieldisdeclaredtohaveprivateaccessornot—you'lllearnaboutprivate
access later inxs this chapter.
Alocal variable cannot have the same name asaparameter because aparameter al-
ways has the same scope as the local variable. However, a local variable can have the
samenameasanotherlocalvariableprovidedthatbothvariablesarelocatedwithindif-
ferentscopes(thatis,withindifferentblocks).Forexample,youcouldspecify int x
= 1; withinanif-elsestatement'sifblockandspecify double x = 2.0; within
the statement's corresponding else block, and each local variable would be distinct.
Note Thediscussionofconstructorparameters,arguments,andlocalvariablesalso
appliestomethodparameters,arguments,andlocalvariables—Idiscussmethodslater
in this chapter.
Creating Arrays with the new Operator
The new operatorisalsousedtocreateanarrayofobjectsintheheap,andisanaltern-
ative to the array initializer presented in Chapter 1 .
Note An array is implemented as a special Java object whose read-only length
fieldcontainsthearray'ssize(thenumberofelements).You'lllearnaboutfieldslater
in this chapter.
Whencreatingthearray,specify new followedbyanamethatidentifiesthetypeof
valuesthatarestoredinthearray,followedbyoneormorepairsofsquarebracketsthat
signify the number of dimensions occupied by the array. The leftmost pair of square
bracketsmustcontainanintegralexpressionthatspecifiesthesizeofthearray(thenum-
ber of elements), whereas remaining pairs contain integral expressions or are empty.
Search WWH ::




Custom Search