•
•
TableofContents
Index
JustJava™2SIXTHEDITION
ByPETERvanderLINDEN
Publisher :AddisonWesley
PubDate :June21,2004
ISBN :0-13-148211-4
Pages :848
The#1introductiontoJ2SE1.5and
enterprise/server-sidedevelopment!
Aninternationalbestsellerforeightyears,
JustJava(TM)2isthecomplete,accessible
Javatutorialforworkingprogrammersatall
levels.Fullyupdatedandrevised,thissixth
editionismorethananengagingoverviewof
Java2StandardEdition(J2SE1.5)andits
libraries:it'salsoapracticalintroductionto
today'sbestenterpriseandserver-side
programmingtechniques.JustJava(TM)2,
SixthEdition,reflectsbothJ2SE1.5andthe
latestTomcatandservletspecifications.
Extensivenewcoverageincludes:
Newchaptersongenericsandenumerated
types
NewcoverageofWebservices,with
practicalexamplesusingGoogleand
AmazonWebservices
SimplifiedinteractiveI/Owithprintf()
Autoboxingandunboxingofprimitive
types
Staticimports,foreachloopconstruct,and
othernewlanguagefeatures
PetervanderLindendeliversexpertadvice,
clearexplanations,andcrispsample
programsthroughoutincludingdozensnewto
thisedition.Alongtheway,heintroduces:
Thecorelanguage:syntax,objects,
interfaces,nestedclasses,compiler
secrets,andmuchmore
Keylibraries:dateandcalendar,pattern
matching,networksoftware,mappedI/O,
utilitiesandgenericcollections
Server-sidetechnology:networkserver
systems,acompletetinyHTMLWeb
server,andXMLinJava
EnterpriseJ2EE:SqlandJDBC(TM)
tutorial,servletsandJSPandmuchmore
Client-sideJava:fundamentalsof
JFC/SwingGUIdevelopment,newclass
datasharingdetails
CompanionWebSite
Allthebook'sexamplesandsampleprograms
areavailableat.
•
•
TableofContents
Index
JustJava™2SIXTHEDITION
ByPETERvanderLINDEN
Publisher :AddisonWesley
PubDate :June21,2004
ISBN :0-13-148211-4
Pages :848
Copyright
Preface
Acknowledgments
Part1.Language
Chapter1.WhatCanJavaDoforMe?
WhatJavaDoesforYou:SoftwarePortability
WhyPortabilityMatters
OneSizeDoesn'tFitAll
LanguageandLibraries
SomeLightReliefAJavaDesktopApplication
Chapter2.IntroducingObjects
DownloadingandCompilingJava
WhatIsaClass?
JavaDigitalClockProgram
Exercises
WhatIsanObject?
Summary
SomeLightReliefNapsterandLimeWire
Chapter3.PrimitiveTypes,Wrappers,andBoxing
LiteralValues
char
long
short
double
ObjectWrappersforPrimitives
PerformanceImplicationsofAutoboxing
java.lang.String
StringComparison
boolean
int
byte
LimitedAccuracyofFloatingPointTypes
float
AutoboxingandUnboxing
java.lang.Object
LanguageSupportforStringConcatenation
SomeLightReliefHatlessAtlas
Chapter4.StatementsandComments
OrganizingStatements
ExpressionStatements
LoopingStatements
Comments
Exercises
SelectionStatements
TransferofControlStatements
ReadingtheJavaAPI
SomeLightReliefMiniScribe:TheHardLuckHardDisk
Chapter5.OOPPartIIConstructorsandVisibility
PolymorphismIsaLongWordforaShortTopic
CreatingNewObjects:Constructors
Variable-ArityMethods
HowtheJDKFindsClasses
Exercises
MoreAboutMethods
Packages
AccessModifiers
SomeLightReliefIt'sNotYourFather'sIBM
Chapter6.Static,Final,andEnumeratedTypes
WhatFieldModifierstaticMeans
WhatFieldModifierfinalMeans
StatementsUpdatedforEnumerations
SomeLightReliefTheHauntedZenGardenofApple
WhyEnumerateaType?
MoreComplicatedEnumeratedTypes
Chapter7.Names,Operators,andAccuracy
Keywords
Names
Expressions
Operators
HowAccurateAreCalculations?
WhatHappensonOverflow?
PunctuationTerminology
Identifiers
Arrays
Associativity
WideningandNarrowingConversions
SomeLightReliefFurby'sBrainTransplant
Chapter8.MoreOOPExtendingClasses
Inheritance
Polymorphism
Exercises
TheClassWhoseNameIsClass
SomeLightReliefTheNerdDetectionSystem
Chapter9.Arrays
UnderstandingandCreatingArrays
ArraysofArrays
TheMathPackage
HaveArrayBrackets,WillTravel
SomeLightReliefThinkBig(andSmall)
Chapter10.Exceptions
Run-timeInternals:TheHeap
GarbageCollection
Exceptions
FurtherReading
Run-timeInternals:TheStack
TheAssertStatement
SomeLightReliefMakinganExceptionforYou
Chapter11.Interfaces
WhatProblemDoesanInterfaceSolve?
InterfacesVersusAbstractClasses
WhatProtectedReallyMeans
TheClassDouble
SomeLightReliefTheJava-PoweredToaster
Interfacejava.lang.Comparable
GrantingPermissionThroughanInterfaceCloneable
UsingInterfaceCallbacksforGUIEventHandlers
Exercises
Chapter12.NestedClasses
IntroductiontoNestedClasses
InnerMemberClasses
InnerAnonymousClasses
TheClassCharacter
NestedStaticClasses
InnerLocalClasses
HowInnerClassesAreCompiled
Exercises
SomeLightReliefTheDomesticObfuscatedJavaCodeNon-Competition
Part2.KeyLibraries
Chapter13.DoingSeveralThingsatOnce:Threads
WhatAreThreads?
TheLifecycleofaThread
FourKindsofThreadsProgramming
Chapter14.AdvancedThreadTopics
TwoWaystoObtainaNewThread
ThreadGroups
SomeLightReliefTheMotionSensorSolution
MutuallyExclusiveThreads
CommunicatingMutuallyExclusiveThreads
ThreadLocalStorage
AnAsideonDesignPatterns
Exercises
PipedI/OforThreads
Packagejava.util.concurrent
FurtherReading
SomeLightReliefAreYouCertifiable?IAm.
Chapter15.Explanation<Generics>
TerminologyRefresher:ParametersVersusArguments
WhatGenericCodeLooksLike
TheProblemthatGenericCodeAddresses
GenericInterfaces
BoundsRequiringaTypeParametertoImplementanInterfaceorExtenda
ParentClass
SomeLightReliefOnComputableNumberswithanApplicationtothe
Entscheidungsproblem
Part3.Server-sideJava
Chapter16.Collections
CollectionAPI
Set,HashSet,andSortedSet
WildcardParametersandGenericMethods
GenericMethods
Map,HashMap,andTreeMap
SomeLightReliefEarlyNamesforJava
List,LinkedList,andArrayList
TheCollectionsHelperClass
WildcardingaGenericParameter
SummaryofCollection
Exercises
Chapter17.SimpleInputOutput
GettingtoKnowJavaI/O
TheClassjava.io.File
Output
Input
InputtingASCIICharactersandBinaryValues
FurtherReading
SomeLightReliefTheIllegalPrimeNumber!
DesignPhilosophy
KeyboardI/O
WrappingAdditionalOutputClasses
ReaderWrappers
InputStreamWrappers
Exercises
Chapter18.AdvancedInputOutput
RandomAccessFile
RunningCommandsandGettingOutputFromThem
FormattedStringOutput
WritingObjectstoDisk
NewI/OPackage
FileLocking
Exercises
MemoryMappedI/O
CharsetsandEndian-ness
SomeLightReliefTheIllegalT-shirt!
Part4.ClientJava
Chapter19.RegularExpressions
RegularExpressionsAndPatternMatching
CalendarUtilities
FurtherReading
SomeLightReliefExchangingApplesAndCrays
OtherUtilityClasses
Exercises
Chapter20.GUIBasicsandEventHandling
AllAboutEventHandling
SummaryofEventHandling
SomeLightReliefTheMouseThatRoared
TipsforSlimmingDownHandlerCode
Exercises
Chapter21.JFCandtheSwingPackage
JavaFoundationClasses
SwingThreadsACaution!
MoreAboutSwingComponents
Exercises
AllAboutControls(JComponents)
SwingComponents
FurtherReading
SomeLightReliefTheBibleCode
Chapter22.Containers,Layouts,andAWTLooseEnds
PluggableLookandFeel
AllAboutContainers
TyinguptheLooseEnds
SomeLightReliefSkyViewCafe:AHighQualityApplet
LayoutinaContainer
Exercises
Part5.EnterpriseJava
Chapter23.RelationalDatabasesandSQL
IntroductiontoRelationalDatabases
PrimaryandForeignKeys
NormalForms
DownloadandInstallMckoi
CreatingandPopulatingTables
SubquerySelections
UpdatingValues
SQLPreparedStatementsandStoredProcedures
SomeLightReliefReadingtheDocs
Relationships
RelationalDatabaseGlossary
BasicSQLPrimer
QueryingandRetrievingData
ResultSetofaSELECTQuery
DeletingRecordsandTables
Exercises
Chapter24.JDBC
IntroductiontoJDBC
RunningtheExampleCode
ExecutingSQLStatements
BatchingSQLStatementsandTransactions
CompleteExample
FurtherReading
HeavyLightReliefInWhich"I"SpamMyself
InstallingtheMckoiDatabaseSoftware
ConnectingtotheDatabase
ResultSets
PreparedStatementsandStoredProcedures
DatabaseandResultSetMetadata
Exercises
Chapter25.NetworkinginJava
EverythingYouNeedToKnowaboutTCP/IPbutFailedtoLearninKindergarten
SendingEmailbyJava
AClientSocketinJava
AServerSocketinJava
HTTPandWebBrowsing:RetrievingHTTPPages
AMultithreadedHTTPServer
AMappedI/OHTTPServer
FurtherReading
Exercises
SomeLightRelief500MileLimitonEmail
Chapter26.ServletsandJSP
OverviewofServletsandJSP
WhyUseServlets?
InstallingtheTomcatSoftware
PortsandProtocols
AServletandItsRequest/Response
ResponsetoaServletRequest
ServletOperatingCycleandThreading
JavaBeansinServletsandJSP
FurtherReading
SomeLightReliefUsingJavatoStuffanOnlinePoll
ReleasesandVersions
RunningtheExampleServlets
TheHTMLtoInvokeaServlet
ServletRequest
WritingYourOwnServlet
JavaServerPages
LastWordsonJSP,Beans,andTagLibraries
Exercises
Chapter27.XMLandJava
XMLVersusHTML
TheDocumentTypeDefinition(DTD)
XMLVersionsandGlossary
ReadingXMLWithDOMParsers
ReadinganXMLFileSAXParsers
TheFactoryDesignPattern
SomeRulesofXML
WhatIsXMLUsedFor?
JAXPLibraryContents
AProgramThatUsesaDOMParser
AProgramThatUsesaSAXParser
DesignPatternSummary
OtherJavaXMLNotes
FurtherReading
Exercises
SomeLightReliefViewSourceonKevin'sLife
Chapter28.WebServicesatGoogleandAmazon
WebServicesIntroduction
AmazonWebServices
Conclusions
GoogleWebServices
SomeLightReliefGooglewhacking
AppendixA.DownloadingJava
AppendixB.PowersofTwoTable
Nowit'sHelloWorld
AppendixC.Codesets
Index
Copyright
©2004SunMicrosystems,Inc.
PrintedintheUnitedStatesofAmerica.
4150NetworkCircle,SantaClara,California
95054U.S.A.
LibraryofCongressControlNumber:2004107483
Allrightsreserved.Thisproductandrelateddocumentationare
protectedbycopyrightanddistributedunderlicensesrestricting
itsuse,copying,distribution,anddecompilation.Nopartofthis
productorrelateddocumentationmaybereproducedinany
formbyanymeanswithoutpriorwrittenauthorizationofSun
anditslicensors,ifany.
RESTRICTEDRIGHTSLEGEND:Use,duplication,ordisclosure
bytheUnitedStatesGovernmentissubjecttotherestrictions
setforthinDFARS252.227-7013(c)(1)(ii)andFAR52.227-19.
TheproductsdescribedmaybeprotectedbyoneormoreU.S.
patents,foreignpatents,orpendingapplications.
TRADEMARKSHotJava,Java,JavaDevelopmentKit,J2EE,JPS,
JavaServerPages,EnterpriseJavaBeans,EJB,JDBC,J2SE,
Solaris,SPARC,SunOS,andSunsoftaretrademarksofSun
Microsystems,Inc.Allotherproductsorservicesmentionedin
thisbookarethetrademarksorservicemarksoftheir
respectivecompaniesororganizations.
PrenticeHallPTRoffersexcellentdiscountsonthisbook
whenorderedinquantityforbulkpurchasesorspecial
sales.Formoreinformation,pleasecontactU.S.
CorporateandGovernmentSales,1-800-382-3419,
Forsalesoutsideofthe
U.S.,pleasecontactInternationalSales,1-317-5813793,
AcquisitionsEditor:GregoryG.Doench
EditorialAssistant:RaquelKaplan
ProductionSupervision:JulieB.Nahil
Editor:SolveigHaugland
CoverDesigner:NinaScuderi
ArtDirector:GailCocker-Bogusz
ManufacturingManager:CarolMelville
MarketingManager:ChrisGuzikowski
SunMicrosystemsPressPublisher:MyrnaRivera
Textprintedonrecycledpaper
12345678910CRW0807060504
Firstprinting,June2004
Dedication
Iusedtodedicatethesebookstospecificbrandsofrealale;it
wasalwaysgoodforlunchwiththechairmanwhenItouredthe
brewery.Here'ssomethingdifferent.I'veworkedinthe
computerindustryallmylife,andinthelastfewyearsstarted
teachingprogrammingclassestoo.Youlearnalotwhenyouget
immediatefeedbackabouttopicsthatneedtobeexpressedin
easierpieces.Iwouldliketodedicatethisbooktoallmy
studentspastandpresent,andallmyteachers,youngandold.
Preface
ThefirsteditionofJustJavawasoneoftheearliestbooksto
accompanytheoriginalreleaseofJavain1996.Thelaunchof
Javacoincidedwiththeexplosionofinterestinthewebandthe
netwhich,inturn,drovetechnologyforwardatafranticpace.
Peopletalkedabout"Internettime,"whichmeantthreethings
tomeinSiliconValley:therewasimmensepressuretorapidly
createnewhardwareandsoftwareproducts;everyonewrote
softwaretodisplaystockpricesontheirdesktopsandcell
phones;youwereforgivenfornotshoweringifyoufellasleep
atyourdeskaftermidnightandwokeuptherethenext
morning.Timeshavechanged,butsoftwareproductivity
remainsabigreasonbehindJava'spopularity.
OverthelasteightyearsJavahashadsixmajorreleases,
averagingoneaboutevery18months.Witheachofthese
releases,therehasbeenaneweditionofJustJavatodescribe
andexplainthetechnology.Table1showshowthelanguage
andlibrarieshaveimproved.
Table1.JavachangesfromJDK1.0.2toJava2v1.4
Release
Date
SeeJustJava6th
ed.
Content
JDK1.0.2
Jan1996
Firstgeneralreleaseof Throughoutthebook
thelanguageand
libraries
JDK1.1
Feb1997
Languagechanges:
Instanceinitializers
Chapter5
Arrayinitializers
Chapter9
Nestedclasses
Chapter12
Librarychanges:
JDK1.2
(rebadgedto
Java2)
Dec1998
Delegationbased
event-handlers
Chapter20
I/OReadersand
Writers
Chapter17
Objectserialization
Chapter18
Languagechanges:
strictfp
Chapter7
Weakreferences
Chapter10
Librarychanges:
JavaFoundationand
Swing
Chapter21
Collectionclasses,
JDBCenhancements
Chapter16,23-24
Threadlocalstorage
Chapter14
Throughoutthebook
Java2v1.3
May2000
Performanceandbug
fixes,nosignificant
changes
Java2v1.4
Dec2001
Languagechanges:
Assertstatement
Librarychanges:
Chapter10
Regularexpressions
Chapter19
NewI/O(third
attempt)
Chapter18
Thisisaremarkablepaceofdevelopmentforaprogramming
system,particularlywhenSunkeepssuchanemphasison
backwardcompatibilityandportability.TheJava1.2releasewas
asignificantone,bundlingmajorfunctionalityimprovements
likethecollectionclassesandtheSwingGUIlibrary.Java1.3
and1.4werecomparativelysmaller,although1.4didbringa
newstatement("assert")intothelanguage.
Twoandahalfyearsinthemaking,Java1.5isthebiggest
versionyet.ItisbiggerandmoresignificantthanJDK1.2.Sun
willprobablyrenameJava1.5tosomeawkwardandconfusing
nameusingtwosetsofnumbers,like"Java2Mega-editionv1.5
fab-o-lux".Whatevertheycallit,thinkofJava1.5as"Java3".
Table2showssomeofthesubstantiallanguageadditions.
Table2.Java2v1.5
Release
Java2
Date
Content
Jun2004 Languagechanges:
SeeJustJava6thed.
v1.5
Autoboxingandunboxing
Chapter3
Enumtypes
Chapter6
Generictypes
Chapter15,16
Variable-aritymethods
Chapter5
Staticimport
Chapter6
Enhancedforloop
Chapter4
Covariantreturntypes
Chapter11
Librarychanges:
printf(likeC'sprintf)
Chapter17
java.util.scanner(fourth
attemptatfixingI/O)
Chapter17
java.util.concurrentthread
utilities
Chapter14
javax.xmlXMLsupport
bundled
Chapter27,28
Classdatasharing
Chapter2
CanaddSwingcomponents Chapter21
directlytoaContainer!
Therearealsothetraditionalbug-fix,libraryandperformance
improvements,includingsomeexcitingoptimizationsfor
desktopapplications.
Overtheyears,I'veputalotofhardworkintounlockingthe
changesinJava,soyoudon'thaveto.You'relookingatthe
resultsofthateffort:thesixtheditionofJustJava.
I'mconfidentyou'llfinditeasytoread,andpackedwiththe
informationyouneed.
Ihopethatyou'llwantacopyforyourself.
Butifnot,Iwantyoutoputitbackontheshelf,only(asmy
friendAlanAbelsuggested)inamoreprominentposition.
P.
Acknowledgments
I'mverygratefultothefollowingpeople,whoaresomeofthe
mosttalentedandcreativeindividualsyou'llfind:
GiladBracha
MichaelDavidson
JaneErskine
MarcusGreen
RoedyGreen
TreyHarris
KarstenLentzsch
BobLynch
AleksanderMalinowski
SimonRoberts
RickRoss,whoprovidesfirst-classleadershipat
KerryShetline
RobinSouthgate
LeftyWalkowiak
AllthecowboysandcowgirlsdownontheJavaRanch
TheLimewireteam
TheunsungheroesandheroinesofSun'sJavaandSolaris
groups
Theeditorial,marketing,andproductionteamsatPrentice-Hall
andSunMicrosystemsdeservefullappreciation:
GregDoench,ChrisGuzikowski,JulieNahil,RaquelKaplan,Nina
Scuderi,andSolveigHauglandandhermagiceditingpixies.
Thankstoo,tomywife,family,andfriendshey,ifIwantedmy
studytolookorganized,I'dkeepitthatway,OK?
Part1:Language
Chapter1.WhatCanJavaDoforMe?
Chapter2.IntroducingObjects
Chapter3.PrimitiveTypes,Wrappers,andBoxing
Chapter4.StatementsandComments
Chapter5.OOPPartIIConstructorsandVisibility
Chapter6.Static,Final,andEnumeratedTypes
Chapter7.Names,Operators,andAccuracy
Chapter8.MoreOOPExtendingClasses
Chapter9.Arrays
Chapter10.Exceptions
Chapter11.Interfaces
Chapter12.NestedClasses
Chapter1.WhatCanJavaDoforMe?
WhatJavaDoesforYou
WhyPortabilityMatters
LanguageandLibraries
OneSizeDoesn'tFitAll
SomeLightReliefAJavaDesktopApplication
Javahasbecomeaverypopularprogramminglanguageforthe
kindofmodernsoftwarepeoplewanttowrite.Javabeganasa
researchprojectinsideSunMicrosystems.Theresultswere
postedontheweb,andJavatookofflikeaTitanrocket.Sun
wiselydecidedtonurturethemarketbysharing,andlicensed
thetechnologyacrossthecomputerindustry.Today,Java
compilersandsourcecodeareavailableforfreedownloadfrom
manydifferentorganizations.Justabouttheentirecomputer
industryisbackingJavaenthusiasticallywithproductsand
support.Inthischapterwe'lllookatthereasonsbehindJava's
popularity,andsummarizethekeyfeaturesofthelanguage.
Javaworkswellforwebandserver-basedapplications.Ithas
greatfeatureslikeobject-orientedprogramming,easydatabase
access,andwell-designedGUIsupport.Thelatestrelease,Java
2version1.5,hasperformancetweakstospeedupdesktop
programs.Therearelibrariesforcommunicatingacross
networks,andforencryption.Ithasstrongsecuritybuiltin.
MostprogrammerspickupJavaquickly.Behindallthis,Javais
morethanjustthelatest,mostpopularprogramminglanguage.
Itisawayofcreatingapplicationsthatareindependentofall
hardwareandalloperatingsystems.
WhatJavaDoesforYou:SoftwarePortability
Whatismeantby"applicationsthatareindependentofall
hardwareandoperatingsystems?"Itmeansyoucancompilea
Javaprogramonanysystemandruntheresultingbinary
executablefileonthesameoranyothersystemonaMacintosh,
onWindows98,NT,2K,XP,onSolaris,Linux,BSDoranyofthe
varietiesofUnix,onIBM'smainframeoperatingsystems,oncell
phones,PersonalDigitalAssistants(PDAs),embedded
processors,andevenonsmartcards(creditcardswitha
microprocessorandmemory),asshowninFigure1-1.
Figure1-1.Future-proofsoftware:YourJava
applicationrunsoneverysystem.Nomore
"requiresWindowsXP"or"LinuxPPConly",or
"compiledforMacOSXversion10.5";just"built
withJava,"andyou'redone.
[Viewfullsizeimage]
Youwillevenbeabletorunonfutureoperatingsystem
releases,likeMicrosoft'sLonghorn.Javawillbeportedtoall
futureoperatingsystemsofsignificance.It'salsoafastwayfor
newhardwaretogetsoftwareapplicationsthatwillrunonit.
JavaunlockssoftwarefrombeingcoupledtoanyspecificOS
andhardwareplatform.ThisnewflexibilityhasmadeJavavery
popularwithusers,ITdepartments,andsoftwarevendors.All
threebenefitenormouslyfromsoftwareportability.
WhyPortabilityMatters
Youmightthinkthatsoftwareportabilitydoesnotaffectyou:
yourapplicationsoftwarerunsfineonyourPCtodayandthat's
allyouuse.Andthat'strue,rightupuntilthetimeyouwantto
consideranewordifferentsystem.
Sayyou'reinthemarkettobuyanewdesktopsystem,anda
friendshowsyouthevideo-editing,music,virusresistance,and
digitalpicturecapabilitiesofhisAppleMacintosh.Youconsider
switchingtoaMac.SwitchingGUIsisano-brainerGUIsalldo
essentiallythesamethings,anditonlytakesadayortwoto
re-trainyourfingers.Theproblemistheapps.Youarefaced
withthe"choice"ofwalkingawayfromyourinvestmentinyour
existingPC-onlysoftware,orbuyingyetanotherWindowsPC
thathassomecompatibilitywithyourprevioussystem.Youcan
easilyswitchhardwarefromDelltoH-PorIBM,butthere'sa
softwarebarriertoswitchingfromWindowstosomethingwith
fewersecurityproblems,likeLinuxorMacOS.You'vebeen
lockedin.
WhenyourapplicationprogramsarewritteninJava,youcan
upgradeOSandapplicationsindependently.YoucantryLinux
andstilluseyourfamiliarapplications.Youcanmoveyour
existingJavaprogramstoanynewsystem,andcarryonusing
them.Thisiswhysoftwareportabilitymatterstohomeusers.
Forbusinesses,theproblemisworseandfarmoreexpensive.
Evenifyourwholeorganizationhasstandardizedon,say,
MicrosoftWindowsXP,therehavebeennumerousreleasesover
justthelastdecadeandabit:MS-DOS,Win3.1,Win3.11,
Win95A,Win95B,Win98,98SE,ME,NT3.1,NT3.5,NT3.51,
NT4,2K,multipleservicepacksandrequiredhot-fixes,XP,and
Longhornonthehorizon.Theseplatformshavesubtleand
differentincompatibilitiesamongthem.Evenapplications
runningonasingleplatformhavelimitedinteroperability.Older