OCA Java SE 8 Programmer I Exam Guide (Exams 1Z0 808) (Certification & Career OMG)
OCA%20Java%20SE%208%20Programmer%20I%20Exam%20Guide%20(Exams%201Z0-808)%20(Certification%20%26%20Career%20-%20OMG)
OCA%20Java%20SE%208%20Programmer%20I%20Exam%20Guide%20(Exams%201Z0-808)
OCA%201Z0-808%20SE%208%20Programmer%20I%20Exam%20Guide%20-%20%20Kathy%20Sierra
2017OCA%20Java%20SE%208%20Examination%20Guide
OCA%201Z0-808%20SE%208%20Programmer%20I%20Exam%20Guide%20Kathy%20Sierra
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 427 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Title Page
- Copyright Page
- Contents
- Acknowledgments
- Preface
- Introduction
- 1 Declarations and Access Control
- Java Refresher
- Features and Benefits of Java (OCA Objective 1.5)
- Identifiers and Keywords (OCA Objectives 1.2 and 2.1)
- Legal Identifiers
- Oracle’s Java Code Conventions
- Define Classes (OCA Objectives 1.2, 1.3, 1.4, 6.4, and 7.5)
- Exercise 1-1: Creating an Abstract Superclass and Concrete Subclass
- Use Interfaces (OCA Objective 7.5)
- Declare Class Members (OCA Objectives 2.1, 2.2, 2.3, 4.1, 4.2, 6.2, 6.3, and 6.4)
- Declare and Use enums (OCA Objective 1.2)
- Certification Summary
- Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 2 Object Orientation
- Encapsulation (OCA Objectives 6.1 and 6.5)
- Inheritance and Polymorphism (OCA Objectives 7.1 and 7.2)
- Polymorphism (OCA Objective 7.2)
- Overriding/Overloading (OCA Objectives 6.1 and 7.2)
- Casting (OCA Objectives 2.2 and 7.3)
- Implementing an Interface (OCA Objective 7.5)
- Legal Return Types (OCA Objectives 2.2 and 6.1)
- Constructors and Instantiation (OCA Objectives 6.3 and 7.4)
- Initialization Blocks (OCA Objectives 1.2 and 6.3-ish)
- Statics (OCA Objective 6.2)
- Certification Summary
- Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 3 Assignments
- Stack and Heap—Quick Review
- Literals, Assignments, and Variables (OCA Objectives 2.1, 2.2, and 2.3)
- Scope (OCA Objective 1.1)
- Variable Initialization (OCA Objectives 2.1, 4.1, and 4.2)
- Passing Variables into Methods (OCA Objective 6.6)
- Garbage Collection (OCA Objective 2.4)
- Certification Summary
- Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 4 Operators
- 5 Flow Control and Exceptions
- Using if and switch Statements (OCA Objectives 3.3 and 3.4)
- Creating Loops Constructs (OCA Objectives 5.1, 5.2, 5.3, 5.4, and 5.5)
- Handling Exceptions (OCA Objectives 8.1, 8.2, 8.3, 8.4, and 8.5)
- Catching an Exception Using try and catch
- Using finally
- Propagating Uncaught Exceptions
- Exercise 5-3: Propagating and Catching an Exception
- Defining Exceptions
- Exception Hierarchy
- Handling an Entire Class Hierarchy of Exceptions
- Exception Matching
- Exception Declaration and the Public Interface
- Exercise 5-4: Creating an Exception
- Rethrowing the Same Exception
- Common Exceptions and Errors (OCA Objective 8.5)
- Certification Summary
- Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- 6 Strings, Arrays, ArrayLists, Dates, and Lambdas
- Using String and StringBuilder (OCA Objectives 9.2 and 9.1)
- Working with Calendar Data (OCA Objective 9.3)
- Using Arrays (OCA Objectives 4.1 and 4.2)
- Using ArrayLists and Wrappers (OCA Objectives 9.4 and 2.5)
- Advanced Encapsulation (OCA Objective 6.5)
- Using Simple Lambdas (OCA Objective 9.5)
- Certification Summary
- Two-Minute Drill
- Q&A Self Test
- Self Test Answers
- A About the Download
- Index
Copyright©2017byMcGraw-HillEducation.Allrightsreserved.ExceptaspermittedundertheUnited
StatesCopyrightActof1976,nopartofthispublicationmaybereproducedordistributedinanyformor
byanymeans,orstoredinadatabaseorretrievalsystem,withoutthepriorwrittenpermissionofthe
publisher,withtheexceptionthattheprogramlistingsmaybeentered,stored,andexecutedinacomputer
system,buttheymaynotbereproducedforpublication.
ISBN:978-1-26-001138-8
MHID:1-26-001138-0.
ThematerialinthiseBookalsoappearsintheprintversionofthistitle:ISBN:978-1-26-001136-4,
MHID:1-26-001136-4.
eBookconversionbycodeMantra
Version1.0
Alltrademarksaretrademarksoftheirrespectiveowners.Ratherthanputatrademarksymbolafterevery
occurrenceofatrademarkedname,weusenamesinaneditorialfashiononly,andtothebenefitofthe
trademarkowner,withnointentionofinfringementofthetrademark.Wheresuchdesignationsappearin
thisbook,theyhavebeenprintedwithinitialcaps.
McGraw-HillEducationeBooksareavailableatspecialquantitydiscountstouseaspremiumsandsales
promotionsorforuseincorporatetrainingprograms.Tocontactarepresentative,pleasevisittheContact
Uspageatwww.mhprofessional.com.
OracleandJavaareregisteredtrademarksofOracleCorporationand/oritsaffiliates.Allother
trademarksarethepropertyoftheirrespectiveowners,andMcGraw-HillEducationmakesnoclaimof
ownershipbythementionofproductsthatcontainthesemarks.
ScreendisplaysofcopyrightedOraclesoftwareprogramshavebeenreproducedhereinwiththe
permissionofOracleCorporationand/oritsaffiliates.
OracleCorporationdoesnotmakeanyrepresentationsorwarrantiesastotheaccuracy,adequacy,or
completenessofanyinformationcontainedinthisWork,andisnotresponsibleforanyerrorsor
omissions.
TERMSOFUSE
ThisisacopyrightedworkandMcGraw-HillEducationanditslicensorsreserveallrightsinandtothe
work.Useofthisworkissubjecttotheseterms.ExceptaspermittedundertheCopyrightActof1976and
therighttostoreandretrieveonecopyofthework,youmaynotdecompile,disassemble,reverse
engineer,reproduce,modify,createderivativeworksbasedupon,transmit,distribute,disseminate,sell,
publishorsublicensetheworkoranypartofitwithoutMcGraw-HillEducation’spriorconsent.Youmay
usetheworkforyourownnoncommercialandpersonaluse;anyotheruseoftheworkisstrictly
prohibited.Yourrighttousetheworkmaybeterminatedifyoufailtocomplywiththeseterms.
THEWORKISPROVIDED“ASIS.”McGRAW-HILLEDUCATIONANDITSLICENSORSMAKE
NOGUARANTEESORWARRANTIESASTOTHEACCURACY,ADEQUACYOR
COMPLETENESSOFORRESULTSTOBEOBTAINEDFROMUSINGTHEWORK,INCLUDING
ANYINFORMATIONTHATCANBEACCESSEDTHROUGHTHEWORKVIAHYPERLINKOR
OTHERWISE,ANDEXPRESSLYDISCLAIMANYWARRANTY,EXPRESSORIMPLIED,
INCLUDINGBUTNOTLIMITEDTOIMPLIEDWARRANTIESOFMERCHANTABILITYOR
FITNESSFORAPARTICULARPURPOSE.McGraw-HillEducationanditslicensorsdonotwarrantor
guaranteethatthefunctionscontainedintheworkwillmeetyourrequirementsorthatitsoperationwillbe
uninterruptedorerrorfree.NeitherMcGraw-HillEducationnoritslicensorsshallbeliabletoyouor
anyoneelseforanyinaccuracy,errororomission,regardlessofcause,intheworkorforanydamages
resultingtherefrom.McGraw-HillEducationhasnoresponsibilityforthecontentofanyinformation
accessedthroughthework.UndernocircumstancesshallMcGraw-HillEducationand/oritslicensorsbe
liableforanyindirect,incidental,special,punitive,consequentialorsimilardamagesthatresultfromthe
useoforinabilitytousethework,evenifanyofthemhasbeenadvisedofthepossibilityofsuch
damages.Thislimitationofliabilityshallapplytoanyclaimorcausewhatsoeverwhethersuchclaimor
causearisesincontract,tortorotherwise.
CONTRIBUTORS
AbouttheAuthors
KathySierrawasaleaddeveloperfortheSCJPexamforJava5andJava6.KathyworkedasaSun
“mastertrainer,”andin1997,foundedJavaRanch.com(nownamedCoderanch.com),theworld’slargest
Javacommunitywebsite.HerbestsellingJavabookshavewonmultipleSoftwareDevelopment
Magazineawards,andsheisafoundingmemberofOracle’sJavaChampionsprogram.
Thesedays,Kathyisdevelopingadvancedtrainingprogramsinavarietyofdomains(from
horsemanshiptocomputerprogramming),butthethreadthattiesallherprojectstogetherishelping
learnersreducecognitiveload.
BertBateswasaleaddeveloperformanyofSun’sJavacertificationexams,includingtheSCJPforJava
5andJava6.BertwasalsooneoftheleaddevelopersforOracle’sOCA7andOCP7examsanda
contributoronOracle’sOCA8andOCP8exams.HeisaforummoderatoronCoderanch.com(formerly
JavaRanch.com)andhasbeendevelopingsoftwareformorethan30years(argh!).Bertistheco-authorof
severalbestsellingJavabooks,andhe’safoundingmemberofOracle’sJavaChampionsprogram.Now
thatthebookisdone,Bertplanstogowhackafewtennisballsaroundandonceagainstartridinghis
beautifulIcelandichorse,EyrrarosfraGufudal-Fremri.
AbouttheTechnicalReviewTeam
Thisisthefiftheditionofthebookthatwe’vecookedup.ThefirstversionweworkedonwasforJava2.
ThenweupdatedthebookfortheSCJP5,againfortheSCJP6,againfortheOCA7andOCP7exams,
andnowfortheOCA8.Everystepoftheway,wewereunbelievablyfortunatetohavefantastic,
JavaRanch.com-centrictechnicalreviewteamsatoursides.Overthecourseofthelast14years,we’ve
been“evolving”thebookmorethanrewritingit.ManysectionsfromouroriginalworkontheJava2
bookarestillintact.Onthefollowingpages,we’dliketoacknowledgethemembersofthevarious
technicalreviewteamswhohavesavedourbaconovertheyears.
AbouttheJava2TechnicalReviewTeam
JohannesdeJonghasbeentheleaderofourtechnicalreviewteamsforeverandever.(Hehasmore
patiencethananythreepeopleweknow.)FortheJava2book,heledourbiggestteamever.Oursincere
thanksgoouttothefollowingvolunteerswhowereknowledgeable,diligent,patient,andpicky,picky,
picky!
RobRoss,NicholasCheung,JaneGriscti,IljaPreuss,VincentBrabant,KudretSerin,BillSeipel,Jing
Yi,GinuJacobGeorge,Radiya,LuAnnMazza,AnshuMishra,AnandhiNavaneethakrishnan,Didier
Varon,MaryMcCartney,HarshaPherwani,AbhishekMisra,andSumanDas.
AbouttheSCJP5TechnicalReviewTeam
Wedon’tknowwhoburnedthemostmidnightoil,butwecan(anddid)counteverybody’sedits—soin
orderofmosteditsmade,weproudlypresentourSuperstars.
OurtophonorsgotoKristinStromberg—everytimeyouseeasemicolonusedcorrectly,tipyourhat
toKristin.NextupisBurkHufnagelwhofixedmorecodethanwecaretoadmit.BillMietelskiand
GianFrancoCasulacaughteverykindoferrorwethrewatthem—awesomejob,guys!Devender
Tharejamadesurewedidn’tusetoomuchslang,andMarkSpritzlerkeptthehumorcoming.Mikalai
ZaikinandSeemaManivannanmadegreatcatcheseverystepoftheway,andMarilyndeQueirozand
ValentinCrettazbothputinanotherstellarperformance(savingourbuttsyetagain).
MarceloOrtega,JefCumps(anotherveteran),AndrewMonkhouse,andJeroenSterkenroundedout
ourcrewofSuperstars—thankstoyouall.JimYingstwasamemberoftheSunexamcreationteam,and
hehelpeduswriteandreviewsomeofthetwistierquestionsinthebook(bwa-ha-ha-ha).
Asalways,everytimeyoureadacleanpage,thankourreviewers,andifyoudocatchanerror,it’s
mostcertainlybecauseyourauthorsmessedup.Andoh,onelastthankstoJohannes.Yourule,dude!
AbouttheSCJP6TechnicalReviewTeam
SincetheupgradetotheJava6examwaslikeasmallsurgicalstrikewedecidedthatthetechnical
reviewteamforthisupdatetothebookneededtobesimilarlyfashioned.Tothatendwehand-pickedan
elitecrewofJavaRanch’stopgurustoperformthereviewfortheJava6exam.
OurendlessgratitudegoestoMikalaiZaikin.MikalaiplayedahugeroleintheJava5book,andhe
returnedtohelpusoutagainforthisJava6edition.WeneedtothankVolha,Anastasia,andDariafor
lettingusborrowMikalai.Hiscommentsandeditshelpedusmakehugeimprovementstothebook.
Thanks,Mikalai!
MarcPeabodygetsspecialkudosforhelpingusoutonadoubleheader!Inadditiontohelpinguswith
Sun’snewSCWCDexam,Marcpitchedinwithagreatsetofeditsforthisbook—yousavedourbacon
thiswinter,Marc!(BTW,wedidn’tlearnuntillateinthegamethatMarc,BryanBasham,andBertall
shareapassionforultimateFrisbee!)
Likeseveralofourreviewers,notonlydoesFredRosenbergervolunteercopiousamountsofhistime
moderatingatJavaRanch,healsofoundtimetohelpusoutwiththisbook.StaceyandOlivia,youhave
ourthanksforloaningusFredforawhile.
MarcWebermoderatesatsomeofJavaRanch’sbusiestforums.Marcknowshisstuffanduncovered
somereallysneakyproblemsthatwereburiedinthebook.WhilewereallyappreciateMarc’shelp,we
needtowarnyoualltowatchout—he’sgotaPhaser!
Finally,wesendourthankstoChristopheVerre—ifwecanfindhim.ItappearsthatChristophe
performshisJavaRanchmoderationdutiesfromvariouslocationsaroundtheglobe,includingFrance,
Wales,andmostrecentlyTokyo.OnmorethanoneoccasionChristopheprotectedusfromourownlackof
organization.Thanksforyourpatience,Christophe!It’simportanttoknowthattheseguysalldonatedtheir
reviewerhonorariumstoJavaRanch!TheJavaRanchcommunityisinyourdebt.
TheOCA7andOCP7Team
ContributingAuthors
TheOCA7examisprimarilyausefulrepackagingofsomeoftheobjectivesfromtheSCJP6exam.On
theotherhand,theOCP7examintroducedavastarrayofbrand-newtopics.Weenlistedseveraltalented
JavagurustohelpuscoversomeofthenewtopicsontheOCP7exam.ThanksandkudostoTom
McGinnforhisfantasticworkincreatingthemassiveJDBCchapter.SeveralreviewerstoldusthatTom
didanamazingjobchannelingtheinformaltoneweusethroughoutthebook.Next,thankstoJeanne
Boyarsky.Jeannewastrulyarenaissancewomanonthisproject.ShecontributedtoseveralOCP
chapters;shewrotesomequestionsforthemasterexams;sheperformedsomeprojectmanagement
activities;andasifthatwasn’tenough,shewasoneofourmostenergetictechnicalreviewers.Jeanne,we
can’tthankyouenough.OurthanksgotoMattHeimerforhisexcellentworkontheConcurrentchapter.
Areallytoughtopicnicelyhandled!Finally,RoelDeNijsandRobertoPerillomadesomenice
contributionstothebookandhelpedoutonthetechnicalreviewteam—thanks,guys!
TechnicalReviewTeam
Roel,whatcanwesay?Yourworkasatechnicalreviewerisunparalleled.Roelcaughtsomany
technicalerrors,itmadeourheadsspin.BetweentheprintedbookandallthematerialontheCD,we
estimatethatthereareover1,500pagesof“stuff”here.It’shuge!Roelgrindedthroughpageafterpage,
neverlosthisfocus,andmadethisbookbetterincountlessways.Thankyou,Roel!
Inadditiontoherothercontributions,Jeanneprovidedoneofthemostthoroughtechnicalreviewswe
received.(Wethinksheenlistedherteamofkillerrobotstohelpher!)
ItseemslikenoK&BbookwouldbecompletewithouthelpfromouroldfriendMikalaiZaikin.
Somehow,betweenearning812differentJavacertifications,beingahusbandandfather(thankstoVolha,
Anastasia,Daria,andIvan),andbeinga“theoreticalfisherman”[sic],Mikalaimadesubstantial
contributionstothequalityofthebook;we’rehonoredthatyouhelpedusagain,Mikalai.
Nextup,we’dliketothankVijithaKumara,JavaRanchmoderatorandtechreviewerextraordinaire.
Wehadmanyreviewershelpoutduringthelongcourseofwritingthisbook,butVijithawasoneofthe
fewwhostuckwithusfromChapter1allthewaythroughthemasterexamsandontoChapter15.Vijitha,
thankyouforyourhelpandpersistence!
Finally,thankstotherestofourreviewteam:RobertoPerillo(whoalsowrotesomekillerexam
questions),JimYingst(wasthisyourfourthtime?),otherrepeatoffenders:FredRosenberger,
ChristopheVerre,DevakaCooray,MarcPeabody,andnewcomerAmitGhorpade—thanks,guys!
AbouttheOCA8TechnicalReviewTeam
Dueto“piloterror”onyourauthors’part,themembersofthereviewteamforthisbookwereaskedto
workunderatighter-than-idealschedule.Weoweahugethankstooursixreviewersforthisbook,who
leapttoactiononshortnoticeandonceagainmadenumerousfinecontributionstothequalityofthebook.
Ashasbecome“thenorm,”allourreviewersaremoderatorsatthefinestJavacommunitywebsiteinthe
wholeuniverse,Coderanch.com.
OurfirstmentiongoestoCampbellRitchie,long-timeCoderanchmoderator,hikerofsteephills,and,
byourcount,mostprolificreviewerforthisedition.Inotherwords,Campbellfoundthemosterrors.
Amongotherpursuits,Campbellisanexpertinbothpathologyandprogramming,because…whynot?
Everytimeyoureadanerror-freepage,thinkofCampbellandthankhim.
Inavirtualtieforsecondplaceinthe“errorsfound”competition,wepresentPawełBaczyńskiand
FritzWalraven.PawełcallsPolandhishomeandismostproudofhiswife,Ania,andkids,Szymekand
Gabrysia.Heisalmostasproudofthefactthatwehavetouseaspecialkeyboardtospellhisname
correctly!
FritzhailsfromtheNetherlands,andifweunderstandcorrectly,cheershiskidsastheydemonstrate
theirathleticprowessinvarioussportsvenuesaroundAmersfoort.Fritzhasalsovolunteeredatan
orphanageinUganda(wehopeheteachesthosekidsJava!).Fritz,ifweevermeetinperson,Berthereby
challengesyoutoatabletennismatch.
We’dliketogiveaspecialshoutouttoFritzandPawelforstickingwithusfromChapter1alltheway
throughtothesecondpracticeexam.Itwasamarathon,andwethankyouboth.
Next,we’dliketothankreturningreviewerVijithaKumara.That’sright,he’shelpedusbeforeand
yethevolunteeredagain—wow!WhenVijithaisn’ttravelingorhiking,heenjoyswhathereferstoas
“crazyexperiments.”Weloveyou,Vijitha—don’tblowyourselfup!
TimCookewastherewhenweneededhim,atthebeginningoftheprocessandagaintohelpuswrap
thingsup.WelikeTimeventhoughhe’sbeenknowntospendtimewithnefarious“functional
programmers.”(Wesuspectthat’swherehewaswhenhewentmissingforafewofthemiddle-of-the-
bookchapters.)TimlivesinIrelandandstartedprogrammingatanearlyageonanAmstradCPC464.
Nice!
Finally,aspecialthankstoanotherveteranofthetechnicalreviewteam,RobertoPerillo.Thanksfor
comingbacktohelpusagainRoberto.Robertoisafamilymanwholovesspendingtimewithhisson,
Lorenzo.OnceLorenzohasgonetobed,RobertoisknowntoplayabitofguitarorcheerfortheSao
Paulo“FutebolClube”(wethinkthisisasoccerteam).
Youguysareallawesome.Thanksforyourwonderfulassistance.
ForAndi
ForBob
CONTENTS
Acknowledgments
Preface
Introduction
1DeclarationsandAccessControl
JavaRefresher
FeaturesandBenefitsofJava(OCAObjective1.5)
IdentifiersandKeywords(OCAObjectives1.2and2.1)
LegalIdentifiers
Oracle’sJavaCodeConventions
DefineClasses(OCAObjectives1.2,1.3,1.4,6.4,and7.5)
SourceFileDeclarationRules
UsingthejavacandjavaCommands
Usingpublicstaticvoidmain(String[]args)
ImportStatementsandtheJavaAPI
StaticImportStatements
ClassDeclarationsandModifiers
Exercise1-1:CreatinganAbstractSuperclassandConcreteSubclass
UseInterfaces(OCAObjective7.5)
DeclaringanInterface
DeclaringInterfaceConstants
DeclaringdefaultInterfaceMethods
DeclaringstaticInterfaceMethods
DeclareClassMembers(OCAObjectives2.1,2.2,2.3,4.1,4.2,6.2,6.3,and6.4)
AccessModifiers
NonaccessMemberModifiers
ConstructorDeclarations
VariableDeclarations
DeclareandUseenums(OCAObjective1.2)
Declaringenums
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
2ObjectOrientation
Encapsulation(OCAObjectives6.1and6.5)
InheritanceandPolymorphism(OCAObjectives7.1and7.2)
TheEvolutionofInheritance
IS-AandHAS-ARelationships
Polymorphism(OCAObjective7.2)
Overriding/Overloading(OCAObjectives6.1and7.2)
OverriddenMethods
OverloadedMethods
Casting(OCAObjectives2.2and7.3)
ImplementinganInterface(OCAObjective7.5)
Java8—NowwithMultipleInheritance!
LegalReturnTypes(OCAObjectives2.2and6.1)
ReturnTypeDeclarations
ReturningaValue
ConstructorsandInstantiation(OCAObjectives6.3and7.4)
ConstructorBasics
ConstructorChaining
RulesforConstructors
DetermineWhetheraDefaultConstructorWillBeCreated
OverloadedConstructors
InitializationBlocks(OCAObjectives1.2and6.3-ish)
Statics(OCAObjective6.2)
StaticVariablesandMethods
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
3Assignments
StackandHeap—QuickReview
Literals,Assignments,andVariables(OCAObjectives2.1,2.2,and2.3)
LiteralValuesforAllPrimitiveTypes
AssignmentOperators
Exercise3-1:CastingPrimitives
Scope(OCAObjective1.1)
VariableScope
VariableInitialization(OCAObjectives2.1,4.1,and4.2)
UsingaVariableorArrayElementThatIsUninitializedandUnassigned
Local(Stack,Automatic)PrimitivesandObjects
PassingVariablesintoMethods(OCAObjective6.6)
PassingObjectReferenceVariables
DoesJavaUsePass-By-ValueSemantics?
PassingPrimitiveVariables
GarbageCollection(OCAObjective2.4)
OverviewofMemoryManagementandGarbageCollection
OverviewofJava’sGarbageCollector
WritingCodeThatExplicitlyMakesObjectsEligibleforCollection
Exercise3-2:GarbageCollectionExperiment
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
4Operators
JavaOperators(OCAObjectives3.1,3.2,and3.3)
AssignmentOperators
RelationalOperators
instanceofComparison
ArithmeticOperators
ConditionalOperator
LogicalOperators
OperatorPrecedence
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
5FlowControlandExceptions
UsingifandswitchStatements(OCAObjectives3.3and3.4)
if-elseBranching
switchStatements
Exercise5-1:Creatingaswitch-caseStatement
CreatingLoopsConstructs(OCAObjectives5.1,5.2,5.3,5.4,and5.5)
UsingwhileLoops
UsingdoLoops
UsingforLoops
Usingbreakandcontinue
UnlabeledStatements
LabeledStatements
Exercise5-2:CreatingaLabeledwhileLoop
HandlingExceptions(OCAObjectives8.1,8.2,8.3,8.4,and8.5)
CatchinganExceptionUsingtryandcatch
Usingfinally
PropagatingUncaughtExceptions
Exercise5-3:PropagatingandCatchinganException
DefiningExceptions
ExceptionHierarchy
HandlinganEntireClassHierarchyofExceptions
ExceptionMatching
ExceptionDeclarationandthePublicInterface
Exercise5-4:CreatinganException
RethrowingtheSameException
CommonExceptionsandErrors(OCAObjective8.5)
WhereExceptionsComeFrom
JVM-ThrownExceptions
ProgrammaticallyThrownExceptions
ASummaryoftheExam’sExceptionsandErrors
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
6Strings,Arrays,ArrayLists,Dates,andLambdas
UsingStringandStringBuilder(OCAObjectives9.2and9.1)
TheStringClass
ImportantFactsAboutStringsandMemory
ImportantMethodsintheStringClass
TheStringBuilderClass
ImportantMethodsintheStringBuilderClass
WorkingwithCalendarData(OCAObjective9.3)
Immutability
FactoryClasses
UsingandManipulatingDatesandTimes
FormattingDatesandTimes
UsingArrays(OCAObjectives4.1and4.2)
DeclaringanArray
ConstructinganArray
InitializinganArray
UsingArrayListsandWrappers(OCAObjectives9.4and2.5)
WhentoUseArrayLists
ArrayListMethodsinAction
ImportantMethodsintheArrayListClass
AutoboxingwithArrayLists
TheJava7“Diamond”Syntax
AdvancedEncapsulation(OCAObjective6.5)
EncapsulationforReferenceVariables
UsingSimpleLambdas(OCAObjective9.5)
CertificationSummary
Two-MinuteDrill
Q&ASelfTest
SelfTestAnswers
AAbouttheDownload
SystemRequirements
DownloadingfromMcGraw-HillProfessional’sMediaCenter
InstallingthePracticeExamSoftware
RunningthePracticeExamSoftware
PracticeExamSoftwareFeatures
RemovingInstallation
Help
TechnicalSupport
Windows8Troubleshooting
McGraw-HillEducationContentSupport
Index
K
ACKNOWLEDGMENTS
athyandBertwouldliketothankthefollowingpeople:
Alltheincrediblyhard-workingfolksatMcGraw-HillEducation:TimGreen(who’s
beenputtingupwithusfor14yearsnow),LisaMcClain,andLeeAnnPickrell.Thanksforallyour
helpandforbeingsoresponsive,patient,flexible,andprofessional,andthenicestgroupofpeople
wecouldhopetoworkwith.
AllourfriendsatKraftur(andourotherhorse-relatedfriends)and,mostespecially,toSherry,
Steinar,Stinaandthegirls,Kacie,DJ,Jec,LeslieandDavid,AnnetteandBruce,Lucy,Cait,and
Jennifer,Gabrielle,andMary.ThankstoPedroandEly.
Someofthesoftwareprofessionalsandfriendswhohelpedusintheearlydays:TomBender,
PeterLoerincs,CraigMatthews,LeonardCoyne,MorganPorter,andMikeKavenaugh.
DaveGustafsonforhiscontinuedsupport,insights,andcoaching.
OurwonderfulcontactandfriendatOracle,YvonnePrefontaine.
Ourgreatfriendsandgurus:SimonRoberts,BryanBasham,andKathyCollina.
Stu,Steve,Burt,andMarcHedlundforinjectingsomefunintotheprocess.
ToEdenandSkyler,forbeinghorrifiedthatadults—outofschool—wouldstudythishardfor
anexam.
TotheCoderanchTrailBoss,PaulWheaton,forrunningthebestJavacommunitysiteonthe
Web,andtoallthegenerousandpatientJavaRanch,er,Coderanchmoderators.
ToallthepastandpresentJavainstructorsforhelpingtomakelearningJavaafunexperience,
including(tonameonlyafew)AlanPetersen,JeanTordella,GeorgiannaMeagher,Anthony
Orapallo,JacquelineJones,JamesCubeta,TeriCubeta,RobWeingruber,JohnNyquist,Asok
Perumainar,SteveStelting,KimberlyBobrow,KeithRatliff,andthemostcaringandinspiringJava
guyontheplanet,JariPaukku.
Ourfurryandfeatheredfriends:Eyra,Kara,Draumur,Vafi,Boi,Niki,andBokeh.
Finally,toEricFreemanandBethRobsonforyourcontinuedinspiration.
T
PREFACE
hisbook’sprimaryobjectiveistohelpyouprepareforandpassOracle’sOCAJavaSE8
ProgrammerIcertificationexam.
Thisbookfollowscloselyboththebreadthandthedepthoftherealexams.Forinstance,
afterreadingthisbook,youprobablywon’temergeasanOOguru,butifyoustudythematerialanddo
wellontheSelfTests,you’llhaveabasicunderstandingofOO,andyou’lldowellontheexam.After
completingthisbook,youshouldfeelconfidentthatyouhavethoroughlyreviewedalltheobjectivesthat
Oraclehasestablishedfortheseexams.
InThisBook
ThisbookisorganizedintosixchapterstooptimizeyourlearningofthetopicscoveredbytheOCA8
exam.Wheneverpossible,we’veorganizedthechapterstoparalleltheOracleobjectives,butsometimes
we’llmixupobjectivesorpartiallyrepeatthemtopresenttopicsinanorderbettersuitedtolearningthe
material.
InEveryChapter
We’vecreatedasetofchaptercomponentsthatcallyourattentiontoimportantitems,reinforceimportant
points,andprovidehelpfulexam-takinghints.Takealookatwhatyou’llfindineverychapter:
EverychapterbeginswiththeCertificationObjectives—whatyouneedtoknowin
ordertopassthesectionontheexamdealingwiththechaptertopic.TheCertification
Objectiveheadingsidentifytheobjectiveswithinthechapter,soyou’llalwaysknowan
objectivewhenyouseeit!
ExamWatchnotescallattentiontoinformationabout,andpotentialpitfallsin,theexam.
Becausewewereontheteamthatcreatedtheseexams,weknowwhatyou’reabouttogo
through!
OntheJobcalloutsdiscusspracticalaspectsofcertificationtopicsthatmightnot
occurontheexam,butthatwillbeusefulintherealworld.
Exercisesareinterspersedthroughoutthechapters.Theyhelpyoumasterskillsthat
arelikelytobeanareaoffocusontheexam.Don’tjustreadthroughtheexercises;theyare
hands-onpracticethatyoushouldbecomfortablecompleting.Learningbydoingisan
effectivewaytoincreaseyourcompetencywithaproduct.
FromtheClassroomsidebarsdescribetheissuesthatcomeupmostofteninthe
trainingclassroomsetting.Thesesidebarsgiveyouavaluableperspectiveinto
certification-andproduct-relatedtopics.Theypointoutcommonmistakesandaddress
questionsthathavearisenfromclassroomdiscussions.
TheCertificationSummaryisasuccinctreviewofthechapterandarestatementof
salientpointsregardingtheexam.
TheTwo-MinuteDrillattheendofeverychapterisachecklistofthemainpoints
ofthechapter.Itcanbeusedforlast-minutereview.
Q&A TheSelfTestoffersquestionssimilartothosefoundonthecertificationexam,including
multiplechoiceandpseudodrag-and-dropquestions.Theanswerstothesequestions,as
wellasexplanationsoftheanswers,canbefoundattheendofeverychapter.Bytakingthe
SelfTestaftercompletingeachchapter,you’llreinforcewhatyou’velearnedfromthat
chapter,whilebecomingfamiliarwiththestructureoftheexamquestions.
INTRODUCTION
Organization
Thisbookisorganizedinsuchawayastoserveasanin-depthreviewfortheOCA8exam,forboth
experiencedJavaprofessionalsandthoseintheearlystagesofexperiencewithJavatechnologies.Each
chaptercoversatleastonemajoraspectoftheexam,withanemphasisonthe“why”aswellasthe“how
to”ofprogrammingintheJavalanguage.
Practiceexamsoftwarewithtwo80-questionexamsisavailablefordownload.
WhatThisBookIsNot
Youwillnotfindabeginner’sguidetolearningJavainthisbook.All500+pagesofthisbookare
dedicatedsolelytohelpingyoupasstheexam.IfyouarebrandnewtoJava,wesuggestyouspendalittle
timelearningthebasics.Youshouldnotstartwiththisbookuntilyouknowhowtowrite,compile,and
runsimpleJavaprograms.Wedonot,however,assumeanylevelofpriorknowledgeoftheindividual
topicscovered.Inotherwords,foranygiventopic(drivenexclusivelybytheactualexamobjectives),we
startwiththeassumptionthatyouarenewtothattopic.Soweassumeyou’renewtotheindividualtopics,
butweassumethatyouarenotnewtoJava.
Wealsodonotpretendtobebothpreparingyoufortheexamandsimultaneouslymakingyoua
completeJavabeing.Thisisacertificationexamstudyguide,andit’sveryclearaboutitsmission.That’s
nottosaythatpreparingfortheexamwon’thelpyoubecomeabetterJavaprogrammer!Onthecontrary,
eventhemostexperiencedJavadevelopersoftenclaimthathavingtoprepareforthecertificationexam
madethemfarmoreknowledgeableandwell-roundedprogrammersthantheywouldhavebeenwithout
theexam-drivenstudying.
DigitalContent
Formoreinformationaboutthepracticeexamsoftware,pleaseseetheAppendix.
SomePointers
Onceyou’vefinishedreadingthisbook,setasidesometimetodoathoroughreview.Youmightwantto
returntothebookseveraltimesandmakeuseofallthemethodsitoffersforreviewingthematerial:
1.Re-readalltheTwo-MinuteDrills,orhavesomeonequizyou.Youalsocanusethedrillsas
awaytodoaquickcrambeforetheexam.Youmightwanttomakesomeflashcardsoutof3×5
indexcardsthathavetheTwo-MinuteDrillmaterialonthem.
2.Re-readalltheExamWatchnotes.Rememberthatthesenotesarewrittenbyauthorswho
helpedcreatetheexam.Theyknowwhatyoushouldexpect—andwhatyoushouldbeonthelookout
for.
3.Re-taketheSelfTests.Takingthetestsrightafteryou’vereadthechapterisagoodidea
becausethequestionshelpreinforcewhatyou’vejustlearned.However,it’sanevenbetterideato
gobacklateranddoallthequestionsinthebookinonesitting.Pretendthatyou’retakingthelive
exam.(WheneveryoutaketheSelfTests,markyouranswersonaseparatepieceofpaper.That
way,youcanrunthroughthequestionsasmanytimesasyouneedtountilyoufeelcomfortablewith
thematerial.)
4.Completetheexercises.Theexercisesaredesignedtocoverexamtopics,andthere’sno
betterwaytogettoknowthismaterialthanbypracticing.Besureyouunderstandwhyyouare
performingeachstepineachexercise.Ifthereissomethingyouarenotclearon,re-readthatsection
inthechapter.
5.WritelotsofJavacode.We’llrepeatthisadviceseveraltimes.Whenwewrotethisbook,we
wrotehundredsofsmallJavaprogramstohelpusdoourresearch.Wehaveheardfromhundredsof
candidateswhohavepassedtheexam,andinalmosteverycase,thecandidateswhoscored
extremelywellontheexamwrotelotsofcodeduringtheirstudies.Experimentwiththecode
samplesinthebook,createhorrendouslistsofcompilererrors—putawayyourIDE,crankupthe
commandline,andwritecode!
IntroductiontotheMaterialintheBook
TheOCA8examisconsideredoneofthehardestintheITindustry,andwecantellyoufromexperience
thatalargechunkofexamcandidatesgoesintothetestunprepared.Asprogrammers,wetendtolearn
onlywhatweneedtocompleteourcurrentproject,giventheinsanedeadlineswe’reusuallyunder.
ButthisexamattemptstoproveyourcompleteunderstandingoftheJavalanguage,notjustthepartsof
ityou’vebecomefamiliarwithinyourwork.
Experiencealonewillrarelygetyouthroughthisexamwithapassingmark,becauseeventhethings
youthinkyouknowmightworkjustalittledifferentlythanyouimagined.Itisn’tenoughtobeabletoget
yourcodetoworkcorrectly;youmustunderstandthecorefundamentalsinadeepway,andwithenough
breadthtocovervirtuallyanythingthatcouldcropupinthecourseofusingthelanguage.
WhoCaresAboutCertification?
Employersdo.Headhuntersdo.Programmersdo.Passingthisexamprovesthreeimportantthingstoa
currentorprospectiveemployer:you’resmart;youknowhowtostudyandprepareforachallengingtest;
and,mostofall,youknowtheJavalanguage.Ifanemployerhasachoicebetweenacandidatewhohas
passedtheexamandonewhohasn’t,theemployerknowsthatthecertifiedprogrammerdoesnothaveto
taketimetolearntheJavalanguage.
ButdoesitmeanthatyoucanactuallydevelopsoftwareinJava?Notnecessarily,butit’sagoodhead
start.Toreallydemonstrateyourabilitytodevelop(asopposedtojustyourknowledgeofthelanguage),
youshouldconsiderpursuingtheJavaDeveloperExam,whereyou’regivenanassignmenttobuilda
program,starttofinish,andsubmititforanassessortoevaluateandscore.
TakingtheProgrammer’sExam
Inaperfectworld,youwouldbeassessedforyourtrueknowledgeofasubject,notsimplyhowyou
respondtoaseriesoftestquestions.Butlifeisn’tperfect,anditjustisn’tpracticaltoevaluateeveryone’s
knowledgeonaone-to-onebasis.
Formostofitscertifications,Oracleevaluatescandidatesusingacomputer-basedtestingservice
operatedbyPearsonVUE.Todiscouragesimplememorization,Oracleexamspresentapotentially
differentsetofquestionstodifferentcandidates.Inthedevelopmentoftheexam,hundredsofquestions
arecompiledandrefinedusingbetatesters.Fromthislargecollection,questionsarepulledtogetherfrom
eachobjectiveandassembledintomanydifferentversionsoftheexam.
EachOracleexamhasaspecificnumberofquestions,andthetest’sdurationisdesignedtobe
generous.Thetimeremainingisalwaysdisplayedinthecornerofthetestingscreen.Iftimeexpires
duringanexam,thetestterminates,andincompleteanswersarecountedasincorrect.
Manyexperiencedtest-takersdonotgobackandchangeanswersunlesstheyhaveagood
reasontodoso.Onlychangeananswerwhenyoufeelyoumayhavemisreadormisinterpreted
thequestionthefirsttime.Nervousnessmaymakeyousecond-guesseveryanswerandtalk
yourselfoutofacorrectone.
Aftercompletingtheexam,youwillreceiveane-mailfromOracletellingyouthatyourresultsare
availableontheWeb.Asofwinter2017,yourresultscanbefoundatcertview.oracle.com.Ifyouwanta
printedcopyofyourcertificate,youmustmakeaspecificrequest.
QuestionFormat
Oracle’sJavaexamsposequestionsinmultiple-choiceformat.
Multiple-ChoiceQuestions
Inearlierversionsoftheexam,whenyouencounteredamultiple-choicequestion,youwerenottoldhow
manyanswerswerecorrect;butwitheachversionoftheexam,thequestionshavebecomemoredifficult,
sotoday,eachmultiple-choicequestiontellsyouhowmanyanswerstochoose.TheSelfTestquestionsat
theendofeachchaptercloselymatchtheformat,wording,anddifficultyoftherealexamquestions,with
twoexceptions:
Wheneverwecan,ourquestionswillnottellyouhowmanycorrectanswersexist(wewill
say“Chooseallthatapply”).Wedothistohelpyoumasterthematerial.Somesavvytest-takers
caneliminatewronganswerswhenthenumberofcorrectanswersisknown.It’salsopossible,if
youknowhowmanyanswersarecorrect,tochoosethemostplausibleanswers.Ourjobisto
toughenyouupfortherealexam!
Therealexamtypicallynumberslinesofcodeinaquestion.Sometimeswedonotnumber
linesofcode—mostlysothatwehavethespacetoaddcommentsatkeyplaces.Ontherealexam,
whenacodelistingstartswithline1,itmeansthatyou’relookingatanentiresourcefile.Ifacode
listingstartsatalinenumbergreaterthan1,thatmeansyou’relookingatapartialsourcefile.
Whenlookingatapartialsourcefile,assumethecodeyoucan’tseeiscorrect.(Forinstance,
unlessexplicitlystated,youcanassumethatapartialsourcefilewillhavethecorrectimportand
packagestatements.)
Whenyoufindyourselfstumpedansweringmultiple-choicequestions,useyourscratchpaper
(orwhiteboard)towritedownthetwoorthreeanswersyouconsiderthestrongest,then
underlinetheansweryoufeelismostlikelycorrect.Hereisanexampleofwhatyourscratch
papermightlooklikewhenyou’vegonethroughthetestonce:
21.BorC
33.AorC
Thisisextremelyhelpfulwhenyoumarkthequestionandcontinueon.Youcanthenreturnto
thequestionandimmediatelypickupyourthoughtprocesswhereyouleftoff.Usethis
techniquetoavoidhavingtore-readandrethinkquestions.Youwillalsoneedtouseyour
scratchpaperduringcomplex,text-basedscenarioquestionstocreatevisualimagestobetter
understandthequestion.Thistechniqueisespeciallyhelpfulifyouareavisuallearner.
TipsonTakingtheExam
Thenumberofquestionsandpassingpercentagesforeveryexamaresubjecttochange.Alwayscheck
withOraclebeforetakingtheexam,atwww.Oracle.com.
Youareallowedtoanswerquestionsinanyorder,andyoucangobackandcheckyouranswersafter
you’vegonethroughthetest.Therearenopenaltiesforwronganswers,soit’sbettertoatleastattemptan
answerthantonotgiveoneatall.
Agoodstrategyfortakingtheexamistogothroughonceandanswerallthequestionsthatcometoyou
quickly.Youcanthengobackanddotheothers.Answeringonequestionmightjogyourmemoryforhow
toanswerapreviousone.
Beverycarefulonthecodeexamples.Checkforsyntaxerrorsfirst:countcurlybraces,semicolons,
andparentheses,andthenmakesurethereareasmanyleftonesasrightones.Lookforcapitalization
errorsandothersuchsyntaxproblemsbeforetryingtofigureoutwhatthecodedoes.
Manyofthequestionsontheexamwillhingeonsubtletiesofsyntax.Youwillneedtohaveathorough
knowledgeoftheJavalanguageinordertosucceed.
Thisbringsustoanotherissuethatsomecandidateshavereported.Thetestingcenterissupposedto
provideyouwithsufficientwritingimplementssoyoucanworkproblemsout“onpaper.”Insomecases,
thecentershaveprovidedinadequatemarkersanddry-eraseboardsthataretoosmallandcumbersometo
useeffectively.Werecommendthatyoucallaheadandverifythatyouwillbesuppliedwithasufficiently
largewhiteboard,sufficientlyfine-tippedmarkers,andagooderaser.Whatwe’dreallyliketoencourage
isforeveryonetocomplaintoOracleandPearsonVUEandhavethemprovideactualpencilsandatleast
severalsheetsofblankpaper.
TipsonStudyingfortheExam
Firstandforemost,giveyourselfplentyoftimetostudy.Javaisacomplexprogramminglanguage,and
youcan’texpecttocramwhatyouneedtoknowintoasinglestudysession.Itisafieldbestlearnedover
time,bystudyingasubjectandthenapplyingyourknowledge.Buildyourselfastudyscheduleandstickto
it,butbereasonableaboutthepressureyouputonyourself,especiallyifyou’restudyinginadditionto
yourregulardutiesatwork.
Oneeasytechniquetouseinstudyingforcertificationexamsisthe15-minutes-per-dayeffort.Simply
studyforaminimumof15minuteseveryday.Itisasmallbutsignificantcommitment.Ifyouhaveaday
whereyoujustcan’tfocus,thengiveupat15minutes.Ifyouhaveadaywhereitflowscompletelyfor
you,studylonger.Aslongasyouhavemoreofthe“flowdays,”yourchancesofsucceedingareexcellent.
Westronglyrecommendyouuseflashcardswhenpreparingfortheprogrammer’sexams.Aflashcard
issimplya3×5or4×6indexcardwithaquestiononthefrontandtheanswerontheback.You
constructthesecardsyourselfasyougothroughachapter,capturinganytopicyouthinkmightneedmore
memorizationorpracticetime.Youcandrillyourselfwiththembyreadingthequestion,thinkingthrough
theanswer,andthenturningthecardovertoseeifyou’recorrect.Oryoucangetanotherpersontohelp
youbyholdingupthecardwiththequestionfacingyouandthenverifyingyouranswer.Mostofour
studentshavefoundthesetobetremendouslyhelpful,especiallybecausethey’resoportablethatwhile
you’reinstudymode,youcantakethemeverywhere.Bestnottousethemwhiledriving,though,exceptat
redlights.We’vetakenourseverywhere—thedoctor’soffice,restaurants,theaters,younameit.
Certificationstudygroupsareanotherexcellentresource,andyouwon’tfindalargerormorewilling
communitythanontheCoderanch.comBigMooseSalooncertificationforums.Ifyouhaveaquestion
fromthisbook,oranyothermockexamquestionyoumayhavestumbledupon,postingaquestionina
certificationforumwillgetyouananswerinnearlyallcaseswithinaday—usually,withinafewhours.
Finally,werecommendthatyouwritealotoflittleJavaprograms!Duringthecourseofwritingthis
book,wewrotehundredsofsmallprograms,andifyoulistentowhatthemostsuccessfulcandidatessay
(youknow,thoseguyswhogot98percent),theyalmostalwaysreportthattheywrotealotofcode.
SchedulingYourExam
YoucanpurchaseyourexamvoucherfromeitherOracleorPearsonVUE.VisitOracle.com(followthe
training/certificationlinks)orvisitPearsonVue.comforexamschedulingdetailsandlocationsoftest
centers.
ArrivingattheExam
Aswithanytest,you’llbetemptedtocramthenightbefore.Resistthattemptation.Youshouldknowthe
materialbythispoint,andifyou’regroggyinthemorning,youwon’trememberwhatyoustudiedanyway.
Getagoodnight’ssleep.
Arriveearlyforyourexam;itgivesyoutimetorelaxandreviewkeyfacts.Taketheopportunityto
reviewyournotes.Ifyougetburnedoutonstudying,youcanusuallystartyourexamafewminutesearly.
Wedon’trecommendarrivinglate.Yourtestcouldbecancelled,oryoumightnothaveenoughtimeto
completetheexam.
Whenyouarriveatthetestingcenter,you’llneedtoprovidecurrent,validphotoidentification.Visit
PearsonVue.comfordetailsontheIDrequirements.Theyjustwanttobesurethatyoudon’tsendyour
brilliantJavagurunext-doorneighborwhoyou’vepaidtotaketheexamforyou.
Asidefromabrainfulloffacts,youdon’tneedtobringanythingelsetotheexamroom.Infact,your
brainisaboutallyou’reallowedtotakeintotheexam!
Allthetestsareclosedbook,meaningyoudon’tgettobringanyreferencematerialswithyou.You’re
alsonotallowedtotakeanynotesoutoftheexamroom.Thetestadministratorwillprovideyouwitha
smallmarkerboard.Ifyou’reallowedto,wedorecommendthatyoubringawaterbottleorajuicebottle
(callaheadfordetailsofwhat’sallowed).Theseexamsarelongandhard,andyourbrainfunctionsmuch
betterwhenit’swellhydrated.Intermsofhydration,theidealapproachistotakefrequent,smallsips.
Youshouldalsoverifyhowmany“bio-breaks”you’llbeallowedtotakeduringtheexam!
Leaveyourphoneinthecar.Itwillonlyaddstresstothesituation,sincetheyarenotallowedinthe
examroom,andcansometimesstillbeheardiftheyringoutsideoftheroom.Purses,books,andother
materialsmustbeleftwiththeadministratorbeforeenteringtheexam.
Onceinthetestingroom,you’llbebriefedontheexamsoftware.Youmightbeaskedtocompletea
survey.Thetimeyouspendonthesurveyisnotdeductedfromyouractualtesttime—nordoyougetmore
timeifyoufilloutthesurveyquickly.Also,rememberthequestionsyougetontheexamwillnotchange
dependingonhowyouanswerthesurveyquestions.Onceyou’redonewiththesurvey,therealclock
startstickingandthefunbegins.
Thetestingsoftwareallowsyoutomoveforwardandbackwardbetweenquestions.Mostimportant,
thereisaMarkcheckboxonthescreen—thiswillprovetobeacriticaltool,asexplainedinthenext
section.
Test-TakingTechniques
Withoutaplanofattack,candidatescanbecomeoverwhelmedbytheexamorbecomesidetrackedand
runoutoftime.Forthemostpart,ifyouarecomfortablewiththematerial,theallottedtimeismorethan
enoughtocompletetheexam.Thetrickistokeepthetimefromslippingawayduringanyoneparticular
problem.
Yourobviousgoalistoanswerthequestionscorrectlyandquickly,butotherfactorscandistractyou.
Herearesometipsfortakingtheexammoreefficiently.
SizeUptheChallenge
First,takeaquickpassthroughallthequestionsintheexam.“Cherry-pick”theeasyquestions,answering
themonthespot.Brieflyreadeachquestion,noticingthetypeofquestionandthesubject.Asaguideline,
trytospendlessthan25percentofyourtestingtimeinthispass.
Thisstepletsyouassessthescopeandcomplexityoftheexam,andithelpsyoudeterminehowtopace
yourtime.Italsogivesyouanideaofwheretofindpotentialanswerstosomeofthequestions.
Sometimesthewordingofonequestionmightlendcluesorjogyourthoughtsforanotherquestion.
Ifyou’renotentirelyconfidentinyouranswertoaquestion,answeritanyway,butchecktheMarkbox
toflagitforlaterreview.Intheeventyourunoutoftime,atleastyou’veprovideda“firstguess”answer,
ratherthanleavingitblank.
Second,gobackthroughtheentiretest,usingtheinsightyougainedfromthefirstgo-through.For
example,iftheentiretestlooksdifficult,you’llknowbetterthantospendmorethanaminuteortwoon
eachquestion.Createapacingwithsmallmilestones—forexample,“Ineedtoanswer10questionsevery
15minutes.”
Atthisstage,it’sprobablyagoodideatoskippastthetime-consumingquestions,markingthemforthe
nextpass.Trytofinishthisphasebeforeyou’re50to60percentthroughthetestingtime.
Third,gobackthroughallthequestionsyoumarkedforreview,usingtheReviewMarkedbuttoninthe
questionreviewscreen.Thisstepincludestakingasecondlookatallthequestionsyouwereunsureofin
previouspasses,aswellastacklingthetime-consumingonesyoudeferreduntilnow.Chiselawayatthis
groupofquestionsuntilyou’veansweredthemall.
Ifyou’remorecomfortablewithapreviouslymarkedquestion,unmarktheReviewMarkedbutton
now.Otherwise,leaveitmarked.Workyourwaythroughthetime-consumingquestionsnow,especially
thoserequiringmanualcalculations.Unmarkthemwhenyou’resatisfiedwiththeanswer.
Bytheendofthisstep,you’veansweredeveryquestioninthetest,despitehavingreservationsabout
someofyouranswers.Ifyourunoutoftimeinthenextstep,atleastyouwon’tlosepointsforlackofan
answer.You’reingreatshapeifyoustillhave10to20percentofyourtimeremaining.
ReviewYourAnswers
Nowyou’recruising!You’veansweredallthequestions,andyou’rereadytodoaqualitycheck.Takeyet
anotherpass(yes,onemore)throughtheentiretest,brieflyre-readingeachquestionandyouranswer.
Carefullylookoverthequestionsagaintocheckfor“trick”questions.Beparticularlywaryofthose
thatincludeachoiceof“Doesnotcompile.”Bealertforlast-minuteclues.You’reprettyfamiliarwith
nearlyeveryquestionatthispoint,andyoumayfindafewcluesthatyoumissedbefore.
TheGrandFinale
Whenyou’reconfidentwithallyouranswers,finishtheexambysubmittingitforgrading.Afteryoufinish
yourexam,you’llreceiveane-mailfromOraclegivingyoualinktoapagewhereyourexamresultswill
beavailable.Asofthiswriting,youmustaskforahardcopycertificatespecificallyoronewillnotbe
senttoyou.
Retesting
Ifyoudon’tpasstheexam,don’tbediscouraged.Trytohaveagoodattitudeabouttheexperience,andget
readytotryagain.Consideryourselfalittlemoreeducated.You’llknowtheformatofthetestalittle
better,andyou’llhaveagoodideaofthedifficultylevelofthequestionsyou’llgetnexttimearound.
Ifyoubouncebackquickly,you’llprobablyrememberseveralofthequestionsyoumighthavemissed.
Thiswillhelpyoufocusyourstudyeffortsintherightarea.
Ultimately,rememberthatOraclecertificationsarevaluablebecausethey’rehardtoget.Afterall,if
anyonecouldgetone,whatvaluewouldithave?Intheend,ittakesagoodattitudeandalotofstudying,
butyoucandoit!
ObjectivesMap
W
1
DeclarationsandAccessControl
CERTIFICATIONOBJECTIVES
•JavaFeaturesandBenefits
•IdentifiersandKeywords
•javac,java,main(),andImports
•DeclareClassesandInterfaces
•DeclareClassMembers
•DeclareConstructorsandArrays
•CreatestaticClassMembers
•Useenums
Two-MinuteDrill
Q&ASelfTest
eassumethatbecauseyou’replanningonbecomingcertified,youalreadyknowthe
basicsofJava.Ifyou’recompletelynewtothelanguage,thischapter—andtherestofthe
book—willbeconfusing;sobesureyouknowatleastthebasicsofthelanguagebefore
divingintothisbook.Thatsaid,we’restartingwithabrief,high-levelrefreshertoput
youbackintheJavamood,incaseyou’vebeenawayforawhile.
JavaRefresher
AJavaprogramismostlyacollectionofobjectstalkingtootherobjectsbyinvokingeachother’s
methods.Everyobjectisofacertaintype,andthattypeisdefinedbyaclassoraninterface.MostJava
programsuseacollectionofobjectsofmanydifferenttypes.Followingisalistofafewusefultermsfor
thisobject-oriented(OO)language:
ClassAtemplatethatdescribesthekindsofstateandbehaviorthatobjectsofitstypesupport.
ObjectAtruntime,whentheJavaVirtualMachine(JVM)encountersthenewkeyword,itwill
usetheappropriateclasstomakeanobjectthatisaninstanceofthatclass.Thatobjectwillhave
itsownstateandaccesstoallofthebehaviorsdefinedbyitsclass.
State(instancevariables)Eachobject(instanceofaclass)willhaveitsownuniquesetof
instancevariablesasdefinedintheclass.Collectively,thevaluesassignedtoanobject’sinstance
variablesmakeuptheobject’sstate.
Behavior(methods)Whenaprogrammercreatesaclass,shecreatesmethodsforthatclass.
Methodsarewheretheclass’slogicisstoredandwheretherealworkgetsdone.Theyarewhere
algorithmsgetexecutedanddatagetsmanipulated.
IdentifiersandKeywords
AlltheJavacomponentswejusttalkedabout—classes,variables,andmethods—neednames.InJava,
thesenamesarecalledidentifiers,and,asyoumightexpect,therearerulesforwhatconstitutesalegal
Javaidentifier.Beyondwhat’slegal,though,Java(andOracle)programmershavecreatedconventions
fornamingmethods,variables,andclasses.
Likeallprogramminglanguages,Javahasasetofbuilt-inkeywords.Thesekeywordsmustnotbeused
asidentifiers.Laterinthischapterwe’llreviewthedetailsofthesenamingrules,conventions,andthe
Javakeywords.
Inheritance
CentraltoJavaandotherOOlanguagesistheconceptofinheritance,whichallowscodedefinedinone
classorinterfacetobereusedinotherclasses.InJava,youcandefineageneral(moreabstract)
superclassandthenextenditwithmorespecificsubclasses.Thesuperclassknowsnothingoftheclasses
thatinheritfromit,butallofthesubclassesthatinheritfromthesuperclassmustexplicitlydeclarethe
inheritancerelationship.Asubclassthatinheritsfromasuperclassisautomaticallygivenaccessible
instancevariablesandmethodsdefinedbythesuperclass,butthesubclassisalsofreetooverride
superclassmethodstodefinemorespecificbehavior.Forexample,aCarsuperclasscoulddefinegeneral
methodscommontoallautomobiles,butaFerrarisubclasscouldoverridetheaccelerate()method
thatwasalreadydefinedintheCarclass.
Interfaces
Apowerfulcompaniontoinheritanceistheuseofinterfaces.Interfacesareusuallylikea100percent
abstractsuperclassthatdefinesthemethodsasubclassmustsupport,butnothowtheymustbesupported.
Inotherwords,forexample,anAnimalinterfacemightdeclarethatallAnimalimplementationclasses
haveaneat()method,buttheAnimalinterfacedoesn’tsupplyanylogicfortheeat()method.That
meansit’suptotheclassesthatimplementtheAnimalinterfacetodefinetheactualcodeforhowthat
particularAnimaltypebehaveswhenitseat()methodisinvoked.Note:AsofJava8,interfacescan
nowincludeconcrete,inheritablemethods.WewilltalkmuchmoreaboutthiswhenwediveintoOOin
thenextchapter.
CERTIFICATIONOBJECTIVE
FeaturesandBenefitsofJava(OCAObjective1.5)
1.5CompareandcontrastthefeaturesandcomponentsofJavasuchas:platformindependence,object
orientation,encapsulation,etc.
Perhapsagreattopictostartwith,onourofficialcoverageoftheOCA8,istodiscussthevarious
benefitsthatJavaprovidestoprogrammers.Javaisnowover20yearsold(wow!)andremainsoneofthe
mostin-demandprogramminglanguagesintheworld.Somewhatconfusinglythereisasimilarlynamed
language,“JavaScript”(animplementationoftheECMAstandard),whichisalsoaverypopular
language.JavaandJavaScripthavesomeaspectsincommon,buttheyarenottobeconfused;theyare
quitedistinct.Let’slookatsomeofthebenefitsthatJavaprovidestoprogrammersandcomparethem
(whenappropriate)tosomeofJava’scompetitors.Acaveathere,manyofthesebenefitsarebasedon
extremelycomplextopics.Thesedescriptionsarebynomeansdefinitive,butthey’resufficientforthe
exam:
ObjectorientedAssoftwaresystemsgetlarger,theygetmoredifficulttotestandenhance.
Forthelastseveraldecades,object-oriented(OO)programminghasbeenthedominantsoftware
designapproachforlargesystems,becausewell-designedOOsystemsremaintestableand
enhanceable,evenastheygrowintohugeapplicationswithmillionsoflinesofcode.OOdesign
alsooffersanaturalwaytothinkabouthowthecomponentsinasystemshouldbeconstructedand
howtheyshouldinteract.Theclasses,objects,systemstate,andbehaviorsinwell-designedOO
systemsareeasytomapconceptuallytotheircounterpartsintherealworld.
EncapsulationEncapsulationisakeyconceptinOOprogramming.Encapsulationallowsa
softwarecomponenttohideitsdatafromothercomponents,protectingthedatafrombeingupdated
withoutthecomponent’sapprovalorknowledge.Javamakesencapsulationfareasiertoachieve
thaninnon-OOlanguages.
MemorymanagementUnlikesomeofitscompetitors(CandC++),Javaprovidesautomatic
memorymanagement.Inlanguagesthatdon’tprovideautomaticmemorymanagement,keepingtrack
ofmemorythroughpointersisquitecomplex.Further,trackingdownbugsrelatedtomemory
management(oftencalledmemoryleaks)isacommon,error-prone,andtime-consumingprocess.
HugelibraryJavahasanenormouslibraryofprewritten,well-tested,andwell-supported
code.ThiscodeiseasytoincludeinyourJavaapplicationsandiswelldocumentedviatheJava
API.Throughoutthisbookwewillexploresomeofthemostused(andmostuseful)membersof
Java’sstandardcorelibrary.
SecurebydesignWhencompiledJavacodeisexecuted,itrunsinsidetheJavaVirtual
Machine(JVM).TheJVMprovidesasecure“sandbox”foryourJavacodetorunin,andtheJVM
makessurethatnefariousprogrammerscannotwriteJavacodethatwillcausetroubleonother
people’smachineswhenitruns.
Writeonce,runanywhere(cross-platformexecution)Oneofthegoals(largely,butnot
perfectlyachieved)ofJavaisthatmuchoftheJavacodeyouwritecanrunonmanyplatforms,
rangingfromtinyInternet-of-Things(IoT)devices,tophones,tolaptopcomputers,tolargeservers.
Anothercommonphraseforthisabilitytorunonmanydevicesiscross-platform.
StronglytypedAstronglytypedlanguageusuallyrequirestheprogrammertoexplicitly
declarethetypesofthedataandobjectsbeingusedintheprogram.StrongtypingallowstheJava
compilertocatchmanypotentialprogrammingerrorsbeforeyourcodeevencompiles.Attheother
endofthespectrumaredynamicallytypedlanguages.Dynamicallytypedlanguagescanbeless
verbose,fastertocodeinitially,andareoftenpreferredinenvironmentswheresmallteamsand
rapidprototypingarethenorm.ButstronglytypedlanguageslikeJavacomeintotheirowninlarge
softwareshopswithmanyteamsofprogrammersandtheneedformorereliable,testable,
production-qualitycode.
MultithreadedJavaprovidesbuilt-inlanguagefeaturesandAPIsthatallowprogramstouse
manyoperating-systemprocesses(hence,many“cores”)atthesametime.Assystemsgrowto
handlemorecomputationallyintensiveproblemsandlargerdatasets,theabilitytouseallofa
computer’scoreprocessorsbecomesessential.Multithreadedprogrammingisneversimple,but
Javaprovidesarichtoolkittomakeitaseasyaspossible.
DistributedcomputingAnotherwaytotacklebigprogrammingproblemsistodistributethe
workloadacrossmanymachines.TheJavaAPIprovidesseveralwaystosimplifytasksrelatedto
distributedcomputing.Onesuchexampleisserialization,aprocessinwhichaJavaobjectis
convertedtoaportableform.Serializedobjectscanbesenttoothermachines,deserialized,and
thenusedasanormalJavaobject.
Again,we’vejustscratchedthesurfaceofthesecomplextopics,butifyouunderstandthesebrief
descriptions,youshouldbepreparedtohandleanyquestionsforthisobjective.Somuchforthetheory,
let’sgetintodetails…
CERTIFICATIONOBJECTIVE
IdentifiersandKeywords(OCAObjectives1.2and2.1)
1.2DefinethestructureofaJavaclass.
2.1Declareandinitializevariables(includingcastingofprimitivedatatypes).
RememberthatwhenwelistoneormoreCertificationObjectivesinthebook,aswejustdid,itmeans
thatthefollowingsectioncoversatleastsomepartofthatobjective.Someobjectiveswillbecoveredin
severaldifferentchapters,soyou’llseethesameobjectiveinmorethanoneplaceinthebook.For
example,thissectioncoversdeclarationsandidentifiers,butusingthethingsyoudeclareiscovered
primarilyinlaterchapters.
So,we’llstartwithJavaidentifiers.ThetwoaspectsofJavaidentifiersthatwecoverhereare
LegalidentifiersTherulesthecompilerusestodeterminewhetheranameislegal.
Oracle’sJavaCodeConventionsOracle’srecommendationsfornamingclasses,variables,
andmethods.Wetypicallyadheretothesestandardsthroughoutthebook,exceptwhenwe’retrying
toshowyouhowatrickyexamquestionmightbecoded.Youwon’tbeaskedquestionsaboutthe
JavaCodeConventions,butwestronglyrecommendyouusethem.
LegalIdentifiers
Technically,legalidentifiersmustbecomposedofonlyUnicodecharacters,numbers,currencysymbols,
andconnectingcharacters(suchasunderscores).Theexamdoesn’tdiveintothedetailsofwhichranges
oftheUnicodecharactersetqualifyaslettersanddigits.So,forexample,youwon’tneedtoknowthat
Tibetandigitsrangefrom\u0420to\u0f29.Herearetherulesyoudoneedtoknow:
Identifiersmuststartwithaletter,acurrencycharacter($),oraconnectingcharactersuchas
theunderscore(_).Identifierscannotstartwithadigit!
Afterthefirstcharacter,identifierscancontainanycombinationofletters,currency
characters,connectingcharacters,ornumbers.
Inpractice,thereisnolimittothenumberofcharactersanidentifiercancontain.
Youcan’tuseaJavakeywordasanidentifier.Table1-1listsalltheJavakeywords.
TABLE1-1 CompleteListofJavaKeywords(assertaddedin1.4,enumaddedin1.5)
IdentifiersinJavaarecasesensitive;fooandFOOaretwodifferentidentifiers.
Examplesoflegalandillegalidentifiersfollow.Firstsomelegalidentifiers:
Thefollowingareillegal(it’syourjobtorecognizewhy):
Oracle’sJavaCodeConventions
Oracleestimatesthatoverthelifetimeofastandardpieceofcode,20percentoftheeffortwillgointothe
originalcreationandtestingofthecode,and80percentoftheeffortwillgointothesubsequent
maintenanceandenhancementofthecode.Agreeingon,andcodingto,asetofcodestandardshelpsto
reducetheeffortinvolvedintesting,maintaining,andenhancinganypieceofcode.Oraclehascreateda
setofcodingstandardsforJavaandpublishedthosestandardsinadocumentcleverlytitled“JavaCode
Conventions,”whichyoucanfindifyoustartatjava.oracle.com.It’sagreatdocument,short,andeasy
toread,andwerecommendithighly.
Thatsaid,you’llfindthatmanyofthequestionsintheexamdon’tfollowthecodeconventionsbecause
ofthelimitationsinthetestenginethatisusedtodelivertheexaminternationally.Oneofthegreatthings
abouttheOraclecertificationsisthattheexamsareadministereduniformlythroughouttheworld.To
achievethat,thecodelistingsthatyou’llseeintherealexamareoftenquitecrampedanddonotfollow
Oracle’scodestandards.Totoughenyouupfortheexam,we’lloftenpresentcodelistingsthathavea
similarlycrampedlookandfeel,oftenindentingourcodeonlytwospacesasopposedtotheOracle
standardoffour.
We’llalsojamourcurlybracestogetherunnaturally,andwe’llsometimesputseveralstatementsonthe
sameline…ouch!Forexample:
Consideryourselfforewarned—you’llseelotsofcodelistings,mockquestions,andrealexam
questionsthatarethissickandtwisted.Nobodywantsyoutowriteyourcodelikethis—notyour
employer,notyourcoworkers,notus,notOracle,andnottheexamcreationteam!Codelikethiswas
createdonlysothatcomplexconceptscouldbetestedwithinauniversaltestingtool.Theonlystandards
thatarefollowedasmuchaspossibleintherealexamarethenamingstandards.Herearethenaming
standardsthatOraclerecommendsandthatweuseintheexamandinmostofthebook:
ClassesandinterfacesThefirstlettershouldbecapitalized,andifseveralwordsarelinked
togethertoformthename,thefirstletteroftheinnerwordsshouldbeuppercase(aformatthat’s
sometimescalled“CamelCase”).Forclasses,thenamesshouldtypicallybenouns.Herearesome
examples:
Dog
Account
PrintWriter
Forinterfaces,thenamesshouldtypicallybeadjectives,likethese:
Runnable
Serializable
MethodsThefirstlettershouldbelowercase,andthennormalCamelCaserulesshouldbe
used.Inaddition,thenamesshouldtypicallybeverb-nounpairs.Forexample:
getBalance
doCalculation
setCustomerName
VariablesLikemethods,theCamelCaseformatshouldbeused,butstartingwithalowercase
letter.Oraclerecommendsshort,meaningfulnames,whichsoundsgoodtous.Someexamples:
buttonWidth
accountBalance
myString
ConstantsJavaconstantsarecreatedbymarkingvariablesstaticandfinal.Theyshouldbe
namedusinguppercaseletterswithunderscorecharactersasseparators:
MIN_HEIGHT
CERTIFICATIONOBJECTIVE
DefineClasses(OCAObjectives1.2,1.3,1.4,6.4,and7.5)
1.2DefinethestructureofaJavaclass.
1.3CreateexecutableJavaapplicationswithamainmethod;runaJavaprogramfromthecommand
line;includingconsoleoutput.(sic)
1.4ImportotherJavapackagestomakethemaccessibleinyourcode.
6.4Applyaccessmodifiers.
7.5Useabstractclassesandinterfaces.
WhenyouwritecodeinJava,you’rewritingclassesorinterfaces.Withinthoseclasses,asyouknow,
arevariablesandmethods(plusafewotherthings).Howyoudeclareyourclasses,methods,and
variablesdramaticallyaffectsyourcode’sbehavior.Forexample,apublicmethodcanbeaccessedfrom
coderunninganywhereinyourapplication.Markthatmethodprivate,though,anditvanishesfrom
everyone’sradar(excepttheclassinwhichitwasdeclared).
Forthisobjective,we’llstudythewaysinwhichyoucandeclareandmodify(ornot)aclass.You’ll
findthatwecovermodifiersinanextremelevelofdetail,andalthoughweknowyou’realreadyfamiliar
withthem,we’restartingfromtheverybeginning.MostJavaprogrammersthinktheyknowhowallthe
modifierswork,butoncloserstudytheyoftenfindoutthattheydon’t(atleastnottothedegreeneededfor
theexam).Subtledistinctionsareeverywhere,soyouneedtobeabsolutelycertainyou’recompletely
solidoneverythinginthissection’sobjectivesbeforetakingtheexam.
SourceFileDeclarationRules
Beforewedigintoclassdeclarations,let’sdoaquickreviewoftherulesassociatedwithdeclaring
classes,importstatements,andpackagestatementsinasourcefile:
Therecanbeonlyonepublicclasspersourcecodefile.
Commentscanappearatthebeginningorendofanylineinthesourcecodefile;theyare
independentofanyofthepositioningrulesdiscussedhere.
Ifthereisapublicclassinafile,thenameofthefilemustmatchthenameofthepublic
class.Forexample,aclassdeclaredaspublicclassDog{}mustbeinasourcecodefile
namedDog.java.
Iftheclassispartofapackage,thepackagestatementmustbethefirstlineinthesource
codefile,beforeanyimportstatementsthatmaybepresent.
Ifthereareimportstatements,theymustgobetweenthepackagestatement(ifthereisone)
andtheclassdeclaration.Ifthereisn’tapackagestatement,thentheimportstatement(s)mustbe
thefirstline(s)inthesourcecodefile.Iftherearenopackageorimportstatements,theclass
declarationmustbethefirstlineinthesourcecodefile.
importandpackagestatementsapplytoallclasseswithinasourcecodefile.Inother
words,there’snowaytodeclaremultipleclassesinafileandhavethemindifferentpackagesor
usedifferentimports.
Afilecanhavemorethanonenon-publicclass.
Fileswithnopublicclassescanhaveanamethatdoesnotmatchanyoftheclassesinthe
file.
UsingthejavacandjavaCommands
Inthisbook,we’regoingtotalkaboutinvokingthejavacandjavacommandsabout1000times.
Althoughintherealworldyou’llprobablyuseanintegrateddevelopmentenvironment(IDE)mostofthe
time,youcouldseeafewquestionsontheexamthatusethecommandlineinstead,sowe’regoingto
reviewthebasics.(Bytheway,wedidNOTuseanIDEwhilewritingthisbook.Westillhaveaslight
preferenceforthecommandlinewhilestudyingfortheexam;allIDEsdotheirbesttobe“helpful,”and
sometimesthey’llfixyourproblemswithouttellingyou.That’sniceonthejob,butmaybenotsogreat
whenyou’restudyingforacertificationexam!)
Compilingwithjavac
ThejavaccommandisusedtoinvokeJava’scompiler.Youcanspecifymanyoptionswhenrunning
javac.Forexample,thereareoptionstogeneratedebugginginformationorcompilerwarnings.Here’s
thestructuraloverviewforjavac:
javac[options][sourcefiles]
Thereareadditionalcommand-lineoptionscalled@argfiles,butthey’rerarelyused,andyouwon’t
needtostudythemfortheexam.Boththe[options]andthe[sourcefiles]areoptionalpartsofthe
command,andbothallowmultipleentries.Thefollowingarelegaljavaccommands:
javac-help
javac-versionFoo.javaBar.java
Thefirstinvocationdoesn’tcompileanyfiles,butprintsasummaryofvalidoptions.Thesecond
invocationpassesthecompileranoption(-version,whichprintstheversionofthecompileryou’re
using)andpassesthecompilertwo.javafilestocompile(Foo.javaandBar.java).Wheneveryou
specifymultipleoptionsand/orfiles,theyshouldbeseparatedbyspaces.
LaunchingApplicationswithjava
ThejavacommandisusedtoinvoketheJavaVirtualMachine(JVM).Here’sthebasicstructureofthe
command:
java[options]class[args]
The[options]and[args]partsofthejavacommandareoptional,andtheycanbothhavemultiple
values.Youmustspecifyexactlyoneclassfiletoexecute,andthejavacommandassumesyou’retalking
abouta.classfile,soyoudon’tspecifythe.classextensiononthecommandline.Here’sanexample:
java-showversionMyClassx1
Thiscommandcanbeinterpretedas“ShowmetheversionoftheJVMbeingused,andthenlaunchthefile
namedMyClass.classandsendittwoStringargumentswhosevaluesarexand1.”Let’slookatthe
followingcode:
It’scompiledandtheninvokedasfollows:
javaMyClassx1
Theoutputwillbe
x1
We’llbegettingintoarraysindepthlater,butfornowit’senoughtoknowthatargs—likeallarrays—
useazero-basedindex.Inotherwords,thefirstcommand-lineargumentisassignedtoargs[0],the
secondargumentisassignedtoargs[1],andsoon.
Usingpublicstaticvoidmain(String[]args)
Theuseofthemain()methodisimpliedinmostofthequestionsontheexam,andontheOCAexamitis
specificallycovered.Forthe.0001percentofyouwhodon’tknow,main()isthemethodthattheJVM
usestostartexecutionofaJavaprogram.
Firstoff,it’simportantforyoutoknowthatnamingamethodmain()doesn’tgiveitthesuperpowers
wenormallyassociatewithmain().AsfarasthecompilerandtheJVMareconcerned,theonlyversion
ofmain()withsuperpowersisthemain()withthissignature:
publicstaticvoidmain(String[]args)
Otherversionsofmain()withothersignaturesareperfectlylegal,butthey’retreatedasnormalmethods.
Thereissomeflexibilityinthedeclarationofthe“special”main()method(theoneusedtostartaJava
application):theorderofitsmodifierscanbealteredalittle;theStringarraydoesn’thavetobenamed
args;anditcanbedeclaredusingvar-argssyntax.Thefollowingarealllegaldeclarationsforthe
“special”main():
FortheOCA8exam,theonlyotherthingthat’simportantforyoutoknowisthatmain()canbe
overloaded.We’llcoveroverloadingindetailinthenextchapter.
ImportStatementsandtheJavaAPI
ThereareagazillionJavaclassesintheworld.TheJavaAPIhasthousandsofclasses,andtheJava
communityhaswrittentherest.We’llgooutonalimbandcontendthatallJavaprogrammerseverywhere
useacombinationofclassestheywroteandclassesthatotherprogrammerswrote.Supposewecreated
thefollowing:
Thisisaperfectlylegalclass,butasitturnsout,oneofthemostcommonlyusedclassesintheJavaAPI
isalsonamedArrayList,orsoitseems….TheAPIversion’sactualnameisjava.util.ArrayList.
That’sitsfullyqualifiedname.TheuseoffullyqualifiednamesiswhathelpsJavadevelopersmakesure
thattwoversionsofaclasslikeArrayListdon’tgetconfused.Sonowlet’ssaythatIwanttousethe
ArrayListclassfromtheAPI:
(Firstoff,trustusonthe<String>syntax;we’llgettothatlater.)Althoughthisislegal,it’salsoaLOT
ofkeystrokes.Sinceweprogrammersarebasicallylazy(there,wesaidit),weliketouseotherpeople’s
classesaLOT,ANDwehatetotype.Ifwehadalargeprogram,wemightendupusingArrayListsmany
times.
importstatementstotherescue!Insteadoftheprecedingcode,ourclasscouldlooklikethis:
Wecaninterprettheimportstatementassaying,“IntheJavaAPIthereisapackagecalled‘util’,and
inthatpackageisaclasscalled‘ArrayList’.Wheneveryouseetheword‘ArrayList’inthisclass,it’s
justshorthandfor:‘java.util.ArrayList’.”(Note:Lotsmoreonpackagestocome!)Ifyou’reaC
programmer,youmightthinkthattheimportstatementissimilartoan#include.Notreally.AllaJava
importstatementdoesissaveyousometyping.That’sit.
Aswejustimplied,apackagetypicallyhasmanyclasses.Theimportstatementoffersyetanother
keystroke-savingcapability.Let’ssayyouwantedtouseafewdifferentclassesfromthejava.util
package:ArrayListandTreeSet.Youcanaddawildcardcharacter(*)toyourimportstatementthat
means,“Ifyouseeareferencetoaclassyou’renotsureof,youcanlookthroughtheentirepackagefor
thatclass,”likeso:
WhenthecompilerandtheJVMseethiscode,they’llknowtolookthroughjava.utilforArrayList
andTreeSet.Fortheexam,thelastthingyou’llneedtorememberaboutusingimportstatementsinyour
classesisthatyou’refreetomixandmatch.It’sokaytosaythis:
StaticImportStatements
DearReader,Wereallystruggledwithwheretoincludethisdiscussionofstaticimports.Fromalearning
perspective,thisisprobablynottheideallocation,butfromareferenceperspective,wethoughtitmade
sense.Asyou’relearningthematerialforthefirsttime,youmightbeconfusedbysomeoftheideasinthis
section.Ifthat’sthecase,weapologize.Putastickynoteonthispageandcirclebackaroundafteryou’re
finishedwithChapter3.Ontheotherhand,onceyou’repastthelearningstageandyou’reusingthisbook
asareference,wethinkputtingthissectionherewillbequiteuseful.Now,ontostaticimports.
Sometimesclasseswillcontainstaticmembers.(We’lltalkmoreaboutstaticclassmemberslater,but
sincewe’reonthetopicofimportswethoughtwe’dtossinstaticimportsnow.)Staticclassmemberscan
existintheclassesyouwriteandinalotoftheclassesintheJavaAPI.
Aswesaidearlier,ultimatelytheonlyvalueimportstatementshaveisthattheysavetypingandthey
canmakeyourcodeeasiertoread.InJava5(alongtimeago),theimportstatementwasenhancedto
provideevengreaterkeystroke-reductioncapabilities,althoughsomewouldarguethatthiscomesatthe
expenseofreadability.Thisfeatureisknownasstaticimports.Staticimportscanbeusedwhenyouwant
to“savetyping”whileusingaclass’sstaticmembers.(YoucanusethisfeatureonclassesintheAPIand
onyourownclasses.)Here’sa“beforeandafter”exampleusingafewstaticclassmembersprovidedby
acommonlyusedclassintheJavaAPI,java.lang.Integer.Thisexamplealsousesastaticmember
thatyou’veusedathousandtimes,probablywithoutevergivingitmuchthought;theoutfieldinthe
Systemclass.
Beforestaticimports:
Afterstaticimports:
Bothclassesproducethesameoutput:
2147483647
2a
Let’slookatwhat’shappeninginthecodethat’susingthestaticimportfeature:
1.Eventhoughthefeatureiscommonlycalled“staticimport,”thesyntaxMUSTbeimport
staticfollowedbythefullyqualifiednameofthestaticmemberyouwanttoimport,ora
wildcard.Inthiscase,we’redoingastaticimportontheSystemclassoutobject.
2.Inthiscase,wemightwanttouseseveralofthestaticmembersofthejava.lang.Integer
class.Thisstaticimportstatementusesthewildcardtosay,“IwanttodostaticimportsofALLthe
staticmembersinthisclass.”
3.Nowwe’refinallyseeingthebenefitofthestaticimportfeature!Wedidn’thavetotypethe
SysteminSystem.out.println!Wow!Second,wedidn’thavetotypetheIntegerin
Integer.MAX_VALUE.Sointhislineofcodewewereabletouseashortcutforastaticmethod
ANDaconstant.
4.Finally,wedoonemoreshortcut,thistimeforamethodintheIntegerclass.
We’vebeenalittlesarcasticaboutthisfeature,butwe’renottheonlyones.We’renotconvincedthat
savingafewkeystrokesisworthpossiblymakingthecodealittlehardertoread,butenoughdevelopers
requesteditthatitwasaddedtothelanguage.
Hereareacoupleofrulesforusingstaticimports:
Youmustsayimportstatic;youcan’tsaystaticimport.
Watchoutforambiguouslynamedstaticmembers.Forinstance,ifyoudoastaticimportfor
boththeIntegerclassandtheLongclass,referringtoMAX_VALUEwillcauseacompilererror,
becausebothIntegerandLonghaveaMAX_VALUEconstantandJavawon’tknowwhich
MAX_VALUEyou’rereferringto.
Youcandoastaticimportonstaticobjectreferences,constants(rememberthey’restatic
andfinal),andstaticmethods.
Asyou’veseen,whenusingimportandimportstaticstatements,sometimesyoucanusethe
wildcardcharacter*todosomesimplesearchingforyou.(Youcansearchwithinapackageor
withinaclass.)Asyousawearlier,ifyouwantto"searchthroughthejava.utilpackagefor
classnames,"youcansaythis:
Inasimilarvein,ifyouwantto"searchthroughthejava.lang.Integerclassforstatic
members,"youcansaythis:
Butyoucan’tcreatebroadersearches.Forinstance,youCANNOTuseanimporttosearch
throughtheentireJavaAPI:
ClassDeclarationsandModifiers
Theclassdeclarationswe’lldiscussinthissectionarelimitedtotop-levelclasses.Inadditiontotop-
levelclasses,Javaprovidesforanothercategoryofclassknownasnestedclassesorinnerclasses.Inner
classesareincludedontheOCPexam,butnottheOCAexam.WhenyoubecomeanOCPcandidate,
you’regoingtolovelearningaboutinnerclasses.No,really.Seriously.
Thefollowingcodeisabare-bonesclassdeclaration:
classMyClass{}
Thiscodecompilesjustfine,butyoucanalsoaddmodifiersbeforetheclassdeclaration.Ingeneral,
modifiersfallintotwocategories:
Accessmodifiers(public,protected,private)
Nonaccessmodifiers(includingstrictfp,final,andabstract)
We’lllookataccessmodifiersfirst,soyou’lllearnhowtorestrictorallowaccesstoaclassyou
create.AccesscontrolinJavaisalittletrickybecausetherearefouraccesscontrols(levelsofaccess)
butonlythreeaccessmodifiers.Thefourthaccesscontrollevel(calleddefaultorpackageaccess)is
whatyougetwhenyoudon’tuseanyofthethreeaccessmodifiers.Inotherwords,everyclass,method,
andinstancevariableyoudeclarehasanaccesscontrol,whetheryouexplicitlytypeoneornot.Although
allfouraccesscontrols(whichmeansallthreemodifiers)workformostmethodandvariable
declarations,aclasscanbedeclaredwithonlypublicordefaultaccess;theothertwoaccesscontrol
levelsdon’tmakesenseforaclass,asyou’llsee.
Javaisapackage-centriclanguage;thedevelopersassumedthatforgoodorganizationandname
scoping,youwouldputallyourclassesintopackages.Theywereright,andyoushould.Imaginethis
nightmare:Threedifferentprogrammers,inthesamecompanybutworkingondifferentpartsofa
project,writeaclassnamedUtilities.IfthosethreeUtilitiesclasseshavenotbeendeclaredin
anyexplicitpackageandareintheclasspath,youwon’thaveanywaytotellthecompilerorJVM
whichofthethreeyou’retryingtoreference.Oraclerecommendsthatdevelopersusereverse
domainnames,appendedwithdivisionand/orprojectnames.Forexample,ifyourdomainnameis
geeksanonymous.comandyou’reworkingontheclientcodefortheTwelvePointOStepsprogram,
youwouldnameyourpackagesomethinglikecom.geeksanonymous.steps.client.Thatwould
essentiallychangethenameofyourclasstocom.geeksanonymous.steps.client.Utilities.You
mightstillhavenamecollisionswithinyourcompanyifyoudon’tcomeupwithyourownnaming
schemes,butyou’reguaranteednottocollidewithclassesdevelopedoutsideyourcompany
(assumingtheyfollowOracle’snamingconvention,andiftheydon’t,well,ReallyBadThingscould
happen).
ClassAccess
Whatdoesitmeantoaccessaclass?Whenwesaycodefromoneclass(classA)hasaccesstoanother
class(classB),itmeansclassAcandooneofthreethings:
CreateaninstanceofclassB.
ExtendclassB(inotherwords,becomeasubclassofclassB).
AccesscertainmethodsandvariableswithinclassB,dependingontheaccesscontrolofthose
methodsandvariables.
Ineffect,accessmeansvisibility.IfclassAcan’tseeclassB,theaccesslevelofthemethodsand
variableswithinclassBwon’tmatter;classAwon’thaveanywaytoaccessthosemethodsand
variables.
DefaultAccessAclasswithdefaultaccesshasnomodifierprecedingitinthedeclaration!It’sthe
accesscontrolyougetwhenyoudon’ttypeamodifierintheclassdeclaration.Thinkofdefaultaccessas
package-levelaccess,becauseaclasswithdefaultaccesscanbeseenonlybyclasseswithinthesame
package.Forexample,ifclassAandclassBareindifferentpackages,andclassAhasdefaultaccess,
classBwon’tbeabletocreateaninstanceofclassAorevendeclareavariableorreturntypeofclassA.
Infact,classBhastopretendthatclassAdoesn’tevenexistorthecompilerwillcomplain.Lookatthe
followingsourcefile:
Asyoucansee,thesuperclass(Beverage)isinadifferentpackagefromthesubclass(Tea).The
importstatementatthetopoftheTeafileistrying(fingerscrossed)toimporttheBeverageclass.The
Beveragefilecompilesfine,butwhenwetrytocompiletheTeafile,wegetsomethinglikethis:
(Note:Forvariousreasons,theerrormessagesweshowthroughoutthisbookmightnotmatchthe
errormessagesyouget.Don’tworry,therealpointistounderstandwhenyou’reapttogetanerror
ofsomesort.)
Teawon’tcompilebecauseitssuperclass,Beverage,hasdefaultaccessandisinadifferentpackage.
Youcandooneoftwothingstomakethiswork.Youcouldputbothclassesinthesamepackage,oryou
coulddeclareBeverageaspublic,asthenextsectiondescribes.
Whenyouseeaquestionwithcomplexlogic,besuretolookattheaccessmodifiersfirst.Thatway,if
youspotanaccessviolation(forexample,aclassinpackageAtryingtoaccessadefaultclassinpackage
B),you’llknowthecodewon’tcompilesoyoudon’thavetobotherworkingthroughthelogic.It’snotas
ifyoudon’thaveanythingbettertodowithyourtimewhiletakingtheexam.Justchoosethe“Compilation
fails”answerandzoomontothenextquestion.
PublicAccess
Aclassdeclarationwiththepublickeywordgivesallclassesfromallpackagesaccesstothepublic
class.Inotherwords,allclassesintheJavaUniverse(JU)haveaccesstoapublicclass.Don’tforget,
though,thatifapublicclassyou’retryingtouseisinadifferentpackagefromtheclassyou’rewriting,
you’llstillneedtoimportthepublicclass.
Intheexamplefromtheprecedingsection,wemaynotwanttoplacethesubclassinthesamepackage
asthesuperclass.Tomakethecodework,weneedtoaddthekeywordpublicinfrontofthesuperclass
(Beverage)declaration,asfollows:
packagecert;
publicclassBeverage{}
ThischangestheBeverageclasssoitwillbevisibletoallclassesinallpackages.Theclasscannow
beinstantiatedfromallotherclasses,andanyclassisnowfreetosubclass(extendfrom)it—unless,that
is,theclassisalsomarkedwiththenonaccessmodifierfinal.Readon.
Other(Nonaccess)ClassModifiers
Youcanmodifyaclassdeclarationusingthekeywordfinal,abstract,orstrictfp.Thesemodifiers
areinadditiontowhateveraccesscontrolisontheclass,soyoucould,forexample,declareaclassas
bothpublicandfinal.Butyoucan’talwaysmixnonaccessmodifiers.You’refreetousestrictfpin
combinationwithfinal,forexample,butyoumustnever,ever,evermarkaclassasbothfinaland
abstract.You’llseewhyinthenexttwosections.
Youwon’tneedtoknowhowstrictfpworks,sowe’refocusingonlyonmodifyingaclassasfinal
orabstract.Fortheexam,youneedtoknowonlythatstrictfpisakeywordandcanbeusedtomodify
aclassoramethod,butneveravariable.Markingaclassasstrictfpmeansthatanymethodcodeinthe
classwillconformstrictlytotheIEEE754standardrulesforfloatingpoints.Withoutthatmodifier,
floatingpointsusedinthemethodsmightbehaveinaplatform-dependentway.Ifyoudon’tdeclareaclass
asstrictfp,youcanstillgetstrictfpbehavioronamethod-by-methodbasisbydeclaringamethodas
strictfp.Ifyoudon’tknowtheIEEE754standard,now’snotthetimetolearnit.Youhave,astheysay,
biggerfishtofry.
FinalClasses
Whenusedinaclassdeclaration,thefinalkeywordmeanstheclasscan’tbesubclassed.Inother
words,nootherclasscaneverextend(inheritfrom)afinalclass,andanyattemptstodosowillresult
inacompilererror.
Sowhywouldyouevermarkaclassfinal?Afterall,doesn’tthatviolatethewholeOOnotionof
inheritance?Youshouldmakeafinalclassonlyifyouneedanabsoluteguaranteethatnoneofthe
methodsinthatclasswilleverbeoverridden.Ifyou’redeeplydependentontheimplementationsof
certainmethods,thenusingfinalgivesyouthesecuritythatnobodycanchangetheimplementationout
fromunderyou.
You’llnoticemanyclassesintheJavacorelibrariesarefinal.Forexample,theStringclasscannot
besubclassed.Imaginethehavocifyoucouldn’tguaranteehowaStringobjectwouldworkonany
givensystemyourapplicationisrunningon!IfprogrammerswerefreetoextendtheStringclass(and
thussubstitutetheirnewStringsubclassinstanceswherejava.lang.Stringinstancesareexpected),
civilization—asweknowit—couldcollapse.Sousefinalforsafety,butonlywhenyou’recertainthat
yourfinalclasshasindeedsaidallthateverneedstobesaidinitsmethods.Markingaclassfinal
means,inessence,yourclasscan’teverbeimprovedupon,orevenspecialized,byanotherprogrammer.
There’sabenefittohavingnonfinalclassesinthisscenario:Imaginethatyoufindaproblemwitha
methodinaclassyou’reusing,butyoudon’thavethesourcecode.Soyoucan’tmodifythesourceto
improvethemethod,butyoucanextendtheclassandoverridethemethodinyournewsubclassand
substitutethesubclasseverywheretheoriginalsuperclassisexpected.Iftheclassisfinal,though,
you’restuck.
Let’smodifyourBeverageexamplebyplacingthekeywordfinalinthedeclaration:
Nowlet’strytocompiletheTeasubclass:
Inpractice,you’llalmostnevermakeafinalclass.AfinalclassobliteratesakeybenefitofOO—
extensibility.Unlessyouhaveaserioussafetyorsecurityissue,assumethatsomedayanotherprogrammer
willneedtoextendyourclass.Ifyoudon’t,thenextprogrammerforcedtomaintainyourcodewillhunt
youdownand<insertreallyscarything>.
AbstractClassesAnabstractclasscanneverbeinstantiated.Itssolepurpose,missioninlife,
raisond’être,istobeextended(subclassed).(Note,however,thatyoucancompileandexecutean
abstractclass,aslongasyoudon’ttrytomakeaninstanceofit.)Whymakeaclassifyoucan’tmake
objectsoutofit?Becausetheclassmightbejusttoo,well,abstract.Forexample,imagineyouhavea
classCarthathasgenericmethodscommontoallvehicles.Butyoudon’twantanyoneactuallycreatinga
genericabstractCarobject.Howwouldtheyinitializeitsstate?Whatcolorwoulditbe?Howmany
seats?Horsepower?All-wheeldrive?Ormoreimportantly,howwoulditbehave?Inotherwords,how
wouldthemethodsbeimplemented?
No,youneedprogrammerstoinstantiateactualcartypessuchasBMWBoxsterandSubaruOutback.
We’llbettheBoxsterownerwilltellyouhiscardoesthingstheSubarucando“onlyinitsdreams.”Take
alookatthefollowingabstractclass:
Theprecedingcodewillcompilefine.However,ifyoutrytoinstantiateaCarinanotherbodyofcode,
you’llgetacompilererrorsomethinglikethis:
Noticethatthemethodsmarkedabstractendinasemicolonratherthancurlybraces.
Lookforquestionswithamethoddeclarationthatendswithasemicolon,ratherthancurlybraces.If
themethodisinaclass—asopposedtoaninterface—thenboththemethodandtheclassmustbemarked
abstract.Youmightgetaquestionthataskshowyoucouldfixacodesamplethatincludesamethod
endinginasemicolonbutwithoutanabstractmodifierontheclassormethod.Inthatcase,youcould
eithermarkthemethodandclassabstractorchangethesemicolontocode(likeacurlybracepair).
Rememberthatifyouchangeamethodfromabstracttononabstract,don’tforgettochangethe
semicolonattheendofthemethoddeclarationintoacurlybracepair!
We’lllookatabstractmethodsinmoredetaillaterinthisobjective,butalwaysrememberthatif
evenasinglemethodisabstract,thewholeclassmustbedeclaredabstract.Oneabstractmethod
spoilsthewholebunch.Youcan,however,putnonabstractmethodsinanabstractclass.Forexample,
youmighthavemethodswithimplementationsthatshouldn’tchangefromCartypetoCartype,suchas
getColor()orsetPrice().Byputtingnonabstractmethodsinanabstractclass,yougiveallconcrete
subclasses(concretejustmeansnotabstract)inheritedmethodimplementations.Thegoodnewsthereis
thatconcretesubclassesgettoinheritfunctionalityandneedtoimplementonlythemethodsthatdefine
subclass-specificbehavior.
(Bytheway,ifyouthinkwemisusedraisond’êtreearlier,don’tsendane-mail.We’dliketoseeyou
workitintoaprogrammercertificationbook.)
Codingwithabstractclasstypes(includinginterfaces,discussedlaterinthischapter)letsyoutake
advantageofpolymorphismandgivesyouthegreatestdegreeofflexibilityandextensibility.You’lllearn
moreaboutpolymorphisminChapter2.
Youcan’tmarkaclassasbothabstractandfinal.Theyhavenearlyoppositemeanings.An
abstractclassmustbesubclassed,whereasafinalclassmustnotbesubclassed.Ifyouseethis
combinationofabstractandfinalmodifiersusedforaclassormethoddeclaration,thecodewillnot
compile.
EXERCISE1-1
CreatinganAbstractSuperclassandConcreteSubclass
Thefollowingexercisewilltestyourknowledgeofpublic,default,final,andabstractclasses.
CreateanabstractsuperclassnamedFruitandaconcretesubclassnamedApple.Thesuperclass
shouldbelongtoapackagecalledfoodandthesubclasscanbelongtothedefaultpackage(meaningit
isn’tputintoapackageexplicitly).Makethesuperclasspublicandgivethesubclassdefaultaccess.
1.Createthesuperclassasfollows:
packagefood;
publicabstractclassFruit{/*anycodeyouwant*/}
2.Createthesubclassinaseparatefileasfollows:
importfood.Fruit;
classAppleextendsFruit{/*anycodeyouwant*/}
3.Createadirectorycalledfoodoffthedirectoryinyourclasspathsetting.
4.Attempttocompilethetwofiles.IfyouwanttousetheAppleclass,makesureyouplacethe
Fruit.classfileinthefoodsubdirectory.
CERTIFICATIONOBJECTIVE
UseInterfaces(OCAObjective7.5)
7.6Useabstractclassesandinterfaces.
DeclaringanInterface
Ingeneral,whenyoucreateaninterface,you’redefiningacontractforwhataclasscando,without
sayinganythingabouthowtheclasswilldoit.
Note:AsofJava8,youcannowalsodescribethehow,butyouusuallywon’t.Untilwegettothenew
interface-relatedfeaturesofJava8—defaultandstaticmethods—wewilldiscussinterfacesfroma
traditionalperspective,whichisagain,definingacontractforwhataclasscando.
Aninterfaceisacontract.YoucouldwriteaninterfaceBounceable,forexample,thatsaysineffect,
“ThisistheBounceableinterface.Anyconcreteclasstypethatimplementsthisinterfacemustagreeto
writethecodeforthebounce()andsetBounceFactor()methods.”
BydefininganinterfaceforBounceable,anyclassthatwantstobetreatedasaBounceablethingcan
simplyimplementtheBounceableinterfaceandprovidecodefortheinterface’stwomethods.
Interfacescanbeimplementedbyanyclass,fromanyinheritancetree.Thisletsyoutakeradically
differentclassesandgivethemacommoncharacteristic.Forexample,youmightwantbothaBallanda
Tiretohavebouncebehavior,butBallandTiredon’tshareanyinheritancerelationship;Ballextends
ToywhileTireextendsonlyjava.lang.Object.ButbymakingbothBallandTireimplement
Bounceable,you’resayingthatBallandTirecanbetreatedas“Thingsthatcanbounce,”whichinJava
translatesto,“Thingsonwhichyoucaninvokethebounce()andsetBounceFactor()methods.”Figure
1-1illustratestherelationshipbetweeninterfacesandclasses.
FIGURE1-1 Therelationshipbetweeninterfacesandclasses
Thinkofatraditionalinterfaceasa100percentabstractclass.Likeanabstractclass,aninterface
definesabstractmethodsthattakethefollowingform:
Butalthoughanabstractclasscandefinebothabstractandnonabstractmethods,aninterface
generallyhasonlyabstractmethods.Anotherwayinterfacesdifferfromabstractclassesisthat
interfaceshaveverylittleflexibilityinhowthemethodsandvariablesdefinedintheinterfaceare
declared.Theserulesarestrict:
Interfacemethodsareimplicitlypublicandabstract,unlessdeclaredasdefaultor
static.Inotherwords,youdonotneedtoactuallytypethepublicorabstractmodifiersinthe
methoddeclaration,butthemethodisstillalwayspublicandabstract.
Allvariablesdefinedinaninterfacemustbepublic,static,andfinal—inotherwords,
interfacescandeclareonlyconstants,notinstancevariables.
Interfacemethodscannotbemarkedfinal,strictfp,ornative.(Moreonthesemodifiers
laterinthechapter.)
Aninterfacecanextendoneormoreotherinterfaces.
Aninterfacecannotextendanythingbutanotherinterface.
Aninterfacecannotimplementanotherinterfaceorclass.
Aninterfacemustbedeclaredwiththekeywordinterface.
Interfacetypescanbeusedpolymorphically(seeChapter2formoredetails).
Thefollowingisalegalinterfacedeclaration:
publicabstractinterfaceRollable{}
Typingintheabstractmodifierisconsideredredundant;interfacesareimplicitlyabstractwhether
youtypeabstractornot.Youjustneedtoknowthatbothofthesedeclarationsarelegalandfunctionally
identical:
publicabstractinterfaceRollable{}
publicinterfaceRollable{}
Thepublicmodifierisrequiredifyouwanttheinterfacetohavepublicratherthandefaultaccess.
We’velookedattheinterfacedeclaration,butnowwe’lllookcloselyatthemethodswithinan
interface:
Typinginthepublicandabstractmodifiersonthemethodsisredundant,though,sinceallinterface
methodsareimplicitlypublicandabstract.Giventhatrule,youcanseethatthefollowingcodeis
exactlyequivalenttotheprecedinginterface:
Youmustrememberthatallinterfacemethodsnotdeclareddefaultorstaticarepublicand
abstractregardlessofwhatyouseeintheinterfacedefinition.
Lookforinterfacemethodsdeclaredwithanycombinationofpublic,abstract,ornomodifiers.For
example,thefollowingfivemethoddeclarations,ifdeclaredwithintheirowninterfaces,arelegaland
identical!
Thefollowinginterfacemethoddeclarationswon’tcompile:
DeclaringInterfaceConstants
You’reallowedtoputconstantsinaninterface.Bydoingso,youguaranteethatanyclassimplementing
theinterfacewillhaveaccesstothesameconstant.Byplacingtheconstantsrightintheinterface,any
classthatimplementstheinterfacehasdirectaccesstotheconstants,justasiftheclasshadinherited
them.
Youneedtorememberonekeyruleforinterfaceconstants.Theymustalwaysbe
publicstaticfinal
Sothatsoundssimple,right?Afterall,interfaceconstantsarenodifferentfromanyotherpublicly
accessibleconstants,sotheyobviouslymustbedeclaredpublic,static,andfinal.Butbeforeyou
breezepasttherestofthisdiscussion,thinkabouttheimplications:Becauseinterfaceconstantsare
definedinaninterface,theydon’thavetobedeclaredaspublic,static,orfinal.Theymustbe
public,static,andfinal,butyoudon’tactuallyhavetodeclarethemthatway.Justasinterface
methodsarealwayspublicandabstractwhetheryousaysointhecodeornot,anyvariabledefinedin
aninterfacemustbe—andimplicitlyis—apublicconstant.Seeifyoucanspottheproblemwiththe
followingcode(assumetwoseparatefiles):
Youcan’tchangethevalueofaconstant!Oncethevaluehasbeenassigned,thevaluecanneverbe
modified.Theassignmenthappensintheinterfaceitself(wheretheconstantisdeclared),sothe
implementingclasscanaccessitanduseit,butasaread-onlyvalue.SotheBAR=27assignmentwill
notcompile.
Lookforinterfacedefinitionsthatdefineconstants,butwithoutexplicitlyusingtherequired
modifiers.Forexample,thefollowingareallidentical:
Anycombinationoftherequired(butimplicit)modifiersislegal,asisusingnomodifiersat
all!Ontheexam,youcanexpecttoseequestionsyouwon’tbeabletoanswercorrectlyunless
youknow,forexample,thataninterfacevariableisfinalandcanneverbegivenavaluebythe
implementing(oranyother)class.
DeclaringdefaultInterfaceMethods
AsofJava8,interfacescanincludeinheritable*methodswithconcreteimplementations.(*Thestrict
definitionof“inheritance”hasgottenalittlefuzzywithJava8;we’lltalkmoreaboutinheritancein
Chapter2.)Theseconcretemethodsarecalleddefaultmethods.Inthenextchapterwe’lltalkalotabout
thevariousOO-relatedrulesthatareimpactedbecauseofdefaultmethods.Fornowwe’lljustcoverthe
simpledeclarationrules:
defaultmethodsaredeclaredbyusingthedefaultkeyword.Thedefaultkeywordcanbe
usedonlywithinterfacemethodsignatures,notclassmethodsignatures.
defaultmethodsarepublicbydefinition,andthepublicmodifierisoptional.
defaultmethodscannotbemarkedasprivate,protected,static,final,orabstract.
defaultmethodsmusthaveaconcretemethodbody.
Herearesomeexamplesoflegalandillegaldefaultmethods:
DeclaringstaticInterfaceMethods
AsofJava8,interfacescanincludestaticmethodswithconcreteimplementations.Aswithinterface
defaultmethods,thereareOOimplicationsthatwe’lldiscussinChapter2.Fornow,we’llfocusonthe
basicsofdeclaringandusingstaticinterfacemethods:
staticinterfacemethodsaredeclaredbyusingthestatickeyword.
staticinterfacemethodsarepublicbydefault,andthepublicmodifierisoptional.
staticinterfacemethodscannotbemarkedasprivate,protected,final,orabstract.
staticinterfacemethodsmusthaveaconcretemethodbody.
Wheninvokingastaticinterfacemethod,themethod’stype(interfacename)MUSTbe
includedintheinvocation.
Herearesomeexamplesoflegalandillegalstaticinterfacemethodsandtheiruse:
whichproducesthisoutput:
42
42
Aswesaidearlier,we’llreturntoourdiscussionofdefaultmethodsandstaticmethodsforinterfaces
inChapter2.
CERTIFICATIONOBJECTIVE
DeclareClassMembers(OCAObjectives2.1,2.2,2.3,4.1,
4.2,6.2,6.3,and6.4)
2.1Declareandinitializevariables(includingcastingofprimitivedatatypes).
2.2Differentiatebetweenobjectreferencevariablesandprimitivevariables.
2.3Knowhowtoreadorwritetoobjectfields.
4.1Declare,instantiate,initialize,anduseaone-dimensionalarray.
4.2Declare,instantiate,initialize,andusemultidimensionalarray.(sic)
6.2Applythestatickeywordtomethodsandfields.
6.3Createandoverloadconstructors;includingimpactondefaultconstructors.(sic)
6.4Applyaccessmodifiers.
We’velookedatwhatitmeanstouseamodifierinaclassdeclaration,andnowwe’lllookatwhatit
meanstomodifyamethodorvariabledeclaration.
Methodsandinstance(nonlocal)variablesarecollectivelyknownasmembers.Youcanmodifya
memberwithbothaccessandnonaccessmodifiers,andyouhavemoremodifierstochoosefrom(and
combine)thanwhenyou’redeclaringaclass.
AccessModifiers
Becausemethodandvariablemembersareusuallygivenaccesscontrolinexactlythesameway,we’ll
coverbothinthissection.
Whereasaclasscanusejusttwoofthefouraccesscontrollevels(defaultorpublic),memberscan
useallfour:
public
protected
default
private
Defaultprotectioniswhatyougetwhenyoudon’ttypeanaccessmodifierinthememberdeclaration.
Thedefaultandprotectedaccesscontroltypeshavealmostidenticalbehavior,exceptforonedifference
thatwewillmentionlater.
Note:AsofJava8,theworddefaultcanALSObeusedtodeclarecertainmethodsininterfaces.
Whenusedinaninterface’smethoddeclaration,defaulthasadifferentmeaningthanwhatweare
describingfortherestofthischapter.
It’scrucialthatyouknowaccesscontrolinsideandoutsidefortheexam.Therewillbequiteafew
questionswhereaccesscontrolplaysarole.Somequestionstestseveralconceptsofaccesscontrolatthe
sametime,sonotknowingonesmallpartofaccesscontrolcouldmeanyoublowanentirequestion.
Whatdoesitmeanforcodeinoneclasstohaveaccesstoamemberofanotherclass?Fornow,ignore
anydifferencesbetweenmethodsandvariables.IfclassAhasaccesstoamemberofclassB,itmeans
thatclassB’smemberisvisibletoclassA.Whenaclassdoesnothaveaccesstoanothermember,the
compilerwillslapyoufortryingtoaccesssomethingthatyou’renotevensupposedtoknowexists!
Youneedtounderstandtwodifferentaccessissues:
Whethermethodcodeinoneclasscanaccessamemberofanotherclass
Whetherasubclasscaninheritamemberofitssuperclass
Thefirsttypeofaccessoccurswhenamethodinoneclasstriestoaccessamethodoravariableof
anotherclass,usingthedotoperator(.)toinvokeamethodorretrieveavariable.Forexample:
Thesecondtypeofaccessrevolvesaroundwhich,ifany,membersofasuperclassasubclasscan
accessthroughinheritance.We’renotlookingatwhetherthesubclasscan,say,invokeamethodonan
instanceofthesuperclass(whichwouldjustbeanexampleofthefirsttypeofaccess).Instead,we’re
lookingatwhetherthesubclassinheritsamemberofitssuperclass.Remember,ifasubclassinheritsa
member,it’sexactlyasifthesubclassactuallydeclaredthememberitself.Inotherwords,ifasubclass
inheritsamember,thesubclasshasthemember.Here’sanexample:
Figure1-2comparesaclassinheritingamemberofanotherclassandaccessingamemberofanother
classusingareferenceofaninstanceofthatclass.
FIGURE1-2 Comparisonofinheritancevs.dotoperatorformemberaccess
Muchofaccesscontrol(bothtypes)centersonwhetherthetwoclassesinvolvedareinthesameor
differentpackages.Don’tforget,though,thatifclassAitselfcan’tbeaccessedbyclassB,thenno
memberswithinclassAcanbeaccessedbyclassB.
Youneedtoknowtheeffectofdifferentcombinationsofclassandmemberaccess(suchasadefault
classwithapublicvariable).Tofigurethisout,firstlookattheaccessleveloftheclass.Iftheclass
itselfwillnotbevisibletoanotherclass,thennoneofthememberswillbevisibleeither,evenifthe
memberisdeclaredpublic.Onceyou’veconfirmedthattheclassisvisible,thenitmakessensetolook
ataccesslevelsonindividualmembers.
PublicMembers
Whenamethodorvariablememberisdeclaredpublic,itmeansallotherclasses,regardlessofthe
packagetheybelongto,canaccessthemember(assumingtheclassitselfisvisible).
Lookatthefollowingsourcefile:
Asyoucansee,GooandSludgeareindifferentpackages.However,Goocaninvokethemethodin
SludgewithoutproblemsbecauseboththeSludgeclassanditstestIt()methodaremarkedpublic.
Forasubclass,ifamemberofitssuperclassisdeclaredpublic,thesubclassinheritsthatmember
regardlessofwhetherbothclassesareinthesamepackage:
TheRooclassdeclaresthedoRooThings()memberaspublic.SoifwemakeasubclassofRoo,any
codeinthatRoosubclasscancallitsowninheriteddoRooThings()method.
NoticeinthefollowingcodethatthedoRooThings()methodisinvokedwithouthavingtoprefaceit
withareference:
Remember,ifyouseeamethodinvoked(oravariableaccessed)withoutthedotoperator(.),itmeans
themethodorvariablebelongstotheclasswhereyouseethatcode.Italsomeansthatthemethodor
variableisimplicitlybeingaccessedusingthethisreference.Sointheprecedingcode,thecallto
doRooThings()intheClooclasscouldalsohavebeenwrittenasthis.doRooThings().Thereference
thisalwaysreferstothecurrentlyexecutingobject—inotherwords,theobjectrunningthecodewhere
youseethethisreference.Becausethethisreferenceisimplicit,youdon’tneedtoprefaceyour
memberaccesscodewithit,butitwon’thurt.Someprogrammersincludeittomakethecodeeasierto
readfornew(ornon)Javaprogrammers.
BesidesbeingabletoinvokethedoRooThings()methodonitself,codefromsomeotherclasscan
calldoRooThings()onaClooinstance,asinthefollowing:
PrivateMembers
Membersmarkedprivatecan’tbeaccessedbycodeinanyclassotherthantheclassinwhichthe
privatememberwasdeclared.Let’smakeasmallchangetotheRooclassfromanearlierexample:
ThedoRooThings()methodisnowprivate,sonootherclasscanuseit.Ifwetrytoinvokethe
methodfromanyotherclass,we’llrunintotrouble:
IfwetrytocompileUseARoo,wegetacompilererrorsomethinglikethis:
cannotfindsymbol
symbol:methoddoRooThings()
It’sasifthemethoddoRooThings()doesn’texist,andasfarasanycodeoutsideoftheRooclassis
concerned,thisistrue.Aprivatememberisinvisibletoanycodeoutsidethemember’sownclass.
Whataboutasubclassthattriestoinheritaprivatememberofitssuperclass?Whenamemberis
declaredprivate,asubclasscan’tinheritit.Fortheexam,youneedtorecognizethatasubclasscan’t
see,use,oreventhinkabouttheprivatemembersofitssuperclass.Youcan,however,declarea
matchingmethodinthesubclass.Butregardlessofhowitlooks,itisnotanoverridingmethod!Itis
simplyamethodthathappenstohavethesamenameasaprivatemethod(whichyou’renotsupposedto
knowabout)inthesuperclass.Therulesofoverridingdonotapply,soyoucanmakethisnewly-
declared-but-just-happens-to-matchmethoddeclarenewexceptions,orchangethereturntype,ordo
anythingelseyouwantittodo.
ThedoRooThings()methodisnowofflimitstoallsubclasses,eventhoseinthesamepackageasthe
superclass:
IfwetrytocompilethesubclassCloo,thecompilerisdelightedtospitoutanerrorsomethinglike
this:
Canaprivatemethodbeoverriddenbyasubclass?That’saninterestingquestion,buttheansweris
no.Becausethesubclass,aswe’veseen,cannotinheritaprivatemethod,it,therefore,cannotoverride
themethod—overridingdependsoninheritance.We’llcovertheimplicationsofthisinmoredetailalittle
laterinthissectionaswellasinChapter2,butfornow,justrememberthatamethodmarkedprivate
cannotbeoverridden.Figure1-3illustratestheeffectsofthepublicandprivatemodifiersonclasses
fromthesameordifferentpackages.
FIGURE1-3 Effectsofpublicandprivateaccess
ProtectedandDefaultMembers
Note:Justareminder,inthenextseveralsections,whenweusetheword“default,”we’retalkingabout
accesscontrol.We’reNOTtalkingaboutthenewkindofJava8interfacemethodthatcanbedeclared
default.
Theprotectedanddefaultaccesscontrollevelsarealmostidentical,butwithonecriticaldifference.
Adefaultmembermaybeaccessedonlyiftheclassaccessingthememberbelongstothesamepackage,
whereasaprotectedmembercanbeaccessed(throughinheritance)byasubclassevenifthesubclass
isinadifferentpackage.Takealookatthefollowingtwoclasses:
Inanothersourcecodefileyouhavethefollowing:
Asyoucansee,thetestIt()methodinthefirstfilehasdefault(thinkpackage-level)access.Notice
alsothatclassOtherClassisinadifferentpackagefromtheAccessClass.WillAccessClassbeable
tousethemethodtestIt()?Willitcauseacompilererror?WillDanielevermarryFrancesca?Stay
tuned.
NomethodmatchingtestIt()foundinclass
certification.OtherClass.o.testIt();
Fromtheprecedingresults,youcanseethatAccessClasscan’tusetheOtherClassmethod
testIt()becausetestIt()hasdefaultaccessandAccessClassisnotinthesamepackageas
OtherClass.SoAccessClasscan’tseeit,thecompilercomplains,andwehavenoideawhoDanieland
Francescaare.
Defaultandprotectedbehaviordifferonlywhenwetalkaboutsubclasses.Iftheprotectedkeyword
isusedtodefineamember,anysubclassoftheclassdeclaringthemembercanaccessitthrough
inheritance.Itdoesn’tmatterifthesuperclassandsubclassareindifferentpackages;theprotected
superclassmemberisstillvisibletothesubclass(althoughvisibleonlyinaveryspecificway,aswe’ll
seealittlelater).Thisisincontrasttothedefaultbehavior,whichdoesn’tallowasubclasstoaccessa
superclassmemberunlessthesubclassisinthesamepackageasthesuperclass.
Whereasdefaultaccessdoesn’textendanyspecialconsiderationtosubclasses(you’reeitherinthe
packageoryou’renot),theprotectedmodifierrespectstheparent-childrelationship,evenwhenthe
childclassmovesaway(andjoinsanewpackage).Sowhenyouthinkofdefaultaccess,thinkpackage
restriction.Noexceptions.Butwhenyouthinkprotected,thinkpackage+kids.Aclasswitha
protectedmemberismarkingthatmemberashavingpackage-levelaccessforallclasses,butwitha
specialexceptionforsubclassesoutsidethepackage.
Butwhatdoesitmeanforasubclass-outside-the-packagetohaveaccesstoasuperclass(parent)
member?Itmeansthesubclassinheritsthemember.Itdoesnot,however,meanthesubclass-outside-the-
packagecanaccessthememberusingareferencetoaninstanceofthesuperclass.Inotherwords,
protected=inheritance.Protecteddoesnotmeanthatthesubclasscantreattheprotectedsuperclass
memberasthoughitwerepublic.Soifthesubclass-outside-the-packagegetsareferencetothesuperclass
(by,forexample,creatinganinstanceofthesuperclasssomewhereinthesubclass’scode),thesubclass
cannotusethedotoperatoronthesuperclassreferencetoaccesstheprotectedmember.Toasubclass-
outside-the-package,aprotectedmembermightaswellbedefault(orevenprivate),whenthe
subclassisusingareferencetothesuperclass.Thesubclasscanseetheprotectedmemberonly
throughinheritance.
Areyouconfused?Hanginthereanditwillallbecomeclearerwiththenextbatchofcodeexamples.
ProtectedDetails
Let’stakealookataprotectedinstancevariable(remember,aninstancevariableisamember)ofa
superclass.
Theprecedingcodedeclaresthevariablexasprotected.Thismakesthevariableaccessibletoall
otherclassesinsidethecertificationpackage,aswellasinheritablebyanysubclassesoutsidethe
package.
Nowlet’screateasubclassinadifferentpackageandattempttousethevariablex(thatthesubclass
inherits):
Theprecedingcodecompilesfine.Notice,though,thattheChildclassisaccessingtheprotected
variablethroughinheritance.Rememberthatanytimewetalkaboutasubclasshavingaccesstoa
superclassmember,wecouldbetalkingaboutthesubclassinheritingthemember,notsimplyaccessing
thememberthroughareferencetoaninstanceofthesuperclass(thewayanyothernonsubclasswould
accessit).WatchwhathappensifthesubclassChild(outsidethesuperclass’spackage)triestoaccessa
protectedvariableusingaParentclassreference:
Thecompilerismorethanhappytoshowustheproblem:
Sofar,we’veestablishedthataprotectedmemberhasessentiallypackage-levelordefaultaccessto
allclassesexceptforsubclasses.We’veseenthatsubclassesoutsidethepackagecaninheritaprotected
member.Finally,we’veseenthatsubclassesoutsidethepackagecan’tuseasuperclassreferenceto
accessaprotectedmember.Forasubclassoutsidethepackage,theprotectedmembercanbe
accessedonlythroughinheritance.
Butthere’sstillonemoreissuewehaven’tlookedat:Whatdoesaprotectedmemberlookliketo
otherclassestryingtousethesubclass-outside-the-packagetogettothesubclass’sinheritedprotected
superclassmember?Forexample,usingourpreviousParent/Childclasses,whathappensifsomeother
class—Neighbor,say—inthesamepackageastheChild(subclass)hasareferencetoaChildinstance
andwantstoaccessthemembervariablex?Inotherwords,howdoesthatprotectedmemberbehave
oncethesubclasshasinheritedit?DoesitmaintainitsprotectedstatussuchthatclassesintheChild’s
packagecanseeit?
No!Oncethesubclass-outside-the-packageinheritstheprotectedmember,thatmember(asinherited
bythesubclass)becomesprivatetoanycodeoutsidethesubclass,withtheexceptionofsubclassesofthe
subclass.SoifclassNeighborinstantiatesaChildobject,thenevenifclassNeighborisinthesame
packageasclassChild,classNeighborwon’thaveaccesstotheChild’sinherited(butprotected)
variablex.Figure1-4illustratestheeffectofprotectedaccessonclassesandsubclassesinthesameor
differentpackages.
Whew!Thatwrapsupprotected,themostmisunderstoodmodifierinJava.Again,it’susedonlyin
veryspecialcases,butyoucancountonitshowingupontheexam.Nowthatwe’vecoveredthe
protectedmodifier,we’llswitchtodefaultmemberaccess,apieceofcakecomparedtoprotected.
FIGURE1-4 Effectsofprotectedaccess
DefaultDetails
Let’sstartwiththedefaultbehaviorofamemberinasuperclass.We’llmodifytheParent’smemberxto
makeitdefault.
Noticewedidn’tplaceanaccessmodifierinfrontofthevariablex.Rememberthatifyoudon’ttype
anaccessmodifierbeforeaclassormemberdeclaration,theaccesscontrolisdefault,whichmeans
packagelevel.We’llnowattempttoaccessthedefaultmemberfromtheChildclassthatwesawearlier.
WhenwetrytocompiletheChild.javafile,wegetanerrorlikethis:
Thecompilergivesthesameerroraswhenamemberisdeclaredasprivate.ThesubclassChild(ina
differentpackagefromthesuperclassParent)can’tseeorusethedefaultsuperclassmemberx!Now,
whataboutdefaultaccessfortwoclassesinthesamepackage?
Andinthesecondclassyouhavethefollowing:
Theprecedingsourcefilecompilesfine,andtheclassChildrunsanddisplaysthevalueofx.Just
rememberthatdefaultmembersarevisibletosubclassesonlyifthosesubclassesareinthesamepackage
asthesuperclass.
LocalVariablesandAccessModifiers
Canaccessmodifiersbeappliedtolocalvariables?NO!
Thereisneveracasewhereanaccessmodifiercanbeappliedtoalocalvariable,sowatchoutfor
codelikethefollowing:
Youcanbecertainthatanylocalvariabledeclaredwithanaccessmodifierwillnotcompile.Infact,
thereisonlyonemodifierthatcaneverbeappliedtolocalvariables—final.
Thataboutdoesitforourdiscussiononmemberaccessmodifiers.Table1-2showsallthe
combinationsofaccessandvisibility;youreallyshouldspendsometimewithit.Next,we’regoingtodig
intotheother(nonaccess)modifiersthatyoucanapplytomemberdeclarations.
TABLE1-2 DeterminingAccesstoClassMembers
NonaccessMemberModifiers
We’vediscussedmemberaccess,whichreferstowhethercodefromoneclasscaninvokeamethod(or
accessaninstancevariable)fromanotherclass.Thatstillleavesaboatloadofothermodifiersyoucan
useonmemberdeclarations.Twoyou’realreadyfamiliarwith—finalandabstract—becausewe
appliedthemtoclassdeclarationsearlierinthischapter.Butwestillhavetotakeaquicklookat
transient,synchronized,native,strictfp,andthenalonglookattheBigOne,static,muchlater
inthechapter.
We’lllookfirstatmodifiersappliedtomethods,followedbyalookatmodifiersappliedtoinstance
variables.We’llwrapupthissectionwithalookathowstaticworkswhenappliedtovariablesand
methods.
FinalMethods
Thefinalkeywordpreventsamethodfrombeingoverriddeninasubclassandisoftenusedtoenforce
theAPIfunctionalityofamethod.Forexample,theThreadclasshasamethodcalledisAlive()that
checkswhetherathreadisstillactive.IfyouextendtheThreadclass,though,thereisreallynowaythat
youcancorrectlyimplementthismethodyourself(itusesnativecode,foronething),sothedesigners
havemadeitfinal.Justasyoucan’tsubclasstheStringclass(becauseweneedtobeabletotrustin
thebehaviorofaStringobject),youcan’toverridemanyofthemethodsinthecoreclasslibraries.This
can’t-be-overriddenrestrictionprovidesforsafetyandsecurity,butyoushoulduseitwithgreatcaution.
PreventingasubclassfromoverridingamethodstiflesmanyofthebenefitsofOO,includingextensibility
throughpolymorphism.Atypicalfinalmethoddeclarationlookslikethis:
It’slegaltoextendSuperClass,sincetheclassisn’tmarkedfinal,butwecan’toverridethefinal
methodshowSample(),asthefollowingcodeattemptstodo:
Attemptingtocompiletheprecedingcodegivesussomethinglikethis:
FinalArguments
Methodargumentsarethevariabledeclarationsthatappearinbetweentheparenthesesinamethod
declaration.Atypicalmethoddeclarationwithmultipleargumentslookslikethis:
publicRecordgetRecord(intfileNumber,intrecNumber){}
Methodargumentsareessentiallythesameaslocalvariables.Intheprecedingexample,thevariables
fileNumberandrecNumberwillbothfollowalltherulesappliedtolocalvariables.Thismeansthey
canalsohavethemodifierfinal:
publicRecordgetRecord(intfileNumber,finalintrecNumber){}
Inthisexample,thevariablerecNumberisdeclaredasfinal,which,ofcourse,meansitcan’tbe
modifiedwithinthemethod.Inthiscase,“modified”meansreassigninganewvaluetothevariable.In
otherwords,afinalparametermustkeepthesamevalueastheargumenthadwhenitwaspassedinto
themethod.
AbstractMethods
Anabstractmethodisamethodthat’sbeendeclared(asabstract)butnotimplemented.Inother
words,themethodcontainsnofunctionalcode.Andifyourecallfromtheearliersection“Abstract
Classes,”anabstractmethoddeclarationdoesn’tevenhavecurlybracesforwheretheimplementation
codegoes,butinsteadcloseswithasemicolon.Inotherwords,ithasnomethodbody.Youmarka
methodabstractwhenyouwanttoforcesubclassestoprovidetheimplementation.Forexample,ifyou
writeanabstractclassCarwithamethodgoUpHill(),youmightwanttoforceeachsubtypeofCarto
defineitsowngoUpHill()behavior,specifictothatparticulartypeofcar.
publicabstractvoidshowSample();
Noticethattheabstractmethodendswithasemicoloninsteadofcurlybraces.Itisillegaltohave
evenasingleabstractmethodinaclassthatisnotexplicitlydeclaredabstract!Lookatthe
followingillegalclass:
Youcan,however,haveanabstractclasswithnoabstractmethods.Thefollowingexamplewill
compilefine:
Intheprecedingexample,goodMethod()isnotabstract.Threedifferentcluestellyouit’snotan
abstractmethod:
Themethodisnotmarkedabstract.
Themethoddeclarationincludescurlybraces,asopposedtoendinginasemicolon.Inother
words,themethodhasamethodbody.
Themethodmightprovideactualimplementationcodeinsidethecurlybraces.
Anyclassthatextendsanabstractclassmustimplementallabstractmethodsofthesuperclass,
unlessthesubclassisalsoabstract.Theruleisthis:
Thefirstconcretesubclassofanabstractclassmustimplementallabstractmethodsofthe
superclass.
Concretejustmeansnonabstract,soifyouhaveanabstractclassextendinganotherabstractclass,
theabstractsubclassdoesn’tneedtoprovideimplementationsfortheinheritedabstractmethods.
Soonerorlater,though,somebody’sgoingtomakeanonabstractsubclass(inotherwords,aclassthatcan
beinstantiated),andthatsubclasswillhavetoimplementalltheabstractmethodsfromupthe
inheritancetree.Thefollowingexampledemonstratesaninheritancetreewithtwoabstractclassesand
oneconcreteclass:
SohowmanymethodsdoesclassMinihave?Three.ItinheritsboththegetType()and
doCarThings()methodsbecausethey’republicandconcrete(nonabstract).ButbecausegoUpHill()is
abstractinthesuperclassVehicleandisneverimplementedintheCarclass(soitremainsabstract),
itmeansclassMini—asthefirstconcreteclassbelowVehicle—mustimplementthegoUpHill()
method.Inotherwords,classMinican’tpassthebuck(ofabstractmethodimplementation)tothenext
classdowntheinheritancetree,butclassCarcan,sinceCar,likeVehicle,isabstract.Figure1-5
illustratestheeffectsoftheabstractmodifieronconcreteandabstractsubclasses.
FIGURE1-5 Theeffectsoftheabstractmodifieronconcreteandabstractsubclasses
Lookforconcreteclassesthatdon’tprovidemethodimplementationsforabstractmethodsofthe
superclass.Thefollowingcodewon’tcompile:
ClassBwon’tcompilebecauseitdoesn’timplementtheinheritedabstractmethodfoo().Although
thefoo(intI)methodinclassBmightappeartobeanimplementationofthesuperclass’sabstract
method,itissimplyanoverloadedmethod(amethodusingthesameidentifier,butdifferentarguments),
soitdoesn’tfulfilltherequirementsforimplementingthesuperclass’sabstractmethod.We’lllookat
thedifferencesbetweenoverloadingandoverridingindetailinChapter2.
Amethodcannever,ever,everbemarkedasbothabstractandfinal,orbothabstractand
private.Thinkaboutit—abstractmethodsmustbeimplemented(whichessentiallymeansoverridden
byasubclass),whereasfinalandprivatemethodscannoteverbeoverriddenbyasubclass.Orto
phraseitanotherway,anabstractdesignationmeansthesuperclassdoesn’tknowanythingabouthow
thesubclassesshouldbehaveinthatmethod,whereasafinaldesignationmeansthesuperclassknows
everythingabouthowallsubclasses(howeverfardowntheinheritancetreetheymaybe)shouldbehave
inthatmethod.Theabstractandfinalmodifiersarevirtuallyopposites.Becauseprivatemethods
cannotevenbeseenbyasubclass(letaloneinherited),they,too,cannotbeoverridden,sothey,too,
cannotbemarkedabstract.
Finally,youneedtoknowthat—fortop-levelclasses—theabstractmodifiercanneverbecombined
withthestaticmodifier.We’llcoverstaticmethodslaterinthisobjective,butfornowjustremember
thatthefollowingwouldbeillegal:
abstractstaticvoiddoStuff();
Anditwouldgiveyouanerrorthatshouldbefamiliarbynow:
MyClass.java:2:illegalcombinationofmodifiers:abstractandstatic
abstractstaticvoiddoStuff();
SynchronizedMethods
Thesynchronizedkeywordindicatesthatamethodcanbeaccessedbyonlyonethreadatatime.When
youarestudyingforyourOCP8,you’llstudythesynchronizedkeywordextensively,butfornow...all
we’reconcernedwithisknowingthatthesynchronizedmodifiercanbeappliedonlytomethods—not
variables,notclasses,justmethods.Atypicalsynchronizeddeclarationlookslikethis:
publicsynchronizedRecordretrieveUserInfo(intid){}
Youshouldalsoknowthatthesynchronizedmodifiercanbematchedwithanyofthefouraccess
controllevels(whichmeansitcanbepairedwithanyofthethreeaccessmodifierkeywords).
NativeMethods
Thenativemodifierindicatesthatamethodisimplementedinplatform-dependentcode,ofteninC.You
don’tneedtoknowhowtousenativemethodsfortheexam,otherthanknowingthatnativeisa
modifier(thusareservedkeyword)andthatnativecanbeappliedonlytomethods—notclasses,not
variables,justmethods.Notethatanativemethod’sbodymustbeasemicolon(;)(likeabstract
methods),indicatingthattheimplementationisomitted.
StrictfpMethods
Welookedearlieratusingstrictfpasaclassmodifier,butevenifyoudon’tdeclareaclassas
strictfp,youcanstilldeclareanindividualmethodasstrictfp.Remember,strictfpforcesfloating
points(andanyfloating-pointoperations)toadheretotheIEEE754standard.Withstrictfp,youcan
predicthowyourfloatingpointswillbehaveregardlessoftheunderlyingplatformtheJVMisrunningon.
Thedownsideisthatiftheunderlyingplatformiscapableofsupportinggreaterprecision,astrictfp
methodwon’tbeabletotakeadvantageofit.
You’llwanttostudytheIEEE754ifyouneedsomethingtohelpyoufallasleep.Fortheexam,
however,youdon’tneedtoknowanythingaboutstrictfpotherthanwhatit’susedfor—thatitcan
modifyaclassormethoddeclaration,andthatavariablecanneverbedeclaredstrictfp.
MethodswithVariableArgumentLists(var-args)
Javaallowsyoutocreatemethodsthatcantakeavariablenumberofarguments.Dependingonwhereyou
look,youmighthearthiscapabilityreferredtoas“variable-lengthargumentlists,”“variablearguments,”
“var-args,”“varargs,”orourpersonalfavorite(fromthedepartmentofobfuscation),“variablearity
parameters.”They’reallthesamething,andwe’llusetheterm“var-args”fromhereonout.
Asabitofbackground,we’dliketoclarifyhowwe’regoingtousetheterms“argument”and
“parameter”throughoutthisbook:
argumentsThethingsyouspecifybetweentheparentheseswhenyou’reinvokingamethod:
parametersThethingsinthemethod’ssignaturethatindicatewhatthemethodmustreceive
whenit’sinvoked:
Let’sreviewthedeclarationrulesforvar-args:
Var-argtypeWhenyoudeclareavar-argparameter,youmustspecifythetypeofthe
argument(s)thisparameterofyourmethodcanreceive.(Thiscanbeaprimitivetypeoranobject
type.)
BasicsyntaxTodeclareamethodusingavar-argparameter,youfollowthetypewithan
ellipsis(...),aspace,andthenthenameofthearraythatwillholdtheparametersreceived.
OtherparametersIt’slegaltohaveotherparametersinamethodthatusesavar-arg.
Var-arglimitsThevar-argmustbethelastparameterinthemethod’ssignature,andyou
canhaveonlyonevar-arginamethod.
Let’slookatsomelegalandillegalvar-argdeclarations:
Legal:
Illegal:
ConstructorDeclarations
InJava,objectsareconstructed.Everytimeyoumakeanewobject,atleastoneconstructorisinvoked.
Everyclasshasaconstructor,althoughifyoudon’tcreateoneexplicitly,thecompilerwillbuildonefor
you.Therearetonsofrulesconcerningconstructors,andwe’resavingourdetaileddiscussionfor
Chapter2.Fornow,let’sfocusonthebasicdeclarationrules.Here’sasimpleexample:
Thefirstthingtonoticeisthatconstructorslookanawfullotlikemethods.Akeydifferenceisthata
constructorcan’tever,ever,ever,haveareturntype…ever!Constructordeclarationscan,however,have
allofthenormalaccessmodifiers,andtheycantakearguments(includingvar-args),justlikemethods.
TheotherBIGRULEtounderstandaboutconstructorsisthattheymusthavethesamenameastheclassin
whichtheyaredeclared.Constructorscan’tbemarkedstatic(theyare,afterall,associatedwithobject
instantiation),andtheycan’tbemarkedfinalorabstract(becausetheycan’tbeoverridden).Hereare
somelegalandillegalconstructordeclarations:
VariableDeclarations
TherearetwotypesofvariablesinJava:
PrimitivesAprimitivecanbeoneofeighttypes:char,boolean,byte,short,int,long,
double,orfloat.Onceaprimitivehasbeendeclared,itsprimitivetypecanneverchange,
althoughinmostcasesitsvaluecanchange.
ReferencevariablesAreferencevariableisusedtoreferto(oraccess)anobject.A
referencevariableisdeclaredtobeofaspecifictype,andthattypecanneverbechanged.A
referencevariablecanbeusedtorefertoanyobjectofthedeclaredtypeorofasubtypeofthe
declaredtype(acompatibletype).We’lltalkalotmoreaboutusingareferencevariabletoreferto
asubtypeinChapter2,whenwediscusspolymorphism.
DeclaringPrimitivesandPrimitiveRanges
Primitivevariablescanbedeclaredasclassvariables(statics),instancevariables,methodparameters,
orlocalvariables.Youcandeclareoneormoreprimitives,ofthesameprimitivetype,inasingleline.In
Chapter3wewilldiscussthevariouswaysinwhichtheycanbeinitialized,butfornowwe’llleaveyou
withafewexamplesofprimitivevariabledeclarations:
OnpreviousversionsoftheexamyouneededtoknowhowtocalculaterangesforalltheJava
primitives.Forthecurrentexam,youcanskipsomeofthatdetail,butit’sstillimportanttounderstandthat
fortheintegertypesthesequencefromsmalltobigisbyte,short,int,andlong,andthatdoublesare
biggerthanfloats.
Youwillalsoneedtoknowthatthenumbertypes(bothintegerandfloating-pointtypes)areallsigned
andhowthataffectstheirranges.First,let’sreviewtheconcepts.
AllsixnumbertypesinJavaaremadeupofacertainnumberof8-bitbytesandaresigned,meaning
theycanbenegativeorpositive.Theleftmostbit(themostsignificantdigit)isusedtorepresentthesign,
wherea1meansnegativeand0meanspositive,asshowninFigure1-6.Therestofthebitsrepresentthe
value,usingtwo’scomplementnotation.
FIGURE1-6 Thesignbitforabyte
TABLE1-3 RangesofNumericPrimitives
Table1-3showstheprimitivetypeswiththeirsizesandranges.Figure1-6showsthatwithabyte,for
example,thereare256possiblenumbers(or28).Halfofthesearenegative,andhalf–1arepositive.The
positiverangeisonelessthanthenegativerangebecausethenumber0isstoredasapositivebinary
number.Weusetheformula–2(bits–1)tocalculatethenegativerange,andweuse2(bits–1)–1forthe
positiverange.Again,ifyouknowthefirsttwocolumnsofthistable,you’llbeingoodshapeforthe
exam.
Therangeforfloating-pointnumbersiscomplicatedtodetermine,butluckilyyoudon’tneedtoknow
thesefortheexam(althoughyouareexpectedtoknowthatadoubleholds64bitsandafloat32).
Thereisnotarangeofbooleanvalues;abooleancanbeonlytrueorfalse.Ifsomeoneasksyou
forthebitdepthofaboolean,lookthemstraightintheeyeandsay,“That’svirtual-machinedependent.”
They’llbeimpressed.
Thechartype(acharacter)containsasingle,16-bitUnicodecharacter.AlthoughtheextendedASCII
setknownasISOLatin-1needsonly8bits(256differentcharacters),alargerrangeisneededto
representcharactersfoundinlanguagesotherthanEnglish.Unicodecharactersareactuallyrepresentedby
unsigned16-bitintegers,whichmeans216possiblevalues,rangingfrom0to65535(216–1).You’lllearn
inChapter3thatbecauseacharisreallyanintegertype,itcanbeassignedtoanynumbertypelarge
enoughtohold65535(whichmeansanythinglargerthanashort;althoughbothcharsandshortsare
16-bittypes,rememberthatashortuses1bittorepresentthesign,sofewerpositivenumbersare
acceptableinashort).
DeclaringReferenceVariables
Referencevariablescanbedeclaredasstaticvariables,instancevariables,methodparameters,orlocal
variables.Youcandeclareoneormorereferencevariables,ofthesametype,inasingleline.InChapter
3wewilldiscussthevariouswaysinwhichtheycanbeinitialized,butfornowwe’llleaveyouwitha
fewexamplesofreferencevariabledeclarations:
InstanceVariables
Instancevariablesaredefinedinsidetheclass,butoutsideofanymethod,andareinitializedonlywhen
theclassisinstantiated.Instancevariablesarethefieldsthatbelongtoeachuniqueobject.Forexample,
thefollowingcodedefinesfields(instancevariables)forthename,title,andmanagerforemployee
objects:
TheprecedingEmployeeclasssaysthateachemployeeinstancewillknowitsownname,title,and
manager.Inotherwords,eachinstancecanhaveitsownuniquevaluesforthosethreefields.Forthe
exam,youneedtoknowthatinstancevariables
Canuseanyofthefouraccesslevels(whichmeanstheycanbemarkedwithanyofthethree
accessmodifiers)
Canbemarkedfinal
Canbemarkedtransient
Cannotbemarkedabstract
Cannotbemarkedsynchronized
Cannotbemarkedstrictfp
Cannotbemarkednative
Cannotbemarkedstaticbecausethenthey’dbecomeclassvariables
We’vealreadycoveredtheeffectsofapplyingaccesscontroltoinstancevariables(itworksthesame
wayasitdoesformembermethods).Alittlelaterinthischapterwe’lllookatwhatitmeanstoapplythe
finalortransientmodifiertoaninstancevariable.First,though,we’lltakeaquicklookatthe
differencebetweeninstanceandlocalvariables.Figure1-7comparesthewayinwhichmodifierscanbe
appliedtomethodsversusvariables.
FIGURE1-7 Comparisonofmodifiersonvariablesvs.methods
Local(Automatic/Stack/Method)Variables
Alocalvariableisavariabledeclaredwithinamethod.Thatmeansthevariableisnotjustinitialized
withinthemethod,butalsodeclaredwithinthemethod.Justasthelocalvariablestartsitslifeinsidethe
method,it’salsodestroyedwhenthemethodhascompleted.Localvariablesarealwaysonthestack,not
theheap.(We’lltalkmoreaboutthestackandtheheapinChapter3.)Althoughthevalueofthevariable
mightbepassedinto,say,anothermethodthatthenstoresthevalueinaninstancevariable,thevariable
itselflivesonlywithinthescopeofthemethod.
Justdon’tforgetthatwhilethelocalvariableisonthestack,ifthevariableisanobjectreference,the
objectitselfwillstillbecreatedontheheap.Thereisnosuchthingasastackobject,onlyastack
variable.You’lloftenhearprogrammersusethephrase“localobject,”butwhattheyreallymeanis,
“locallydeclaredreferencevariable.”Soifyouhearaprogrammerusethatexpression,you’llknowthat
he’sjusttoolazytophraseitinatechnicallypreciseway.Youcantellhimwesaidthat—unlessheknows
wherewelive.
Localvariabledeclarationscan’tusemostofthemodifiersthatcanbeappliedtoinstancevariables,
suchaspublic(ortheotheraccessmodifiers),transient,volatile,abstract,orstatic,butaswe
sawearlier,localvariablescanbemarkedfinal.Andasyou’lllearninChapter3(buthere’sa
preview),beforealocalvariablecanbeused,itmustbeinitializedwithavalue.Forinstance:
Typically,you’llinitializealocalvariableinthesamelineinwhichyoudeclareit,althoughyoumight
stillneedtoreassignitlaterinthemethod.Thekeyistorememberthatalocalvariablemustbe
initializedbeforeyoutrytouseit.Thecompilerwillrejectanycodethattriestousealocalvariablethat
hasn’tbeenassignedavaluebecause—unlikeinstancevariables—localvariablesdon’tgetdefault
values.
Alocalvariablecan’tbereferencedinanycodeoutsidethemethodinwhichit’sdeclared.Inthe
precedingcodeexample,itwouldbeimpossibletorefertothevariablecountanywhereelseintheclass
exceptwithinthescopeofthemethodlogIn().Again,that’snottosaythatthevalueofcountcan’tbe
passedoutofthemethodtotakeonanewlife.Butthevariableholdingthatvalue,count,can’tbe
accessedoncethemethodiscomplete,asthefollowingillegalcodedemonstrates:
Itispossibletodeclarealocalvariablewiththesamenameasaninstancevariable.It’sknownas
shadowing,asthefollowingcodedemonstrates:
WhyonEarth(ortheplanetofyourchoice)wouldyouwanttodothat?Normally,youwon’t.Butone
ofthemorecommonreasonsistonameaparameterwiththesamenameastheinstancevariabletowhich
theparameterwillbeassigned.
Thefollowing(wrong)codeistryingtosetaninstancevariable’svalueusingaparameter:
Soyou’vedecidedthat—foroverallreadability—youwanttogivetheparameterthesamenameasthe
instancevariableitsvalueisdestinedfor,buthowdoyouresolvethenamingcollision?Usethekeyword
this.Thekeywordthisalways,always,alwaysreferstotheobjectcurrentlyrunning.Thefollowing
codeshowsthisinaction:
ArrayDeclarations
InJava,arraysareobjectsthatstoremultiplevariablesofthesametypeorvariablesthatareall
subclassesofthesametype.Arrayscanholdeitherprimitivesorobjectreferences,butanarrayitself
willalwaysbeanobjectontheheap,evenifthearrayisdeclaredtoholdprimitiveelements.Inother
words,thereisnosuchthingasaprimitivearray,butyoucanmakeanarrayofprimitives.
Fortheexam,youneedtoknowthreethings:
Howtomakeanarrayreferencevariable(declare)
Howtomakeanarrayobject(construct)
Howtopopulatethearraywithelements(initialize)
Forthisobjective,youonlyneedtoknowhowtodeclareanarray;we’llcoverconstructingand
initializingarraysinChapter5.
Arraysareefficient,butmanytimesyou’llwanttouseoneoftheCollectiontypesfromjava.util
(includingHashMap,ArrayList,andTreeSet).Collectionclassesoffermoreflexiblewaysto
accessanobject(forinsertion,deletion,reading,andsoon)and,unlikearrays,canexpandor
contractdynamicallyasyouaddorremoveelements.ThereareCollectiontypesforawiderangeof
needs.Doyouneedafastsort?Agroupofobjectswithnoduplicates?Awaytoaccessaname-value
pair?JavaprovidesawidevarietyofCollectiontypestoaddressthesesituations,buttheonly
CollectiontypeontheexamisArrayList,andChapter5discussesArrayListinmoredetail.
Arraysaredeclaredbystatingthetypeofelementsthearraywillhold(anobjectoraprimitive),
followedbysquarebracketstoeithersideoftheidentifier.
DeclaringanArrayofPrimitives:
DeclaringanArrayofObjectReferences:
Whendeclaringanarrayreference,youshouldalwaysputthearraybracketsimmediatelyafterthe
declaredtype,ratherthanaftertheidentifier(variablename).Thatway,anyonereadingthecode
caneasilytellthat,forexample,keyisareferencetoanintarrayobject,notanintprimitive.
Wecanalsodeclaremultidimensionalarrays,whichare,infact,arraysofarrays.Thiscanbedonein
thefollowingmanner:
String[][][]occupantName;
String[]managerName[];
Thefirstexampleisathree-dimensionalarray(anarrayofarraysofarrays),andthesecondisatwo-
dimensionalarray.Noticeinthesecondexample,wehaveonesquarebracketbeforethevariablename
andoneafter.Thisisperfectlylegaltothecompiler,provingonceagainthatjustbecauseit’slegal
doesn’tmeanit’sright.
Itisneverlegaltoincludethesizeofthearrayinyourdeclaration.Yes,weknowyoucando
thatinsomeotherlanguages,whichiswhyyoumightseeaquestionortwothatincludecode
similartothefollowing:
int[5]scores;
Theprecedingcodewon’tcompile.Remember,theJVMdoesn’tallocatespaceuntilyou
actuallyinstantiatethearrayobject.That’swhensizematters.
InChapter6,we’llspendalotoftimediscussingarrays,howtoinitializeandusethemandhowto
dealwithmultidimensionalarrays…staytuned!
FinalVariables
Declaringavariablewiththefinalkeywordmakesitimpossibletoreassignthatvariableonceithas
beeninitializedwithanexplicitvalue(noticewesaid“explicit”ratherthan“default”).Forprimitives,
thismeansthatoncethevariableisassignedavalue,thevaluecan’tbealtered.Forexample,ifyou
assign10totheintvariablex,thenxisgoingtostay10,forever.Sothat’sstraightforwardfor
primitives,butwhatdoesitmeantohaveafinalobjectreferencevariable?Areferencevariable
markedfinalcanneverbereassignedtorefertoadifferentobject.Thedatawithintheobjectcanbe
modified,butthereferencevariablecannotbechanged.Inotherwords,afinalreferencestillallows
youtomodifythestateoftheobjectitrefersto,butyoucan’tmodifythereferencevariabletomakeit
refertoadifferentobject.Burnthisin:therearenofinalobjects,onlyfinalreferences.We’llexplain
thisinmoredetailinChapter3.
We’venowcoveredhowthefinalmodifiercanbeappliedtoclasses,methods,andvariables.Figure
1-8highlightsthekeypointsanddifferencesofthevariousapplicationsoffinal.
FIGURE1-8 Effectoffinalonvariables,methods,andclasses
TransientVariables
Ifyoumarkaninstancevariableastransient,you’retellingtheJVMtoskip(ignore)thisvariablewhen
youattempttoserializetheobjectcontainingit.SerializationisoneofthecoolestfeaturesofJava;itlets
yousave(sometimescalled“flatten”)anobjectbywritingitsstate(inotherwords,thevalueofits
instancevariables)toaspecialtypeofI/Ostream.Withserialization,youcansaveanobjecttoafileor
evenshipitoverawireforreinflating(deserializing)attheotherendinanotherJVM.Wewerehappy
whenserializationwasaddedtotheexamasofJava5,butwe’resadtosaythatasofJava7,
serializationisnolongerontheexam.
VolatileVariables
ThevolatilemodifiertellstheJVMthatathreadaccessingthevariablemustalwaysreconcileitsown
privatecopyofthevariablewiththemastercopyinmemory.Saywhat?Don’tworryaboutit.Forthe
exam,allyouneedtoknowaboutvolatileisthatitexists.
Thevolatilemodifiermayalsobeappliedtoprojectmanagers!
StaticVariablesandMethods
Note:ThediscussionofstaticinthissectionDOESNOTincludethenewstaticinterfacemethod
discussedearlierinthischapter.Don’tyoujustlovehowtheJava8folksreusedimportantJavaterms?
Thestaticmodifierisusedtocreatevariablesandmethodsthatwillexistindependentlyofany
instancescreatedfortheclass.Allstaticmembersexistbeforeyouevermakeanewinstanceofaclass,
andtherewillbeonlyonecopyofastaticmemberregardlessofthenumberofinstancesofthatclass.
Inotherwords,allinstancesofagivenclasssharethesamevalueforanygivenstaticvariable.We’ll
coverstaticmembersingreatdetailinthenextchapter.
Thingsyoucanmarkasstatic:
Methods
Variables
Aclassnestedwithinanotherclass,butnotwithinamethod(notontheOCA8exam)
Initializationblocks
Thingsyoucan’tmarkasstatic:
Constructors(makesnosense;aconstructorisusedonlytocreateinstances)
Classes(unlesstheyarenested)
Interfaces(unlesstheyarenested)
Methodlocalinnerclasses(notontheOCA8exam)
Innerclassmethodsandinstancevariables(notontheOCA8exam)
Localvariables
CERTIFICATIONOBJECTIVE
DeclareandUseenums(OCAObjective1.2)
1.2DefinethestructureofaJavaclass.
Note:Duringthecreationofthisbook,OracleadjustedsomeoftheobjectivesfortheOCAexam.
We’renot100percentsurethatthetopicofenumsisincludedintheOCAexam,butwe’vedecidedthat
it’sbettertobesafethansorry,sowerecommendthatOCAcandidatesstudythissection.Inanycase,
you’relikelytoencountertheuseofenumsintheJavacodeyouread,solearningaboutthemwillpayoff
regardless.
Declaringenums
Javaletsyourestrictavariabletohavingoneofonlyafewpredefinedvalues—inotherwords,onevalue
fromanenumeratedlist.(Theitemsintheenumeratedlistarecalled,surprisingly,enums.)
Usingenumscanhelpreducethebugsinyourcode.Forinstance,imagineyou’recreatinga
commercial-coffee-establishmentapplication,andinyourcoffeeshopapplication,youmightwantto
restrictyourCoffeeSizeselectionstoBIG,HUGE,andOVERWHELMING.IfyouletanorderforaLARGE
oraGRANDEslipin,itmightcauseanerror.enumstotherescue.Withthefollowingsimpledeclaration,
youcanguaranteethatthecompilerwillstopyoufromassigninganythingtoaCoffeeSizeexceptBIG,
HUGE,orOVERWHELMING:
enumCoffeeSize{BIG,HUGE,OVERWHELMING};
Fromthenon,theonlywaytogetaCoffeeSizewillbewithastatementsomethinglikethis:
CoffeeSizecs=CoffeeSize.BIG;
It’snotrequiredthatenumconstantsbeinallcaps,butborrowingfromtheOraclecodeconventionthat
constantsarenamedincaps,it’sagoodidea.
Thebasiccomponentsofanenumareitsconstants(thatis,BIG,HUGE,andOVERWHELMING),althoughin
aminuteyou’llseethattherecanbealotmoretoanenum.enumscanbedeclaredastheirownseparate
classorasaclassmember;however,theymustnotbedeclaredwithinamethod!
Here’sanexampledeclaringanenumoutsideaclass:
Theprecedingcodecanbepartofasinglefile(or,ingeneral,enumclassescanexistintheirownfile
likeCoffeeSize.java).Butremember,inthiscasethefilemustbenamedCoffeeTest1.javabecause
that’sthenameofthepublicclassinthefile.Thekeypointtorememberisthatanenumthatisn’t
enclosedinaclasscanbedeclaredwithonlythepublicordefaultmodifier,justlikeanon-innerclass.
Here’sanexampleofdeclaringanenuminsideaclass:
Thekeypointstotakeawayfromtheseexamplesarethatenumscanbedeclaredastheirownclassor
enclosedinanotherclass,andthatthesyntaxforaccessinganenum’smembersdependsonwherethe
enumwasdeclared.
ThefollowingisNOTlegal:
Tomakeitmoreconfusingforyou,theJavalanguagedesignersmadeitoptionaltoputasemicolonat
theendoftheenumdeclaration(whennootherdeclarationsforthisenumfollow):
Sowhatgetscreatedwhenyoumakeanenum?Themostimportantthingtorememberisthatenumsare
notStringsorints!EachoftheenumeratedCoffeeSizevaluesisactuallyaninstanceofCoffeeSize.
Inotherwords,BIGisoftypeCoffeeSize.Thinkofanenumasakindofclassthatlookssomething(but
notexactly)likethis:
Noticehoweachoftheenumeratedvalues,BIG,HUGE,andOVERWHELMING,isaninstanceoftype
CoffeeSize.They’rerepresentedasstaticandfinal,which,intheJavaworld,isthoughtofasa
constant.Alsonoticethateachenumvalueknowsitsindexorposition—inotherwords,theorderin
whichenumvaluesaredeclaredmatters.YoucanthinkoftheCoffeeSizeenumsasexistinginanarray
oftypeCoffeeSize,andasyou’llseeinalaterchapter,youcaniteratethroughthevaluesofanenumby
invokingthevalues()methodonanyenumtype.(Don’tworryaboutthatinthischapter.)
DeclaringConstructors,Methods,andVariablesinanenum
Becauseanenumreallyisaspecialkindofclass,youcandomorethanjustlisttheenumeratedconstant
values.Youcanaddconstructors,instancevariables,methods,andsomethingreallystrangeknownasa
constantspecificclassbody.Tounderstandwhyyoumightneedmoreinyourenum,thinkaboutthis
scenario:Imagineyouwanttoknowtheactualsize,inounces,thatmaptoeachofthethreeCoffeeSize
constants.Forexample,youwanttoknowthatBIGis8ounces,HUGEis10ounces,andOVERWHELMINGis
awhopping16ounces.
Youcouldmakesomekindofalookuptableusingsomeotherdatastructure,butthatwouldbeapoor
designandhardtomaintain.Thesimplestwayistotreatyourenumvalues(BIG,HUGE,and
OVERWHELMING)asobjects,eachofwhichcanhaveitsowninstancevariables.Thenyoucanassignthose
valuesatthetimetheenumsareinitializedbypassingavaluetotheenumconstructor.Thistakesalittle
explaining,butfirstlookatthefollowingcode:
whichproduces:
8
BIG8
HUGE10
OVERWHELMING16
Note:Everyenumhasastaticmethod,values(),thatreturnsanarrayoftheenum’svaluesintheorder
they’redeclared.
Thekeypointstorememberaboutenumconstructorsare
YoucanNEVERinvokeanenumconstructordirectly.Theenumconstructorisinvoked
automatically,withtheargumentsyoudefineaftertheconstantvalue.Forexample,BIG(8)invokes
theCoffeeSizeconstructorthattakesanint,passingtheintliteral8totheconstructor.(Behind
thescenes,ofcourse,youcanimaginethatBIGisalsopassedtotheconstructor,butwedon’thave
toknow—orcare—aboutthedetails.)
Youcandefinemorethanoneargumenttotheconstructor,andyoucanoverloadtheenum
constructors,justasyoucanoverloadanormalclassconstructor.Wediscussconstructorsinmuch
moredetailinChapter2.ToinitializeaCoffeeSizewithboththenumberofouncesand,say,alid
type,you’dpasstwoargumentstotheconstructorasBIG(8,“A”),whichmeansyouhavea
constructorinCoffeeSizethattakesbothanintandaString.
And,finally,youcandefinesomethingreallystrangeinanenumthatlookslikeananonymousinner
class.It’sknownasaconstantspecificclassbody,andyouuseitwhenyouneedaparticularconstantto
overrideamethoddefinedintheenum.
Imaginethisscenario:Youwantenumstohavetwomethods—oneforouncesandoneforlidcode(a
String).Nowimaginethatmostcoffeesizesusethesamelidcode,“B”,buttheOVERWHELMINGsizeuses
type“A”.YoucandefineagetLidCode()methodintheCoffeeSizeenumthatreturns“B”,butthenyou
needawaytooverrideitforOVERWHELMING.Youdon’twanttodosomehard-to-maintainif/thencode
inthegetLidCode()method,sothebestapproachmightbetosomehowhavetheOVERWHELMING
constantoverridethegetLidCode()method.
Thislooksstrange,butyouneedtounderstandthebasicdeclarationrules:
CERTIFICATIONSUMMARY
Afterabsorbingthematerialinthischapter,youshouldbefamiliarwithsomeofthenuancesoftheJava
language.Youmayalsobeexperiencingconfusionaroundwhyyoueverwantedtotakethisexaminthe
firstplace.That’snormalatthispoint.Ifyouhearyourselfasking,“WhatwasIthinking?”justliedown
untilitpasses.Wewouldliketotellyouthatitgetseasier…thatthiswasthetoughestchapterandit’sall
downhillfromhere.
Let’sbrieflyreviewwhatyou’llneedtoknowfortheexam:
Therewillbemanyquestionsdealingwithkeywordsindirectly,sobesureyoucanidentifywhichare
keywordsandwhicharen’t.
Youneedtounderstandtherulesassociatedwithcreatinglegalidentifiersandtherulesassociated
withsourcecodedeclarations,includingtheuseofpackageandimportstatements.
Youlearnedthebasicsyntaxforthejavaandjavaccommand-lineprograms.
Youlearnedaboutwhenmain()hassuperpowersandwhenitdoesn’t.
Wecoveredthebasicsofimportandimportstaticstatements.It’stemptingtothinkthatthere’s
moretothemthansavingabitoftyping,butthereisn’t.
Younowhaveagoodunderstandingofaccesscontrolasitrelatestoclasses,methods,andvariables.
You’velookedathowaccessmodifiers(public,protected,andprivate)definetheaccesscontrolof
aclassormember.
Youlearnedthatabstractclassescancontainbothabstractandnonabstractmethods,butthatif
evenasinglemethodismarkedabstract,theclassmustbemarkedabstract.Don’tforgetthata
concrete(nonabstract)subclassofanabstractclassmustprovideimplementationsforalltheabstract
methodsofthesuperclass,butthatanabstractclassdoesnothavetoimplementtheabstractmethods
fromitssuperclass.Anabstractsubclasscan“passthebuck”tothefirstconcretesubclass.
Wecoveredinterfaceimplementation.Rememberthatinterfacescanextendanotherinterface(even
multipleinterfaces),andthatanyclassthatimplementsaninterfacemustimplementallmethodsfromall
theinterfacesintheinheritancetreeoftheinterfacetheclassisimplementing.
You’vealsolookedattheothermodifiers,includingstatic,final,abstract,synchronized,and
soon.You’velearnedhowsomemodifierscanneverbecombinedinadeclaration,suchasmixing
abstractwitheitherfinalorprivate.
KeepinmindthattherearenofinalobjectsinJava.Areferencevariablemarkedfinalcanneverbe
changed,buttheobjectitreferstocanbemodified.You’veseenthatfinalappliedtomethodsmeansa
subclasscan’toverridethem,andwhenappliedtoaclass,thefinalclasscan’tbesubclassed.
Methodscanbedeclaredwithavar-argparameter(whichcantakefromzerotomanyargumentsofthe
declaredtype),butthatyoucanhaveonlyonevar-argpermethod,anditmustbethemethod’slast
parameter.
Makesureyou’refamiliarwiththerelativesizesofthenumericprimitives.Rememberthatwhilethe
valuesofnonfinalvariablescanchange,areferencevariable’stypecanneverchange.
Youalsolearnedthatarraysareobjectsthatcontainmanyvariablesofthesametype.Arrayscanalso
containotherarrays.
Rememberwhatyou’velearnedaboutstaticvariablesandmethods,especiallythatstaticmembers
areper-classasopposedtoper-instance.Don’tforgetthatastaticmethodcan’tdirectlyaccessan
instancevariablefromtheclassit’sinbecauseitdoesn’thaveanexplicitreferencetoanyparticular
instanceoftheclass.
Finally,wecoveredenums.Anenumisasafeandflexiblewaytoimplementconstants.Becausethey
areaspecialkindofclass,enumscanbedeclaredverysimply,ortheycanbequitecomplex—including
suchattributesasmethods,variables,constructors,andaspecialtypeofinnerclasscalledaconstant
specificclassbody.
Beforeyouhurlyourselfatthepracticetest,spendsometimewiththefollowingoptimisticallynamed
“Two-MinuteDrill.”Comebacktothisparticulardrilloftenasyouworkthroughthisbookand
especiallywhenyou’redoingthatlast-minutecramming.Because—andhere’stheadviceyouwished
yourmotherhadgivenyoubeforeyouleftforcollege—it’snotwhatyouknow,it’swhenyouknowit.
Fortheexam,knowingwhatyoucan’tdowiththeJavalanguageisjustasimportantasknowingwhat
youcando.Givethesamplequestionsatry!They’reverysimilartothedifficultyandstructureofthereal
examquestionsandshouldbeaneyeopenerforhowdifficulttheexamcanbe.Don’tworryifyougeta
lotofthemwrong.Ifyoufindatopicthatyouareweakin,spendmoretimereviewingandstudying.Many
programmersneedtwoorthreeseriouspassesthroughachapter(oranindividualobjective)beforethey
cananswerthequestionsconfidently.
TWO-MINUTEDRILL
Rememberthatinthischapter,whenwetalkaboutclasses,we’rereferringtonon-innerclasses,inother
words,top-levelclasses.
JavaFeaturesandBenefits(OCAObjective1.5)
WhileJavaprovidesmanybenefitstoprogrammers,fortheexamyoushouldrememberthat
Javasupportsobject-orientedprogrammingingeneral,encapsulation,automaticmemory
management,alargeAPI(library),built-insecurityfeatures,multiplatformcompatibility,strong
typing,multithreading,anddistributedcomputing.
Identifiers(OCAObjective2.1)
Identifierscanbeginwithaletter,anunderscore,oracurrencycharacter.
Afterthefirstcharacter,identifierscanalsoincludedigits.
Identifierscanbeofanylength.
ExecutableJavaFilesandmain()(OCAObjective1.3)
YoucancompileandexecuteJavaprogramsusingthecommand-lineprogramsjavacand
java,respectively.Bothprogramssupportavarietyofcommand-lineoptions.
Theonlyversionsofmain()methodswithspecialpowersarethoseversionswithmethod
signaturesequivalenttopublicstaticvoidmain(String[]args).
main()canbeoverloaded.
Imports(OCAObjective1.4)
Animportstatement’sonlyjobistosavekeystrokes.
Youcanuseanasterisk(*)tosearchthroughthecontentsofasinglepackage.
Althoughreferredtoas“staticimports,”thesyntaxisimportstatic….
YoucanimportAPIclassesand/orcustomclasses.
SourceFileDeclarationRules(OCAObjective1.2)
Asourcecodefilecanhaveonlyonepublicclass.
Ifthesourcefilecontainsapublicclass,thefilenamemustmatchthepublicclassname.
Afilecanhaveonlyonepackagestatement,butitcanhavemultipleimports.
Thepackagestatement(ifany)mustbethefirst(noncomment)lineinasourcefile.
Theimportstatements(ifany)mustcomeafterthepackagestatement(ifany)andbeforethe
firstclassdeclaration.
Ifthereisnopackagestatement,importstatementsmustbethefirst(noncomment)statements
inthesourcefile.
packageandimportstatementsapplytoallclassesinthefile.
Afilecanhavemorethanonenonpublicclass.
Fileswithnopublicclasseshavenonamingrestrictions.
ClassAccessModifiers(OCAObjective6.4)
Therearethreeaccessmodifiers:public,protected,andprivate.
Therearefouraccesslevels:public,protected,default,andprivate.
Classescanhaveonlypublicordefaultaccess.
Aclasswithdefaultaccesscanbeseenonlybyclasseswithinthesamepackage.
Aclasswithpublicaccesscanbeseenbyallclassesfromallpackages.
Classvisibilityrevolvesaroundwhethercodeinoneclasscan
Createaninstanceofanotherclass
Extend(orsubclass)anotherclass
Accessmethodsandvariablesofanotherclass
ClassModifiers(Nonaccess)(OCAObjectives1.2,7.1,and7.5)
Classescanalsobemodifiedwithfinal,abstract,orstrictfp.
Aclasscannotbebothfinalandabstract.
Afinalclasscannotbesubclassed.
Anabstractclasscannotbeinstantiated.
Asingleabstractmethodinaclassmeansthewholeclassmustbeabstract.
Anabstractclasscanhavebothabstractandnonabstractmethods.
Thefirstconcreteclasstoextendanabstractclassmustimplementallofitsabstract
methods.
InterfaceImplementation(OCAObjective7.5)
Usually,interfacesarecontractsforwhataclasscando,buttheysaynothingaboutthewayin
whichtheclassmustdoit.
Interfacescanbeimplementedbyanyclassfromanyinheritancetree.
Usually,aninterfaceislikea100percentabstractclassandisimplicitlyabstractwhether
ornotyoutypetheabstractmodifierinthedeclaration.
Usuallyinterfaceshaveonlyabstractmethods.
Interfacemethodsarebydefaultpublicandusuallyabstract—explicitdeclarationofthese
modifiersisoptional.
Interfacescanhaveconstants,whicharealwaysimplicitlypublic,static,andfinal.
Interfaceconstantdeclarationsofpublic,static,andfinalareoptionalinany
combination.
AsofJava8,interfacescanhaveconcretemethodsdeclaredaseitherdefaultorstatic.
Note:ThissectionusessomeconceptsthatweHAVENOTyetcovered.Don’tpanic:onceyou’veread
throughallofthebook,thissectionwillmakesenseasareference.
Alegalnonabstractimplementingclasshasthefollowingproperties:
Itprovidesconcreteimplementationsfortheinterface’smethods.
Itmustfollowalllegaloverriderulesforthemethodsitimplements.
Itmustnotdeclareanynewcheckedexceptionsforanimplementationmethod.
Itmustnotdeclareanycheckedexceptionsthatarebroaderthantheexceptionsdeclared
intheinterfacemethod.
Itmaydeclareruntimeexceptionsonanyinterfacemethodimplementationregardlessof
theinterfacedeclaration.
Itmustmaintaintheexactsignature(allowingforcovariantreturns)andreturntypeofthe
methodsitimplements(butdoesnothavetodeclaretheexceptionsoftheinterface).
Aclassimplementinganinterfacecanitselfbeabstract.
Anabstractimplementingclassdoesnothavetoimplementtheinterfacemethods(butthe
firstconcretesubclassmust).
Aclasscanextendonlyoneclass(nomultipleinheritance),butitcanimplementmany
interfaces.
Interfacescanextendoneormoreotherinterfaces.
Interfacescannotextendaclassorimplementaclassorinterface.
Whentakingtheexam,verifythatinterfaceandclassdeclarationsarelegalbeforeverifying
othercodelogic.
MemberAccessModifiers(OCAObjective6.4)
Methodsandinstance(nonlocal)variablesareknownas“members.”
Memberscanuseallfouraccesslevels:public,protected,default,andprivate.
Memberaccesscomesintwoforms:
Codeinoneclasscanaccessamemberofanotherclass.
Asubclasscaninheritamemberofitssuperclass.
Ifaclasscannotbeaccessed,itsmemberscannotbeaccessed.
Determineclassvisibilitybeforedeterminingmembervisibility.
publicmemberscanbeaccessedbyallotherclasses,eveninotherpackages.
Ifasuperclassmemberispublic,thesubclassinheritsit—regardlessofpackage.
Membersaccessedwithoutthedotoperator(.)mustbelongtothesameclass.
this.alwaysreferstothecurrentlyexecutingobject.
this.aMethod()isthesameasjustinvokingaMethod().
privatememberscanbeaccessedonlybycodeinthesameclass.
privatemembersarenotvisibletosubclasses,soprivatememberscannotbeinherited.
Defaultandprotectedmembersdifferonlywhensubclassesareinvolved:
Defaultmemberscanbeaccessedonlybyclassesinthesamepackage.
protectedmemberscanbeaccessedbyotherclassesinthesamepackage,plus
subclasses,regardlessofpackage.
protected=package+kids(kidsmeaningsubclasses).
Forsubclassesoutsidethepackage,theprotectedmembercanbeaccessedonlythrough
inheritance;asubclassoutsidethepackagecannotaccessaprotectedmemberbyusinga
referencetoasuperclassinstance.(Inotherwords,inheritanceistheonlymechanismfora
subclassoutsidethepackagetoaccessaprotectedmemberofitssuperclass.)
Aprotectedmemberinheritedbyasubclassfromanotherpackageisnotaccessibleto
anyotherclassinthesubclasspackage,exceptforthesubclass’sownsubclasses.
LocalVariables(OCAObjectives2.1and6.4)
Local(method,automatic,orstack)variabledeclarationscannothaveaccessmodifiers.
finalistheonlymodifieravailabletolocalvariables.
Localvariablesdon’tgetdefaultvalues,sotheymustbeinitializedbeforeuse.
OtherModifiers—Members(OCAObjectives7.1and7.5)
finalmethodscannotbeoverriddeninasubclass.
abstractmethodsaredeclaredwithasignature,areturntype,andanoptionalthrows
clause,buttheyarenotimplemented.
abstractmethodsendinasemicolon—nocurlybraces.
Threewaystospotanonabstractmethod:
Themethodisnotmarkedabstract.
Themethodhascurlybraces.
ThemethodMIGHThavecodebetweenthecurlybraces.
Thefirstnonabstract(concrete)classtoextendanabstractclassmustimplementallofthe
abstractclass’sabstractmethods.
Thesynchronizedmodifierappliesonlytomethodsandcodeblocks.
synchronizedmethodscanhaveanyaccesscontrolandcanalsobemarkedfinal.
abstractmethodsmustbeimplementedbyasubclass,sotheymustbeinheritable.Forthat
reason
abstractmethodscannotbeprivate.
abstractmethodscannotbefinal.
Thenativemodifierappliesonlytomethods.
Thestrictfpmodifierappliesonlytoclassesandmethods.
Methodswithvar-args(OCAObjective1.2)
Methodscandeclareaparameterthatacceptsfromzerotomanyarguments,aso-calledvar-
argmethod.
Avar-argparameterisdeclaredwiththesyntaxtype...name;forinstance:
doStuff(int...x){}.
Avar-argmethodcanhaveonlyonevar-argparameter.
Inmethodswithnormalparametersandavar-arg,thevar-argmustcomelast.
Constructors(OCAObjectives1.2,and6.3)
Constructorsmusthavethesamenameastheclass
Constructorscanhavearguments,buttheycannothaveareturntype.
Constructorscanuseanyaccessmodifier(evenprivate!).
VariableDeclarations(OCAObjective2.1)
Instancevariablescan
Haveanyaccesscontrol
Bemarkedfinalortransient
Instancevariablescan’tbeabstract,synchronized,native,orstrictfp.
Itislegaltodeclarealocalvariablewiththesamenameasaninstancevariable;thisis
called“shadowing.”
finalvariableshavethefollowingproperties:
finalvariablescannotbereassignedonceassignedavalue.
finalreferencevariablescannotrefertoadifferentobjectoncetheobjecthasbeen
assignedtothefinalvariable.
finalvariablesmustbeinitializedbeforetheconstructorcompletes.
Thereisnosuchthingasafinalobject.AnobjectreferencemarkedfinaldoesNOTmean
theobjectitselfcan’tchange.
Thetransientmodifierappliesonlytoinstancevariables.
Thevolatilemodifierappliesonlytoinstancevariables.
ArrayDeclarations(OCAObjectives4.1and4.2)
Arrayscanholdprimitivesorobjects,butthearrayitselfisalwaysanobject.
Whenyoudeclareanarray,thebracketscanbetotheleftortotherightofthevariablename.
Itisneverlegaltoincludethesizeofanarrayinthedeclaration.
AnarrayofobjectscanholdanyobjectthatpassestheIS-A(orinstanceof)testforthe
declaredtypeofthearray.Forexample,ifHorseextendsAnimal,thenaHorseobjectcangointo
anAnimalarray.
StaticVariablesandMethods(OCAObjective6.2)
Theyarenottiedtoanyparticularinstanceofaclass.
Noclassinstancesareneededinordertousestaticmembersoftheclassorinterface.
Thereisonlyonecopyofastaticvariable/class,andallinstancesshareit.
staticmethodsdonothavedirectaccesstononstaticmembers.
enums(OCAObjective1.2)
Anenumspecifiesalistofconstantvaluesassignedtoatype.
AnenumisNOTaStringoranint;anenumconstant’stypeistheenumtype.Forexample,
SUMMERandFALLareoftheenumtypeSeason.
Anenumcanbedeclaredoutsideorinsideaclass,butNOTinamethod.
AnenumdeclaredoutsideaclassmustNOTbemarkedstatic,final,abstract,
protected,orprivate.
enumscancontainconstructors,methods,variables,andconstant-specificclassbodies.
enumconstantscansendargumentstotheenumconstructor,usingthesyntaxBIG(8),where
theintliteral8ispassedtotheenumconstructor.
enumconstructorscanhaveargumentsandcanbeoverloaded.
enumconstructorscanNEVERbeinvokeddirectlyincode.Theyarealwayscalled
automaticallywhenanenumisinitialized.
Thesemicolonattheendofanenumdeclarationisoptional.Thesearelegal:
enumFoo{ONE,TWO,THREE}enumFoo{ONE,TWO,THREE};
MyEnum.values()returnsanarrayofMyEnum’svalues.
SELFTEST
Thefollowingquestionswillhelpyoumeasureyourunderstandingofthematerialpresentedinthis
chapter.Readallthechoicescarefully,astheremaybemorethanonecorrectanswer.Chooseallcorrect
answersforeachquestion.Stayfocused.
Ifyouhavearoughtimewiththeseatfirst,don’tbeatyourselfup.Bepositive.Repeatnice
affirmationstoyourselflike,“Iamsmartenoughtounderstandenums”and“OK,sothatotherguyknows
enumsbetterthanIdo,butIbethecan’t<insertsomethingyouaregoodat>likeme.”
1.Whicharetrue?(Chooseallthatapply.)
A.“XextendsY”iscorrectifandonlyifXisaclassandYisaninterface
B.“XextendsY”iscorrectifandonlyifXisaninterfaceandYisaclass
C.“XextendsY”iscorrectifXandYareeitherbothclassesorbothinterfaces
D.“XextendsY”iscorrectforallcombinationsofXandYbeingclassesand/orinterfaces
2.Given:
Whicharetrue?(Chooseallthatapply.)
A.Asthecodestands,theoutputisbang
B.Asthecodestands,theoutputissh-bang
C.Asthecodestands,compilationfails
D.IflineAisuncommented,theoutputisbangbang
E.IflineAisuncommented,theoutputissh-bangbang
F.IflineAisuncommented,compilationfails.
3.Giventhattheforloop’ssyntaxiscorrect,andgiven:
Andthecommandline:
java_-A.
Whatistheresult?
A.-A
B.A.
C.-A.
D._A.
E._-A.
F.Compilationfails
G.Anexceptionisthrownatruntime
4.Given:
Whatistheresult?
A.woofburble
B.Multiplecompilationerrors
C.Compilationfailsduetoanerroronline2
D.Compilationfailsduetoanerroronline3
E.Compilationfailsduetoanerroronline4
F.Compilationfailsduetoanerroronline9
5.Giventwofiles:
Whatistheresult?(Chooseallthatapply.)
A.567
B.5followedbyanexception
C.Compilationfailswithanerroronline7
D.Compilationfailswithanerroronline8
E.Compilationfailswithanerroronline9
F.Compilationfailswithanerroronline10
6.Given:
Whatistheresult?(Chooseallthatapply.)
A.Compilationsucceeds
B.Compilationfailswithanerroronline1
C.Compilationfailswithanerroronline3
D.Compilationfailswithanerroronline5
E.Compilationfailswithanerroronline7
F.Compilationfailswithanerroronline9
7.Given:
Whatistheresult?(Chooseallthatapply.)
A.Compilationsucceeds
B.Compilationfailswithanerroronline6
C.Compilationfailswithanerroronline7
D.Compilationfailswithanerroronline8
E.Compilationfailswithanerroronline9
8.Given:
Whatistheresult?(Chooseallthatapply.)
A.TUE
B.WED
C.Theoutputisunpredictable
D.Compilationfailsduetoanerroronline4
E.Compilationfailsduetoanerroronline6
F.Compilationfailsduetoanerroronline8
G.Compilationfailsduetoanerroronline9
9.Given:
Whatistheresult?
A.13
B.Compilationfailsduetomultipleerrors
C.Compilationfailsduetoanerroronline6
D.Compilationfailsduetoanerroronline7
E.Compilationfailsduetoanerroronline11
10.Given:
Whicharetrue?(Chooseallthatapply.)
A.TheclassTabletwillNOTcompile
B.TheinterfaceGadgetwillNOTcompile
C.Theoutputwillbepluginshowbook
D.TheabstractclassElectronicwillNOTcompile
E.TheclassTabletCANNOTbothextendandimplement
11.GiventhattheIntegerclassisinthejava.langpackageandgiven:
Which,insertedindependentlyatline1,compiles?(Chooseallthatapply.)
A.importstaticjava.lang;
B.importstaticjava.lang.Integer;
C.importstaticjava.lang.Integer.*;
D.staticimportjava.lang.Integer.*;
E.importstaticjava.lang.Integer.MAX_VALUE;
F.Noneoftheabovestatementsarevalidimportsyntax
12.Given:
Whichlinesofcode—insertedindependentlyatinsertcodehere—willcompile?(Chooseall
thatapply.)
A.publicstaticm1(){;}
B.defaultvoidm2(){;}
C.abstractintm3();
D.finalshortm4(){return5;}
E.defaultlongm5();
F.staticvoidm6(){;}
13.Whicharetrue?(Chooseallthatapply.)
A.Javaisadynamicallytypedprogramminglanguage
B.Javaprovidesfine-grainedcontrolofmemorythroughtheuseofpointers
C.Javaprovidesprogrammerstheabilitytocreateobjectsthatarewellencapsulated
D.JavaprovidesprogrammerstheabilitytosendJavaobjectsfromonemachinetoanother
E.JavaisanimplementationoftheECMAstandard
F.Java’sencapsulationcapabilitiesprovideitsprimarysecuritymechanism
SELFTESTANSWERS
1. Ciscorrect.
Aisincorrectbecauseclassesimplementinterfaces,theydon’textendthem.Bisincorrect
becauseinterfacesonly“inheritfrom”otherinterfaces.Disincorrectbasedontheprecedingrules.
(OCAObjective7.5)
2. BandFarecorrect.SinceRocket.blastOff()isprivate,itcan’tbeoverridden,andit
isinvisibletoclassShuttle.
A,C,D,andEareincorrectbasedontheabove.(OCAObjective6.4)
3. Biscorrect.Thisquestionisusingvalid(butinappropriateandweird)identifiers,static
imports,main(),andpre-incrementinglogic.(Note:Youmightgetacompilerwarningwhen
compilingthiscode.)
A,C,D,E,F,andGareincorrectbasedontheabove.(OCAObjective1.2)
4. Aiscorrect;enumscanhaveconstructorsandvariables.
B,C,D,E,andFareincorrect;theselinesallusecorrectsyntax.(OCAObjective1.2)
5. DandEarecorrect.Variableahasdefaultaccess,soitcannotbeaccessedfromoutside
thepackage.VariablebhasprotectedaccessinpkgA.
A,B,C,andFareincorrectbasedontheaboveinformation.(OCAObjectives1.4and6.5)
6. Aiscorrect;allofthesearelegaldeclarations.
B,C,D,E,andFareincorrectbasedontheaboveinformation.(OCAObjective7.5)
7. CandDarecorrect.Variablenamescannotbeginwitha#,andanarraydeclarationcan’t
includeasizewithoutaninstantiation.Therestofthecodeisvalid.
A,B,andEareincorrectbasedontheabove.(OCAObjective2.1)
8. Biscorrect.Everyenumcomeswithastaticvalues()methodthatreturnsanarrayof
theenum’svaluesintheorderinwhichtheyaredeclaredintheenum.
A,C,D,E,F,andGareincorrectbasedontheaboveinformation.(OCPObjective1.2)
9. Discorrect.ThecountGold()methodcannotbeinvokedfromastaticcontext.
A,B,C,andEareincorrectbasedontheaboveinformation.(OCAObjective6.2)
10. Aiscorrect.Bydefault,aninterface’smethodsarepublicsotheTablet.doStuff
methodmustbepublic,too.Therestofthecodeisvalid.
B,C,D,andEareincorrectbasedontheabove.(OCAObjective7.5)
11. CandEarecorrectsyntaxforstaticimports.Line4isn’tmakinguseofstaticimports,
sothecodewillalsocompilewithnoneoftheimports.
A,B,D,andFareincorrectbasedontheabove.(OCAObjective1.4)
12. B,C,andFarecorrect.AsofJava8,interfacescanhavedefaultandstaticmethods.
A,D,andEareincorrect.Ahasnoreturntype;Dcannothaveamethodbody;andEneedsa
methodbody.(OCAObjective7.5)
13. CandDarecorrect.
AisincorrectbecauseJavaisastaticallytypedlanguage.Bisincorrectbecauseitdoesnot
providepointers.EisincorrectbecauseJavaScriptisanimplementationoftheECMAstandard,
notJava.FisincorrectbecausetheuseofbytecodeandtheJVMprovideJava’sprimarysecurity
mechanisms.
B
2
ObjectOrientation
CERTIFICATIONOBJECTIVES
•DescribeEncapsulation
•ImplementInheritance
•UseIS-AandHAS-ARelationships(OCP)
•UsePolymorphism
•UseOverridingandOverloading
•UnderstandCasting
•UseInterfaces
•UnderstandandUseReturnTypes
•DevelopConstructors
•UsestaticMembers
Two-MinuteDrill
Q&ASelfTest
einganOracleCertifiedAssociate(OCA)8meansyoumustbeatonewiththeobject-
orientedaspectsofJava.Youmustdreamofinheritancehierarchies;thepowerof
polymorphismmustflowthroughyou;andencapsulationmustbecomesecondnaturetoyou.
(Coupling,cohesion,composition,anddesignpatternswillbecomeyourbreadandbutter
whenyou’reanOracleCertifiedProfessional[OCP]8.)Thischapterwillprepareyouforalltheobject-
orientedobjectivesandquestionsyou’llencounterontheexam.WehaveheardofmanyexperiencedJava
programmerswhohaven’treallybecomefluentwiththeobject-orientedtoolsthatJavaprovides,sowe’ll
startatthebeginning.
CERTIFICATIONOBJECTIVE
Encapsulation(OCAObjectives6.1and6.5)
6.1Createmethodswithargumentsandreturnvalues;includingoverloadedmethods.
6.5Applyencapsulationprinciplestoaclass.
Imagineyouwrotethecodeforaclassandanotherdozenprogrammersfromyourcompanyallwrote
programsthatusedyourclass.Nowimaginethatlateron,youdidn’tlikethewaytheclassbehaved,
becausesomeofitsinstancevariableswerebeingset(bytheotherprogrammersfromwithintheircode)
tovaluesyouhadn’tanticipated.Theircodebroughtouterrorsinyourcode.(Relax,thisisjust
hypothetical.)Well,itisaJavaprogram,soyoushouldbeabletoshipoutanewerversionoftheclass,
whichtheycouldreplaceintheirprogramswithoutchanginganyoftheirowncode.
Thisscenariohighlightstwoofthepromises/benefitsofanobject-oriented(OO)language:flexibility
andmaintainability.Butthosebenefitsdon’tcomeautomatically.Youhavetodosomething.Youhaveto
writeyourclassesandcodeinawaythatsupportsflexibilityandmaintainability.SowhatifJava
supportsOO?Itcan’tdesignyourcodeforyou.Forexample,imagineyoumadeyourclasswithpublic
instancevariables,andthoseotherprogrammersweresettingtheinstancevariablesdirectly,asthe
followingcodedemonstrates:
Andnowyou’reintrouble.Howareyougoingtochangetheclassinawaythatletsyouhandlethe
issuesthatcomeupwhensomebodychangesthesizevariabletoavaluethatcausesproblems?Your
onlychoiceistogobackinandwritemethodcodetoadjustsize(asetSize(inta)method,for
example)andtheninsulatethesizevariablewith,say,aprivateaccessmodifier.Butassoonasyou
makethatchangetoyourcode,youbreakeveryoneelse’s!
Theabilitytomakechangesinyourimplementationcodewithoutbreakingthecodeofotherswhouse
yourcodeisakeybenefitofencapsulation.Youwanttohideimplementationdetailsbehindapublic
programminginterface.Byinterface,wemeanthesetofaccessiblemethodsyourcodemakesavailable
forothercodetocall—inotherwords,yourcode’sAPI.Byhidingimplementationdetails,youcan
reworkyourmethodcode(perhapsalsoalteringthewayvariablesareusedbyyourclass)withoutforcing
achangeinthecodethatcallsyourchangedmethod.
Ifyouwantmaintainability,flexibility,andextensibility(and,ofcourse,youdo),yourdesignmust
includeencapsulation.Howdoyoudothat?
Keepinstancevariableshidden(withanaccessmodifier,oftenprivate).
Makepublicaccessormethods,andforcecallingcodetousethosemethodsratherthan
directlyaccessingtheinstancevariable.Theseso-calledaccessormethodsallowusersofyour
classtosetavariable’svalueorgetavariable’svalue.
Fortheseaccessormethods,usethemostcommonnamingconventionofset<SomeProperty>
andget<SomeProperty>.
Figure2-1illustratestheideathatencapsulationforcescallersofourcodetogothroughmethods
ratherthanaccessingvariablesdirectly.
FIGURE2-1 Thenatureofencapsulation
Wecalltheaccessmethodsgettersandsetters,althoughsomepreferthefanciertermsaccessorsand
mutators.(Personally,wedon’tliketheword“mutate.”)Regardlessofwhatyoucallthem,they’re
methodsthatotherprogrammersmustgothroughinordertoaccessyourinstancevariables.Theylook
simple,andyou’veprobablybeenusingthemforever:
Waitaminute.Howusefulisthepreviouscode?Itdoesn’tevendoanyvalidationorprocessing.What
benefitcantherebefromhavinggettersandsettersthataddnofunctionality?Thepointis,youcanchange
yourmindlaterandaddmorecodetoyourmethodswithoutbreakingyourAPI.Eveniftodayyoudon’t
thinkyoureallyneedvalidationorprocessingofthedata,goodOOdesigndictatesthatyouplanforthe
future.Tobesafe,forcecallingcodetogothroughyourmethodsratherthangoingdirectlytoinstance
variables.Always.Thenyou’refreetoreworkyourmethodimplementationslater,withoutriskingthe
wrathofthosedozenprogrammerswhoknowwhereyoulive.
Note:InChapter6we’llrevisitthetopicofencapsulationasitappliestoinstancevariablesthatare
alsoreferencevariables.It’strickierthanyoumightthink,sostaytuned!(Also,we’llwaituntilChapter6
tochallengeyouwithencapsulation-themedmockquestions.)
Lookoutforcodethatappearstobeaskingaboutthebehaviorofamethod,whentheproblem
isactuallyalackofencapsulation.Lookatthefollowingexample,andseeifyoucanfigure
outwhat’sgoingon:
Nowconsiderthisquestion:Isthevalueofrightalwaysgoingtobeone-thirdthevalueofleft?
Itlookslikeitwill,untilyourealizethatusersoftheFooclassdon’tneedtousethesetLeft()
method!Theycansimplygostraighttotheinstancevariablesandchangethemtoany
arbitraryintvalue.
CERTIFICATIONOBJECTIVE
InheritanceandPolymorphism(OCAObjectives7.1and
7.2)
7.1Describeinheritanceanditsbenefits.
7.2Developcodethatdemonstratestheuseofpolymorphism;includingoverridingandobjecttype
versusreferencetype(sic).
InheritanceiseverywhereinJava.It’ssafetosaythatit’salmost(almost?)impossibletowriteeven
thetiniestJavaprogramwithoutusinginheritance.Toexplorethistopic,we’regoingtousethe
instanceofoperator,whichwe’lldiscussinmoredetailinChapter4.Fornow,justrememberthat
instanceofreturnstrueifthereferencevariablebeingtestedisofthetypebeingcomparedto.This
code
producesthisoutput:
they’renotequal
t1’sanObject
Wheredidthatequalsmethodcomefrom?Thereferencevariablet1isoftypeTest,andthere’sno
equalsmethodintheTestclass.Oristhere?Thesecondiftestaskswhethert1isaninstanceofclass
Object,andbecauseitis(moreonthatsoon),theiftestsucceeds.
Holdon…howcant1beaninstanceoftypeObject,whenwejustsaiditwasoftypeTest?I’msure
you’rewayaheadofushere,butitturnsoutthateveryclassinJavaisasubclassofclassObject(except,
ofcourse,classObjectitself).Inotherwords,everyclassyou’lleveruseoreverwritewillinheritfrom
classObject.You’llalwayshaveanequalsmethod,aclonemethod,notify,wait,andothers
availabletouse.Wheneveryoucreateaclass,youautomaticallyinheritallofclassObject’smethods.
Why?Let’slookatthatequalsmethodforinstance.Java’screatorscorrectlyassumedthatitwouldbe
verycommonforJavaprogrammerstowanttocompareinstancesoftheirclassestocheckforequality.If
classObjectdidn’thaveanequalsmethod,you’dhavetowriteoneyourself—youandeveryotherJava
programmer.Thatoneequalsmethodhasbeeninheritedbillionsoftimes.(Tobefair,equalshasalso
beenoverriddenbillionsoftimes,butwe’regettingaheadofourselves.)
TheEvolutionofInheritance
UpuntilJava8,whenthetopicofinheritancewasdiscussed,itusuallyrevolvedaroundsubclasses
inheritingmethodsfromtheirsuperclasses.Whilethissimplificationwasneverperfectlycorrect,it
becamelesscorrectwiththenewfeaturesavailableinJava8.Asthefollowingtableshows,it’snow
possibletoinheritconcretemethodsfrominterfaces.Thisisabigchange.Fortherestofthechapter,
whenwetalkaboutinheritancegenerally,wewilltendtousetheterms“subtypes”and“supertypes”to
acknowledgethatbothclassesandinterfacesneedtobeaccountedfor.Wewilltendtousetheterms
“subclass”and“superclass”whenwe’rediscussingaspecificexamplethat’sunderdiscussion.
Inheritanceisakeyaspectofmostofthetopicswe’llbediscussinginthischapter,sobepreparedfor
LOTSofdiscussionabouttheinteractionsbetweensupertypesandsubtypes!
Asyoustudythefollowingtable,you’llnoticethatasofJava8interfacescancontaintwotypesof
concretemethods,staticanddefault.We’lldiscusstheseimportantadditionslaterinthischapter.
Table2-1summarizestheelementsofclassesandinterfacesrelativetoinheritance.
TABLE2-1 InheritableElementsofClassesandInterfaces
Fortheexam,you’llneedtoknowthatyoucancreateinheritancerelationshipsinJavabyextendinga
classorbyimplementinganinterface.It’salsoimportanttounderstandthatthetwomostcommonreasons
touseinheritanceare
Topromotecodereuse
Tousepolymorphism
Let’sstartwithreuse.Acommondesignapproachistocreateafairlygenericversionofaclasswith
theintentionofcreatingmorespecializedsubclassesthatinheritfromit.Forexample:
outputs:
displayingshape
movinggamepiece
NoticethatthePlayerPiececlassinheritsthegenericdisplayShape()methodfromtheless-
specializedclassGameShapeandalsoaddsitsownmethod,movePiece().Codereusethrough
inheritancemeansthatmethodswithgenericfunctionality—suchasdisplayShape(),whichcouldapply
toawiderangeofdifferentkindsofshapesinagame—don’thavetobereimplemented.Thatmeansall
specializedsubclassesofGameShapeareguaranteedtohavethecapabilitiesofthemoregeneral
superclass.Youdon’twanttohavetorewritethedisplayShape()codeineachofyourspecialized
componentsofanonlinegame.
Butyouknewthat.You’veexperiencedthepainofduplicatecodewhenyoumakeachangeinone
placeandhavetotrackdownalltheotherplaceswherethatsame(orverysimilar)codeexists.
Thesecond(andrelated)useofinheritanceistoallowyourclassestobeaccessedpolymorphically—
acapabilityprovidedbyinterfacesaswell,butwe’llgettothatinaminute.Let’ssaythatyouhavea
GameLauncherclassthatwantstoloopthroughalistofdifferentkindsofGameShapeobjectsandinvoke
displayShape()oneachofthem.Atthetimeyouwritethisclass,youdon’tknoweverypossiblekindof
GameShapesubclassthatanyoneelsewilleverwrite.Andyousuredon’twanttohavetoredoyourcode
justbecausesomebodydecidedtobuildadiceshapesixmonthslater.
Thebeautifulthingaboutpolymorphism(“manyforms”)isthatyoucantreatanysubclassof
GameShapeasaGameShape.Inotherwords,youcanwritecodeinyourGameLauncherclassthatsays,“I
don’tcarewhatkindofobjectyouareaslongasyouinheritfrom(extend)GameShape.AndasfarasI’m
concerned,ifyouextendGameShape,thenyou’vedefinitelygotadisplayShape()method,soIknowI
cancallit.”
ImaginewenowhavetwospecializedsubclassesthatextendthemoregenericGameShapeclass,
PlayerPieceandTilePiece:
NowimagineatestclasshasamethodwithadeclaredargumenttypeofGameShape,whichmeansit
cantakeanykindofGameShape.Inotherwords,anysubclassofGameShapecanbepassedtoamethod
withanargumentoftypeGameShape.Thiscode
outputs:
displayingshape
displayingshape
ThekeypointisthatthedoShapes()methodisdeclaredwithaGameShapeargumentbutcanbe
passedanysubtype(inthisexample,asubclass)ofGameShape.Themethodcantheninvokeanymethod
ofGameShape,withoutanyconcernfortheactualruntimeclasstypeoftheobjectpassedtothemethod.
Thereareimplications,though.ThedoShapes()methodknowsonlythattheobjectsareatypeof
GameShapesincethat’showtheparameterisdeclared.Andusingareferencevariabledeclaredastype
GameShape—regardlessofwhetherthevariableisamethodparameter,localvariable,orinstance
variable—meansthatonlythemethodsofGameShapecanbeinvokedonit.Themethodsyoucancallona
referencearetotallydependentonthedeclaredtypeofthevariable,nomatterwhattheactualobjectis,
thatthereferenceisreferringto.Thatmeansyoucan’tuseaGameShapevariabletocall,say,the
getAdjacent()methodeveniftheobjectpassedinisoftypeTilePiece.(We’llseethisagainwhenwe
lookatinterfaces.)
IS-AandHAS-ARelationships
Note:AsofWinter2017,theOCA8examwon’taskyoudirectlyaboutIS-AandHAS-Arelationships.
ButunderstandingIS-AandHAS-ArelationshipswillhelpOCA8candidateswithmanyofthequestions
ontheexam.
IS-A
InOO,theconceptofIS-Aisbasedoninheritance(orinterfaceimplementation).IS-Aisawayofsaying,
“Thisthingisatypeofthatthing.”Forexample,aMustangisatypeofHorse,soinOOtermswecansay,
“MustangIS-AHorse.”SubaruIS-ACar.BroccoliIS-AVegetable(notaveryfunone,butitstillcounts).
YouexpresstheIS-ArelationshipinJavathroughthekeywordsextends(forclassinheritance)and
implements(forinterfaceimplementation).
ACarisatypeofVehicle,sotheinheritancetreemightstartfromtheVehicleclassasfollows:
InOOterms,youcansaythefollowing:
VehicleisthesuperclassofCar.
CaristhesubclassofVehicle.
CaristhesuperclassofSubaru.
SubaruisthesubclassofVehicle.
CarinheritsfromVehicle.
SubaruinheritsfrombothVehicleandCar.
SubaruisderivedfromCar.
CarisderivedfromVehicle.
SubaruisderivedfromVehicle.
SubaruisasubtypeofbothVehicleandCar.
ReturningtoourIS-Arelationship,thefollowingstatementsaretrue:
“CarextendsVehicle”means“CarIS-AVehicle.”
“SubaruextendsCar”means“SubaruIS-ACar.”
Andwecanalsosay:
“SubaruIS-AVehicle”
becauseaclassissaidtobe“atypeof”anythingfurtherupinitsinheritancetree.Iftheexpression(Foo
instanceofBar)istrue,thenclassFooIS-ABar,evenifFoodoesn’tdirectlyextendBar,butinstead
extendssomeotherclassthatisasubclassofBar.Figure2-2illustratestheinheritancetreeforVehicle,
Car,andSubaru.Thearrowsmovefromthesubclasstothesuperclass.Inotherwords,aclass’sarrow
pointstowardtheclassfromwhichitextends.
FIGURE2-2 InheritancetreeforVehicle,Car,Subaru
HAS-A
HAS-Arelationshipsarebasedonuse,ratherthaninheritance.Inotherwords,classAHAS-ABifcode
inclassAhasareferencetoaninstanceofclassB.Forexample,youcansaythefollowing:
AHorseIS-AAnimal.AHorseHAS-AHalter.
Thecodemightlooklikethis:
Inthiscode,theHorseclasshasaninstancevariableoftypeHalter(ahalterisapieceofgearyoumight
haveifyouhaveahorse),soyoucansaythata“HorseHAS-AHalter.”Inotherwords,Horsehasa
referencetoaHalter.HorsecodecanusethatHalterreferencetoinvokemethodsontheHalterand
getHalterbehaviorwithouthavingHalter-relatedcode(methods)intheHorseclassitself.Figure2-3
illustratestheHAS-ArelationshipbetweenHorseandHalter.
FIGURE2-3 HAS-ArelationshipbetweenHorseandHalter
HAS-ArelationshipsallowyoutodesignclassesthatfollowgoodOOpracticesbynothaving
monolithicclassesthatdoagazilliondifferentthings.Classes(andtheirresultingobjects)shouldbe
specialists.AsourfriendAndrewsays,“Specializedclassescanactuallyhelpreducebugs.”Themore
specializedtheclass,themorelikelyitisthatyoucanreusetheclassinotherapplications.Ifyouputall
theHalter-relatedcodedirectlyintotheHorseclass,you’llendupduplicatingcodeintheCowclass,
UnpaidInternclass,andanyotherclassthatmightneedHalterbehavior.BykeepingtheHaltercode
inaseparate,specializedHalterclass,youhavethechancetoreusetheHalterclassinmultiple
applications.
UsersoftheHorseclass(thatis,codethatcallsmethodsonaHorseinstance)thinkthattheHorse
classhasHalterbehavior.TheHorseclassmighthaveatie(LeadRoperope)method,forexample.
UsersoftheHorseclassshouldneverhavetoknowthatwhentheyinvokethetie()method,theHorse
objectturnsaroundanddelegatesthecalltoitsHalterclassbyinvokingmyHalter.tie(rope).The
scenariojustdescribedmightlooklikethis:
InOO,wedon’twantcallerstoworryaboutwhichclassorobjectisactuallydoingtherealwork.To
makethathappen,theHorseclasshidesimplementationdetailsfromHorseusers.Horseusersaskthe
Horseobjecttodothings(inthiscase,tieitselfup),andtheHorsewilleitherdoitor,asinthisexample,
asksomethingelse(likeperhapsaninheritedAnimalclassmethod)todoit.Tothecaller,though,it
alwaysappearsthattheHorseobjecttakescareofitself.UsersofaHorseshouldnotevenneedtoknow
thatthereissuchathingasaHalterclass.
FROMTHECLASSROOM
Object-OrientedDesign
IS-AandHAS-ArelationshipsandencapsulationarejustthetipoftheicebergwhenitcomestoOO
design.Manybooksandgraduatetheseshavebeendedicatedtothistopic.Thereasonforthe
emphasisonproperdesignissimple:money.Thecosttodeliverasoftwareapplicationhasbeen
estimatedtobeasmuchastentimesmoreexpensiveforpoorlydesignedprograms.
EventhebestOOdesigners(oftencalled"architects")makemistakes.Itisdifficulttovisualizethe
relationshipsbetweenhundreds,oreventhousands,ofclasses.Whenmistakesarediscoveredduring
theimplementation(codewriting)phaseofaproject,theamountofcodethatmustberewrittencan
sometimesmeanprogrammingteamshavetostartoverfromscratch.
Thesoftwareindustryhasevolvedtoaidthedesigner.Visualobjectmodelinglanguages,suchas
theUnifiedModelingLanguage(UML),allowdesignerstodesignandeasilymodifyclasseswithout
havingtowritecodefirstbecauseOOcomponentsarerepresentedgraphically.Thisallowsdesigners
tocreateamapoftheclassrelationshipsandhelpsthemrecognizeerrorsbeforecodingbegins.
AnotherinnovationinOOdesignisdesignpatterns.DesignersnoticedthatmanyOOdesignsapply
consistentlyfromprojecttoprojectandthatitwasusefultoapplythesamedesignsbecauseitreduced
thepotentialtointroducenewdesignerrors.OOdesignersthenstartedtosharethesedesignswith
eachother.NowtherearemanycatalogsofthesedesignpatternsbothontheInternetandinbookform.
AlthoughpassingtheJavacertificationexamdoesnotrequireyoutounderstandOOdesignthis
thoroughly,hopefullythisbackgroundinformationwillhelpyoubetterappreciatewhythetestwriters
chosetoincludeencapsulationandIS-AandHAS-Arelationshipsontheexam.
—JonathanMeeks,
SunCertifiedJavaProgrammer
CERTIFICATIONOBJECTIVE
Polymorphism(OCAObjective7.2)
7.2Developcodethatdemonstratestheuseofpolymorphism;includingoverridingandobjecttype
versusreferencetype(sic).
RememberthatanyJavaobjectthatcanpassmorethanoneIS-Atestcanbeconsideredpolymorphic.
OtherthanobjectsoftypeObject,allJavaobjectsarepolymorphicinthattheypasstheIS-Atestfor
theirowntypeandforclassObject.
Remember,too,thattheonlywaytoaccessanobjectisthroughareferencevariable.Thereareafew
keythingsyoushouldknowaboutreferences:
Areferencevariablecanbeofonlyonetype,andoncedeclared,thattypecanneverbe
changed(althoughtheobjectitreferencescanchange).
Areferenceisavariable,soitcanbereassignedtootherobjects(unlessthereferenceis
declaredfinal).
Areferencevariable’stypedeterminesthemethodsthatcanbeinvokedontheobjectthe
variableisreferencing.
Areferencevariablecanrefertoanyobjectofthesametypeasthedeclaredreference,or—
thisisthebigone—itcanrefertoanysubtypeofthedeclaredtype!
Areferencevariablecanbedeclaredasaclasstypeoraninterfacetype.Ifthevariableis
declaredasaninterfacetype,itcanreferenceanyobjectofanyclassthatimplementstheinterface.
EarlierwecreatedaGameShapeclassthatwasextendedbytwootherclasses,PlayerPieceand
TilePiece.Nowimagineyouwanttoanimatesomeoftheshapesonthegameboard.Butnotallshapes
areabletobeanimated,sowhatdoyoudowithclassinheritance?
Couldwecreateaclasswithananimate()methodandhaveonlysomeoftheGameShapesubclasses
inheritfromthatclass?Ifwecan,thenwecouldhavePlayerPiece,forexample,extendboththe
GameShapeclassandAnimatableclass,whereastheTilePiecewouldextendonlyGameShape.Butno,
thiswon’twork!Javasupportsonlysingleclassinheritance!Thatmeansaclasscanhaveonlyone
immediatesuperclass.Inotherwords,ifPlayerPieceisaclass,thereisnowaytosaysomethinglike
this:
classPlayerPieceextendsGameShape,Animatable{//NO!
//morecode
}
Aclasscannotextendmorethanoneclass:thatmeansoneparentperclass.Aclasscanhavemultiple
ancestors,however,sinceclassBcouldextendclassA,andclassCcouldextendclassB,andsoon.So
anygivenclassmighthavemultipleclassesupitsinheritancetree,butthat’snotthesameassayingaclass
directlyextendstwoclasses.
Somelanguages(suchasC++)allowaclasstoextendmorethanoneotherclass.Thiscapabilityis
knownas“multipleinheritance.”ThereasonthatJava’screatorschosenottoallowmultipleclass
inheritanceisthatitcanbecomequitemessy.Inanutshell,theproblemisthatifaclassextended
twootherclasses,andbothsuperclasseshad,say,adoStuff()method,whichversionofdoStuff()
wouldthesubclassinherit?Thisissuecanleadtoascenarioknownasthe“DeadlyDiamondof
Death,”becauseoftheshapeoftheclassdiagramthatcanbecreatedinamultipleinheritance
design.ThediamondisformedwhenclassesBandCbothextendA,andbothBandCinherita
methodfromA.IfclassDextendsbothBandC,andbothBandChaveoverriddenthemethodinA,
classDhas,intheory,inheritedtwodifferentimplementationsofthesamemethod.Drawnasa
classdiagram,theshapeofthefourclasseslookslikeadiamond.
Soifthatdoesn’twork,whatelsecouldyoudo?Youcouldsimplyputtheanimate()codein
GameShape,andthendisablethemethodinclassesthatcan’tbeanimated.Butthat’sabaddesignchoice
formanyreasons—it’smoreerrorprone;itmakestheGameShapeclasslesscohesive;anditmeansthe
GameShapeAPI“advertises”thatallshapescanbeanimatedwhen,infact,that’snottruesinceonlysome
oftheGameShapesubclasseswillbeabletoruntheanimate()methodsuccessfully.
Toreiterate,asofJava8,interfacescanhaveconcretemethods(calleddefaultmethods).This
allowsforaformofmultipleinterhance,whichwe’lldiscusslaterinthechapter.
Sowhatelsecouldyoudo?Youalreadyknowtheanswer—createanAnimatableinterface,andhave
onlytheGameShapesubclassesthatcanbeanimatedimplementthatinterface.Here’stheinterface:
Andhere’sthemodifiedPlayerPiececlassthatimplementstheinterface:
SonowwehaveaPlayerPiecethatpassestheIS-AtestforboththeGameShapeclassandthe
Animatableinterface.ThatmeansaPlayerPiececanbetreatedpolymorphicallyasoneoffourthingsat
anygiventime,dependingonthedeclaredtypeofthereferencevariable:
AnObject(sinceanyobjectinheritsfromObject)
AGameShape(sincePlayerPieceextendsGameShape)
APlayerPiece(sincethat’swhatitreallyis)
AnAnimatable(sincePlayerPieceimplementsAnimatable)
Thefollowingarealllegaldeclarations.Lookclosely:
There’sonlyoneobjecthere—aninstanceoftypePlayerPiece—buttherearefourdifferenttypesof
referencevariables,allreferringtothatoneobjectontheheap.Popquiz:Whichofthepreceding
referencevariablescaninvokethedisplayShape()method?Hint:Onlytwoofthefourdeclarationscan
beusedtoinvokethedisplayShape()method.
Rememberthatmethodinvocationsallowedbythecompilerarebasedsolelyonthedeclaredtypeof
thereference,regardlessoftheobjecttype.Solookingatthefourreferencetypesagain—Object,
GameShape,PlayerPiece,andAnimatable—whichofthesefourtypesknowaboutthe
displayShape()method?
Youguessedit—boththeGameShapeclassandthePlayerPiececlassareknown(bythecompiler)to
haveadisplayShape()method,soeitherofthosereferencetypescanbeusedtoinvoke
displayShape().Rememberthattothecompiler,aPlayerPieceIS-AGameShape,sothecompiler
says,“IseethatthedeclaredtypeisPlayerPiece,andsincePlayerPieceextendsGameShape,that
meansPlayerPieceinheritedthedisplayShape()method.Therefore,PlayerPiececanbeusedto
invokethedisplayShape()method.”
WhichmethodscanbeinvokedwhenthePlayerPieceobjectisbeingreferredtousingareference
declaredastypeAnimatable?Onlytheanimate()method.Ofcourse,thecoolthinghereisthatany
classfromanyinheritancetreecanalsoimplementAnimatable,sothatmeansifyouhaveamethodwith
anargumentdeclaredastypeAnimatable,youcanpassinPlayerPieceobjects,SpinningLogo
objects,andanythingelsethat’saninstanceofaclassthatimplementsAnimatable.Andyoucanusethat
parameter(oftypeAnimatable)toinvoketheanimate()method,butnotthedisplayShape()method
(whichitmightnotevenhave),oranythingotherthanwhatisknowntothecompilerbasedonthe
referencetype.Thecompileralwaysknows,though,thatyoucaninvokethemethodsofclassObjecton
anyobject,sothosearesafetocallregardlessofthereference—classorinterface—usedtorefertothe
object.
We’veleftoutonebigpartofallthis,whichisthateventhoughthecompileronlyknowsaboutthe
declaredreferencetype,theJavaVirtualMachine(JVM)atruntimeknowswhattheobjectreallyis.And
thatmeansthatevenifthePlayerPieceobject’sdisplayShape()methodiscalledusingaGameShape
referencevariable,ifthePlayerPieceoverridesthedisplayShape()method,theJVMwillinvokethe
PlayerPieceversion!TheJVMlooksattherealobjectattheotherendofthereference,“sees”thatit
hasoverriddenthemethodofthedeclaredreferencevariabletype,andinvokesthemethodoftheobject’s
actualclass.Butthereisoneotherthingtokeepinmind:
Polymorphicmethodinvocationsapplyonlytoinstancemethods.Youcanalwaysrefertoanobjectwithamoregeneral
referencevariabletype(asuperclassorinterface),butatruntime,theONLYthingsthataredynamicallyselectedbasedonthe
actualobject(ratherthanthereferencetype)areinstancemethods.Notstaticmethods.Notvariables.Onlyoverridden
instancemethodsaredynamicallyinvokedbasedontherealobject’stype.
Becausethisdefinitiondependsonaclearunderstandingofoverridingandthedistinctionbetweenstatic
methodsandinstancemethods,we’llcoverthoselaterinthechapter.
CERTIFICATIONOBJECTIVE
Overriding/Overloading(OCAObjectives6.1and7.2)
6.1Createmethodswithargumentsandreturnvalues;includingoverloadedmethods.
7.2Developcodethatdemonstratestheuseofpolymorphism;includingoverridingandobjecttype
versusreferencetype(sic).
Theexamwilluseoverriddenandoverloadedmethodsonmany,manyquestions.Thesetwoconcepts
areoftenconfused(perhapsbecausetheyhavesimilarnames?),buteachhasitsownuniqueandcomplex
setofrules.It’simportanttogetreallyclearaboutwhich“over”useswhichrules!
OverriddenMethods
Anytimeatypeinheritsamethodfromasupertype,youhavetheopportunitytooverridethemethod
(unless,asyoulearnedearlier,themethodismarkedfinal).Thekeybenefitofoverridingistheability
todefinebehaviorthat’sspecifictoaparticularsubtype.ThefollowingexampledemonstratesaHorse
subclassofAnimaloverridingtheAnimalversionoftheeat()method:
Forabstractmethodsyouinheritfromasupertype,youhavenochoice:Youmustimplementthe
methodinthesubtypeunlessthesubtypeisalsoabstract.Abstractmethodsmustbeimplementedbythe
firstconcretesubclass,butthisisalotlikesayingtheconcretesubclassoverridestheabstractmethodsof
thesupertype(s).Soyoucouldthinkofabstractmethodsasmethodsyou’reforcedtooverride—
eventually.
TheAnimalclasscreatormighthavedecidedthatforthepurposesofpolymorphism,allAnimal
subtypesshouldhaveaneat()methoddefinedinauniqueway.Polymorphically,whenanAnimal
referencerefersnottoanAnimalinstance,buttoanAnimalsubclassinstance,thecallershouldbeable
toinvokeeat()ontheAnimalreference,buttheactualruntimeobject(say,aHorseinstance)willrunits
ownspecificeat()method.Markingtheeat()methodabstractistheAnimalprogrammer’swayof
sayingtoallsubclassdevelopers,“Itdoesn’tmakeanysenseforyournewsubtypetouseagenericeat()
method,soyouhavetocomeupwithyourowneat()methodimplementation!”A(nonabstract)example
ofusingpolymorphismlookslikethis:
Intheprecedingcode,thetestclassusesanAnimalreferencetoinvokeamethodonaHorseobject.
Remember,thecompilerwillallowonlymethodsinclassAnimaltobeinvokedwhenusingareference
toanAnimal.Thefollowingwouldnotbelegalgiventheprecedingcode:
Toreiterate,thecompilerlooksonlyatthereferencetype,nottheinstancetype.Polymorphismletsyou
useamoreabstractsupertype(includinganinterface)referencetooneofitssubtypes(includinginterface
implementers).
Theoverridingmethodcannothaveamorerestrictiveaccessmodifierthanthemethodbeing
overridden(forexample,youcan’toverrideamethodmarkedpublicandmakeitprotected).Think
aboutit:IftheAnimalclassadvertisesapubliceat()methodandsomeonehasanAnimalreference
(inotherwords,areferencedeclaredastypeAnimal),thatsomeonewillassumeit’ssafetocalleat()
ontheAnimalreferenceregardlessoftheactualinstancethattheAnimalreferenceisreferringto.Ifa
subtypewereallowedtosneakinandchangetheaccessmodifierontheoverridingmethod,thensuddenly
atruntime—whentheJVMinvokesthetrueobject’s(Horse)versionofthemethodratherthanthe
referencetype’s(Animal)version—theprogramwoulddieahorribledeath.(Nottomentionthe
emotionaldistressfortheonewhowasbetrayedbytheroguesubtype.)
Let’smodifythepolymorphicexamplewesawearlierinthissection:
Ifthiscodecompiled(whichitdoesn’t),thefollowingwouldfailatruntime:
ThevariablebisoftypeAnimal,whichhasapubliceat()method.Butrememberthatatruntime,
Javausesvirtualmethodinvocationtodynamicallyselecttheactualversionofthemethodthatwillrun,
basedontheactualinstance.AnAnimalreferencecanalwaysrefertoaHorseinstance,becauseHorse
IS-A(n)Animal.Whatmakesthatsupertypereferencetoasubtypeinstancepossibleisthatthesubtypeis
guaranteedtobeabletodoeverythingthesupertypecando.WhethertheHorseinstanceoverridesthe
inheritedmethodsofAnimalorsimplyinheritsthem,anyonewithanAnimalreferencetoaHorse
instanceisfreetocallallaccessibleAnimalmethods.Forthatreason,anoverridingmethodmustfulfill
thecontractofthesuperclass.
Note:InChapter5wewillexploreexceptionhandlingindetail.Onceyou’vestudiedChapter5,you’ll
appreciatethissinglehandylistofoverridingrules.Therulesforoverridingamethodareasfollows:
Theargumentlistmustexactlymatchthatoftheoverriddenmethod.Iftheydon’tmatch,you
canendupwithanoverloadedmethodyoudidn’tintend.
Thereturntypemustbethesameas,orasubtypeof,thereturntypedeclaredintheoriginal
overriddenmethodinthesuperclass.(Moreonthisinafewpageswhenwediscusscovariant
returns.)
Theaccesslevelcan’tbemorerestrictivethanthatoftheoverriddenmethod.
TheaccesslevelCANbelessrestrictivethanthatoftheoverriddenmethod.
Instancemethodscanbeoverriddenonlyiftheyareinheritedbythesubtype.Asubtypewithin
thesamepackageastheinstance’ssupertypecanoverrideanysupertypemethodthatisnotmarked
privateorfinal.Asubtypeinadifferentpackagecanoverrideonlythosenonfinalmethods
markedpublicorprotected(sinceprotectedmethodsareinheritedbythesubtype).
TheoverridingmethodCANthrowanyunchecked(runtime)exception,regardlessofwhether
theoverriddenmethoddeclarestheexception.(MoreinChapter5.)
TheoverridingmethodmustNOTthrowcheckedexceptionsthatareneworbroaderthan
thosedeclaredbytheoverriddenmethod.Forexample,amethodthatdeclaresa
FileNotFoundExceptioncannotbeoverriddenbyamethodthatdeclaresaSQLException,
Exception,oranyothernonruntimeexceptionunlessit’sasubclassofFileNotFoundException.
Theoverridingmethodcanthrownarrowerorfewerexceptions.Justbecauseanoverridden
method“takesrisks”doesn’tmeanthattheoverridingsubtype’sexceptiontakesthesamerisks.
Bottomline:anoverridingmethoddoesn’thavetodeclareanyexceptionsthatitwillneverthrow,
regardlessofwhattheoverriddenmethoddeclares.
Youcannotoverrideamethodmarkedfinal.
Youcannotoverrideamethodmarkedstatic.We’lllookatanexampleinafewpageswhen
wediscussstaticmethodsinmoredetail.
Ifamethodcan’tbeinherited,youcannotoverrideit.Rememberthatoverridingimpliesthat
you’rereimplementingamethodyouinherited!Forexample,thefollowingcodeisnotlegal,and
evenifyouaddedaneat()methodtoHorse,itwouldn’tbeanoverrideofAnimal’seat()
method:
InvokingaSupertypeVersionofanOverriddenMethod
Often,you’llwanttotakeadvantageofsomeofthecodeinthesupertypeversionofamethod,yetstill
overrideittoprovidesomeadditionalspecificbehavior.It’slikesaying,“Runthesupertypeversionof
themethod,andthencomebackdownhereandfinishwithmysubtypeadditionalmethodcode.”(Note
thatthere’snorequirementthatthesupertypeversionrunbeforethesubtypecode.)It’seasytodoincode
usingthekeywordsuperasfollows:
Inasimilarway,youcanaccessaninterface’soverriddenmethodwiththesyntax:
InterfaceX.super.doStuff();
Note:Usingsupertoinvokeanoverriddenmethodappliesonlytoinstancemethods.(Rememberthat
staticmethodscan’tbeoverridden.)Andyoucanusesuperonlytoaccessamethodinatype’s
supertype,notthesupertypeofthesupertype—thatis,youcannotsaysuper.super.doStuff()andyou
cannotsay:InterfaceX.super.super.doStuff().
Ifamethodisoverriddenbutyouuseapolymorphic(supertype)referencetorefertothe
subtypeobjectwiththeoverridingmethod,thecompilerassumesyou’recallingthesupertype
versionofthemethod.Ifthesupertypeversiondeclaresacheckedexception,buttheoverriding
subtypemethoddoesnot,thecompilerstillthinksyouarecallingamethodthatdeclaresan
exception(moreinChapter5).Let’slookatanexample:
ThiscodewillnotcompilebecauseoftheexceptiondeclaredontheAnimaleat()method.
Thishappenseventhough,atruntime,theeat()methodusedwouldbetheDogversion,which
doesnotdeclaretheexception.
ExamplesofIllegalMethodOverrides
Let’stakealookatoverridingtheeat()methodofAnimal:
publicclassAnimal{
publicvoideat(){}
}
Table2-2listsexamplesofillegaloverridesoftheAnimaleat()method,giventhepreceding
versionoftheAnimalclass.
TABLE2-2 ExamplesofIllegalOverrides
OverloadedMethods
Overloadedmethodsletyoureusethesamemethodnameinaclass,butwithdifferentarguments(and,
optionally,adifferentreturntype).Overloadingamethodoftenmeansyou’rebeingalittlenicertothose
whocallyourmethodsbecauseyourcodetakesontheburdenofcopingwithdifferentargumenttypes
ratherthanforcingthecallertodoconversionspriortoinvokingyourmethod.Therulesaren’ttoo
complex:
OverloadedmethodsMUSTchangetheargumentlist.
OverloadedmethodsCANchangethereturntype.
OverloadedmethodsCANchangetheaccessmodifier.
OverloadedmethodsCANdeclareneworbroadercheckedexceptions.
Amethodcanbeoverloadedinthesametypeorinasubtype.Inotherwords,ifclassA
definesadoStuff(inti)method,thesubclassBcoulddefineadoStuff(Strings)method
withoutoverridingthesuperclassversionthattakesanint.Sotwomethodswiththesamename
butindifferenttypescanstillbeconsideredoverloadedifthesubtypeinheritsoneversionofthe
methodandthendeclaresanotheroverloadedversioninitstypedefinition.
LessexperiencedJavadevelopersareoftenconfusedaboutthesubtledifferencesbetween
overloadedandoverriddenmethods.Becarefultorecognizewhenamethodisoverloaded
ratherthanoverridden.Youmightseeamethodthatappearstobeviolatingarulefor
overriding,butthatisactuallyalegaloverload,asfollows:
It’stemptingtoseetheIOExceptionastheproblembecausetheoverriddendoStuff()method
doesn’tdeclareanexceptionandIOExceptionischeckedbythecompiler.ButthedoStuff()
methodisnotoverridden!SubclassBaroverloadsthedoStuff()methodbyvaryingthe
argumentlist,sotheIOExceptionisfine.
LegalOverloads
Let’slookatamethodwewanttooverload:
InvokingOverloadedMethods
InChapter6wewilllookathowboxingandvar-argsimpactoverloading.(Youstillhavetopayattention
towhat’scoveredhere,however.)
Whenamethodisinvoked,morethanonemethodofthesamenamemightexistfortheobjecttype
you’reinvokingamethodon.Forexample,theHorseclassmighthavethreemethodswiththesamename
butwithdifferentargumentlists,whichmeansthemethodisoverloaded.
Decidingwhichofthematchingmethodstoinvokeisbasedonthearguments.Ifyouinvokethemethod
withaStringargument,theoverloadedversionthattakesaStringiscalled.Ifyouinvokeamethodof
thesamenamebutpassitafloat,theoverloadedversionthattakesafloatwillrun.Ifyouinvokethe
methodofthesamenamebutpassitaFooobject,andthereisn’tanoverloadedversionthattakesaFoo,
thenthecompilerwillcomplainthatitcan’tfindamatch.Thefollowingareexamplesofinvoking
overloadedmethods:
InthisTestAddercode,thefirstcalltoa.addThem(b,c)passestwointstothemethod,sothefirst
versionofaddThem()—theoverloadedversionthattakestwointarguments—iscalled.Thesecondcall
toa.addThem(22.5,9.3)passestwodoublestothemethod,sothesecondversionofaddThem()—the
overloadedversionthattakestwodoublearguments—iscalled.
Invokingoverloadedmethodsthattakeobjectreferencesratherthanprimitivesisalittlemore
interesting.SayyouhaveanoverloadedmethodsuchthatoneversiontakesanAnimalandonetakesa
Horse(subclassofAnimal).IfyoupassaHorseobjectinthemethodinvocation,you’llinvokethe
overloadedversionthattakesaHorse.Orsoitlooksatfirstglance:
Theoutputiswhatyouexpect:
IntheAnimalversion
IntheHorseversion
ButwhatifyouuseanAnimalreferencetoaHorseobject?
AnimalanimalRefToHorse=newHorse();
ua.doStuff(animalRefToHorse);
Whichoftheoverloadedversionsisinvoked?Youmightwanttoanswer,“TheonethattakesaHorse
sinceit’saHorseobjectatruntimethat’sbeingpassedtothemethod.”Butthat’snothowitworks.The
precedingcodewouldactuallyprintthis:
intheAnimalversion
EventhoughtheactualobjectatruntimeisaHorseandnotanAnimal,thechoiceofwhichoverloaded
methodtocall(inotherwords,thesignatureofthemethod)isNOTdynamicallydecidedatruntime.
Justrememberthatthereferencetype(nottheobjecttype)determineswhichoverloadedmethodis
invoked!
Tosummarize,whichoverriddenversionofthemethodtocall(inotherwords,fromwhichclass
intheinheritancetree)isdecidedatruntimebasedonobjecttype,butwhichoverloadedversionof
themethodtocallisbasedonthereferencetypeoftheargumentpassedatcompiletime.
IfyouinvokeamethodpassingitanAnimalreferencetoaHorseobject,thecompilerknowsonly
abouttheAnimal,soitchoosestheoverloadedversionofthemethodthattakesanAnimal.Itdoesnot
matterthat,atruntime,aHorseisactuallybeingpassed.
Canmain()beoverloaded?
Absolutely!Buttheonlymain()withJVMsuperpowersistheonewiththesignatureyou’ve
seenabout100timesalreadyinthisbook.
PolymorphisminOverloadedandOverriddenMethodsHowdoespolymorphismwork
withoverloadedmethods?Fromwhatwejustlookedat,itdoesn’tappearthatpolymorphismmatters
whenamethodisoverloaded.IfyoupassanAnimalreference,theoverloadedmethodthattakesan
Animalwillbeinvoked,eveniftheactualobjectpassedisaHorse.OncetheHorsemasqueradingas
Animalgetsintothemethod,however,theHorseobjectisstillaHorsedespitebeingpassedintoa
methodexpectinganAnimal.Soit’struethatpolymorphismdoesn’tdeterminewhichoverloadedversion
iscalled;however,polymorphismdoescomeintoplaywhenthedecisionisaboutwhichoverridden
versionofamethodiscalled.Butsometimesamethodisbothoverloadedandoverridden.Imaginethat
theAnimalandHorseclasseslooklikethis:
NoticethattheHorseclasshasbothoverloadedandoverriddentheeat()method.Table2-3shows
whichversionofthethreeeat()methodswillrundependingonhowtheyareinvoked.
TABLE2-3 ExamplesofLegalandIllegalOverrides
Don’tbefooledbyamethodthat’soverloadedbutnotoverriddenbyasubclass.It’sperfectly
legaltodothefollowing:
TheBarclasshastwodoStuff()methods:theno-argversionitinheritsfromFoo(anddoes
notoverride)andtheoverloadeddoStuff(Strings)definedintheBarclass.Codewitha
referencetoaFoocaninvokeonlytheno-argversion,butcodewithareferencetoaBarcan
invokeeitheroftheoverloadedversions.
Table2-4summarizesthedifferencebetweenoverloadedandoverriddenmethods.
TABLE2-4 DifferencesBetweenOverloadedandOverriddenMethods
We’llcoverconstructoroverloadinglaterinthechapter,wherewe’llalsocovertheotherconstructor-
relatedtopicsthatareontheexam.Figure2-4illustratesthewayoverloadedandoverriddenmethods
appearinclassrelationships.
FIGURE2-4 Overloadedandoverriddenmethodsinclassrelationships
CERTIFICATIONOBJECTIVE
Casting(OCAObjectives2.2and7.3)
2.2Differentiatebetweenobjectreferencevariablesandprimitivevariables.
7.3Determinewhencastingisnecessary.
You’veseenhowit’sbothpossibleandcommontousegeneralreferencevariabletypestoreferto
morespecificobjecttypes.It’sattheheartofpolymorphism.Forexample,thislineofcodeshouldbe
secondnaturebynow:
Animalanimal=newDog();
Butwhathappenswhenyouwanttousethatanimalreferencevariabletoinvokeamethodthatonly
classDoghas?Youknowit’sreferringtoaDog,andyouwanttodoaDog-specificthing?Inthefollowing
code,we’vegotanarrayofAnimals,andwheneverwefindaDoginthearray,wewanttodoaspecial
Dogthing.Let’sagreefornowthatallthiscodeisokay,exceptthatwe’renotsureaboutthelineofcode
thatinvokestheplayDeadmethod.
Whenwetrytocompilethiscode,thecompilersayssomethinglikethis:
cannotfindsymbol
Thecompilerissaying,“Hey,classAnimaldoesn’thaveaplayDead()method.”Let’smodifytheif
codeblock:
Thenewandimprovedcodeblockcontainsacast,whichinthiscaseissometimescalledadowncast,
becausewe’recastingdowntheinheritancetreetoamorespecificclass.Nowthecompilerishappy.
BeforewetrytoinvokeplayDead,wecasttheanimalvariabletotypeDog.Whatwe’resayingtothe
compileris,“Weknowit’sreallyreferringtoaDogobject,soit’sokaytomakeanewDogreference
variabletorefertothatobject.”Inthiscasewe’resafe,becausebeforeweevertrythecast,wedoan
instanceoftesttomakesure.
It’simportanttoknowthatthecompilerisforcedtotrustuswhenwedoadowncast,evenwhenwe
screwup:
Itcanbemaddening!Thiscodecompiles!Butwhenwetrytorunit,we’llgetanexception,something
likethis:
java.lang.ClassCastException
Whycan’twetrustthecompilertohelpusouthere?Can’titseethatanimalisoftypeAnimal?All
thecompilercandoisverifythatthetwotypesareinthesameinheritancetree,sothatdependingon
whatevercodemighthavecomebeforethedowncast,it’spossiblethatanimalisoftypeDog.The
compilermustallowthingsthatmightpossiblyworkatruntime.However,ifthecompilerknowswith
certaintythatthecastcouldnotpossiblywork,compilationwillfail.Thefollowingreplacementcode
blockwillNOTcompile:
Animalanimal=newAnimal();
Dogd=(Dog)animal;
Strings=(String)animal;//animalcan’tEVERbeaString
Inthiscase,you’llgetanerrorlikethis:
inconvertibletypes
Unlikedowncasting,upcasting(castinguptheinheritancetreetoamoregeneraltype)works
implicitly(thatis,youdon’thavetotypeinthecast)becausewhenyouupcastyou’reimplicitly
restrictingthenumberofmethodsyoucaninvoke,asopposedtodowncasting,whichimpliesthatlateron,
youmightwanttoinvokeamorespecificmethod.Here’sanexample:
BothofthepreviousupcastswillcompileandrunwithoutexceptionbecauseaDogIS-A(n)Animal,
whichmeansthatanythinganAnimalcando,aDogcando.ADogcandomore,ofcourse,butthepointis
thatanyonewithanAnimalreferencecansafelycallAnimalmethodsonaDoginstance.TheAnimal
methodsmayhavebeenoverriddenintheDogclass,butallwecareaboutnowisthataDogcanalways
doatleasteverythinganAnimalcando.ThecompilerandJVMknowit,too,sotheimplicitupcastis
alwayslegalforassigninganobjectofasubtypetoareferenceofoneofitssupertypeclasses(or
interfaces).IfDogimplementsPetandPetdefinesbeFriendly(),thenaDogcanbeimplicitlycasttoa
Pet,buttheonlyDogmethodyoucaninvokethenisbeFriendly(),whichDogwasforcedtoimplement
becauseDogimplementsthePetinterface.
Onemorething…ifDogimplementsPet,then,ifBeagleextendsDogbutBeagledoesnotdeclarethat
itimplementsPet,BeagleisstillaPet!BeagleisaPetsimplybecauseitextendsDog,andDog’s
alreadytakencareofthePetpartsforitselfandforallitschildren.TheBeagleclasscanalways
overrideanymethoditinheritsfromDog,includingmethodsthatDogimplementedtofulfillitsinterface
contract.
Andjustonemorething…ifBeagledoesdeclarethatitimplementsPet,justsothatotherslookingat
theBeagleclassAPIcaneasilyseethatBeagleIS-APetwithouthavingtolookatBeagle’s
superclasses,Beaglestilldoesn’tneedtoimplementthebeFriendly()methodiftheDogclass
(Beagle’ssuperclass)hasalreadytakencareofthat.Inotherwords,ifBeagleIS-ADog,andDogIS-A
Pet,thenBeagleIS-APetandhasalreadymetitsPetobligationsforimplementingthebeFriendly()
methodsinceitinheritsthebeFriendly()method.Thecompilerissmartenoughtosay,“IknowBeagle
alreadyISaDog,butit’sokaytomakeitmoreobviousbyaddingacast.”
Sodon’tbefooledbycodethatshowsaconcreteclassthatdeclaresitimplementsaninterfacebut
doesn’timplementthemethodsoftheinterface.Beforeyoucantellwhetherthecodeislegal,youmust
knowwhatthesupertypesofthisimplementingclasshavedeclared.Ifanysupertypeinitsinheritancetree
hasalreadyprovidedconcrete(thatis,nonabstract)methodimplementations,thenregardlessofwhether
thesupertypedeclaresthatitimplementstheinterface,thesubclassisundernoobligationtoreimplement
(override)thosemethods.
Theexamcreatorswilltellyouthatthey’reforcedtojamtonsofcodeintolittlespaces
"becauseoftheexamengine."Althoughthat’spartiallytrue,theyALSOliketoobfuscate.The
followingcode
canbereplacedwiththiseasy-to-readbitoffun:
Inthiscasethecompilerneedsallthoseparentheses;otherwise,itthinksit’sbeenhandedan
incompletestatement.
CERTIFICATIONOBJECTIVE
ImplementinganInterface(OCAObjective7.5)
7.5Useabstractclassesandinterfaces.
Whenyouimplementaninterface,you’reagreeingtoadheretothecontractdefinedintheinterface.
Thatmeansyou’reagreeingtoprovidelegalimplementationsforeveryabstractmethoddefinedinthe
interface,andthatanyonewhoknowswhattheinterfacemethodslooklike(nothowthey’reimplemented,
buthowtheycanbecalledandwhattheyreturn)canrestassuredthattheycaninvokethosemethodsonan
instanceofyourimplementingclass.
Forexample,ifyoucreateaclassthatimplementstheRunnableinterface(sothatyourcodecanbe
executedbyaspecificthread),youmustprovidethepublicvoidrun()method.Otherwise,thepoor
threadcouldbetoldtogoexecuteyourRunnableobject’scodeand—surprise,surprise—thethreadthen
discoverstheobjecthasnorun()method!(Atwhichpoint,thethreadwouldblowupandtheJVM
wouldcrashinaspectacularyethorribleexplosion.)Thankfully,Javapreventsthismeltdownfrom
occurringbyrunningacompilercheckonanyclassthatclaimstoimplementaninterface.Iftheclasssays
it’simplementinganinterface,itdarnwellbetterhaveanimplementationforeachabstractmethodinthe
interface(withafewexceptionsthatwe’lllookatinamoment).
AssuminganinterfaceBounceablewithtwomethods,bounce()andsetBounceFactor(),the
followingclasswillcompile:
Okay,weknowwhatyou’rethinking:“Thishasgottobetheworstimplementationclassinthehistoryof
implementationclasses.”Itcompiles,though.Anditruns.Theinterfacecontractguaranteesthataclass
willhavethemethod(inotherwords,otherscancallthemethodsubjecttoaccesscontrol),butitnever
guaranteedagoodimplementation—orevenanyactualimplementationcodeinthebodyofthemethod.
(Keepinmind,though,thatiftheinterfacedeclaresthatamethodisNOTvoid,yourclass’s
implementationcodehastoincludeareturnstatement.)Thecompilerwillneversay,“Um,excuseme,but
didyoureallymeantoputnothingbetweenthosecurlybraces?HELLO.Thisisamethodafterall,so
shouldn’titdosomething?”
Implementationclassesmustadheretothesamerulesformethodimplementationasaclassextending
anabstractclass.Tobealegalimplementationclass,anonabstractimplementationclassmustdothe
following:
Provideconcrete(nonabstract)implementationsforallabstractmethodsfromthedeclared
interface.
Followalltherulesforlegaloverrides,suchasthefollowing:
Declarenocheckedexceptionsonimplementationmethodsotherthanthosedeclaredby
theinterfacemethodorsubclassesofthosedeclaredbytheinterfacemethod.
Maintainthesignatureoftheinterfacemethod,andmaintainthesamereturntype(ora
subtype).(Butitdoesnothavetodeclaretheexceptionsdeclaredintheinterfacemethod
declaration.)
Butwait,there’smore!Animplementationclasscanitselfbeabstract!Forexample,thefollowingis
legalforaclassBallimplementingBounceable:
abstractclassBallimplementsBounceable{}
Noticeanythingmissing?Weneverprovidedtheimplementationmethods.Andthat’sokay.Ifthe
implementationclassisabstract,itcansimplypassthebucktoitsfirstconcretesubclass.Forexample,
ifclassBeachBallextendsBall,andBeachBallisnotabstract,thenBeachBallhastoprovidean
implementationforalltheabstractmethodsfromBounceable:
ImplementationclassesareNOTrequiredtoimplementaninterface’sstaticordefault
methods.We’lldiscussthisinmoredepthlaterinthechapter.
Lookforclassesthatclaimtoimplementaninterfacebutdon’tprovidethecorrectmethod
implementations.Unlesstheimplementingclassisabstract,theimplementingclassmustprovide
implementationsforallabstractmethodsdefinedintheinterface.
Youneedtoknowtwomorerules,andthenwecanputthistopictosleep(orputyoutosleep;we
alwaysgetthosetwoconfused):
1.Aclasscanimplementmorethanoneinterface.It’sperfectlylegaltosay,forexample,the
following:
publicclassBallimplementsBounceable,Serializable,Runnable{...}
Youcanextendonlyoneclass,butyoucanimplementmanyinterfaces(which,asofJava8,
meansaformofmultipleinheritance,whichwe’lldiscussshortly).Inotherwords,subclassing
defineswhoandwhatyouare,whereasimplementingdefinesaroleyoucanplayorahatyoucan
wear,despitehowdifferentyoumightbefromsomeotherclassimplementingthesameinterface
(butfromadifferentinheritancetree).Forexample,aPersonextendsHumanBeing(althoughfor
some,that’sdebatable).ButaPersonmayalsoimplementProgrammer,Snowboarder,Employee,
Parent,orPersonCrazyEnoughToTakeThisExam.
2.Aninterfacecanitselfextendanotherinterface.Thefollowingcodeisperfectlylegal:
publicinterfaceBounceableextendsMoveable{}//ok!
Whatdoesthatmean?Thefirstconcrete(nonabstract)implementationclassofBounceablemust
implementalltheabstractmethodsofBounceable,plusalltheabstractmethodsofMoveable!The
subinterface,aswecallit,simplyaddsmorerequirementstothecontractofthesuperinterface.You’llsee
thisconceptappliedinmanyareasofJava,especiallyJavaEE,whereyou’lloftenhavetobuildyour
owninterfacethatextendsoneoftheJavaEEinterfaces.
Holdon,though,becausehere’swhereitgetsstrange.Aninterfacecanextendmorethanoneinterface!
Thinkaboutthatforamoment.Youknowthatwhenwe’retalkingaboutclasses,thefollowingisillegal:
publicclassProgrammerextendsEmployee,Geek{}//Illegal!
Aswementionedearlier,aclassisnotallowedtoextendmultipleclassesinJava.Aninterface,however,
isfreetoextendmultipleinterfaces:
Inthenextexample,BallisrequiredtoimplementBounceable,plusallabstractmethodsfromthe
interfacesthatBounceableextends(includinganyinterfacesthoseinterfacesextend,andsoon,untilyou
reachthetopofthestack—orisitthebottomofthestack?).SoBallwouldneedtolooklikethe
following:
IfclassBallfailstoimplementanyoftheabstractmethodsfromBounceable,Moveable,or
Spherical,thecompilerwilljumpupanddownwildly,redintheface,untilitdoes.Unless,thatis,
classBallismarkedabstract.Inthatcase,Ballcouldchoosetoimplementany,all,ornoneofthe
abstractmethodsfromanyoftheinterfaces,thusleavingtherestoftheimplementationstoaconcrete
subclassofBall,asfollows:
Figure2-5comparesconcreteandabstractexamplesofextendsandimplementsforbothclassesand
interfaces.
FIGURE2-5 Comparingconcreteandabstractexamplesofextendsandimplements
Java8—NowwithMultipleInheritance!
Itmighthavealreadyoccurredtoyouthatsinceinterfacescannowhaveconcretemethodsandclasses
canimplementmultipleinterfaces,thespectreofmultipleinheritanceandtheDeadlyDiamondofDeath
canrearitsuglyhead!Well,you’repartlycorrect.AclassCANimplementinterfaceswithduplicate,
concretemethodsignatures!Butthegoodnewsisthatthecompiler’sgotyourback,andifyouDOwantto
implementbothinterfaces,you’llhavetoprovideanoverridingmethodinyourclass.Let’slookatthe
followingcode:
Lookforillegalusesofextendsandimplements.Thefollowingshowsexamplesoflegaland
illegalclassandinterfacedeclarations:
Burnthesein,andwatchforabusesinthequestionsyougetontheexam.Regardlessofwhat
thequestionappearstobetesting,therealproblemmightbetheclassorinterfacedeclaration.
Beforeyougetcaughtupin,say,tracingacomplexthreadingflow,checktoseeifthecodewill
evencompile.(Justthattipalonemaybeworthyourputtingusinyourwill!)(You’llbe
impressedbytheefforttheexamdevelopersputintodistractingyoufromtherealproblem.)
(Howdidpeoplemanagetowriteanythingbeforeparentheseswereinvented?)
Asthecodestands,itWILLNOTCOMPILEbecauseit’snotclearwhichversionofdoStuff()should
beused.Inordertomakethecodecompile,youneedtooverridedoStuff()intheclass.Uncommenting
theclass’sdoStuff()methodwouldallowthecodetocompileandwhenrunproducethefollowing
output:
3
CERTIFICATIONOBJECTIVE
LegalReturnTypes(OCAObjectives2.2and6.1)
2.2Differentiatebetweenobjectreferencevariablesandprimitivevariables.
6.1Createmethodswithargumentsandreturnvalues;includingoverloadedmethods.
Thissectioncoverstwoaspectsofreturntypes:whatyoucandeclareasareturntype,andwhatyou
canactuallyreturnasavalue.Whatyoucanandcannotdeclareisprettystraightforward,butitall
dependsonwhetheryou’reoverridinganinheritedmethodorsimplydeclaringanewmethod(which
includesoverloadedmethods).We’lltakejustaquicklookatthedifferencebetweenreturntyperulesfor
overloadedandoverridingmethods,becausewe’vealreadycoveredthatinthischapter.We’llcovera
smallbitofnewground,though,whenwelookatpolymorphicreturntypesandtherulesforwhatisand
isnotlegaltoactuallyreturn.
ReturnTypeDeclarations
Thissectionlooksatwhatyou’reallowedtodeclareasareturntype,whichdependsprimarilyon
whetheryouareoverriding,overloading,ordeclaringanewmethod.
ReturnTypesonOverloadedMethods
Rememberthatmethodoverloadingisnotmuchmorethannamereuse.Theoverloadedmethodisa
completelydifferentmethodfromanyothermethodofthesamename.Soifyouinheritamethodbut
overloaditinasubtype,you’renotsubjecttotherestrictionsofoverriding,whichmeansyoucandeclare
anyreturntypeyoulike.Whatyoucan’tdoischangeonlythereturntype.Tooverloadamethod,
remember,youmustchangetheargumentlist.Thefollowingcodeshowsanoverloadedmethod:
NoticethattheBarversionofthemethodusesadifferentreturntype.That’sperfectlyfine.Aslongas
you’vechangedtheargumentlist,you’reoverloadingthemethod,sothereturntypedoesn’thavetomatch
thatofthesupertypeversion.Whatyou’reNOTallowedtodoisthis:
OverridingandReturnTypesandCovariantReturns
Whenasubtypewantstochangethemethodimplementationofaninheritedmethod(anoverride),the
subtypemustdefineamethodthatmatchestheinheritedversionexactly.Or,sinceJava5,you’reallowed
tochangethereturntypeintheoverridingmethodaslongasthenewreturntypeisasubtypeofthe
declaredreturntypeoftheoverridden(superclass)method.
Let’slookatacovariantreturninaction:
SinceJava5,thiscodecompiles.Ifyouweretoattempttocompilethiscodewitha1.4compilerorwith
thesourceflagasfollows,
javac-source1.4Beta.java
youwouldgetacompilererrorlikethis:
attemptingtouseincompatiblereturntype
Otherrulesapplytooverriding,includingthoseforaccessmodifiersanddeclaredexceptions,but
thoserulesaren’trelevanttothereturntypediscussion.
Fortheexam,besureyouknowthatoverloadedmethodscanchangethereturntype,but
overridingmethodscandosoonlywithintheboundsofcovariantreturns.Justthatknowledge
alonewillhelpyouthroughawiderangeofexamquestions.
ReturningaValue
Youhavetorememberonlysixrulesforreturningavalue:
1.Youcanreturnnullinamethodwithanobjectreferencereturntype.
2.Anarrayisaperfectlylegalreturntype.
3.Inamethodwithaprimitivereturntype,youcanreturnanyvalueorvariablethatcanbe
implicitlyconvertedtothedeclaredreturntype.
4.Inamethodwithaprimitivereturntype,youcanreturnanyvalueorvariablethatcanbe
explicitlycasttothedeclaredreturntype.
5.Youmustnotreturnanythingfromamethodwithavoidreturntype.
6.Inamethodwithanobjectreferencereturntype,youcanreturnanyobjecttypethatcanbe
implicitlycasttothedeclaredreturntype.
Watchformethodsthatdeclareanabstractclassorinterfacereturntype,andknowthatany
objectthatpassestheIS-Atest(inotherwords,wouldtesttrueusingtheinstanceofoperator)
canbereturnedfromthatmethod.Forexample:
Thiscodewillcompile,andthereturnvalueisasubtype.
CERTIFICATIONOBJECTIVE
ConstructorsandInstantiation
(OCAObjectives6.3and7.4)
6.3Createandoverloadconstructors;includingimpactondefaultconstructors(sic)
7.4Usesuperandthistoaccessobjectsandconstructors.
Objectsareconstructed.YouCANNOTmakeanewobjectwithoutinvokingaconstructor.Infact,you
can’tmakeanewobjectwithoutinvokingnotjusttheconstructoroftheobject’sactualclasstype,butalso
theconstructorofeachofitssuperclasses!Constructorsarethecodethatrunswheneveryouusethe
keywordnew.(Okay,tobeabitmoreaccurate,therecanalsobeinitializationblocksthatrunwhenyou
saynew,andwe’regoingtocoverinitblocksandtheirstaticinitializationcounterpartsafterwediscuss
constructors.)We’vegotplentytotalkabouthere—we’lllookathowconstructorsarecoded,whocodes
them,andhowtheyworkatruntime.Sograbyourhardhatandahammer,andlet’sdosomeobject
building.
ConstructorBasics
Everyclass,includingabstractclasses,MUSThaveaconstructor.Burnthatintoyourbrain.Butjust
becauseaclassmusthaveaconstructordoesn’tmeantheprogrammerhastotypeit.Aconstructorlooks
likethis:
classFoo{
Foo(){}//TheconstructorfortheFooclass}
Noticewhat’smissing?There’snoreturntype!Twokeypointstorememberaboutconstructorsare
thattheyhavenoreturntype,andtheirnamesmustexactlymatchtheclassname.Typically,
constructorsareusedtoinitializetheinstancevariablestate,asfollows:
Intheprecedingcodeexample,theFooclassdoesnothaveano-argconstructor.Thatmeansthe
followingwillfailtocompile:
Foof=newFoo();//Won’tcompile,nomatchingconstructor
butthefollowingwillcompile:
Soit’sverycommon(anddesirable)foraclasstohaveano-argconstructor,regardlessofhow
manyotheroverloadedconstructorsareintheclass(yes,constructorscanbeoverloaded).You
can’talwaysmakethatworkforyourclasses;occasionallyyouhaveaclasswhereitmakesno
sensetocreateaninstancewithoutsupplyinginformationtotheconstructor.Ajava.awt.Color
object,forexample,can’tbecreatedbycallingano-argconstructor,becausethatwouldbelike
sayingtotheJVM,“MakemeanewColorobject,andIreallydon’tcarewhatcoloritis…you
pick.”DoyouseriouslywanttheJVMmakingyourstyledecisions?
ConstructorChaining
Weknowthatconstructorsareinvokedatruntimewhenyousaynewonsomeclasstypeasfollows:
Horseh=newHorse();
ButwhatreallyhappenswhenyousaynewHorse()?(AssumeHorseextendsAnimalandAnimal
extendsObject.)
1.TheHorseconstructorisinvoked.Everyconstructorinvokestheconstructorofits
superclasswithan(implicit)calltosuper(),unlesstheconstructorinvokesanoverloaded
constructorofthesameclass(moreonthatinaminute).
2.TheAnimalconstructorisinvoked(AnimalisthesuperclassofHorse).
3.TheObjectconstructorisinvoked(Objectistheultimatesuperclassofallclasses,so
classAnimalextendsObjecteventhoughyoudon’tactuallytype“extendsObject”intothe
Animalclassdeclaration;it’simplicit.)Atthispointwe’reonthetopofthestack.
4.IfclassObjecthadanyinstancevariables,thentheywouldbegiventheirexplicitvalues.
Byexplicitvalues,wemeanvaluesthatareassignedatthetimethevariablesaredeclared,
suchasintx=27,where27istheexplicitvalue(asopposedtothedefaultvalue)ofthe
instancevariable.
5.TheObjectconstructorcompletes.
6.TheAnimalinstancevariablesaregiventheirexplicitvalues(ifany).
7.TheAnimalconstructorcompletes.
8.TheHorseinstancevariablesaregiventheirexplicitvalues(ifany).
9.TheHorseconstructorcompletes.
Figure2-6showshowconstructorsworkonthecallstack.
FIGURE2-6 Constructorsonthecallstack
RulesforConstructors
Thefollowinglistsummarizestherulesyou’llneedtoknowfortheexam(andtounderstandthe
restofthissection).YouMUSTrememberthese,sobesuretostudythemmorethanonce.
Constructorscanuseanyaccessmodifier,includingprivate.(Aprivateconstructor
meansonlycodewithintheclassitselfcaninstantiateanobjectofthattype,soiftheprivate
constructorclasswantstoallowaninstanceoftheclasstobeused,theclassmustprovidea
staticmethodorvariablethatallowsaccesstoaninstancecreatedfromwithintheclass.)
Theconstructornamemustmatchthenameoftheclass.
Constructorsmustnothaveareturntype.
It’slegal(butstupid)tohaveamethodwiththesamenameastheclass,butthatdoesn’t
makeitaconstructor.Ifyouseeareturntype,it’samethodratherthanaconstructor.In
fact,youcouldhavebothamethodandaconstructorwiththesamename—thenameofthe
class—inthesameclass,andthat’snotaproblemforJava.Becarefulnottomistakea
methodforaconstructor—besuretolookforareturntype.
Ifyoudon’ttypeaconstructorintoyourclasscode,adefaultconstructorwillbe
automaticallygeneratedbythecompiler.
ThedefaultconstructorisALWAYSano-argconstructor.
Ifyouwantano-argconstructorandyou’vetypedanyotherconstructor(s)intoyour
classcode,thecompilerwon’tprovidetheno-argconstructor(oranyotherconstructor)for
you.Inotherwords,ifyou’vetypedinaconstructorwitharguments,youwon’thaveano-arg
constructorunlessyoutypeditinyourself!
Everyconstructorhas,asitsfirststatement,eitheracalltoanoverloadedconstructor
(this())oracalltothesuperclassconstructor(super()),althoughrememberthatthiscall
canbeinsertedbythecompiler.
Ifyoudotypeinaconstructor(asopposedtorelyingonthecompiler-generateddefault
constructor),andyoudonottypeinthecalltosuper()oracalltothis(),thecompilerwill
insertano-argcalltosuper()foryouastheveryfirststatementintheconstructor.
Acalltosuper()caneitherbeano-argcallorcanincludeargumentspassedtothe
superconstructor.
Ano-argconstructorisnotnecessarilythedefault(thatis,compiler-supplied)
constructor,althoughthedefaultconstructorisalwaysano-argconstructor.Thedefault
constructoristheonethecompilerprovides!Althoughthedefaultconstructorisalwaysano-
argconstructor,you’refreetoputinyourownno-argconstructor.
Youcannotmakeacalltoaninstancemethodoraccessaninstancevariableuntilafter
thesuperconstructorruns.
Onlystaticvariablesandmethodscanbeaccessedaspartofthecalltosuper()or
this().(Example:super(Animal.NAME)isOK,becauseNAMEisdeclaredasastatic
variable.)
Abstractclasseshaveconstructors,andthoseconstructorsarealwayscalledwhena
concretesubclassisinstantiated.
Interfacesdonothaveconstructors.Interfacesarenotpartofanobject’sinheritance
tree.
Theonlywayaconstructorcanbeinvokedisfromwithinanotherconstructor.Inother
words,youcan’twritecodethatactuallycallsaconstructorasfollows:
DetermineWhetheraDefaultConstructorWillBeCreated
ThefollowingexampleshowsaHorseclasswithtwoconstructors:
Willthecompilerputinadefaultconstructorforthisclass?No!
Howaboutforthefollowingvariationoftheclass?
classHorse{
Horse(Stringname){}
}
Nowwillthecompilerinsertadefaultconstructor?No!
Whataboutthisclass?
classHorse{}
Nowwe’retalking.Thecompilerwillgenerateadefaultconstructorforthisclassbecausetheclass
doesn’thaveanyconstructorsdefined.
Okay,whataboutthisclass?
classHorse{
voidHorse(){}
}
Itmightlooklikethecompilerwon’tcreateaconstructor,sinceoneisalreadyintheHorseclass.
Orisit?TakeanotherlookattheprecedingHorseclass.
What’swrongwiththeHorse()constructor?Itisn’taconstructoratall!It’ssimplyamethod
thathappenstohavethesamenameastheclass.Remember,thereturntypeisadeadgiveaway
thatwe’relookingatamethod,notaconstructor.
Howdoyouknowforsurewhetheradefaultconstructorwillbecreated?Because
youdidn’twriteanyconstructorsinyourclass.
Howdoyouknowwhatthedefaultconstructorwilllooklike?Because...
Thedefaultconstructorhasthesameaccessmodifierastheclass.
Thedefaultconstructorhasnoarguments.
Thedefaultconstructorincludesano-argcalltothesuperconstructor(super()).
Table2-5showswhatthecompilerwill(orwon’t)generateforyourclass.
TABLE2-5 Compiler-GeneratedConstructorCode
Whathappensifthesuperconstructorhasarguments?Constructorscanhave
argumentsjustasmethodscan,andifyoutrytoinvokeamethodthattakes,say,anint,butyou
don’tpassanythingtothemethod,thecompilerwillcomplainasfollows:
Thecompilerwillcomplainthatyoucan’tinvoketakeInt()withoutpassinganint.Ofcourse,
thecompilerenjoystheoccasionalriddle,sothemessageitspitsoutonsomeversionsoftheJVM
(yourmileagemayvary)islessthanobvious:
UseBar.java:7:takeInt(int)inBarcannotbeappliedto()
b.takeInt();
^
Butyougettheidea.Thebottomlineisthattheremustbeamatchforthemethod.Andbymatch,
wemeantheargumenttypesmustbeabletoacceptthevaluesorvariablesyou’repassingandin
theorderyou’repassingthem.Whichbringsusbacktoconstructors(andhereyouwerethinking
we’dnevergetthere),whichworkexactlythesameway.
Soifyoursuperconstructor(thatis,theconstructorofyourimmediatesuperclass/parent)has
arguments,youmusttypeinthecalltosuper(),supplyingtheappropriatearguments.Crucial
point:ifyoursuperclassdoesnothaveano-argconstructor,youmusttypeaconstructorinyour
class(thesubclass)becauseyouneedaplacetoputinthecalltosuper()withtheappropriate
arguments.
Thefollowingisanexampleoftheproblem:
Andonceagainthecompilertreatsuswithstunninglucidity:
Ifyou’relucky(andit’safullmoon),yourcompilermightbealittlemoreexplicit.Butagain,the
problemisthattherejustisn’tamatchforwhatwe’retryingtoinvokewithsuper()—anAnimal
constructorwithnoarguments.
Anotherwaytoputthisisthatifyoursuperclassdoesnothaveano-argconstructor,theninyour
subclassyouwillnotbeabletousethedefaultconstructorsuppliedbythecompiler.It’sthatsimple.
Becausethecompilercanonlyputinacalltoano-argsuper(),youwon’tevenbeabletocompile
somethinglikethis:
Tryingtocompilethiscodegivesusexactlythesameerrorwegotwhenweputaconstructorin
thesubclasswithacalltotheno-argversionofsuper():
Infact,theprecedingClothingandTShirtcodeisimplicitlythesameasthefollowingcode,
wherewe’vesuppliedaconstructorforTShirtthat’sidenticaltothedefaultconstructorsupplied
bythecompiler:
Onelastpointonthewholedefaultconstructorthing(andit’sprobablyveryobvious,butwe
havetosayitorwe’llfeelguiltyforyears),constructorsareneverinherited.Theyaren’tmethods.
Theycan’tbeoverridden(becausetheyaren’tmethods,andonlyinstancemethodscanbe
overridden).Sothetypeofconstructor(s)yoursuperclasshasinnowaydeterminesthetypeof
defaultconstructoryou’llget.Somefolksmistakenlybelievethatthedefaultconstructorsomehow
matchesthesuperconstructor,eitherbytheargumentsthedefaultconstructorwillhave
(remember,thedefaultconstructorisalwaysano-arg)orbytheargumentsusedinthecompiler-
suppliedcalltosuper().
Soalthoughconstructorscan’tbeoverridden,you’vealreadyseenthattheycanbeoverloaded,
andtypicallyare.
OverloadedConstructors
Overloadingaconstructormeanstypinginmultipleversionsoftheconstructor,eachhavinga
differentargumentlist,likethefollowingexamples:
TheprecedingFooclasshastwooverloadedconstructors:onethattakesastring,andonewith
noarguments.Becausethere’snocodeintheno-argversion,it’sactuallyidenticaltothedefault
constructorthecompilersupplies—butremember,sincethere’salreadyaconstructorinthisclass
(theonethattakesastring),thecompilerwon’tsupplyadefaultconstructor.Ifyouwantano-arg
constructortooverloadthewith-argsversionyoualreadyhave,you’regoingtohavetotypeit
yourself,justasintheFooexample.
Overloadingaconstructoristypicallyusedtoprovidealternatewaysforclientstoinstantiate
objectsofyourclass.Forexample,ifaclientknowstheanimalname,theycanpassthattoan
Animalconstructorthattakesastring.Butiftheydon’tknowthename,theclientcancalltheno-
argconstructor,andthatconstructorcansupplyadefaultname.Here’swhatitlookslike:
Runningthecodefourtimesproducesthisoutput:
There’salotgoingonintheprecedingcode.Figure2-7showsthecallstackforconstructor
invocationswhenaconstructorisoverloaded.
FIGURE2-7 Overloadedconstructorsonthecallstack
Takealookatthecallstack,andthenlet’swalkthroughthecodestraightfromthetop.
Line2DeclareaStringinstancevariablename.
Lines3–5ConstructorthattakesaStringandassignsittoinstancevariablename.
Line7Here’swhereitgetsfun.Assumeeveryanimalneedsaname,buttheclient
(callingcode)mightnotalwaysknowwhatthenameshouldbe,sotheAnimalclasswillassign
arandomname.Theno-argconstructorgeneratesanamebyinvokingthemakeRandomName()
method.
Line8Theno-argconstructorinvokesitsownoverloadedconstructorthattakesa
String,ineffectcallingitthesamewayitwouldbecalledifclientcodeweredoinganewto
instantiateanobject,passingitaStringforthename.Theoverloadedinvocationusesthe
keywordthis,butusesitasthoughitwereamethodnamedthis().Soline8issimply
callingtheconstructoronline3,passingitarandomlyselectedStringratherthanaclient-
codechosenname.
Line11NoticethatthemakeRandomName()methodismarkedstatic!That’sbecause
youcannotinvokeaninstance(inotherwords,nonstatic)method(oraccessaninstance
variable)untilafterthesuperconstructorhasrun.Andsincethesuperconstructorwillbe
invokedfromtheconstructoronline3,ratherthanfromtheoneonline7,line8canuseonly
astaticmethodtogeneratethename.Ifwewantedallanimalsnotspecificallynamedbythe
callertohavethesamedefaultname,say,“Fred,”thenline8couldhavereadthis(“Fred”);
ratherthancallingamethodthatreturnsastringwiththerandomlychosenname.
Line12Thisdoesn’thaveanythingtodowithconstructors,butsincewe’reallhereto
learn,itgeneratesarandomintegerbetween0and4.
Line13Weirdsyntax,weknow.We’recreatinganewStringobject(justasingle
Stringinstance),butwewantthestringtobeselectedrandomlyfromalist.Exceptwedon’t
havethelist,soweneedtomakeit.Sointhatonelineofcodewe
1.DeclareaStringvariablename.
2.CreateaStringarray(anonymously—wedon’tassignthearrayitselftoavariable).
3.Retrievethestringatindex[x](xbeingtherandomnumbergeneratedonline12)of
thenewlycreatedStringarray.
4.Assignthestringretrievedfromthearraytothedeclaredinstancevariablename.We
couldhavemadeitmucheasiertoreadifwe’djustwritten
Butwhere’sthefuninthat?Throwinginunusualsyntax(especiallyforcodewholly
unrelatedtotherealquestion)isinthespiritoftheexam.Don’tbestartled!(Okay,be
startled,butthenjustsaytoyourself,“Whoa!”andgetonwithit.)
Line18We’reinvokingtheno-argversionoftheconstructor(causingarandomname
fromthelisttobepassedtotheotherconstructor).
Line20We’reinvokingtheoverloadedconstructorthattakesastringrepresentingthe
name.
Thekeypointtogetfromthiscodeexampleisinline8.Ratherthancallingsuper(),we’re
callingthis(),andthis()alwaysmeansacalltoanotherconstructorinthesameclass.Okay,fine,
butwhathappensafterthecalltothis()?Soonerorlaterthesuper()constructorgetscalled,
right?Yes,indeed.Acalltothis()justmeansyou’redelayingtheinevitable.Someconstructor,
somewhere,mustmakethecalltosuper().
KeyRule:Thefirstlineinaconstructormustbeacalltosuper()oracalltothis().
Noexceptions.Ifyouhaveneitherofthosecallsinyourconstructor,thecompilerwillinserttheno-
argcalltosuper().Inotherwords,ifconstructorA()hasacalltothis(),thecompilerknowsthat
constructorA()willnotbetheonetoinvokesuper().
Theprecedingrulemeansaconstructorcanneverhavebothacalltosuper()andacallto
this().Becauseeachofthosecallsmustbethefirststatementinaconstructor,youcan’tlegally
usebothinthesameconstructor.Thatalsomeansthecompilerwillnotputacalltosuper()inany
constructorthathasacalltothis().
Thoughtquestion:Whatdoyouthinkwillhappenifyoutrytocompilethefollowingcode?
Yourcompilermaynotactuallycatchtheproblem(itvariesdependingonyourcompiler,butmost
won’tcatchtheproblem).Itassumesyouknowwhatyou’redoing.Canyouspottheflaw?Given
thatasuperconstructormustalwaysbecalled,wherewouldthecalltosuper()go?Remember,
thecompilerwon’tputinadefaultconstructorifyou’vealreadygotoneormoreconstructorsin
yourclass.Andwhenthecompilerdoesn’tputinadefaultconstructor,itstillinsertsacallto
super()inanyconstructorthatdoesn’texplicitlyhaveacalltothesuperconstructor—unless,that
is,theconstructoralreadyhasacalltothis().Sointheprecedingcode,wherecansuper()go?
Theonlytwoconstructorsintheclassbothhavecallstothis(),and,infact,you’llgetexactlywhat
you’dgetifyoutypedthefollowingmethodcode:
publicvoidgo(){
doStuff();
}
publicvoiddoStuff(){
go();
}
Nowcanyouseetheproblem?Ofcourseyoucan.Thestackexplodes!Itgetshigherandhigher
andhigheruntilitjustburstsopenandmethodcodegoesspillingout,oozingoutoftheJVMright
ontothefloor.Twooverloadedconstructorsbothcallingthis()aretwoconstructorscallingeach
other—overandoverandover,resultinginthis:
%javaA
Exceptioninthread“main”java.lang.StackOverflowError
Thebenefitofhavingoverloadedconstructorsisthatyouofferflexiblewaystoinstantiate
objectsfromyourclass.Thebenefitofhavingoneconstructorinvokeanotheroverloaded
constructoristoavoidcodeduplication.IntheAnimalexample,therewasn’tanycodeotherthan
settingthename,butimagineifafterline4therewasstillmoreworktobedoneintheconstructor.
Byputtingalltheotherconstructorworkinjustoneconstructor,andthenhavingtheother
constructorsinvokeit,youdon’thavetowriteandmaintainmultipleversionsofthatother
importantconstructorcode.Basically,eachoftheothernot-the-real-oneoverloadedconstructors
willcallanotheroverloadedconstructor,passingitwhateverdataitneeds(datatheclientcode
didn’tsupply).
Constructorsandinstantiationbecomeevenmoreexciting(justwhenyouthoughtitwassafe)
whenyougettoinnerclasses,butweknowyoucanstandtohaveonlysomuchfuninonechapter,
andbesides,youdon’thavetodealwithinnerclassesuntilyoutackletheOCPexam.
CERTIFICATIONOBJECTIVE
InitializationBlocks(OCAObjectives1.2and6.3-ish)
1.2DefinethestructureofaJavaclass
6.3Createandoverloadconstructors;includingimpactondefaultconstructors
We’vetalkedabouttwoplacesinaclasswhereyoucanputcodethatperformsoperations:
methodsandconstructors.InitializationblocksarethethirdplaceinaJavaprogramwhere
operationscanbeperformed.Staticinitializationblocksrunwhentheclassisfirstloaded,and
instanceinitializationblocksrunwheneveraninstanceiscreated(abitsimilartoaconstructor).
Let’slookatanexample:
Asyoucansee,thesyntaxforinitializationblocksisprettyterse.Theydon’thavenames,they
can’ttakearguments,andtheydon’treturnanything.Astaticinitializationblockrunsoncewhen
theclassisfirstloaded.Aninstanceinitializationblockrunsonceeverytimeanewinstanceis
created.Rememberwhenwetalkedabouttheorderinwhichconstructorcodeexecuted?Instance
initblockcoderunsrightafterthecalltosuper()inaconstructor—inotherwords,afterall
superconstructorshaverun.
Youcanhavemanyinitializationblocksinaclass.Itisimportanttonotethatunlikemethodsor
constructors,theorderinwhichinitializationblocksappearinaclassmatters.Whenit’stimefor
initializationblockstorun,ifaclasshasmorethanone,theywillrunintheorderinwhichthey
appearintheclassfile—inotherwords,fromthetopdown.Basedontheruleswejustdiscussed,
canyoudeterminetheoutputofthefollowingprogram?
Tofigurethisout,remembertheserules:
initblocksexecuteintheorderinwhichtheyappear.
Staticinitblocksrunonce,whentheclassisfirstloaded.
Instanceinitblocksruneverytimeaclassinstanceiscreated.
Instanceinitblocksrunaftertheconstructor’scalltosuper().
Withthoserulesinmind,thefollowingoutputshouldmakesense:
Asyoucansee,theinstanceinitblockseachrantwice.Instanceinitblocksareoftenusedasa
placetoputcodethatalltheconstructorsinaclassshouldshare.Thatway,thecodedoesn’thave
tobeduplicatedacrossconstructors.
Finally,ifyoumakeamistakeinyourstaticinitblock,theJVMcanthrowan
ExceptionInInitializerError.Let’slookatanexample:
Itproducessomethinglikethis:
Byconvention,initblocksusuallyappearnearthetopoftheclassfile,somewherearoundthe
constructors.However,thisistheOCAexamwe’retalkingabout.Don’tbesurprisedifyou
findaninitblocktuckedinbetweenacoupleofmethods,lookingforalltheworldlikea
compilererrorwaitingtohappen!
CERTIFICATIONOBJECTIVE
Statics(OCAObjective6.2)
6.2Applythestatickeywordtomethodsandfields.
StaticVariablesandMethods
Thestaticmodifierhassuchaprofoundimpactonthebehaviorofamethodorvariablethatwe’re
treatingitasaconceptentirelyseparatefromtheothermodifiers.Tounderstandthewayastatic
memberworks,we’lllookfirstatareasonforusingone.Imagineyou’vegotautilityclassor
interfacewithamethodthatalwaysrunsthesameway;itssolefunctionistoreturn,say,arandom
number.Itwouldn’tmatterwhichinstanceoftheclassperformedthemethod—itwouldalways
behaveexactlythesameway.Inotherwords,themethod’sbehaviorhasnodependencyonthe
state(instancevariablevalues)ofanobject.Sowhy,then,doyouneedanobjectwhenthemethod
willneverbeinstance-specific?Whynotjustaskthetypeitselftorunthemethod?
Let’simagineanotherscenario:Supposeyouwanttokeeparunningcountofallinstances
instantiatedfromaparticularclass.Wheredoyouactuallykeepthatvariable?Itwon’tworkto
keepitasaninstancevariablewithintheclasswhoseinstancesyou’retracking,becausethecount
willjustbeinitializedbacktoadefaultvaluewitheachnewinstance.Theanswertoboththe
utility-method-always-runs-the-samescenarioandthekeep-a-running-total-of-instancesscenariois
tousethestaticmodifier.Variablesandmethodsmarkedstaticbelongtothetype,ratherthanto
anyparticularinstance.Infact,forclasses,youcanuseastaticmethodorvariablewithouthaving
anyinstancesofthatclassatall.Youneedonlyhavethetypeavailabletobeabletoinvokea
staticmethodoraccessastaticvariable.staticvariables,too,canbeaccessedwithouthaving
aninstanceofaclass.Butifthereareinstances,astaticvariableofaclasswillbesharedbyall
instancesofthatclass;thereisonlyonecopy.
Thefollowingcodedeclaresandusesastaticcountervariable:
Intheprecedingcode,thestaticfrogCountvariableissettozerowhentheFrogclassisfirst
loadedbytheJVM,beforeanyFroginstancesarecreated!(Bytheway,youdon’tactuallyneedto
initializeastaticvariabletozero;staticvariablesgetthesamedefaultvaluesinstancevariables
get.)WheneveraFroginstanceiscreated,theFrogconstructorrunsandincrementsthestatic
frogCountvariable.Whenthiscodeexecutes,threeFroginstancesarecreatedinmain(),andthe
resultis
Frogcountisnow3
NowimaginewhatwouldhappeniffrogCountwereaninstancevariable(inotherwords,
nonstatic):
Whenthiscodeexecutes,itshouldstillcreatethreeFroginstancesinmain(),buttheresultis…a
compilererror!Wecan’tgetthiscodetocompile,letalonerun.
TheJVMdoesn’tknowwhichFrogobject’sfrogCountyou’retryingtoaccess.Theproblemis
thatmain()isitselfastaticmethodandthusisn’trunningagainstanyparticularinstanceofthe
class;insteadit’srunningontheclassitself.Astaticmethodcan’taccessanonstatic(instance)
variablebecausethereisnoinstance!That’snottosaytherearen’tinstancesoftheclassaliveon
theheap,butratherthatevenifthereare,thestaticmethoddoesn’tknowanythingaboutthem.
Thesameappliestoinstancemethods;astaticmethodcan’tdirectlyinvokeanonstaticmethod.
Thinkstatic=class,nonstatic=instance.MakingthemethodcalledbytheJVM(main())astatic
methodmeanstheJVMdoesn’thavetocreateaninstanceofyourclassjusttostartrunningcode.
OneofthemistakesmostoftenmadebynewJavaprogrammersisattemptingtoaccessan
instancevariable(whichmeansnonstaticvariable)fromthestaticmain()method(which
doesn’tknowanythingaboutanyinstances,soitcan’taccessthevariable).Thefollowingcode
isanexampleofillegalaccessofanonstaticvariablefromastaticmethod:
Understandthatthiscodewillnevercompile,becauseyoucan’taccessanonstatic(instance)
variablefromastaticmethod.Justthinkofthecompilersaying,“Hey,Ihavenoideawhich
Fooobject’sxvariableyou’retryingtoprint!”Remember,it’stheclassrunningthemain()
method,notaninstanceoftheclass.
Ofcourse,thetrickypartfortheexamisthatthequestionwon’tlookasobviousasthe
precedingcode.Theproblemyou’rebeingtestedfor—accessinganonstaticvariablefroma
staticmethod—willbeburiedincodethatmightappeartobetestingsomethingelse.For
example,theprecedingcodewouldbemorelikelytoappearas
Sowhileyou’retryingtofollowthelogic,therealissueisthatxandycan’tbeusedwithin
main()becausexandyareinstance,notstatic,variables!Thesameappliesforaccessing
nonstaticmethodsfromastaticmethod.Theruleis,astaticmethodofaclasscan’taccessa
nonstatic(instance)methodorvariableofitsownclass.
AccessingStaticMethodsandVariables
Sinceyoudon’tneedtohaveaninstanceinordertoinvokeastaticmethodoraccessastatic
variable,howdoyouinvokeoruseastaticmember?What’sthesyntax?Weknowthatwitha
regularoldinstancemethod,youusethedotoperatoronareferencetoaninstance:
Intheprecedingcode,weinstantiateaFrog,assignittothereferencevariablef,andthenuse
thatfreferencetoinvokeamethodontheFroginstancewejustcreated.Inotherwords,the
getFrogSize()methodisbeinginvokedonaspecificFrogobjectontheheap.
Butthisapproach(usingareferencetoanobject)isn’tappropriateforaccessingastatic
method,becausetheremightnotbeanyinstancesoftheclassatall!Sothewayweaccessastatic
method(orstaticvariable)istousethedotoperatoronthetypename,asopposedtousingitona
referencetoaninstance,asfollows:
whichproducestheoutput:
fromstatic3
frominstance4
userefvar5
Butjusttomakeitreallyconfusing,theJavalanguagealsoallowsyoutouseanobjectreference
variabletoaccessastaticmember.Didyoucatchthelastlineofmain()?Itincludedthis
invocation:
f.getCount();//Accessastaticusinganinstancevariable
Intheprecedingcode,weinstantiateaFrog,assignthenewFrogobjecttothereference
variablef,andthenusethefreferencetoinvokeastaticmethod!Buteventhoughweareusinga
specificFroginstancetoaccessthestaticmethod,theruleshaven’tchanged.Thisismerelya
syntaxtricktoletyouuseanobjectreferencevariable(butnottheobjectitrefersto)togettoa
staticmethodorvariable,butthestaticmemberisstillunawareoftheparticularinstanceused
toinvokethestaticmember.IntheFrogexample,thecompilerknowsthatthereferencevariable
fisoftypeFrog,andsotheFrogclassstaticmethodisrunwithnoawarenessorconcernforthe
Froginstanceattheotherendofthefreference.Inotherwords,thecompilercaresonlythat
referencevariablefisdeclaredastypeFrog.
Invokingstaticmethodsfrominterfacesisalmostthesameasinvokingstaticmethodsfrom
classes,exceptthe“instancevariablesyntaxtrick”justdiscussedworksonlyforstaticmethodsin
classes.Thefollowingcodedemonstrateshowinterfacestaticmethodscanandcannotbeinvoked:
Let’sreviewthecode:
Line1isalegalinvocationofaninterface’sdefaultmethod.
Line2isanillegalattempttoinvokeaninterface’sstaticmethod.
Line3isTHElegalwaytoinvokeaninterface’sstaticmethod.
Line4isanotherillegalattempttoinvokeaninterface’sstaticmethod.
Figure2-8illustratestheeffectsofthestaticmodifieronmethodsandvariables.
FIGURE2-8 Theeffectsofstaticonmethodsandvariables
Finally,rememberthatstaticmethodscan’tbeoverridden!Thisdoesn’tmeantheycan’tbe
redefinedinasubclass,butredefiningandoverridingaren’tthesamething.Let’slookatan
exampleofaredefined(remember,notoverridden)staticmethod:
Runningthiscodeproducesthisoutput:
aaad
Remember,thesyntaxa[x].doStuff()isjustashortcut(thesyntaxtrick)—thecompileris
goingtosubstitutesomethinglikeAnimal.doStuff()instead.Noticealsothatyoucaninvokea
staticmethodbyusingtheclassname.
Noticethatwedidn’tusetheenhancedforloophere(coveredinChapter5),eventhoughwe
couldhave.ExpecttoseeamixofbothJava1.4andJava5–8codingstylesandpracticesonthe
exam.
CERTIFICATIONSUMMARY
WestartedthechapterbydiscussingtheimportanceofencapsulationingoodOOdesign,andthen
wetalkedabouthowgoodencapsulationisimplemented:withprivateinstancevariablesandpublic
gettersandsetters.
Next,wecoveredtheimportanceofinheritance,sothatyoucangraspoverriding,overloading,
polymorphism,referencecasting,returntypes,andconstructors.
WecoveredIS-AandHAS-A.IS-Aisimplementedusinginheritance,andHAS-Aisimplemented
byusinginstancevariablesthatrefertootherobjects.
Polymorphismwasnext.Althoughareferencevariable’stypecan’tbechanged,itcanbeusedto
refertoanobjectwhosetypeisasubtypeofitsown.Welearnedhowtodeterminewhatmethods
areinvocableforagivenreferencevariable.
Welookedatthedifferencebetweenoverriddenandoverloadedmethods,learningthatan
overriddenmethodoccurswhenasubtypeinheritsamethodfromasupertypeandthen
reimplementsthemethodtoaddmorespecializedbehavior.Welearnedthat,atruntime,theJVM
willinvokethesubtypeversiononaninstanceofasubtypeandthesupertypeversiononaninstance
ofthesupertype.Abstractmethodsmustbe“overridden”(technically,abstractmethodsmustbe
implemented,asopposedtooverridden,sincetherereallyisn’tanythingtooverride).
Wesawthatoverridingmethodsmustdeclarethesameargumentlistandreturntypeortheycan
returnasubtypeofthedeclaredreturntypeofthesupertype’soverriddenmethod),andthatthe
accessmodifiercan’tbemorerestrictive.Theoverridingmethodalsocan’tthrowanynewor
broadercheckedexceptionsthatweren’tdeclaredintheoverriddenmethod.Youalsolearnedthat
theoverriddenmethodcanbeinvokedusingthesyntaxsuper.doSomething();.
Overloadedmethodsletyoureusethesamemethodnameinaclass,butwithdifferent
arguments(and,optionally,adifferentreturntype).Whereasoverridingmethodsmustnotchange
theargumentlist,overloadedmethodsmust.Butunlikeoverridingmethods,overloadedmethods
arefreetovarythereturntype,accessmodifier,anddeclaredexceptionsanywaytheylike.
Welearnedthemechanicsofcasting(mostlydowncasting)referencevariablesandwhenit’s
necessarytodoso.
Implementinginterfacescamenext.Aninterfacedescribesacontractthattheimplementing
classmustfollow.Therulesforimplementinganinterfacearesimilartothoseforextendingan
abstractclass.AsofJava8,interfacescanhaveconcretemethods,whicharelabeleddefault.
Also,rememberthataclasscanimplementmorethanoneinterfaceandthatinterfacescanextend
anotherinterface.
Wealsolookedatmethodreturntypesandsawthatyoucandeclareanyreturntypeyoulike
(assumingyouhaveaccesstoaclassforanobjectreferencereturntype),unlessyou’reoverriding
amethod.Barringacovariantreturn,anoverridingmethodmusthavethesamereturntypeasthe
overriddenmethodofthesuperclass.Wesawthat,althoughoverridingmethodsmustnotchange
thereturntype,overloadedmethodscan(aslongastheyalsochangetheargumentlist).
Finally,youlearnedthatitislegaltoreturnanyvalueorvariablethatcanbeimplicitlyconverted
tothedeclaredreturntype.So,forexample,ashortcanbereturnedwhenthereturntypeis
declaredasanint.And(assumingHorseextendsAnimal),aHorsereferencecanbereturnedwhen
thereturntypeisdeclaredanAnimal.
Wecoveredconstructorsindetail,learningthatifyoudon’tprovideaconstructorforyourclass,
thecompilerwillinsertone.Thecompiler-generatedconstructoriscalledthedefaultconstructor,
anditisalwaysano-argconstructorwithano-argcalltosuper().Thedefaultconstructorwill
neverbegeneratedifevenasingleconstructorexistsinyourclass(regardlessoftheargumentsof
thatconstructor);soifyouneedmorethanoneconstructorinyourclassandyouwantano-arg
constructor,you’llhavetowriteityourself.Wealsosawthatconstructorsarenotinheritedand
thatyoucanbeconfusedbyamethodthathasthesamenameastheclass(whichislegal).The
returntypeisthegiveawaythatamethodisnotaconstructorbecauseconstructorsdonothave
returntypes.
Wesawhowalltheconstructorsinanobject’sinheritancetreewillalwaysbeinvokedwhenthe
objectisinstantiatedusingnew.Wealsosawthatconstructorscanbeoverloaded,whichmeans
definingconstructorswithdifferentargumentlists.Aconstructorcaninvokeanotherconstructorof
thesameclassusingthekeywordthis(),asthoughtheconstructorwereamethodnamedthis().
Wesawthateveryconstructormusthaveeitherthis()orsuper()asthefirststatement(although
thecompilercaninsertitforyou).
Afterconstructors,wediscussedthetwokindsofinitializationblocksandhowandwhentheir
coderuns.
Welookedatstaticmethodsandvariables.staticmembersaretiedtotheclassorinterface,
notaninstance,sothereisonlyonecopyofanystaticmember.Acommonmistakeistoattemptto
referenceaninstancevariablefromastaticmethod.Usetherespectiveclassorinterfacename
withthedotoperatortoaccessstaticmembers.
And,onceagain,youlearnedthattheexamincludestrickyquestionsdesignedlargelytotest
yourabilitytorecognizejusthowtrickythequestionscanbe.
TWO-MINUTEDRILL
Herearesomeofthekeypointsfromeachcertificationobjectiveinthischapter.
Encapsulation,IS-A,HAS-A*(OCAObjective6.5)
Encapsulationhelpshideimplementationbehindaninterface(orAPI).
Encapsulatedcodehastwofeatures:
Instancevariablesarekeptprotected(usuallywiththeprivatemodifier).
Getterandsettermethodsprovideaccesstoinstancevariables.
IS-Areferstoinheritanceorimplementation.
IS-Aisexpressedwiththekeywordextendsorimplements.
IS-A,“inheritsfrom,”and“isasubtypeof”areallequivalentexpressions.
HAS-Ameansaninstanceofoneclass“hasa”referencetoaninstanceofanotherclass
oranotherinstanceofthesameclass.*HAS-AisNOTontheexam,butit’sgoodtoknow.
Inheritance(OCAObjective7.1)
Inheritanceallowsatypetobeasubtypeofasupertypeandtherebyinheritpublicand
protectedvariablesandmethodsofthesupertype.
InheritanceisakeyconceptthatunderliesIS-A,polymorphism,overriding,overloading,
andcasting.
Allclasses(exceptclassObject)aresubclassesoftypeObject,andthereforethey
inheritObject’smethods.
Polymorphism(OCAObjective7.2)
Polymorphismmeans“manyforms.”
Areferencevariableisalwaysofasingle,unchangeabletype,butitcanrefertoa
subtypeobject.
Asingleobjectcanbereferredtobyreferencevariablesofmanydifferenttypes—as
longastheyarethesametypeorasupertypeoftheobject.
Thereferencevariable’stype(nottheobject’stype)determineswhichmethodscanbe
called!
Polymorphicmethodinvocationsapplyonlytooverriddeninstancemethods.
OverridingandOverloading(OCAObjectives6.1and7.2)
Methodscanbeoverriddenoroverloaded;constructorscanbeoverloadedbutnot
overridden.
Withrespecttothemethoditoverrides,theoverridingmethod
Musthavethesameargumentlist
Musthavethesamereturntypeorasubclass(knownasacovariantreturn)
Mustnothaveamorerestrictiveaccessmodifier
Mayhavealessrestrictiveaccessmodifier
Mustnotthrowneworbroadercheckedexceptions
Maythrowfewerornarrowercheckedexceptions,oranyuncheckedexception
finalmethodscannotbeoverridden.
Onlyinheritedmethodsmaybeoverridden,andrememberthatprivatemethodsarenot
inherited.
Asubclassusessuper.overriddenMethodName()tocallthesuperclassversionofan
overriddenmethod.
AsubclassusesMyInterface.super.overriddenMethodName()tocallthesuper
interfaceversiononanoverriddenmethod.
Overloadingmeansreusingamethodnamebutwithdifferentarguments.
Overloadedmethods
Musthavedifferentargumentlists
Mayhavedifferentreturntypes,ifargumentlistsarealsodifferent
Mayhavedifferentaccessmodifiers
Maythrowdifferentexceptions
Methodsfromasupertypecanbeoverloadedinasubtype.
Polymorphismappliestooverriding,nottooverloading.
Objecttype(notthereferencevariable’stype)determineswhichoverriddenmethodis
usedatruntime.
Referencetypedetermineswhichoverloadedmethodwillbeusedatcompiletime.
ReferenceVariableCasting(OCAObjective7.3)
Therearetwotypesofreferencevariablecasting:downcastingandupcasting.
DowncastingIfyouhaveareferencevariablethatreferstoasubtypeobject,you
canassignittoareferencevariableofthesubtype.Youmustmakeanexplicitcasttodo
this,andtheresultisthatyoucanaccessthesubtype’smemberswiththisnewreference
variable.
UpcastingYoucanassignareferencevariabletoasupertypereferencevariable
explicitlyorimplicitly.Thisisaninherentlysafeoperationbecausetheassignment
restrictstheaccesscapabilitiesofthenewvariable.
ImplementinganInterface(OCAObjective7.5)
Whenyouimplementaninterface,youarefulfillingitscontract.
Youimplementaninterfacebyproperlyandconcretelyimplementingalltheabstract
methodsdefinedbytheinterface.
Asingleclasscanimplementmanyinterfaces.
ReturnTypes(OCAObjectives7.2and7.5)
Overloadedmethodscanchangereturntypes;overriddenmethodscannot,exceptinthe
caseofcovariantreturns.
Objectreferencereturntypescanacceptnullasareturnvalue.
Anarrayisalegalreturntype,bothtodeclareandreturnasavalue.
Formethodswithprimitivereturntypes,anyvaluethatcanbeimplicitlyconvertedto
thereturntypecanbereturned.
Nothingcanbereturnedfromavoid,butyoucanreturnnothing.You’reallowedto
simplysayreturninanymethodwithavoidreturntypetobustoutofamethodearly.But
youcan’treturnnothingfromamethodwithanon-voidreturntype.
Methodswithanobjectreferencereturntypecanreturnasubtype.
Methodswithaninterfacereturntypecanreturnanyimplementer.
ConstructorsandInstantiation(OCAObjectives6.3and7.4)
Aconstructorisalwaysinvokedwhenanewobjectiscreated.
Eachsuperclassinanobject’sinheritancetreewillhaveaconstructorcalled.
Everyclass,evenanabstractclass,hasatleastoneconstructor.
Constructorsmusthavethesamenameastheclass.
Constructorsdon’thaveareturntype.Ifyouseecodewithareturntype,it’samethod
withthesamenameastheclass;it’snotaconstructor.
Typicalconstructorexecutionoccursasfollows:
Theconstructorcallsitssuperclassconstructor,whichcallsitssuperclass
constructor,andsoonallthewayuptotheObjectconstructor.
TheObjectconstructorexecutesandthenreturnstothecallingconstructor,which
runstocompletionandthenreturnstoitscallingconstructor,andsoonbackdowntothe
completionoftheconstructoroftheactualinstancebeingcreated.
Constructorscanuseanyaccessmodifier(evenprivate!).
Thecompilerwillcreateadefaultconstructorifyoudon’tcreateanyconstructorsin
yourclass.
Thedefaultconstructorisano-argconstructorwithano-argcalltosuper().
Thefirststatementofeveryconstructormustbeacalleithertothis()(anoverloaded
constructor)ortosuper().
Thecompilerwilladdacalltosuper()unlessyouhavealreadyputinacalltothis()or
super().
Instancemembersareaccessibleonlyafterthesuperconstructorruns.
Abstractclasseshaveconstructorsthatarecalledwhenaconcretesubclassis
instantiated.
Interfacesdonothaveconstructors.
Ifyoursuperclassdoesnothaveano-argconstructor,youmustcreateaconstructorand
insertacalltosuper()withargumentsmatchingthoseofthesuperclassconstructor.
Constructorsareneverinherited;thustheycannotbeoverridden.
Aconstructorcanbedirectlyinvokedonlybyanotherconstructor(usingacallto
super()orthis()).
Regardingissueswithcallstothis():
Theymayappearonlyasthefirststatementinaconstructor.
Theargumentlistdetermineswhichoverloadedconstructoriscalled.
Constructorscancallconstructors,andsoon,butsoonerorlateroneofthembetter
callsuper()orthestackwillexplode.
Callstothis()andsuper()cannotbeinthesameconstructor.Youcanhaveoneor
theother,butneverboth.
InitializationBlocks(OCAObjective1.2and6.3-ish)
Usestaticinitblocks—static{/*codehere*/}—forcodeyouwanttohave
runonce,whentheclassisfirstloaded.Multipleblocksrunfromthetopdown.
Usenormalinitblocks—{/*codehere}—forcodeyouwanttohaverunforevery
newinstance,rightafterallthesuperconstructorshaverun.Again,multipleblocksrunfrom
thetopoftheclassdown.
Statics(OCAObjective6.2)
Usestaticmethodstoimplementbehaviorsthatarenotaffectedbythestateofany
instances.
Usestaticvariablestoholddatathatisclassspecificasopposedtoinstancespecific—
therewillbeonlyonecopyofastaticvariable.
Allstaticmembersbelongtotheclass,nottoanyinstance.
Astaticmethodcan’taccessaninstancevariabledirectly.
Usethedotoperatortoaccessstaticmembers,butrememberthatusingareference
variablewiththedotoperatorisreallyasyntaxtrick,andthecompilerwillsubstitutethe
classnameforthereferencevariable;forinstance:
d.doStuff();
becomes
Dog.doStuff();
Toinvokeaninterface’sstaticmethoduseMyInterface.doStuff()syntax.
staticmethodscan’tbeoverridden,buttheycanberedefined.
SELFTEST
1.Given:
publicabstractinterfaceFrobnicate{publicvoidtwiddle(Strings);}
Whichisacorrectclass?(Chooseallthatapply.)
2.Given:
Whatistheresult?
A.BD
B.DB
C.BDC
D.DBC
E.Compilationfails
3.Given:
Whatistheresult?
A.Clidlet
B.Clidder
C.Clidder
Clidlet
D.Clidlet
Clidder
E.Compilationfails
SpecialNote:Thenextquestioncrudelysimulatesastyleofquestionknownas“drag-and-
drop.”UpthroughtheSCJP6exam,drag-and-dropquestionswereincludedontheexam.Asof
spring2014,OracleDOESNOTincludeanydrag-and-dropquestionsonitsJavaexams,but
justincaseOracle’spolicychanges,weleftafewinthebook.
4.Usingthefragmentsbelow,completethefollowingcodesoitcompiles.Notethatyou
maynothavetofillinalloftheslots.
Code:
Fragments:Usethefollowingfragmentszeroormoretimes:
5.Given:
Whatistheresult?
A.preb1b2r3r2hawk
B.preb2b1r2r3hawk
C.preb2b1r2r3hawkr1r4
D.r1r4preb1b2r3r2hawk
E.r1r4preb2b1r2r3hawk
F.prer1r4b1b2r3r2hawk
G.prer1r4b2b1r2r3hawk
H.Theorderofoutputcannotbepredicted
I.Compilationfails
Note:You’llprobablyneverseethismanychoicesontherealexam!
6.Giventhefollowing:
Whichofthefollowing,insertedatline9,willcompile?(Chooseallthatapply.)
A.x2.do2();
B.(Y)x2.do2();
C.((Y)x2).do2();
D.Noneoftheabovestatementswillcompile
7.Given:
Whatistheresult?(Chooseallthatapply.)
A.2willbeincludedintheoutput
B.3willbeincludedintheoutput
C.hiwillbeincludedintheoutput
D.Compilationfails
E.Anexceptionisthrownatruntime
8.Given:
Whatistheresult?(Chooseallthatapply.)
A.howlhowlsniff
B.howlwoofsniff
C.howlhowlfollowedbyanexception
D.howlwooffollowedbyanexception
E.Compilationfailswithanerroratline14
F.Compilationfailswithanerroratline15
9.Given:
Whatistheresult?(Chooseallthatapply.)
A.Anexceptionisthrownatruntime
B.Thecodecompilesandrunswithnooutput
C.Compilationfailswithanerroratline8
D.Compilationfailswithanerroratline9
E.Compilationfailswithanerroratline12
F.Compilationfailswithanerroratline13
10.Given:
Whatistheresult?
A.fafa
B.fala
C.lala
D.Compilationfails
E.Anexceptionisthrownatruntime
11.Given:
13.Given:
Whatistheresult?
A.furrybray
B.stripesbray
C.furrygenericnoise
D.stripesgenericnoise
E.Compilationfails
F.Anexceptionisthrownatruntime
14.Given:
Whatistheresult?(Chooseallthatapply.)
A.hopping212
B.Compilationfailsduetoanerroronline2
C.Compilationfailsduetoanerroronline5
D.Compilationfailsduetoanerroronline12
E.Compilationfailsduetoanerroronline13
F.Compilationfailsduetoanerroronline14
G.Compilationfailsduetoanerroronline16
15.Given:
Whatistheresult?
A.1
B.2
C.3
D.Theoutputisunpredictable
E.Compilationfails
F.Anexceptionisthrownatruntime
16.Given:
Whichline(s)ofcode,insertedindependentlyat//INSERTCODEHERE,willallowthe
codetocompile?(Chooseallthatapply.)
A.System.out.println(“class:”+doStuff());
B.System.out.println(“iface:”+super.doStuff());
C.System.out.println(“iface:”+MyInterface.super.doStuff());
D.System.out.println(“iface:”+MyInterface.doStuff());
E.System.out.println(“iface:”+super.MyInterface.doStuff());
F.Noneofthelines,A–Ewillallowthecodetocompile
SELFTESTANSWERS
1. BandEarecorrect.Biscorrectbecauseanabstractclassneednotimplementany
orallofaninterface’smethods.Eiscorrectbecausetheclassimplementstheinterface
methodandadditionallyoverloadsthetwiddle()method.
A,C,andDareincorrect.Aisincorrectbecauseabstractmethodshavenobody.Cis
incorrectbecauseclassesimplementinterfaces;theydon’textendthem.Disincorrect
becauseoverloadingamethodisnotimplementingit.(OCAObjectives7.1and7.5)
2. Eiscorrect.Theimpliedsuper()callinBottom2’sconstructorcannotbesatisfied
becausethereisnono-argconstructorinTop.Adefault,no-argconstructorisgeneratedby
thecompileronlyiftheclasshasnoconstructordefinedexplicitly.
A,B,C,andDareincorrectbasedontheabove.(OCAObjective6.3)
3. Aiscorrect.Althoughafinalmethodcannotbeoverridden,inthiscase,themethod
isprivateand,therefore,hidden.Theeffectisthatanew,accessible,methodflipperis
created.Therefore,nopolymorphismoccursinthisexample,themethodinvokedissimply
thatofthechildclass,andnoerroroccurs.
B,C,D,andEareincorrectbasedonthepreceding.(OCAObjective7.2)
SpecialNote:Thisnextquestioncrudelysimulatesastyleofquestionknownas“drag-and-
drop.”UpthroughtheSCJP6exam,drag-and-dropquestionswereincludedontheexam.As
ofspring2014,OracleDOESNOTincludeanydrag-and-dropquestionsonitsJavaexams,
butjustincaseOracle’spolicychanges,weleftafewinthebook.
4.Hereistheanswer:
Asthereisnodroppabletileforthevariablexandtheparentheses(intheKinder
constructor)arealreadyinplaceandempty,thereisnowaytoconstructacalltothe
superclassconstructorthattakesanargument.Therefore,theonlyremainingpossibilityisto
createacalltotheno-argsuperclassconstructor.Thisisdoneassuper();.Thelinecannot
beleftblank,astheparenthesesarealreadyinplace.Further,sincethesuperclass
constructorcalledistheno-argversion,thisconstructormustbecreated.Itwillnotbe
createdbythecompilerbecauseanotherconstructorisalreadypresent.(OCAObjectives6.3
and7.4)Note:Asyoucansee,manyquestionstestforOCAObjective7.1,we’regoingto
stopmentioningobjective7.1.
5. Discorrect.Staticinitblocksareexecutedatclassloadingtime;instanceinit
blocksrunrightafterthecalltosuper()inaconstructor.Whenmultipleinitblocksofa
singletypeoccurinaclass,theyruninorder,fromthetopdown.
A,B,C,E,F,G,H,andIareincorrectbasedontheabove.Note:You’llprobablyneversee
thismanychoicesontherealexam!(OCAObjective6.3)
6. Ciscorrect.BeforeyoucaninvokeY’sdo2method,youhavetocastx2tobeoftype
Y.
A,B,andDareincorrectbasedonthepreceding.Blookslikeapropercast,butwithoutthe
secondsetofparentheses,thecompilerthinksit’sanincompletestatement.(OCAObjective
7.3)
7. Aiscorrect.It’slegaltooverloadmain().SincenoinstancesofLocomotiveare
created,theconstructordoesnotrunandtheoverloadedversionofmain()doesnotrun.
B,C,D,andEareincorrectbasedonthepreceding.(OCAObjectives1.3and6.3)
8. Fiscorrect.ClassDogdoesn’thaveasniffmethod.
A,B,C,D,andEareincorrectbasedontheaboveinformation.(OCAObjectives7.2and
7.3)
9. Aiscorrect.AClassCastExceptionwillbethrownwhenthecodeattemptsto
downcastaTreetoaRedwood.
B,C,D,E,andFareincorrectbasedontheaboveinformation.(OCAObjective7.3)
10. Biscorrect.Thecodeiscorrect,butpolymorphismdoesn’tapplytostaticmethods.
A,C,D,andEareincorrectbasedontheaboveinformation.(OCAObjectives6.2and7.2)
11. Ciscorrect.Watchout,becauseSubSubAlphaextendsAlpha!Becausethecode
doesn’tattempttomakeaSubAlpha,theprivateconstructorinSubAlphaisokay.
A,B,D,E,andFareincorrectbasedontheaboveinformation.(OCAObjectives6.3and
7.2)
12. Ciscorrect.Rememberthatconstructorscalltheirsuperclassconstructors,which
executefirst,andthatconstructorscanbeoverloaded.
A,B,D,E,F,G,andHareincorrectbasedontheaboveinformation.(OCAObjectives6.3
and7.4)
13. Aiscorrect.Polymorphismisonlyforinstancemethods,notinstancevariables.
B,C,D,E,andFareincorrectbasedontheaboveinformation.(OCAObjective6.3)
14. EandGarecorrect.Neitheroftheselinesofcodeusesthecorrectsyntaxtoinvoke
aninterface’sstaticmethod.
A,B,C,D,andFareincorrectbasedontheaboveinformation.(OCPObjectives6.2and
7.5)
15. Eiscorrect.Thisiskindofatrickquestion;theimplementingmethodmustbe
markedpublic.Ifitwas,alltheothercodeislegal,andtheoutputwouldbe3.Ifyou
understoodallthemultipleinheritancerulesandjustmissedtheaccessmodifier,giveyourself
halfcredit.
A,B,C,D,andFareincorrectbasedontheaboveinformation.(OCPObjective7.5)
16. AandCarecorrect.Ausescorrectsyntaxtoinvoketheclass’smethod,andCuses
thecorrectsyntaxtoinvoketheinterface’soverloadeddefaultmethod.
B,D,E,andFareincorrect.(OCPObjective7.5)
3
Assignments
CERTIFICATIONOBJECTIVES
•UseClassMembers
•UnderstandPrimitiveCasting
•UnderstandVariableScope
•DifferentiateBetweenPrimitiveVariablesandReferenceVariables
•DeterminetheEffectsofPassingVariablesintoMethods
•UnderstandObjectLifecycleandGarbageCollection
Two-MinuteDrill
Q&ASelfTest
StackandHeap—QuickReview
Formostpeople,understandingthebasicsofthestackandtheheapmakesitfareasiertounderstand
topicslikeargumentpassing,polymorphism,threads,exceptions,andgarbagecollection.Inthissection,
we’llsticktoanoverview,butwe’llexpandthesetopicsseveralmoretimesthroughoutthebook.
Forthemostpart,thevariouspieces(methods,variables,andobjects)ofJavaprogramsliveinoneof
twoplacesinmemory:thestackortheheap.Fornow,we’reconcernedaboutonlythreetypesofthings—
instancevariables,localvariables,andobjects:
Instancevariablesandobjectsliveontheheap.
Localvariablesliveonthestack.
Let’stakealookataJavaprogramandhowitsvariouspiecesarecreatedandmapintothestackand
theheap:
FIGURE3-1 Overviewofthestackandtheheap
Line7—main()isplacedonthestack.
Line9—Referencevariablediscreatedonthestack,butthere’snoDogobjectyet.
Line10—AnewDogobjectiscreatedontheheapandisassignedtothedreferencevariable.
Line11—Acopyofthereferencevariabledispassedtothego()method.
Line13—Thego()methodisplacedonthestack,withthedogparameterasalocalvariable.
Line14—AnewCollarobjectiscreatedontheheapandassignedtoDog’sinstance
variable.
Line17—setName()isaddedtothestack,withthedogNameparameterasitslocalvariable.
Line18—ThenameinstancevariablenowalsoreferstotheStringobject.
NoticethattwodifferentlocalvariablesrefertothesameDogobject.
NoticethatonelocalvariableandoneinstancevariablebothrefertothesameStringAiko.
AfterLine19completes,setName()completesandisremovedfromthestack.Atthispoint
thelocalvariabledogNamedisappears,too,althoughtheStringobjectitreferredtoisstillonthe
heap.
CERTIFICATIONOBJECTIVE
Literals,Assignments,andVariables
(OCAObjectives2.1,2.2,and2.3)
2.1Declareandinitializevariables(includingcastingofprimitivedatatypes).
2.2Differentiatebetweenobjectreferencevariablesandprimitivevariables.
2.3Knowhowtoreadorwritetoobjectfields.
LiteralValuesforAllPrimitiveTypes
Aprimitiveliteralismerelyasourcecoderepresentationoftheprimitivedatatypes—inotherwords,an
integer,floating-pointnumber,boolean,orcharacterthatyoutypeinwhilewritingcode.Thefollowing
areexamplesofprimitiveliterals:
IntegerLiterals
TherearefourwaystorepresentintegernumbersintheJavalanguage:decimal(base10),octal(base8),
hexadecimal(base16),and,asofJava7,binary(base2).Mostexamquestionswithintegerliteralsuse
decimalrepresentations,butthefewthatuseoctal,hexadecimal,orbinaryareworthstudyingfor.Even
thoughtheoddsthatyou’lleveractuallyuseoctalintherealworldareastronomicallytiny,theywere
includedintheexamjustforfun.Beforewelookatthefourwaystorepresentintegernumbers,let’sfirst
discussanewfeatureaddedtoJava7:literalswithunderscores.
NumericLiteralswithUnderscoresAsofJava7,numericliteralscanbedeclaredusing
underscorecharacters(_),ostensiblytoimprovereadability.Let’scompareapre-Java7declarationtoan
easier-to-readJava7declaration:
ThemainruleyouhavetokeeptrackofisthatyouCANNOTusetheunderscoreliteralatthe
beginningorendoftheliteral.Thepotentialgotchahereisthatyou’refreetousetheunderscorein
“weird”places:
Asafinalnote,rememberthatyoucanusetheunderscorecharacterforanyofthenumerictypes
(includingdoublesandfloats),butfordoublesandfloats,youCANNOTaddanunderscorecharacter
directlynexttothedecimalpoint,ornexttotheXorBinhexorbinarynumbers(whicharecomingup
soon).
DecimalLiteralsDecimalintegersneednoexplanation;you’vebeenusingthemsincegradeoneor
earlier.Chancesareyoudon’tkeepyourcheckbookinhex.(Ifyoudo,there’saGeeksAnonymous[GA]
groupreadytohelp.)IntheJavalanguage,theyarerepresentedasis,withnoprefixofanykind,as
follows:
intlength=343;
BinaryLiteralsAlsonewtoJava7istheadditionofbinaryliterals.Binaryliteralscanuseonlythe
digits0and1.Binaryliteralsmuststartwitheither0Bor0b,asshown:
OctalLiteralsOctalintegersuseonlythedigits0to7.InJava,yourepresentanintegerinoctalform
byplacingazeroinfrontofthenumber,asfollows:
Youcanhaveupto21digitsinanoctalnumber,notincludingtheleading0.Ifwerunthepreceding
program,itdisplaysthefollowing:
Octal010=8
HexadecimalLiteralsHexadecimal(hexforshort)numbersareconstructedusing16distinct
symbols.Becauseweneverinventedsingle-digitsymbolsforthenumbers10through15,weuse
alphabeticcharacterstorepresentthesedigits.Countingfrom0through15inhexlookslikethis:
0123456789abcdef
Javawillacceptuppercaseorlowercaselettersfortheextradigits(oneofthefewplacesJavaisnot
casesensitive!).Youareallowedupto16digitsinahexadecimalnumber,notincludingtheprefix0x(or
0X)ortheoptionalsuffixextensionL,whichwillbeexplainedabitlaterinthechapter.Allofthe
followinghexadecimalassignmentsarelegal:
RunningHexTestproducesthefollowingoutput:
x=1y=2147483647z=-559035650
Don’tbemisledbychangesincaseforahexadecimaldigitorthexprecedingit.0XCAFEand0xcafe
arebothlegalandhavethesamevalue.
Allfourintegerliterals(binary,octal,decimal,andhexadecimal)aredefinedasintbydefault,but
theymayalsobespecifiedaslongbyplacingasuffixofLorlafterthenumber:
longjo=110599L;
longso=0xFFFFl;//Notethelowercase‘l’
Floating-pointLiterals
Floating-pointnumbersaredefinedasanumber,adecimalsymbol,andmorenumbersrepresentingthe
fraction.Inthefollowingexample,thenumber11301874.9881024istheliteralvalue:
doubled=11301874.9881024;
Floating-pointliteralsaredefinedasdouble(64bits)bydefault,soifyouwanttoassignafloating-
pointliteraltoavariableoftypefloat(32bits),youmustattachthesuffixForftothenumber.Ifyou
don’tdothis,thecompilerwillcomplainaboutapossiblelossofprecision,becauseyou’retryingtofita
numberintoa(potentially)lessprecise“container.”TheFsuffixgivesyouawaytotellthecompiler,
“Hey,IknowwhatI’mdoing,andI’lltaketherisk,thankyouverymuch.”
YoumayalsooptionallyattachaDordtodoubleliterals,butitisnotnecessarybecausethisisthe
defaultbehavior.
Lookfornumericliteralsthatincludeacomma;here’sanexample:
BooleanLiterals
Booleanliteralsarethesourcecoderepresentationforbooleanvalues.Abooleanvaluecanbedefined
onlyastrueorfalse.AlthoughinC(andsomeotherlanguages),itiscommontousenumbersto
representtrueorfalse,thiswillnotworkinJava.Again,repeatafterme:“JavaisnotC.”
Beonthelookoutforquestionsthatusenumberswherebooleansarerequired.Youmightseeanif
testthatusesanumber,asinthefollowing:
intx=1;if(x){}//Compilererror!
CharacterLiterals
Acharliteralisrepresentedbyasinglecharacterinsinglequotes:
chara=‘a’;
charb=‘@’;
YoucanalsotypeintheUnicodevalueofthecharacter,usingtheUnicodenotationofprefixingthe
valuewith\u,asfollows:
charletterN=‘\u004E’;//Theletter‘N’
Remember,charactersarejust16-bitunsignedintegersunderthehood.Thatmeansyoucanassigna
numberliteral,assumingitwillfitintotheunsigned16-bitrange(0to65535).Forexample,thefollowing
arealllegal:
Andthefollowingarenotlegalandproducecompilererrors:
Youcanalsouseanescapecode(thebackslash)ifyouwanttorepresentacharacterthatcan’tbe
typedinasaliteral,includingthecharactersforlinefeed,newline,horizontaltab,backspace,andquotes:
LiteralValuesforStrings
AstringliteralisasourcecoderepresentationofavalueofaStringobject.Thefollowingisan
exampleoftwowaystorepresentastringliteral:
Althoughstringsarenotprimitives,they’reincludedinthissectionbecausetheycanberepresentedas
literals—inotherwords,theycanbetypeddirectlyintocode.Theonlyothernonprimitivetypethathasa
literalrepresentationisanarray,whichwe’lllookatlaterinthechapter.
Threadt=???//whatliteralvaluecouldpossiblygohere?
AssignmentOperators
Assigningavaluetoavariableseemsstraightforwardenough;yousimplyassignthestuffontherightside
ofthe=tothevariableontheleft.Well,sure,butdon’texpecttobetestedonsomethinglikethis:
x=6;
No,youwon’tbetestedontheno-brainer(technicalterm)assignments.Youwill,however,betested
onthetrickierassignmentsinvolvingcomplexexpressionsandcasting.We’lllookatbothprimitiveand
referencevariableassignments.Butbeforewebegin,let’sbackupandpeekinsideavariable.Whatisa
variable?Howarethevariableanditsvaluerelated?
Variablesarejustbitholderswithadesignatedtype.Youcanhaveanintholder,adoubleholder,a
Buttonholder,andevenaString[]holder.Withinthatholderisabunchofbitsrepresentingthevalue.
Forprimitives,thebitsrepresentanumericvalue(althoughwedon’tknowwhatthatbitpatternlookslike
forboolean,luckily,wedon’tcare).Abytewithavalueof6,forexample,meansthatthebitpatternin
thevariable(thebyteholder)is00000110,representingthe8bits.
Sothevalueofaprimitivevariableisclear,butwhat’sinsideanobjectholder?Ifyousay,
Buttonb=newButton();
what’sinsidetheButtonholderb?IsittheButtonobject?No!Avariablereferringtoanobjectisjust
that—areferencevariable.Areferencevariablebitholdercontainsbitsrepresentingawaytogettothe
object.Wedon’tknowwhattheformatis.Thewayinwhichobjectreferencesarestoredisvirtual-
machinespecific(it’sapointertosomething,wejustdon’tknowwhatthatsomethingreallyis).Allwe
cansayforsureisthatthevariable’svalueisnottheobject,butratheravaluerepresentingaspecific
objectontheheap.Ornull.Ifthereferencevariablehasnotbeenassignedavalueorhasbeenexplicitly
assignedavalueofnull,thevariableholdsbitsrepresenting—youguessedit—null.Youcanread
Buttonb=null;
as“TheButtonvariablebisnotreferringtoanyobject.”
Sonowthatweknowavariableisjustalittleboxo’bits,wecangetonwiththeworkofchanging
thosebits.We’lllookfirstatassigningvaluestoprimitivesandthenfinishwithassignmentstoreference
variables.
PrimitiveAssignments
Theequal(=)signisusedforassigningavaluetoavariable,andit’scleverlynamedtheassignment
operator.Thereareactually12assignmentoperators,butonlythe5mostcommonlyusedassignment
operatorsareontheexam,andtheyarecoveredinChapter4.
Youcanassignaprimitivevariableusingaliteralortheresultofanexpression.
Takealookatthefollowing:
Themostimportantpointtorememberisthataliteralinteger(suchas7)isalwaysimplicitlyanint.
ThinkingbacktoChapter1,you’llrecallthatanintisa32-bitvalue.Nobigdealifyou’reassigninga
valuetoanintoralongvariable,butwhatifyou’reassigningtoabytevariable?Afterall,abyte-
sizedholdercan’tholdasmanybitsasanint-sizedholder.Here’swhereitgetsweird.Thefollowingis
legal,
byteb=27;
butonlybecausethecompilerautomaticallynarrowstheliteralvaluetoabyte.Inotherwords,the
compilerputsinthecast.Theprecedingcodeisidenticaltothefollowing:
byteb=(byte)27;//Explicitlycasttheintliteraltoabyte
Itlooksasthoughthecompilergivesyouabreakandletsyoutakeashortcutwithassignmentsto
integervariablessmallerthananint.(Everythingwe’resayingaboutbyteappliesequallytocharand
short,bothofwhicharesmallerthananint.)We’renotactuallyattheweirdpartyet,bytheway.
Weknowthataliteralintegerisalwaysanint,butmoreimportantly,theresultofanexpression
involvinganythingint-sizedorsmallerisalwaysanint.Inotherwords,addtwobytestogetherand
you’llgetanint—evenifthosetwobytesaretiny.Multiplyanintandashortandyou’llgetanint.
Divideashortbyabyteandyou’llget…anint.Okay,nowwe’reattheweirdpart.Checkthisout:
Thelastlinewon’tcompile!You’llgetanerrorsomethinglikewhatyourgrandfatherusedtoget:
Wetriedtoassignthesumoftwobytestoabytevariable,theresultofwhich(11)wasdefinitely
smallenoughtofitintoabyte,butthecompilerdidn’tcare.Itknewtheruleaboutint-or-smaller
expressionsalwaysresultinginanint.Itwouldhavecompiledifwe’ddonetheexplicitcast:
bytec=(byte)(a+b);
Wewerestrugglingtofindagoodwaytoteachthistopic,andourfriend,co–JavaRanch*
moderatorandrepeattechnicalreviewerMarcPeabody,cameupwiththefollowing.Wethink
hedidagreatjob:It’sperfectlylegaltodeclaremultiplevariablesofthesametypewitha
singlelinebyplacingacommabetweeneachvariable:
inta,b,c;
Youalsohavetheoptiontoinitializeanynumberofthosevariablesrightinplace:
intj,k=1,l,m=3;
Andthesevariablesareeachevaluatedintheorderthatyoureadthem,lefttoright.It’sjustas
ifyouweretodeclareeachoneonaseparateline:
intj;
intk=1;
intl;
intm=3;
Buttheorderisimportant.Thisislegal:
Butthesearenot:
*Iknow,Iknow,butit’llalwaysbeJavaRanchinourhearts.
PrimitiveCasting
Castingletsyouconvertprimitivevaluesfromonetypetoanother.Wementionedprimitivecastinginthe
previoussection,butnowwe’regoingtotakeadeeperlook.(ObjectcastingwascoveredinChapter2.)
Castscanbeimplicitorexplicit.Animplicitcastmeansyoudon’thavetowritecodeforthecast;the
conversionhappensautomatically.Typically,animplicitcasthappenswhenyou’redoingawidening
conversion—inotherwords,puttingasmallerthing(say,abyte)intoabiggercontainer(suchasanint).
Rememberthose“possiblelossofprecision”compilererrorswesawintheassignmentssection?
Thosehappenedwhenwetriedtoputalargerthing(say,along)intoasmallercontainer(suchasa
short).Thelarge-value-into-small-containerconversionisreferredtoasnarrowingandrequiresan
explicitcast,whereyoutellthecompilerthatyou’reawareofthedangerandacceptfullresponsibility.
Firstwe’lllookatanimplicitcast:
inta=100;
longb=a;//Implicitcast,anintvaluealwaysfitsinalong
Anexplicitcastlookslikethis:
floata=100.001f;
intb=(int)a;//explicitcast,theintmightlosesomeoffloat’sinfo!
Integervaluesmaybeassignedtoadoublevariablewithoutexplicitcasting,becauseanyinteger
valuecanfitina64-bitdouble.Thefollowinglinedemonstratesthis:
doubled=100L;//Implicitcast
Intheprecedingstatement,adoubleisinitializedwithalongvalue(asdenotedbytheLafterthe
numericvalue).Nocastisneededinthiscasebecauseadoublecanholdeverypieceofinformationthat
alongcanstore.If,however,wewanttoassignadoublevaluetoanintegertype,we’reattemptinga
narrowingconversionandthecompilerknowsit:
Ifwetrytocompiletheprecedingcode,wegetanerrorsomethinglikethis:
Intheprecedingcode,afloating-pointvalueisbeingassignedtoanintegervariable.Becausean
integerisnotcapableofstoringdecimalplaces,anerroroccurs.Tomakethiswork,we’llcastthe
floating-pointnumbertoanint:
Whenyoucastafloating-pointnumbertoanintegertype,thevaluelosesallthedigitsafterthe
decimal.Theprecedingcodewillproducethefollowingoutput:
intx=3957
Wecanalsocastalargernumbertype,suchasalong,intoasmallernumbertype,suchasabyte.
Lookatthefollowing:
Theprecedingcodewillcompileandrunfine.Butwhathappensifthelongvalueislargerthan127
(thelargestnumberabytecanstore)?Let’smodifythecode:
Thecodecompilesfine,andwhenwerunitwegetthefollowing:
%javaCasting
Thebyteis-126
Wedon’tgetaruntimeerror,evenwhenthevaluebeingnarrowedistoolargeforthetype.Thebitsto
theleftofthelower8just…goaway.Iftheleftmostbit(thesignbit)inthebyte(oranyintegerprimitive)
nowhappenstobea1,theprimitivewillhaveanegativevalue.
EXERCISE3-1
CastingPrimitives
Createafloatnumbertypeofanyvalue,andassignittoashortusingcasting.
1.Declareafloatvariable:floatf=234.56F;
2.Assignthefloattoashort:shorts=(short)f;
AssigningFloating-pointNumbers
Floating-pointnumbershaveaslightlydifferentassignmentbehaviorthanintegertypes.First,youmust
knowthateveryfloating-pointliteralisimplicitlyadouble(64bits),notafloat.Sotheliteral32.3,for
example,isconsideredadouble.Ifyoutrytoassignadoubletoafloat,thecompilerknowsyoudon’t
haveenoughroomina32-bitfloatcontainertoholdtheprecisionofa64-bitdouble,anditletsyou
know.Thefollowingcodelooksgood,butitwon’tcompile:
floatf=32.3;
Youcanseethat32.3shouldfitjustfineintoafloat-sizedvariable,butthecompilerwon’tallowit.In
ordertoassignafloating-pointliteraltoafloatvariable,youmusteithercastthevalueorappendanf
totheendoftheliteral.Thefollowingassignmentswillcompile:
AssigningaLiteralThatIsTooLargefortheVariable
We’llalsogetacompilererrorifwetrytoassignaliteralvaluethatthecompilerknowsistoobigtofit
intothevariable.
bytea=128;//bytecanonlyholdupto127
Theprecedingcodegivesusanerrorsomethinglikethis:
Wecanfixitwithacast:
bytea=(byte)128;
Butthenwhat’stheresult?Whenyounarrowaprimitive,Javasimplytruncatesthehigher-orderbits
thatwon’tfit.Inotherwords,itlosesallthebitstotheleftofthebitsyou’renarrowingto.
Let’stakealookatwhathappensintheprecedingcode.There,128isthebitpattern10000000.It
takesafull8bitstorepresent128.Butbecausetheliteral128isanint,weactuallyget32bits,withthe
128livingintherightmost(lowerorder)8bits.Soaliteral128isactually
00000000000000000000000010000000
Takeourwordforit;thereare32bitsthere.
Tonarrowthe32bitsrepresenting128,Javasimplylopsofftheleftmost(higherorder)24bits.What
remainsisjustthe10000000.Butrememberthatabyteissigned,withtheleftmostbitrepresentingthe
sign(andnotpartofthevalueofthevariable).Soweendupwithanegativenumber(the1thatusedto
represent128nowrepresentsthenegativesignbit).Remember,tofindoutthevalueofanegativenumber
using2’scomplementnotation,youflipallofthebitsandthenadd1.Flippingthe8bitsgivesus
01111111,andadding1tothatgivesus10000000,orbackto128!Andwhenweapplythesignbit,we
endupwith–128.
Youmustuseanexplicitcasttoassign128toabyte,andtheassignmentleavesyouwiththevalue–
128.Acastisnothingmorethanyourwayofsayingtothecompiler,“Trustme.I’maprofessional.Itake
fullresponsibilityforanythingweirdthathappenswhenthosetopbitsarechoppedoff.”
Thatbringsustothecompoundassignmentoperators.Thiswillcompile:
Thecompoundassignmentoperator+=letsyouaddtothevalueofb,withoutputtinginanexplicitcast.
Infact,+=,-=,*=,and/=willallputinanimplicitcast.
AssigningOnePrimitiveVariabletoAnotherPrimitiveVariable
Whenyouassignoneprimitivevariabletoanother,thecontentsoftheright-handvariablearecopied.For
example:
inta=6;
intb=a;
Thiscodecanbereadas,“Assignthebitpatternforthenumber6totheintvariablea.Thencopythebit
patternina,andplacethecopyintovariableb.”
Sobothvariablesnowholdabitpatternfor6,butthetwovariableshavenootherrelationship.We
usedthevariableaonlytocopyitscontents.Atthispoint,aandbhaveidenticalcontents(inother
words,identicalvalues),butifwechangethecontentsofeitheraorb,theothervariablewon’tbe
affected.
Takealookatthefollowingexample:
Theoutputfromthisprogramis
%javaValueTest
a=10
a=10afterchangetob
Noticethevalueofastayedat10.Thekeypointtorememberisthatevenafteryouassignatob,aand
barenotreferringtothesameplaceinmemory.Theaandbvariablesdonotshareasinglevalue;they
haveidenticalcopies.
ReferenceVariableAssignments
Youcanassignanewlycreatedobjecttoanobjectreferencevariableasfollows:
Buttonb=newButton();
Theprecedinglinedoesthreekeythings:
Makesareferencevariablenamedb,oftypeButton
CreatesanewButtonobjectontheheap
AssignsthenewlycreatedButtonobjecttothereferencevariableb
Youcanalsoassignnulltoanobjectreferencevariable,whichsimplymeansthevariableisnot
referringtoanyobject:
Buttonc=null;
TheprecedinglinecreatesspacefortheButtonreferencevariable(thebitholderforareferencevalue),
butitdoesn’tcreateanactualButtonobject.
Aswediscussedinthelastchapter,youcanalsouseareferencevariabletorefertoanyobjectthatis
asubclassofthedeclaredreferencevariabletype,asfollows:
Theruleisthatyoucanassignasubclassofthedeclaredtypebutnotasuperclassofthedeclaredtype.
Remember,aBarobjectisguaranteedtobeabletodoanythingaFoocando,soanyonewithaFoo
referencecaninvokeFoomethodseventhoughtheobjectisactuallyaBar.
Intheprecedingcode,weseethatFoohasamethoddoFooStuff()thatsomeonewithaFooreference
mighttrytoinvoke.IftheobjectreferencedbytheFoovariableisreallyaFoo,noproblem.Butit’salso
noproblemiftheobjectisaBarbecauseBarinheritedthedoFooStuff()method.Youcan’tmakeit
workinreverse,however.IfsomebodyhasaBarreference,they’regoingtoinvokedoBarStuff(),butif
theobjectisaFoo,itwon’tknowhowtorespond.
TheOCA8examcoverswrapperclasses.Wecouldhavediscussedwrapperclassesinthis
chapter,butwefeltitmademoresensetodiscusstheminthecontextofArrayLists(whichwe
willcoverinChapter6).SountilyougettoChapter6,allyou’llneedtoknowaboutwrappers
follows:
Awrapperobjectisanobjectthatholdsthevalueofaprimitive.Everykindofprimitivehasan
associatedwrapperclass:Boolean,Byte,Character,Double,Float,Integer,Long,
andShort.Thefollowingcodecreatestwowrapperobjectsandthenprintstheirvalues:
producesthefollowingoutput:
4257
We’llbedivingmuchmoredeeplyintowrappersinChapter5.
CERTIFICATIONOBJECTIVE
Scope(OCAObjective1.1)
1.1Determinethescopeofvariables.
VariableScope
Onceyou’vedeclaredandinitializedavariable,anaturalquestionis,“Howlongwillthisvariablebe
around?”Thisisaquestionregardingthescopeofvariables.Andnotonlyisscopeanimportantthingto
understandingeneral,italsoplaysabigpartintheexam.Let’sstartbylookingataclassfile:
AswithvariablesinallJavaprograms,thevariablesinthisprogram(s,x,x2,x3,y,andz)allhavea
scope:
sisastaticvariable.
xisaninstancevariable.
yisalocalvariable(sometimescalleda“methodlocal”variable).
zisablockvariable.
x2isaninitblockvariable,aflavoroflocalvariable.
x3isaconstructorvariable,aflavoroflocalvariable.
Forthepurposesofdiscussingthescopeofvariables,wecansaythattherearefourbasicscopes:
1.Staticvariableshavethelongestscope;theyarecreatedwhentheclassisloaded,andthey
surviveaslongastheclassstaysloadedintheJavaVirtualMachine(JVM).
2.Instancevariablesarethenextmostlong-lived;theyarecreatedwhenanewinstanceis
created,andtheyliveuntiltheinstanceisremoved.
3.Localvariablesarenext;theyliveaslongastheirmethodremainsonthestack.Aswe’llsoon
see,however,localvariablescanbealiveandstillbe“outofscope.”
4.Blockvariablesliveonlyaslongasthecodeblockisexecuting.
Scopingerrorscomeinmanysizesandshapes.Onecommonmistakehappenswhenavariableis
shadowedandtwoscopesoverlap.We’lltakeadetailedlookatshadowinginafewpages.Themost
commonreasonforscopingerrorsisanattempttoaccessavariablethatisnotinscope.Let’slookat
threecommonexamplesofthistypeoferror:
Attemptingtoaccessaninstancevariablefromastaticcontext(typicallyfrommain()):
Attemptingtoaccessalocalvariableofthemethodthatinvokedyou.Whenamethod,say
go(),invokesanothermethod,saygo2(),go2()won’thaveaccesstogo()’slocalvariables.
Whilego2()isexecuting,go()’slocalvariablesarestillalive,buttheyareoutofscope.When
go2()completes,itisremovedfromthestack,andgo()resumesexecution.Atthispoint,allof
go()’spreviouslydeclaredvariablesarebackinscope.Forexample:
Attemptingtouseablockvariableafterthecodeblockhascompleted.It’sverycommonto
declareanduseavariablewithinacodeblock,butbecarefulnottotrytousethevariableoncethe
blockhascompleted:
Inthelasttwoexamples,thecompilerwillsaysomethinglikethis:
cannotfindsymbol
Thisisthecompiler’swayofsaying,“Thatvariableyoujusttriedtouse?Well,itmighthavebeenvalid
inthedistantpast(likeonelineofcodeago),butthisisInternettime,baby,Ihavenomemoryofsucha
variable.”
Payextraattentiontocode-blockscopingerrors.Youmightseetheminswitches,try-catches,
for,do,andwhileloops,whichwe’llcoverinlaterchapters.
CERTIFICATIONOBJECTIVE
VariableInitialization
(OCAObjectives2.1,4.1,and4.2)
2.1Declareandinitializevariables(includingcastingofprimitivedatatypes).
4.1Declare,instantiate,initializeanduseaone-dimensionalarray
4.2Declare,instantiate,initializeandusemulti-dimensionalarray(sic)
UsingaVariableorArrayElement
ThatIsUninitializedandUnassigned
Javagivesustheoptionofinitializingadeclaredvariableorleavingituninitialized.Whenweattemptto
usetheuninitializedvariable,wecangetdifferentbehaviordependingonwhattypeofvariableorarray
wearedealingwith(primitivesorobjects).Thebehavioralsodependsonthelevel(scope)atwhichwe
aredeclaringourvariable.Aninstancevariableisdeclaredwithintheclassbutoutsideanymethodor
constructor,whereasalocalvariableisdeclaredwithinamethod(orintheargumentlistofthemethod).
Localvariablesaresometimescalledstack,temporary,automatic,ormethodvariables,buttherules
forthesevariablesarethesameregardlessofwhatyoucallthem.Althoughyoucanleavealocalvariable
uninitialized,thecompilercomplainsifyoutrytousealocalvariablebeforeinitializingitwithavalue,
asweshallsee.
PrimitiveandObjectTypeInstanceVariables
Instancevariables(alsocalledmembervariables)arevariablesdefinedattheclasslevel.Thatmeansthe
variabledeclarationisnotmadewithinamethod,constructor,oranyotherinitializerblock.Instance
variablesareinitializedtoadefaultvalueeachtimeanewinstanceiscreated,althoughtheymaybegiven
anexplicitvalueaftertheobject’ssuperconstructorshavecompleted.Table3-1liststhedefaultvalues
forprimitiveandobjecttypes.
TABLE3-1 DefaultValuesforPrimitivesandReferenceTypes
PrimitiveInstanceVariables
Inthefollowingexample,theintegeryearisdefinedasaclassmemberbecauseitiswithintheinitial
curlybracesoftheclassandnotwithinamethod’scurlybraces:
Whentheprogramisstarted,itgivesthevariableyearavalueofzero,thedefaultvalueforprimitive
numberinstancevariables.
It’sagoodideatoinitializeallyourvariables,evenifyou’reassigningthemwiththedefaultvalue.
Yourcodewillbeeasiertoread;programmerswhohavetomaintainyourcode(afteryouwinthe
lotteryandmovetoTahiti)willbegrateful.
ObjectReferenceInstanceVariables
Whencomparedwithuninitializedprimitivevariables,objectreferencesthataren’tinitializedarea
completelydifferentstory.Let’slookatthefollowingcode:
Thiscodewillcompilefine.Whenwerunit,theoutputis
Thetitleisnull
ThetitlevariablehasnotbeenexplicitlyinitializedwithaStringassignment,sotheinstance
variablevalueisnull.RememberthatnullisnotthesameasanemptyString(“”).Anullvaluemeans
thereferencevariableisnotreferringtoanyobjectontheheap.ThefollowingmodificationtotheBook
coderunsintotrouble:
WhenwetrytoruntheBookclass,theJVMwillproducesomethinglikethis:
Exceptioninthread“main”java.lang.NullPointerException
atBook.main(Book.java:9)
Wegetthiserrorbecausethereferencevariabletitledoesnotpoint(refer)toanobject.Wecancheck
toseewhetheranobjecthasbeeninstantiatedbyusingthekeywordnull,asthefollowingrevisedcode
shows:
Theprecedingcodecheckstomakesuretheobjectreferencedbythevariablesisnotnullbefore
tryingtouseit.Watchoutforscenariosontheexamwhereyoumighthavetotracebackthroughthecode
tofindoutwhetheranobjectreferencewillhaveavalueofnull.Intheprecedingcode,forexample,you
lookattheinstancevariabledeclarationfortitle,seethatthere’snoexplicitinitialization,recognizethat
thetitlevariablewillbegiventhedefaultvalueofnull,andthenrealizethatthevariableswillalso
haveavalueofnull.Remember,thevalueofsisacopyofthevalueoftitle(asreturnedbythe
getTitle()method),soiftitleisanullreference,swillbe,too.
ArrayInstanceVariables
InChapter5we’llbetakingaverydetailedlookatdeclaring,constructing,andinitializingarraysand
multidimensionalarrays.Fornow,we’rejustgoingtolookattheruleforanarrayelement’sdefault
values.
Anarrayisanobject;thus,anarrayinstancevariablethat’sdeclaredbutnotexplicitlyinitializedwill
haveavalueofnull,justasanyotherobjectreferenceinstancevariable.But…ifthearrayisinitialized,
whathappenstotheelementscontainedinthearray?Allarrayelementsaregiventheirdefaultvalues—
thesamedefaultvaluesthatelementsofthattypegetwhenthey’reinstancevariables.Thebottomline:
Arrayelementsarealways,always,alwaysgivendefaultvalues,regardlessofwherethearrayitselfis
instantiated.
Ifweinitializeanarray,objectreferenceelementswillequalnulliftheyarenotinitialized
individuallywithvalues.Ifprimitivesarecontainedinanarray,theywillbegiventheirrespective
defaultvalues.Forexample,inthefollowingcode,thearrayyearwillcontain100integersthatallequal
to0(zero)bydefault:
Whentheprecedingcoderuns,theoutputindicatesthatall100integersinthearrayhaveavalueof0.
Local(Stack,Automatic)PrimitivesandObjects
Localvariablesaredefinedwithinamethod,andtheyincludeamethod’sparameters.
Automaticisjustanothertermforlocalvariable.Itdoesnotmeantheautomaticvariableis
automaticallyassignedavalue!Infact,theoppositeistrue.Anautomaticvariablemustbe
assignedavalueinthecodeorthecompilerwillcomplain.
LocalPrimitives
Inthefollowingtime-travelsimulator,theintegeryearisdefinedasanautomaticvariablebecauseitis
withinthecurlybracesofamethod:
Localvariables,includingprimitives,always,always,alwaysmustbeinitializedbeforeyouattemptto
usethem(thoughnotnecessarilyonthesamelineofcode).Javadoesnotgivelocalvariablesadefault
value;youmustexplicitlyinitializethemwithavalue,asintheprecedingexample.Ifyoutrytousean
uninitializedprimitiveinyourcode,you’llgetacompilererror:
Compilingproducesoutputsomethinglikethis:
Tocorrectourcode,wemustgivetheintegeryearavalue.Inthisupdatedexample,wedeclareitona
separateline,whichisperfectlyvalid:
Noticeintheprecedingexamplewedeclaredanintegercalleddaythatnevergetsinitialized,yetthe
codecompilesandrunsfine.Legally,youcandeclarealocalvariablewithoutinitializingitaslongas
youdon’tusethevariable—but,let’sfaceit,ifyoudeclaredit,youprobablyhadareason(althoughwe
haveheardofprogrammersdeclaringrandomlocalvariablesjustforsport,toseeiftheycanfigureout
howandwhythey’rebeingused).
Thecompilercan’talwaystellwhetheralocalvariablehasbeeninitializedbeforeuse.For
example,ifyouinitializewithinalogicallyconditionalblock(inotherwords,acodeblockthatmay
notrun,suchasanifblockorforloopwithoutaliteralvalueoftrueorfalseinthetest),the
compilerknowsthattheinitializationmightnothappenandcanproduceanerror.Thefollowing
codeupsetsthecompiler:
Thecompilerwillproduceanerrorsomethinglikethis:
TestLocal.java:9:variablexmightnothavebeeninitialized
Becauseofthecompiler-can’t-tell-for-certainproblem,youwillsometimesneedtoinitializeyour
variableoutsidetheconditionalblock,justtomakethecompilerhappy.Youknowwhythat’s
importantifyou’veseenthebumpersticker,“Whenthecompiler’snothappy,ain’tnobodyhappy.”
LocalObjectReferences
Objectsreferences,too,behavedifferentlywhendeclaredwithinamethodratherthanasinstance
variables.Withinstancevariableobjectreferences,youcangetawaywithleavinganobjectreference
uninitialized,aslongasthecodecheckstomakesurethereferenceisn’tnullbeforeusingit.Remember,
tothecompiler,nullisavalue.Youcan’tusethedotoperatoronanullreference,becausethereisno
objectattheotherendofit,butanullreferenceisnotthesameasanuninitializedreference.Locally
declaredreferencescan’tgetawaywithcheckingfornullbeforeuse,unlessyouexplicitlyinitializethe
localvariabletonull.Thecompilerwillcomplainaboutthefollowingcode:
Compilingthecoderesultsinanerrorsimilartothefollowing:
Instancevariablereferencesarealwaysgivenadefaultvalueofnull,untiltheyareexplicitly
initializedtosomethingelse.Butlocalreferencesarenotgivenadefaultvalue;inotherwords,they
aren’tnull.Ifyoudon’tinitializealocalreferencevariable,then,bydefault,itsvalueis—wellthat’sthe
wholepoint:itdoesn’thaveanyvalueatall!Sowe’llmakethissimple:Justsetthedarnthingtonull
explicitlyuntilyou’rereadytoinitializeittosomethingelse.Thefollowinglocalvariablewillcompile
properly:
LocalArrays
Justlikeanyotherobjectreference,arrayreferencesdeclaredwithinamethodmustbeassignedavalue
beforeuse.Thatjustmeansyoumustdeclareandconstructthearray.Youdonot,however,needto
explicitlyinitializetheelementsofanarray.We’vesaiditbefore,butit’simportantenoughtorepeat:
Arrayelementsaregiventheirdefaultvalues(0,false,null,‘\u0000’,andsoon)regardlessof
whetherthearrayisdeclaredasaninstanceorlocalvariable.Thearrayobjectitself,however,willnot
beinitializedifit’sdeclaredlocally.Inotherwords,youmustexplicitlyinitializeanarrayreferenceif
it’sdeclaredandusedwithinamethod,butatthemomentyouconstructanarrayobject,allofitselements
areassignedtheirdefaultvalues.
AssigningOneReferenceVariabletoAnother
Withprimitivevariables,anassignmentofonevariabletoanothermeansthecontents(bitpattern)ofone
variablearecopiedintoanother.Objectreferencevariablesworkexactlythesameway.Thecontentsofa
referencevariableareabitpattern,soifyouassignreferencevariablea1toreferencevariableb1,thebit
patternina1iscopiedandthenewcopyisplacedintob1.(Somepeoplehavecreatedagamearound
countinghowmanytimesweusethewordcopyinthischapter…thiscopyconceptisabiggie!)Ifwe
assignanexistinginstanceofanobjecttoanewreferencevariable,thentworeferencevariableswill
holdthesamebitpattern—abitpatternreferringtoaspecificobjectontheheap.Lookatthefollowing
code:
Intheprecedingexample,aDimensionobjecta1isdeclaredandinitializedwithawidthof5anda
heightof10.Next,Dimensionb1isdeclaredandassignedthevalueofa1.Atthispoint,bothvariables
(a1andb1)holdidenticalvaluesbecausethecontentsofa1werecopiedintob1.Thereisstillonlyone
Dimensionobject—theonethatbotha1andb1referto.Finally,theheightpropertyischangedusingthe
b1reference.Nowthinkforaminute:isthisgoingtochangetheheightpropertyofa1aswell?Let’ssee
whattheoutputwillbe:
Fromthisoutput,wecanconcludethatbothvariablesrefertothesameinstanceoftheDimensionobject.
Whenwemadeachangetob1,theheightpropertywasalsochangedfora1.
OneexceptiontothewayobjectreferencesareassignedisString.InJava,Stringobjectsaregiven
specialtreatment.Foronething,Stringobjectsareimmutable;youcan’tchangethevalueofaString
object(lotsmoreonthisconceptinChapter6).Butitsurelooksasthoughyoucan.Examinethe
followingcode:
BecauseStringsareobjects,youmightthinkStringywillcontainthecharactersJavaBeanafter
thevariablexischanged.Let’sseewhattheoutputis:
Asyoucansee,eventhoughyisareferencevariabletothesameobjectthatxrefersto,whenwe
changex,itdoesn’tchangey!Foranyotherobjecttype,wheretworeferencesrefertothesameobject,if
eitherreferenceisusedtomodifytheobject,bothreferenceswillseethechangebecausethereisstill
onlyasingleobject.ButanytimewemakeanychangesatalltoaString,theVMwillupdatethe
referencevariabletorefertoadifferentobject.Thedifferentobjectmightbeanewobject,oritmight
notbe,butitwilldefinitelybeadifferentobject.Thereasonwecan’tsayforsurewhetheranewobject
iscreatedisbecauseoftheStringconstantpool,whichwe’llcoverinChapter6.
YouneedtounderstandwhathappenswhenyouuseaStringreferencevariabletomodifyastring:
Anewstringiscreated(oramatchingStringisfoundintheStringpool),leavingthe
originalStringobjectuntouched.
ThereferenceusedtomodifytheString(orrather,makeanewStringbymodifyingacopy
oftheoriginal)isthenassignedthebrand-newStringobject.
Sowhenyousay,
youhaven’tchangedtheoriginalStringobjectcreatedonline1.Whenline2completes,bothtands
referencethesameStringobject.Butwhenline3runs,ratherthanmodifyingtheobjectreferredtobyt
ands(whichistheoneandonlyStringobjectuptothispoint),abrandnewStringobjectiscreated.
Andthenit’sabandoned.BecausethenewStringisn’tassignedtoaStringvariable,thenewlycreated
String(whichholdsthestring“FRED”)istoast.SoalthoughtwoStringobjectswerecreatedinthe
precedingcode,onlyoneisactuallyreferenced,andbothtandsrefertoit.ThebehaviorofStringsis
extremelyimportantintheexam,sowe’llcoveritinmuchmoredetailinChapter6.
CERTIFICATIONOBJECTIVE
PassingVariablesintoMethods(OCAObjective6.6)
6.8Determinetheeffectuponobjectreferencesandprimitivevalueswhentheyarepassedinto
methodsthatchangethevalues.
Methodscanbedeclaredtotakeprimitivesand/orobjectreferences.Youneedtoknowhow(orif)the
caller’svariablecanbeaffectedbythecalledmethod.Thedifferencebetweenobjectreferenceand
primitivevariables,whenpassedintomethods,ishugeandimportant.Tounderstandthissection,you’ll
needtobecomfortablewiththeinformationcoveredinthe“Literals,Assignments,andVariables”section
intheearlypartofthischapter.
PassingObjectReferenceVariables
Whenyoupassanobjectvariableintoamethod,youmustkeepinmindthatyou’repassingtheobject
reference,nottheactualobjectitself.Rememberthatareferencevariableholdsbitsthatrepresent(tothe
underlyingVM)awaytogettoaspecificobjectinmemory(ontheheap).Moreimportantly,youmust
rememberthatyouaren’tevenpassingtheactualreferencevariable,butratheracopyofthereference
variable.Acopyofavariablemeansyougetacopyofthebitsinthatvariable,sowhenyoupassa
referencevariable,you’repassingacopyofthebitsrepresentinghowtogettoaspecificobject.Inother
words,boththecallerandthecalledmethodwillnowhaveidenticalcopiesofthereference;thus,both
willrefertothesameexact(notacopy)objectontheheap.
Forthisexample,we’llusetheDimensionclassfromthejava.awtpackage:
Whenwerunthisclass,wecanseethemodify()methodwas,indeed,abletomodifytheoriginal
(andonly)Dimensionobjectcreatedonline4.
NoticewhentheDimensionobjectonline4ispassedtothemodify()method,anychangestothe
objectthatoccurinsidethemethodarebeingmadetotheobjectwhosereferencewaspassed.Inthe
precedingexample,referencevariablesdanddimbothpointtothesameobject.
DoesJavaUsePass-By-ValueSemantics?
IfJavapassesobjectsbypassingthereferencevariableinstead,doesthatmeanJavausespass-by-
referenceforobjects?Notexactly,althoughyou’lloftenhearandreadthatitdoes.Javaisactuallypass-
by-valueforallvariablesrunningwithinasingleVM.Pass-by-valuemeanspass-by-variable-value.And
thatmeanspass-by-copy-of-the-variable!(There’sthatwordcopyagain!)
Itmakesnodifferenceifyou’repassingprimitiveorreferencevariables;youarealwayspassinga
copyofthebitsinthevariable.Soforaprimitivevariable,you’repassingacopyofthebitsrepresenting
thevalue.Forexample,ifyoupassanintvariablewiththevalueof3,you’repassingacopyofthebits
representing3.Thecalledmethodthengetsitsowncopyofthevaluetodowithitwhatitlikes.
Andifyou’repassinganobjectreferencevariable,you’repassingacopyofthebitsrepresentingthe
referencetoanobject.Thecalledmethodthengetsitsowncopyofthereferencevariabletodowithit
whatitlikes.Butbecausetwoidenticalreferencevariablesrefertotheexactsameobject,ifthecalled
methodmodifiestheobject(byinvokingsettermethods,forexample),thecallerwillseethattheobject
thecaller’soriginalvariablereferstohasalsobeenchanged.Inthenextsection,we’lllookathowthe
picturechangeswhenwe’retalkingaboutprimitives.
Thebottomlineonpass-by-value:Thecalledmethodcan’tchangethecaller’svariable,althoughfor
objectreferencevariables,thecalledmethodcanchangetheobjectthevariablereferredto.What’sthe
differencebetweenchangingthevariableandchangingtheobject?Forobjectreferences,itmeansthe
calledmethodcan’treassignthecaller’soriginalreferencevariableandmakeitrefertoadifferentobject
ornull.Forexample,inthefollowingcodefragment,
reassigninggdoesnotreassignf!Attheendofthebar()method,twoFooobjectshavebeencreated:
onereferencedbythelocalvariablefandonereferencedbythelocal(argument)variableg.Becausethe
doStuff()methodhasacopyofthereferencevariable,ithasawaytogettotheoriginalFooobject,for
instancetocallthesetName()method.ButthedoStuff()methoddoesnothaveawaytogettothef
referencevariable.SodoStuff()canchangevalueswithintheobjectfrefersto,butdoStuff()can’t
changetheactualcontents(bitpattern)off.Inotherwords,doStuff()canchangethestateoftheobject
thatfrefersto,butitcan’tmakefrefertoadifferentobject!
PassingPrimitiveVariables
Let’slookatwhathappenswhenaprimitivevariableispassedtoamethod:
Inthissimpleprogram,thevariableaispassedtoamethodcalledmodify(),whichincrementsthe
variableby1.Theresultingoutputlookslikethis:
Noticethatadidnotchangeafteritwaspassedtothemethod.Remember,itwasacopyofathatwas
passedtothemethod.Whenaprimitivevariableispassedtoamethod,itispassedbyvalue,which
meanspass-by-copy-of-the-bits-in-the-variable.
FROMTHECLASSROOM
TheShadowyWorldofVariables
Justwhenyouthinkyou’vegotitallfiguredout,youseeapieceofcodewithvariablesnotbehaving
thewayyouthinktheyshould.Youmighthavestumbledintocodewithashadowedvariable.Youcan
shadowavariableinseveralways.We’lllookatonewaythatmighttripyouup:hidingastatic
variablebyshadowingitwithalocalvariable.
Shadowinginvolvesreusingavariablenamethat’salreadybeendeclaredsomewhereelse.
Theeffectofshadowingistohidethepreviouslydeclaredvariableinsuchawaythatitmaylookas
thoughyou’reusingthehiddenvariable,butyou’reactuallyusingtheshadowingvariable.Youmight
findreasonstoshadowavariableintentionally,buttypicallyithappensbyaccidentandcauseshard-
to-findbugs.Ontheexam,youcanexpecttoseequestionswhereshadowingplaysarole.
Youcanshadowavariablebydeclaringalocalvariableofthesamename,eitherdirectlyoras
partofanargument:
TheprecedingcodeappearstochangethestaticsizevariableinthechangeIt()method,but
becausechangeIt()hasaparameternamedsize,thelocalsizevariableismodifiedwhilethestatic
sizevariableisuntouched.
RunningclassFooprintsthis:
Thingsbecomemoreinterestingwhentheshadowedvariableisanobjectreference,ratherthana
primitive:
Theprecedingcodeprintsoutthis:
Youcanseethattheshadowingvariable(thelocalparametermyBarinchangeIt())canstill
affectthemyBarinstancevariable,becausethemyBarparameterreceivesareferencetothesameBar
object.ButwhenthelocalmyBarisreassignedanewBarobject,whichwethenmodifybychanging
itsbarNumvalue,Foo’soriginalmyBarinstancevariableisuntouched.
CERTIFICATIONOBJECTIVE
GarbageCollection(OCAObjective2.4)
2.4Explainanobject’slifecycle(creation,“dereferencebyreassignment,”andgarbagecollection)
Thephrasegarbagecollectionseemstocomeandgofromtheexamobjectives.AsoftheOCA8
exam,it’sback,andwe’rehappy.Garbagecollectionisawell-knownideaandauniversalphrasein
computerscience.
OverviewofMemoryManagementandGarbageCollection
Thisisthesectionyou’vebeenwaitingfor!It’sfinallytimetodigintothewonderfulworldofmemory
managementandgarbagecollection.
Memorymanagementisacrucialelementinmanytypesofapplications.Consideraprogramthatreads
inlargeamountsofdata,sayfromsomewhereelseonanetwork,andthenwritesthatdataintoadatabase
onaharddrive.Atypicaldesignwouldbetoreadthedataintosomesortofcollectioninmemory,
performsomeoperationsonthedata,andthenwritethedataintothedatabase.Afterthedataiswritten
intothedatabase,thecollectionthatstoredthedatatemporarilymustbeemptiedofolddataordeleted
andre-createdbeforeprocessingthenextbatch.Thisoperationmightbeperformedthousandsoftimes,
andinlanguageslikeCorC++thatdonotofferautomaticgarbagecollection,asmallflawinthelogic
thatmanuallyemptiesordeletesthecollectiondatastructurescanallowsmallamountsofmemorytobe
improperlyreclaimedorlost.Forever.Thesesmalllossesarecalledmemoryleaks,andovermany
thousandsofiterationstheycanmakeenoughmemoryinaccessiblethatprogramswilleventuallycrash.
Creatingcodethatperformsmanualmemorymanagementcleanlyandthoroughlyisanontrivialand
complextask,andwhileestimatesvary,itisarguablethatmanualmemorymanagementcandoublethe
developmenteffortforacomplexprogram.
Java’sgarbagecollectorprovidesanautomaticsolutiontomemorymanagement.Inmostcasesitfrees
youfromhavingtoaddanymemorymanagementlogictoyourapplication.Thedownsidetoautomatic
garbagecollectionisthatyoucan’tcompletelycontrolwhenitrunsandwhenitdoesn’t.
OverviewofJava’sGarbageCollector
Let’slookatwhatwemeanwhenwetalkaboutgarbagecollectioninthelandofJava.Fromthe30,000-
footlevel,garbagecollectionisthephraseusedtodescribeautomaticmemorymanagementinJava.
Wheneverasoftwareprogramexecutes(inJava,C,C++,Lisp,Ruby,andsoon),itusesmemoryin
severaldifferentways.We’renotgoingtogetintoComputerScience101here,butit’stypicalformemory
tobeusedtocreateastack,aheap,inJava’scaseconstantpoolsandmethodareas.Theheapisthat
partofmemorywhereJavaobjectslive,andit’stheoneandonlypartofmemorythatisinanyway
involvedinthegarbagecollectionprocess.
Aheapisaheapisaheap.Fortheexam,it’simportantthatyouknowthatyoucancallittheheap,you
cancallitthegarbagecollectibleheap,oryoucancallitJohnson,butthereisoneandonlyoneheap.
Soallgarbagecollectionrevolvesaroundmakingsuretheheaphasasmuchfreespaceaspossible.
Forthepurposeoftheexam,whatthisboilsdowntoisdeletinganyobjectsthatarenolongerreachable
bytheJavaprogramrunning.We’lltalkmoreaboutwhat“reachable”meansinaminute,butlet’sdrill
thispointin.Whenthegarbagecollectorruns,itspurposeistofindanddeleteobjectsthatcannotbe
reached.IfyouthinkofaJavaprogramasbeinginaconstantcycleofcreatingtheobjectsitneeds(which
occupyspaceontheheap)andthendiscardingthemwhenthey’renolongerneeded,creatingnewobjects,
discardingthem,andsoon,themissingpieceofthepuzzleisthegarbagecollector.Whenitruns,itlooks
forthosediscardedobjectsanddeletesthemfrommemory,sothatthecycleofusingmemoryand
releasingitcancontinue.Ah,thegreatcircleoflife.
WhenDoestheGarbageCollectorRun?
ThegarbagecollectorisunderthecontroloftheJVM;theJVMdecideswhentorunthegarbage
collector.FromwithinyourJavaprogram,youcanasktheJVMtorunthegarbagecollector;butthereare
noguarantees,underanycircumstances,thattheJVMwillcomply.Lefttoitsowndevices,theJVMwill
typicallyrunthegarbagecollectorwhenitsensesthatmemoryisrunninglow.Experienceindicatesthat
whenyourJavaprogrammakesarequestforgarbagecollection,theJVMwillusuallygrantyourrequest
inshortorder,buttherearenoguarantees.Justwhenyouthinkyoucancountonit,theJVMwilldecideto
ignoreyourrequest.
HowDoestheGarbageCollectorWork?
Youjustcan’tbesure.Youmighthearthatthegarbagecollectorusesamarkandsweepalgorithm,andfor
anygivenJavaimplementationthatmightbetrue,buttheJavaspecificationdoesn’tguaranteeany
particularimplementation.Youmighthearthatthegarbagecollectorusesreferencecounting;onceagain,
maybeyes,maybeno.Theimportantconceptforyoutounderstandfortheexamis:Whendoesanobject
becomeeligibleforgarbagecollection?
Inanutshell,everyJavaprogramhasfromonetomanythreads.Eachthreadhasitsownlittle
executionstack.Normally,you(theprogrammer)causeatleastonethreadtoruninaJavaprogram,the
onewiththemain()methodatthebottomofthestack.However,therearemanyreallycoolreasonsto
launchadditionalthreadsfromyourinitialthread(whichyou’llgetintoifyoupreparefortheOCP8
exam).Inadditiontohavingitsownlittleexecutionstack,eachthreadhasitsownlifecycle.Fornow,all
youneedtoknowisthatthreadscanbealiveordead.
Withthisbackgroundinformation,wecannowsaywithstunningclarityandresolvethatanobjectis
eligibleforgarbagecollectionwhennolivethreadcanaccessit.(Note:Duetothevagariesofthe
Stringconstantpool,theexamfocusesitsgarbagecollectionquestionsonnon-Stringobjects,andso
ourgarbagecollectiondiscussionsapplytoonlynon-Stringobjectstoo.)
Basedonthatdefinition,thegarbagecollectorperformssomemagical,unknownoperations;andwhen
itdiscoversanobjectthatcan’tbereachedbyanylivethread,itwillconsiderthatobjectaseligiblefor
deletion,anditmightevendeleteitatsomepoint.(Youguessedit:italsomightneverdeleteit.)Whenwe
talkaboutreachinganobject,we’rereallytalkingabouthavingareachablereferencevariablethatrefers
totheobjectinquestion.IfourJavaprogramhasareferencevariablethatreferstoanobjectandthat
referencevariableisavailabletoalivethread,thenthatobjectisconsideredreachable.We’lltalkmore
abouthowobjectscanbecomeunreachableinthefollowingsection.
CanaJavaapplicationrunoutofmemory?Yes.Thegarbagecollectionsystemattemptstoremove
objectsfrommemorywhentheyarenotused.However,ifyoumaintaintoomanyliveobjects(objects
referencedfromotherliveobjects),thesystemcanrunoutofmemory.Garbagecollectioncannotensure
thatthereisenoughmemory,onlythatthememorythatisavailablewillbemanagedasefficientlyas
possible.
WritingCodeThatExplicitlyMakesObjectsEligibleforCollection
Intheprecedingsection,youlearnedthetheoriesbehindJavagarbagecollection.Inthissection,weshow
howtomakeobjectseligibleforgarbagecollectionusingactualcode.Wealsodiscusshowtoattemptto
forcegarbagecollectionifitisnecessaryandhowyoucanperformadditionalcleanuponobjectsbefore
theyareremovedfrommemory.
NullingaReference
Aswediscussedearlier,anobjectbecomeseligibleforgarbagecollectionwhentherearenomore
reachablereferencestoit.Obviously,iftherearenoreachablereferences,itdoesn’tmatterwhathappens
totheobject.Forourpurposesitisjustfloatinginspace,unused,inaccessible,andnolongerneeded.
Thefirstwaytoremoveareferencetoanobjectistosetthereferencevariablethatreferstotheobject
tonull.Examinethefollowingcode:
TheStringBufferobjectwiththevaluehelloisassignedtothereferencevariablesbinthethird
line.Tomaketheobjecteligible(forgarbagecollection),wesetthereferencevariablesbtonull,which
removesthesinglereferencethatexistedtotheStringBufferobject.Onceline6hasrun,ourhappy
littlehelloStringBufferobjectisdoomed,eligibleforgarbagecollection.
ReassigningaReferenceVariable
Wecanalsodecoupleareferencevariablefromanobjectbysettingthereferencevariabletoreferto
anotherobject.Examinethefollowingcode:
Objectsthatarecreatedinamethodalsoneedtobeconsidered.Whenamethodisinvoked,anylocal
variablescreatedexistonlyforthedurationofthemethod.Oncethemethodhasreturned,theobjects
createdinthemethodareeligibleforgarbagecollection.Thereisanobviousexception,however.Ifan
objectisreturnedfromthemethod,itsreferencemightbeassignedtoareferencevariableinthemethod
thatcalledit;hence,itwillnotbeeligibleforcollection.Examinethefollowingcode:
Intheprecedingexample,wecreatedamethodcalledgetDate()thatreturnsaDateobject.This
methodcreatestwoobjects:aDateandaStringBuffercontainingthedateinformation.Sincethe
methodreturnsareferencetotheDateobjectandthisreferenceisassignedtoalocalvariable,itwillnot
beeligibleforcollectionevenafterthegetDate()methodhascompleted.TheStringBufferobject,
though,willbeeligible,eventhoughwedidn’texplicitlysetthenowvariabletonull.
IsolatingaReference
Thereisanotherwayinwhichobjectscanbecomeeligibleforgarbagecollection,eveniftheystillhave
validreferences!Wecallthisscenario“islandsofisolation.”
Asimpleexampleisaclassthathasaninstancevariablethatisareferencevariabletoanother
instanceofthesameclass.Nowimaginethattwosuchinstancesexistandthattheyrefertoeachother.If
allotherreferencestothesetwoobjectsareremoved,theneventhougheachobjectstillhasavalid
reference,therewillbenowayforanylivethreadtoaccesseitherobject.Whenthegarbagecollector
runs,itcanusuallydiscoveranysuchislandsofobjectsandremovethem.Asyoucanimagine,such
islandscanbecomequitelarge,theoreticallycontaininghundredsofobjects.Examinethefollowingcode:
Whenthecodereaches//docomplicated,thethreeIslandobjects(previouslyknownasi2,i3,
andi4)haveinstancevariablessothattheyrefertoeachother,buttheirlinkstotheoutsideworld(i2,
i3,andi4)havebeennulled.Thesethreeobjectsareeligibleforgarbagecollection.
Thiscoverseverythingyouwillneedtoknowaboutmakingobjectseligibleforgarbagecollection.
StudyFigure3-2toreinforcetheconceptsofobjectswithoutreferencesandislandsofisolation.
FIGURE3-2 Islandobjectseligibleforgarbagecollection
ForcingGarbageCollection
Thefirstthingthatweshouldmentionhereisthat,contrarytothissection’stitle,garbagecollection
cannotbeforced.However,JavaprovidessomemethodsthatallowyoutorequestthattheJVMperform
garbagecollection.
Note:TheJavagarbagecollectorhasevolvedtosuchanadvancedstatethatit’srecommendedthatyou
neverinvokeSystem.gc()inyourcode—leaveittotheJVM.
Inreality,itispossibleonlytosuggesttotheJVMthatitperformgarbagecollection.However,there
arenoguaranteestheJVMwillactuallyremovealloftheunusedobjectsfrommemory(evenifgarbage
collectionisrun).Itisessentialthatyouunderstandthisconceptfortheexam.
ThegarbagecollectionroutinesthatJavaprovidesaremembersoftheRuntimeclass.TheRuntime
classisaspecialclassthathasasingleobject(aSingleton)foreachmainprogram.TheRuntime
objectprovidesamechanismforcommunicatingdirectlywiththevirtualmachine.TogettheRuntime
instance,youcanusethemethodRuntime.getRuntime(),whichreturnstheSingleton.Onceyouhave
theSingleton,youcaninvokethegarbagecollectorusingthegc()method.Alternatively,youcancall
thesamemethodontheSystemclass,whichhasstaticmethodsthatcandotheworkofobtainingthe
Singletonforyou.Thesimplestwaytoaskforgarbagecollection(remember—justarequest)is
System.gc();
Theoretically,aftercallingSystem.gc(),youwillhaveasmuchfreememoryaspossible.Wesay
“theoretically”becausethisroutinedoesnotalwaysworkthatway.First,yourJVMmaynothave
implementedthisroutine;thelanguagespecificationallowsthisroutinetodonothingatall.Second,
anotherthreadmightgrablotsofmemoryrightafteryourunthegarbagecollector.
ThisisnottosaythatSystem.gc()isauselessmethod—it’smuchbetterthannothing.Youjustcan’t
relyonSystem.gc()tofreeupenoughmemorysothatyoudon’thavetoworryaboutrunningoutof
memory.TheCertificationExamisinterestedinguaranteedbehavior,notprobablebehavior.
Nowthatyouaresomewhatfamiliarwithhowthisworks,let’sdoalittleexperimenttoseetheeffects
ofgarbagecollection.ThefollowingprogramletsusknowhowmuchtotalmemorytheJVMhas
availabletoitandhowmuchfreememoryithas.Itthencreates10,000Dateobjects.Afterthis,ittellsus
howmuchmemoryisleftandthencallsthegarbagecollector(which,ifitdecidestorun,shouldhaltthe
programuntilallunusedobjectsareremoved).Thefinalfreememoryresultshouldindicatewhetherit
hasrun.Let’slookattheprogram:
Asyoucansee,theJVMactuallydiddecidetogarbagecollect(thatis,delete)theeligibleobjects.In
theprecedingexample,wesuggestedthattheJVMperformgarbagecollectionwith458,048bytesof
memoryremaining,andithonoredourrequest.Thisprogramhasonlyoneuserthreadrunning,sothere
wasnothingelsegoingonwhenwecalledrt.gc().Keepinmindthatthebehaviorwhengc()iscalled
maybedifferentfordifferentJVMs;hence,thereisnoguaranteethattheunusedobjectswillberemoved
frommemory.Abouttheonlythingyoucanguaranteeisthatifyouarerunningverylowonmemory,the
garbagecollectorwillrunbeforeitthrowsanOutOfMemoryException.
EXERCISE3-2
GarbageCollectionExperiment
TrychangingtheCheckGCprogrambyputtinglines13and14insidealoop.Youmightseethatnotall
memoryisreleasedonanygivenrunoftheGC.
CleaningUpBeforeGarbageCollection—thefinalize()Method
Javaprovidesamechanismthatletsyourunsomecodejustbeforeyourobjectisdeletedbythegarbage
collector.Thiscodeislocatedinamethodnamedfinalize()thatallclassesinheritfromclassObject.
Onthesurface,thissoundslikeagreatidea;maybeyourobjectopenedupsomeresources,andyou’dlike
toclosethembeforeyourobjectisdeleted.Theproblemisthat,asyoumayhavegatheredbynow,you
cannevercountonthegarbagecollectortodeleteanobject.So,anycodethatyouputintoyourclass’s
overriddenfinalize()methodisnotguaranteedtorun.Becausethefinalize()methodforanygiven
objectmightrun,butyoucan’tcountonit,don’tputanyessentialcodeintoyourfinalize()method.In
fact,werecommendthat,ingeneral,youdon’toverridefinalize()atall.
TrickyLittlefinalize()Gotchas
Thereareacoupleofconceptsconcerningfinalize()thatyouneedtoremember:
Foranygivenobject,finalize()willbecalledonlyonce(atmost)bythegarbage
collector.
Callingfinalize()canactuallyresultinsavinganobjectfromdeletion.
Let’sexaminethesestatementsalittlefurther.Firstofall,rememberthatanycodeyoucanputintoa
normalmethodyoucanputintofinalize().Forexample,inthefinalize()methodyoucouldwrite
codethatpassesareferencetotheobjectinquestionbacktoanotherobject,effectivelyineligible-izing
theobjectforgarbagecollection.Ifatsomelaterpointthissameobjectbecomeseligibleforgarbage
collectionagain,thegarbagecollectorcanstillprocesstheobjectanddeleteit.Thegarbagecollector,
however,willrememberthat,forthisobject,finalize()alreadyran,anditwillnotrunfinalize()
again.
CERTIFICATIONSUMMARY
Thischaptercoveredawiderangeoftopics.Don’tworryifyouhavetoreviewsomeofthesetopicsas
yougetintolaterchapters.Thischapterincludesalotoffoundationalstuffthatwillcomeintoplaylater.
Westartedthechapterbyreviewingthestackandtheheap;rememberthatlocalvariablesliveonthe
stackandinstancevariableslivewiththeirobjectsontheheap.
WereviewedlegalliteralsforprimitivesandStrings,andthenwediscussedthebasicsofassigning
valuestoprimitivesandreferencevariablesandtherulesforcastingprimitives.
Nextwediscussedtheconceptofscope,or“Howlongwillthisvariablelive?”Rememberthefour
basicscopesinorderoflesseninglifespan:static,instance,local,andblock.
Wecoveredtheimplicationsofusinguninitializedvariablesandtheimportanceofthefactthatlocal
variablesMUSTbeassignedavalueexplicitly.Wetalkedaboutsomeofthetrickyaspectsofassigning
onereferencevariabletoanotherandsomeofthefinerpointsofpassingvariablesintomethods,including
adiscussionof“shadowing.”
Finally,wedoveintogarbagecollection,Java’sautomaticmemorymanagementfeature.Welearned
thattheheapiswhereobjectsliveandwhereallthecoolgarbagecollectionactivitytakesplace.We
learnedthatintheend,theJVMwillperformgarbagecollectionwheneveritwantsto.You(the
programmer)canrequestagarbagecollectionrun,butyoucan’tforceit.Wetalkedaboutgarbage
collectiononlyapplyingtoobjectsthatareeligible,andthateligiblemeans“inaccessiblefromanylive
thread.”Finally,wediscussedtherarelyusefulfinalize()methodandwhatyou’llhavetoknowabout
itfortheexam.Allinall,thiswasonefascinatingchapter.
TWO-MINUTEDRILL
Herearesomeofthekeypointsfromthischapter.
StackandHeap
Localvariables(methodvariables)liveonthestack.
Objectsandtheirinstancevariablesliveontheheap.
LiteralsandPrimitiveCasting(OCAObjective2.1)
Integerliteralscanbebinary,decimal,octal(suchas013),orhexadecimal(suchas0x3d).
LiteralsforlongsendinLorl.(Forthesakeofreadability,werecommend“L“.)
FloatliteralsendinForf,anddoubleliteralsendinadigitorDord.
Thebooleanliteralsaretrueandfalse.
Literalsforcharsareasinglecharacterinsidesinglequotes:‘d’.
Scope(OCAObjective1.1)
Scopereferstothelifetimeofavariable.
Therearefourbasicscopes:
Staticvariableslivebasicallyaslongastheirclasslives.
Instancevariablesliveaslongastheirobjectlives.
Localvariablesliveaslongastheirmethodisonthestack;however,iftheirmethod
invokesanothermethod,theyaretemporarilyunavailable.
Blockvariables(forexample,inafororanif)liveuntiltheblockcompletes.
BasicAssignments(OCAObjectives2.1,2.2,and2.3)
Literalintegersareimplicitlyints.
Integerexpressionsalwaysresultinanint-sizedresult,neversmaller.
Floating-pointnumbersareimplicitlydoubles(64bits).
Narrowingaprimitivetruncatesthehighorderbits.
Compoundassignments(suchas+=)performanautomaticcast.
Areferencevariableholdsthebitsthatareusedtorefertoanobject.
Referencevariablescanrefertosubclassesofthedeclaredtypebutnottosuperclasses.
Whenyoucreateanewobject,suchasButtonb=newButton();,theJVMdoesthree
things:
Makesareferencevariablenamedb,oftypeButton.
CreatesanewButtonobject.
AssignstheButtonobjecttothereferencevariableb.
UsingaVariableorArrayElementThatIsUninitializedandUnassigned(OCA
Objectives4.1and4.2)
Whenanarrayofobjectsisinstantiated,objectswithinthearrayarenotinstantiated
automatically,butallthereferencesgetthedefaultvalueofnull.
Whenanarrayofprimitivesisinstantiated,elementsgetdefaultvalues.
Instancevariablesarealwaysinitializedwithadefaultvalue.
Local/automatic/methodvariablesarenevergivenadefaultvalue.Ifyouattempttouseone
beforeinitializingit,you’llgetacompilererror.
PassingVariablesintoMethods(OCAObjective6.6)
Methodscantakeprimitivesand/orobjectreferencesasarguments.
Methodargumentsarealwayscopies.
Methodargumentsareneveractualobjects(theycanbereferencestoobjects).
Aprimitiveargumentisanunattachedcopyoftheoriginalprimitive.
Areferenceargumentisanothercopyofareferencetotheoriginalobject.
Shadowingoccurswhentwovariableswithdifferentscopessharethesamename.Thisleads
tohard-to-findbugsandhard-to-answerexamquestions.
GarbageCollection(OCAObjective2.4)
InJava,garbagecollection(GC)providesautomatedmemorymanagement.
ThepurposeofGCistodeleteobjectsthatcan’tbereached.
OnlytheJVMdecideswhentoruntheGC;youcanonlysuggestit.
Youcan’tknowtheGCalgorithmforsure.
Objectsmustbeconsideredeligiblebeforetheycanbegarbagecollected.
Anobjectiseligiblewhennolivethreadcanreachit.
Toreachanobject,youmusthavealive,reachablereferencetothatobject.
Javaapplicationscanrunoutofmemory.
Islandsofobjectscanbegarbagecollected,eventhoughtheyrefertoeachother.
RequestgarbagecollectionwithSystem.gc();.
TheObjectclasshasafinalize()method.
Thefinalize()methodisguaranteedtorunonceandonlyoncebeforethegarbagecollector
deletesanobject.
Thegarbagecollectormakesnoguarantees;finalize()mayneverrun.
Youcanineligible-izeanobjectforGCfromwithinfinalize().
SELFTEST
1.Given:
When//doStuffisreached,howmanyobjectsareeligibleforgarbagecollection?
A.0
B.1
C.2
D.Compilationfails
E.Itisnotpossibletoknow
F.Anexceptionisthrownatruntime
2.Given:
Whatistheresult?
A.710
B.810
C.712
D.812
E.Compilationfails
F.Anexceptionisthrownatruntime
7.Given:
Whenexecutionreachesthecommentedline,whicharetrue?(Chooseallthatapply.)
A.Theoutputcontains1
B.Theoutputcontains2
C.Theoutputcontains3
D.ZeroWindobjectsareeligibleforgarbagecollection
E.OneWindobjectiseligibleforgarbagecollection
F.TwoWindobjectsareeligibleforgarbagecollection
G.ThreeWindobjectsareeligibleforgarbagecollection
Whatistheresult?
A.2
B.3
C.4
D.5
E.Compilationfails
F.Anexceptionisthrownatruntime
SELFTESTANSWERS
1. Ciscorrect.OnlyoneCardBoardobject(c1)iseligible,butithasanassociatedShort
wrapperobjectthatisalsoeligible.
A,B,D,E,andFareincorrectbasedontheabove.(OCAObjective2.4)
2. Eiscorrect;compilationoflineEfails.Whenamathematicaloperationisperformedon
anyprimitivessmallerthanints,theresultisautomaticallycasttoaninteger.
A,B,C,andDarealllegalprimitivecasts.(OCAObjective2.1)
3. Ciscorrect;lineCwillNOTcompile.AsofJava7,underscorescanbeincludedin
numericliterals,butnotatthebeginningortheend.
A,B,D,E,andFareincorrect.AandBarelegalnumericliterals.DandEareexamplesof
validbinaryliterals,whichwerenewtoJava7,andFisavalidhexadecimalliteralthatusesan
underscore.(OCAObjective2.1)
4. Fiscorrect.Them2object’sm1instancevariableisneverinitialized,sowhenm5triesto
useit,aNullPointerExceptionisthrown.
A,B,C,D,andEareincorrectbasedontheabove.(OCAObjectives2.1and2.3)
5. Aiscorrect.Thereferencesf1,z,andf3allrefertothesameinstanceofFizz.Thefinal
modifierassuresthatareferencevariablecannotbereferredtoadifferentobject,butfinal
doesn’tkeeptheobject’sstatefromchanging.
B,C,D,E,andFareincorrectbasedontheabove.(OCAObjective2.2)
6. Biscorrect.Inthego()method,mreferstothesingleMirrorinstance,buttheintiisa
newintvariable,adetachedcopyofi2.
A,C,D,E,andFareincorrectbasedontheabove.(OCAObjectives2.2and2.3)
7. A,B,andGarecorrect.Theconstructorsetsthevalueofidforw1andw2.Whenthe
commentedlineisreached,noneofthethreeWindobjectscanbeaccessed,sotheyareeligibleto
begarbagecollected.
C,D,E,andFareincorrectbasedontheabove.(OCAObjectives1.1,2.3,and2.4)
8. Eiscorrect.Theparameterdeclaredonline9isvalid(althoughugly),butthevariable
nameouchcannotbedeclaredagainonline11inthesamescopeasthedeclarationonline9.
A,B,C,D,andFareincorrectbasedontheabove.(OCAObjectives1.1and2.1)
9. Discorrect.Insidethego()method,h1isoutofscope.
A,B,C,andEareincorrectbasedontheabove.(OCAObjectives1.1and6.1)
10. Aiscorrect.ThreeNetworkobjectsarecreated.Then2objecthasareferencetothen1
object,andthen3objecthasareferencetothen2object.TheS.O.P.canbereadas,“Usethen3
object’sNetworkreference(thefirstp),tofindthatobject’sreference(n2),andusethatobject’s
reference(thesecondp)tofindthatobject’s(n1’s)id,andprintthatid.”
B,C,D,andEareincorrectbasedontheabove.(OCAObjectives,2.2,2.3,and6.4)
11. Biscorrect.Itshouldbeclearthatthereisstillareferencetotheobjectreferredtobya2,
andthatthereisstillareferencetotheobjectreferredtobya2.b2.Whatmightbelessclearisthat
youcanstillaccesstheotherBetaobjectthroughthestaticvariablea2.b1—becauseit’sstatic.
A,C,D,E,andFareincorrectbasedontheabove.(OCAObjective2.4)
12. Biscorrect.IntheTelescopeclass,therearethreedifferentvariablesnamedmagnify.
Thego()method’sversionandthezoomMore()method’sversionarenotusedinthezoomIn()
method.ThezoomIn()methodmultipliestheclassvariable*5.Theresult(10)issentto
zoomMore(),butwhathappensinzoomMore()staysinzoomMore().TheS.O.P.printsthevalueof
zoomIn()’smagnify.
A,C,D,E,F,andGareincorrectbasedontheabove.(OCAObjectives1.1and6.6)
13. Eiscorrect.Ingo1()thelocalvariablexisnotinitialized.
A,B,C,D,andFareincorrectbasedontheabove.(OCAObjectives2.1and2.3)
I
4
Operators
CERTIFICATIONOBJECTIVES
•UsingJavaOperators
•UseParenthesestoOverrideOperatorPrecedence
•TestEqualityBetweenStringsandOtherObjectsUsing==andequals()
Two-MinuteDrill
Q&ASelfTest
fyou’vegotvariables,you’regoingtomodifythem.(Unlessyou’reoneofthosenew-fangled“FP”
programmers.)You’llincrementthem,addthemtogether,andcompareonetoanother(inabouta
dozendifferentways).Inthischapter,you’lllearnhowtodoallthatinJava.Asanaddedbonus,
you’lllearnhowtodothingsthatyou’llprobablyneveruseintherealworld,butthatwillalmost
certainlybeontheexam.
CERTIFICATIONOBJECTIVE
JavaOperators(OCAObjectives3.1,3.2,and3.3)
3.1UseJavaoperators;includingparenthesestooverrideoperatorprecedence.
3.2TestequalitybetweenStringsandotherobjectsusing==andequals().
3.3Createifandif/elseandternaryconstructs
Javaoperatorsproducenewvaluesfromoneormoreoperands.(Justsowe’reallclear,rememberthat
operandsarethethingsontherightorleftsideoftheoperator.)Theresultofmostoperationsiseithera
booleanornumericvalue.BecauseyouknowbynowthatJavaisnotC++,youwon’tbesurprisedthat
Javaoperatorsaren’ttypicallyoverloaded.Thereare,however,afewexceptionaloperatorsthatcome
overloaded:
The+operatorcanbeusedtoaddtwonumericprimitivestogetherortoperforma
concatenationoperationifeitheroperandisaString.
The&,|,and^operatorscanallbeusedintwodifferentways,althoughonthisversionofthe
exam,theirbit-twiddlingcapabilitieswon’tbetested.
Stayawake.Operatorsareoftenthesectionoftheexamwherecandidatesseetheirlowestscores.
Additionally,operatorsandassignmentsareapartofmanyquestionsdealingwithothertopics—itwould
beashametonailareallytrickylambdasquestiononlytoblowitonapre-incrementstatement.
AssignmentOperators
Wecoveredmostofthefunctionalityoftheequal(=)assignmentoperatorinChapter3.Tosummarize:
Whenassigningavaluetoaprimitive,sizematters.Besureyouknowwhenimplicitcasting
willoccur,whenexplicitcastingisnecessary,andwhentruncationmightoccur.
Rememberthatareferencevariableisn’tanobject;it’sawaytogettoanobject.(Weknow
allyouC++programmersarejustdyingforustosay,“it’sapointer,”butwe’renotgoingto.)
Whenassigningavaluetoareferencevariable,typematters.Remembertherulesfor
supertypes,subtypes,andarrays.
Nextwe’llcoverafewmoredetailsabouttheassignmentoperatorsthatareontheexam,andwhenwe
gettothenextchapter,we’lltakealookathowtheassignmentoperator=workswithStrings(whichare
immutable).
Don’tspendtimepreparingfortopicsthatarenolongerontheexam!Thefollowingtopics
haveNOTbeenontheexamsinceJava1.4:
Bit-shiftingoperators
Bitwiseoperators
Two’scomplement
Divide-by-zerostuff
It’snotthatthesearen’timportanttopics;it’sjustthatthey’renotontheexamanymore,and
we’rereallyfocusedontheexam.(Note:Thereasonwebringthisupatallisbecauseyou
mightencountermockexamquestionsonthesetopics—youcanignorethosequestions!)
CompoundAssignmentOperators
Thereareactually11orsocompoundassignmentoperators,butonlythe4mostcommonlyused(+=,-=,
*=,and/=)areontheexam.Thecompoundassignmentoperatorsletlazytypistsshaveafewkeystrokes
offtheirworkload.
Hereareseveralexampleassignments,firstwithoutusingacompoundoperator:
y=y-6;
x=x+2*5;
Now,withcompoundoperators:
y-=6;
x+=2*5;
Thelasttwoassignmentsgivethesameresultasthefirsttwo.
RelationalOperators
Theexamcoverssixrelationaloperators(<,<=,>,>=,==,and!=).Relationaloperatorsalwaysresultin
aboolean(trueorfalse)value.Thisbooleanvalueismostoftenusedinaniftest,asfollows:
Buttheresultingvaluecanalsobeassigneddirectlytoabooleanprimitive:
Javahasfourrelationaloperatorsthatcanbeusedtocompareanycombinationofintegers,floating-
pointnumbers,orcharacters:
>Greaterthan
>=Greaterthanorequalto
<Lessthan
<=Lessthanorequalto
Let’slookatsomelegalcomparisons:
Intheprecedingcode,weareusingacomparisonbetweencharacters.It’salsolegaltocomparea
characterprimitivewithanynumber(althoughitisn’tgreatprogrammingstyle).Runningthepreceding
classwilloutputthefollowing:
Theanimalisagrayelephant
Wementionedthatcharacterscanbeusedincomparisonoperators.Whencomparingacharacterwith
acharacteroracharacterwithanumber,JavawillusetheUnicodevalueofthecharacterasthe
numericalvalueforcomparison.
“Equality”Operators
Javaalsohastworelationaloperators(sometimescalled“equalityoperators”)thatcomparetwosimilar
“things”andreturnaboolean(trueorfalse)thatrepresentswhat’strueaboutthetwo“things”being
equal.Theseoperatorsare
==Equal(alsoknownasequalto)
!=Notequal(alsoknownasnotequalto)
Eachindividualcomparisoncaninvolvetwonumbers(includingchar),twobooleanvalues,ortwo
objectreferencevariables.Youcan’tcompareincompatibletypes,however.Whatwoulditmeantoaskif
abooleanisequaltoachar?OrifaButtonisequaltoaStringarray?(Thisisnonsense,whichis
whyyoucan’tdoit.)Therearefourdifferenttypesofthingsthatcanbetested:
Numbers
Characters
Booleanprimitives
Objectreferencevariables
Sowhatdoes==lookat?Thevalueinthevariable—inotherwords,thebitpattern.
EqualityforPrimitives
Mostprogrammersarefamiliarwithcomparingprimitivevalues.Thefollowingcodeshowssome
equalitytestsonprimitivevariables:
Thisprogramproducesthefollowingoutput:
Asyoucansee,ifafloating-pointnumberiscomparedwithanintegerandthevaluesarethesame,the
==operatorusuallyreturnstrueasexpected.
EqualityforReferenceVariables
Asyousawearlier,tworeferencevariablescanrefertothesameobject,asthefollowingcodesnippet
demonstrates:
Don’tmistake=for==inabooleanexpression.Thefollowingislegal:
Lookcarefully!Youmightbetemptedtothinktheoutputisbisfalse,butlookatthe
booleantestinline12.Thebooleanvariablebisnotbeingcomparedtotrue;it’sbeingsetto
true.Oncebissettotrue,theprintlnexecutesandwegetbistrue.Theresultofany
assignmentexpressionisthevalueofthevariablefollowingtheassignment.Thissubstitution
of=for==worksonlywithbooleanvariablesbecausetheiftestcanbedoneonlyonboolean
expressions.Thus,thisdoesnotcompile:
Becausexisaninteger(andnotaboolean),theresultof(x=0)is0(theresultofthe
assignment).Primitiveintscannotbeusedwhereabooleanvalueisexpected,sothecodein
line8won’tworkunlessit’schangedfromanassignment(=)toanequalitytest(==)as
follows:
Afterrunningthiscode,bothvariableaandvariablebwillrefertothesameobject(aJButtonwith
thelabelExit).Referencevariablescanbetestedtoseeiftheyrefertothesameobjectbyusingthe==
operator.Remember,the==operatorislookingatthebitsinthevariable,soforreferencevariables,this
meansthatifthebitsinbothreferencevariablesareidentical,thenbothrefertothesameobject.Lookat
thefollowingcode:
Thiscodecreatesthreereferencevariables.Thefirsttwo,aandb,areseparateJButtonobjectsthat
happentohavethesamelabel.Thethirdreferencevariable,c,isinitializedtorefertothesameobject
thatarefersto.Whenthisprogramruns,thefollowingoutputisproduced:
ThisshowsusthataandcreferencethesameinstanceofaJButton.The==operatorwillnottest
whethertwoobjectsare“meaningfullyequivalent,”aconceptwe’llcoverinmuchmoredetailinChapter
6,whenwelookattheequals()method(asopposedtotheequalsoperatorwe’relookingathere).
EqualityforStringsandjava.lang.Object.equals()
Wejustused==todeterminewhethertworeferencevariablesrefertothesameobject.Becauseobjects
aresocentraltoJava,everyclassinJavainheritsamethodfromclassObjectthatteststoseeiftwo
objectsoftheclassare“equal.”Notsurprisingly,thismethodiscalledequals().Inthiscaseofthe
equals()method,thephrase“meaningfullyequivalent”shouldbeusedinsteadoftheword“equal.”So
theequals()methodisusedtodetermineiftwoobjectsofthesameclassare“meaningfullyequivalent.”
Forclassesthatyoucreate,youhavetheoptionofoverridingtheequals()methodthatyourclass
inheritedfromclassObjectandcreatingyourowndefinitionof“meaningfullyequivalent”forinstances
ofyourclass.
Intermsofunderstandingtheequals()methodfortheOCAexam,youneedtounderstandtwoaspects
oftheequals()method:
Whatequals()meansinclassObject
Whatequals()meansinclassString
Theequals()MethodinClassObjectTheequals()methodinclassObjectworksthesame
waythatthe==operatorworks.Iftworeferencespointtothesameobject,theequals()methodwill
returntrue.Iftworeferencespointtodifferentobjects,eveniftheyhavethesamevalues,themethodwill
returnfalse.
Theequals()MethodinClassStringTheequals()methodinclassStringhasbeen
overridden.Whentheequals()methodisusedtocomparetwostrings,itwillreturntrueifthestrings
havethesamevalue,anditwillreturnfalseifthestringshavedifferentvalues.ForString’sequals()
method,valuesAREcasesensitive.
Let’stakealookathowtheequals()methodworksinaction(noticethattheBudgieclassdidNOT
overrideObject.equals()):
whichproducestheoutput:
false
true
true
false
Equalityforenums
Onceyou’vedeclaredanenum,it’snotexpandable.Atruntime,there’snowaytomakeadditionalenum
constants.Ofcourse,youcanhaveasmanyvariablesasyou’dlikerefertoagivenenumconstant,soit’s
importanttobeabletocomparetwoenumreferencevariablestoseeifthey’re“equal”—thatis,dothey
refertothesameenumconstant?Youcanuseeitherthe==operatorortheequals()methodtodetermine
whethertwovariablesarereferringtothesameenumconstant:
(Weknow}}isugly;we’repreppingyou.)Thisproducestheoutput:
instanceofComparison
Theinstanceofoperatorisusedforobjectreferencevariablesonly,andyoucanuseittocheckwhether
anobjectisofaparticulartype.By“type,”wemeanclassorinterfacetype—inotherwords,whetherthe
objectreferredtobythevariableontheleftsideoftheoperatorpassestheIS-Atestfortheclassor
interfacetypeontherightside.(Chapter2coveredIS-Arelationshipsindetail.)Thefollowingsimple
example,
printsthis:
sisaString
Eveniftheobjectbeingtestedisnotanactualinstantiationoftheclasstypeontherightsideofthe
operator,instanceofwillstillreturntrueiftheobjectbeingcomparedisassignmentcompatiblewith
thetypeontheright.
Thefollowingexampledemonstratesacommonuseforinstanceof:testinganobjecttoseeifit’san
instanceofoneofitssubtypesbeforeattemptingadowncast:
Thecodecompilesandproducesthisoutput:
‘a’referstoaB
Inexampleslikethis,theuseoftheinstanceofoperatorprotectstheprogramfromattemptingan
illegaldowncast.
Youcantestanobjectreferenceagainstitsownclasstypeoranyofitssuperclasses.Thismeansthat
anyobjectreferencewillevaluatetotrueifyouusetheinstanceofoperatoragainsttypeObject,as
follows:
Thisprints
bisdefinitelyanObject
Lookforinstanceofquestionsthattestwhetheranobjectisaninstanceofaninterfacewhen
theobject’sclassimplementstheinterfaceindirectly.Anindirectimplementationoccurswhen
oneofanobject’ssuperclassesimplementsaninterface,buttheactualclassoftheinstance
doesnot.Inthisexample,
thefollowingaretrue:
Anobjectissaidtobeofaparticularinterfacetype(meaningitwillpasstheinstanceoftest)
ifanyoftheobject’ssuperclassesimplementtheinterface.
Inaddition,itislegaltotestwhetherthenullreferenceisaninstanceofaclass.Thiswillalways
resultinfalse,ofcourse.Thisexample,
printsthis:
falsefalse
instanceofCompilerError
Youcan’tusetheinstanceofoperatortotestacrosstwodifferentclasshierarchies.Forinstance,the
followingwillNOTcompile:
Compilationfails—there’snowaydcouldeverrefertoaCatorasubtypeofCat.
Rememberthatarraysareobjects,evenifthearrayisanarrayofprimitives.Watchfor
questionsthatlooksomethinglikethis:
AnarrayisalwaysaninstanceofObject.Anyarray.
Table4-1summarizestheuseoftheinstanceofoperatorgiventhefollowing:
TABLE4-1 OperandsandResultsUsinginstanceofOperator
ArithmeticOperators
We’resureyou’refamiliarwiththebasicarithmeticoperators:
+addition
–subtraction
*multiplication
/division
Thesecanbeusedinthestandardway:
TheRemainder(%)Operator(a.k.a.theModulusOperator)
Oneoperatoryoumightnotbeasfamiliarwithistheremainderoperator:%.Theremainderoperator
dividestheleftoperandbytherightoperand,andtheresultistheremainder,asthefollowingcode
demonstrates:
RunningclassMathTestprintsthefollowing:
Theresultof15%4istheremainderof15dividedby4.Theremainderis3
(Remember:Expressionsareevaluatedfromlefttorightbydefault.Youcanchangethissequence,or
precedence,byaddingparentheses.Alsorememberthatthe*,/,and%operatorshaveahigher
precedencethanthe+and-operators.)
Whenworkingwithints,theremainderoperator(a.k.a.themodulusoperator)andthe
divisionoperatorrelatetoeachotherinaninterestingway:
Themodulusoperatorthrowsouteverythingbuttheremainder.
Thedivisionoperatorthrowsouttheremainder.
StringConcatenationOperator
Theplussigncanalsobeusedtoconcatenatetwostringstogether,aswesawearlier(andaswe’ll
definitelyseeagain):
StringconcatenationgetsinterestingwhenyoucombinenumberswithStrings.Checkoutthe
following:
Willthe+operatoractasaplussignwhenaddingtheintvariablesbandc?Orwillthe+operator
treat3and7ascharactersandconcatenatethemindividually?WilltheresultbeString10orString37?
Okay,you’vehadlongenoughtothinkaboutit.
TheintvaluesweresimplytreatedascharactersandgluedontotherightsideoftheString,giving
theresult:
String37
Sowecouldreadthepreviouscodeas
“StartwiththevalueString,andconcatenatethecharacter3(thevalueofb)toit,toproduceanew
stringString3,andthenconcatenatethecharacter7(thevalueofc)tothat,toproduceanewstring
String37.Thenprintitout.”
However,ifyouputparenthesesaroundthetwointvariables,asfollows,
System.out.println(a+(b+c));
you’llgetthis:
String10
Usingparenthesescausesthe(b+c)toevaluatefirst,sotherightmost+operatorfunctionsasthe
additionoperator,giventhatbothoperandsareintvalues.Thekeypointhereisthatwithinthe
parentheses,theleft-handoperandisnotaString.Ifitwere,thenthe+operatorwouldperformString
concatenation.Thepreviouscodecanbereadas
“Addthevaluesofbandctogether,andthentakethesumandconvertittoaStringandconcatenateitwiththeStringfrom
variablea.”
Theruletorememberisthis:
IfeitheroperandisaString,the+operatorbecomesaStringconcatenationoperator.Ifbothoperandsarenumbers,the+
operatoristheadditionoperator.
You’llfindthatsometimesyoumighthavetroubledecidingwhether,say,theleft-handoperatorisa
Stringornot.Ontheexam,don’texpectitalwaystobeobvious.(Actually,nowthatwethinkaboutit,
don’texpectitevertobeobvious.)Lookatthefollowingcode:
System.out.println(x.foo()+7);
Youcan’tknowhowthe+operatorisbeinguseduntilyoufindoutwhatthefoo()methodreturns!If
foo()returnsaString,then7isconcatenatedtothereturnedString.Butiffoo()returnsanumber,
thenthe+operatorisusedtoadd7tothereturnvalueoffoo().
Finally,youneedtoknowthatit’slegaltomushtogetherthecompoundadditiveoperator(+=)and
Strings,likeso:
Sincebothtimesthe+=operatorwasusedandtheleftoperandwasaString,bothoperationswere
concatenations,resultingin
1234567
Ifyoudon’tunderstandhowStringconcatenationworks,especiallywithinaprintstatement,
youcouldactuallyfailtheexamevenifyouknowtherestoftheanswerstothequestions!
Becausesomanyquestionsask"Whatistheresult?",youneedtoknownotonlytheresultof
thecoderunningbutalsohowthatresultisprinted.Althoughatleastafewquestionswill
directlytestyourStringknowledge,Stringconcatenationshowsupinotherquestionson
virtuallyeveryobjective.Experiment!Forexample,youmightseealinesuchasthis:
Itprintsthis:
23
Butiftheprintstatementchangestothis:
System.out.println(b+3);
Theprintedresultbecomes
5
IncrementandDecrementOperators
Javahastwooperatorsthatwillincrementordecrementavariablebyexactlyone.Theseoperatorsare
eithertwoplussigns(++)ortwominussigns(--):
++Increment(prefixandpostfix)
--Decrement(prefixandpostfix)
Theoperatorisplacedeitherbefore(prefix)orafter(postfix)avariabletochangeitsvalue.Whether
theoperatorcomesbeforeoraftertheoperandcanchangetheoutcomeofanexpression.Examinethe
following:
Noticethatinthefourthlineoftheprogramtheincrementoperatorisafterthevariableplayers.That
meanswe’reusingthepostfixincrementoperator,whichcausesplayerstobeincrementedbyonebut
onlyafterthevalueofplayersisusedintheexpression.Whenwerunthisprogram,itoutputsthe
following:
Noticethatwhenthevariableiswrittentothescreen,atfirstitsaysthevalueis0.Becauseweusedthe
postfixincrementoperator,theincrementdoesn’thappenuntilaftertheplayersvariableisusedinthe
printstatement.Getit?The“post”inpostfixmeansafter.Line5doesn’tincrementplayers;itjust
outputsitsvaluetothescreen,sothenewlyincrementedvaluedisplayedis1.Line6appliestheprefix
incrementoperatortoplayers,whichmeanstheincrementhappensbeforethevalueofthevariableis
used,sotheoutputis2.
Expecttoseequestionsmixingtheincrementanddecrementoperatorswithotheroperators,asinthe
followingexample:
Theprecedingcodeprintsthis:
x=3y=4
Youcanreadthecodeasfollows:“If3isequalto2OR3<4”
Thefirstexpressioncomparesxandy,andtheresultisfalse,becausetheincrementonxdoesn’t
happenuntilafterthe==testismade.Next,weincrementx,sonowxis3.Thenwechecktoseeifxis
lessthany,butweincrementybeforecomparingitwithx!Sothesecondlogicaltestis(3<4).The
resultistrue,sotheprintstatementruns.
AswithStringconcatenation,theincrementanddecrementoperatorsareusedthroughouttheexam,
evenonquestionsthataren’ttryingtotestyourknowledgeofhowthoseoperatorswork.Youmightsee
theminquestionsonforloops,exceptions,oreventhreads.Beready.
Lookoutforquestionsthatusetheincrementordecrementoperatorsonafinalvariable.
Becausefinalvariablescan’tbechanged,theincrementanddecrementoperatorscan’tbeused
withthem,andanyattempttodosowillresultinacompilererror.Thefollowingcodewon’t
compile:
Itproducesthiserror:
Youcanexpectaviolationlikethistobeburieddeepinacomplexpieceofcode.Ifyouspotit,
youknowthecodewon’tcompile,andyoucanmoveonwithoutworkingthroughtherestof
thecode.
Thisquestionmightseemtobetestingyouonsomecomplexarithmeticoperatortrivia,
when,infact,it’stestingyouonyourknowledgeofthefinalmodifier.
ConditionalOperator
Theconditionaloperatorisaternaryoperator(ithasthreeoperands)andisusedtoevaluateboolean
expressions—muchlikeanifstatement,exceptinsteadofexecutingablockofcodeifthetestistrue,a
conditionaloperatorwillassignavaluetoavariable.Inotherwords,thegoaloftheconditionaloperator
istodecidewhichoftwovaluestoassigntoavariable.Thisoperatorisconstructedusinga?(question
mark)anda:(colon).Theparenthesesareoptional.Hereisitsstructure:
x=(booleanexpression)?valuetoassigniftrue:valuetoassigniffalse
Let’stakealookataconditionaloperatorincode:
Youcanreadtheprecedingcodeas“SetnumOfPetsequalto3“.
Nextwe’regoingtoassignaStringtothestatusvariable.IfnumOfPetsislessthan4,assign“Pet
limitnotexceeded”tothestatusvariable;otherwise,assign“toomanypets”tothestatus
variable.
Aconditionaloperatorstartswithabooleanoperation,followedbytwopossiblevaluesforthe
variabletotheleftoftheassignment(=)operator.Thefirstvalue(theonetotheleftofthecolon)is
assignediftheconditional(boolean)testistrue,andthesecondvalueisassignediftheconditionaltest
isfalse.Youcanevennestconditionaloperatorsintoonestatement:
Don’texpectmanyquestionsusingconditionaloperators,butyoumightgetone.
LogicalOperators
Theexamobjectivesspecifysix“logical”operators(&,|,^,!,&&,and||).SomeOracledocumentation
usesotherterminologyfortheseoperators,butforourpurposesandintheexamobjectives,thesesixare
thelogicaloperators.
BitwiseOperators(NotanExamTopic!)
Okay,thisisgoingtobeconfusing.Ofthesixlogicaloperatorsjustlisted,threeofthem(&,|,and^)can
alsobeusedas“bitwise”operators.Bitwiseoperatorswereincludedinpreviousversionsoftheexam,
butthey’reNOTontheJava6,Java7,orJava8exam.Webringthemupherejustsoyouhaveamore
completepictureofthelogicaloperators.
Hereareseverallegalstatementsthatusebitwiseoperators:
Bitwiseoperatorscomparetwovariablesbitbybitandreturnavariablewhosebitshavebeenset
basedonwhetherthetwovariablesbeingcomparedhadrespectivebitsthatwereeitherboth“on”(&),
oneortheother“on”(|),orexactlyone“on”(^).Bytheway,whenweruntheprecedingcode,weget
0151
Havingsaidallthisaboutbitwiseoperators,thekeythingtoremember
BITWISEOPERATORSARENOTONTHEJava6,Java7,orJava8EXAM!
Short-CircuitLogicalOperators
Fivelogicaloperatorsontheexamareusedtoevaluatestatementsthatcontainmorethanoneboolean
expression.Themostcommonlyusedofthefivearethetwoshort-circuitlogicaloperators:
&&Short-circuitAND
||Short-circuitOR
Theyareusedtolinklittlebooleanexpressionstogethertoformbiggerbooleanexpressions.The&&
and||operatorsevaluateonlybooleanvalues.ForanAND(&&)expressiontobetrue,bothoperands
mustbetrue.Forexample:
if((2<3)&&(3<4)){}
Theprecedingexpressionevaluatestotruebecausebothoperandone(2<3)andoperandtwo(3<
4)evaluatetotrue.
Theshort-circuitfeatureofthe&&operatorissonamedbecauseitdoesn’twasteitstimeon
pointlessevaluations.Ashort-circuit&&evaluatestheleftsideoftheoperationfirst(operandone),andif
itresolvestofalse,the&&operatordoesn’tbotherlookingattherightsideoftheexpression(operand
two)sincethe&&operatoralreadyknowsthatthecompleteexpressioncan’tpossiblybetrue.
Whenweruntheprecedingcode,theassignment(b2=true)neverrunsbecauseoftheshort-circuit
operator,sotheoutputis
The||operatorissimilartothe&&operator,exceptthatitevaluatestotrueifEITHERofthe
operandsistrue.IfthefirstoperandinanORoperationistrue,theresultwillbetrue,sotheshort-
circuit||doesn’twastetimelookingattherightsideoftheequation.Ifthefirstoperandisfalse,
however,theshort-circuit||hastoevaluatethesecondoperandtoseeiftheresultoftheORoperation
willbetrueorfalse.Paycloseattentiontothefollowingexample;you’llseequiteafewquestionslike
thisontheexam:
Whatistheresult?
Here’swhathappenedwhenthemain()methodran:
1.Whenwehitline3,thefirstoperandinthe||expression(inotherwords,theleftsideofthe
||operation)isevaluated.
2.TheisItSmall(3)methodisinvoked,prints“i<5”,andreturnstrue.
3.Becausethefirstoperandinthe||expressiononline3istrue,the||operatordoesn’t
botherevaluatingthesecondoperand.Soweneverseethe“i>=5”thatwouldhaveprintedhad
thesecondoperandbeenevaluated(whichwouldhaveinvokedisItSmall(7)).
4.Line6isevaluated,beginningwiththefirstoperandinthe||expression.
5.TheisItSmall(6)methodiscalled,prints“i>=5”,andreturnsfalse.
6.Becausethefirstoperandinthe||expressiononline6isfalse,the||operatorcan’tskip
thesecondoperand;there’sstillachancetheexpressioncanbetrue,ifthesecondoperand
evaluatestotrue.
7.TheisItSmall(9)methodisinvokedandprints“i>=5”.
8.TheisItSmall(9)methodreturnsfalse,sotheexpressiononline6isfalse,andthusline
7neverexecutes.
The||and&&operatorsworkonlywithbooleanoperands.Theexammaytrytofoolyouby
usingintegerswiththeseoperators:
if(5&&6){}
Itlooksasthoughwe’retryingtodoabitwiseANDonthebitsrepresentingtheintegers5and
6,butthecodewon’tevencompile.
LogicalOperators(notShort-Circuit)
Therearetwonon-short-circuitlogicaloperators:
&Non-short-circuitAND
|Non-short-circuitOR
Theseoperatorsareusedinlogicalexpressionsjustlikethe&&and||operatorsareused,butbecause
theyaren’ttheshort-circuitoperators,theyevaluatebothsidesoftheexpression—always!They’re
inefficient.Forexample,evenifthefirstoperand(leftside)inan&expressionisfalse,thesecond
operandwillstillbeevaluated—eventhoughit’snowimpossiblefortheresulttobetrue!Andthe|is
justasinefficient:ifthefirstoperandistrue,theJavaVirtualMachine(JVM)stillplowsaheadand
evaluatesthesecondoperandevenwhenitknowstheexpressionwillbetrueregardless.
You’llfindalotofquestionsontheexamthatuseboththeshort-circuitandnon-short-circuitlogical
operators.You’llhavetoknowexactlywhichoperandsareevaluatedandwhicharenot,becausethe
resultwillvarydependingonwhetherthesecondoperandintheexpressionisevaluated.Considerthis,
versusthis:
LogicalOperators^and!
Thelasttwologicaloperatorsontheexamare
^Exclusive-OR(XOR)
!Booleaninvert
The^(exclusive-OR)operatorevaluatesonlybooleanvalues.The^operatorisrelatedtothenon-
short-circuitoperatorswejustreviewed,inthatitalwaysevaluatesboththeleftandrightoperandsinan
expression.Foranexclusive-OR(^)expressiontobetrue,EXACTLYoneoperandmustbetrue.This
example,
System.out.println(“xor”+((2<3)^(4>3)));
producesthisoutput:
xorfalse
TheprecedingexpressionevaluatestofalsebecauseBOTHoperandone(2<3)andoperandtwo
(4>3)evaluatetotrue.
The!(booleaninvert)operatorreturnstheoppositeofaboolean’scurrentvalue.Thefollowing
statement,
if(!(7==5)){System.out.println(“notequal”);}
canberead“Ifit’snottruethat7==5,”andthestatementproducesthisoutput:
notequal
Here’sanotherexampleusingbooleans:
Itproducesthisoutput:
!truefalse
Intheprecedingexample,noticethatthe&testsucceeded(printingtrue)andthatthevalueofthe
booleanvariablefdidnotchange,soitprintedfalse.
OperatorPrecedence
TheOCA8examhasreintroducedthetopicofoperatorprecedence.Asyouprobablyalreadyknowbut
willdefinitelyseedemonstratedinthissection,whenseveraloperatorsareusedincombination,the
orderinwhichtheyareevaluatedcanaltertheresultoftheexpression.
OperatorPrecedenceRant
Allowustorantforaminutehere.MemorizingoperatorprecedencewasontheoldSCJP1.2examabout
15yearsago.StartingwiththeSCJP1.4exam,andforalltheexamsuntiltheOCA8,operatorprecedence
hasnotbeenontheexam.Foraglorious15years,candidatesdidn’thavetodothisbitofmemorization.
Sadly,thistopicsnuckitswaybackintotheexamforOCA8.Whydowecaresomuchaboutthis?Takea
lookatthiscode:
System.out.println(true&false==false|true);
Whatresultwouldyouexpect?Imagineamorerealisticversion,evaluatingsomebooleans:
System.out.println(b1&b2==b3|b4);
Whatwouldyouguesstheprogrammer’sintentionwashere?Therearetwolikelyscenarios:
Scenario1:(b1&b2)==(b3|b4)Ifthiswastheprogrammer’sintention,thenhejustcreateda
bug.
Scenario2:b1&(b2==b3)|b4Ifthiswastheprogrammer’sintention,thenthecodewillwork
asintended,buthisbossandfellowworkerswillwanttostranglehim.
Thisisalong-windedwaytosaythatwhenyou’rewritingcode,youshouldn’trelyoneveryone’s
memoryofoperatorprecedence.Youshouldjustuseparentheseslikecivilizedpeopledo.
TheActualBeginningoftheOperatorPrecedenceSection
Table4-2liststhemostcommonlyusedoperatorsandtheirrelativeprecedence,startingatthetopwith
thehighestprecedenceoperatorsandendingatthebottomwiththelowest.(Note,notallofJava’s
operatorsareinthistable!)
TABLE4-2 PrecedenceHierarchyofCommonOperators(fromHighesttoLowest)
JavaRanch(weknow,weknow,“Coderanch”)moderatorFritzWalravensharedthistipwithus.We
likeit,andwe’repassingitalongtoyou:forthetableabove,youmightmakeupawordlike
“UMARELSA,”orasentenceusingthosefirstletters,tohelpyouremembertheprecedencerules!
TherearethreeimportantgeneralrulesfordetermininghowJavawillevaluateexpressionswith
operators:
Whentwooperatorsofthesameprecedenceareinthesameexpression,Javaevaluatesthe
expressionfromlefttoright.
Whenpartsofanexpressionareplacedinparentheses,thosepartsareevaluatedfirst.
Whenparenthesesarenested,theinnermostparenthesesareevaluatedfirst.
Agoodwaytoburntheseprecedencerulesintoyourbrainisto—asalways—writesometestcode
andplayaroundwithit.We’veaddedanexampleofsometestcodethatdemonstratesseveralofthe
precedencehierarchyruleslistedhere.Asyoucansee,weoftencomparedparentheses-freeexpressions
withtheirparentheses-richcounterpartstoprovetherules:
Andtorepeat,theoutputis:
We’resosorrythatyouneedtomemorizethisstuff,butifyoumasterwhat’sinthisshortsection,you
shouldbeabletohandlewhateverweirdprecedence-relatedquestionstheexamthrowsatyou.
CERTIFICATIONSUMMARY
Ifyou’vestudiedthischapterdiligently,youshouldhaveafirmgrasponJavaoperators,andyoushould
understandwhatequalitymeanswhentestedwiththe==operator.Let’sreviewthehighlightsofwhat
you’velearnedinthischapter.
Thelogicaloperators(&&,||,&,|,and^)canbeusedonlytoevaluatetwobooleanexpressions.The
differencebetween&&and&isthatthe&&operatorwon’tbothertestingtherightoperandiftheleft
evaluatestofalse,becausetheresultofthe&&expressioncanneverbetrue.Thedifferencebetween||
and|isthatthe||operatorwon’tbothertestingtherightoperandiftheleftevaluatestotruebecausethe
resultisalreadyknowntobetrueatthatpoint.
The==operatorcanbeusedtocomparevaluesofprimitives,butitcanalsobeusedtodetermine
whethertworeferencevariablesrefertothesameobject.
Theinstanceofoperatorisusedtodeterminewhethertheobjectreferredtobyareferencevariable
passestheIS-Atestforaspecifiedtype.
The+operatorisoverloadedtoperformStringconcatenationtasksandcanalsoconcatenate
Stringsandprimitives,butbecareful—concatenationcanbetricky.
Theconditionaloperator(a.k.a.the“ternaryoperator”)hasanunusual,three-operandsyntax—don’t
mistakeitforacomplexassertstatement.
The++and--operatorswillbeusedthroughouttheexam,andyoumustpayattentiontowhetherthey
areprefixedorpostfixedtothevariablebeingupdated.
Eventhoughyoushoulduseparenthesesinreallife,fortheexamyoushouldmemorizeTable4-2so
youcandeterminehowcodethatdoesn’tuseparenthesesforcomplexexpressionswillbeevaluated,
basedonJava’soperator-precedencehierarchy.
Bepreparedforalotofexamquestionsinvolvingthetopicsfromthischapter.Evenwithinquestions
testingyourknowledgeofanotherobjective,thecodewillfrequentlyuseoperators,assignments,object
andprimitivepassing,andsoon.
TWO-MINUTEDRILL
Herearesomeofthekeypointsfromeachsectioninthischapter.
RelationalOperators(OCAObjectives3.1and3.2)
Relationaloperatorsalwaysresultinabooleanvalue(trueorfalse).
Therearesixrelationaloperators:>,>=,<,<=,==,and!=.Thelasttwo(==and!=)are
sometimesreferredtoasequalityoperators.
Whencomparingcharacters,JavausestheUnicodevalueofthecharacterasthenumerical
value.
Equalityoperators
Therearetwoequalityoperators:==and!=.
Fourtypesofthingscanbetested:numbers,characters,booleans,andreference
variables.
Whencomparingreferencevariables,==returnstrueonlyifbothreferencesrefertothe
sameobject.
instanceofOperator(OCAObjective3.1)
instanceofisforreferencevariablesonly;itcheckswhethertheobjectisofaparticular
type.
Theinstanceofoperatorcanbeusedonlytotestobjects(ornull)againstclasstypesthat
areinthesameclasshierarchy.
Forinterfaces,anobjectpassestheinstanceoftestifanyofitssuperclassesimplementthe
interfaceontherightsideoftheinstanceofoperator.
ArithmeticOperators(OCAObjective3.1)
Thefourprimarymathoperatorsareadd(+),subtract(–),multiply(*),anddivide(/).
Theremainder(a.k.a.modulus)operator(%)returnstheremainderofadivision.
Expressionsareevaluatedfromlefttoright,unlessyouaddparentheses,orunlesssome
operatorsintheexpressionhavehigherprecedencethanothers.
The*,/,and%operatorshavehigherprecedencethan+and–.
StringConcatenationOperator(OCAObjective3.1)
IfeitheroperandisaString,the+operatorconcatenatestheoperands.
Ifbothoperandsarenumeric,the+operatoraddstheoperands.
Increment/DecrementOperators(OCAObjective3.1)
Prefixoperators(e.g.--x)runbeforethevalueisusedintheexpression.
Postfixoperators(e.g.,x++)runafterthevalueisusedintheexpression.
Inanyexpression,bothoperandsarefullyevaluatedbeforetheoperatorisapplied.
Variablesmarkedfinalcannotbeincrementedordecremented.
Ternary(Conditional)Operator(OCAObjective3.3)
Returnsoneoftwovaluesbasedonthestateofitsbooleanexpression.
Returnsthevalueafterthe?iftheexpressionistrue.
Returnsthevalueafterthe:iftheexpressionisfalse.
LogicalOperators(OCAObjective3.1)
Theexamcoverssix“logical”operators:&,|,^,!,&&,and||.
Workwithtwoexpressions(exceptfor!)thatmustresolvetobooleanvalues.
The&&and&operatorsreturntrueonlyifbothoperandsaretrue.
The||and|operatorsreturntrueifeitherorbothoperandsaretrue.
The&&and||operatorsareknownasshort-circuitoperators.
The&&operatordoesnotevaluatetherightoperandiftheleftoperandisfalse.
The||doesnotevaluatetherightoperandiftheleftoperandistrue.
The&and|operatorsalwaysevaluatebothoperands.
The^operator(calledthe“logicalXOR”)returnstrueifexactlyoneoperandistrue.
The!operator(calledthe“inversion”operator)returnstheoppositevalueoftheboolean
operanditprecedes.
ParenthesesandOperatorPrecedence(OCAObjective3.1)
Inreallife,useparenthesestoclarifyyourcode,andforceJavatoevaluateexpressionsas
intended.
Fortheexam,memorizeTable4-2todeterminehowparentheses-freecodewillbeevaluated.
SELFTEST
1.Given:
Whatistheresult?
A.null
B.life
C.universe
D.everything
E.Compilationfails
F.Anexceptionisthrownatruntime
2.Given:
Whatistheresult?
A.truetruetrue
B.truetruefalse
C.falsetruefalse
D.falsetruetrue
E.falsefalsefalse
F.Anexceptionwillbethrownatruntime
3.Given:
Andthecommand-lineinvocation:
javaForklive2
Whatistheresult?
A.testcase
B.productionlive2
C.testcaselive2
D.Compilationfails
E.Anexceptionisthrownatruntime
4.Given:
Whatistheresult?
A.9foo4786foo
B.9foo474244foo
C.9foo42586foo
D.9foo4254244foo
E.72foo4786foo
F.72foo474244foo
G.72foo42586foo
H.72foo4254244foo
I.Compilationfails
5.Note:Here’sanotherold-styledrag-and-dropquestion…justincase.
Placethefragmentsintothecodetoproducetheoutput33.Notethatyoumustuseeachfragment
exactlyonce.
FRAGMENTS:
6.Given:
Whatistheresult?(Chooseallthatapply.)
A.21
B.22
C.31
D.32
E.Anexceptionisthrownatruntime
7.Given:
Whatistheresult?
A.sameold
B.newlynew
C.Compilationfailsduetomultipleerrors
D.Compilationfailsdueonlytoanerroronline7
E.Compilationfailsdueonlytoanerroronline8
F.Compilationfailsdueonlytoanerroronline11
G.Compilationfailsdueonlytoanerroronline13
8.Given:
Whicharetrue?(Chooseallthatapply.)
A.Compilationfails
B.xwillbeincludedintheoutput
C.ywillbeincludedintheoutput
D.zwillbeincludedintheoutput
E.Anexceptionisthrownatruntime
9.Given:
Whichtwoaretrueaboutthevalueofmaskandthevalueofcountatline10?(Choosetwo.)
A.maskis0
B.maskis1
C.maskis2
D.maskis10
E.maskisgreaterthan10
F.countis0
G.countisgreaterthan0
10.Given:
Whatistheresult?
A.0
B.01
C.02
D.012
E.Compilationfails
F.Anexceptionisthrownatruntime
11.Given:
Whatistheresult?(Thisisatrickyone.Ifyouwantahint,gotakeanotherlookattheoperator
precedencerantinthechapter.)
A.truetrue
B.falsetrue
C.truefalse
D.falsefalse
E.Compilationfails
F.Anexceptionisthrownatruntime
SELFTESTANSWERS
1. Discorrect.Thisisaternarynestedinaternary.Bothternaryexpressionsarefalse.
A,B,C,E,andFareincorrectbasedontheabove.(OCAObjective3.1and3.3)
2. Ciscorrect.The==operatortestsforreferencevariableequality,notobjectequality.
A,B,D,E,andFareincorrectbasedontheabove.(OCAObjectives3.1and3.2)
3. Eiscorrect.Becausetheshort-circuit(||)isnotused,bothoperandsareevaluated.Since
args[1]ispasttheargsarraybounds,anArrayIndexOutOfBoundsExceptionisthrown.
A,B,C,andDareincorrectbasedontheabove.(OCAObjectives3.1and3.2)
4. Giscorrect.Concatenationrunsfromlefttoright,andifeitheroperandisaString,the
operandsareconcatenated.Ifbothoperandsarenumbers,theyareaddedtogether.
A,B,C,D,E,F,H,andIareincorrectbasedontheabove.(OCAObjective3.1)
5.Answer:
Yeah,weknowit’skindofpuzzle-y,butyoumightencountersomethinglikeitontherealexam
ifOraclereinstatesthistypeofquestion.(OCAObjective3.1)
6. Aiscorrect.Whendividingints,remaindersarealwaysroundeddown.
B,C,D,andEareincorrectbasedontheabove.(OCAObjective3.1)
7. Aiscorrect.Allthissyntaxiscorrect.Thefor-eachiteratesthroughtheenumusingthe
values()methodtoreturnanarray.Anenumcanbecomparedusingeitherequals()or==.An
enumcanbeusedinaternaryoperator’sbooleantest.
B,C,D,E,F,andGareincorrectbasedontheabove.(OCAObjectives3.1,3.2,and3.3)
8. Ciscorrect.Line9usesthemodulusoperator,whichreturnstheremainderofthedivision,
whichinthiscaseis1.Also,line9setsb2tofalse,anditdoesn’ttestb2’svalue.Line10would
setb2totrue;however,theshort-circuitoperatorkeepstheexpressionb2=truefrombeing
executed.
A,B,D,andEareincorrectbasedontheabove.(OCAObjectives3.1,and3.2)
9. CandFarecorrect.Atline7the||keepscountfrombeingincremented,butthe|allows
masktobeincremented.Atline8the^returnstrueonlyifexactlyoneoperandistrue.Atline9
maskis2andthe&&keepscountfrombeingincremented.
A,B,D,E,andGareincorrectbasedontheabove.(OCAObjective3.1)
10. Discorrect.First,rememberthatinstanceofcanlookupthroughmultiplelevelsofan
inheritancetree.Alsorememberthatinstanceofiscommonlyusedbeforeattemptingadowncast;
sointhiscase,afterline15,itwouldbepossibletosaySpeedboats3=(Speedboat)b2;.
A,B,C,E,andFareincorrectbasedontheabove.(OCAObjective3.1)
11. Aiscorrect.We’reprettysureyouwon’tencounteranythingashorribleasthisonthereal
exam.Butifyougotthisonecorrect,patyourselfontheback!Thewaytotackleaproblemlikethis
istoevaluatetheexpressioninstages.Inthiscaseyoumightsolveitlikeso:
Stage1:resolveanyuseofunaryoperators
Stage2:resolveanyuseofmultiplication-relatedoperators
Stage3:handleadditionandsubtraction
Stage4:handleanyrelationshipoperators
Stage5:dealwiththeequalityoperators
Stage6:dealwiththelogicaloperators
Stage7:dotheshort-circuitoperators
Stage8:finally,dotheassignmentoperators
B,C,D,E,andFareincorrectbasedontheabove.(OCAObjective3.1)
C
5
FlowControlandExceptions
CERTIFICATIONOBJECTIVES
•UseifandswitchStatements
•Developfor,do,andwhileLoops
•UsebreakandcontinueStatements
•Usetry,catch,andfinallyStatements
•StatetheEffectsofExceptions
•RecognizeCommonExceptions
Two-MinuteDrill
Q&ASelfTest
anyouimaginetryingtowritecodeusingalanguagethatdidn’tgiveyouawaytoexecute
statementsconditionally?Flowcontrolisakeypartofmostanyusefulprogramming
language,andJavaoffersseveralwaystoaccomplishit.Somestatements,suchasif
statementsandforloops,arecommontomostlanguages.ButJavaalsothrowsinacoupleof
flowcontrolfeaturesyoumightnothaveusedbefore—exceptionsandassertions.(We’lldiscuss
assertionsinthenextchapter.)
Theifstatementandtheswitchstatementaretypesofconditional/decisioncontrolsthatallowyourprogramtobehave
differentlyata“forkintheroad,”dependingontheresultofalogicaltest.Javaalsoprovidesthreedifferentloopingconstructs
—for,while,anddo—soyoucanexecutethesamecodeoverandoveragaindependingonsomeconditionbeingtrue.
Exceptionsgiveyouaclean,simplewaytoorganizecodethatdealswithproblemsthatmightcropupatruntime.
Withthesetools,youcanbuildarobustprogramthatcanhandleanylogicalsituationwithgrace.Expecttoseeawiderange
ofquestionsontheexamthatincludeflowcontrolaspartofthequestioncode,evenonquestionsthataren’ttestingyour
knowledgeofflowcontrol.
CERTIFICATIONOBJECTIVE
UsingifandswitchStatements(OCAObjectives3.3and
3.4)
3.3Createifandif-elseandternaryconstructs.
3.5Useaswitchstatement.
Theifandswitchstatementsarecommonlyreferredtoasdecisionstatements.Whenyouuse
decisionstatementsinyourprogram,you’reaskingtheprogramtoevaluateagivenexpressionto
determinewhichcourseofactiontotake.We’lllookattheifstatementfirst.
if-elseBranching
Thebasicformatofanifstatementisasfollows:
Theexpressioninparenthesesmustevaluateto(aboolean)trueorfalse.Typically,you’retesting
somethingtoseeifit’strueandthenrunningacodeblock(oneormorestatements)ifitistrueand
(optionally)anotherblockofcodeifitisn’t.Thefollowingcodedemonstratesalegalif-elsestatement:
Theelseblockisoptional,soyoucanalsousethefollowing:
Theprecedingcodewillassign2toyifthetestsucceeds(meaningxreallyisgreaterthan3),butthe
othertwolineswillexecuteregardless.Eventhecurlybracesareoptionalifyouhaveonlyonestatement
toexecutewithinthebodyoftheconditionalblock.Thefollowingcodeexampleislegal(althoughnot
recommendedforreadability):
Mostdevelopersconsideritgoodpracticetoencloseblockswithincurlybraces,evenifthere’sonly
onestatementintheblock.Becarefulwithcodelikethepreceding,becauseyoumightthinkitshouldread
as
“Ifxisgreaterthan3,thensetyto2,ztoz+8,andatoy+x.”
Butthelasttwolinesaregoingtoexecutenomatterwhat!Theyaren’tpartoftheconditionalflow.You
mightfinditevenmoremisleadingifthecodewereindentedasfollows:
Youmighthaveaneedtonestif-elsestatements(although,again,it’snotrecommendedforreadability,
sonestediftestsshouldbekepttoaminimum).Youcansetupanif-elsestatementtotestformultiple
conditions.Thefollowingexampleusestwoconditions,soifthefirsttestfails,wewanttoperforma
secondtestbeforedecidingwhattodo:
Thisbringsuptheotherif-elseconstruct,theif,elseif,else.Theprecedingcodecould(and
should)berewrittenlikethis:
Thereareacoupleofrulesforusingelseandelseif:
Youcanhavezerooroneelseforagivenif,anditmustcomeafteranyelseifs.
Youcanhavezerotomanyelseifsforagivenif,andtheymustcomebeforethe(optional)
else.
Onceanelseifsucceeds,noneoftheremainingelseifsnortheelsewillbetested.
Thefollowingexampleshowscodethatishorriblyformattedfortherealworld.Asyou’veprobably
guessed,it’sfairlylikelythatyou’llencounterformattinglikethisontheexam.Inanycase,thecode
demonstratestheuseofmultipleelseifs:
Itproducesthisoutput:
<4
(Noticethateventhoughthesecondelseifistrue,itisneverreached.)
Sometimesyoucanhaveaproblemfiguringoutwhichifyourelseshouldpairwith,asfollows:
Weintentionallyleftouttheindentinginthispieceofcodesoitdoesn’tgivecluesastowhichif
statementtheelsebelongsto.Didyoufigureitout?Javalawdecreesthatanelseclausebelongstothe
innermostifstatementtowhichitmightpossiblybelong(inotherwords,theclosestprecedingifthat
doesn’thaveanelse).Inthecaseoftheprecedingexample,theelsebelongstothesecondifstatement
inthelisting.Withproperindenting,itwouldlooklikethis:
Followingourcodingconventionsbyusingcurlybraces,itwouldbeeveneasier
toread:
Don’tgetyourhopesupabouttheexamquestionsbeingallniceandindentedproperly.Someexamtakers
evenhaveasloganforthewayquestionsarepresentedontheexam:Anythingthatcanbemademore
confusingwillbe.
Bepreparedforquestionsthatnotonlyfailtoindentnicelybutalsointentionallyindentinamisleading
way.Paycloseattentionformisdirectionlikethefollowing:
Ofcourse,theprecedingcodeisexactlythesameastheprevioustwoexamples,exceptforthewayit
looks.
LegalExpressionsforifStatements
Theexpressioninanifstatementmustbeabooleanexpression.Anyexpressionthatresolvestoa
booleanisfine,andsomeoftheexpressionscanbecomplex.AssumedoStuff()returnstrue,
whichprints
true
Youcanreadtheprecedingcodeas,“Ifboth(x>3)and(y<2)aretrue,oriftheresultofdoStuff()
istrue,thenprinttrue.”So,basically,ifjustdoStuff()aloneistrue,we’llstillgettrue.If
doStuff()isfalse,though,thenboth(x>3)and(y<2)willhavetobetrueinordertoprinttrue.
Theprecedingcodeisevenmorecomplexifyouleaveoffonesetofparenthesesasfollows:
Thisnowprints…nothing!Becausetheprecedingcode(withonelesssetofparentheses)evaluatesas
thoughyouweresaying,“If(x>3)istrue,andeither(y<2)ortheresultofdoStuff()istrue,then
printtrue.Soif(x>3)isnottrue,nopointinlookingattherestoftheexpression.”Becauseofthe
short-circuit&&,theexpressionisevaluatedasthoughtherewereparenthesesaround(y<2)|
doStuff().Inotherwords,itisevaluatedasasingleexpressionbeforethe&&andasingleexpression
afterthe&&.
Rememberthattheonlylegalexpressioninaniftestisaboolean.Insomelanguages,0==falseand
1==true.NotsoinJava!Thefollowingcodeshowsifstatementsthatmightlooktemptingbutare
illegal,followedbylegalsubstitutions:
Onecommonmistakeprogrammersmake(andthatcanbedifficulttospot)isassigninga
booleanvariablewhenyoumeanttotestabooleanvariable.Lookoutforcodelikethe
following:
Youmightthinkoneofthreethings:
1.Thecodecompilesandrunsfine,andtheiftestfailsbecausebooisfalse.
2.Thecodewon’tcompilebecauseyou’reusinganassignment(=)ratherthanan
equalitytest(==).
3.Thecodecompilesandrunsfine,andtheiftestsucceedsbecausebooisSETto
true(ratherthanTESTEDfortrue)intheifargument!
Well,number3iscorrect–pointless,butcorrect.Giventhattheresultofanyassignmentisthe
valueofthevariableaftertheassignment,theexpression(boo=true)hasaresultoftrue.
Hence,theiftestsucceeds.Buttheonlyvariablesthatcanbeassigned(ratherthantested
againstsomethingelse)areabooleanoraBoolean;allotherassignmentswillresultin
somethingnon-boolean,sothey’renotlegal,asinthefollowing:
Becauseiftestsrequirebooleanexpressions,youneedtobereallysolidonbothlogical
operatorsandiftestsyntaxandsemantics.
switchStatements
You’veseenhowifandelse-ifstatementscanbeusedtosupportbothsimpleandcomplexdecision
logic.Inmanycases,theswitchstatementprovidesacleanerwaytohandlecomplexdecisionlogic.
Let’scomparethefollowingif-elseifstatementtotheequivalentlyperformingswitchstatement:
Nowlet’sseethesamefunctionalityrepresentedinaswitchconstruct:
Note:Thereasonthisswitchstatementemulatestheifisbecauseofthebreakstatementsthatwere
placedinsideoftheswitch.Ingeneral,breakstatementsareoptional,andasyouwillseeinafew
pages,theirinclusionorexclusioncauseshugechangesinhowaswitchstatementwillexecute.
LegalExpressionsforswitchandcase
Thegeneralformoftheswitchstatementis
Aswitch’sexpressionmustevaluatetoachar,byte,short,int,anenum(asofJava5),anda
String(asofJava7).Thatmeansifyou’renotusinganenumoraString,onlyvariablesandvalues
thatcanbeautomaticallypromoted(inotherwords,implicitlycast)toanintareacceptable.Youwon’t
beabletocompileifyouuseanythingelse,includingtheremainingnumerictypesoflong,float,and
double.
Acaseconstantmustevaluatetothesametypethattheswitchexpressioncanuse,withoneadditional
—andbig—constraint:thecaseconstantmustbeacompile-timeconstant!Sincethecaseargumenthasto
beresolvedatcompiletime,youcanuseonlyaconstantorfinalvariablethatisimmediatelyinitialized
withaliteralvalue.Itisnotenoughtobefinal;itmustbeacompile-timeconstant.Here’sanexample:
Also,theswitchcanonlycheckforequality.Thismeanstheotherrelationaloperatorssuchasgreater
thanarerenderedunusableinacase.Thefollowingisanexampleofavalidexpressionusingamethod
invocationinaswitchstatement.Notethatforthiscodetobelegal,themethodbeinginvokedonthe
objectreferencemustreturnavaluecompatiblewithanint.
Oneotherruleyoumightnotexpectinvolvesthequestion,“WhathappensifIswitchonavariable
smallerthananint?”Lookatthefollowingswitch:
Thiscodewon’tcompile.Althoughtheswitchargumentislegal—abyteisimplicitlycasttoanint—
thesecondcaseargument(128)istoolargeforabyte,andthecompilerknowsit!Attemptingtocompile
theprecedingexamplegivesyouanerrorsomethinglikethis:
It’salsoillegaltohavemorethanonecaselabelusingthesamevalue.Forexample,thefollowing
blockofcodewon’tcompilebecauseitusestwocaseswiththesamevalueof80:
Itislegaltoleveragethepowerofboxinginaswitchexpression.Forinstance,thefollowingislegal:
Lookforanyviolationoftherulesforswitchandcasearguments.Forexample,youmight
findillegalexampleslikethefollowingsnippets:
Inthefirstexample,thecaseomitsthecolon.Thesecondexampleomitsthekeywordcase.
AnIntrotoString“equality”
Aswe’vebeendiscussing,theoperationofswitchstatementsdependsontheexpression“matching”or
being“equal”tooneofthecases.We’vetalkedabouthowweknowwhenprimitivesareequal,butwhat
doesitmeanforobjectstobeequal?Thisisanotheroneofthosesurprisinglytrickytopics,andforthose
ofyouwhointendtotaketheOCPexam,you’llspendalotoftimestudying“objectequality.”Foryou
OCAcandidates,allyouhavetoknowisthatforaswitchstatement,twoStringswillbeconsidered
“equal”iftheyhavethesamecase-sensitivesequenceofcharacters.Forexample,inthefollowingpartial
switchstatement,theexpressionwouldmatchthecase:
ButthefollowingwouldNOTmatch:
BreakandFall-ThroughinswitchBlocks
We’refinallyreadytodiscussthebreakstatementandoffermoredetailsaboutflowcontrolwithina
switchstatement.Themostimportantthingtorememberabouttheflowofexecutionthroughaswitch
statementisthis:
caseconstantsareevaluatedfromthetopdown,andthefirstcaseconstantthatmatchestheswitch’sexpressionistheexecution
entrypoint.
Inotherwords,onceacaseconstantismatched,theJavaVirtualMachine(JVM)willexecutethe
associatedcodeblockandALLsubsequentcodeblocks(barringabreakstatement),too!Thefollowing
exampleusesaStringinacasestatement:
Inthisexamplecase“green”:matched,sotheJVMexecutedthatcodeblockandallsubsequentcode
blockstoproducetheoutput:
greenbluedone
Again,whentheprogramencountersthekeywordbreakduringtheexecutionofaswitchstatement,
executionwillimmediatelymoveoutoftheswitchblocktothenextstatementaftertheswitch.Ifbreak
isomitted,theprogramjustkeepsexecutingtheremainingcaseblocksuntileitherabreakisfoundorthe
switchstatementends.Examinethefollowingcode:
Thecodewillprintthefollowing:
Thiscombinationoccursbecausethecodedidn’thitabreakstatement;executionjustkeptdropping
downthrougheachcaseuntiltheend.Thisdroppingdownisactuallycalled“fall-through,”becauseof
thewayexecutionfallsfromonecasetothenext.Remember,thematchingcaseissimplyyourentry
pointintotheswitchblock!Inotherwords,youmustnotthinkofitas,“Findthematchingcase,execute
justthatcode,andgetout.”That’snothowitworks.Ifyoudowantthat“justthematchingcode”
behavior,you’llinsertabreakintoeachcaseasfollows:
Runningtheprecedingcode,nowthatwe’veaddedthebreakstatements,prints:
Andthat’sit.Weenteredintotheswitchblockatcase1.Becauseitmatchedtheswitch()argument,
wegottheprintlnstatementandthenhitthebreakandjumpedtotheendoftheswitch.
Aninterestingexampleofthisfall-throughlogicisshowninthefollowingcode:
Thisswitchstatementwillprintxisanevennumberornothing,dependingonwhetherthenumberis
betweenoneandtenandisoddoreven.Forexample,ifxis4,executionwillbeginatcase4,butthen
falldownthrough6,8,and10,whereitprintsandthenbreaks.Thebreakatcase10,bytheway,isnot
needed;we’realreadyattheendoftheswitchanyway.
Note:Becausefall-throughislessthanintuitive,Oraclerecommendsthatyouaddacommentsuchas
//fallthroughwhenyouusefall-throughlogic.
TheDefaultCase
Whatif,usingtheprecedingcode,youwantedtoprintxisanoddnumberifnoneofthecases(the
evennumbers)matched?Youcouldn’tputitaftertheswitchstatement,orevenasthelastcaseinthe
switch,becauseinbothofthosesituationsitwouldalwaysprintxisanoddnumber.Togetthis
behavior,you’dusethedefaultkeyword.(Bytheway,ifyou’vewonderedwhythereisadefault
keywordeventhoughwedon’tuseamodifierfordefaultaccesscontrol,nowyou’llseethatthedefault
keywordisusedforacompletelydifferentpurpose.)Theonlychangeweneedtomakeistoaddthe
defaultcasetotheprecedingcode:
Thedefaultcasedoesn’thavetocomeattheendoftheswitch.Lookforitinstrangeplaces
suchasthefollowing:
Runningtheprecedingcodeprintsthis:
Andifwemodifyitsotheonlymatchisthedefaultcase,likethis,
thenrunningtheprecedingcodeprintsthis:
Theruletorememberisthatdefaultworksjustlikeanyothercaseforfall-through!
EXERCISE5-1
Creatingaswitch-caseStatement
Trycreatingaswitchstatementusingacharvalueasthecase.Includeadefaultbehaviorifnoneofthe
charvaluesmatch.
Makesureacharvariableisdeclaredbeforetheswitchstatement.
Eachcasestatementshouldbefollowedbyabreak.
Thedefaultcasecanbelocatedattheend,middle,ortop.
CERTIFICATIONOBJECTIVE
CreatingLoopsConstructs(OCAObjectives5.1,5.2,5.3,
5.4,and5.5)
5.1Createandusewhileloops.
5.2Createanduseforloopsincludingtheenhancedforloop.
5.3Createandusedo/whileloops.
5.4Compareloopconstructs.
5.5Usebreakandcontinue.
Javaloopscomeinthreeflavors:while,do,andfor(andasofJava5,theforloophastwo
variations).Allthreeletyourepeatablockofcodeaslongassomeconditionistrueorforaspecific
numberofiterations.You’reprobablyfamiliarwithloopsfromotherlanguages,soevenifyou’re
somewhatnewtoJava,thesewon’tbeaproblemtolearn.
UsingwhileLoops
Thewhileloopisgoodwhenyoudon’tknowhowmanytimesablockorstatementshouldrepeatbutyou
wanttocontinueloopingaslongassomeconditionistrue.Awhilestatementlookslikethis:
Orthis:
Inthiscase,asinallloops,theexpression(test)mustevaluatetoabooleanresult.Thebodyofthe
whileloopwillexecuteonlyiftheexpression(sometimescalledthe“condition”)resultsinavalueof
true.Onceinsidetheloop,theloopbodywillrepeatuntiltheconditionisnolongermetbecauseit
evaluatestofalse.Inthepreviousexample,programcontrolwillentertheloopbodybecausexisequal
to2.However,xisincrementedintheloop,sowhentheconditionischeckedagainitwillevaluateto
falseandexittheloop.
Anyvariablesusedintheexpressionofawhileloopmustbedeclaredbeforetheexpressionis
evaluated.Inotherwords,youcan’tsaythis:
while(intx=2){}//notlegal
Thenagain,whywouldyou?Insteadoftestingthevariable,you’dbedeclaringandinitializingit,soit
wouldalwayshavetheexactsamevalue.Notmuchofatestcondition!
Thekeypointtorememberaboutawhileloopisthatitmightnoteverrun.Ifthetestexpressionis
falsethefirsttimethewhileexpressionischecked,theloopbodywillbeskippedandtheprogramwill
beginexecutingatthefirststatementafterthewhileloop.Lookatthefollowingexample:
Runningthiscodeproduces
pasttheloop
Becausetheexpression(x>8)evaluatestofalse,noneofthecodewithinthewhileloopever
executes.
UsingdoLoops
Thedoloopissimilartothewhileloop,excepttheexpressionisnotevaluateduntilafterthedoloop’s
codeisexecuted.Therefore,thecodeinadoloopisguaranteedtoexecuteatleastonce.Thefollowing
showsadoloopinaction:
TheSystem.out.println()statementwillprintonce,eventhoughtheexpressionevaluatestofalse.
Remember,thedoloopwillalwaysrunthecodeintheloopbodyatleastonce.Besuretonotetheuseof
thesemicolonattheendofthewhileexpression.
Aswithiftests,lookforwhileloops(andthewhiletestinadoloop)withanexpressionthat
doesnotresolvetoaboolean.Takealookatthefollowingexamplesoflegalandillegalwhile
expressions:
UsingforLoops
AsofJava5,theforlooptookonasecondstructure.We’llcalltheoldstyleofforloopthe“basicfor
loop,”andwe’llcallthenewstyleofforloopthe“enhancedforloop”(it’salsosometimescalledthe
for-each).Dependingonwhatdocumentationyouuse,you’llseebothterms,alongwithfor-in.The
termsfor-in,for-each,and“enhancedfor”allrefertothesameJavaconstruct.
Thebasicforloopismoreflexiblethantheenhancedforloop,buttheenhancedforloopwas
designedtomakeiteratingthrougharraysandcollectionseasiertocode.
TheBasicforLoop
Theforloopisespeciallyusefulforflowcontrolwhenyoualreadyknowhowmanytimesyouneedto
executethestatementsintheloop’sblock.Theforloopdeclarationhasthreemainpartsbesidesthebody
oftheloop:
Declarationandinitializationofvariables
Thebooleanexpression(conditionaltest)
Theiterationexpression
Thethreefordeclarationpartsareseparatedbysemicolons.Thefollowingtwoexamplesdemonstrate
theforloop.Thefirstexampleshowsthepartsofaforloopinapseudocodeform,andthesecond
showsatypicalexampleofaforloop:
TheBasicforLoop:DeclarationandInitialization
Thefirstpartoftheforstatementletsyoudeclareandinitializezero,one,ormultiplevariablesofthe
sametypeinsidetheparenthesesaftertheforkeyword.Ifyoudeclaremorethanonevariableofthesame
type,you’llneedtoseparatethemwithcommasasfollows:
for(intx=10,y=3;y>3;y++){}
Thedeclarationandinitializationhappenbeforeanythingelseinaforloop.Andwhereastheothertwo
parts—thebooleantestandtheiterationexpression—willrunwitheachiterationoftheloop,the
declarationandinitializationhappenjustonce,attheverybeginning.Youalsomustknowthatthescope
ofvariablesdeclaredintheforloopendswiththeforloop!Thefollowingdemonstratesthis:
Ifyoutrytocompilethis,you’llgetsomethinglikethis:
BasicforLoop:Conditional(boolean)Expression
Thenextsectionthatexecutesistheconditionalexpression,which(likeallotherconditionaltests)must
evaluatetoabooleanvalue.Youcanhaveonlyonelogicalexpression,butitcanbeverycomplex.Look
outforcodethatuseslogicalexpressionslikethis:
for(intx=0;((((x<10)&&(y-->2))|x==3));x++){}
Theprecedingcodeislegal,butthefollowingisnot:
Thecompilerwillletyouknowtheproblem:
Theruletorememberisthis:Youcanhaveonlyonetestexpression.
Inotherwords,youcan’tusemultipletestsseparatedbycommas,eventhough,theothertwopartsofa
forstatementcanhavemultipleparts.
BasicforLoop:IterationExpression
Aftereachexecutionofthebodyoftheforloop,theiterationexpressionisexecuted.Thisiswhereyou
gettosaywhatyouwanttohappenwitheachiterationoftheloop.Rememberthatitalwayshappensafter
theloopbodyruns!Lookatthefollowing:
Thisloopexecutesjustonce.Thefirsttimeintotheloop,xissetto0,thenxistestedtoseeifit’sless
than1(whichitis),andthenthebodyoftheloopexecutes.Afterthebodyoftheloopruns,theiteration
expressionruns,incrementingxby1.Next,theconditionaltestischecked,andsincetheresultisnow
false,executionjumpstobelowtheforloopandcontinues.
Keepinmindthatbarringaforcedexit,evaluatingtheiterationexpressionandthenevaluating
theconditionalexpressionarealwaysthelasttwothingsthathappeninaforloop!
Examplesofforcedexitsincludeabreak,areturn,aSystem.exit(),andanexception,whichwill
allcausealooptoterminateabruptly,withoutrunningtheiterationexpression.Lookatthefollowing
code:
Runningthiscodeproduces
inforloop
Thestatementprintsonlyoncebecauseareturncausesexecutiontoleavenotjustthecurrentiteration
ofaloop,buttheentiremethod.Sotheiterationexpressionneverrunsinthatcase.Table5-1liststhe
causesandresultsofabruptlooptermination.
TABLE5-1 CausesofEarlyLoopTermination
BasicforLoop:forLoopIssues
Noneofthethreesectionsofthefordeclarationarerequired!Thefollowingexampleisperfectlylegal
(althoughnotnecessarilygoodpractice):
Inthisexample,allthedeclarationpartsareleftout,sotheforloopwillactlikeanendlessloop.
Fortheexam,it’simportanttoknowthatwiththeabsenceoftheinitializationandincrementsections,
theloopwillactlikeawhileloop.Thefollowingexampledemonstrateshowthisisaccomplished:
Thenextexampledemonstratesaforloopwithmultiplevariablesinplay.Acommaseparatesthe
variables,andtheymustbeofthesametype.Rememberthatthevariablesdeclaredintheforstatement
arealllocaltotheforloopandcan’tbeusedoutsidethescopeoftheloop.
Variablescopeplaysalargeroleintheexam.Youneedtoknowthatavariabledeclaredinthe
forloopcan’tbeusedbeyondtheforloop.Butavariableonlyinitializedintheforstatement
(butdeclaredearlier)canbeusedbeyondtheloop.Forexample,thefollowingislegal:
Butthisisnot:
for(intx=3;x<20;x++){}System.out.println(x);
Thelastthingtonoteisthatallthreesectionsoftheforloopareindependentofeachother.Thethree
expressionsintheforstatementdon’tneedtooperateonthesamevariables,althoughtheytypicallydo.
Buteventheiteratorexpression,whichmanymistakenlycallthe“incrementexpression,”doesn’tneedto
incrementorsetanything;youcanputinvirtuallyanyarbitrarycodestatementsthatyouwanttohappen
witheachiterationoftheloop.Lookatthefollowing:
Theprecedingcodeprints
iterate
iterate
ManyquestionsintheJava8examslist"Compilationfails"and"Anexceptionoccursat
runtime"aspossibleanswers,makingthemmoredifficultbecauseyoucan’tsimplywork
throughthebehaviorofthecode.Youmustfirstmakesurethecodeisn’tviolatingany
fundamentalrulesthatwillleadtoacompilererrorandthenlookforpossibleexceptions.
Onlyafteryou’vesatisfiedthosetwoshouldyoudigintothelogicandflowofthecodeinthe
question.
TheEnhancedforLoop(forArrays)
Theenhancedforloop,newasofJava5,isaspecializedforloopthatsimplifiesloopingthroughan
arrayoracollection.Inthischapterwe’regoingtofocusonusingtheenhancedfortoloopthrough
arrays.InChapter6we’llrevisittheenhancedfor,whenwediscusstheArrayListcollectionclass—
wheretheenhancedforreallycomesintoitsown.
Insteadofhavingthreecomponents,theenhancedforhastwo.Let’sloopthroughanarraythebasic
(old)wayandthenusingtheenhancedfor:
Thisproducesthefollowingoutput:
12341234
Moreformally,let’sdescribetheenhancedforasfollows:
for(declaration:expression)
Thetwopiecesoftheforstatementare
declarationThenewlydeclaredblockvariableofatypecompatiblewiththeelementsof
thearrayyouareaccessing.Thisvariablewillbeavailablewithintheforblock,anditsvalue
willbethesameasthecurrentarrayelement.
expressionThismustevaluatetothearrayyouwanttoloopthrough.Thiscouldbeanarray
variableoramethodcallthatreturnsanarray.Thearraycanbeanytype:primitives,objects,or
evenarraysofarrays.
Usingtheprecedingdefinitions,let’slookatsomelegalandillegalenhancedfordeclarations:
Theenhancedforloopassumesthat,barringanearlyexitfromtheloop,you’llalwaysloopthrough
everyelementofthearray.Thefollowingdiscussionsofbreakandcontinueapplytoboththebasicand
enhancedforloops.
Usingbreakandcontinue
Thebreakandcontinuekeywordsareusedtostopeithertheentireloop(break)orjustthecurrent
iteration(continue).Typically,ifyou’reusingbreakorcontinue,you’lldoaniftestwithintheloop,
andifsomeconditionbecomestrue(orfalsedependingontheprogram),youwanttogetout
immediately.Thedifferencebetweenthemiswhetherornotyoucontinuewithanewiterationorjumpto
thefirststatementbelowtheloopandcontinuefromthere.
Remember,continuestatementsmustbeinsidealoop;otherwise,you’llgetacompilererror.
breakstatementsmustbeusedinsideeitheralooporaswitchstatement.
Thebreakstatementcausestheprogramtostopexecutionoftheinnermostloopandstartprocessing
thenextlineofcodeaftertheblock.
Thecontinuestatementcausesonlythecurrentiterationoftheinnermostlooptoceaseandthenext
iterationofthesamelooptostartiftheconditionoftheloopismet.Whenusingacontinuestatement
withaforloop,youneedtoconsidertheeffectsthatcontinuehasontheloopiteration.Examinethe
followingcode:
Thequestionis,isthisanendlessloop?Theanswerisno.Whenthecontinuestatementishit,the
iterationexpressionstillruns!Itrunsjustasthoughthecurrentiterationended“inthenaturalway.”Soin
theprecedingexample,iwillstillincrementbeforethecondition(i<10)ischeckedagain.
Mostofthetime,acontinueisusedwithinaniftestasfollows:
UnlabeledStatements
Boththebreakstatementandthecontinuestatementcanbeunlabeledorlabeled.Althoughit’sfarmore
commontousebreakandcontinueunlabeled,theexamexpectsyoutoknowhowlabeledbreakand
continuestatementswork.Asstatedbefore,abreakstatement(unlabeled)willexitoutoftheinnermost
loopingconstructandproceedwiththenextlineofcodebeyondtheloopblock.Thefollowingexample
demonstratesabreakstatement:
Inthepreviousexample,thebreakstatementisunlabeled.Thefollowingisanexampleofan
unlabeledcontinuestatement:
Inthisexample,afileisbeingreadonefieldatatime.Whenanerrorisencountered,theprogram
movestothenextfieldinthefileandusesthecontinuestatementtogobackintotheloop(ifitisnotat
theendofthefile)andkeepsreadingthevariousfields.Ifthebreakcommandwereusedinstead,the
codewouldstopreadingthefileoncetheerroroccurredandmoveontothenextlineofcodeafterthe
loop.Thecontinuestatementgivesyouawaytosay,“Thisparticulariterationoftheloopneedstostop,
butnotthewholeloopitself.Ijustdon’twanttherestofthecodeinthisiterationtofinish,sodothe
iterationexpressionandthenstartoverwiththetest,anddon’tworryaboutwhatwasbelowthe
continuestatement.”
LabeledStatements
AlthoughmanystatementsinaJavaprogramcanbelabeled,it’smostcommontouselabelswithloop
statementslikefororwhile,inconjunctionwithbreakandcontinuestatements.Alabelstatementmust
beplacedjustbeforethestatementbeinglabeled,anditconsistsofavalididentifierthatendswitha
colon(:).
Youneedtounderstandthedifferencebetweenlabeledandunlabeledbreakandcontinue.The
labeledvarietiesareneededonlyinsituationswhereyouhaveanestedloop,andtheyneedtoindicate
whichofthenestedloopsyouwanttobreakfrom,orfromwhichofthenestedloopsyouwanttocontinue
withthenextiteration.Abreakstatementwillexitoutofthelabeledloop,asopposedtotheinnermost
loop,ifthebreakkeywordiscombinedwithalabel.
Here’sanexampleofwhatalabellookslike:
ThelabelmustadheretotherulesforavalidvariablenameandshouldadheretotheJavanaming
convention.Thesyntaxfortheuseofalabelnameinconjunctionwithabreakstatementisthebreak
keyword,thenthelabelname,followedbyasemicolon.Amorecompleteexampleoftheuseofalabeled
breakstatementisasfollows:
Runningthiscodeproduces
Hello
Good-Bye
Inthisexample,thewordHellowillbeprintedonetime.Then,thelabeledbreakstatementwillbe
executed,andtheflowwillexitoutofthelooplabeledouter.ThenextlineofcodewillthenprintGood-
Bye.
Let’sseewhatwillhappenifthecontinuestatementisusedinsteadofthebreakstatement.The
followingcodeexampleissimilartotheprecedingone,withtheexceptionofsubstitutingcontinuefor
break:
Runningthiscodeproduces
Hello
Hello
Hello
Hello
Hello
Good-Bye
Inthisexample,Hellowillbeprintedfivetimes.Afterthecontinuestatementisexecuted,theflow
continueswiththenextiterationoftheloopidentifiedwiththelabel.Finally,whentheconditioninthe
outerloopevaluatestofalse,thisloopwillfinishandGood-Byewillbeprinted.
EXERCISE5-2
CreatingaLabeledwhileLoop
Trycreatingalabeledwhileloop.Makethelabelouterandprovideaconditiontocheckwhethera
variableageislessthanorequalto21.Withintheloop,incrementageby1.Everytimetheprogramgoes
throughtheloop,checkwhetherageis16.Ifitis,printthemessage“getyourdriver’slicense”and
continuetotheouterloop.Ifnot,print“Anotheryear.”
Theouterlabelshouldappearjustbeforethewhileloopbegins.
Makesureageisdeclaredoutsideofthewhileloop.
Labeledcontinueandbreakstatementsmustbeinsidetheloopthathasthesamelabelname;
otherwise,thecodewillnotcompile.
CERTIFICATIONOBJECTIVE
HandlingExceptions(OCAObjectives8.1,8.2,8.3,8.4,and
8.5)
8.1Differentiateamongcheckedexceptions,uncheckedexceptions,anderrors.
8.2Createatry-catchblockanddeterminehowexceptionsalternormalprogramflow.
8.3DescribetheadvantagesofExceptionhandling.
8.4Createandinvokeamethodthatthrowsanexception.
8.5Recognizecommonexceptionclasses(suchasNullPointerException,ArithmeticException,
ArrayIndexOutOfBoundsException,ClassCastException)(sic)
Anoldmaximinsoftwaredevelopmentsaysthat80percentoftheworkisused20percentofthetime.
The80percentreferstotheeffortrequiredtocheckandhandleerrors.Inmanylanguages,writing
programcodethatchecksforanddealswitherrorsistediousandbloatstheapplicationsourceinto
confusingspaghetti.Still,errordetectionandhandlingmaybethemostimportantingredientofanyrobust
application.HerearesomeofthebenefitsofJava’sexception-handlingfeatures:
Itarmsdeveloperswithanelegantmechanismforhandlingerrorsthatproducesefficientand
organizederror-handlingcode.
Itallowsdeveloperstodetecterrorseasilywithoutwritingspecialcodetotestreturnvalues.
Itletsuskeepexception-handlingcodecleanlyseparatedfromexception-generatingcode.
Italsoletsususethesameexception-handlingcodetodealwitharangeofpossible
exceptions.
Java7addedseveralnewexception-handlingcapabilitiestothelanguage.Forourpurposes,Oracle
splitthevariousexception-handlingtopicsintotwomainparts:
1.TheOCAexamcoverstheJava6versionofexceptionhandling.
2.TheOCPexamaddsthenewexceptionfeaturesaddedinJava7.
InordertomirrorOracle’sOCA8objectivesversustheOCP8objectives,thischapterwillgiveyou
onlythebasicsofexceptionhandling—butplentytohandletheOCA8exam.
CatchinganExceptionUsingtryandcatch
Beforewebegin,let’sintroducesometerminology.Thetermexceptionmeans“exceptionalcondition”
andisanoccurrencethataltersthenormalprogramflow.Abunchofthingscanleadtoexceptions,
includinghardwarefailures,resourceexhaustion,andgoodoldbugs.Whenanexceptionaleventoccursin
Java,anexceptionissaidtobe“thrown.”Thecodethat’sresponsiblefordoingsomethingaboutthe
exceptioniscalledan“exceptionhandler,”andit“catches”thethrownexception.
Exceptionhandlingworksbytransferringtheexecutionofaprogramtoanappropriateexception
handlerwhenanexceptionoccurs.Forexample,ifyoucallamethodthatopensafilebutthefilecannot
beopened,executionofthatmethodwillstop,andcodethatyouwrotetodealwiththissituationwillbe
run.Therefore,weneedawaytotelltheJVMwhatcodetoexecutewhenacertainexceptionhappens.To
dothis,weusethetryandcatchkeywords.Thetryisusedtodefineablockofcodeinwhich
exceptionsmayoccur.Thisblockofcodeiscalleda“guardedregion”(whichreallymeans“riskycode
goeshere”).Oneormorecatchclausesmatchaspecificexception(orgroupofexceptions—moreon
thatlater)toablockofcodethathandlesit.Here’showitlooksinpseudocode:
Inthispseudocodeexample,lines2through5constitutetheguardedregionthatisgovernedbythetry
clause.Line7isanexceptionhandlerforanexceptionoftypeMyFirstException.Line12isan
exceptionhandlerforanexceptionoftypeMySecondException.Noticethatthecatchblocks
immediatelyfollowthetryblock.Thisisarequirement;ifyouhaveoneormorecatchblocks,theymust
immediatelyfollowthetryblock.Additionally,thecatchblocksmustallfolloweachother,withoutany
otherstatementsorblocksinbetween.Also,theorderinwhichthecatchblocksappearmatters,aswe’ll
seealittlelater.
Executionoftheguardedregionstartsatline2.Iftheprogramexecutesallthewaypastline5withno
exceptionsbeingthrown,executionwilltransfertoline15andcontinuedownward.However,ifatany
timeinlines2through5(thetryblock)anexceptionoftypeMyFirstExceptionisthrown,execution
willimmediatelytransfertoline7.Lines8through10willthenbeexecutedsothattheentirecatch
blockruns,andthenexecutionwilltransfertoline15andcontinue.
Notethatifanexceptionoccurredon,say,line3ofthetryblock,theremaininglinesinthetryblock
(4and5)wouldneverbeexecuted.Oncecontroljumpstothecatchblock,itneverreturnstocomplete
thebalanceofthetryblock.Thisisexactlywhatyouwant,though.Imaginethatyourcodelooks
somethinglikethispseudocode:
Thispseudocodedemonstrateshowyoutypicallyworkwithexceptions.Codethat’sdependentonarisky
operation(aspopulatingatablewithfiledataisdependentongettingthefilefromthenetwork)is
groupedintoatryblockinsuchawaythatif,say,thefirstoperationfails,youwon’tcontinuetryingto
runothercodethat’salsoguaranteedtofail.Inthepseudocodeexample,youwon’tbeabletoreadfrom
thefileifyoucan’tgetthefileoffthenetworkinthefirstplace.
Oneofthebenefitsofusingexceptionhandlingisthatcodetohandleanyparticularexception
thatmayoccurinthegovernedregionneedstobewrittenonlyonce.Returningtoourearliercode
example,theremaybethreedifferentplacesinourtryblockthatcangenerateaMyFirstException,but
whereveritoccursitwillbehandledbythesamecatchblock(online7).We’lldiscussmorebenefitsof
exceptionhandlingneartheendofthischapter.
Usingfinally
Althoughtryandcatchprovideaterrificmechanismfortrappingandhandlingexceptions,weareleft
withtheproblemofhowtocleanupafterourselvesifanexceptionoccurs.Becauseexecutiontransfers
outofthetryblockassoonasanexceptionisthrown,wecan’tputourcleanupcodeatthebottomofthe
tryblockandexpectittobeexecutedifanexceptionoccurs.Almostasbadanideawouldbeplacing
ourcleanupcodeineachofthecatchblocks—let’sseewhy.
Exceptionhandlersareapoorplacetocleanupafterthecodeinthetryblockbecauseeachhandler
thenrequiresitsowncopyofthecleanupcode.If,forexample,youallocatedanetworksocketoropened
afilesomewhereintheguardedregion,eachexceptionhandlerwouldhavetoclosethefileorreleasethe
socket.Thatwouldmakeittooeasytoforgettodocleanupandalsoleadtoalotofredundantcode.To
addressthisproblem,Javaoffersthefinallyblock.
Afinallyblockenclosescodethatisalwaysexecutedatsomepointafterthetryblock,whetheran
exceptionwasthrownornot.Evenifthereisareturnstatementinthetryblock,thefinallyblock
executesrightafterthereturnstatementisencounteredandbeforethereturnexecutes!
Thisistherightplacetocloseyourfiles,releaseyournetworksockets,andperformanyothercleanup
yourcoderequires.Ifthetryblockexecuteswithnoexceptions,thefinallyblockisexecuted
immediatelyafterthetryblockcompletes.Iftherewasanexceptionthrown,thefinallyblockexecutes
immediatelyafterthepropercatchblockcompletes.Let’slookatanotherpseudocodeexample:
Asbefore,executionstartsatthefirstlineofthetryblock,line2.Iftherearenoexceptionsthrownin
thetryblock,executiontransferstoline11,thefirstlineofthefinallyblock.Ontheotherhand,ifa
MySecondExceptionisthrownwhilethecodeinthetryblockisexecuting,executiontransferstothe
firstlineofthatexceptionhandler,line8inthecatchclause.Afterallthecodeinthecatchclauseis
executed,theprogrammovestoline11,thefirstlineofthefinallyclause.Repeatafterme:finally
alwaysruns!Okay,we’llhavetorefinethatalittle,butfornow,startburningintheideathatfinally
alwaysruns.Ifanexceptionisthrown,finallyruns.Ifanexceptionisnotthrown,finallyruns.Ifthe
exceptioniscaught,finallyruns.Iftheexceptionisnotcaught,finallyruns.Laterwe’lllookatthe
fewscenariosinwhichfinallymightnotrunorcomplete.
Remember,finallyclausesarenotrequired.Ifyoudon’twriteone,yourcodewillcompileandrun
justfine.Infact,ifyouhavenoresourcestocleanupafteryourtryblockcompletes,youprobablydon’t
needafinallyclause.Also,becausethecompilerdoesn’tevenrequirecatchclauses,sometimesyou’ll
runacrosscodethathasatryblockimmediatelyfollowedbyafinallyblock.Suchcodeisusefulwhen
theexceptionisgoingtobepassedbacktothecallingmethod,asexplainedinthenextsection.Usinga
finallyblockallowsthecleanupcodetoexecuteevenwhenthereisn’tacatchclause.
Thefollowinglegalcodedemonstratesatrywithafinallybutnocatch:
Thefollowinglegalcodedemonstratesatry,catch,andfinally:
ThefollowingILLEGALcodedemonstratesatrywithoutacatchorfinally:
ThefollowingILLEGALcodedemonstratesamisplacedcatchblock:
Itisillegaltouseatryclausewithouteitheracatchclauseorafinallyclause.Atryclause
byitselfwillresultinacompilererror.Anycatchclausesmustimmediatelyfollowthetry
block.Anyfinallyclausemustimmediatelyfollowthelastcatchclause(oritmust
immediatelyfollowthetryblockifthereisnocatch).Itislegaltoomiteitherthecatch
clauseorthefinallyclause,butnotboth.
PropagatingUncaughtExceptions
Whyaren’tcatchclausesrequired?Whathappenstoanexceptionthat’sthrowninatryblockwhen
thereisnocatchclausewaitingforit?Actually,there’snorequirementthatyoucodeacatchclausefor
everypossibleexceptionthatcouldbethrownfromthecorrespondingtryblock.Infact,it’sdoubtfulthat
youcouldaccomplishsuchafeat!Ifamethoddoesn’tprovideacatchclauseforaparticularexception,
thatmethodissaidtobe“ducking”theexception(or“passingthebuck”).
Sowhathappenstoaduckedexception?Beforewediscussthat,weneedtobrieflyreviewtheconcept
ofthecallstack.Mostlanguageshavetheconceptofamethodstackoracallstack.Simplyput,thecall
stackisthechainofmethodsthatyourprogramexecutestogettothecurrentmethod.Ifyourprogram
startsinmethodmain()andmain()callsmethoda(),whichcallsmethodb(),whichinturncalls
methodc(),thecallstackconsistsofthefollowing:
c
b
a
main
Wewillrepresentthestackasgrowingupward(althoughitcanalsobevisualizedasgrowing
downward).Asyoucansee,thelastmethodcalledisatthetopofthestack,whilethefirstcallingmethod
isatthebottom.Themethodattheverytopofthestacktracewouldbethemethodyouwerecurrently
executing.Ifwemovebackdownthecallstack,we’removingfromthecurrentmethodtothepreviously
calledmethod.Figure5-1illustratesawaytothinkabouthowthecallstackinJavaworks.
FIGURE5-1 TheJavamethodcallstack
Nowlet’sexaminewhathappenstoduckedexceptions.Imagineabuilding,say,fivestorieshigh,and
ateachfloorthereisadeckorbalcony.Nowimaginethatoneachdeck,onepersonisstandingholdinga
baseballmitt.Exceptionsarelikeballsdroppedfrompersontoperson,startingfromtheroof.An
exceptionisfirstthrownfromthetopofthestack(inotherwords,thepersonontheroof);andifitisn’t
caughtbythesamepersonwhothrewit(thepersonontheroof),itdropsdownthecallstacktothe
previousmethod,whichisthepersonstandingonthedeckonefloordown.Ifnotcaughttherebythe
persononefloordown,theexception/ballagaindropsdowntothepreviousmethod(persononthenext
floordown),andsoon,untilitiscaughtoruntilitreachestheverybottomofthecallstack.Thisiscalled
“exceptionpropagation.”
Ifanexceptionreachesthebottomofthecallstack,it’slikereachingthebottomofaverylongdrop;
theballexplodes,andsodoesyourprogram.Anexceptionthat’snevercaughtwillcauseyourapplication
tostoprunning.Adescription(ifoneisavailable)oftheexceptionwillbedisplayed,andthecallstack
willbe“dumped.”Thishelpsyoudebugyourapplicationbytellingyouwhatexceptionwasthrown,from
whatmethoditwasthrown,andwhatthestacklookedlikeatthetime.
Youcankeepthrowinganexceptiondownthroughthemethodsonthestack.Butwhat
happenswhenyougettothemain()methodatthebottom?Youcanthrowtheexceptionoutof
main()aswell.ThisresultsintheJVMhalting,andthestacktracewillbeprintedtothe
output.Thefollowingcodethrowsanexception:
Itprintsoutastacktracesomethinglikethis:
EXERCISE5-3
PropagatingandCatchinganException
Inthisexercise,you’regoingtocreatetwomethodsthatdealwithexceptions.Oneofthemethodsisthe
main()method,whichwillcallanothermethod.Ifanexceptionisthrownintheothermethod,main()
mustdealwithit.Afinallystatementwillbeincludedtoindicatethattheprogramhascompleted.The
methodthatmain()willcallwillbenamedreverse,anditwillreversetheorderofthecharactersina
String.IftheStringcontainsnocharacters,reversewillpropagateanexceptionuptothemain()
method.
1.CreateaclasscalledPropagateandamain()method,whichwillremainemptyfornow.
2.Createamethodcalledreverse.IttakesanargumentofaStringandreturnsaString.
3.Inreverse,checkwhethertheStringhasalengthof0byusingtheString.length()
method.Ifthelengthis0,thereversemethodwillthrowanexception.
4.NowincludethecodetoreversetheorderoftheString.Becausethisisn’tthemaintopicof
thischapter,thereversalcodehasbeenprovided,butfeelfreetotryitonyourown.
5.Nowinthemain()methodyouwillattempttocallthismethodanddealwithanypotential
exceptions.Additionally,youwillincludeafinallystatementthatdisplayswhenmain()has
finished.
DefiningExceptions
Wehavebeendiscussingexceptionsasaconcept.Weknowthattheyarethrownwhenaproblemofsome
typehappens,andweknowwhateffecttheyhaveontheflowofourprogram.Inthissection,wewill
developtheconceptsfurtheranduseexceptionsinfunctionalJavacode.
Earlierwesaidthatanexceptionisanoccurrencethataltersthenormalprogramflow.Butbecause
thisisJava,anythingthat’snotaprimitivemustbe…anobject.Exceptionsarenodifferent.Every
exceptionisaninstanceofaclassthathasclassExceptioninitsinheritancehierarchy.Inotherwords,
exceptionsarealwayssomesubclassofjava.lang.Exception.
Whenanexceptionisthrown,anobjectofaparticularExceptionsubtypeisinstantiatedandhanded
totheexceptionhandlerasanargumenttothecatchclause.Anactualcatchclauselookslikethis:
Inthisexample,eisaninstanceoftheArrayIndexOutOfBoundsExceptionclass.Aswithanyother
object,youcancallitsmethods.
ExceptionHierarchy
AllexceptionclassesaresubtypesofclassException.ThisclassderivesfromtheclassThrowable
(whichderivesfromtheclassObject).Figure5-2showsthehierarchyfortheexceptionclasses.
FIGURE5-2 Exceptionclasshierarchy
Asyoucansee,therearetwosubclassesthatderivefromThrowable:ExceptionandError.Classes
thatderivefromErrorrepresentunusualsituationsthatarenotcausedbyprogramerrorsandindicate
thingsthatwouldnotnormallyhappenduringprogramexecution,suchastheJVMrunningoutofmemory.
Generally,yourapplicationwon’tbeabletorecoverfromanError,soyou’renotrequiredtohandle
them.Ifyourcodedoesnothandlethem(anditusuallywon’t),itwillstillcompilewithnotrouble.
Althoughoftenthoughtofasexceptionalconditions,Errorsaretechnicallynotexceptionsbecausethey
donotderivefromclassException.
Ingeneral,anexceptionrepresentssomethingthathappensnotasaresultofaprogrammingerror,but
ratherbecausesomeresourceisnotavailableorsomeotherconditionrequiredforcorrectexecutionis
notpresent.Forexample,ifyourapplicationissupposedtocommunicatewithanotherapplicationor
computerthatisnotanswering,thisisanexceptionthatisnotcausedbyabug.Figure5-2alsoshowsa
subtypeofExceptioncalledRuntimeException.Theseexceptionsareaspecialcasebecausethey
sometimesdoindicateprogramerrors.Theycanalsorepresentrare,difficult-to-handleexceptional
conditions.Runtimeexceptionsarediscussedingreaterdetaillaterinthischapter.
Javaprovidesmanyexceptionclasses,mostofwhichhavequitedescriptivenames.Therearetwo
waystogetinformationaboutanexception.Thefirstisfromthetypeoftheexceptionitself.Thenextis
frominformationthatyoucangetfromtheexceptionobject.ClassThrowable(atthetopofthe
inheritancetreeforexceptions)providesitsdescendantswithsomemethodsthatareusefulinexception
handlers.OneoftheseisprintStackTrace().Asyouwouldexpect,ifyoucallanexceptionobject’s
printStackTrace()method,asintheearlierexample,astacktracefromwheretheexceptionoccurred
willbeprinted.
Wediscussedthatacallstackbuildsupwardwiththemostrecentlycalledmethodatthetop.Youwill
noticethattheprintStackTrace()methodprintsthemostrecentlyenteredmethodfirstandcontinues
down,printingthenameofeachmethodasitworksitswaydownthecallstack(thisiscalled“unwinding
thestack”)fromthetop.
Fortheexam,youdon’tneedtoknowanyofthemethodscontainedintheThrowableclasses,
includingExceptionandError.YouareexpectedtoknowthatException,Error,
RuntimeException,andThrowabletypescanallbethrownusingthethrowkeywordandcan
allbecaught(althoughyourarelywillcatchanythingotherthanExceptionsubtypes).
HandlinganEntireClassHierarchyofExceptions
We’vediscussedthatthecatchkeywordallowsyoutospecifyaparticulartypeofexceptiontocatch.
Youcanactuallycatchmorethanonetypeofexceptioninasinglecatchclause.Iftheexceptionclassthat
youspecifyinthecatchclausehasnosubclasses,thenonlythespecifiedclassofexceptionwillbe
caught.However,iftheclassspecifiedinthecatchclausedoeshavesubclasses,anyexceptionobject
thatsubclassesthespecifiedclasswillbecaughtaswell.
Forexample,classIndexOutOfBoundsExceptionhastwosubclasses,
ArrayIndexOutOfBoundsExceptionandStringIndexOutOfBoundsException.Youmaywanttowrite
oneexceptionhandlerthatdealswithexceptionsproducedbyeithertypeofboundaryerror,butyoumight
notbeconcernedwithwhichexceptionyouactuallyhave.Inthiscase,youcouldwriteacatchclause
likethefollowing:
IfanycodeinthetryblockthrowsArrayIndexOutOfBoundsExceptionor
StringIndexOutOfBoundsException,theexceptionwillbecaughtandhandled.Thiscanbe
convenient,butitshouldbeusedsparingly.Byspecifyinganexceptionclass’ssuperclassinyourcatch
clause,you’rediscardingvaluableinformationabouttheexception.Youcan,ofcourse,findoutexactly
whatexceptionclassyouhave,butifyou’regoingtodothat,you’rebetteroffwritingaseparatecatch
clauseforeachexceptiontypeofinterest.
Resistthetemptationtowriteasinglecatchallexceptionhandlersuchasthefollowing:
Thiscodewillcatcheveryexceptiongenerated.Ofcourse,nosingleexceptionhandlercanproperly
handleeveryexception,andprogramminginthiswaydefeatsthedesignobjective.Exception
handlersthattrapmanyerrorsatoncewillprobablyreducethereliabilityofyourprogram,because
it’slikelythatanexceptionwillbecaughtthatthehandlerdoesnotknowhowtohandle.
ExceptionMatching
Ifyouhaveanexceptionhierarchycomposedofasuperclassexceptionandanumberofsubtypes,and
you’reinterestedinhandlingoneofthesubtypesinaspecialwaybutwanttohandlealltheresttogether,
youneedwriteonlytwocatchclauses.
Whenanexceptionisthrown,Javawilltrytofind(bylookingattheavailablecatchclausesfromthe
topdown)acatchclausefortheexceptiontype.Ifitdoesn’tfindone,itwillsearchforahandlerfora
supertypeoftheexception.Ifitdoesnotfindacatchclausethatmatchesasupertypefortheexception,
thentheexceptionispropagateddownthecallstack.Thisprocessiscalled“exceptionmatching.”Let’s
lookatanexample.
Thisshortprogramattemptstoopenafileandtoreadsomedatafromit.Openingandreadingfilescan
generatemanyexceptions,mostofwhicharesometypeofIOException.Imaginethatinthisprogram
we’reinterestedinknowingonlywhethertheexactexceptionisaFileNotFoundException.Otherwise,
wedon’tcareexactlywhattheproblemis.
FileNotFoundExceptionisasubclassofIOException.Therefore,wecouldhandleitinthecatch
clausethatcatchesallsubtypesofIOException,butthenwewouldhavetotesttheexceptionto
determinewhetheritwasaFileNotFoundException.Instead,wecodedaspecialexceptionhandlerfor
theFileNotFoundExceptionandaseparateexceptionhandlerforallotherIOExceptionsubtypes.
IfthiscodegeneratesaFileNotFoundException,itwillbehandledbythecatchclausethatbegins
atline10.IfitgeneratesanotherIOException—perhapsEOFException,whichisasubclassof
IOException—itwillbehandledbythecatchclausethatbeginsatline15.Ifsomeotherexceptionis
generated,suchasaruntimeexceptionofsometype,neithercatchclausewillbeexecutedandthe
exceptionwillbepropagateddownthecallstack.
NoticethatthecatchclausefortheFileNotFoundExceptionwasplacedabovethehandlerforthe
IOException.Thisisreallyimportant!Ifwedoittheoppositeway,theprogramwillnotcompile.The
handlersforthemostspecificexceptionsmustalwaysbeplacedabovethoseformoregeneralexceptions.
Thefollowingwillnotcompile:
You’llgetacompilererrorsomethinglikethis:
Ifyouthinkbacktothepeoplewithbaseballmitts(inthesection“PropagatingUncaughtExceptions”),
imaginethatthemostgeneralmittsarethelargestandcanthuscatchmanykindsofballs.An
IOExceptionmittislargeenoughandflexibleenoughtocatchanytypeofIOException.Soiftheperson
onthefifthfloor(say,Fred)hasabigol’IOExceptionmitt,hecan’thelpbutcatcha
FileNotFoundExceptionballwithit.Andiftheguy(say,Jimmy)onthesecondfloorisholdinga
FileNotFoundExceptionmitt,thatFileNotFoundExceptionballwillnevergettohimbecauseitwill
alwaysbestoppedbyFredonthefifthfloor,standingtherewithhisbig-enough-for-any-IOException
mitt.
Sowhatdoyoudowithexceptionsthataresiblingsintheclasshierarchy?IfoneExceptionclassis
notasubtypeorsupertypeoftheother,thentheorderinwhichthecatchclausesareplaceddoesn’t
matter.
ExceptionDeclarationandthePublicInterface
So,howdoweknowthatsomemethodthrowsanexceptionthatwehavetocatch?Justasamethodmust
specifywhattypeandhowmanyargumentsitacceptsandwhatisreturned,theexceptionsthatamethod
canthrowmustbedeclared(unlesstheexceptionsaresubclassesofRuntimeException).Thelistof
thrownexceptionsispartofamethod’spublicinterface.Thethrowskeywordisusedasfollowstolist
theexceptionsthatamethodcanthrow:
Thismethodhasavoidreturntype,acceptsnoarguments,anddeclaresthatitcanthrowoneoftwotypes
ofexceptions:eithertypeMyException1ortypeMyException2.(Justbecausethemethoddeclaresthatit
throwsanexceptiondoesn’tmeanitalwayswill.Itjusttellstheworldthatitmight.)
Supposeyourmethoddoesn’tdirectlythrowanexceptionbutcallsamethodthatdoes.Youcanchoose
nottohandletheexceptionyourselfandinsteadjustdeclareit,asthoughitwereyourmethodthatactually
throwstheexception.Ifyoudodeclaretheexceptionthatyourmethodmightgetfromanothermethodand
youdon’tprovideatry/catchforit,thenthemethodwillpropagatebacktothemethodthatcalledyour
methodandwilleitherbecaughtthereorcontinueontobehandledbyamethodfurtherdownthestack.
Anymethodthatmightthrowanexception(unlessit’sasubclassofRuntimeException)mustdeclare
theexception.Thatincludesmethodsthataren’tactuallythrowingitdirectly,butare“ducking”andletting
theexceptionpassdowntothenextmethodinthestack.Ifyou“duck”anexception,itisjustasifyou
weretheoneactuallythrowingtheexception.RuntimeExceptionsubclassesareexempt,sothecompiler
won’tchecktoseeifyou’vedeclaredthem.Butallnon-RuntimeExceptionsareconsidered“checked”
exceptionsbecausethecompilercheckstobecertainyou’veacknowledgedthat“badthingscouldhappen
here.”
Rememberthis:
Eachmethodmusteitherhandleallcheckedexceptionsbysupplyingacatchclauseorlisteachunhandledcheckedexceptionasa
thrownexception.
ThisruleisreferredtoasJava’s“handleordeclare”requirement(sometimescalled“catchordeclare”).
Lookforcodethatinvokesamethoddeclaringanexception,wherethecallingmethoddoesn’t
handleordeclarethecheckedexception.Thefollowingcode(whichusesthethrowkeywordto
throwanexceptionmanually–moreonthisnext)hastwobigproblemsthatthecompilerwill
prevent:
First,thedoMore()methodthrowsacheckedexceptionbutdoesnotdeclareit!Butsuppose
wefixthedoMore()methodasfollows:
voiddoMore()throwsIOException{…}
ThedoStuff()methodisstillintroublebecauseit,too,mustdeclaretheIOException,
unlessithandlesitbyprovidingatry/catch,withacatchclausethatcantakean
IOException.
Again,someexceptionsareexemptfromthisrule.AnobjectoftypeRuntimeExceptionmaybe
thrownfromanymethodwithoutbeingspecifiedaspartofthemethod’spublicinterface(andahandler
neednotbepresent).AndevenifamethoddoesdeclareaRuntimeException,thecallingmethodis
undernoobligationtohandleordeclareit.RuntimeException,Error,andalltheirsubtypesare
uncheckedexceptions,anduncheckedexceptionsdonothavetobespecifiedorhandled.Hereisan
example:
Let’slookatmyMethod1().BecauseEOFExceptionsubclassesIOExceptionandIOException
subclassesException,itisacheckedexceptionandmustbedeclaredasanexceptionthatmaybethrown
bythismethod.Butwherewilltheexceptionactuallycomefrom?Thepublicinterfaceformethod
myMethod2()calledheredeclaresthatanexceptionofthistypecanbethrown.Whetherthatmethod
actuallythrowstheexceptionitselforcallsanothermethodthatthrowsitisunimportanttous;wesimply
knowthatweeitherhavetocatchtheexceptionordeclarethatwethrewit.ThemethodmyMethod1()
doesnotcatchtheexception,soitdeclaresthatitthrowsit.Nowlet’slookatanotherlegalexample,
myMethod3():
Accordingtothecomment,thismethodcanthrowaNullPointerException.Because
RuntimeExceptionisthesuperclassofNullPointerException,itisanuncheckedexceptionandneed
notbedeclared.WecanseethatmyMethod3()doesnotdeclareanyexceptions.
Runtimeexceptionsarereferredtoasuncheckedexceptions.Allotherexceptionsarechecked
exceptions,andtheydon’tderivefromjava.lang.RuntimeException.Acheckedexceptionmustbe
caughtsomewhereinyourcode.Ifyouinvokeamethodthatthrowsacheckedexceptionbutyoudon’t
catchthecheckedexceptionsomewhere,yourcodewillnotcompile.That’swhythey’recalledchecked
exceptions:thecompilercheckstomakesurethey’rehandledordeclared.Anumberofthemethodsinthe
JavaAPIthrowcheckedexceptions,soyouwilloftenwriteexceptionhandlerstocopewithexceptions
generatedbymethodsyoudidn’twrite.
Youcanalsothrowanexceptionyourself,andthatexceptioncanbeeitheranexistingexceptionfrom
theJavaAPIoroneofyourown.Tocreateyourownexception,yousimplysubclassException(orone
ofitssubclasses)asfollows:
classMyExceptionextendsException{}
Andifyouthrowtheexception,thecompilerwillguaranteethatyoudeclareitasfollows:
Theprecedingcodeupsetsthecompiler:
WhenanobjectofasubtypeofExceptionisthrown,itmustbehandledordeclared.These
objectsarecalled"checkedexceptions"andincludeallexceptionsexceptthosethatare
subtypesofRuntimeException,whichareuncheckedexceptions.Bereadytospotmethods
thatdon’tfollowthe"handleordeclare"rule,suchasthis:
Youneedtorecognizethatthiscodewon’tcompile.Ifyoutry,you’llgetthis:
NoticethatsomeMethod()failseithertohandleordeclaretheexceptionthatcanbethrownby
doStuff().Inthenextpages,we’lldiscussseveralwaystodealwiththissortofsituation.
YouneedtoknowhowanErrorcompareswithcheckedanduncheckedexceptions.Objectsoftype
ErrorarenotExceptionobjects,althoughtheydorepresentexceptionalconditions.BothException
andErrorshareacommonsuperclass,Throwable;thus,bothcanbethrownusingthethrowkeyword.
WhenanErrororasubclassofError(likeStackOverflowError)isthrown,it’sunchecked.Youare
notrequiredtocatchErrorobjectsorErrorsubtypes.YoucanalsothrowanErroryourself(although,
otherthanAssertionError,youprobablywon’teverwantto),andyoucancatchone,butagain,you
probablywon’t.What,forexample,wouldyouactuallydoifyougotanOutOfMemoryError?It’snotlike
youcantellthegarbagecollectortorun;youcanbettheJVMfoughtdesperatelytosaveitself(and
reclaimedallthememoryitcould)bythetimeyougottheerror.Inotherwords,don’texpecttheJVMat
thatpointtosay,“Runthegarbagecollector?Oh,thankssomuchfortellingme.Thatjustneveroccurred
tome.Sure,I’llgetrightonit.”Evenbetter,whatwouldyoudoifaVirtualMachineErrorarose?Your
programistoastbythetimeyou’dcatchtheerror,sothere’sreallynopointintryingtocatchoneofthese
babies.Justremember,though,thatyoucan!Thefollowingcompilesjustfine:
IfwewerethrowingacheckedexceptionratherthanError,thenthedoStuff()methodwouldneedto
declaretheexception.Butremember,sinceErrorisnotasubtypeofException,itdoesn’tneedtobe
declared.You’refreetodeclareitifyoulike,butthecompilerjustdoesn’tcareonewayoranotherwhen
orhowtheErroristhrownorbywhom.
BecauseJavahascheckedexceptions,it’scommonlysaidthatJavaforcesdeveloperstohandle
exceptions.Yes,Javaforcesustowriteexceptionhandlersforeachexceptionthatcanoccurduring
normaloperation,butit’suptoustomaketheexceptionhandlersactuallydosomethinguseful.We
knowsoftwaremanagerswhomeltdownwhentheyseeaprogrammerwritesomethinglikethis:
Noticeanythingmissing?Don’t“eat”theexceptionbycatchingitwithoutactuallyhandlingit.You
won’tevenbeabletotellthattheexceptionoccurredbecauseyou’llneverseethestacktrace.
RethrowingtheSameException
Justasyoucanthrowanewexceptionfromacatchclause,youcanalsothrowthesameexceptionyou
justcaught.Here’sacatchclausethatdoesthis:
Allothercatchclausesassociatedwiththesametryareignored;ifafinallyblockexists,itruns,
andtheexceptionisthrownbacktothecallingmethod(thenextmethoddownthecallstack).Ifyouthrow
acheckedexceptionfromacatchclause,youmustalsodeclarethatexception!Inotherwords,youmust
handleanddeclare,asopposedtohandleordeclare.Thefollowingexampleisillegal:
Intheprecedingcode,thedoStuff()methodisclearlyabletothrowacheckedexception—inthiscase
anIOException—sothecompilersays,“Well,that’sjustpeachythatyouhaveatry/catchinthere,but
it’snotgoodenough.IfyoumightrethrowtheIOExceptionyoucatch,thenyoumustdeclareit(inthe
methodsignature)!”
EXERCISE5-4
CreatinganException
Inthisexercise,weattempttocreateacustomexception.Wewon’tputinanynewmethods(itwillhave
onlythoseinheritedfromException);andbecauseitextendsException,thecompilerconsidersita
checkedexception.Thegoaloftheprogramistodeterminewhetheracommand-lineargument
representingaparticularfood(asastring)isconsideredbadorokay.
1.Let’sfirstcreateourexception.WewillcallitBadFoodException.Thisexceptionwillbe
thrownwhenabadfoodisencountered.
2.CreateanenclosingclasscalledMyExceptionandamain()method,whichwillremain
emptyfornow.
3.CreateamethodcalledcheckFood().IttakesaStringargumentandthrowsourexceptionif
itdoesn’tlikethefooditwasgiven.Otherwise,ittellsusitlikesthefood.Youcanaddanyfoods
youaren’tparticularlyfondoftothelist.
4.Nowinthemain()method,you’llgetthecommand-lineargumentoutoftheStringarrayand
thenpassthatStringontothecheckFood()method.Becauseit’sacheckedexception,the
checkFood()methodmustdeclareit,andthemain()methodmusthandleit(usingatry/catch).
Donothavemain()declaretheexception,becauseifmain()duckstheexception,whoelseisback
theretocatchit?(Actually,main()canlegallydeclareexceptions,butdon’tdothatinthis
exercise.)
Asniftyasexceptionhandlingis,it’sstilluptothedevelopertomakeproperuseofit.Exception
handlingmakesorganizingcodeandsignalingproblemseasy,buttheexceptionhandlersstillhavetobe
written.You’llfindthateventhemostcomplexsituationscanbehandled,andyourcodewillbereusable,
readable,andmaintainable.
CERTIFICATIONOBJECTIVE
CommonExceptionsandErrors(OCAObjective8.5)
8.5Recognizecommonexceptionclasses(suchasNullPointerException,ArithmeticException,
ArrayIndexOutOfBoundsException,ClassCastException)(sic)
Theintentionofthisobjectiveistomakesurethatyouarefamiliarwithsomeofthemostcommon
exceptionsanderrorsyou’llencounterasaJavaprogrammer.
Thequestionsfromthissectionarelikelytobealongthelinesof,"Here’ssomecodethatjust
didsomethingbad,whichexceptionwillbethrown?"Throughouttheexam,questionswill
presentsomecodeandaskyoutodeterminewhetherthecodewillrunorwhetheranexception
willbethrown.Sincethesequestionsaresocommon,understandingthecausesforthese
exceptionsiscriticaltoyoursuccess.
Thisisanotheroneofthoseobjectivesthatwillturnupallthroughtherealexam(does“Anexception
isthrownatruntime”ringabell?),somakesurethissectiongetsalotofyourattention.
WhereExceptionsComeFrom
Jumpbackapageandtakealookatthelastsentence.It’simportantthatyouunderstandwhatcauses
exceptionsanderrorsandwheretheycomefrom.Forthepurposesofexampreparation,let’sdefinetwo
broadcategoriesofexceptionsanderrors:
JVMexceptionsThoseexceptionsorerrorsthatareeitherexclusivelyormostlogically
thrownbytheJVM
ProgrammaticexceptionsThoseexceptionsthatarethrownexplicitlybyapplicationand/or
APIprogrammers
JVM-ThrownExceptions
Let’sstartwithaverycommonexception,theNullPointerException.Aswesawinearlierchapters,
thisexceptionoccurswhenyouattempttoaccessanobjectusingareferencevariablewithacurrentvalue
ofnull.There’snowaythatthecompilercanhopetofindtheseproblemsbeforeruntime.Takealookat
thefollowing:
Surely,thecompilercanfindtheproblemwiththattinylittleprogram!Nope,you’reonyourown.The
codewillcompilejustfine,andtheJVMwillthrowaNullPointerExceptionwhenittriestoinvoke
thelength()method.
Earlierinthischapterwediscussedthecallstack.Asyourecall,weusedtheconventionthatmain()
wouldbeatthebottomofthecallstack,andthatasmain()invokesanothermethod,andthatmethod
invokesanother,andsoon,thestackgrowsupward.Ofcourse,thestackresidesinmemory,andevenif
yourOSgivesyouagigabyteofRAMforyourprogram,it’sstillafiniteamount.It’spossibletogrowthe
stacksolargethattheOSrunsoutofspacetostorethecallstack.Whenthishappens,youget(waitfor
it…)aStackOverflowError.Themostcommonwayforthistooccuristocreatearecursivemethod.A
recursivemethodinvokesitselfinthemethodbody.Althoughthatmaysoundweird,it’saverycommon
andusefultechniqueforsuchthingsassearchingandsortingalgorithms.Takealookatthiscode:
Asyoucansee,ifyouevermakethemistakeofinvokingthego()method,yourprogramwillfallintoa
blackhole—go()invokinggo()invokinggo(),until,nomatterhowmuchmemoryyouhave,you’llgeta
StackOverflowError.Again,onlytheJVMknowswhenthismomentoccurs,andtheJVMwillbethe
sourceofthiserror.
ProgrammaticallyThrownExceptions
Nowlet’slookatprogrammaticallythrownexceptions.Rememberwedefinedprogrammaticallyas
meaningsomethinglikethis:
Createdbyanapplicationand/orAPIdeveloper
Forinstance,manyclassesintheJavaAPIhavemethodsthattakeStringargumentsandconvertthese
Stringsintonumericprimitives.Agoodexampleoftheseclassesistheso-called“wrapperclasses”that
wewillstudyinChapter6.Eventhoughwehaven’ttalkedmuchaboutwrapperclassesyet,thefollowing
exampleshouldmakesense.
Atsomepointlongago,someprogrammerwrotethejava.lang.Integerclassandcreatedmethods
likeparseInt()andvalueOf().Thatprogrammerwiselydecidedthatifoneofthesemethodswas
passedaStringthatcouldnotbeconvertedintoanumber,themethodshouldthrowa
NumberFormatException.Thepartiallyimplementedcodemightlooksomethinglikethis:
OtherexamplesofprogrammaticexceptionsincludeanAssertionError(okay,it’snotanexception,
butitISthrownprogrammatically)andthrowinganIllegalArgumentException.Infact,ourmythical
APIdevelopercouldhaveusedIllegalArgumentExceptionforherparseInt()method.Butitturns
outthatNumberFormatExceptionextendsIllegalArgumentExceptionandisalittlemoreprecise,so
inthiscase,usingNumberFormatExceptionsupportsthenotionwediscussedearlier:thatwhenyou
haveanexceptionhierarchy,youshouldusethemostpreciseexceptionthatyoucan.
Ofcourse,aswediscussedearlier,youcanalsomakeupyourveryownspecialcustomexceptions
andthrowthemwheneveryouwantto.Thesehomemadeexceptionsalsofallintothecategoryof
“programmaticallythrownexceptions.”
ASummaryoftheExam’sExceptionsandErrors
OCA8Objective8.5listsafewspecificexceptionsanderrors;itsays“Recognizecommonexception
classes(suchas….”).Table5-2summarizesthetenexceptionsanderrorsthataremostlikelyapartofthe
OCA8exam.
TABLE5-2 DescriptionsandSourcesofCommonExceptions
CERTIFICATIONSUMMARY
Thischaptercoveredalotofground,allofwhichinvolvedwaysofcontrollingyourprogramflowbased
onaconditionaltest.First,youlearnedaboutifandswitchstatements.Theifstatementevaluatesone
ormoreexpressionstoabooleanresult.Iftheresultistrue,theprogramwillexecutethecodeinthe
blockthatisencompassedbytheif.Ifanelsestatementisusedandtheifexpressionevaluatesto
false,thenthecodefollowingtheelsewillbeperformed.Ifnoelseblockisdefined,thennoneofthe
codeassociatedwiththeifstatementwillexecute.
Youalsolearnedthattheswitchstatementcanbeusedtoreplacemultiple
if-elsestatements.Theswitchstatementcanevaluateintegerprimitivetypesthatcanbeimplicitlycast
toanint(thosetypesarebyte,short,int,andchar);oritcanevaluateenums;andasofJava7,itcan
evaluateStrings.Atruntime,theJVMwilltrytofindamatchbetweentheexpressionintheswitch
statementandaconstantinacorrespondingcasestatement.Ifamatchisfound,executionwillbeginat
thematchingcaseandcontinueonfromthere,executingcodeinalltheremainingcasestatementsuntila
breakstatementisfoundortheendoftheswitchstatementoccurs.Ifthereisnomatch,thenthedefault
casewillexecute,ifthereisone.
You’velearnedaboutthethreeloopingconstructsavailableintheJavalanguage.Theseconstructsare
theforloop(includingthebasicforandtheenhancedfor,whichwasnewtoJava5),thewhileloop,
andthedoloop.Ingeneral,theforloopisusedwhenyouknowhowmanytimesyouneedtogothrough
theloop.Thewhileloopisusedwhenyoudonotknowhowmanytimesyouwanttogothrough,whereas
thedoloopisusedwhenyouneedtogothroughatleastonce.Intheforloopandthewhileloop,the
expressionhastoevaluatetotruetogetinsidetheblockandwillcheckaftereveryiterationoftheloop.
Thedoloopdoesnotchecktheconditionuntilafterithasgonethroughthelooponce.Themajorbenefit
oftheforloopistheabilitytoinitializeoneormorevariablesandincrementordecrementthose
variablesintheforloopdefinition.
Thebreakandcontinuestatementscanbeusedineitheralabeledorunlabeledfashion.When
unlabeled,thebreakstatementwillforcetheprogramtostopprocessingtheinnermostloopingconstruct
andstartwiththelineofcodefollowingtheloop.Usinganunlabeledcontinuecommandwillcausethe
programtostopexecutionofthecurrentiterationoftheinnermostloopandproceedwiththenext
iteration.Whenabreakoracontinuestatementisusedinalabeledmanner,itwillperforminthesame
way,withoneexception:thestatementwillnotapplytotheinnermostloop;instead,itwillapplytothe
loopwiththelabel.Thebreakstatementisusedmostofteninconjunctionwiththeswitchstatement.
Whenthereisamatchbetweentheswitchexpressionandthecaseconstant,thecodefollowingthecase
constantwillbeperformed.Tostopexecution,abreakisneeded.
You’veseenhowJavaprovidesanelegantmechanisminexceptionhandling.Exceptionhandling
allowsyoutoisolateyourerror-correctioncodeintoseparateblockssothemaincodedoesn’tbecome
clutteredbyerror-checkingcode.Anotherelegantfeatureallowsyoutohandlesimilarerrorswitha
singleerror-handlingblock,withoutcodeduplication.Also,theerrorhandlingcanbedeferredto
methodsfurtherbackonthecallstack.
YoulearnedthatJava’strykeywordisusedtospecifyaguardedregion—ablockofcodeinwhich
problemsmightbedetected.Anexceptionhandleristhecodethatisexecutedwhenanexceptionoccurs.
ThehandlerisdefinedbyusingJava’scatchkeyword.Allcatchclausesmustimmediatelyfollowthe
relatedtryblock.
Javaalsoprovidesthefinallykeyword.Thisisusedtodefineablockofcodethatisalways
executed,eitherimmediatelyafteracatchclausecompletesorimmediatelyaftertheassociatedtry
blockinthecasethatnoexceptionwasthrown(ortherewasatrybutnocatch).Usefinallyblocksto
releasesystemresourcesandtoperformanycleanuprequiredbythecodeinthetryblock.Afinally
blockisnotrequired,butifthereisone,itmustimmediatelyfollowthelastcatch.(Ifthereisnocatch
block,thefinallyblockmustimmediatelyfollowthetryblock.)It’sguaranteedtobecalledexcept
whenthetryorcatchissuesaSystem.exit().
AnexceptionobjectisaninstanceofclassExceptionoroneofitssubclasses.Thecatchclause
takes,asaparameter,aninstanceofanobjectofatypederivedfromtheExceptionclass.Javarequires
thateachmethodeithercatchesanycheckedexceptionitcanthroworelsedeclaresthatitthrowsthe
exception.Theexceptiondeclarationispartofthemethod’ssignature.Todeclarethatanexceptionmay
bethrown,thethrowskeywordisusedinamethoddefinition,alongwithalistofallcheckedexceptions
thatmightbethrown.
RuntimeexceptionsareoftypeRuntimeException(oroneofitssubclasses).Theseexceptionsarea
specialcasebecausetheydonotneedtobehandledordeclared,andthusareknownas“unchecked”
exceptions.Errorsareoftypejava.lang.Errororitssubclasses,andlikeruntimeexceptions,theydo
notneedtobehandledordeclared.Checkedexceptionsincludeanyexceptiontypesthatarenotoftype
RuntimeExceptionorError.Ifyourcodefailseithertohandleacheckedexceptionordeclarethatitis
thrown,yourcodewon’tcompile.ButwithuncheckedexceptionsorobjectsoftypeError,itdoesn’t
mattertothecompilerwhetheryoudeclarethemorhandlethem,donothingaboutthem,ordosome
combinationofdeclaringandhandling.Inotherwords,you’refreetodeclarethemandhandlethem,but
thecompilerwon’tcareonewayortheother.It’snotgoodpracticetohandleanError,though,because
youcanrarelyrecoverfromone.
Finally,rememberthatexceptionscanbegeneratedbytheJVMorbyaprogrammer.
TWO-MINUTEDRILL
Herearesomeofthekeypointsfromeachcertificationobjectiveinthischapter.Youmightwanttoloop
throughthemseveraltimes.
WritingCodeUsingifandswitchStatements(OCAObjectives3.3and3.4)
Theonlylegalexpressioninanifstatementisabooleanexpression—inotherwords,an
expressionthatresolvestoabooleanoraBooleanreference.
Watchoutforbooleanassignments(=)thatcanbemistakenforbooleanequality(==)tests:
booleanx=false;
if(x=true){}//anassignment,soxwillalwaysbetrue!
Curlybracesareoptionalforifblocksthathaveonlyoneconditionalstatement.Butwatch
outformisleadingindentations.
switchstatementscanevaluateonlytoenumsorthebyte,short,int,char,and,asofJava
7,Stringdatatypes.Youcan’tsaythis:
longs=30;
switch(s){}
Thecaseconstantmustbealiteraloracompile-timeconstant,includinganenumora
String.Youcannothaveacasethatincludesanonfinalvariableorarangeofvalues.
Iftheconditioninaswitchstatementmatchesacaseconstant,executionwillrunthroughall
codeintheswitchfollowingthematchingcasestatementuntilabreakstatementortheendofthe
switchstatementisencountered.Inotherwords,thematchingcaseisjusttheentrypointintothe
caseblock,butunlessthere’sabreakstatement,thematchingcaseisnottheonlycasecodethat
runs.
Thedefaultkeywordshouldbeusedinaswitchstatementifyouwanttorunsomecode
whennoneofthecasevaluesmatchtheconditionalvalue.
Thedefaultblockcanbelocatedanywhereintheswitchblock,soifnoprecedingcase
matches,thedefaultblockwillbeentered;ifthedefaultdoesnotcontainabreak,thencode
willcontinuetoexecute(fall-through)totheendoftheswitchoruntilthebreakstatementis
encountered.
WritingCodeUsingLoops(OCAObjectives5.1,5.2,5.3,and5.4)
Abasicforstatementhasthreeparts:declarationand/orinitialization,booleanevaluation,
andtheiterationexpression.
Ifavariableisincrementedorevaluatedwithinabasicforloop,itmustbedeclaredbefore
thelooporwithintheforloopdeclaration.
Avariabledeclared(notjustinitialized)withinthebasicforloopdeclarationcannotbe
accessedoutsidetheforloop—inotherwords,codebelowtheforloopwon’tbeabletousethe
variable.
Youcaninitializemorethanonevariableofthesametypeinthefirstpartofthebasicfor
loopdeclaration;eachinitializationmustbecommaseparated.
Anenhancedforstatement(newasofJava5)hastwoparts:thedeclarationandthe
expression.Itisusedonlytoloopthrougharraysorcollections.
Withanenhancedfor,theexpressionisthearrayorcollectionthroughwhichyouwantto
loop.
Withanenhancedfor,thedeclarationistheblockvariable,whosetypeiscompatiblewith
theelementsofthearrayorcollection,andthatvariablecontainsthevalueoftheelementforthe
giveniteration.
UnlikewithC,youcannotuseanumberoranythingthatdoesnotevaluatetoabooleanvalue
asaconditionforanifstatementorloopingconstruct.Youcan’t,forexample,sayif(x),unlessx
isabooleanvariable.
Thedoloopwillalwaysenterthebodyoftheloopatleastonce.
Usingbreakandcontinue(OCAObjective5.5)
Anunlabeledbreakstatementwillcausethecurrentiterationoftheinnermostlooptostop
andthelineofcodefollowingthelooptorun.
Anunlabeledcontinuestatementwillcausethecurrentiterationoftheinnermostloopto
stop,theconditionofthatlooptobechecked,andiftheconditionismet,thelooptorunagain.
Ifthebreakstatementorthecontinuestatementislabeled,itwillcause
asimilaractiontooccuronthelabeledloop,nottheinnermostloop.
HandlingExceptions(OCAObjectives8.1,8.2,8.3,8.4,and8.5)
SomeofthebenefitsofJava’sexception-handlingfeaturesincludeorganizederror-handling
code,easyerrordetection,keepingexception-handlingcodeseparatefromothercode,andthe
abilitytoreuseexception-handlingcodeforarangeofissues.
Exceptionscomeintwoflavors:checkedandunchecked.
CheckedexceptionsincludeallsubtypesofException,excludingclassesthatextend
RuntimeException.
Checkedexceptionsaresubjecttothehandleordeclarerule;anymethodthatmightthrowa
checkedexception(includingmethodsthatinvokemethodsthatcanthrowacheckedexception)
musteitherdeclaretheexceptionusingthrowsorhandletheexceptionwithanappropriate
try/catch.
SubtypesofErrororRuntimeExceptionareunchecked,sothecompilerdoesn’tenforcethe
handleordeclarerule.You’refreetohandlethemortodeclarethem,butthecompilerdoesn’tcare
onewayortheother.
Afinallyblockwillalwaysbeinvoked,regardlessofwhetheranexceptionisthrownor
caughtinitstry/catch.
Theonlyexceptiontothefinally-will-always-be-calledruleisthatafinallywillnotbe
invokediftheJVMshutsdown.Thatcouldhappenifcodefromthetryorcatchblockscalls
System.exit().
Justbecausefinallyisinvokeddoesnotmeanitwillcomplete.Codeinthefinallyblock
coulditselfraiseanexceptionorissueaSystem.exit().
Uncaughtexceptionspropagatebackthroughthecallstack,startingfromthemethodwherethe
exceptionisthrownandendingwitheitherthefirstmethodthathasacorrespondingcatchforthat
exceptiontypeoraJVMshutdown(whichhappensiftheexceptiongetstomain()andmain()is
“ducking”theexceptionbydeclaringit).
YoucanalmostalwayscreateyourownexceptionsbyextendingExceptionoroneofits
checkedexceptionsubtypes.Suchanexceptionwillthenbeconsideredacheckedexceptionbythe
compiler.(Inotherwords,it’sraretoextendRuntimeException.)
Allcatchblocksmustbeorderedfrommostspecifictomostgeneral.Ifyouhaveacatch
clauseforbothIOExceptionandException,youmustputthecatchforIOExceptionfirstin
yourcode.Otherwise,theIOExceptionwouldbecaughtbycatch(Exceptione),becausea
catchargumentcancatchthespecifiedexceptionoranyofitssubtypes!
SomeexceptionsarecreatedbyprogrammersandsomebytheJVM.
SELFTEST
1.GiventhattoLowerCase()isanaptlynamedStringmethodthatreturnsaString,andgiven
thecode:
H.Compilationfails
3.Given:
try{intx=Integer.parseInt(“two”);}
Whichcouldbeusedtocreateanappropriatecatchblock?(Chooseallthatapply.)
A.ClassCastException
B.IllegalStateException
C.NumberFormatException
D.IllegalArgumentException
E.ExceptionInInitializerError
F.ArrayIndexOutOfBoundsException
4.Given:
Andgiventhecommand-lineinvocation:
JavaFlip2REDGreenYeLLow
Whicharetrue?(Chooseallthatapply.)
A.Thestringrgywillappearsomewhereintheoutput
B.Thestringrggwillappearsomewhereintheoutput
C.Thestringgyrwillappearsomewhereintheoutput
D.Compilationfails
E.Anexceptionisthrownatruntime
5.Given:
A.Compilationsucceeds
B.Compilationfailsduetoanerroronline8
C.Compilationfailsduetoanerroronline10
D.Compilationfailsduetoanerroronline12
E.Compilationfailsduetoanerroronline14
8.Given:
Whatistheresult?
A.910d
B.8910d
C.91010d
D.91010d13
E.891010d13
F.891091010d13
G.Compilationfails
9.Given:
Andgiventhatline7willassignthevalue0,1,or2tosw,whicharetrue?(Chooseallthat
apply.)
A.Compilationfails
B.AClassCastExceptionmightbethrown
C.AStackOverflowErrormightbethrown
D.ANullPointerExceptionmightbethrown
E.AnIllegalStateExceptionmightbethrown
F.Theprogrammighthangwithoutevercompleting
G.Theprogramwillalwayscompletewithoutexception
10.Given:
Whatistheresult?
A.139
B.5577
C.13399
D.113399
E.111333999
F.Compilationfails
11.Given:
Whatistheresult?
A.12
B.13
C.123
D.1234
E.Compilationfails
F.123followedbyanexception
G.1234followedbyanexception
H.Anexceptionisthrownwithnootheroutput
12.Given:
Whatistheresult?
A.0123
B.11133
C.0111233
D.11133444
E.0111233444
F.Compilationfails
13.Given:
Andgiventhefollowingthreecodefragments:
WhenfragmentsI–IIIareadded,independently,atline5,whicharetrue?(Chooseallthatapply.)
A.Somewillnotcompile
B.Theywillallcompile
C.Allwillcompletenormally
D.Nonewillcompletenormally
E.Onlyonewillcompletenormally
F.Twoofthemwillcompletenormally
14.Giventhecodesnippet:
Andgiventhatthenumberedlineswillallbetestedbyuncommentingoneswitchstatementand
onecasestatementtogether,whichline(s)willFAILtocompile?(Chooseallthatapply.)
A.line1
B.line2
C.line3
D.line4
E.line5
F.line6
G.Allsixlinesofcodewillcompile
15.GiventhatIOExceptionisinthejava.iopackageandgiven:
Andgiventhefollowingfourcodefragments:
Ifthefourfragmentsareinsertedindependentlyatline2,whicharetrue?(Chooseallthatapply.)
A.Allfourwillcompileandexecutewithoutexception
B.Allfourwillcompileandexecuteandthrowanexception
C.Some,butnotall,willcompileandexecutewithoutexception
D.Some,butnotall,willcompileandexecuteandthrowanexception
E.WhenconsideringfragmentsII,III,andIV,ofthosethatwillcompile,addingatry/catch
blockaroundline4willcausecompilationtofail
16.Given:
Andgiventhefollowingfourcodefragments:
WhenfragmentsI–IVareadded,independently,atline10,whicharetrue?(Chooseallthat
apply.)
A.Nonewillcompile
B.Theywillallcompile
C.Some,butnotall,willcompile
D.Allthosethatcompilewillthrowanexceptionatruntime
E.Noneofthosethatcompilewillthrowanexceptionatruntime
F.Onlysomeofthosethatcompilewillthrowanexceptionatruntime
SELFTESTANSWERS
1. Ciscorrect.AsofJava7it’slegaltoswitchonaString,andrememberthatswitchesuse
“entrypoint”logic.
A,B,D,andEareincorrectbasedontheabove.(OCAObjective3.4)
2. Biscorrect.Onces3()throwstheexceptiontos2(),s2()throwsittos1(),andnomore
ofs2()’scodewillbeexecuted.
A,C,D,E,F,G,andHareincorrectbasedontheabove.(OCAObjectives8.2and8.4)
3. CandDarecorrect.Integer.parseIntcanthrowaNumberFormatException,and
IllegalArgumentExceptionisitssuperclass(thatis,abroaderexception).
A,B,E,andFarenotinNumberFormatException’sclasshierarchy.(OCAObjective8.5)
4. Eiscorrect.AsofJava7thesyntaxislegal.Thesa[]arrayreceivesonlythreearguments
fromthecommandline,soonthelastiterationthroughsa[],aNullPointerExceptionisthrown.
A,B,C,andDareincorrectbasedontheabove.(OCAObjectives1.3,5.2,and8.5)
5. A,D,andFarecorrect.Aisanexampleoftheenhancedforloop.DandFareexamples
ofthebasicforloop.
B,C,andEareincorrect.Bisincorrectbecauseitsoperandsareswapped.Cisincorrect
becausetheenhancedformustdeclareitsfirstoperand.Eisincorrectsyntaxtodeclaretwo
variablesinaforstatement.(OCAObjective5.2)
6. Eiscorrect.Thereisnoproblemnestingtry/catchblocks.Asisnormal,whenan
exceptionisthrown,thecodeinthecatchblockruns,andthenthecodeinthefinallyblockruns.
A,B,C,D,andFareincorrectbasedontheabove.(OCAObjectives8.2and8.4)
7. Ciscorrect.Anoverridingmethodcannotthrowabroaderexceptionthanthemethodit’s
overriding.ClassCC4’smethodisanoverload,notanoverride.
A,B,D,andEareincorrectbasedontheabove.(OCAObjectives8.2and8.4)
8. Discorrect.Didyoucatchthestaticinitializerblock?Rememberthatswitchesworkon
“fall-through”logicandthatfall-throughlogicalsoappliestothedefaultcase,whichisusedwhen
noothercasematches.
A,B,C,E,F,andGareincorrectbasedontheabove.(OCAObjective3.4)
9. DandFarecorrect.Becauseiwasnotinitialized,case1willthrowa
NullPointerException.Case0willinitiateanendlessloop,notastackoverflow.Case2’s
downcastwillnotcauseanexception.
A,B,C,E,andGareincorrectbasedontheabove.(OCAObjectives3.4and8.5)
10. Discorrect.Thebasicruleforunlabeledcontinuestatementsisthatthecurrentiteration
stopsearlyandexecutionjumpstothenextiteration.Thelasttwocontinuestatementsare
redundant!
A,B,C,E,andFareincorrectbasedontheabove.(OCAObjectives5.2and5.5)
11. Hiscorrect.It’struethatthevalueofStringsis123atthetimethatthedivide-by-zero
exceptionisthrown,butfinally()isnotguaranteedtocomplete,andinthiscasefinally()
nevercompletes,sotheSystem.out.println(S.O.P)neverexecutes.
A,B,C,D,E,F,andGareincorrectbasedontheabove.(OCAObjectives8.2and8.5)
12. Ciscorrect.Abreakbreaksoutofthecurrentinnermostloopandcarrieson.Alabeled
breakbreaksoutofandterminatesthelabeledloops.
A,B,D,E,andFareincorrectbasedontheabove.(OCAObjectives5.2and5.5)
13. BandEarecorrect.Firstoff,go()isabadlydesignedrecursivemethod,guaranteedto
causeaStackOverflowError.SinceExceptionisnotasuperclassofError,catchingan
ExceptionwillnothelphandleanError,sofragmentIIIwillnotcompletenormally.Only
fragmentIIwillcatchtheError.
A,C,D,andFareincorrectbasedontheabove.(OCAObjectives8.1,8.2,and8.4)
14. Eiscorrect.Aswitch’scasesmustbecompile-timeconstantsorenumvalues.
A,B,C,D,F,andGareincorrectbasedontheabove.(OCAObjective3.4)
15. Discorrect.Thisiskindofsneaky,butrememberthatwe’retryingtotoughenyouupfor
therealexam.Ifyou’regoingtothrowanIOException,youhavetoimportthejava.iopackageor
declaretheexceptionwithafullyqualifiedname.
A,B,C,andEareincorrect.A,B,andCareincorrectbasedontheabove.Eisincorrect
becauseit’sokaybothtohandleanddeclareanexception.(OCAObjectives8.2and8.5)
16. CandDarecorrect.Anoverridingmethodcannotthrowcheckedexceptionsthatare
broaderthanthosethrownbytheoverriddenmethod.However,anoverridingmethodcanthrow
RuntimeExceptionsnotthrownbytheoverriddenmethod.
A,B,E,andFareincorrectbasedontheabove.(OCAObjective8.1)
T
6
Strings,Arrays,ArrayLists,Dates,andLambdas
CERTIFICATIONOBJECTIVES
•CreateandManipulateStrings
•ManipulateDataUsingtheStringBuilderClassandItsMethods
•CreateandUseCalendarData
•Declare,Instantiate,Initialize,andUseaOne-DimensionalArray
•Declare,Instantiate,Initialize,andUseaMultidimensionalArray
•DeclareandUseanArrayList
•UseWrapperClasses
•UseEncapsulationforReferenceVariables
•UseSimpleLambdaExpressions
Two-MinuteDrill
Q&ASelfTest
hischapterfocusesontheexamobjectivesrelatedtosearching,formatting,andparsingstrings;
creatingandusingcalendar-relatedobjects;creatingandusingarraysandArrayLists;and
usingsimplelambdaexpressions.Manyofthesetopicscouldfillanentirebook.Fortunately,
youwon’thavetobecomeatotalgurutodowellontheexam.Theexamteamintendedto
includejustthebasicaspectsofthesetechnologies,andinthischapter,wecovermorethanyou’llneedto
getthroughtherelatedobjectivesontheexam.
CERTIFICATIONOBJECTIVE
UsingStringandStringBuilder(OCAObjectives9.2and
9.1)
9.2CreatingandmanipulatingStrings.
9.1ManipulatedatausingtheStringBuilderclassanditsmethods.
EverythingyouneededtoknowaboutstringsintheolderOCJPexamsyou’llneedtoknowforthe
OCA8exam.CloselyrelatedtotheStringclassaretheStringBuilderclassandthealmostidentical
StringBufferclass.(Fortheexam,theonlythingyouneedtoknowabouttheStringBufferclassis
thatithasexactlythesamemethodsastheStringBuilderclass,butStringBuilderisfasterbecause
itsmethodsaren’tsynchronized.)Bothclasses,StringBuilderandStringBuffer,giveyouString-
likeobjectsandwaystomanipulatethem,withtheimportantdifferencebeingthattheseobjectsare
mutable.
TheStringClass
ThissectioncoverstheStringclass,andthekeyconceptforyoutounderstandisthatonceaString
objectiscreated,itcanneverbechanged.So,then,whatishappeningwhenaStringobjectseemstobe
changing?Let’sfindout.
StringsAreImmutableObjects
We’llstartwithalittlebackgroundinformationaboutstrings.Youmaynotneedthisforthetest,buta
littlecontextwillhelp.Handling"strings"ofcharactersisafundamentalaspectofmostprogramming
languages.InJava,eachcharacterinastringisa16-bitUnicodecharacter.BecauseUnicodecharacters
are16bits(nottheskimpy7or8bitsthatASCIIprovides),arich,internationalsetofcharactersiseasily
representedinUnicode.
InJava,stringsareobjects.Aswithotherobjects,youcancreateaninstanceofastringwiththenew
keyword,asfollows:
Strings=newString();
ThislineofcodecreatesanewobjectofclassStringandassignsittothereferencevariables.
Sofar,Stringobjectsseemjustlikeotherobjects.Now,let’sgivethestringavalue:
s="abcdef";
(Asyou’llfindoutshortly,thesetwolinesofcodearen’tquitewhattheyseem,sostaytuned.)
ItturnsouttheStringclasshasaboutazillionconstructors,soyoucanuseamoreefficientshortcut:
Strings=newString("abcdef");
Andthisisevenmoreconcise:
Strings="abcdef";
Therearesomesubtledifferencesbetweentheseoptionsthatwe’lldiscusslater,butwhattheyhavein
commonisthattheyallcreateanewStringobject,withavalueof"abcdef",andassignittoa
referencevariables.Nowlet’ssayyouwantasecondreferencetotheStringobjectreferredtobys:
Strings2=s;//refers2tothesameStringass
Sofarsogood.Stringobjectsseemtobebehavingjustlikeotherobjects,sowhat’sallthefuss
about?Immutability!(Whattheheckisimmutability?)OnceyouhaveassignedaStringavalue,that
valuecanneverchange—it’simmutable,frozensolid,won’tbudge,fini,done.(We’lltalkaboutwhy
later;don’tletusforget.)ThegoodnewsisthatalthoughtheStringobjectisimmutable,itsreference
variableisnot,sotocontinuewithourpreviousexample,considerthis:
Now,waitjustaminute,didn’twejustsaythatStringobjectswereimmutable?Sowhat’sallthis
"appendingtotheendofthestring"talk?Excellentquestion:let’slookatwhatreallyhappened.
TheJavaVirtualMachine(JVM)tookthevalueofstrings(whichwas"abcdef")andtacked"more
stuff"ontotheend,givingusthevalue"abcdefmorestuff".Sincestringsareimmutable,theJVM
couldn’tstuffthisnewvalueintotheoldStringreferencedbys,soitcreatedanewStringobject,gave
itthevalue"abcdefmorestuff",andmadesrefertoit.Atthispointinourexample,wehavetwo
Stringobjects:thefirstonewecreated,withthevalue"abcdef",andthesecondonewiththevalue
"abcdefmorestuff".TechnicallytherearenowthreeStringobjects,becausetheliteralargumentto
concat,"morestuff",isitselfanewStringobject.Butwehavereferencesonlyto"abcdef"
(referencedbys2)and"abcdefmorestuff"(referencedbys).
Whatifwedidn’thavetheforesightorlucktocreateasecondreferencevariableforthe"abcdef"
stringbeforewecalleds=s.concat("morestuff");?Inthatcase,theoriginal,unchangedstring
containing"abcdef"wouldstillexistinmemory,butitwouldbeconsidered"lost."Nocodeinour
programhasanywaytoreferenceit—itislosttous.Note,however,thattheoriginal"abcdef"string
didn’tchange(itcan’t,remember;it’simmutable);onlythereferencevariableswaschangedsothatit
wouldrefertoadifferentstring.
Figure6-1showswhathappensontheheapwhenyoureassignareferencevariable.Notethatthe
dashedlineindicatesadeletedreference.
FIGURE6-1 Stringobjectsandtheirreferencevariables
Toreviewourfirstexample:
Let’slookatanotherexample:
Thefirstlineisstraightforward:CreateanewStringobject,giveitthevalue“Java”,andreferxtoit.
NexttheJVMcreatesasecondStringobjectwiththevalue“JavaRules!”butnothingreferstoit.The
secondStringobjectisinstantlylost;youcan’tgettoit.Thereferencevariablexstillreferstothe
originalStringwiththevalue“Java”.Figure6-2showscreatingaStringwithoutassigninga
referencetoit.
FIGURE6-2 AStringobjectisabandoneduponcreation.
Let’sexpandthiscurrentexample.Westartedwith
Nowlet’sadd
(WeactuallydidjustcreateanewStringobjectwiththevalue"JAVA",butitwaslost,andxstill
referstotheoriginalunchangedstring"Java".)Howaboutaddingthis:
Canyoudeterminewhathappened?TheJVMcreatedyetanothernewStringobject,withthevalue
"JXvX",(replacingthea’swithX’s),butonceagainthisnewStringwaslost,leavingxtorefertothe
originalunchangedandunchangeableStringobject,withthevalue"Java".Inallthesecases,wecalled
variousstringmethodstocreateanewStringbyalteringanexistingString,butweneverassignedthe
newlycreatedStringtoareferencevariable.
Butwecanputasmallspinonthepreviousexample:
Thistime,whentheJVMrunsthesecondline,anewStringobjectiscreatedwiththevalue"Java
Rules!",andxissettoreferenceit.Butwait…there’smore—nowtheoriginalStringobject,"Java",
hasbeenlost,andnooneisreferringtoit.Soinbothexamples,wecreatedtwoStringobjectsandonly
onereferencevariable,sooneofthetwoStringobjectswasleftoutinthecold.(SeeFigure6-3fora
graphicdepictionofthissadstory.)
FIGURE6-3 AnoldStringobjectbeingabandoned.Thedashedlineindicatesadeletedreference.
Let’stakethisexamplealittlefurther:
TheprecedingdiscussioncontainsthekeystounderstandingJavastringimmutability.Ifyoureally,
reallygettheexamplesanddiagrams,backwardandforward,youshouldget80percentoftheString
questionsontheexamcorrect.
Wewillcovermoredetailsaboutstringsnext,butmakenomistake—intermsofbangforyourbuck,
whatwe’vealreadycoveredisbyfarthemostimportantpartofunderstandinghowStringobjectswork
inJava.
We’llfinishthissectionbypresentinganexampleofthekindofdevilishStringquestionyoumight
expecttoseeontheexam.Takethetimetoworkitoutonpaper.(Hint:trytokeeptrackofhowmany
objectsandreferencevariablesthereare,andwhichonesrefertowhich.)
Whatistheoutput?Forextracredit,howmanyStringobjectsandhowmanyreferencevariables
werecreatedpriortotheprintlnstatement?
Answer:Theresultofthiscodefragmentisspringwinterspringsummer.Therearetworeference
variables:s1ands2.AtotalofeightStringobjectswerecreatedasfollows:"spring","summer"
(lost),"springsummer","fall"(lost),"springfall"(lost),"springsummerspring"(lost),
"winter"(lost),"springwinter"(atthispoint"spring"islost).OnlytwooftheeightString
objectsarenotlostinthisprocess.
ImportantFactsAboutStringsandMemory
Inthissection,we’lldiscusshowJavahandlesStringobjectsinmemoryandsomeofthereasons
behindthesebehaviors.
Oneofthekeygoalsofanygoodprogramminglanguageistomakeefficientuseofmemory.Asan
applicationgrows,it’sverycommonforstringliteralstooccupylargeamountsofaprogram’smemory,
andthereisoftenalotofredundancywithintheuniverseofStringliteralsforaprogram.TomakeJava
morememoryefficient,theJVMsetsasideaspecialareaofmemorycalledtheStringconstantpool.
WhenthecompilerencountersaStringliteral,itchecksthepooltoseeifanidenticalStringalready
exists.Ifamatchisfound,thereferencetothenewliteralisdirectedtotheexistingString,andnonew
Stringliteralobjectiscreated.(TheexistingStringsimplyhasanadditionalreference.)Nowyoucan
starttoseewhymakingStringobjectsimmutableissuchagoodidea.Ifseveralreferencevariables
refertothesameStringwithoutevenknowingit,itwouldbeverybadifanyofthemcouldchangethe
String’svalue.
Youmightsay,"Wellthat’sallwellandgood,butwhatifsomeoneoverridestheStringclass
functionality;couldn’tthatcauseproblemsinthepool?"That’soneofthemainreasonsthattheString
classismarkedfinal.NobodycanoverridethebehaviorsofanyoftheStringmethods,soyoucanrest
assuredthattheStringobjectsyouarecountingontobeimmutablewill,infact,beimmutable.
CreatingNewStrings
Earlierwepromisedtotalkmoreaboutthesubtledifferencesbetweenthevariousmethodsofcreatinga
String.Let’slookatacoupleofexamplesofhowaStringmightbecreated,andlet’sfurtherassume
thatnootherStringobjectsexistinthepool.Inthissimplecase,"abc"willgointhepool,andswill
refertoit:
Inthenextcase,becauseweusedthenewkeyword,JavawillcreateanewStringobjectinnormal
(nonpool)memory,andswillrefertoit.Inaddition,theliteral"abc"willbeplacedinthepool:
ImportantMethodsintheStringClass
ThefollowingmethodsaresomeofthemorecommonlyusedmethodsintheStringclass,andtheyare
alsotheonesyou’remostlikelytoencounterontheexam.
charAt()Returnsthecharacterlocatedatthespecifiedindex
concat()Appendsonestringtotheendofanother(+alsoworks)
equalsIgnoreCase()Determinestheequalityoftwostrings,ignoringcase
length()Returnsthenumberofcharactersinastring
replace()Replacesoccurrencesofacharacterwithanewcharacter
substring()Returnsapartofastring
toLowerCase()Returnsastring,withuppercasecharactersconvertedtolowercase
toString()Returnsthevalueofastring
toUpperCase()Returnsastring,withlowercasecharactersconvertedtouppercase
trim()Removeswhitespacefrombothendsofastring
Let’slookatthesemethodsinmoredetail.
publiccharcharAt(intindex)
ThismethodreturnsthecharacterlocatedattheString’sspecifiedindex.Remember,Stringindexes
arezero-based—here’sanexample:
publicStringconcat(Strings)
ThismethodreturnsastringwiththevalueoftheStringpassedintothemethodappendedtotheendof
theStringusedtoinvokethemethod—here’sanexample:
Theoverloaded+and+=operatorsperformfunctionssimilartotheconcat()method—here’san
example:
Inthepreceding"Atlanticocean"example,noticethatthevalueofxreallydidchange!Remember
the+=operatorisanassignmentoperator,soline2isreallycreatinganewstring,"Atlanticocean",
andassigningittothexvariable.Afterline2executes,theoriginalstringxwasreferringto,
"Atlantic",isabandoned.
publicbooleanequalsIgnoreCase(Strings)
Thismethodreturnsabooleanvalue(trueorfalse)dependingonwhetherthevalueoftheStringin
theargumentisthesameasthevalueoftheStringusedtoinvokethemethod.Thismethodwillreturn
trueevenwhencharactersintheStringobjectsbeingcomparedhavedifferingcases—here’san
example:
publicintlength()
ThismethodreturnsthelengthoftheStringusedtoinvokethemethod—here’sanexample:
Arrayshaveanattribute(notamethod)calledlength.Youmayencounterquestionsinthe
examthatattempttousethelength()methodonanarrayorthatattempttousethelength
attributeonaString.Bothcausecompilererrors–considerthese,forexample:
and
publicStringreplace(charold,charnew)
ThismethodreturnsaStringwhosevalueisthatoftheStringusedtoinvokethemethod,butupdated
sothatanyoccurrenceofthecharinthefirstargumentisreplacedbythecharinthesecondargument—
here’sanexample:
publicStringsubstring(intbegin)andpublicStringsubstring(intbegin,intend)
Thesubstring()methodisusedtoreturnapart(orsubstring)oftheStringusedtoinvokethemethod.
Thefirstargumentrepresentsthestartinglocation(zero-based)ofthesubstring.Ifthecallhasonlyone
argument,thesubstringreturnedwillincludethecharactersattheendoftheoriginalString.Ifthecall
hastwoarguments,thesubstringreturnedwillendwiththecharacterlocatedinthenthpositionofthe
originalStringwherenisthesecondargument.Unfortunately,theendingargumentisnotzero-based,so
ifthesecondargumentis7,thelastcharacterinthereturnedStringwillbeintheoriginalString’s7
position,whichisindex6(ouch).Let’slookatsomeexamples:
Thefirstexampleshouldbeeasy:startatindex5andreturntherestoftheString.Thesecondexample
shouldbereadasfollows:startatindex5andreturnthecharactersuptoandincludingthe8thposition
(index7).
publicStringtoLowerCase()
ConvertsallcharactersofaStringtolowercase—here’sanexample:
publicStringtoString()
ThismethodreturnsthevalueoftheStringusedtoinvokethemethod.What?Whywouldyouneedsuch
aseemingly"donothing"method?AllobjectsinJavamusthaveatoString()method,whichtypically
returnsaStringthatinsomemeaningfulwaydescribestheobjectinquestion.InthecaseofaString
object,what’samoremeaningfulwaythantheString’svalue?Forthesakeofconsistency,here’san
example:
publicStringtoUpperCase()
ConvertsallcharactersofaStringtouppercase–here’sanexample:
publicStringtrim()
ThismethodreturnsaStringwhosevalueistheStringusedtoinvokethemethod,butwithanyleading
ortrailingwhitespaceremoved—here’sanexample:
TheStringBuilderClass
Thejava.lang.StringBuilderclassshouldbeusedwhenyouhavetomakealotofmodificationsto
stringsofcharacters.Asdiscussedintheprevioussection,Stringobjectsareimmutable,soifyou
choosetodoalotofmanipulationswithStringobjects,youwillendupwithalotofabandonedString
objectsintheStringpool.(EveninthesedaysofgigabytesofRAM,it’snotagoodideatowaste
preciousmemoryondiscardedStringpoolobjects.)Ontheotherhand,objectsoftypeStringBuilder
canbemodifiedoverandoveragainwithoutleavingbehindagreateffluenceofdiscardedString
objects.
AcommonuseforStringBuildersisfileI/Owhenlarge,ever-changingstreamsofinputarebeing
handledbytheprogram.Inthesecases,largeblocksofcharactersarehandledasunits,and
StringBuilderobjectsaretheidealwaytohandleablockofdata,passiton,andthenreusethe
samememorytohandlethenextblockofdata.
PreferStringBuildertoStringBuffer
TheStringBuilderclasswasaddedinJava5.IthasexactlythesameAPIastheStringBufferclass,
exceptStringBuilderisnotthread-safe.Inotherwords,itsmethodsarenotsynchronized.Oracle
recommendsthatyouuseStringBuilderinsteadofStringBufferwheneverpossible,because
StringBuilderwillrunfaster(andperhapsjumphigher).Soapartfromsynchronization,anythingwe
sayaboutStringBuilder’smethodsholdstrueforStringBuffer’smethods,andviceversa.Thatsaid,
fortheOCA8exam,StringBufferisnottested.
UsingStringBuilder(andThisIstheLastTimeWe’llSayThis:StringBuffer)
Intheprevioussection,yousawhowtheexammighttestyourunderstandingofStringimmutabilitywith
codefragmentslikethis:
Becausenonewassignmentwasmade,thenewStringobjectcreatedwiththeconcat()methodwas
abandonedinstantly.Youalsosawexampleslikethis:
WegotanicenewStringoutofthedeal,butthedownsideisthattheoldString"abc"hasbeenlostin
theStringpool,thuswastingmemory.IfwewereusingaStringBuilderinsteadofaString,thecode
wouldlooklikethis:
AlloftheStringBuildermethodswewilldiscussoperateonthevalueoftheStringBuilderobject
invokingthemethod.Soacalltosb.append("def");isactuallyappending"def"toitself
(StringBuildersb).Infact,thesemethodcallscanbechainedtoeachother—here’sanexample:
Noticethatineachoftheprevioustwoexamples,therewasasinglecalltonew,soineachexample
weweren’tcreatinganyextraobjects.EachexampleneededonlyasingleStringBuilderobjectto
execute.
Sofarwe’veseenStringBuildersbeingbuiltwithanargumentspecifyinganinitialvalue.
StringBuilderscanalsobebuiltempty,andtheycanalsobeconstructedwithaspecificsize
or,moreformally,a"capacity."Fortheexam,therearethreewaystocreateanew
StringBuilder:
ThetwomostcommonwaystoworkwithStringBuildersisviaanappend()methodoran
insert()method.IntermsofaStringBuilder’scapacity,therearethreerulestokeepin
mindwhenappendingandinserting:
Ifanappend()growsaStringBuilderpastitscapacity,thecapacityisupdated
automatically.
Ifaninsert()startswithinaStringBuilder’scapacitybutendsafterthecurrent
capacity,thecapacityisupdatedautomatically.
Ifaninsert()attemptstostartatanindexaftertheStringBuilder’scurrentlength,
anexceptionwillbethrown.
ImportantMethodsintheStringBuilderClass
TheStringBuilderclasshasazillionmethods.Followingarethemethodsyou’remostlikelytousein
therealworldand,happily,theonesyou’remostlikelytofindontheexam.
publicStringBuilderappend(Strings)
Asyou’veseenearlier,thismethodwillupdatethevalueoftheobjectthatinvokedthemethod,whether
ornotthereturnedvalueisassignedtoavariable.Versionsofthisheavilyoverloadedmethodwilltake
manydifferentarguments,includingboolean,char,double,float,int,long,andothers,buttheone
mostlikelyusedontheexamwillbeaStringargument—forexample,
publicStringBuilderdelete(intstart,intend)
ThismethodmodifiesthevalueoftheStringBuilderobjectusedtoinvokeit.Thestartingindexofthe
substringtoberemovedisdefinedbythefirstargument(whichiszero-based),andtheendingindexofthe
substringtoberemovedisdefinedbythesecondargument(butitisone-based)!Studythefollowing
examplecarefully:
TheexamwillprobablytestyourknowledgeofthedifferencebetweenStringand
StringBuilderobjects.BecauseStringBuilderobjectsarechangeable,thefollowingcode
fragmentwillbehavedifferentlythanasimilarcodefragmentthatusesStringobjects:
Inthiscase,theoutputwillbe:"abcdef"
publicStringBuilderinsert(intoffset,Strings)
ThismethodupdatesthevalueoftheStringBuilderobjectthatinvokedthemethodcall.TheString
passedintothesecondargumentisinsertedintotheStringBuilderstartingattheoffsetlocation
representedbythefirstargument(theoffsetiszero-based).Again,othertypesofdatacanbepassedin
throughthesecondargument(boolean,char,double,float,int,long,andsoon),buttheStringargument
istheoneyou’remostlikelytosee:
publicStringBuilderreverse()
ThismethodupdatesthevalueoftheStringBuilderobjectthatinvokedthemethodcall.Wheninvoked,
thecharactersintheStringBuilderarereversed—thefirstcharacterbecomingthelast,thesecond
becomingthesecondtothelast,andsoon:
publicStringtoString()
ThismethodreturnsthevalueoftheStringBuilderobjectthatinvokedthemethodcallasaString:
That’sitforStringBuilders.Ifyoutakeonlyonethingawayfromthissection,it’sthatunlikeString
objects,StringBuilderobjectscanbechanged.
Manyoftheexamquestionscoveringthischapter’stopicsuseatrickybitofJavasyntax
knownas“chainedmethods.”Astatementwithchainedmethodshasthisgeneralform:
result=method1().method2().method3();
Intheory,anynumberofmethodscanbechainedinthisfashion,althoughtypicallyyouwon’t
seemorethanthree.Here’showtodecipherthese"handyJavashortcuts"whenyouencounter
them:
1.Determinewhattheleftmostmethodcallwillreturn(let’scallitx).
2.Usexastheobjectinvokingthesecond(fromtheleft)method.Ifthereareonlytwo
chainedmethods,theresultofthesecondmethodcallistheexpression’sresult.
3.Ifthereisathirdmethod,theresultofthesecondmethodcallisusedtoinvokethe
thirdmethod,whoseresultistheexpression’sresult–forexample,
Let’slookatwhathappened.Theliteraldefwasconcatenatedtoabc,creatingatemporary,
intermediateString(soontobelost),withthevalueabcdef.ThetoUpperCase()methodwas
calledonthisString,whichcreatedanew(soontobelost)temporaryStringwiththevalue
ABCDEF.Thereplace()methodwasthencalledonthissecondStringobject,whichcreateda
finalStringwiththevalueABxDEFandreferredytoit.
CERTIFICATIONOBJECTIVE
WorkingwithCalendarData(OCAObjective9.3)
9.3Createandmanipulatecalendardatausingthefollowingclasses:java.time.LocalDateTime,
java.time.LocalDate,java.time.LocalTime,java.time.format.DateTimeFormatter,java.time.Period
Java8introducedalargecollection(argh)ofnewpackagesrelatedtoworkingwithcalendars,dates,
andtimes.TheOCA8creatorschosetoincludeknowledgeofasubsetofthesepackagesandclassesas
anexamobjective.Ifyouunderstandtheclassesincludedintheexamobjective,you’llhaveagood
introductiontotheentirecalendar/date/timetopic.Asweworkthroughthissection,we’llusethephrase
"calendarobject,"whichweusetorefertoobjectsofoneoftheseveraltypesofcalendar-relatedclasses
we’recovering.So"calendarobject"isamade-upumbrellaterm.Here’sasummaryofthefivecalendar-
relatedclasseswe’llstudy,plusaninterfacethatloomslarge:
java.time.LocalDateTimeThisclassisusedtocreateimmutableobjects,eachofwhich
representsaspecificdateandtime.Additionally,thisclassprovidesmethodsthatcanmanipulate
thevaluesofthedate/timeobjectscreatedandassignthemtonewimmutableobjects.
LocalDateTimeobjectscontainBOTHinformationaboutdays,months,andyears,ANDabout
hours,minutes,seconds,andfractionsofseconds.
java.time.LocalDateThisclassisusedtocreateimmutableobjects,eachofwhich
representsaspecificdate.Additionally,thisclassprovidesmethodsthatcanmanipulatethevalues
ofthedateobjectscreatedandassignthemtonewimmutableobjects.LocalDateobjectsare
accurateonlytodays.Hours,minutes,andsecondsarenotpartofaLocalDateobject.
java.time.LocalTimeThisclassisusedtocreateimmutableobjects,eachofwhich
representsaspecifictime.Additionally,thisclassprovidesmethodsthatcanmanipulatethevalues
ofthetimeobjectscreatedandassignthemtonewimmutableobjects.LocalTimeobjectsrefer
onlytohours,minutes,seconds,andfractionsofseconds.Days,months,andyearsarenotapartof
LocalTimeobjects.
java.time.format.DateTimeFormatterThisclassisusedbytheclassesjustdescribedto
formatdate/timeobjectsforoutputandtoparseinputstringsandconvertthemtodate/timeobjects.
DateTimeFormatterobjectsarealsoimmutable.
java.time.PeriodThisclassisusedtocreateimmutableobjectsthatrepresentaperiodof
time,forexample,"oneyear,twomonths,andthreedays."Thisclassworksinyears,months,and
days.Ifyouwanttorepresentchunksoftimeinincrementsfinerthanaday(e.g.,hoursand
minutes),youcanusethejava.time.Durationclass,butDurationisnotontheexam.
java.time.temporal.TemporalAmountThisinterfaceisimplementedbythePeriodclass.
WhenyouusePeriodobjectstomanipulate(seethefollowingsection),calendarobjects,you’ll
oftenusemethodsthattakeobjectsthatimplementTemporalAmount.Ingeneral,asyouusethe
JavaAPImoreandmore,it’sagoodideatolearnwhichclassesimplementwhichinterfaces;this
isakeywaytolearnhowtheclassesincomplexpackagesinteractwitheachother.
Immutability
Thereareacoupleofrecurringthemesinthepreviousdefinitions.First,noticethatmostofthecalendar-
relatedobjectsyou’llcreateareimmutable.JustlikeStringobjects!Sowhenwesaywe’regoingto
"manipulate"acalendarobject,whatwe"really"meanisthatwe’llinvokeamethodonacalendar
object,andwe’llreturnanewcalendarobjectthatrepresentstheresultofmanipulatingthevalueofthe
originalcalendarobject.Buttheoriginalcalendarobject’svalueisnot,andcannot,bechanged.Justlike
Strings!Let’sseeanexample:
whichproduces:
2017-01-31
2017-01-31
2017-02-28
Noticethatinvokingtheplusmethodondate1doesn’tchangeitsvalue,butassigningtheresultofthe
plusmethodtodate2capturesanewvalue.Expectexamquestionsthattestyourunderstandingofthe
immutabilityofcalendarobjects.
FactoryClasses
Thenextthingtonoticeinthepreviouscodelistingisthatweneverusedthekeywordnewinthecode.
Wedidn’tdirectlyinvokeaconstructor.NoneofthefiveclasseslistedinOCA8objective9.3have
publicconstructors.Instead,foralltheseclasses,youinvokeapublicstaticmethodintheclassto
createanewobject.AsyougofurtherintoyourstudiesofOOdesign,you’llcomeacrossthephrases
"factorypattern,""factorymethods,"and"factoryclasses."Usually,whenaclasshasnopublic
constructorsandprovidesatleastonepublicstaticmethodthatcancreatenewinstancesoftheclass,
thatclassiscalledafactoryclass,andanymethodthatisinvokedtogetanewinstanceoftheclassis
calledafactorymethod.Therearemanygoodreasonstocreatefactoryclasses,mostofwhichare
beyondthescopeofthisbook,butoneofthemwewilldiscussnow.IfweusetheLocalDateclassasan
example,wefindthefollowingstaticmethodsthatcreateandreturnanewinstance:
Sowehavewhat,abouttendifferentwaystocreateanewLocalDateobject?Byusingmethodswith
differentnames(insteadofusingoverloadedconstructors),themethodnamesthemselvesmakethecode
morereadable.It’sclearerwhatvariationofLocalDatewe’remaking.Asyouusemoreandmore
classesfromtheJavaAPI,you’lldiscoverthattheAPIcreatorsusefactoryclassesalot.
Wheneveryouseeanexamquestionrelatingtodatesortimes,beonthelookoutforthenew
keyword.Thisisyourtipoffthatthecodewon’tcompile:
LocalDateTimed1=newLocalDateTime();//won’tcompile
Remembertheexam’sdateandtimeclassesusefactorymethodstocreatenewobjects.
UsingandManipulatingDatesandTimes
Nowthatweknowhowtocreatenewcalendar-relatedobjects,let’sturntousingandmanipulatingthem.
(Andyouknowwhatwemeanwhenwesay"manipulate.")Thefollowingcodedemonstratessome
commonusesandpowerfulfeaturesofthenewJava8calendar-relatedclasses:
Invokingtheprogramwitharelevantbirthday:
java01201934
producestheoutput(whenrunonJanuary13,2017):
There’salotgoingonhere,solet’sdoawalk-through.First,wewantuserstoentertheirbirthdayin
theformofmmddyyyy.WeuseaDateTimeFormatterobjecttoparsetheuser’sfirstargumentandverify
thatit’savaliddateoftheformwe’rehopingfor.UsuallyintheJavaAPI,parse()methodscanthrow
exceptions,sowehavetodoourparsinginatry/catchblock.
Next,weprintouttheverifieddateandshowoffabitbyprintingoutwhatdayoftheweekthatdate
occurredon.Thiscalculationwouldbequitetrickytodobyhand!
Next,wecreateaPeriodobjectthatrepresentstheamountoftimebetweentheuser’sbirthdayand
today,andweusevariousgetX()methodstolistthedetailsofthePeriodobject.
Aftermakingsurewe’renotdealingwithatimelord,wethenusetheverypowerfuluntil()method
and"day"astheunitoftimetodeterminehowmanydaystheuserhasbeenalive.Wecheatedabithere
andusedtheChronoUnitenumfromthejava.time.temporalpackage.(EventhoughChronoUnitisn’t
ontheexam,wethinkifyoudoalotofcalendarcalculations,you’llendupusingthisenumalot.)
Next,weadd30,000daystotheuser’sbirthdaysowecancalculateonwhichdateouruserwillhave
livedfor30,000days.It’sashortjumptoseeinghowthesesortsofcalendarcalculationswillbevery
powerfulforschedulingapplications,projectmanagementapplications,travelplanning,andsoon.
Finally,weuseacommonfactorymethod,of(),tocreateanotherdateobject(representingtoday’s
date),andweusethatinconjunctionwiththeverypowerfulbetween()methodtoseehowlongit’sbeen
sinceJanuary1,2000,Y2K.
FormattingDatesandTimes
Nowlet’sturntoformattingdatesandtimesusingtheDateTimeFormatterclass,soyourcalendar
objectswilllookallshinywhenyouwanttoincludetheminyourprogram’soutput.Fortheexam,you
shouldknowthefollowingtwo-stepprocessforcreatingStringsthatrepresentwell-formattedcalendar
objects:
1.UseformattersandpatternsfromtheHUGElistsprovidedintheDateTimeFormatterclass
tocreateaDataTimeFormatterobject.
2.IntheLocalDate,LocalDateTime,andLocalTimeclasses,usetheformat()methodwith
theDateTimeFormatterobjectastheargumenttocreateawell-formedString—orusethe
DateTimeFormatter.format()methodwithacalendarargumenttocreateawell-formedString.
Let’slookatafewexamples:
which,whenweranthiscode,producedthefollowing(youroutputwillvary):
Jan14,2017
SatJan14,2017AD
14:17:951429958PM
Someofthepatterncodesweusedareself-evident(e.g.MMMddyyyy),andsomearefairlyarbitrary
like"E"fordayofweekor"k"formilitaryhours.Allofthecodescanbefoundinthe
DateTimeFormatterAPI.
That’senoughaboutcalendars;ontoarrays!
CERTIFICATIONOBJECTIVE
UsingArrays(OCAObjectives4.1and4.2)
4.1Declare,instantiate,initialize,anduseaone-dimensionalarray.
4.2Declare,instantiate,initialize,anduseamulti-dimensionalarray.
ArraysareobjectsinJavathatstoremultiplevariablesofthesametype.Arrayscanholdeither
primitivesorobjectreferences,butthearrayitselfwillalwaysbeanobjectontheheap,evenifthearray
isdeclaredtoholdprimitiveelements.Inotherwords,thereisnosuchthingasaprimitivearray,butyou
canmakeanarrayofprimitives.Forthisobjective,youneedtoknowthreethings:
Howtomakeanarrayreferencevariable(declare)
Howtomakeanarrayobject(construct)
Howtopopulatethearraywithelements(initialize)
Thereareseveraldifferentwaystodoeachofthese,andyouneedtoknowaboutallofthemfortheexam.
Arraysareefficient,butmostofthetimeyou’llwanttouseoneoftheCollectiontypesfrom
java.util(includingHashMap,ArrayList,andTreeSet).Collectionclassesoffermoreflexible
waystoaccessanobject(forinsertion,deletion,andsoon),andunlikearrays,theycanexpandor
contractdynamicallyasyouaddorremoveelements(they’rereallymanagedarrays,sincetheyuse
arraysbehindthescenes).There’saCollectiontypeforawiderangeofneeds.Doyouneedafast
sort?Agroupofobjectswithnoduplicates?Awaytoaccessaname/valuepair?Alinkedlist?The
OCP8examcoverscollectionsinmoredetail.
DeclaringanArray
Arraysaredeclaredbystatingthetypeofelementthearraywillhold,whichcanbeanobjectora
primitive,followedbysquarebracketstotheleftorrightoftheidentifier.
Declaringanarrayofprimitives:
Declaringanarrayofobjectreferences:
Whendeclaringanarrayreference,youshouldalwaysputthearraybracketsimmediatelyafterthe
declaredtyperatherthanaftertheidentifier(variablename).Thatway,anyonereadingthecodecan
easilytellthat,forexample,keyisareferencetoanintarrayobjectandnotanintprimitive.
Wecanalsodeclaremultidimensionalarrays,whichare,infact,arraysofarrays.Thiscanbedonein
thefollowingmanner:
Thefirstexampleisathree-dimensionalarray(anarrayofarraysofarrays)andthesecondisatwo-
dimensionalarray.Noticeinthesecondexamplewehaveonesquarebracketbeforethevariablename
andoneafter.Thisisperfectlylegaltothecompiler,provingonceagainthatjustbecauseit’slegal
doesn’tmeanit’sright.
Itisneverlegaltoincludethesizeofthearrayinyourdeclaration.Yes,weknowyoucandothatin
someotherlanguages,whichiswhyyoumightseeaquestionortwointheexamthatincludecodesimilar
tothefollowing:
int[5]scores;//willNOTcompile
Theprecedingcodewon’tmakeitpastthecompiler.Remember,theJVMdoesn’tallocatespaceuntilyou
actuallyinstantiatethearrayobject.That’swhensizematters.
ConstructinganArray
Constructinganarraymeanscreatingthearrayobjectontheheap(whereallobjectslive)—thatis,doing
anewonthearraytype.Tocreateanarrayobject,Javamustknowhowmuchspacetoallocateonthe
heap,soyoumustspecifythesizeofthearrayatcreationtime.Thesizeofthearrayisthenumberof
elementsthearraywillhold.
ConstructingOne-DimensionalArrays
Themoststraightforwardwaytoconstructanarrayistousethekeywordnewfollowedbythearraytype,
withabracketspecifyinghowmanyelementsofthattypethearraywillhold.Thefollowingisanexample
ofconstructinganarrayoftypeint:
Theprecedingcodeputsonenewobjectontheheap—anarrayobjectholdingfourelements—witheach
elementcontaininganintwithadefaultvalueof0.Thinkofthiscodeassayingtothecompiler,"Create
anarrayobjectthatwillholdfourints,andassignittothereferencevariablenamedtestScores.Also,
goaheadandseteachintelementtozero.Thanks."(Thecompilerappreciatesgoodmanners.)
Figure6-4showsthetestScoresarrayontheheap,afterconstruction.
FIGURE6-4 Aone-dimensionalarrayontheheap
Youcanalsodeclareandconstructanarrayinonestatement,asfollows:
int[]testScores=newint[4];
Thissinglestatementproducesthesameresultasthetwopreviousstatements.
Arraysofobjecttypescanbeconstructedinthesameway:
Rememberthat,despitehowthecodeappears,theThreadconstructorisnotbeinginvoked.We’renot
creatingaThreadinstance,butratherasingleThreadarrayobject.Aftertheprecedingstatement,there
arestillnoactualThreadobjects!
Thinkcarefullyabouthowmanyobjectsareontheheapafteracodestatementorblock
executes.Theexamwillexpectyoutoknow,forexample,thattheprecedingcodeproducesjust
oneobject(thearrayassignedtothereferencevariablenamedthreads).Thesingleobject
referencedbythreadsholdsfiveThreadreferencevariables,butnoThreadobjectshavebeen
createdorassignedtothosereferences.
Remember,arraysmustalwaysbegivenasizeatthetimetheyareconstructed.TheJVMneedsthesize
toallocatetheappropriatespaceontheheapforthenewarrayobject.Itisneverlegal,forexample,todo
thefollowing:
int[]carList=newint[];//Willnotcompile;needsasize
Sodon’tdoit,andifyouseeitonthetest,runscreamingtowardthenearestanswermarked"Compilation
fails."
Youmayseethewords"construct,""create,"and"instantiate"usedinterchangeably.Theyall
mean,"Anobjectisbuiltontheheap."Thisalsoimpliesthattheobject’sconstructorrunsas
aresultoftheconstruct/create/instantiatecode.Youcansaywithcertainty,forexample,that
anycodethatusesthekeywordnewwill(ifitrunssuccessfully)causetheclassconstructorand
allsuperclassconstructorstorun.
Inadditiontobeingconstructedwithnew,arrayscanbecreatedusingakindofsyntaxshorthandthat
createsthearraywhilesimultaneouslyinitializingthearrayelementstovaluessuppliedincode(as
opposedtodefaultvalues).We’lllookatthatinthenextsection.Fornow,understandthatbecauseof
thesesyntaxshortcuts,objectscanstillbecreatedevenwithoutyoueverusingorseeingthekeywordnew.
ConstructingMultidimensionalArrays
Multidimensionalarrays,remember,aresimplyarraysofarrays.Soatwo-dimensionalarrayoftypeint
isreallyanobjectoftypeintarray(int[]),witheachelementinthatarrayholdingareferenceto
anotherintarray.Theseconddimensionholdstheactualintprimitives.
Thefollowingcodedeclaresandconstructsatwo-dimensionalarrayoftypeint:
int[][]myArray=newint[3][];
Noticethatonlythefirstbracketsaregivenasize.That’sacceptableinJavabecausetheJVMneedsto
knowonlythesizeoftheobjectassignedtothevariablemyArray.
Figure6-5showshowatwo-dimensionalintarrayworksontheheap.
FIGURE6-5 Atwo-dimensionalarrayontheheap
InitializinganArray
Initializinganarraymeansputtingthingsintoit.The"things"inthearrayarethearray’selements,and
they’reeitherprimitivevalues(2,x,false,andsoon)orobjectsreferredtobythereferencevariablesin
thearray.Ifyouhaveanarrayofobjects(asopposedtoprimitives),thearraydoesn’tactuallyholdthe
objects—justasanyothernonprimitivevariableneveractuallyholdstheobject—butinsteadholdsa
referencetotheobject.Butwetalkaboutarraysas,forexample,"anarrayoffivestrings,"eventhough
whatwereallymeanis"anarrayoffivereferencestoStringobjects."Thenthebigquestionbecomes
whetherthosereferencesareactuallypointing(oops,thisisJava,wemeanreferring)torealString
objectsoraresimplynull.Remember,areferencethathasnothadanobjectassignedtoitisanull
reference.Andifyouactuallytrytousethatnullreferenceby,say,applyingthedotoperatorto
invokeamethodonit,you’llgettheinfamousNullPointerException.
Theindividualelementsinthearraycanbeaccessedwithanindexnumber.Theindexnumberalways
beginswithzero(0),soforanarrayoftenobjects,theindexnumberswillrunfrom0through9.Suppose
wecreateanarrayofthreeAnimalsasfollows:
Animal[]pets=newAnimal[3];
Wehaveonearrayobjectontheheap,withthreenullreferencesoftypeAnimal,butwedon’thave
anyAnimalobjects.ThenextstepistocreatesomeAnimalobjectsandassignthemtoindexpositionsin
thearrayreferencedbypets:
ThiscodeputsthreenewAnimalobjectsontheheapandassignsthemtothethreeindexpositions
(elements)inthepetsarray.
Lookforcodethattriestoaccessanout-of-rangearrayindex.Forexample,ifanarrayhas
threeelements,tryingtoaccesstheelement[3]willraisean
ArrayIndexOutOfBoundsException,becauseinanarrayofthreeelements,thelegalindex
valuesare0,1,and2.Youalsomightseeanattempttouseanegativenumberasanarray
index.Thefollowingareexamplesoflegalandillegalarrayaccessattempts.Besureto
recognizethatthesecauseruntimeexceptionsandnotcompilererrors!
Nearlyalltheexamquestionslistbothruntimeexceptionandcompilererroraspossible
answers:
numberThesecanbehardtospotinacomplexloop,butthat’swhereyou’remostlikelytosee
arrayindexproblemsinexamquestions.
Atwo-dimensionalarray(anarrayofarrays)canbeinitializedasfollows:
InitializingElementsinaLoop
Arrayobjectshaveasinglepublicvariable,length,thatgivesyouthenumberofelementsinthearray.
Thelastindexvalue,then,isalwaysonelessthanthelength.Forexample,ifthelengthofanarrayis
4,theindexvaluesarefrom0through3.Often,you’llseearrayelementsinitializedinaloop,asfollows:
Thelengthvariabletellsushowmanyelementsthearrayholds,butitdoesnottelluswhetherthose
elementshavebeeninitialized.
Declaring,Constructing,andInitializingonOneLine
Youcanusetwodifferentarray-specificsyntaxshortcutsbothtoinitialize(putexplicitvaluesintoan
array’selements)andconstruct(instantiatethearrayobjectitself)inasinglestatement.Thefirstisused
todeclare,create,andinitializeinonestatement,asfollows:
Line2intheprecedingcodedoesfourthings:
Declaresanintarrayreferencevariablenameddots.
Createsanintarraywithalengthofthree(threeelements).
Populatesthearray’selementswiththevalues6,9,and8.
Assignsthenewarrayobjecttothereferencevariabledots.
Thesize(lengthofthearray)isdeterminedbythenumberofcomma-separateditemsbetweenthecurly
braces.Thecodeisfunctionallyequivalenttothefollowinglongercode:
Thisbegsthequestion,"Whywouldanyoneusethelongerway?"Onereasoncomestomind.You
mightnotknow—atthetimeyoucreatethearray—thevaluesthatwillbeassignedtothearray’selements.
Withobjectreferencesratherthanprimitives,itworksexactlythesameway:
TheprecedingcodecreatesoneDogarray,referencedbythevariablemyDogs,withalengthofthree
elements.ItassignsapreviouslycreatedDogobject(assignedtothereferencevariablepuppy)tothefirst
elementinthearray.ItalsocreatestwonewDogobjects(CloverandAiko)andaddsthemtothelasttwo
DogreferencevariableelementsinthemyDogsarray.Thisarrayshortcutalone(combinedwiththe
stimulatingprose)isworththepriceofthisbook.Figure6-6showstheresult.
FIGURE6-6 Declaring,constructing,andinitializinganarrayofobjects
Youcanalsousetheshortcutsyntaxwithmultidimensionalarrays,asfollows:
int[][]scores={{5,2,4,7},{9,2},{3,4}};
Thiscodecreatesatotaloffourobjectsontheheap.First,anarrayofintarraysisconstructed(the
objectthatwillbeassignedtothescoresreferencevariable).Thescoresarrayhasalengthofthree,
derivedfromthenumberofcomma-separateditemsbetweentheoutercurlybraces.Eachofthethree
elementsinthescoresarrayisareferencevariabletoanintarray,sothethreeintarraysare
constructedandassignedtothethreeelementsinthescoresarray.
Thesizeofeachofthethreeintarraysisderivedfromthenumberofitemswithinthecorresponding
innercurlybraces.Forexample,thefirstarrayhasalengthoffour,thesecondarrayhasalengthoftwo,
andthethirdarrayhasalengthoftwo.Sofar,wehavefourobjects:onearrayofintarrays(each
elementisareferencetoanintarray),andthreeintarrays(eachelementinthethreeintarraysisan
intvalue).Finally,thethreeintarraysareinitializedwiththeactualintvalueswithintheinnercurly
braces.Thus,thefirstintarraycontainsthevalues5,2,4,7.Thefollowingcodeshowsthevaluesof
someoftheelementsinthistwo-dimensionalarray:
Figure6-7showstheresultofdeclaring,constructing,andinitializingatwo-dimensionalarrayinone
statement.
FIGURE6-7 Declaring,constructing,andinitializingatwo-dimensionalarray
ConstructingandInitializinganAnonymousArray
Thesecondshortcutiscalled"anonymousarraycreation"andcanbeusedtoconstructandinitializean
arrayandthenassignthearraytoapreviouslydeclaredarrayreferencevariable:
Theprecedingcodecreatesanewintarraywiththreeelements;initializesthethreeelementswiththe
values4,7,and2;andthenassignsthenewarraytothepreviouslydeclaredintarrayreferencevariable
testScores.Wecallthisanonymousarraycreationbecausewiththissyntax,youdon’tevenneedto
assignthenewarraytoanything.Maybeyou’rewondering,"Whatgoodisanarrayifyoudon’tassignitto
areferencevariable?"Youcanuseittocreateajust-in-timearraytouse,forexample,asanargumenttoa
methodthattakesanarrayparameter.
Thefollowingcodedemonstratesajust-in-timearrayargument:
Rememberthatyoudonotspecifyasizewhenusinganonymousarraycreationsyntax.The
sizeisderivedfromthenumberofitems(comma-separated)betweenthecurlybraces.Payvery
closeattentiontothearraysyntaxusedinexamquestions(andtherewillbealotofthem).You
mightseesyntaxsuchasthis:
LegalArrayElementAssignments
Whatcanyouputinaparticulararray?Fortheexam,youneedtoknowthatarrayscanhaveonlyone
declaredtype(int[],Dog[],String[],andsoon),butthatdoesn’tnecessarilymeanthatonlyobjects
orprimitivesofthedeclaredtypecanbeassignedtothearrayelements.Andwhataboutthearray
referenceitself?Whatkindofarrayobjectcanbeassignedtoaparticulararrayreference?Fortheexam,
you’llneedtoknowtheanswerstoallofthesequestions.And,asifbymagic,we’reactuallycovering
thoseverysametopicsinthefollowingsections.Payattention.
ArraysofPrimitivesPrimitivearrayscanacceptanyvaluethatcanbepromotedimplicitlytothe
declaredtypeofthearray.Forexample,anintarraycanholdanyvaluethatcanfitintoa32-bitint
variable.Thus,thefollowingcodeislegal:
ArraysofObjectReferencesIfthedeclaredarraytypeisaclass,youcanputobjectsofanysubclassof
thedeclaredtypeintothearray.Forexample,ifSubaruisasubclassofCar,youcanputbothSubaru
objectsandCarobjectsintoanarrayoftypeCarasfollows:
IthelpstorememberthattheelementsinaCararrayarenothingmorethanCarreferencevariables.So
anythingthatcanbeassignedtoaCarreferencevariablecanbelegallyassignedtoaCararrayelement.
Ifthearrayisdeclaredasaninterfacetype,thearrayelementscanrefertoanyinstanceofanyclass
thatimplementsthedeclaredinterface.Thefollowingcodedemonstratestheuseofaninterfaceasan
arraytype:
Thebottomlineisthis:anyobjectthatpassestheIS-Atestforthedeclaredarraytypecanbeassigned
toanelementofthatarray.
ArrayReferenceAssignmentsforOne-DimensionalArraysFortheexam,youneedtorecognizelegal
andillegalassignmentsforarrayreferencevariables.We’renottalkingaboutreferencesinthearray(in
otherwords,arrayelements),butratherreferencestothearrayobject.Forexample,ifyoudeclareanint
array,thereferencevariableyoudeclaredcanbereassignedtoanyintarray(ofanysize),butthe
variablecannotbereassignedtoanythingthatisnotanintarray,includinganintvalue.Remember,all
arraysareobjects,soanintarrayreferencecannotrefertoanintprimitive.Thefollowingcode
demonstrateslegalandillegalassignmentsforprimitivearrays:
It’stemptingtoassumethatbecauseavariableoftypebyte,short,orcharcanbeexplicitly
promotedandassignedtoanint,anarrayofanyofthosetypescouldbeassignedtoanintarray.You
can’tdothatinJava,butitwouldbejustlikethosecruel,heartless(butotherwiseattractive)exam
developerstoputtrickyarrayassignmentquestionsintheexam.
Arraysthatholdobjectreferences,asopposedtoprimitives,aren’tasrestrictive.Justasyoucanputa
HondaobjectinaCararray(becauseHondaextendsCar),youcanassignanarrayoftypeHondatoaCar
arrayreferencevariableasfollows:
ApplytheIS-Atesttohelpsortthelegalfromtheillegal.HondaIS-ACar,soaHondaarraycanbe
assignedtoaCararray.BeerIS-ACarisnottrue;BeerdoesnotextendCar(plusitdoesn’tmakesense,
unlessyou’vealreadyhadtoomuchofit).
Therulesforarrayassignmentapplytointerfacesaswellasclasses.Anarraydeclaredasaninterface
typecanreferenceanarrayofanytypethatimplementstheinterface.Remember,anyobjectfromaclass
implementingaparticularinterfacewillpasstheIS-A(instanceof)testforthatinterface.Forexample,
ifBoximplementsFoldable,thefollowingislegal:
Youcannotreversethelegalassignments.ACararraycannotbeassignedtoaHondaarray.A
CarisnotnecessarilyaHonda,soifyou’vedeclaredaHondaarray,itmightblowupifyou
assignedaCararraytotheHondareferencevariable.Thinkaboutit:aCararraycouldholda
referencetoaFerrari,sosomeonewhothinkstheyhaveanarrayofHondascouldsuddenly
findthemselveswithaFerrari.RememberthattheIS-Atestcanbecheckedincodeusingthe
instanceofoperator.
ArrayReferenceAssignmentsforMultidimensionalArraysWhenyouassignanarraytoapreviously
declaredarrayreference,thearrayyou’reassigningmustbeinthesamedimensionasthereferenceyou’re
assigningitto.Forexample,atwo-dimensionalarrayofintarrayscannotbeassignedtoaregularint
arrayreference,asfollows:
Payparticularattentiontoarrayassignmentsusingdifferentdimensions.Youmight,forexample,be
askedifit’slegaltoassignanintarraytothefirstelementinanarrayofintarrays,asfollows:
2.5DevelopcodethatuseswrapperclassessuchasBoolean,Double,andInteger.
Datastructuresareapartofalmosteveryapplicationyou’lleverworkon.TheJavaAPIprovides
anextensiverangeofclassesthatsupportcommondatastructuressuchasLists,Sets,Maps,and
Queues.ForthepurposeoftheOCAexam,youshouldrememberthattheclassesthatsupportthese
commondatastructuresareapartofwhatisknownas"TheCollectionAPI"(oneofitsmanyaliases).
(TheOCPexamcoversthemostcommonimplementationsofallthesestructures.)
WhentoUseArrayLists
We’vealreadytalkedaboutarrays.Arraysseemusefulandprettydarnedflexible.Sowhydoweneed
morefunctionalitythanarraysprovide?Considerthesetwosituations:
Youneedtobeabletoincreaseanddecreasethesizeofyourlistofthings.
Theorderofthingsinyourlistisimportantandmightchange.
Bothsituationscanbehandledwitharrays,butit’snoteasy….
SupposeyouwanttoplanavacationtoEurope.Youhaveseveraldestinationsinmind(Paris,Oslo,
Rome),butyou’renotyetsureinwhatorderyouwanttovisitthesecities,andasyourplanning
progresses,youmightwanttoaddorsubtractcitiesfromyourlist.Let’ssayyourfirstideaistotravel
fromnorthtosouth,soyourlistlookslikethis:
Oslo,Paris,Rome.
Ifwewereusinganarray,wecouldstartwiththis:
String[]cities={"Oslo","Paris","Rome"};
ButnowimaginethatyourememberthatyouREALLYwanttogotoLondon,too!You’vegottwo
problems:
Yourcitiesarrayisalreadyfull.
Ifyou’regoingfromnorthtosouth,youneedtoinsertLondonbeforeParis.
Ofcourse,youcanfigureoutawaytodothis.Maybeyoucreateasecondarray,andyoucopycities
fromonearraytotheother,andatthecorrectmomentyouaddLondontothesecondarray.Doable,but
difficult.
Nowlet’sseehowyoucoulddothesamethingwithanArrayList:
Theoutputwillbesomethinglikethis:
Byreviewingthecode,wecanlearnsomeimportantfactsaboutArrayLists:
TheArrayListclassisinthejava.utilpackage.
Similartoarrays,whenyoubuildanArrayList,youhavetodeclarewhatkindofobjectsit
cancontain.Inthiscase,we’rebuildinganArrayListofStringobjects.(We’lllookatthelineof
codethatcreatestheArrayListinalotmoredetailinaminute.)
ArrayListimplementstheListinterface.
WeworkwiththeArrayListthroughmethods.Inthiscaseweusedacoupleofversionsof
add();weusedindexOf();and,indirectly,weusedtoString()todisplaytheArrayList’s
contents.(MoreontoString()inaminute.)
Likearrays,indexesforArrayListsarezero-based.
Wedidn’tdeclarehowbigtheArrayListwaswhenwebuiltit.
WewereabletoaddanewelementtotheArrayListonthefly.
Wewereabletoaddthenewelementinthemiddleofthelist.
TheArrayListmaintaineditsorder.
Aspromised,weneedtolookatthefollowinglineofcodemoreclosely:
List<String>c=newArrayList<String>();
Firstoff,weseethatthisisapolymorphicdeclaration.Aswesaidearlier,ArrayListimplementsthe
Listinterface(alsoinjava.util).IfyouplantotaketheOCP8examafteryou’veacedtheOCA8,
you’lllearnalotmoreaboutwhywemightwanttodoapolymorphicdeclaration.Fornow,imaginethat
somedayyoumightwanttocreateaListofyourArrayLists.
Next,wehavethisweird-lookingsyntaxwiththe<and>characters.Thissyntaxwasaddedtothe
languageinJava5,andithastodowith"generics."Genericsaren’treallyincludedintheOCAexam,so
wedon’twanttospendalotoftimeonthemhere,butwhat’simportanttoknowisthatthisishowyoutell
thecompilerandtheJVMthatforthisparticularArrayListyouwantonlyStringstobeallowed.What
thismeansisifthecompilercantellthatyou’retryingtoadda"not-a-String"objecttothisArrayList,
yourcodewon’tcompile.Thisisagoodthing!
Alsoaspromised,let’slookatTHISlineofcode:
System.out.println(c);
RememberthatallclassesultimatelyinheritfromclassObject.ClassObjectcontainsamethodcalled
toString().Again,toString()isn’t"officially"ontheOCAexam(ofcourse,itISintheOCPexam!),
butyouneedtounderstanditabitfornow.Whenyoupassanobjectreferencetoeither
System.out.print()orSystem.out.println(),you’retellingthemtoinvokethatobject’s
toString()method.(Wheneveryoumakeanewclass,youcanoptionallyoverridethetoString()
methodyourclassinheritedfromObjecttoshowusefulinformationaboutyourclass’sobjects.)TheAPI
developerswereniceenoughtooverrideArrayList’stoString()methodforyoutoshowthecontents
oftheArrayList,asyousawintheprogram’soutput.Hooray!
ArrayListsandDuplicates
Asyou’replanningyourtriptoEurope,yourealizethathalfwaythroughyourstayinRome,there’sgoing
tobeafantasticmusicfestivalinNaples!NaplesisjustdownthecoastfromRome!You’vegottoadd
thatsidetriptoyouritinerary.Thequestionis,cananArrayListhaveduplicateentries?Isitlegaltosay
this:
Andtheshortansweris:Yes,ArrayListscanhaveduplicates.Nowifyoustopandthinkaboutit,the
notionof"duplicateJavaobjects"isactuallyabittricky.Relax,becauseyouwon’thavetogetintothat
trickinessuntilyoustudyfortheOCP8.
Technicallyspeaking,ArrayListsholdonlyobjectreferences,notactualobjectsandnot
primitives.Ifyouseecodelikethis,
myArrayList.add(7);
what’sreallyhappeningistheintisbeingautoboxed(converted)intoanIntegerobjectand
thenaddedtotheArrayList.We’lltalkmoreaboutautoboxinginafewpages.
ArrayListMethodsinAction
Let’slookatanotherpieceofcodethatshowsoffmostoftheArrayListmethodsyouneedtoknowfor
theexam:
whichshouldproducesomethinglikethis:
Acoupleofquicknotesaboutthiscode:Firstoff,noticethatcontains()returnsaboolean.This
makescontains()greattousein"if"tests.Second,noticethatArrayListhasasize()method.It’s
importanttorememberthatarrayshavealengthattributeandArrayListshaveasize()method.
ImportantMethodsintheArrayListClass
ThefollowingmethodsaresomeofthemorecommonlyusedmethodsintheArrayListclassandalso
thosethatyou’remostlikelytoencounterontheexam:
add(element)AddsthiselementtotheendoftheArrayList
add(index,element)Addsthiselementattheindexpointandshiftstheremainingelements
back(forexample,whatwasatindexisnowatindex+1)
clear()RemovesalltheelementsfromtheArrayList
booleancontains(element)Returnswhethertheelementisinthelist
Objectget(index)ReturnstheObjectlocatedatindex
intindexOf(Object)Returnsthe(int)locationoftheelementor-1iftheObjectisnot
found
remove(index)Removestheelementatthatindexandshiftslaterelementstowardthe
beginningonespace
remove(Object)RemovesthefirstoccurrenceoftheObjectandshiftslaterelements
towardthebeginningonespace
intsize()ReturnsthenumberofelementsintheArrayList
Tosummarize,theOCA8examtestsonlyforverybasicknowledgeofArrayLists.Ifyougoonto
taketheOCP8exam,you’lllearnalotmoreaboutArrayListsandothercommoncollections-oriented
classes.
AutoboxingwithArrayLists
Ingeneral,collectionslikeArrayListcanholdobjectsbutnotprimitives.PriortoJava5,acommonuse
fortheso-calledwrapperclasses(e.g.,Integer,Float,Boolean,andsoon)wastoprovideawayto
getprimitivesintoandoutofcollections.PriortoJava5,youhadto"wrap"aprimitivemanuallybefore
youcouldputitintoacollection.AsofJava5,primitivesstillhavetobewrappedbeforetheycanbe
addedtoArrayLists,butautoboxingtakescareofitforyou.
Inthepreviousexample,wecreateaninstanceofclassIntegerwithavalueof42.We’vecreatedan
entireobjectto"wraparound"aprimitivevalue.AsofJava5,wecansay:
Inthislastexample,wearestilladdinganIntegerobjecttomyInts(notanintprimitive);it’sjustthat
autoboxinghandlesthewrappingforus.Therearesomesneakyimplicationswhenweneedtouse
wrapperobjects;let’stakeacloserlook…
Intheold,pre–Java5days,ifyouwantedtomakeawrapper,unwrapit,useit,andthenrewrapit,you
mightdosomethinglikethis:
Nowyoucansay:
Bothexamplesproducethefollowingoutput:
y=568
Andyes,youreadthatcorrectly.Thecodeappearstobeusingthepostincrementoperatoronanobject
referencevariable!Butit’ssimplyaconvenience.Behindthescenes,thecompilerdoestheunboxingand
reassignmentforyou.Earlier,wementionedthatwrapperobjectsareimmutable…thisexampleappears
tocontradictthatstatement.Itsurelookslikey’svaluechangedfrom567to568.Whatactuallyhappened,
however,isthatasecondwrapperobjectwascreatedanditsvaluewassetto568.Ifonlywecould
accessthatfirstwrapperobject,wecouldproveit….
Let’strythis:
whichproducestheoutput:
So,underthecovers,whenthecompilergottotheliney++;ithadtosubstitutesomethinglikethis:
Justaswesuspected,there’sgottabeacalltonewintheresomewhere.
AllthewrapperclassesexceptCharacterprovidetwoconstructors:onetakesaprimitiveof
thetypebeingconstructed,andtheothertakesaStringrepresentationofthetypebeing
constructed.Forexample,
arebothvalidwaystoconstructanewIntegerobject(that"wraps"thevalue42).
Boxing,==,andequals()
Wejustused==todoalittleexplorationofwrappers.Let’stakeamorethoroughlookathowwrappers
workwith==,!=,andequals().TheAPIdevelopersdecidedthatforallthewrapperclasses,two
objectsareequaliftheyareofthesametypeandhavethesamevalue.Itshouldn’tbesurprisingthat
producestheoutput
It’sjusttwowrapperobjectshappentohavethesamevalue.Becausetheyhavethesameintvalue,
theequals()methodconsidersthemtobe"meaningfullyequivalent"and,therefore,returnstrue.How
aboutthisone?
Thisexampleproducestheoutput:
Yikes!Theequals()methodseemstobeworking,butwhathappenedwith==and!=?Whyis!=
tellingusthati1andi2aredifferentobjects,when==issayingthati3andi4arethesameobject?In
ordertosavememory,twoinstancesofthefollowingwrapperobjects(createdthroughboxing)will
alwaysbe==whentheirprimitivevaluesarethesame:
Boolean
Byte
Characterfrom\u0000to\u007f(7fis127indecimal)
ShortandIntegerfrom–128to127
When==isusedtocompareaprimitivetoawrapper,thewrapperwillbeunwrappedandthe
comparisonwillbeprimitivetoprimitive.
WhereBoxingCanBeUsed
Aswediscussedearlier,it’scommontousewrappersinconjunctionwithcollections.Anytimeyouwant
yourcollectiontoholdobjectsandprimitives,you’llwanttousewrapperstomakethoseprimitives
collection-compatible.Thegeneralruleisthatboxingandunboxingworkwhereveryoucannormallyuse
aprimitiveorawrappedobject.Thefollowingcodedemonstratessomelegalwaystouseboxing:
Remember,wrapperreferencevariablescanbenull.Thatmeansyouhavetowatchoutfor
codethatappearstobedoingsafeprimitiveoperationsbutthatcouldthrowa
NullPointerException:
Thiscodecompilesfine,buttheJVMthrowsaNullPointerExceptionwhenitattemptsto
invokedoStuff(x)becausexdoesn’trefertoanIntegerobject,sothere’snovaluetounbox.
TheJava7"Diamond"Syntax
Earlierinthebook,wediscussedseveralsmalladditions/improvementstothelanguagethatwereadded
underthename"ProjectCoin."ThelastProjectCoinimprovementwe’lldiscussisthe"diamondsyntax."
We’vealreadyseenseveralexamplesofdeclaringtype-safeArrayListslikethis:
Noticethatthetypeparametersareduplicatedinthesedeclarations.AsofJava7,thesedeclarations
couldbesimplifiedto:
NoticethatinthesimplerJava7declarations,therightsideofthedeclarationincludedthetwocharacters
"<>,"whichtogethermakeadiamondshape—doh!
Youcannotswapthese;forexample,thefollowingdeclarationisNOTlegal:
Forthepurposesoftheexam,that’sallyou’llneedtoknowaboutthediamondoperator.Forthe
remainderofthebook,we’llusethepre-diamondsyntaxandtheJava7diamondsyntaxsomewhat
randomly—justliketherealworld!
CERTIFICATIONOBJECTIVE
AdvancedEncapsulation(OCAObjective6.5)
6.5Applyencapsulationprinciplestoaclass.
EncapsulationforReferenceVariables
InChapter2webeganourdiscussionoftheobject-orientedconceptofencapsulation.Atthatpoint,we
limitedourdiscussiontoprotectingaclass’sprimitivefieldsand(immutable)Stringfields.Nowthat
you’velearnedmoreaboutwhatitmeansto"pass-by-copy"andwe’velookedatnonprimitivewaysof
handlingdatasuchasarrays,StringBuilders,andArrayLists,it’stimetotakeacloserlookat
encapsulation.
Let’ssaywehavesomespecialdatawhosevaluewe’resavinginaStringBuilder.We’rehappyto
sharethevaluewithotherprogrammers,butwedon’twantthemtochangethevalue:
Whenwerunthecode,wegetthis:
bobfred
Uhoh!Itlookslikewepracticedgoodencapsulationtechniquesbymakingourfieldprivateand
providinga"getter"method,butbasedontheoutput,it’sclearthatwedidn’tdoaverygoodjobof
protectingthedataintheSpecialclass.Canyoufigureoutwhy?Takeaminute….
Okay—justtoverifyyouranswer—whenweinvokegetName(),wedo,infact,returnacopy,justlike
Javaalwaysdoes.Butwe’renotreturningacopyoftheStringBuilderobject;we’rereturningacopy
ofthereferencevariablethatpointsto(Iknow)theoneandonlyStringBuilderobjectweeverbuilt.So
atthepointthatgetName()returns,wehaveoneStringBuilderobjectandtworeferencevariables
pointingtoit(sands2).
ForthepurposeoftheOCAexam,thekeypointisthis:Whenencapsulatingamutableobjectlikea
StringBuilder,oranarray,oranArrayList,ifyouwanttoletoutsideclasseshaveacopyofthe
object,youmustactuallycopytheobjectandreturnareferencevariabletotheobjectthatisacopy.Ifall
youdoisreturnacopyoftheoriginalobject’sreferencevariable,youDONOThaveencapsulation.
CERTIFICATIONOBJECTIVE
UsingSimpleLambdas(OCAObjective9.5)
9.5WriteasimpleLambdaexpressionthatconsumesaLambdaPredicateexpression.
Java8isprobablybestknownastheversionofJavathatfinallyaddedlambdasandstreams.These
twonewfeatures(lambdasandstreams)giveprogrammerstoolstotacklesomecommonandcomplex
problemswitheasier-to-read,moreconcise,and,inmanycases,faster-runningcode.Thecreatorsofthe
OCA8examfeltthat,ingeneral,lambdasandstreamsaretopicsmoreappropriatefortheOCP8exam,
buttheywantedOCA8candidatestogetanintroduction,perhapstowhettheirappetite…
Inthissection,we’regoingtodoareallybasicintroductiontolambdas.Wesuspectthisdiscussion
willraisesomequestionsinyourmind,andwe’resorryforthat,butwe’regoingtorestrictourselvesto
justtheintroductionthattheexamcreatorshadinmind.
Ontherealexam,youshouldexpecttoseemanyquestionsthattestformorethanone
objective.Inthefollowingpages,aswediscusslambdas,we’llbeleaningheavilyon
ArrayListsandwrapperclasses.You’llseethatwecombineArrayLists,wrappers,AND
lambdasintomanyofourcodelistings,andwealsousethiscombinationinthemockexam
questionsweprovide.Therealexam(andreal-lifeprogramming)willdothesame.
Supposeyou’recreatinganapplicationforaveterinaryhospital.Wewanttofocusonthatpartofthe
applicationthatallowsthevetstogetsummaryinformationaboutallthedogsthattheyworkwith.Here’s
ourDogclass:
Nowlet’swritesometestcodetocreatesomesampleDogs,putthemintoanArrayListaswego,and
thenrunsome"queries"againsttheArrayList.
Firsthere’sthesummarypseudocode:
Here’stheactualtestcode:
whichproducesthefollowing(predictablewehope)output:
You’reprobablywayaheadofushere,butnoticehowsimilartheminAge()andmaxWeight()
methodsare.AnditshouldbeeasytoimagineothersimilarmethodswithnameslikemaxAge()or
namesStartingWithC().Sothelineofcodewewanttofocusonis:
Whatif—justsayin’—wecouldcreateasingleDog-queryingmethod(insteadofthemanywe’vebeen
contemplating)andpassitthequeryexpressionwewantedittouse?Itwouldsortoflooklikethis:
Nowwe’rethinkingaboutpassingcodeasanargument?Lambdasletusdojustthat!Let’slookatour
dogQuerier()methodalittlemoreclosely.Firstoff,thecodewe’regoingtopassinisgoingtobeused
astheexpressioninanifstatement.Whatdoweknowaboutifexpressions?Right!Theyhaveto
resolvetoabooleanvalue.Sowhenwedeclareourmethod,thesecondargument(theonethat’sgoingto
holdthepassed-in-code)hastobedeclaredasaboolean.ThefolkswhobroughtusJava8andlambdas
andstreamsprovidedabunchofnewinterfacesintheAPI,andoneofthemostusefuloftheseisthe
java.util.function.Predicateinterface.ThePredicateinterfacehassomeofthosenew-fangled
staticanddefaultinterfacemethods,wediscussedearlierinthebook,and,mostimportantlyforus,it
hasonenonconcretemethodcalledtest()thatreturns—youguessedit—aboolean.
Here’sthemultipurposedogQuerier()method:
Sofarthislookslikegood-oldJava;it’swhenweinvokedogQuerier()thatthesyntaxgets
interesting:
Whenwesay[c]d->d.getAge()<9[/c]—THATisthelambdaexpression.Thedrepresentsthe
argument,andthenthecodemustreturnaboolean.Let’sputallofthistogetherinanewversionof
TestDogs:
whichproducesthefollowingoutput(thelasttwolinesgeneratedusinglambdas!):
Let’sstepbacknowandcoversomesyntaxrules.ThefollowingrulesareforthepurposesoftheOCA
8examonly!IfyoudecidetoearnyourOCP8,you’lldoamuchdeeperdiveintolambdas,andthereare
lotsof"cansofworms"you’llhavetoopen,whichwe’repurposelygoingtoavoid.Sowhatfollowsisan
OCA8appropriatesimplification.
ThebasicsyntaxforaPredicatelambdahasthreeparts:
Othertypesoflambdastakezeroormoreparameters,butfortheOCA8,we’refocusedexclusivelyon
thePredicate,whichmusttakeexactlyoneparameter.Herearesomedetailedsyntaxrulesfor
Predicatelambdas:
Theparametercanbejustavariablename,oritcanbethetypefollowedbyavariablename
allinparentheses.
ThebodyMUST(onewayoranother)returnaboolean.
Thebodycanbeasingleexpression,whichcannothaveareturnstatement.
Thebodycanbeacodeblocksurroundedbycurlybraces,containingoneormorevalid
statements,eachendingwithasemicolon,andtheblockmustendwithareturnstatement.
FollowingisacodelistingthatshowsexamplesoflegalandthenillegalexamplesofPredicate
lambdas:
Thiscodeismostlyaboutvalidandinvalidsyntax,butlet’slookalittlemorecloselyatthego()method.
Thetestismainlyconcernedwiththecodetobepassedtoamethod,butit’susefultolook(butnotTOO
closely)atamethodthatreceiveslambdacode.InboththeDogscodeandthecodedirectlyabove,the
receivingmethodtookaPredicate.Insidethereceivingmethods,wecreatedanobjectofthetypewe’re
workingwith,whichwepasstothePredicate.test()method.Thereceivingmethodexpectsthe
test()methodtoreturnaboolean.
Wehavetoadmitthatlambdasareabittrickytolearn.Again,weexpectwe’veleftyouwithsome
unansweredquestions,butwethinkOracledidareasonablejobofslicingoutapieceofthelambda
puzzletostartwith.Ifyouunderstandthebitswe’vecovered,youshouldbeabletohandlethelambda-
relatedquestionsOraclethrowsyou.
CERTIFICATIONSUMMARY
ThemostimportantthingtorememberaboutStringsisthatStringobjectsareimmutable,but
referencestoStringsarenot!YoucanmakeanewStringbyusinganexistingStringasastarting
point,butifyoudon’tassignareferencevariabletothenewString,itwillbelosttoyourprogram—you
willhavenowaytoaccessyournewString.ReviewtheimportantmethodsintheStringclass.
TheStringBuilderclasswasaddedinJava5.Ithasexactlythesamemethodsastheold
StringBufferclass,exceptStringBuilder’smethodsaren’tthread-safe.BecauseStringBuilder’s
methodsarenotthread-safe,theytendtorunfasterthanStringBuffermethods,sochoose
StringBuilderwheneverthreadingisnotanissue.BothStringBufferandStringBuilderobjects
canhavetheirvaluechangedoverandoverwithoutyourhavingtocreatenewobjects.Ifyou’redoinga
lotofstringmanipulation,theseobjectswillbemoreefficientthanimmutableStringobjects,whichare,
moreorless,"useonce,remaininmemoryforever."Remember,thesemethodsALWAYSchangethe
invokingobject’svalue,evenwithnoexplicitassignment.
NextwediscussedkeyclassesandinterfacesinthenewJava8calendarandtime-relatedpackages.
SimilartoStrings,allofthecalendarclasseswestudiedcreateimmutableobjects.Inaddition,these
classesusefactorymethodsexclusivelytocreatenewobjects.Thekeywordnewcannotbeusedwith
theseclasses.Welookedatsomeofthepowerfulfeaturesoftheseclasses,likecalculatingtheamountof
timebetweentwodifferentdatesortimes.ThenwetookalookathowtheDateTimeFormatterclassis
usedtoparseStringsintocalendarobjectsandhowitisusedtobeautifycalendarobjects.
Thenexttopicwasarrays.Wetalkedaboutdeclaring,constructing,andinitializingone-dimensional
andmultidimensionalarrays.Wetalkedaboutanonymousarraysandthefactthatarraysofobjectsare
actuallyarraysofreferencestoobjects.
Next,wediscussedthebasicsofArrayLists.ArrayListsarelikearrayswithsuperpowersthat
allowthemtogrowandshrinkdynamicallyandtomakeiteasyforyoutoinsertanddeleteelementsat
locationsofyourchoosingwithinthelist.WediscussedtheideathatArrayListscannotholdprimitives,
andthatifyouwanttomakeanArrayListfilledwithagiventypeofprimitivevalues,youuse
"wrapper"classestoturnaprimitivevalueintoanobjectthatrepresentsthatvalue.Thenwediscussed
howwithautoboxing,turningprimitivesintowrapperobjects,andviceversa,isdoneautomatically.
Finally,wediscussedaspecificsubsetofthetopicoflambdas,usingthePredicateinterface.The
basicideaoflambdasisthatyoucanpassabitofcodefromonemethodtoanother.ThePredicate
interfaceisoneofmany"functionalinterfaces"providedintheJava8API.Afunctionalinterfaceisone
thathasonlyonemethodtobeimplemented.InthecaseofthePredicateinterface,thismethodiscalled
test(),andittakesasingleargumentandreturnsaboolean.Towrapupourdiscussionoflambdas,we
coveredsomeofthetrickysyntaxrulesyouneedtoknowtowritevalidlambdas.
TWO-MINUTEDRILL
Herearesomeofthekeypointsfromthecertificationobjectivesinthischapter.
UsingStringandStringBuilder(OCAObjectives9.2and9.1)
Stringobjectsareimmutable,andStringreferencevariablesarenot.
IfyoucreateanewStringwithoutassigningit,itwillbelosttoyourprogram.
IfyouredirectaStringreferencetoanewString,theoldStringcanbelost.
Stringmethodsusezero-basedindexes,exceptforthesecondargumentofsubstring().
TheStringclassisfinal—itcannotbeextended.
WhentheJVMfindsaStringliteral,itisaddedtotheStringliteralpool.
Stringshaveamethodcalledlength()—arrayshaveanattributenamedlength.
StringBuilderobjectsaremutable—theycanchangewithoutcreatinganewobject.
StringBuildermethodsactontheinvokingobject,andobjectscanchangewithoutan
explicitassignmentinthestatement.
Rememberthatchainedmethodsareevaluatedfromlefttoright.
Stringmethodstoremember:charAt(),concat(),equalsIgnoreCase(),length(),
replace(),substring(),toLowerCase(),toString(),toUpperCase(),andtrim().
StringBuildermethodstoremember:append(),delete(),insert(),reverse(),and
toString().
ManipulatingCalendarData(OCAObjective9.3)
Ontheexamalltheobjectscreatedusingthecalendarclassesareimmutable,buttheir
referencevariablesarenot.
Ifyoucreateanewcalendarobjectwithoutassigningit,itwillbelosttoyourprogram.
Ifyouredirectacalendarreferencetoanewcalendarobject,theoldcalendarobjectcanbe
lost.
Alloftheobjectscreatedusingtheexam’scalendarclassesmustbecreatedusingfactory
methods(e.g.,from(),now(),of(),parse());thekeywordnewisnotallowed.
Theuntil()andbetween()methodsperformcomplexcalculationsthatdeterminethe
amountoftimebetweenthevaluesoftwocalendarobjects.
TheDateTimeFormatterclassusestheparse()methodtoparseinputStringsintovalid
calendarobjects.
TheDateTimeFormatterclassusestheformat()methodtoformatcalendarobjectsinto
beautifullyformedStrings.
UsingArrays(OCAObjectives4.1and4.2)
Arrayscanholdprimitivesorobjects,butthearrayitselfisalwaysanobject.
Whenyoudeclareanarray,thebracketscanbetotheleftorrightofthename.
Itisneverlegaltoincludethesizeofanarrayinthedeclaration.
Youmustincludethesizeofanarraywhenyouconstructit(usingnew)unlessyouarecreating
ananonymousarray.
Elementsinanarrayofobjectsarenotautomaticallycreated,althoughprimitivearray
elementsaregivendefaultvalues.
You’llgetaNullPointerExceptionifyoutrytouseanarrayelementinanobjectarrayif
thatelementdoesnotrefertoarealobject.
Arraysareindexedbeginningwithzero.
AnArrayIndexOutOfBoundsExceptionoccursifyouuseabadindexvalue.
Arrayshavealengthattributewhosevalueisthenumberofarrayelements.
Thelastindexyoucanaccessisalwaysonelessthanthelengthofthearray.
Multidimensionalarraysarejustarraysofarrays.
Thedimensionsinamultidimensionalarraycanhavedifferentlengths.
Anarrayofprimitivescanacceptanyvaluethatcanbepromotedimplicitlytothearray’s
declaredtype—forexample,abytevariablecangoinanintarray.
AnarrayofobjectscanholdanyobjectthatpassestheIS-A(orinstanceof)testforthe
declaredtypeofthearray.Forexample,ifHorseextendsAnimal,thenaHorseobjectcangointo
anAnimalarray.
Ifyouassignanarraytoapreviouslydeclaredarrayreference,thearrayyou’reassigning
mustbethesamedimensionasthereferenceyou’reassigningitto.
Youcanassignanarrayofonetypetoapreviouslydeclaredarrayreferenceofoneofits
supertypes.Forexample,aHondaarraycanbeassignedtoanarraydeclaredastypeCar(assuming
HondaextendsCar).
UsingArrayList(OCAObjective9.4)
ArrayListsallowyoutoresizeyourlistandmakeinsertionsanddeletionstoyourlistfar
moreeasilythanarrays.
ArrayListsareorderedbydefault.Whenyouusetheadd()methodwithnoindexargument,
thenewentrywillbeappendedtotheendoftheArrayList.
FortheOCA8exam,theonlyArrayListdeclarationsyouneedtoknowareofthisform:
ArrayListscanholdonlyobjects,notprimitives,butrememberthatautoboxingcanmakeit
looklikeyou’readdingprimitivestoanArrayListwhen,infact,you’readdingawrapperobject
versionofaprimitive.
AnArrayList’sindexstartsat0.
ArrayListscanhaveduplicateentries.Note:Determiningwhethertwoobjectsare
duplicatesistrickierthanitseemsanddoesn’tcomeupuntiltheOCP8exam.
ArrayListmethodstoremember:add(element),add(index,element),clear(),
contains(object),get(index),indexOf(object),remove(index),remove(object),and
size().
EncapsulatingReferenceVariables(OCAObjective6.5)
IfyouwanttoencapsulatemutableobjectslikeStringBuildersorarraysorArrayLists,
youcannotreturnareferencetotheseobjects;youmustfirstmakeacopyoftheobjectandreturna
referencetothecopy.
Anyclassthathasamethodthatreturnsareferencetoamutableobjectisbreaking
encapsulation.
UsingPredicateLambdaExpressions(OCAObjective9.5)
Lambdasallowyoutopassbitsofcodefromonemethodtoanother.Andthereceiving
methodcanrunwhatevercomplyingcodeitissent.
WhiletherearemanytypesoflambdasthatJava8supports,forthisexam,theonlylambda
typeyouneedtoknowisthePredicate.
ThePredicateinterfacehasasinglemethodtoimplementthat’scalledtest(),andittakes
oneargumentandreturnsaboolean.
AsthePredicate.test()methodreturnsaboolean,itcanbeplaced(mostly?)wherevera
booleanexpressioncango,e.g.,inif,while,do,andternarystatements.
Predicatelambdaexpressionshavethreeparts:asingleargument,anarrow(->),andan
expressionorcodeblock.
APredicatelambdaexpression’sargumentcanbejustavariableoratypeandvariable
togetherinparentheses,e.g.,(MyClassm).
APredicatelambdaexpression’sbodycanbeanexpressionthatresolvestoaboolean,OR
itcanbeablockofstatements(surroundedbycurlybraces)thatendswithaboolean-returning
returnstatement.
SELFTEST
1.Given:
Whichtwosubstringswillbeincludedintheresult?(Choosetwo.)
2.Given:
And,ifthecodecompiles,thecommandline:
javaHilltopeyravafidraumurkara
Whatistheresult?
A.EYRAVAFIDRAUMURKARA
B.EYRAVAFIDRAUMURKARAnull
C.Anexceptionisthrownwithnootheroutput
D.EYRAVAFIDRAUMURKARA,andthenaNullPointerException
E.EYRAVAFIDRAUMURKARA,andthenanArrayIndexOutOfBoundsException
F.Compilationfails
3.Given:
Whatistheresult?
A.truetrue
B.truefalse
C.falsetrue
D.falsefalse
E.Compilationfails
4.Given:
Whatistheresult?(Chooseallthatapply.)
A.2
B.4
C.Anexceptionisthrownatruntime
D.Compilationfailsduetoanerroronline4
E.Compilationfailsduetoanerroronline5
F.Compilationfailsduetoanerroronline6
G.Compilationfailsduetoanerroronline7
5.Given:
Whatistheresult?
A.[apple,banana,carrot,plum]
B.[apple,plum,carrot,banana]
C.[apple,plum,banana,carrot]
D.[plum,banana,carrot,apple]
E.[plum,apple,carrot,banana]
F.[banana,plum,carrot,apple]
G.Compilationfails
6.Given:
Whichtwoaretrueabouttheobjectscreatedwithinmain(),andwhichareeligibleforgarbage
collectionwhenline14isreached?
A.Threeobjectswerecreated
B.Fourobjectswerecreated
C.Fiveobjectswerecreated
D.ZeroobjectsareeligibleforGC
E.OneobjectiseligibleforGC
F.TwoobjectsareeligibleforGC
G.ThreeobjectsareeligibleforGC
7.Given:
Whatistheresult?
A.24
B.27
C.32
D.37
E.42
F.47
G.Compilationfails
8.Given:
Whicharetrue?(Chooseallthatapply.)
A.Compilationfails
B.Thefirstlineofoutputisabcabctrue
C.Thefirstlineofoutputisabcabcfalse
D.Thefirstlineofoutputisabcdabcfalse
E.Thesecondlineofoutputisabcdabcfalse
F.Thesecondlineofoutputisabcdabcdtrue
G.Thesecondlineofoutputisabcdabcdfalse
9.Given:
IfthegarbagecollectordoesNOTrunwhilethiscodeisexecuting,approximatelyhowmany
objectswillexistinmemorywhentheloopisdone?
A.Lessthan10
B.About1000
C.About2000
D.About3000
E.About4000
10.Given:
Whichlinesofcode(ifany)breakencapsulation?(Chooseallthatapply.)
A.Line3
B.Line4
C.Line5
D.Line7
E.Line8
F.Line9
G.Theclassisalreadywellencapsulated
13.Given:
Whatistheresult?
A.truetruefalse
B.CompilationfailsdueonlytoanerroratlineA
C.CompilationfailsdueonlytoanerroratlineB
D.CompilationfailsdueonlytoanerroratlineC
E.CompilationfailsdueonlytoerrorsatlinesAandB
F.CompilationfailsdueonlytoerrorsatlinesAandC
G.CompilationfailsdueonlytoerrorsatlinesA,B,andC
H.Compilationfailsforreasonsnotlisted
14.Given:
Whatistheresult?
A.2018-01-152018-01-15
B.2018-01-152018-01-16
C.Jan15,2018Jan15,2018
D.Jan15,2018Jan16,2018
E.Compilationfails
F.Anexceptionisthrownatruntime
15.Given:
Whatistheresult?
A.[5,42,113,7]
B.Compilationfailsdueonlytoanerroronline5
C.Compilationfailsdueonlytoanerroronline8
D.Compilationfailsdueonlytoerrorsonlines5and8
E.Compilationfailsdueonlytoerrorsonlines7and8
F.Compilationfailsdueonlytoerrorsonlines5,7,and8
G.Compilationfailsdueonlytoerrorsonlines5,7,8,and9
16.Giventhatadder()returnsanint,whicharevalidPredicatelambdas?(Chooseallthatapply.)
Whicharetrue?(Chooseallthatapply.)
A.Theoutputis:2018-08-162018-08-172018-08-18
B.Theoutputis:2018-08-162018-08-182018-08-17
C.Theoutputis:2018-08-162018-08-172018-08-17
D.AtlineX,zeroLocalDateobjectsareeligibleforgarbagecollection
E.AtlineX,oneLocalDateobjectiseligibleforgarbagecollection
F.AtlineX,twoLocalDateobjectsareeligibleforgarbagecollection
G.Compilationfails
19.GiventhatereferstoanobjectthatimplementsPredicate,whichcouldbevalidcodesnippetsor
statements?(Chooseallthatapply.)
A.if(e.test(m))
B.switch(e.test(m))
C.while(e.test(m))
D.e.test(m)?"yes":"no";
E.do{}while(e.test(m));
F.System.out.print(e.test(m));
G.booleanb=e.test(m));
SELFTESTANSWERS
1. AandDarecorrect.TheStringoperationsareworkingonanew(lost)Stringnot
Strings.TheStringBuilderoperationsworkfromlefttoright.
B,C,andEareincorrectbasedontheabove.(OCAObjectives9.2and9.1)
2. Discorrect.Thehorsesarray’sfirstfourelementscontainStrings,butthefifthisnull,
sothetoUpperCase()invocationforthefifthelementthrowsaNullPointerException.
A,B,C,E,andFareincorrectbasedontheabove.(OCAObjectives4.1and1.3)
3. Eiscorrect.TheUnicodedeclarationmustbeenclosedinsinglequotes:’\u004e’.Ifthis
weredone,theanswerwouldbeA,butthatequalityisn’tontheOCAexam.
A,B,C,andDareincorrectbasedontheabove.(OCAObjectives2.1and4.1)
4. Ciscorrect.AClassCastExceptionisthrownatline7becauseo1referstoanint[][],
notanint[].Ifline7wereremoved,theoutputwouldbe4.
A,B,D,E,F,andGareincorrectbasedontheabove.(OCAObjective4.2)
5. Biscorrect.ArrayListelementsareautomaticallyinsertedintheorderofentry;theyare
notautomaticallysorted.ArrayListsusezero-basedindexes,andthelastadd()insertsanew
elementandshiftstheremainingelementsback.
A,C,D,E,F,andGareincorrectbasedontheabove.(OCAObjective9.4)
6. CandFarecorrect.dareferstoanobjectoftype"Dozensarray,"andeachDozensobject
thatiscreatedcomeswithitsown"intarray"object.Whenline14isreached,onlythesecond
Dozensobject(andits"intarray"object)arenotreachable.
A,B,D,E,andGareincorrectbasedontheabove.(OCAObjectives4.1and2.4)
7. Ciscorrect.Atwo-dimensionalarrayisan"arrayofarrays."Thelengthofbais2because
itcontains2one-dimensionalarrays.Arrayindexesarezero-based,soba[1]referstoba’ssecond
array.
A,B,D,E,F,andGareincorrectbasedontheabove.(OCAObjective4.2)
8. DandFarecorrect.AlthoughStringobjectsareimmutable,referencestoStringsare
mutable.Thecodes1+="d";createsanewStringobject.StringBuilderobjectsaremutable,
sotheappend()ischangingthesingleStringBuilderobjecttowhichbothStringBuilder
referencesrefer.
A,B,C,E,andGareincorrectbasedontheabove.(OCAObjectives9.2and9.1)
9. Biscorrect.StringBuildersaremutable,soalloftheappend()invocationsareacting
onthesameStringBuilderobjectoverandover.Strings,however,areimmutable,soevery
StringconcatenationoperationresultsinanewStringobject.Also,thestring""iscreated
onceandreusedineveryloopiteration.
A,C,D,andEareincorrectbasedontheabove.(OCAObjectives9.2and9.1)
10. Aiscorrect.Althoughmain()’sb1isadifferentreferencevariablethango()’sb1,they
refertothesameBoxobject.
B,C,D,E,andFareincorrectbasedontheabove.(OCAObjectives4.1,6.1,and6.6)
11. Discorrect.Thesubstring()invocationusesazero-basedindexandthesecond
argumentisexclusive,sothecharacteratindex8isNOTincluded.ThetoUpperCase()invocation
makesanewStringobjectthatisinstantlylost.ThetoUpperCase()invocationdoesNOTaffect
theStringreferredtobys.
A,B,C,E,F,andGareincorrectbasedontheabove.(OCAObjective9.2)
12. Fiscorrect.WhenencapsulatingamutableobjectlikeanArrayList,yourgettermust
returnareferencetoacopyoftheobject,notjustthereferencetotheoriginalobject.
A,B,C,D,E,andGareincorrectbasedontheabove.(OCAObjective6.5)
13. Fiscorrect.Predicatelambdastakeexactlyoneparameter;therestofthecodeiscorrect.
A,B,C,D,E,G,andHareincorrectbasedontheabove.(OCAObjective9.5)
14. Discorrect.InvokingtheplusDays()methodcreatesanewobject,andbothLocalDate
andDateTimeFormatterhaveformat()methods.
A,B,C,E,andFareincorrectbasedontheabove.(OCAObjective9.3)
15. Ciscorrect.TheonlyerrorinthiscodeisattemptingtoaddaStringtoanArrayListof
Integerwrapperobjects.Line7usesautoboxing,andlines6and9demonstrateusingawrapper
class’stwoconstructors.
A,B,D,E,F,andGareincorrectbasedontheabove.(OCAObjectives2.5and9.4)
16. B,EandFusecorrectsyntax.
A,C,D,andGareincorrect.Apassestwoparameters.C,areturn,mustbeinacodeblock,
andcodeblocksmustbeincurlybraces.D,ablock,musthaveareturnstatement.G,theresult,is
notaboolean.(OCAObjective9.5)
17. Ciscorrect.ArrayListscanhaveduplicateentries.
A,B,D,E,andFareincorrectbasedontheabove.(OCAObjective9.4)
18. BandEarecorrect.AtotaloffourLocalDateobjectsarecreated,buttheonecreated
usingtheof()methodisabandonedonthenextlineofcodewhenitsreferencevariableisassigned
tothenewLocalDateobjectcreatedviathefirstplusDays()invocation.Thereferencevariables
areswappedabit,whichaccountsforthedatesnotprintinginchronologicalorder.
A,C,D,F,andGareincorrectbasedontheabove.(OCAObjectives2.4and9.3)
19. A,C,D,E,F,andGarecorrect;theyallrequireaboolean.
Bisincorrect.Aswitchdoesn’ttakeaboolean.(OCAObjective9.5)
A
AbouttheDownload
Thise-bookcomeswithfreedownloadableOraclePressPracticeExamSoftware,whichcanbe
downloadedusingthelinksprovidedinthisappendix.ThissoftwareiseasytoinstallonanyMacor
WindowscomputerandmustbeinstalledtoaccessthePracticeExamfeature.
SystemRequirements
Windows
•2.33GHzorfasterx86-compatibleprocessor,orIntelAtom™1.6GHzorfasterprocessorfor
netbookclassdevices
•Microsoft®WindowsServer2008,Windows7,Windows8.1ClassicorWindows10
•512MBofRAM(1GBrecommended)
MacOS
•Intel®Core™Duo1.83GHzorfasterprocessor
•MacOSXv10.7andabove
•512MBofRAM(1GBrecommended)
DownloadingfromMcGraw-HillProfessional’sMedia
Center
Todownloadtheglossary,additionalcontent,andOraclePressPracticeExamSoftware,visitMcGraw-
HillProfessional’sMediaCenterbyclickingthelinkbelowandenteringthise-book’sISBNandyoure-
mailaddress.Youwillthenreceiveane-mailmessagewithadownloadlinkfortheadditionalcontent.
http://mhprofessional.com/mediacenter
Thise-book’sISBNis1260011380.
Onceyou’vereceivedthee-mailmessagefromMcGraw-HillProfessional’sMediaCenter,clickthe
linkincludedtodownloadthepracticeexams.Ifyoudonotreceivethee-mail,besuretocheckyour
spamfolder.
InstallingthePracticeExamSoftware
FollowtheinstructionsbelowforWindowsorMacOS.
Windows
Step1OpentheInstallerforPC.zipfile.Youwillneedtounzipthefileandextractorcopyandpastethe
contentstoyourharddrive.
Step2LocatetheInstaller.exefileanddoubleclickthefile.Afterafewmoments,theinstallerwillopen.
Step3Followtheonscreeninstructionstoinstalltheapplication.
MacOS
Step1OpentheInstallerforMac.zipfile.Youwillneedtounzipthefileandextractorcopyandpastethe
contentstoyourharddrive.
Step2Afterafewmoments,thecontentsofthe.zipfilewillbedisplayed.
Step3DoubleclickonInstallertobegininstallation.
Step4Followtheonscreeninstructionstoinstalltheapplication.
NOTE:Ifyougetanerrorwhileinstallingthesoftwarepleaseensureyouranti-virusorinternetsecurity
programsaredisabledandtryinstallingthesoftwareagain.Youmayenabletheantivirusorinternet
securityprogramagainafterinstallationiscomplete.
RunningthePracticeExamSoftware
Followtheinstructionsbelowafteryouhavecompletedthesoftwareinstallation.
Windows
Afterinstalling,youcanstarttheapplicationusingeitherofthetwomethodsbelow:
1.Double-clicktheOraclePressJavaSE8Practiceicononyourdesktop,or
2.GototheStartmenuandclickProgramsorAllPrograms.ClickOraclePressJavaSE8
Practicetostarttheapplication.
MacOS
OpentheOraclePressJavaSE8PracticefolderinsideyourMac’sapplicationfolderanddouble-click
theOraclePressJavaSE8Practiceicontoruntheapplication.
PracticeExamSoftwareFeatures
ThePracticeExamSoftwareprovidesyouwithasimulationoftheactualexam.Thesoftwarealso
featuresacustommodethatcanbeusedtogeneratequizzesbyexamobjectivedomain.Quizmodeisthe
defaultmode.Tolaunchanexamsimulation,selectoneoftheOCAexambuttonsatthetopofthescreen,
orchecktheExamModecheckboxatthebottomofthescreenandselecttheOCAexaminthecustom
window.
Thenumberofquestions,typesofquestions,andthetimeallowedontheexamsimulationareintended
tobearepresentationoftheliveexam.Thecustomexammodeincludeshintsandreferences,andin-depth
answerexplanationsareprovidedthroughtheFeedbackfeature.
Whenyoulaunchthesoftware,adigitalclockdisplaywillappearintheupper-rightcornerofthe
questionwindow.TheclockwillcontinuetocountunlessyouchoosetoendtheexambyselectingGrade
TheExam.
RemovingInstallation
ThePracticeExamSoftwareisinstalledonyourharddrive.Forbestresultsforremovalofprograms
usingaWindowsPCusetheControlPanel|UninstallAProgramoptionandthenchooseOraclePress
JavaSE8Practicetouninstall.
ForbestresultsforremovalofprogramsusingaMacgototheOraclePressJavaSE8Practicefolder
insideyourapplicationsfolderanddragthe“OraclePressJavaSE8Practice”icontothetrash.
Help
AhelpfileisprovidedthroughtheHelpbuttononthemainpageinthetop-rightcorner.Areadmefileis
alsoincludedintheBonusContentfolder.
TechnicalSupport
TechnicalSupportinformationisprovidedinthefollowingsectionsbyfeature.
Windows8Troubleshooting
ThefollowingknownerrorsonWindows8havebeenreported.Pleaseseebelowforinformationon
troubleshootingtheseknownissues.
Ifyougetanerrorwhileinstallingthesoftware,suchas“Theapplicationcouldnotbeinstalled
becausetheinstallerfileisdamaged.Tryobtainingthenewinstallerfromtheapplicationauthor,”you
mayneedtodisableyouranti-virusorInternetsecurityprogramsandtryinstallingthesoftwareagain.
YoumayenabletheantivirusorInternetsecurityprogramagainafterinstallationiscomplete.
Formoreinformationonhowtodisableanti-virusprogramsinWindows,pleasevisitthewebsiteof
thesoftwareproviderofyouranti-virusprogram.Forexample,ifyouuseNortonorMacAfeeproducts,
youmayneedtovisittheNortonortheMacAfeewebsiteandsearchfor“howtodisableantivirusin
Windows8.”Anti-virusprogramsaredifferentfromfirewalltechnology,sobesuretodisabletheanti-
virusprogram,andbesuretore-enabletoprogramafteryouhaveinstalledthepracticeexamsoftware.
WhileWindowsdoesn’tincludedefaultantivirussoftware,Windowscanoftendetectantivirus
softwareinstalledbyyouorthemanufacturerofyourcomputerandtypicallydisplaysthestatusofany
suchsoftwareintheActionCenter,whichislocatedintheControlPanelunderSystemandSecurity
(selectReviewYourComputer’sStatus).Window’shelpfeaturecanalsoprovidemoreinformationon
howtodetectyouranti-virussoftware.Iftheanti-virussoftwareison,checktheHelpfeaturethatcame
withthatsoftwareforinformationonhowtodisableit.
Windowswillnotdetectallanti-virussoftware.Ifyouranti-virussoftwareisn’tdisplayedinthe
ActionCenteryoucantrytypingthenameofthesoftwareorthepublisherintheStartMenu’ssearchfield.
McGraw-HillEducationContentSupport
ForquestionsregardingtheGlossaryortheadditionalbonuscontent,e-mailtechsolutions@mhedu.com
orvisithttp://mhp.softwareassist.com.
Forquestionsregardingbookcontent,e-mailhep_customer.service@mheducation.com.For
customersoutsidetheUnitedStates,e-mailinternational_cs@mheducation.com.
INDEX
A
abandonedstrings,344–346
abstractclasses,19
constructors,133,136
creating,23
implementation,123
vs.interfaces,25
overview,21–22
abstractmethods
inheritance,93
overview,45–48
subclassimplementation,106
accessandaccessmodifiers,30–33
classes,17–21
constructors,135
encapsulation,89
keypoints,71
levels,54
localvariables,42–43
overloadedmethods,111
overriddenmethods,107–108
private,34–36
protectedanddefaultmembers,36–42
public,33–34
staticmethodsandvariables,151–154
add()methodinArrayList,383
addition
compoundassignment,236
operator,244
precedence,257
ampersands(&)
bitwiseoperators,251–252
logicaloperators,252–255
precedence,257
ANDexpressions,252–255
anglebrackets(<>)ingenericcode,381
anonymousarrays,372–373
append()method,353–354
appendingstrings,341–342,353–354
applications,launching,11–12
@argfilesoptions,11
arguments
final,44–45
overloadedmethods,111,113
overriddenmethods,108
vs.parameters,49–50
superconstructors,137
variableargumentlists,49–50
arithmeticoperators,244–249
basic,244–245
incrementanddecrement,248–250
keypoints,260–261
remainder,245–246
stringconcatenation,246–248
ArithmeticExceptionclass,322
ArrayIndexOutOfBoundsExceptionclass,306
description,322
out-of-rangearrayindexes,369
superclass,308–309
ArrayListclass,13–14
autoboxing,384–388
basics,380–381
diamondsyntax,388–389
duplicates,383
keypoints,401
methods,382–384
uses,379–381
arrays,363
constructing,364–367,370–372
declaring,57–59,363–364,370–372
defaultelementvalues,198–199,202,221
elementassignments,374–378
enhancedforloops,292–293
indexes,12,368
initializing,368–374
instanceofcomparisons,244
keypoints,76,399–400
lengthattribute,350
referenceassignments,376–378
returning,131
ASCIIset,53
AssertionErrorclass,316,321
assignments
arrayelements,374–378
compilererrors,188–189
floating-pointnumbers,188
keypoints,220–221
objectcompatibility,242
operators,182–183,235–236,257
primitives,183–185,190
referencevariables,190–191,202–203,376–378
asterisks(*)
compoundassignmentoperators,236
importstatements,14,16
multiplication,244
precedence,257
autoboxingwithArrayLists,384–388
automaticlocalvariables,55–57
automaticvariables.Seelocalvariables
B
backslashes(\)forescapedcharacters,182
base2(binary)integers,178
base8(octal)integers,178–179
base10(decimal)integers,178
base16(hexadecimal)literals,178,180
basicforloops,288
conditionalexpressions,289–290
declarationandinitialization,288–289
iterationexpressions,289–290
loopissues,290–292
behaviors,description,2
between()method,361
binary(base2)integers,178
binaryliterals,179
bitwiseoperators,251–252
blocks
initialization,145–147
variables,193
booleantypeandvalues
bitdepth,53
defaultvalues,196
doloops,287
inforloops,288–289
ifstatements,276–277
invertoperator,255–256
literals,181
relationaloperators,236
whileloops,286
braces({}).Seecurlybraces({})
branching
if-else,273–277
switchstatements.Seeswitchstatementsbreakstatement
inforloops,290
keypoints,326
loopconstructs,294–296
switchstatements,278,281–283
bugs.Seeexceptions
bytes
caseconstants,278–279
defaultvalues,196
andint,184
ranges,53
C
calendardata
classes,357–358
factoryclasses,359
formatting,362
immutability,358–359
keypoints,398–399
usingandmanipulating,360–361
callstackexceptions,303–305
CamelCase,9
capacityofstrings,354
carets(^)
bitwiseoperators,251–252
exclusive-ORoperators,255
casesensitivity
identifiers,7
stringcomparisons,348–349
casestatements,278–280
casts,184
assignment,235
explicit,185–186
implicit,186
keypoints,159,220
overview,118–121
precision,188–189
primitives,185–188
catchclause,299–300
chainedmethods,356
chainingconstructors,134
charactersandchartype
bitdepth,53
caseconstants,278–279
comparisons,237
defaultvalues,196
literals,181–182
charAt()method,348–349
checkedexceptions
handling,314–315
interfaceimplementation,123
overloadedmethods,111
overriddenmethods,108,110
ChronoUnitenum,361
.classfiles,12
ClassCastExceptionclass
description,322
downcasts,119
classes
access,17–21
compiling,11
constructors.Seeconstructorsdeclaring,17–18
defining,9–10
description,2
extending,18,102
final,20–21,59–61
importstatements,13–14
interfaceimplementation,123
launchingapplicationswithjava,11–12
main()method,12–13
memberdeclarations,28
names,8–9,151
overriding,3
sourcefiledeclarationrules,10
wrapper,320
cleaningupgarbagecollection,218
clear()method,383
codeconventions,7–9
collections,58
colons(:)
conditionaloperators,250–251
labels,296
commas(,)
inforloops,288–289
variables,185
commentsinsourcecodefiles,10
comparisons
instanceof,242–244
relationaloperators,236–241
strings,348–349
compilerandcompiling
casts,119
interfaceimplementation,122–123
javac,11
overloadedmethods,114
compilererrors
assignments,188–189
instanceof,244
compoundassignments
withcasts,189
operators,236
strings,247
concat()method,348–349
concatenatingstrings,246–248,261,348–349
concreteclasses
abstractmethodsimplementedby,106
creating,23
subclasses,46–47
concretemethods,102
conditionaloperators
keypoints,261
overview,250–251
conditions
doloops,287
inforloops,288–290
if-elsebranching,273–277
switchstatements.Seeswitchstatementswhileloops,286
constantspecificclassbody,65–66
constants
case,278–279
enum,62
interface,26–27
names,9
Stringclass,347
constructingarrays,364–367,370–372
constructors,132
basics,133
calendardata,359
chaining,134
declarations,50–51
default,135–137
enums,65–66
inheritance,93,140
keypoints,75,160–161
overloaded,140–145
rules,135–136
strings,341
super()andthis()calls,144
contains()method,383
continuestatement
keypoints,326
loopconstructs,294–295
controls,17
conventions
code,7–9
identifiers,6
names,2
conversions
returntype,131
types.Seecasts
costreduction,object-orienteddesignfor,100
counting
instances,148
references,212
covariantreturns,129–130
cross-platformexecution,5
curlybraces({})
abstractmethods,46
arrays,370,372,374
classmembers,196,199
ifexpressions,273,275
instancevariables,196
lambdas,395
methods,46
optional,273
D
Dsuffix,181
dashes(-)
compoundassignmentoperators,236
decrementoperators,248–249
precedence,257
subtraction,244
datedata
usingandmanipulating,360–361
formatting,362
DateTimeFormatterclass,358,361–362
DeadlyDiamondofDeath,102
decimal(base10)integers,178
decimalliteralswithunderscores,179
declarations
arrays,57–59,363–364,370–372
basicforloops,288–289
classmembers,28
classes,17–18
constructors,50–51
enhancedforloops,293
enumelements,65–67
enums,62–64
exceptions,312–317
interfaceconstants,26–27
interfaces,23–26
polymorphic,381
referencevariables,53–54
returntypes,129–132
sourcefilerules,10
variables,51–61,75–76
decrementoperators
keypoints,261
workingwith,248–250
defaultaccess
description,17
overview,18–19
andprotected,30,36–42
defaultcaseinswitchstatements,283–284
Defaultprotection,30
defaults
constructors,135–137
interfacemethods,28
primitiveandobjecttypeinstancevariables,195–198
defining
classes,9–10
exceptions,306–307
delete()method,354–355
deletingstrings,354–355
diamondsyntax,388–389
distributedcomputing,5
division
compoundassignment,236
operator,244
precedence,257
doloops,287
dots(.)
access,31–32
classnames,151
instancereferences,151
variableargumentlists,50
doubletype
casts,186
defaultvalues,196
floating-pointliterals,180
ranges,53
underscores,179
downcasts,119
duckingexceptions,303,312
duplicatesinArrayLists,383
E
elementsinarrays.Seearrays
ellipses(...)invariableargumentlists,50
elsestatements,273–277
encapsulation
benefits,100
description,4
keypoints,157
overview,88–91
referencevariables,389–390,401
entrypointsinswitchstatements,281
enums,62
caseconstants,278–279
constants,62
declaring,62–64
declaringelements,65–67
equalitytests,241
keypoints,76–77
EOFExceptionclass,311,314
equalsigns(=)
assignment,182,235
boxing,386–387
compoundassignmentoperators,236
equalitytests,237–241
relationaloperators,236–237
equalityandequalityoperators
enums,241
objects,386–387
precedence,257
primitives,238
references,238–240
strings,240–241,281
equals()method,240–241,386–387
equalsIgnoreCase()method,348–349
Errorclass,307
Exceptionclass,306–307
ExceptionInInitializerErrorclass
description,322
initblocks,147
exceptions,298–299
creating,317–318
declarations,312–317
defining,306–307
hierarchy,307–309
interfaceimplementation,123
JVMthrown,319–320
keypoints,327
listof,321–322
matching,309–310
overriddenmethods,108,110
programmaticallythrown,320–321
propagating,303–306
rethrowing,317
sources,319
tryandcatch,299–303
exclamationpoints(!)
booleaninvertoperator,255–256
precedence,257
relationaloperators,236–237
exclusive-OR(XOR)operator,255
executionentrypointsinswitchstatements,281
exit()method
loops,290
tryandcatch,324
explicitcasts,185–186
explicitvaluesinconstructors,134
expressions
enhancedforloops,293
ifstatements,276–277
extendedASCIIset,53
extending
classes,18,102
inheritancein,94
interfaces,124
extendskeyword
illegaluses,127
IS-Arelationships,97
F
Fsuffix,181
factoryclasses,359
fall-throughinswitchstatements,281–283
falsevalue,181
featuresandbenefits,3–5
FileNotFoundExceptionclass,311–312
finalarguments,44–45
finalclasses,20–21,59–61
finalconstants,26–27
finalmethods
nonaccessmembermodifiers,43–45
overriding,108
finalmodifiers
incrementanddecrementoperators,250
variables,42,59
finalize()method,218–219
finallyclauses,301–303
flexibilityfromobjectorientation,88
floattypeandfloating-pointnumbers
assigning,188
casts,187
classes,20
comparisons,237
defaultvalues,196
literals,180–181
ranges,53
underscores,179
flowcontrol,272
breakandcontinuestatements,294–295
doloops,287
forloops,287–293
if-elsebranching,273–277
labeledstatements,295–297
switchstatements.Seeswitchstatementsunlabeledstatements,295
whileloops,285–286
forloops
basic,288–292
enhanced,292–293
forcedexitsfromloops,290
forcinggarbagecollection,215–218
format()method,362
formattingcalendardata,362
fractions,180
fullyqualifiednames,13
G
garbagecollection
cleaningupbefore,218
forcing,215–218
keypoints,222
objectseligiblefor,213–215
overview,210
garbagecollector
operation,212
overview,210
running,210
gc()method,215–216
generics,381
get()method,383
getRuntime()method,216
gettersencapsulation,89
greaterthansigns(>)
precedence,257
relationaloperators,236–237
guardedregions,299
H
HAS-Arelationships
keypoints,157
overview,96–100
heap
garbagecollection,210
keypoints,220
overview,176–177
hexadecimal(base16)literals,178,180
hidingimplementationdetails,89
hierarchyofexceptions,307–309
I
IDE(integrateddevelopmentenvironment),11
identifiers,2
keypoints,70
legal,6–7
if-elsebranching
keypoints,325–326
overview,273–277
IllegalArgumentExceptionclass
description,322
programmaticallythrownexceptions,321
IllegalStateExceptionclass,322
immutability
calendardata,358–359
strings,340–347
implementationdetails,hiding,89
implementinginterfaces
keypoints,159
overview,122–128
implementskeyword
illegaluses,127
IS-Arelationships,97
implicitcasts
assignment,235
primitives,186
importstatements
keypoints,70
overview,13–14
sourcecodefiles,10
static,14–16
incrementoperators
keypoints,261
workingwith,248–250
indexes
ArrayLists,380
arrays,12,368
out-of-range,369
string,348–349
zero-based,12
indexOf()method,ArrayLists,383
IndexOutOfBoundsExceptionclass,308
indirectinterfaceimplementation,243
inheritance
accessmodifiers,31–33,38–39
constructors,140
evolution,93–95
HAS-Arelationships,98–100
IS-Arelationships,96–97
keypoints,157
multiple,102,126–128
overview,3,92–93
inheritedmethods,overriding,109
initialization
arrays,202,368–374
basicforloops,288–289
loopelements,370
objectreferences,201–202
primitives,199–201
variables,56,185
initializationblocks,145–147
inheritance,93
keypoints,161
innerclasses,17
insert()method,354–355
insertingstringelements,355
instancemethods
inheritance,93
overriding,108
polymorphic,104
instancevariables,54–55
constructors,134
defaultvalues,195–198
description,2,193
onheap,176–177
inheritance,93
instanceofoperator
keypoints,260
objecttests,242–243
instances
counting,148
initializationblocks,146
referencesto,151
instantiation,160–161
Integerclass,15–16,321
integersandintdatatype
andbyte,184
caseconstants,278–279
casts,186–187
comparisons,237
defaultvalues,196
literals,178
ranges,53
remainderoperator,246
integrateddevelopmentenvironment(IDE),11
interfaces,2,89
vs.abstractclasses,25
constants,26–27
constructors,136
declaring,23–26
extending,124
implementing,122–128,159
indirectimplementation,243
keypoints,72–73
methods,28–29
names,8–9
overview,3
invertoperator,255–256
invoking
overloadedmethods,112–115
polymorphicmethods,103
IOExceptionclass
checkedexceptions,314
files,311–312
IS-Arelationships
keypoints,157
overview,96–97
polymorphism,101
returntypes,132
ISOLatin-1characters,53
isolationofreferences,214–215
iterationinbasicforloops,289–290
J
javacommand,11–12
java.io.IOExceptionclass
checkedexceptions,314
files,311–312
java.lang.ClassCastExceptionclass
description,322
downcasts,119
java.lang.Exceptionclass,306–307
java.lang.Integerclass,15–16,321
java.lang.Objectclass,92
java.lang.Object.equals()method,240–241
java.lang.Runtimeclass,216
java.lang.RuntimeExceptionclass,308,312–314
java.lang.StringBuilderclass,340
keypoints,398
methods,354–356
overview,352
vs.StringBuffer,352–353
java.time.DateTimeFormatterclass,358,361–362
java.time.LocalDateclass,357,362
java.time.LocalDateTimeclass,357,362
java.time.LocalTimeclass,357,362
java.time.Periodclass,358,361
java.time.temporalpackage,361
java.time.temporal.TemporalAmountinterface,358
java.util.ArrayListclass.SeeArrayListclass
java.util.function.Predicateinterface,393–395
java.util.Listinterface,381
JavaVirtualMachine(JVM),5,11
javac,compilingwith,11
K
keywords,2,7
L
Lsuffix,180
labeledstatements,295–297
lambdas,390–396,401
launchingapplications,11–12
leaks,memory,4
legalidentifiers,6–7
length()method,350
lengthofarraysandstrings,350
lessthansigns(<)
precedence,257
relationaloperators,236–237
libraries,4
listsandListinterface,381
ArrayLists.SeeArrayListclassimplementations,381
literals
binary,179
boolean,181
character,181–182
floating-point,180–181
hexadecimal,180
integer,178
keypoints,220
octal,179
primitiveassignments,183–184
strings,182,347
localarrays,202
localobjectreferences,201–202
localprimitives,199–201
localvariables,198–199
accessmodifiers,42–43
description,193
keypoints,74
onstack,55,176–177
workingwith,55–57
LocalDateclass,357,362
LocalDateTimeclass,357,362
LocalTimeclass,357,362
logicaloperators,251
bitwise,251–252
keypoints,261–262
non-short-circuit,254–256
precedence,257
short-circuit,252–254,276–277
longtype
defaultvalues,196
ranges,53
loopconstructs,285
breakandcontinue,294–295
do,287
elementinitialization,370
for,287–293
keypoints,326
while,285–286
lowercasecharactersinstrings,351
M
main()method,12–13
exceptions,303–305
overloaded,115
maintainability,objectorientationfor,88
markandsweepalgorithm,212
matchingexceptions,309–310
MAX_VALUEconstant,16
meaningfullyequivalentobjects,240
membermodifiers,nonaccess,43–50
members
access.Seeaccessandaccessmodifiersdeclaring,28
keypoints,74–75
memory
garbagecollection.Seegarbagecollectionstrings,347
memoryleaks,210
memorymanagement,4
methods
abstract,45–48
accessmodifiers.SeeaccessandaccessmodifiersArrayLists,382–384
chained,356
description,2
enums,65–66
factory,359
final,43–45,59
instance,104,108
interfaceimplementation,122–123
interfaces,28–29
names,9
native,49
overloaded,111–117
overridden,105–111
recursive,320
stacks,303–305
static,61,148–150
strictfp,49
String,348–352
StringBuilder,354–356
synchronized,48–49
variableargumentlists,49–50
minussigns(–)
compoundassignmentoperators,236
decrementoperators,248–249
precedence,257
subtraction,244
modifiers.Seeaccessandaccessmodifiers
modulusoperator
overview,245–246
precedence,257
multidimensionalarrays
constructing,366
declaring,58–59,364
referenceassignments,377–378
multipleinheritance,102,126–128
multiplication
compoundassignment,236
operator,244
precedence,257
multithreadedprogramming,5
mutatorsinencapsulation,89
N
names
classesandinterfaces,8–9
constants,9
constructors,51,133,135
conventions,2
dotoperator,151
fullyqualified,13
labels,296
methods,9
shadowvariables,208–209
variables,9
narrowingconversions,186
nativemethods,49
negativenumbers
fromcasts,189
representing,53
nestedclasses,17
nestedif-elsestatements,273
newkeyword
arrays,364
calendardata,359
no-argconstructors,135–136
NoClassDefFoundErrorclass,322
nonaccessmembermodifiers,19–20,43
abstractmethods,45–48
finalarguments,44–45
finalmethods,43–45
keypoints,71–72
methodswithvariableargumentlists,49–50
nativemethods,49
strictfpmethods,49
synchronizedmethods,48–49
notequaloperator(!=),237
nullvalues
referencevariables,183,191
returning,130
wrappervariables,388
nullingreferences,213
NullPointerExceptionclass,314
arrays,368
description,322
referencevariables,319–320
wrappervariables,388
NumberFormatExceptionclass
description,322
stringconversions,321
numbers
primitives.Seeprimitives
withstringconcatenation,246–247
withunderscores,178–179
O
Objectclass,92
objectorientation(OO),87–88
benefits,100
casting,118–121
constructors.Seeconstructorsdescription,4
encapsulation,88–91
inheritance,92–100
initializationblocks,145–147
interfaceimplementation,122–128
overloadedmethods,111–117
overriddenmethods,105–111
polymorphism,101–105
returntypes,129–132
statics,148–154
objectsandobjectreferences
arrays,58,363–364,374–375
defaultvalues,196–198
description,2,183
equality,386–387
garbagecollection,213–219
onheap,176–177
initializing,201–202
instanceofcomparisons,242–244
overloadedmethods,113–114
passing,205–207
stringsas,341
octal(base8)integers,178–179
of()method,361
one-dimensionalarrays
constructing,364–366
referenceassignments,376–377
operands,234
operators,233–234
arithmetic,244–249
assignment,235–236
conditional,250–251
incrementanddecrement,248–250
instanceof,242–244
logical,251–256
precedence,256–258,262
relational,236–241
ORexpressions,253–255
orderofinstanceinitializationblocks,146
out-of-rangearrayindexes,369
out-of-scopevariables,194
OutOfMemoryExceptionclass,218
overloadedconstructors,140–145
overloadedmethods,111
invoking,112–115
keypoints,158
legal,112,116
main(),13,115
vs.overridden,112,117
polymorphism,115
returntypes,129
overriddenmethods,105–109
illegal,110–111
invokingsuperclass,109–110
vs.overloaded,112,117
polymorphism,115
returntypes,129–130
static,154
overriding
classes,3
keypoints,158
privatemethods,36
P
package-centriclanguages,17
package-levelaccess,18–19
packagestatementinsourcecodefiles,10
packages
access,17
classesin,14
parameters
vs.arguments,49–50
lambdas,395
parentheses()
arguments,44,50
conditionaloperator,250
inforloops,288
ifexpressions,273,276–277
operatorprecedence,246–247,258,262
stringconcatenation,247
parseInt()method,321
passing
keypoints,221
objectreferencevariables,205–207
pass-by-value,206–207
primitivevariables,207–208
Peabody,Marc,185
percentsigns(%)
precedence,257
remainderoperator,245–246
Periodclass,358,361
pipe(|)characters
bitwiseoperators,251–252
logicalORoperator,253–255
plussigns(+)
addition,244
compoundassignmentoperators,236
incrementoperators,248–249
precedence,257
stringconcatenation,246–248
polymorphism
abstractclasses,22
declarations,381
inheritance,95
keypoints,157
overloadedandoverriddenmethods,115
overview,101–105
poolsforStringconstants,347
postfixincrementoperators,248–249
precedenceofoperators,245,247,256–258,262
precision
casts,186,188–189
floating-pointliterals,181
floating-pointnumbers,188
Predicateinterface,393–395
prefixincrementoperators,248–249
primitives
arrays,58,363–364,374
assignments,183–185,190
casting,185–188,220
comparisons,238
declarations,51–53
defaultvalues,195–196
final,59
initializing,199–201
literals,178–182
passing,207–208
returning,131
wrapperclasses,192
printStackTrace()method,308
privatemodifiers,30
overriding,36
overview,34–36
programmaticallythrownexceptions,320–321
ProjectCoin,diamondsyntax,388–389
propagatinguncaughtexceptions,303–306
protectedmodifiers,30,36–42
publicaccess,19
publicinterfaceforexceptions,312–317
publicmodifiers,30
constants,26–27
encapsulation,89
overview,33–34
publicstaticvoidmain()method,12–13
Q
questionmarks(?)forconditionaloperators,250–251
R
ranges,numbers,53
reachableobjects,210
reassigningreferencevariables,213–214
recursivemethods,320
redefinedstaticmethods,154
referencecounting,212
references,101
arrays,368
assigning,190–191,202–203
casting,118–121,159
declaring,53–54
description,183
encapsulation,389–390,401
equality,238–240
instances,151
isolating,214–215
multidimensionalarrays,377–378
nulling,213
one-dimensionalarrays,376–377
overloadedmethods,113–114
passing,205–207
reassigning,213–214
returning,130
strings,342–347
regions,guarded,299
relationaloperators,236–237
equality,237–241
keypoints,260
precedence,257
remainderoperator,245–246
remove()method,384
removingArrayListelements,384
replace()method,350
replacingstringelements,350
rethrowingexceptions,317
returnstatement
forloops,290
lambdas,395
returntype
constructors,51,133,135
declarations,129–132
keypoints,159
overloadedmethods,111,129
overriddenmethods,108,129–130
returningvalues,130–131
reuse
inheritancefor,94
names,208–209
reverse()method,355
reversingstrings,355
rules
constructors,135–136
sourcefile,10
Runtimeclass,216
runtimeexceptionsforoverriddenmethods,108
RuntimeExceptionclass,308,312–314
S
sandbox,5
scope
inforloops,291
keypoints,220
variables,192–195
security,5
semicolons(;)
abstractmethods,22,45
enums,64
inforloops,288
labels,296
lambdas,395
nativemethods,49
whileloops,287
serialization,5
settersencapsulation,89
shadowedvariables,56,193,208–209
short-circuitlogicaloperators
ifstatements,276–277
overview,252–254
precedence,257
shorttype
caseconstants,278–279
defaultvalues,196
ranges,53
signaturesofmethods,117,123
signednumbers,53
size
ArrayLists,383–384
arrays,59,364,366,370,372,374
assignmentissues,235
numbers,53
size()method,383–384
slashes(/)
compoundassignmentoperators,236
division,244
precedence,257
sourcecodefiledeclarationrules,10,71
squarebrackets([])
arrayelements,58
arrays,363
stack
exceptions,320
keypoints,220
localvariables,55
methods,303–305
overview,176–177
StackOverflowErrorclass
description,322
recursivemethods,320
states,2
staticconstants,26–27
staticimports,14–16
staticinitializationblocks,146
staticinterfacemethods,28–29
staticvariablesandmethods,14–15,61
constructors,136
description,193
inheritance,93
keypoints,76,161
overriding,109,154
overview,148–150
streams,390
strictfpmodifiers
classes,19–20
methods,49
Stringclass,340–347
constantpool,347
keypoints,398
methods,348–352
objectreferences,203–204
StringBufferclass,340,352–353
StringBuilderclass,340
keypoints,398
methods,354–356
overview,352
vs.StringBuffer,352–353
StringIndexOutOfBoundsExceptionclass,308–309
strings,340
appending,341–342,353–354
caseconstants,278–279
comparing,348–349
concatenating,246–248,261,348–349
creating,348
deleting,354–355
equality,240–241,281
immutability,340–347
insertingelementsinto,355
keypoints,398
length,350
literals,182,347
lowercase,351
memory,347
methods,348–352
replacingelementsin,350
reversing,355
substrings,350–351
trimming,352
uppercase,351
strongtyping,5
subclasses
concrete,46–47
inheritance,3
substring()method,350–351
subtraction
compoundassignment,236
operator,244
precedence,257
subtypesforreferencevariables,101
super()callsforconstructors,144
superconstructorarguments,137
superclasses,3
constructors,135
overriddenmethods,109–110
switchstatements,278
breakandfall-through,281–283
defaultcase,283–284
exercise,285
keypoints,325–326
legalexpressions,278–280
stringequality,281
synchronizationmethods,48–49
System.exit()method
loops,290
tryandcatch,324
System.gc()method,215–216
T
TemporalAmountinterface,358
ternaryoperator
conditional,250–251
keypoints,261
test()method,393,396
this()callsforconstructors,135,144
thiskeyword,57
threadsingarbagecollector,212
three-dimensionalarrays,59,364
Throwableclass,307
thrownexceptions
description,299
JVM,319–320
programmatically,320–321
timedata
usingandmanipulating,360–361
formatting,362
toLowerCase()method,351
toString()method
ArrayLists,381
String,351
StringBuilder,356
toUpperCase()method,351
transientvariables,60–61
trim()method,352
truevalue,181
truncatingfromcasts,189
tryandcatchfeature
finally,301–303
overview,299–300
two-dimensionalarrays,59,364
two’scomplementnotationandcasts,189
types
arraydeclarations,363
assignments,235
casting.Seecasts
return.Seereturntype
variables,183
U
\uprefix,181
UML(UnifiedModelingLanguage),100
unaryoperators,precedence,257
unassignedvariables
keypoints,221
workingwith,195–199
uncaughtexceptions,303–306
uncheckedexceptions
description,314–315
overriddenmethods,108
underscores(_)innumericliterals,178–179
Unicodecharacters
chartype,53
identifiers,6
literals,181
strings,341
UnifiedModelingLanguage(UML),100
uninitializedvariables
keypoints,221
workingwith,195–199
unlabeledstatements,295
until()method,361
unwindingthestack,308
upcasting,120
uppercaseforstrings,351
V
values()method,66
valuesofvariables,182
var-args
keypoints,75
methods,49–50
variableargumentlists,49–50
variables
access.Seeaccessandaccessmodifiersassignments.Seeassignmentsdeclarations,51–53,75–
76
description,2
enums,65–66
final,59
inforloops,291
heapandstack,176–177
initializing,185
instance,54–55
local.Seelocalvariables
names,9
primitives,51–53
scope,192–195
shadow,208–209
static,61,148–150
transient,60–61
uninitializedandunassigned,195–199,221
values,182
volatile,61
verticalbars(|)
bitwiseoperators,251–252
logicalORoperator,253–255
precedence,257
visibility,access,18,43
voidreturntype,131
volatilevariables,61
W
Walraven,Fritz,258
whileloops
labeled,297
workingwith,285–286
whitespace,trimmingfromstrings,352
wideningconversions,186
wildcardsinimportstatements,14,16
wrapperclasses
primitives,192
strings,320