Tải bản đầy đủ (.pdf) (1,326 trang)

The java programming language, 4th edition (2005)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.94 MB, 1,326 trang )

THEJava™ProgrammingLanguage,FourthEdition
ByKenArnold,JamesGosling,DavidHolmes
...............................................
Publisher:AddisonWesleyProfessional
PubDate:August17,2005
ISBN:0-321-34980-6
Pages:928

TableofContents|Index

DirectfromthecreatorsoftheJava™programminglanguage,thecompletelyrevised
fourtheditionofTheJava™ProgrammingLanguageisanindispensableresourcefor
noviceandadvancedprogrammersalike.
Developersaroundtheworldhaveusedpreviouseditionstoquicklygainadeep
understandingoftheJavaprogramminglanguage,itsdesigngoals,andhowtouseitmost
effectivelyinreal-worlddevelopment.Now,KenArnold,JamesGosling,andDavidHolmes
haveupdatedthisclassictoreflectthemajorenhancementsinJava™2StandardEdition
5.0(J2SE™5.0).
TheauthorssystematicallycovermostclassesinJava'smainpackages,java.lang.*,
java.util,andjava.io,presentingin-depthexplanationsofwhytheseclassesworkasthey
do,withinformativeexamples.Severalnewchaptersandmajorsectionshavebeenadded,
andeverychapterhasbeenupdatedtoreflecttoday'sbestpracticesforbuildingrobust,
efficient,andmaintainableJavasoftware.
Keychangesinthiseditioninclude
Newchaptersongenerics,enums,andannotations,themostpowerfulnewlanguage
featuresintroducedinJ2SE5.0
Changestoclassesandmethodsthroughouttoreflecttheadditionofgenerics
Majornewsectionsonassertionsandregularexpressions
Coverageofallthenewlanguagefeatures,fromautoboxingandvariableargument
methodstotheenhancedfor-loopandcovariantreturntypes
Coverageofkeynewclasses,suchasFormatterandScanner


TheJava™ProgrammingLanguage,FourthEdition,isthedefinitivetutorial
introductiontotheJavalanguageandessentiallibrariesandanindispensablereferencefor
allprogrammers,includingthosewithextensiveexperience.Itbringstogetherinsightsyou
canonlygetfromthecreatorsofJava:insightsthatwillhelpyouwritesoftwareof
exceptionalquality.


THEJava™ProgrammingLanguage,FourthEdition
ByKenArnold,JamesGosling,DavidHolmes
...............................................
Publisher:AddisonWesleyProfessional
PubDate:August17,2005
ISBN:0-321-34980-6
Pages:928

TableofContents|Index



















































Copyright
TheJava™Series
Preface
AboutThisBook
ExamplesandDocumentation
Acknowledgments(FourthEdition)
Acknowledgments(ThirdEdition)
Acknowledgments(SecondEdition)
Acknowledgments(FirstEdition)
Chapter1.AQuickTour
Section1.1.GettingStarted
Section1.2.Variables
Section1.3.CommentsinCode
Section1.4.NamedConstants
Section1.5.UnicodeCharacters
Section1.6.FlowofControl
Section1.7.ClassesandObjects
Section1.8.MethodsandParameters
Section1.9.Arrays
Section1.10.StringObjects
Section1.11.ExtendingaClass
Section1.12.Interfaces
Section1.13.GenericTypes
Section1.14.Exceptions
Section1.15.Annotations

















































































Section1.16.Packages
Section1.17.TheJavaPlatform
Section1.18.OtherTopicsBrieflyNoted
Chapter2.ClassesandObjects
Section2.1.ASimpleClass
Section2.2.Fields
Section2.3.AccessControl
Section2.4.CreatingObjects
Section2.5.ConstructionandInitialization
Section2.6.Methods
Section2.7.this
Section2.8.OverloadingMethods

Section2.9.ImportingStaticMemberNames
Section2.10.ThemainMethod
Section2.11.NativeMethods
Chapter3.ExtendingClasses
Section3.1.AnExtendedClass
Section3.2.ConstructorsinExtendedClasses
Section3.3.InheritingandRedefiningMembers
Section3.4.TypeCompatibilityandConversion
Section3.5.WhatprotectedReallyMeans
Section3.6.MarkingMethodsandClassesfinal
Section3.7.AbstractClassesandMethods
Section3.8.TheObjectClass
Section3.9.CloningObjects
Section3.10.ExtendingClasses:HowandWhen
Section3.11.DesigningaClasstoBeExtended
Section3.12.SingleInheritanceversusMultipleInheritance
Chapter4.Interfaces
Section4.1.ASimpleInterfaceExample
Section4.2.InterfaceDeclarations
Section4.3.ExtendingInterfaces
Section4.4.WorkingwithInterfaces
Section4.5.MarkerInterfaces
Section4.6.WhentoUseInterfaces
Chapter5.NestedClassesandInterfaces
Section5.1.StaticNestedTypes
Section5.2.InnerClasses
Section5.3.LocalInnerClasses
















































































Section5.4.AnonymousInnerClasses
Section5.5.InheritingNestedTypes
Section5.6.NestinginInterfaces
Section5.7.ImplementationofNestedTypes
Chapter6.EnumerationTypes
Section6.1.ASimpleEnumExample
Section6.2.EnumDeclarations
Section6.3.EnumConstantDeclarations
Section6.4.java.lang.Enum
Section6.5.ToEnumorNot
Chapter7.Tokens,Values,andVariables
Section7.1.LexicalElements
Section7.2.TypesandLiterals
Section7.3.Variables
Section7.4.ArrayVariables
Section7.5.TheMeaningsofNames

Chapter8.PrimitivesasTypes
Section8.1.CommonFieldsandMethods
Section8.2.Void
Section8.3.Boolean
Section8.4.Number
Section8.5.Character
Section8.6.BoxingConversions
Chapter9.OperatorsandExpressions
Section9.1.ArithmeticOperations
Section9.2.GeneralOperators
Section9.3.Expressions
Section9.4.TypeConversions
Section9.5.OperatorPrecedenceandAssociativity
Section9.6.MemberAccess
Chapter10.ControlFlow
Section10.1.StatementsandBlocks
Section10.2.ifelse
Section10.3.switch
Section10.4.whileanddowhile
Section10.5.for
Section10.6.Labels
Section10.7.break
Section10.8.continue

















































































Section10.9.return
Section10.10.What,Nogoto?
Chapter11.GenericTypes
Section11.1.GenericTypeDeclarations
Section11.2.WorkingwithGenericTypes
Section11.3.GenericMethodsandConstructors
Section11.4.WildcardCapture
Section11.5.UndertheHood:ErasureandRawTypes
Section11.6.FindingtheRightMethodRevisited
Section11.7.ClassExtensionandGenericTypes
Chapter12.ExceptionsandAssertions
Section12.1.CreatingExceptionTypes
Section12.2.throw
Section12.3.ThethrowsClause
Section12.4.try,catch,andfinally
Section12.5.ExceptionChaining
Section12.6.StackTraces
Section12.7.WhentoUseExceptions
Section12.8.Assertions

Section12.9.WhentoUseAssertions
Section12.10.TurningAssertionsOnandOff
Chapter13.StringsandRegularExpressions
Section13.1.CharacterSequences
Section13.2.TheStringClass
Section13.3.RegularExpressionMatching
Section13.4.TheStringBuilderClass
Section13.5.WorkingwithUTF-16
Chapter14.Threads
Section14.1.CreatingThreads
Section14.2.UsingRunnable
Section14.3.Synchronization
Section14.4.wait,notifyAll,andnotify
Section14.5.DetailsofWaitingandNotification
Section14.6.ThreadScheduling
Section14.7.Deadlocks
Section14.8.EndingThreadExecution
Section14.9.EndingApplicationExecution
Section14.10.TheMemoryModel:Synchronizationandvolatile
Section14.11.ThreadManagement,Security,andThreadGroup
















































































Section14.12.ThreadsandExceptions
Section14.13.ThreadLocalVariables
Section14.14.DebuggingThreads
Chapter15.Annotations
Section15.1.ASimpleAnnotationExample
Section15.2.AnnotationTypes
Section15.3.AnnotatingElements
Section15.4.RestrictingAnnotationApplicability
Section15.5.RetentionPolicies
Section15.6.WorkingwithAnnotations
Chapter16.Reflection
Section16.1.TheClassClass
Section16.2.AnnotationQueries
Section16.3.TheModifierClass
Section16.4.TheMemberclasses
Section16.5.AccessCheckingandAccessibleObject
Section16.6.TheFieldClass
Section16.7.TheMethodClass
Section16.8.CreatingNewObjectsandtheConstructorClass
Section16.9.GenericTypeInspection
Section16.10.Arrays
Section16.11.Packages
Section16.12.TheProxyClass

Section16.13.LoadingClasses
Section16.14.ControllingAssertionsatRuntime
Chapter17.GarbageCollectionandMemory
Section17.1.GarbageCollection
Section17.2.ASimpleModel
Section17.3.Finalization
Section17.4.InteractingwiththeGarbageCollector
Section17.5.ReachabilityStatesandReferenceObjects
Chapter18.Packages
Section18.1.PackageNaming
Section18.2.TypeImports
Section18.3.PackageAccess
Section18.4.PackageContents
Section18.5.PackageAnnotations
Section18.6.PackageObjectsandSpecifications
Chapter19.DocumentationComments


















































































Section19.1.TheAnatomyofaDocComment
Section19.2.Tags
Section19.3.InheritingMethodDocumentationComments
Section19.4.ASimpleExample
Section19.5.ExternalConventions
Section19.6.NotesonUsage
Chapter20.TheI/OPackage
Section20.1.StreamsOverview
Section20.2.ByteStreams
Section20.3.CharacterStreams
Section20.4.InputStreamReaderandOutputStreamWriter
Section20.5.AQuickTouroftheStreamClasses
Section20.6.TheDataByteStreams
Section20.7.WorkingwithFiles
Section20.8.ObjectSerialization
Section20.9.TheIOExceptionClasses
Section20.10.ATasteofNewI/O
Chapter21.Collections
Section21.1.Collections
Section21.2.Iteration
Section21.3.OrderingwithComparableandComparator
Section21.4.TheCollectionInterface
Section21.5.SetandSortedSet
Section21.6.List
Section21.7.Queue

Section21.8.MapandSortedMap
Section21.9.enumCollections
Section21.10.WrappedCollectionsandtheCollectionsClass
Section21.11.SynchronizedWrappersandConcurrentCollections
Section21.12.TheArraysUtilityClass
Section21.13.WritingIteratorImplementations
Section21.14.WritingCollectionImplementations
Section21.15.TheLegacyCollectionTypes
Section21.16.Properties
Chapter22.MiscellaneousUtilities
Section22.1.Formatter
Section22.2.BitSet
Section22.3.Observer/Observable
Section22.4.Random
















































































Section22.5.Scanner
Section22.6.StringTokenizer
Section22.7.TimerandTimerTask
Section22.8.UUID
Section22.9.MathandStrictMath
Chapter23.SystemProgramming
Section23.1.TheSystemClass
Section23.2.CreatingProcesses
Section23.3.Shutdown
Section23.4.TheRestofRuntime
Section23.5.Security
Chapter24.InternationalizationandLocalization
Section24.1.Locale
Section24.2.ResourceBundles
Section24.3.Currency
Section24.4.Time,Dates,andCalendars
Section24.5.FormattingandParsingDatesandTimes
Section24.6.InternationalizationandLocalizationforText
Chapter25.StandardPackages
Section25.1.java.awtTheAbstractWindowToolkit
Section25.2.java.appletApplets
Section25.3.java.beansComponents
Section25.4.java.mathMathematics
Section25.5.java.netTheNetwork
Section25.6.java.rmiRemoteMethodInvocation
Section25.7.java.securityandRelatedPackagesSecurityTools
Section25.8.java.sqlRelationalDatabaseAccess
Section25.9.UtilitySubpackages
Section25.10.javax.*StandardExtensions

Section25.11.javax.accessibilityAccessibilityforGUIs
Section25.12.javax.namingDirectoryandNamingServices
Section25.13.javax.soundSoundManipulation
Section25.14.javax.swingSwingGUIComponents
Section25.15.org.omg.CORBACORBAAPIs
AppendixA.ApplicationEvolution
SectionA.1.Language,Library,andVirtualMachineVersions
SectionA.2.DealingwithMultipleDialects
SectionA.3.Generics:Reification,Erasure,andRawTypes
AppendixB.UsefulTables



















FurtherReading











JavaPlatformTopics
Object-OrientedDesign
MultithreadedProgramming
Generics
RegularExpressions
GeneralProgrammingTechniques
RelatedLanguages
SoftwareEngineering
VisualDesign&GUIDesign
Colophon

NotetoTranslators
Article
Exercises
Quotes
Index


Copyright
©2006SunMicrosystems,Inc.

4150NetworkCircle,SantaClara,California95054U.S.A.
Allrightsreserved.
Use,duplication,ordisclosurebytheUnitedStatesGovernment
issubjecttotherestrictionssetforthinDFARS252.227-7013
(c)(1)(ii)andFAR52.227-19.
Thereleasedescribedinthisbookmaybeprotectedbyoneor
moreU.S.patents,foreignpatents,orpendingapplications.
SunMicrosystems,Inc.(SUN)herebygrantstoyouafully-paid,
nonexclusive,nontransferable,perpetual,worldwidelimited
license(withouttherighttosublicense)underSUN'sintellectual
propertyrightsthatareessentialtopracticethisspecification.
Thislicenseallowsandislimitedtothecreationanddistribution
ofcleanroomimplementationsofthisspecificationthat:(i)
includeacompleteimplementationofthecurrentversionofthis
specificationwithoutsubsettingorsupersetting;(ii)implement
alltheinterfacesandfunctionalityofthestandardjava.*
packagesasdefinedbySUN,withoutsubsettingor
supersetting;(iii)donotaddanyadditionalpackages,classes
ormethodstothejava.*packages;(iv)passalltestsuites
relatingtothemostrecentpublishedversionofthis
specificationthatareavailablefromSUNsix(6)monthspriorto
anybetareleaseofthecleanroomimplementationorupgrade
thereto;(v)donotderivefromSUNsourcecodeorbinary
materials;and(vi)donotincludeanySUNbinarymaterials
withoutanappropriateandseparatelicensefromSUN.
Sun,SunMicrosystems,SunMicrosystemsComputer
Corporation,theSunlogo,theSunMicrosystemsComputer


Corporationlogo,Java,JavaSoft,JavaScriptJDBC,JDBC

Compliant,JavaOS,JavaBeansandHotJavaaretrademarksor
registeredtrademarksofSunMicrosystems,Inc.UNIX®isa
registeredtrademarkintheUnitedStatesandothercountries,
exclusivelylicensedthroughX/OpenCompany,Ltd.Appleand
DylanaretrademarksofAppleComputer,Inc.Allotherproduct
namesmentionedhereinarethetrademarksoftheirrespective
owners.
THISPUBLICATIONISPROVIDED"ASIS"WITHOUTWARRANTY
OFANYKIND,EITHEREXPRESSORIMPLIED,INCLUDING,BUT
NOTLIMITEDTO,THEIMPLIEDWARRANTIESOF
MERCHANTABILITY,FITNESSFORAPARTICULARPURPOSE,OR
NON-INFRINGEMENT.
THISPUBLICATIONCOULDINCLUDETECHNICAL
INACCURACIESORTYPOGRAPHICALERRORS.CHANGESARE
PERIODICALLYADDEDTOTHEINFORMATIONHEREIN;THESE
CHANGESWILLBEINCORPORATEDINNEWEDITIONSOFTHE
PUBLICATION.SUNMICROSYSTEMS,INC.MAYMAKE
IMPROVEMENTSAND/ORCHANGESINTHEPRODUCT(S)
AND/ORTHEPROGRAM(S)DESCRIBEDINTHISPUBLICATION
ATANYTIME.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor

programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen


orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:U.S.CorporateandGovernmentSales,(800)3823419,
ForsalesoutsidetheU.S.,pleasecontact:InternationalSales,

VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData

Arnold,Ken,1958TheJavaprogramminglanguage/KenArnold,JamesGosling,DavidHolm
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-321-34980-6(pbk.:alk.paper)
1.Java(Computerprogramlanguage)I.Gosling,James.II.Holmes,Davi
QA76.73.J38A762005
005.13'3-dc222005017029
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:PearsonEducation,Inc.,Rightsand
ContractsDepartment,OneLakeStreet,UpperSaddleRiver,NJ
07458

TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.


Firstprinting,August2005

Dedication
ThisbookisdedicatedtotheJavateamFromwhosehardwork
andvisionAmightyoakhasgrown
ToSusanK.A.
ToJudyandKateJ.A.G.
ToLee,Taylor,andCaitlinD.H.


TheJava™Series
KenArnold,JamesGosling,DavidHolmes
TheJava™ProgrammingLanguage,ThirdEdition
CynthiaBloch,AnnetteWagner
MIDP2.0StyleGuidefortheJava™2Platform,MicroEdition
JoshuaBloch
EffectiveJava™ProgrammingLanguageGuide
MaryCampione,KathyWalrath,AlisonHuml
TheJava™Tutorial,ThirdEdition:AShortCourseontheBasics
MaryCampione,KathyWalrath,AlisonHuml,TutorialTeam
TheJava™TutorialContinued:TheRestoftheJDK™
PatrickChan
TheJava™DevelopersAlmanac1.4,Volume1
PatrickChan
TheJava™DevelopersAlmanac1.4,Volume2
PatrickChan,RosannaLee

TheJava™ClassLibraries,SecondEdition,Volume2:
java.applet,java.awt,java.beans
PatrickChan,RosannaLee,DougKramer
TheJava™ClassLibraries,SecondEdition,Volume1:java.io,


java.lang,java.math,java.net,java.text,java.util
PatrickChan,RosannaLee,DougKramer
TheJava™ClassLibraries,SecondEdition,Volume1:
SupplementfortheJava™2Platform,StandardEdition,v1.2
KirkChen,LiGong
ProgrammingOpenServiceGatewayswithJava™Embedded
Server
ZhiqunChen
JavaCard™TechnologyforSmartCards:Architectureand
Programmer'sGuide
MaydeneFisher,JonEllis,JonathanBruce
JDBC™APITutorialandReference,ThirdEdition
LiGong,GaryEllison,MaryDageforde
InsideJava™2PlatformSecurity,SecondEdition:Architecture,
APIDesign,andImplementation
JamesGosling,BillJoy,GuySteele,GiladBracha
TheJava™LanguageSpecification,ThirdEdition
DougLea
ConcurrentProgramminginJava™,SecondEdition:Design
PrinciplesandPatterns
RosannaLee,ScottSeligman
JNDIAPITutorialandReference:BuildingDirectory-Enabled
Java™Applications



ShengLiang
TheJava™NativeInterface:Programmer'sGuideand
Specification
TimLindholm,FrankYellin
TheJava™VirtualMachineSpecification,SecondEdition
RogerRiggs,AnteroTaivalsaari,JimVanPeursem,Jyri
Huopaniemi,MarkPatel,AleksiUotila
ProgrammingWirelessDeviceswiththeJava™2Platform,Micro
Edition,SecondEdition
SunMicrosystems,Inc.
Java™LookandFeelDesignGuidelines:AdvancedTopics
KathyWalrath,MaryCampione,AlisonHuml,SharonZakhour
TheJFCSwingTutorial,SecondEdition:AGuidetoConstructing
GUIs
SethWhite,MaydeneFisher,RickCattell,GrahamHamilton,
MarkHapner
JDBC™APITutorialandReference,SecondEdition:Universal
DataAccessfortheJava™2Platform
SteveWilson,JeffKesselman
Java™PlatformPerformance:StrategiesandTactics
TheJini™TechnologySeries
EricFreeman,SusanneHupfer,KenArnold
JavaSpaces™Principles,Patterns,andPractice


TheJava™Series,EnterpriseEdition
StephanieBodoff,DaleGreen,KimHaase,EricJendrock
TheJ2EE™Tutorial,SecondEdition
RickCattell,JimInscore,EnterprisePartners

J2EE™TechnologyinPractice:BuildingBusinessApplications
withtheJava™2Platform,EnterpriseEdition
MarkHapner,RichBurridge,RahulSharma,JosephFialli,Kim
Haase
Java™MessageServiceAPITutorialandReference:Messaging
fortheJ2EE™Platform
InderjeetSingh,BethStearns,MarkJohnson,EnterpriseTeam
DesigningEnterpriseApplicationswiththeJava™2Platform,
EnterpriseEdition
VladaMatena,SanjeevKrishnan,LindaDeMichiel,BethStearns
ApplyingEnterpriseJavaBeans™,SecondEdition:ComponentBasedDevelopmentfortheJ2EE™Platform
BillShannon,MarkHapner,VladaMatena,JamesDavidson,
EduardoPelegri-Llopart,LarryCable,EnterpriseTeam
Java™2Platform,EnterpriseEdition:PlatformandComponent
Specifications
RahulSharma,BethStearns,TonyNg
J2EE™ConnectorArchitectureandEnterpriseApplication
Integration


Preface
Beautifulbuildingsaremorethanscientific.Theyaretrue
organisms,spirituallyconceived;worksofart,usingthe
besttechnologybyinspirationratherthanthe
idiosyncrasiesofmeretasteoranyaveragingbythe
committeemind.
FrankLloydWright
TheJava™programminglanguagehasbeenwarmlyreceivedby
theworldcommunityofsoftwaredevelopersandInternet
contentproviders.UsersoftheInternetandWorldWideWeb

benefitfromaccesstosecure,platform-independent
applicationsthatcancomefromanywhereontheInternet.
SoftwaredeveloperswhocreateapplicationsintheJava
programminglanguagebenefitbydevelopingcodeonlyonce,
withnoneedto"port"theirapplicationstoeverysoftwareand
hardwareplatform.
Formany,thelanguagewasknownfirstasatooltocreate
appletsfortheWorldWideWeb.Anappletisamini-application
thatrunsinsideaWebpage.Anappletcanperformtasksand
interactwithusersontheirbrowserpageswithoutusing
resourcesfromtheWebserverafterbeingdownloaded.Some
appletsmay,ofcourse,talkwiththeservertodotheirjob,but
that'stheirbusiness.
TheJavaprogramminglanguageisindeedvaluablefor
distributednetworkenvironmentsliketheWeb.However,it
goeswellbeyondthisdomaintoprovideapowerfulgeneralpurposeprogramminglanguagesuitableforbuildingavarietyof
applicationsthateitherdonotdependonnetworkfeaturesor
wantthemfordifferentreasons.Theabilitytoexecute
downloadedcodeonremotehostsinasecuremannerisa


criticalrequirementformanyorganizations.
Othergroupsuseitasageneral-purposeprogramming
languageforprojectsinwhichmachineindependenceisless
important.Easeofprogrammingandsafetyfeatureshelpyou
quicklyproduceworkingcode.Somecommonprogramming
errorsneveroccurbecauseoffeatureslikegarbagecollection
andtype-safereferences.Supportformultithreadingcatersto
modernnetwork-basedandgraphicaluserinterfacebased
applicationsthatmustattendtomultipletaskssimultaneously,

andthemechanismsofexceptionhandlingeasethetaskof
dealingwitherrorconditions.Whilethebuilt-intoolsare
powerful,itisasimplelanguageinwhichprogrammerscan
quicklybecomeproficient.
TheJavaprogramminglanguageisdesignedformaximum
portabilitywithasfewimplementationdependenciesas
possible.Anint,forexample,isa32-bitsignedtwo'scomplementintegerinallimplementations,irrespectiveofthe
CPUarchitectureonwhichtheprogramexecutes.Defining
everythingpossibleaboutthelanguageanditsruntime
environmentenablesuserstoruncompiledcodeanywhereand
sharecodewithanyonewhohasaJavaruntimeenvironment.


AboutThisBook
ThisbookteachestheJavaprogramminglanguagetopeople
whoarefamiliarwithbasicprogrammingconcepts.Itexplains
thelanguagewithoutbeingarduouslyformalorcomplete.This
bookisnotanintroductiontoobject-orientedprogramming,
althoughsomeissuesarecoveredtoestablishacommon
terminology.Otherbooksinthisseriesandmuchonline
documentationfocusonapplets,graphicalinterfaces,Websites,
databases,components,andotherspecifickindsof
programmingtasks.Forotherreferences,see"FurtherReading"
onpage755.
ThisfourtheditionprovidesintegratedcoverageoftheJava
programminglanguageasprovidedbytheJava™2Platform
StandardEdition5.0andspecifiedbytheJava™Language
Specification,ThirdEdition.Italsocoversmostoftheclassesin
themainpackages(java.lang,java.util,java.io)asimplemented
intheJ2SE™DevelopmentKit5.0(morecommonlyknownasJDK

5.0,orintheoldernomenclatureJDK1.5.0).
Ifyouhavealreadyreadthethirdeditionofthisbook,youwill
findsomemajorchanges,bothinthelanguageandthebook,
sincethe1.3releasethatthethirdeditioncovered.Thereare
newchaptersongenerics,enums,andannotationsthemajor
newlanguagefeaturesintroducedinthe5.0releaseandmajor
newsectionsonassertionsandregularexpressions.Some
existingmaterialhasbeenrestructuredtoaccommodateother
changesandtoimprovethegeneralflowofthetextsuchas
introducingthenewboxingandunboxingconversions.But
everysinglechapterhasbeenupdatedinsomeway,whetherit
isanewlanguagefeaturelikevariableargumentmethods;the
newenhancedforloopconstruct;anewclasssuchasFormatter
forformattingtextoutput;orchangestoclassesandmethods
causedbytheadditionofgenerics(suchasthecollections


utilitiesandthereflectionclasses)changepermeatesthisentire
fourthedition.
TheJavaprogramminglanguagesharesmanyfeaturescommon
tomostprogramminglanguagesinusetoday.Thelanguage
shouldlookfamiliartoCandC++programmersbecauseitwas
designedwithCandC++constructswherethelanguagesare
similar.Thatsaid,thisbookisneitheracomparativeanalysis
nora"bridge"tutorialnoknowledgeofCorC++isassumed.
C++programmers,especially,maybeashinderedbywhat
theymustunlearnastheyarehelpedbytheirknowledge.
Chapter1AQuickTourgivesaquickoverviewofthelanguage.
Programmerswhoareunfamiliarwithobject-oriented
programmingnotionsshouldreadthequicktour,while

programmerswhoarealreadyfamiliarwithobject-oriented
programmingparadigmswillfindthequicktourauseful
introductiontotheobject-orientedfeaturesofthelanguage.
Thequicktourintroducessomeofthebasiclanguagefeatures
onwhichexamplesthroughtherestofthebookarebuilt.
Chapters2through6covertheobject-orientedcorefeaturesof
thelanguage,namely,classdeclarationsthatdefine
componentsofaprogram,andobjectsmanufacturedaccording
toclassdefinitions.Chapter2ClassesandObjectsdescribesthe
basisofthelanguage:classes.Chapter3Extending
Classesdescribeshowanexistingclasscanbeextended,or
subclassed,tocreateanewclasswithadditionaldataand
behavior.Chapter4Interfacesdescribeshowtodeclareinterface
typesthatareabstractdescriptionsofbehaviorthatprovide
maximumflexibilityforclassdesignersandimplementors.
Chapter5NestedClassesandInterfacesdescribeshowclasses
andinterfacescanbedeclaredinsideotherclassesand
interfaces,andthebenefitsthatprovides.Finally,Chapter
6EnumerationTypescoversthedefinitionanduseoftype-safe
enumerationconstants.
Chapters7through10coverstandardconstructscommonto


mostlanguages.Chapter7Tokens,Values,and
Variablesdescribesthetokensofthelanguagefromwhich
statementsareconstructed,thetypesdefinedbythelanguage
andtheirallowedvalues,andthevariablesthatstoredatain
objects,arrays,orlocallywithinmethods.Chapter8Primitives
asTypesexplorestherelationshipbetweentheprimitivetypes
andobjectsoftheircorrespondingwrapperclasses,andhow

boxingandunboxingcantransparentlyconvertbetweenthem.
Chapter9OperatorsandExpressionsdescribesthebasic
operatorsofthelanguage,howtheseoperatorsareusedto
buildexpressions,andhowexpressionsareevaluated.Chapter
10ControlFlowdescribeshowcontrolstatementsdirectthe
orderofstatementexecution.
Chapter11GenericTypesdescribesgenerictypes:howtheyare
writtenandused,theirpower,andtheirlimitations.
Chapter12ExceptionsandAssertionsdescribesthelanguage's
powerfulerror-handlingcapabilities,andtheuseofassertions
tovalidatetheexpectedbehaviorofcode.
Chapter13StringsandRegularExpressionsdescribesthebuilt-in
languageandruntimesupportforStringobjects,theunderlying
charactersetsupport,andthepowerfulutilitiesforregular
expressionmatching.
Chapter14Threadsexplainsthelanguage'sviewof
multithreading.Manyapplications,suchasgraphical
interfacebasedsoftware,mustattendtomultipletasks
simultaneously.Thesetasksmustcooperatetobehave
correctly,andthreadsmeettheneedsofcooperative
multitasking.
Chapter15Annotationsdescribestheannotationtypesusedto
documentsomeoftheextra-linguisticpropertiesofclassesand
method.
Chapter16Reflectiondescribestheruntimetypeintrospection


mechanismandhowyoucanconstructandmanipulateobjects
ofunknowntypedynamicallyatruntime.
Chapter17GarbageCollectionandMemorytalksaboutgarbage

collection,finalization,andlower-strengthreferenceobjects.
Chapter18Packagesdescribeshowyoucangroupcollectionsof
classesandinterfacesintoseparatepackages.
Chapter19DocumentationCommentsshowshowtowrite
referencedocumentationincomments.
Chapters20through24coverthemainpackages.Chapter
20TheI/OPackagedescribestheinput/outputsystem,whichis
basedonstreams.Chapter21Collectionscoversthecollectionor
containerclassessuchassetsandlists.Chapter
22MiscellaneousUtilitiescoverstherestoftheutilityclasses
suchasbitsets,formattedoutput,textscanning,andrandom
numbergeneration.Chapter23SystemProgrammingleadsyou
throughthesystemclassesthatprovideaccesstofeaturesof
theunderlyingplatform.Chapter24Internationalizationand
Localizationcoverssomeofthetoolsusedtocreateprograms
thatcanruninmanylinguisticandculturalenvironments.
Chapter25StandardPackagesbrieflyexploresthepackagesthat
arepartofthestandardplatform,givingoverviewsofthose
packagesnotcoveredinmoredetailinthisbook.
AppendixAApplicationEvolutionlooksatsomeoftheissues
involvedindealingwiththeevolutionofapplicationsandthe
Javaplatform,andtheimpactthishasonsomeofthenew
languagefeatures.
AppendixBUsefulTableshastablesofinformationthatyoumay
findusefulforquickreference.
Finally,FurtherReadinglistsworksthatmaybeinterestingfor
furtherreadingoncompletedetails,objectorientation,


programmingwiththreads,softwaredesign,andothertopics.



ExamplesandDocumentation
Allthecodeexamplesinthetexthavebeencompiledandrun
onthelatestversionofthelanguageavailableatthetimethe
bookwaswritten,whichwastheJDK1.5.0_02productversion.
Onlysupportedfeaturesarecovereddeprecatedtypes,
methods,andfieldsareignoredexceptwhenunavoidableor
whenknowledgeofthepastisnecessarytounderstandthe
present.Wehavealsocoveredissuesbeyondwritingprograms
thatsimplycompile.Partoflearningalanguageistolearnto
useitwell.Forthisreason,wehavetriedtoshowprinciplesof
goodprogrammingstyleanddesign.
Inafewplaceswerefertoonlinedocumentation.Development
environmentsprovideawaytoautomaticallygenerate
documentation(usuallyHTMLdocuments)foracompiledclass
fromitsdocumentationcomments.Thisdocumentationis
normallyviewedwithaWebbrowser.


×