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

OReilly learning java 3rd edition may 2005 ISBN 0596008732

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 (8.29 MB, 1,816 trang )

LearningJava,3rdEdition
ByJonathanKnudsen,PatrickNiemeyer
...............................................
Publisher:O'Reilly
PubDate:May2005
ISBN:0-596-00873-2
Pages:976

TableofContents|Index

Version5.0oftheJava2StandardEditionSDKisthemostimportantupgradesinceJava
firstappearedadecadeago.WithJava5.0,you'llnotonlyfindsubstantialchangesinthe
platform,buttothelanguageitself-somethingthatdevelopersofJavatookfiveyearsto
complete.ThemaingoalofJava5.0istomakeiteasierforyoutodevelopsafe,powerful
code,butnoneoftheseimprovementsmakesJavaanyeasiertolearn,evenifyou've
programmedwithJavaforyears.Andthatmeansourbestsellinghands-ontutorialtakes
onevengreatersignificance.
LearningJavaisthemostwidelysoughtintroductiontotheprogramminglanguagethat's
changedthewaywethinkaboutcomputing.Ourupdatedthirdeditiontakesanobjective,
no-nonsenseapproachtothenewfeaturesinJava5.0,someofwhicharedrastically
differentfromthewaythingsweredoneinanypreviousversions.Themostessential
changeistheadditionof"generics",afeaturethatallowsdeveloperstowrite,test,and
deploycodeonce,andthenreusethecodeagainandagainfordifferentdatatypes.The
beautyofgenericsisthatmoreproblemswillbecaughtduringdevelopment,andLearning
Javawillshowyouexactlyhowit'sdone.
Java5.0alsoaddsmorethan1,000newclassestotheJavalibrary.Thatmeans1,000
newthingsyoucandowithouthavingtoprogramitinyourself.That'sahugechange.
Withourbook'spracticalexamples,you'llcomeuptospeedquicklyonthisandothernew
featuressuchasloopsandthreads.Theneweditionalsoincludesanintroductionto
Eclipse,theopensourceIDEthatisgrowinginpopularity.
LearningJava,3rdEditionaddressesalloftheimportantusesofJava,suchasweb


applications,servlets,andXMLthatareincreasinglydrivingenterpriseapplications.The
accompanyingCDincludestheJava5.0SDKforWindows,LinuxandSolaris,plusthe
EclipseIDE,theNetBeansIDE,andthemanyexampleprogramsfromthebook.


LearningJava,3rdEdition
ByJonathanKnudsen,PatrickNiemeyer
...............................................
Publisher:O'Reilly
PubDate:May2005
ISBN:0-596-00873-2
Pages:976

TableofContents|Index



















































Copyright
Preface
NewDevelopments
UsingThisBook
OnlineResources
ConventionsUsedinThisBook
UsingCodeExamples
SafariEnabled
HowtoContactUs
Acknowledgments
Chapter1.AModernLanguage
Section1.1.EnterJava
Section1.2.AVirtualMachine
Section1.3.JavaComparedwithOtherLanguages
Section1.4.SafetyofDesign
Section1.5.SafetyofImplementation
Section1.6.ApplicationandUser-LevelSecurity
Section1.7.JavaandtheWeb
Section1.8.JavaasaGeneralApplicationLanguage
Section1.9.AJavaRoadMap
Chapter2.AFirstApplication
Section2.1.JavaToolsandEnvironment
Section2.2.HelloJava
Section2.3.HelloJava2:TheSequel
Section2.4.HelloJava3:TheButtonStrikes!















































































Section2.5.HelloJava4:Netscape'sRevenge
Section2.6.Troubleshooting
Chapter3.ToolsoftheTrade
Section3.1.TheJavaVM
Section3.2.RunningJavaApplications
Section3.3.TheClasspath
Section3.4.TheJavaCompiler
Section3.5.JARFiles
Section3.6.PolicyFiles
Chapter4.TheJavaLanguage
Section4.1.TextEncoding
Section4.2.Comments
Section4.3.Types
Section4.4.StatementsandExpressions
Section4.5.Exceptions
Section4.6.Assertions

Section4.7.Arrays
Chapter5.ObjectsinJava
Section5.1.Classes
Section5.2.Methods
Section5.3.ObjectCreation
Section5.4.ObjectDestruction
Section5.5.Enumerations
Chapter6.RelationshipsAmongClasses
Section6.1.SubclassingandInheritance
Section6.2.Interfaces
Section6.3.PackagesandCompilationUnits
Section6.4.VisibilityofVariablesandMethods
Section6.5.ArraysandtheClassHierarchy
Section6.6.InnerClasses
Chapter7.WorkingwithObjectsandClasses
Section7.1.TheObjectClass
Section7.2.TheClassClass
Section7.3.Reflection
Section7.4.Annotations
Chapter8.Generics
Section8.1.Containers:BuildingaBetterMousetrap
Section8.2.EnterGenerics
Section8.3."ThereIsNoSpoon"

















































































Section8.4.ParameterizedTypeRelationships
Section8.5.Casts
Section8.6.WritingGenericClasses
Section8.7.Bounds
Section8.8.Wildcards
Section8.9.GenericMethods
Section8.10.ArraysofParameterizedTypes
Section8.11.CaseStudy:TheEnumClass
Section8.12.CaseStudy:Thesort()Method
Section8.13.Conclusion
Chapter9.Threads
Section9.1.IntroducingThreads
Section9.2.ThreadinganApplet
Section9.3.Synchronization
Section9.4.SchedulingandPriority
Section9.5.ThreadGroups
Section9.6.ThreadPerformance
Section9.7.ConcurrencyUtilities
Section9.8.Conclusion

Chapter10.WorkingwithText
Section10.1.Text-RelatedAPIs
Section10.2.Strings
Section10.3.Internationalization
Section10.4.ParsingandFormattingText
Section10.5.Printf-StyleFormatting
Section10.6.Formattingwiththejava.textPackage
Section10.7.RegularExpressions
Chapter11.CoreUtilities
Section11.1.MathUtilities
Section11.2.DatesandTimes
Section11.3.Timers
Section11.4.Collections
Section11.5.Properties
Section11.6.ThePreferencesAPI
Section11.7.TheLoggingAPI
Section11.8.ObserversandObservables
Chapter12.Input/OutputFacilities
Section12.1.Streams
Section12.2.Files
















































































Section12.3.Serialization
Section12.4.DataCompression
Section12.5.TheNIOPackage
Chapter13.NetworkProgramming
Section13.1.Sockets
Section13.2.DatagramSockets
Section13.3.SimpleSerializedObjectProtocols
Section13.4.RemoteMethodInvocation
Section13.5.ScalableI/OwithNIO
Chapter14.ProgrammingfortheWeb
Section14.1.UniformResourceLocators(URLs)
Section14.2.TheURLClass
Section14.3.TalkingtoWebApplications
Section14.4.WebServices
Chapter15.WebApplicationsandWebServices
Section15.1.WebApplicationTechnologies
Section15.2.WebApplications
Section15.3.WARFilesandDeployment
Section15.4.ServletFilters
Section15.5.BuildingWARFileswithAnt
Section15.6.ImplementingWebServices
Chapter16.Swing
Section16.1.Components

Section16.2.Events
Section16.3.EventSummary
Section16.4.TheAWTRobot!
Section16.5.MultithreadinginSwing
Chapter17.UsingSwingComponents
Section17.1.ButtonsandLabels
Section17.2.HTMLTextinButtonsandLabels
Section17.3.CheckboxesandRadioButtons
Section17.4.ListsandComboBoxes
Section17.5.TheSpinner
Section17.6.Borders
Section17.7.Menus
Section17.8.Pop-upMenus
Section17.9.Component-ManagedPop-ups
Section17.10.TheJScrollPaneClass
Section17.11.TheJSplitPaneClass

















































































Section17.12.TheJTabbedPaneClass
Section17.13.ScrollbarsandSliders
Section17.14.Dialogs
Section17.15.FileSelectionDialog
Section17.16.TheColorChooser
Chapter18.MoreSwingComponents
Section18.1.TextComponents
Section18.2.FocusNavigation
Section18.3.Tables
Section18.4.Desktops
Section18.5.PluggableLook-and-Feel
Section18.6.CreatingCustomComponents
Chapter19.LayoutManagers
Section19.1.FlowLayout
Section19.2.GridLayout
Section19.3.BorderLayout
Section19.4.BoxLayout
Section19.5.CardLayout
Section19.6.GridBagLayout
Section19.7.NonstandardLayoutManagers
Section19.8.AbsolutePositioning
Section19.9.SpringLayout
Chapter20.Drawingwiththe2DAPI
Section20.1.TheBigPicture
Section20.2.TheRenderingPipeline
Section20.3.AQuickTourofJava2D

Section20.4.FillingShapes
Section20.5.StrokingShapeOutlines
Section20.6.UsingFonts
Section20.7.DisplayingImages
Section20.8.DrawingTechniques
Section20.9.Printing
Chapter21.WorkingwithImagesandOtherMedia
Section21.1.LoadingImages
Section21.2.ProducingImageData
Section21.3.FilteringImageData
Section21.4.SavingImageData
Section21.5.SimpleAudio
Section21.6.JavaMediaFramework











































Chapter22.JavaBeans






































Section22.1.What'saBean?
Section22.2.TheNetBeansIDE
Section22.3.PropertiesandCustomizers
Section22.4.EventHookupsandAdapters
Section22.5.BindingProperties
Section22.6.BuildingBeans
Section22.7.LimitationsofVisualDesign
Section22.8.SerializationVersusCodeGeneration
Section22.9.CustomizingwithBeanInfo
Section22.10.Hand-CodingwithBeans
Section22.11.BeanContextandBeanContextServices
Section22.12.TheJavaActivationFramework
Section22.13.EnterpriseJavaBeans
Chapter23.Applets
Section23.1.ThePoliticsofApplets
Section23.2.TheJAppletClass
Section23.3.UsingtheJavaPlug-in
Section23.4.JavaWebStart
Section23.5.UsingDigitalSignatures
Section23.6.Conclusion
Chapter24.XML
Section24.1.ABitofBackground
Section24.2.XMLBasics
Section24.3.SAX
Section24.4.DOM
Section24.5.XPath
Section24.6.XInclude
Section24.7.ValidatingDocuments

Section24.8.JAXBandCodeGeneration
Section24.9.TransformingDocumentswithXSL/XSLT
Section24.10.WebServices
Section24.11.TheEndoftheBook
AppendixA.TheEclipseIDE
SectionA.1.TheIDEWars
SectionA.2.GettingStartedwithEclipse
SectionA.3.UsingEclipse
SectionA.4.EclipseFeatures
SectionA.5.Conclusion


AppendixB.BeanShell:SimpleJavaScripting






















SectionB.1.RunningBeanShell
SectionB.2.JavaStatementsandExpressions
SectionB.3.BeanShellCommands
SectionB.4.ScriptedMethodsandObjects
SectionB.5.ChangingtheClasspath
SectionB.6.LearningMore...
Glossary
Colophon

AbouttheAuthors

Colophon
Index


LearningJava?,ThirdEdition
byPatrickNiemeyerandJonathanKnudsen
Copyright©2005,2002,2000O'ReillyMedia,Inc.Allrights
reserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or


Editor:

MikeLoukidesandDebraCameron

ProductionEditor:

MattHutchinson

ProductionServices:

MendeDesign,OctalPublishing,Inc.

CoverDesigner:

HannaDyer

InteriorDirector:

DavidFutato

PrintingHistory:



May2000:

FirstEdition.

June2002:


SecondEdition.

May2005:

ThirdEdition.


NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
LearningJava,theimageofaBengaltigressandcubs,and
relatedtradedressaretrademarksofO'ReillyMedia,Inc.
Java?andallJava-basedtrademarksandlogosaretrademarks
orregisteredtrademarksofSunMicrosystems,Inc.,inthe
UnitedStatesandothercountries.O'ReillyMedia,Inc.,is
independentofSunMicrosystems.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-00873-2
[M]


Preface

ThisbookisabouttheJavaTMlanguageandprogramming
environment.Whetheryouareasoftwaredeveloperorjust
someonewhousestheInternetinyourdailylife,you've
undoubtedlyheardaboutJava.Itsintroductionwasoneofthe
mostexcitingdevelopmentsinthehistoryoftheWebandit
hasn'tsloweddownmuchsince.Javaisnow,arguably,themost
popularprogramminglanguageintheworld,usedbymillionsof
developersonalmosteverykindofcomputerimaginable.In
recentyearsJavahassurpassedlanguagessuchasC++and
VisualBasicintermsofdeveloperdemandandbecomethede
factolanguagefornewdevelopmentespeciallyforweb-based
applicationsandservices.MostuniversitiesarenowusingJava
intheirintroductorycourses,alongsidetheotherimportant
modernlanguages.Perhapsyouareusingthistextinoneof
yourclassesrightnow!
ThisbookgivesyouathoroughgroundinginJavafundamentals
andAPIs.LearningJava,ThirdEditionattemptstoliveuptoits
namebymappingouttheJavalanguage,itsclasslibraries,
programmingtechniques,andidioms.We'lldigdeepinto
interestingareasandatleastscratchthesurfaceoftherest.
OthertitlesfromO'Reillypickupwhereweleaveoffand
providemorecomprehensiveinformationonspecificareasand
applicationsofJava.
Wheneverpossible,weprovidecompelling,realistic,andfun
examplesandavoidmerelycatalogingfeatures.Theexamples
aresimplebuthintatwhatcanbedone.Wewon'tbe
developingthenextgreat"killerapp"inthesepages,butwe
hopetogiveyouastartingpointformanyhoursof
experimentationandinspiredtinkeringthatwillleadyouto
learnmoreonyourown.



NewDevelopments
ThiseditionofLearningJavaisactuallythefiftheditionupdated
andretitledofouroriginal,popularExploringJava.Witheach
editionwe'vetakengreatcarenotonlytoaddnewmaterial
coveringadditionalfeatures,buttothoroughlyreviseand
updatetheexistingcontenttosynthesizethecoverageandadd
yearsofreal-worldperspectiveandexperiencetothesepages.
Onenoticeablechangeinrecenteditionsisthatwe've
deemphasizedtheuseofapplets,reflectingtheirsomewhat
staticroleoverthepastcoupleofyearsincreatinginteractive
webpages.Incontrast,we'vegreatlyexpandedourcoverageof
server-sidewebapplicationsandXML,whicharenowmature
technologies.
Wecoveralloftheimportantfeaturesofthelatestreleaseof
Java,officiallycalledJava2StandardEdition5.0,JDK1.5.Sun
haschangedthenamingschememanytimesovertheyears
andthisisthemostconfusingreleaseever!Suncoinedthe
term"Java2"tocoverthemajornewfeaturesintroducedin
JavaVersion1.2anddroppedthetermJDKinfavorofSDK.
WiththisreleaseSunhasskippedfromJavaVersion1.4tothe
Java5.0,butreprievedthetermJDKandkeptitsnumbering
conventionthere.We'vehadnochoicebuttoaccepttheterm
Java5.0intoourvocabulary.Youcan'tfightmarketing.
ThisreleaseofJavaistargetedatdevelopersandhasthe
biggestsetoflanguagechangessinceJava'sbirth.We'vetried
tocapturethesenewfeaturesandupdateeveryexampleinthis
booktoreflectnotonlythecurrentJavapractice,butstyle.


NewinThisEdition


Thiseditionofthebookhasbeensignificantlyreworkedtobeas
completeanduptodateaspossible.Newtopicsinthisedition
include:
NewJava5.0languagefeatures,includingtypesafe
enumerations,variable-lengthargumentlists(varargs),the
enhancedforloop,autoboxing,staticimports,and
annotations(Chapters4through7)
Afullchapterongenericsandparameterizedtypes(Chapter
8)
FullcoverageofthenewJavaconcurrencypackage,
includingdetailsonexecutors,threadpools,read/write
locks,andmore(Chapter9)
Printf-styletextformattingandthenewScannertextparsingAPI(Chapter10)
NewCollectionsclasses,includingQueueandConcurrent
collections(Chapter11)
EnhancedRMI(Chapter13)
UsingandwritingwebserviceswiththeJavaWebServices
DeveloperPack(Chapters14and15)
CoverageofNetBeans4.x(Chapter22)
MajorXMLenhancements,includingXMLschemaand
validation,JAXBXMLbinding,XPathExpressions,and
XIncludedocumentprocessing(Chapter24)
IntroductiontotheEclipseIDE3.x(AppendixA)and
Audience


Thisbookisforcomputerprofessionals,students,technical

people,andFinnishhackers.It'sforeveryonewhohasaneed
forhands-onexperiencewiththeJavalanguagewithaneye
towardbuildingrealapplications.Thisbookcouldalsobe
consideredacrashcourseinobject-orientedprogramming,
networking,GUIs,andXML.AsyoulearnaboutJava,you'llalso
learnapowerfulandpracticalapproachtosoftware
developmentbeginningwithadeepunderstandingofthe
fundamentalsofJavaanditsAPIs.
Superficially,JavalookslikeCorC++,soyou'llhaveatiny
headstartinusingthisbookifyouhavesomeexperiencewith
oneoftheselanguages.Ifyoudonot,don'tworry.Don'tmake
toomuchofthesyntacticsimilaritiesbetweenJavaandCor
C++.Inmanyrespects,Javaactslikemoredynamiclanguages
suchasSmalltalkandLisp.Knowledgeofanotherobjectorientedprogramminglanguageshouldcertainlyhelp,although
youmayhavetochangesomeideasandunlearnafewhabits.
JavaisconsiderablysimplerthanlanguagessuchasC++and
Smalltalk.Ifyoulearnwellfromgood,conciseexamplesand
personalexperimentation,wethinkyou'lllikethisbook.
ThelastpartofthisbookbranchesouttodiscussJavainthe
contextofwebapplications,webservices,andXMLprocessing,
soyoushouldbefamiliarwiththebasicideasbehindweb
browsers,servers,anddocuments.


UsingThisBook
Thisbookisorganizedroughlyasfollows:
Chapters1and2provideabasicintroductiontoJava
conceptsandatutorialtogiveyouajumpstartonJava
programming.
Chapter3discussesfundamentaltoolsfordevelopingwith

Java(thecompiler,theinterpreter,andtheJARfile
package).
Chapters4through7describetheJavalanguageitself,
beginningwiththebasicsyntaxandthencoveringclasses
andobjects,exceptions,arrays,enumerations,annotations,
andmuchmore.
Chapter8coversgenericsandparameterizedtypesinJava.
Chapter9coversthelanguage'sbuilt-inthreadfacilitiesand
theJavaConcurrencypackage,whichshouldbeof
particularinteresttoadvancedprogrammers.
Chapter10coverstextprocessing,formatting,scanning,
stringutilities,andthepowerfulregularexpressionsAPI.
Chapter11coversmuchofthecoreAPIincludingutilities
andcollections.
Chapter12coversJavaI/O,streams,files,andtheNIO
package.
Chapters13and14coverJavanetworking,including


socketsandNIO,URLs,andRMI.
Chapter15coverswebapplicationsusingservlets,servlet
filters,andWARfiles,aswellaswebservices.
Chapters16through21coverGUIdevelopmentwiththe
AbstractWindowToolkit(AWT)andSwing,whichprovide
graphicaluserinterface(GUI)andimagesupport.
Chapter22coverstheJavaBeans?componentarchitecture
andintroducestheNetBeansIDE.
Chapter23coversapplets,theJavaPlug-In,andJAR
signing.
Chapter24coverstheJavaAPIsforworkingwithXMLand

XSLT,includingXMLSchema,validation,XPath,and
XInclude,aswellasXMLbindingwithJAXB.
AppendixAcoversusingtheEclipseIDEwiththeexamples
inthisbook.
AppendixBdescribesBeanShell,alightweightscripting
languageforJavathatIdeveloped.
Ifyou'relikeus,youdon'treadbooksfromfronttoback.If
you'rereallylikeus,youusuallydon'treadthePrefaceatall.
However,ontheoffchancethatyouwillseethisintime,here
areafewsuggestions:
Ifyouareanexperiencedprogrammerwhohastolearn
Javainthenextfiveminutes,youareprobablylookingfor
theexamples.Youmightwanttostartbyglancingatthe
tutorialinChapter2.Ifthatdoesn'tfloatyourboat,you
shouldatleastlookattheinformationinChapter3,which


explainshowtousethecompilerandinterpreter,or
AppendixA,whichshowshowtoruntheexamplesinthe
EclipseIDE.Thisshouldgetyoustarted.
Chapters12through15areessentialifyouareinterested
inwritingadvancednetworkedorweb-basedapplications.
Thisisoneofthemoreinterestingandimportantpartsof
Java.
Chapters16though22discussJava'sgraphicsfeaturesand
componentarchitecture.Youshouldreadthisifyouare
interestedinwritinggraphicalJavaapplicationsorapplets.
Chapter23coverstheAppletAPI,includingtheJavaplug-in
forguaranteedbrowsercompatibilityandsignedappletsfor
advancedapplications.

Chapter24coverstheJavaAPIsforworkingwithXML,
includingSAX,DOM,DTDs,XMLSchema,andusingXSLto
renderoutputfortheWeb.XMLtechnologyisbecomingkey
tocross-platformdevelopment.Readthischapter!

OntheCD-ROM
TheaccompanyingCD-ROMprovidesallyouneedtostart
workingwithJavaimmediately(viewCDcontentonlineat
Inaddition
tothefullsourcecodeforallexamplesinthebook,theCD
containsthefollowingsoftware:
Java5StandardEdition(alsoknownasJDK1.5)
NetBeans(Version4.1),avisualIDEforworkingwith
JavaBeans


Eclipse(Version3.1),oneofthemostpopularJavaIDEs
Ant(Version1.4.1),auniversalJavabuildsystemfromthe
ApacheProject
Tomcat(Version4.0.3),aJavaservletandwebservices
containerfromtheJakartaProject
BeanShell(Version2.0),asimpleJavascriptinglanguage


OnlineResources
TherearemanyonlinesourcesforinformationaboutJava.Sun
Microsystems'sofficialwebsiteforJavatopicsis
;lookhereforthesoftware,updates,and
Javareleases.Thisiswhereyou'llfindtheJDK,whichincludes
thecompiler,theinterpreter,andothertools(theJDKisalsoon

theCD-ROMthatcomeswiththisbook;viewtheCDcontent
onlineat />YoushouldalsovisitO'ReillyMedia'sJavasiteat
.Thereyou'llfindinformationaboutother
O'ReillyJavabooks,andapointertothehomepagefor
LearningJava, />whereyou'llfindthesourcecodeexamplesforthisbook.


ConventionsUsedinThisBook
Thefontconventionsusedinthisbookarequitesimple.
Italicisusedfor:
Unixpathnames,filenames,andprogramnames
Internetaddresses,suchasdomainnamesandURLs
Newtermswheretheyaredefined
Programnames,compilers,interpreters,utilities,and
commands
Threads
Constantwidthisusedfor:

AnythingthatmightappearinaJavaprogram,including
methodnames,variablenames,andclassnames
TagsthatmightappearinanHTMLorXMLdocument
Keywords,objects,andenvironmentvariables
Constantwidthboldisusedfor:

Textthatistypedbytheuseronthecommandline
Constantwidthitalicisusedfor:


Replaceableitemsincode


Thisicondesignatesanote,whichisanimportantasidetothenearby
text.

Thisicondesignatesawarningrelatingtothenearbytext.

Inthemainbodyoftext,wealwaysuseapairofempty
parenthesesafteramethodnametodistinguishmethodsfrom
variablesandothercreatures.
IntheJavasourcelistings,wefollowthecodingconventions
mostfrequentlyusedintheJavacommunity.Classnamesbegin
withcapitalletters;variableandmethodnamesbeginwith
lowercase.Allthelettersinthenamesofconstantsare
capitalized.Wedon'tuseunderscorestoseparatewordsina
longname;followingcommonpractice,wecapitalizeindividual
words(afterthefirst)andrunthewordstogether.Forexample:
thisIsAVariable,thisIsAMethod(),ThisIsAClass,andTHISISACONSTANT.
Also,notethatwedifferentiatebetweenstaticandnonstatic
methodswhenwerefertothem.Unlikesomebooks,wenever
writeFoo.bar()tomeanthebar()methodofFoounlessbar()is
actuallystatic.


UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Generally,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes

requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.
Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"LearningJava,ThirdEditionbyPatrickNiemeyerand
JonathanKnudsen.Copyright2005O'ReillyMedia,Inc.,0-59600873-2."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat



SafariEnabled

WhenyouseeaSafari®Enabledicononthecoverof
yourfavoritetechnologybook,itmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechnology
books,cutandpastecodesamples,downloadchapters,and
findquickanswerswhenyouneedthemostaccurate,current
information.Tryitforfreeat.


HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.

1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,
examples,oranyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:



Acknowledgments
Manypeoplehavecontributedtoputtingthisbooktogether,
bothinitsExploringJavaincarnationandinitscurrentformas
LearningJava.Foremost,wewouldliketothankTimO'Reillyfor
givingustheopportunitytowritethisbook.ThankstoMike
Loukides,theserieseditor,whosepatienceandexperience
helpedusgetstartedonthisjourney.ThankstoPaulaFerguson
andJohnPosner,whocontributedtheirorganizationaland
editingabilitiesatvarioustimes.AndaspecialthankstoDeb
Cameron,thetirelesseditorofthisbook,withoutwhomthelast
twoeditionsmightneverhavebeenfinishedandcertainly
wouldn'thaveresembledEnglish.Wecouldnothaveaskedfora
moreskillfulorresponsiveteamofpeoplewithwhomtowork.
Speakingofborrowings,theoriginalversionoftheglossary

camefromDavidFlanagan'sbook,JavainaNutshell(O'Reilly).
WealsoborrowedseveralclasshierarchydiagramsfromDavid's
book.Thesediagramswerebasedonsimilardiagramsby
CharlesL.Perkins.
ThanksalsotoMarcWallaceandStevenBurkettforreadingthe
originalworkinprogressandforthesupportofourfriendsat
WashingtonUniversity:BryanO'ConnorandBrianGottlieb.
ThanksalsotoJoshPeck,coauthoroftheoriginalbook,
ExploringJava.Thankstoallthosewhoreviewedoranswered
questions:DavidFlanaganforgenerics;HenryWongforthe
concurrencyutilities;JimElliott,MarcLoy,andBrianColefor
Swing;JackShiraziforNIO;TimBoudreauforNetBeans;Martin
Aeschlimann,JimFarley,andJohnNormanforEclipse;Ed
HowlandforXML;andIanDarwinforregularexpressions.
(CheckoutIan'sJavaCookbook[O'Reilly]formoreexamples.)
ThanksalsotoRayO'Leary,MarioAquino,andMarkVolkmann
fortheirreviews.Andfinally,thankstomybeautifulwife,Song
Fangforputtingupwithmethroughallthiswork.


×