You are on page 1of 32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Java A Beginner's Guide, 6th Edition

Recent

Topics
Tutorials
NEXT

PREV

Chapter 17: Introd

Appendix B: Using

Highlights

Settings
Feedback(http://community.safaribooksonline.com)
Sign Out

Settings
AppendixA
AnswerstoSelfTests

days left in your trial. Subscribe.

Chapter1:JavaFundamentals

Feedback(http://community.safaribooksonline.com/)

1.WhatisbytecodeandwhyisitimportanttoJavasusefor
Internetprogramming?
Bytecodeisahighlyoptimizedsetofinstructionsthatisexecutedbythe
Sign Out
JavaVirtualMachine.BytecodehelpsJavaachievebothportabilityand
security.
2.Whatarethethreemainprinciplesofobjectoriented
programming?
Encapsulation,polymorphism,andinheritance.
3.WheredoJavaprogramsbeginexecution?
Javaprogramsbeginexecutionatmain().
4.Whatisavariable?
Avariableisanamedmemorylocation.Thecontentsofavariablecanbe
changedduringtheexecutionofaprogram.
5.Whichofthefollowingvariablenamesisinvalid?
TheinvalidvariableisD.Variablenamescannotbeginwithadigit.
6.Howdoyoucreateasinglelinecomment?Howdoyoucreate
amultilinecomment?
Asinglelinecommentbeginswith//andendsattheendoftheline.A

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

1/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

multilinecommentbeginswith/*andendswith*/.
7.Showthegeneralformoftheifstatement.Showthegeneral
formoftheforloop.
Thegeneralformoftheif:
if(condition)statement
Thegeneralformofthefor:
for(initializationconditioniteration)statement
8.Howdoyoucreateablockofcode?
Ablockofcodeisstartedwitha{andendedwitha}.
9.Themoonsgravityisabout17percentthatoftheearths.Write
aprogramthatcomputesyoureffectiveweightonthemoon.

10.AdaptTryThis12sothatitprintsaconversiontableofinches
tometers.Display12feetofconversions,inchbyinch.Outputa
blanklineevery12inches.(Onemeterequalsapproximately39.37
inches.)

11.Ifyoumakeatypingmistakewhenenteringyourprogram,
whatsortoferrorwillresult?
Asyntaxerror.
12.Doesitmatterwhereonalineyouputastatement?

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

2/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

No,Javaisafreeformlanguage.
Chapter2:IntroducingDataTypesandOperators
1.WhydoesJavastrictlyspecifytherangeandbehaviorofits
primitivetypes?
Javastrictlyspecifiestherangeandbehaviorofitsprimitivetypesto
ensureportabilityacrossplatforms.
2.WhatisJavascharactertype,andhowdoesitdifferfromthe
charactertypeusedbysomeotherprogramminglanguages?
Javascharactertypeischar.JavacharactersareUnicoderatherthan
ASCII,whichisusedbysomeothercomputerlanguages.
3.Abooleanvaluecanhaveanyvalueyoulikebecauseany
nonzerovalueistrue.TrueorFalse?
False.Abooleanvaluemustbeeithertrueorfalse.
4.Giventhisoutput,

useasinglestringtoshowtheprintln()statementthatproducedit.

5.Whatiswrongwiththisfragment?

Therearetwofundamentalflawsinthefragment.First,sumiscreated
eachtimetheblockdefinedbytheforloopisenteredanddestroyedon
exit.Thus,itwillnotholditsvaluebetweeniterations.Attemptingtouse
sumtoholdarunningsumoftheiterationsispointless.Second,sum
willnotbeknownoutsideoftheblockinwhichitisdeclared.Thus,the
referencetoitintheprintln()statementisinvalid.
6.Explainthedifferencebetweentheprefixandpostfixformsof
theincrementoperator.
Whentheincrementoperatorprecedesitsoperand,Javawillperform
theincrementpriortoobtainingtheoperandsvalueforusebytherestof
theexpression.Iftheoperatorfollowsitsoperand,thenJavawillobtain
theoperandsvaluebeforeincrementing.
7.ShowhowashortcircuitANDcanbeusedtopreventadivide
byzeroerror.

8.Inanexpression,whattypearebyteandshortpromotedto?
Inanexpression,byteandshortarepromotedtoint.
9.Ingeneral,whenisacastneeded?
Acastisneededwhenconvertingbetweenincompatibletypesorwhena
narrowingconversionisoccurring.
10.Writeaprogramthatfindsalloftheprimenumbersbetween2
and100.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

3/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

11.Doestheuseofredundantparenthesesaffectprogram
performance?

No.
Enjoy Safari?
Subscribe Today

12.Doesablockdefineascope?
Yes.

You have 8 days


left in your trial, V9ansa.
Chapter3:ProgramControlStatements

1.Writeaprogramthatreadscharactersfromthekeyboarduntil
aperiodisreceived.Havetheprogramcountthenumberofspaces.
Reportthetotalattheendoftheprogram.

Safari is your trusted guide for building a


remarkable career. We hope you've been
enjoying your trialready to join?

Subscribe Today
2.Showthegeneralformoftheifelseifladder.

/ Contact Us(http://safaribooksonline.com/contact/) /
Blog(http://blog.safaribooksonline.com)
2015 Safari(http://www.safaribooksonline.com)
Terms of Service /
Membership Agreement / Privacy Policy

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

4/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

3.Given

towhatifdoesthelastelseassociate?
Thelastelseassociateswithif(y>100).
4.Showtheforstatementforaloopthatcountsfrom1000to0by
2.

5.Isthefollowingfragmentvalid?

Noiisnotknownoutsideoftheforloopinwhichitisdeclared.
6.Explainwhatbreakdoes.Besuretoexplainbothofitsforms.
Abreakwithoutalabelcausesterminationofitsimmediatelyenclosing
looporswitchstatement.Abreakwithalabelcausescontroltotransfer
totheendofthelabeledblock.
7.Inthefollowingfragment,afterthebreakstatementexecutes,
whatisdisplayed?

Afterbreakexecutes,afterwhileisdisplayed.
8.Whatdoesthefollowingfragmentprint?

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

5/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Hereistheanswer:

9.Theiterationexpressioninaforloopneednotalwaysalterthe
loopcontrolvariablebyafixedamount.Instead,theloopcontrol
variablecanchangeinanyarbitraryway.Usingthisconcept,
writeaprogramthatusesaforlooptogenerateanddisplaythe
progression1,2,4,8,16,32,andsoon.

10.TheASCIIlowercaselettersareseparatedfromtheuppercase
lettersby32.Thus,toconvertalowercaselettertouppercase,
subtract32fromit.Usethisinformationtowriteaprogramthat
readscharactersfromthekeyboard.Haveitconvertalllowercase
letterstouppercase,andalluppercaseletterstolowercase,
displayingtheresult.Makenochangestoanyothercharacter.
Havetheprogramstopwhentheuserentersaperiod.Attheend,
havetheprogramdisplaythenumberofcasechangesthathave
takenplace.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

6/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

11.Whatisaninfiniteloop?
Aninfiniteloopisaloopthatrunsindefinitely.
12.Whenusingbreakwithalabel,mustthelabelbeonablock
thatcontainsthebreak?
Yes.
Chapter4:IntroducingClasses,Objects,andMethods
1.Whatisthedifferencebetweenaclassandanobject?
Aclassisalogicalabstractionthatdescribestheformandbehaviorofan
object.Anobjectisaphysicalinstanceoftheclass.
2.Howisaclassdefined?
Aclassisdefinedbyusingthekeywordclass.Insidetheclass
statement,youspecifythecodeanddatathatcomprisetheclass.
3.Whatdoeseachobjecthaveitsowncopyof?
Eachobjectofaclasshasitsowncopyoftheclassinstancevariables.
4.Usingtwoseparatestatements,showhowtodeclareanobject
calledcounterofaclasscalledMyCounter.

5.ShowhowamethodcalledmyMeth()isdeclaredifithasa
returntypeofdoubleandhastwointparameterscalledaandb.

6.Howmustamethodreturnifitreturnsavalue?
Amethodthatreturnsavaluemustreturnviathereturnstatement,
passingbackthereturnvalueintheprocess.
7.Whatnamedoesaconstructorhave?
Aconstructorhasthesamenameasitsclass.
8.Whatdoesnewdo?
Thenewoperatorallocatesmemoryforanobjectandinitializesitusing
theobjectsconstructor.
9.Whatisgarbagecollectionandhowdoesitwork?Whatis
finalize()?
Garbagecollectionisthemechanismthatrecyclesunusedobjectssothat
theirmemorycanbereused.Anobjectsfinalize()methodiscalledjust

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

7/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

priortoanobjectbeingrecycled.
10.Whatisthis?
Thethiskeywordisareferencetotheobjectonwhichamethodis
invoked.Itisautomaticallypassedtoamethod.
11.Canaconstructorhaveoneormoreparameters?
Yes.
12.Ifamethodreturnsnovalue,whatmustitsreturntypebe?
void
Chapter5:MoreDataTypesandOperators
1.Showtwowaystodeclareaonedimensionalarrayof12
doubles.

2.Showhowtoinitializeaonedimensionalarrayofintegersto
thevalues1through5.

3.Writeaprogramthatusesanarraytofindtheaverageoften
doublevalues.Useanytenvaluesyoulike.

4.ChangethesortinTryThis51sothatitsortsanarrayof
strings.Demonstratethatitworks.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

8/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

5.WhatisthedifferencebetweentheStringmethodsindexOf()
andlastIndexOf()?
TheindexOf()methodfindsthefirstoccurrenceofthespecified
substring.lastIndexOf()findsthelastoccurrence.
6.SinceallstringsareobjectsoftypeString,showhowyoucan
callthelength()andcharAt()methodsonthisstringliteral:"I
likeJava".
Asstrangeasitmaylook,thisisavalidcalltolength():
Theoutputdisplayedis11.charAt()iscalledinasimilarfashion.
7.ExpandingontheEncodecipherclass,modifyitsothatituses
aneightcharacterstringasthekey.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

9/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

8.Canthebitwiseoperatorsbeappliedtothedoubletype?
No.
9.Showhowthissequencecanberewrittenusingthe?operator.

Hereistheanswer:

10.Inthefollowingfragment,isthe&abitwiseorlogical
operator?Why?

Itisalogicaloperatorbecausetheoperandsareoftypeboolean.
11.Isitanerrortooverruntheendofanarray?
Yes.
Isitanerrortoindexanarraywithanegativevalue?
Yes.Allarrayindexesstartatzero.
12.Whatistheunsignedrightshiftoperator?
13.RewritetheMinMaxclassshownearlierinthischapterso
thatitusesaforeachstyleforloop.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

10/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

14.CantheforloopsthatperformsortingintheBubbleclass
showninTryThis51beconvertedintoforeachstyleloops?Ifnot,
whynot?
No,theforloopsintheBubbleclassthatperformthesortcannotbe
convertedintoforeachstyleloops.Inthecaseoftheouterloop,the
currentvalueofitsloopcounterisneededbytheinnerloop.Inthecase
oftheinnerloop,outofordervaluesmustbeexchanged,whichimplies
assignments.Assignmentstotheunderlyingarraycannottakeplace
whenusingaforeachstyleloop.
15.CanaStringcontrolaswitchstatement?
BeginningwithJDK7,theanswerisYes.
Chapter6:ACloserLookatMethodsandClasses
1.Giventhisfragment,

isthefollowingfragmentcorrect?

Noaprivatemembercannotbeaccessedoutsideofitsclass.
2.Anaccessmodifiermust__________amembers
declaration.
precede
3.Thecomplementofaqueueisastack.Itusesfirstin,lastout
accessingandisoftenlikenedtoastackofplates.Thefirstplate
putonthetableisthelastplateused.Createastackclasscalled
Stackthatcanholdcharacters.Callthemethodsthataccessthe
stackpush()andpop().Allowtheusertospecifythesizeofthe
stackwhenitiscreated.KeepallothermembersoftheStackclass
private.(Hint:YoucanusetheQueueclassasamodeljustchange
thewaythatthedataisaccessed.)

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

11/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

12/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Hereistheoutputfromtheprogram:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

13/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

4.Giventhisclass,

writeamethodcalledswap()thatexchangesthecontentsoftheobjects
referredtobytwoTestobjectreferences.

5.Isthefollowingfragmentcorrect?

No.Overloadedmethodscanhavedifferentreturntypes,buttheydonot
playaroleinoverloadresolution.Overloadedmethodsmusthave
differentparameterlists.
6.Writearecursivemethodthatdisplaysthecontentsofastring
backwards.

7.Ifallobjectsofaclassneedtosharethesamevariable,how
mustyoudeclarethatvariable?
Sharedvariablesaredeclaredasstatic.
8.Whymightyouneedtouseastaticblock?

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

14/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Astaticblockisusedtoperformanyinitializationsrelatedtotheclass,
beforeanyobjectsarecreated.
9.Whatisaninnerclass?
Aninnerclassisanonstaticnestedclass.
10.Tomakeamemberaccessiblebyonlyothermembersofits
class,whataccessmodifiermustbeused?
private
11.Thenameofamethodplusitsparameterlistconstitutesthe
methods__________.
signature
12.Anintargumentispassedtoamethodbyusingcallby
__________.
value
13.Createavarargsmethodcalledsum()thatsumstheintvalues
passedtoit.Haveitreturntheresult.Demonstrateitsuse.
Therearemanywaystocraftthesolution.Hereisone:

14.Canavarargsmethodbeoverloaded?
Yes.
15.Showanexampleofanoverloadedvarargsmethodthatis
ambiguous.
Hereisoneexampleofanoverloadedvarargsmethodthatisambiguous:

IfyoutrytocallmyMeth()withoneargument,likethis,

thecompilercantdeterminewhichversionofthemethodtoinvoke.
Chapter7:Inheritance
1.Doesasuperclasshaveaccesstothemembersofasubclass?
Doesasubclasshaveaccesstothemembersofasuperclass?
No,asuperclasshasnoknowledgeofitssubclasses.Yes,asubclasshas
accesstoallnonprivatemembersofitssuperclass.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

15/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

2.CreateasubclassofTwoDShapecalledCircle.Includean
area()methodthatcomputestheareaofthecircleanda
constructorthatusessupertoinitializetheTwoDShapeportion.

3.Howdoyoupreventasubclassfromhavingaccesstoamember
ofasuperclass?
Topreventasubclassfromhavingaccesstoasuperclassmember,declare
thatmemberasprivate.
4.Describethepurposeanduseofthetwoversionsofsuper
describedinthischapter.
Thesuperkeywordhastwoforms.Thefirstisusedtocallasuperclass
constructor.Thegeneralformofthisusageis
super(paramlist)
Thesecondformofsuperisusedtoaccessasuperclassmember.Ithas
thisgeneralform:
super.member
5.Giventhefollowinghierarchy,inwhatorderdothe
constructorsfortheseclassescompletetheirexecutionwhena
Gammaobjectisinstantiated?

Constructorscompletetheirexecutioninorderofderivation.Thus,when
aGammaobjectiscreated,theorderisAlpha,Beta,Gamma.
6.Asuperclassreferencecanrefertoasubclassobject.Explain
whythisisimportantasitisrelatedtomethodoverriding.
Whenanoverriddenmethodiscalledthroughasuperclassreference,itis
thetypeoftheobjectbeingreferredtothatdetermineswhichversionof
themethodiscalled.
7.Whatisanabstractclass?
Anabstractclasscontainsatleastoneabstractmethod.
8.Howdoyoupreventamethodfrombeingoverridden?Howdo
youpreventaclassfrombeinginherited?
Topreventamethodfrombeingoverridden,declareitasfinal.To
preventaclassfrombeinginherited,declareitasfinal.
9.Explainhowinheritance,methodoverriding,andabstract
classesareusedtosupportpolymorphism.
Inheritance,methodoverriding,andabstractclassessupport
polymorphismbyenablingyoutocreateageneralizedclassstructurethat

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

16/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

canbeimplementedbyavarietyofclasses.Thus,theabstractclass
definesaconsistentinterfacethatissharedbyallimplementingclasses.
Thisembodiestheconceptofoneinterface,multiplemethods.
10.Whatclassisasuperclassofeveryotherclass?
TheObjectclass.
11.Aclassthatcontainsatleastoneabstractmethodmust,itself,
bedeclaredabstract.TrueorFalse?
True.
12.Whatkeywordisusedtocreateanamedconstant?
final
Chapter8:PackagesandInterfaces
1.UsingthecodefromTryThis81,puttheICharQinterface
anditsthreeimplementationsintoapackagecalledqpack.
KeepingthequeuedemonstrationclassIQDemointhedefault
package,showhowtoimportandusetheclassesinqpack.
ToputICharQanditsimplementationsintotheqpackpackage,you
mustseparateeachintoitsownfile,makeeachimplementationclass
public,andaddthisstatementtothetopofeachfile.

Oncethishasbeendone,youcanuseqpackbyaddingthisimport
statementtoIQDemo.

2.Whatisanamespace?WhyisitimportantthatJavaallowsyou
topartitionthenamespace?
Anamespaceisadeclarativeregion.Bypartitioningthenamespace,you
canpreventnamecollisions.
3.Packagesarestoredin__________.
directories
4.Explainthedifferencebetweenprotectedanddefaultaccess.
Amemberwithprotectedaccesscanbeusedwithinitspackageandbya
subclassinanypackage.
Amemberwithdefaultaccesscanbeusedonlywithinitspackage.
5.Explainthetwowaysthatthemembersofapackagecanbe
usedbyotherpackages.
Touseamemberofapackage,youcaneitherfullyqualifyitsname,or
youcanimportitusingimport.
6.Oneinterface,multiplemethodsisakeytenetofJava.What
featurebestexemplifiesit?
Theinterfacebestexemplifiestheoneinterface,multiplemethods
principleofOOP.
7.Howmanyclassescanimplementaninterface?Howmany
interfacescanaclassimplement?
Aninterfacecanbeimplementedbyanunlimitednumberofclasses.A
classcanimplementasmanyinterfacesasitchooses.
8.Caninterfacesbeextended?
Yes,interfacescanbeextended.
9.CreateaninterfacefortheVehicleclassfromChapter7.Call
theinterfaceIVehicle.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

17/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

10.Variablesdeclaredinaninterfaceareimplicitlystaticand
final.Cantheybesharedwithotherpartsofaprogram?
Yes,interfacevariablescanbeusedasnamedconstantsthatareshared
byallfilesinaprogram.Theyarebroughtintoviewbyimportingtheir
interface.
11.Apackageis,inessence,acontainerforclasses.Trueor
False?
True.
12.WhatstandardJavapackageisautomaticallyimportedintoa
program?
java.lang
13.Whatkeywordisusedtodeclareadefaultinterfacemethod?
default
14.BeginningwithJDK8,isitpossibletodefineastaticmethod
inaninterface?
Yes
15.AssumethattheICharQinterfaceshowninTryThis81has
beeninwidespreaduseforseveralyears.Now,youwanttoadda
methodtoitcalledreset(),whichwillbeusedtoresetthequeueto
itsempty,startingcondition.AssumingJDK8orlater,howcan
thisbeaccomplishedwithoutbreakingpreexistingcode?
Toavoidbreakingpreexistingcode,youmustuseadefaultinterface
method.Becauseyoucantknowhowtoreseteachqueue
implementation,thedefaultreset()implementationwillneedtoreport
anerrorthatindicatesthatitisnotimplemented.(Thebestwaytodothis
istouseanexception.Exceptionsareexaminedinthefollowing
chapter.)Fortunately,sincenopreexistingcodeassumesthatICharQ
definesareset()method,nopreexistingcodewillencounterthaterror,
andnopreexistingcodewillbebroken.
16.Howisastaticmethodinaninterfacecalled?
Astaticinterfacemethodiscalledthroughitsinterfacename,byuseof
thedotoperator.
Chapter9:ExceptionHandling
1.Whatclassisatthetopoftheexceptionhierarchy?
Throwableisatthetopoftheexceptionhierarchy.
2.Brieflyexplainhowtousetryandcatch.
Thetryandcatchstatementsworktogether.Programstatementsthat
youwanttomonitorforexceptionsarecontainedwithinatryblock.An
exceptioniscaughtusingcatch.
3.Whatiswrongwiththisfragment?

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

18/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Thereisnotryblockprecedingthecatchstatement.
4.Whathappensifanexceptionisnotcaught?
Ifanexceptionisnotcaught,abnormalprogramterminationresults.
5.Whatiswrongwiththisfragment?

Inthefragment,asuperclasscatchprecedesasubclasscatch.Sincethe
superclasscatchwillcatchallsubclassestoo,unreachablecodeis
created.
6.Cananinnercatchrethrowanexceptiontoanoutercatch?
Yes,anexceptioncanberethrown.
7.Thefinallyblockisthelastbitofcodeexecutedbeforeyour
programends.TrueorFalse?Explainyouranswer.
False.Thefinallyblockisthecodeexecutedwhenatryblockends.
8.Whattypeofexceptionsmustbeexplicitlydeclaredina
throwsclauseofamethod?
AllexceptionsexceptthoseoftypeRuntimeExceptionandErrormust
bedeclaredinathrowsclause.
9.Whatiswrongwiththisfragment?

MyClassdoesnotextendThrowable.OnlysubclassesofThrowable
canbethrownbythrow.
10.Inquestion3oftheChapter6SelfTest,youcreatedaStack
class.Addcustomexceptionstoyourclassthatreportstackfulland
stackemptyconditions.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

19/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

20/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

11.Whatarethethreewaysthatanexceptioncanbegenerated?
AnexceptioncanbegeneratedbyanerrorintheJVM,byanerrorin
yourprogram,orexplicitlyviaathrowstatement.
12.WhatarethetwodirectsubclassesofThrowable?
ErrorandException
13.Whatisthemulticatchfeature?
Themulticatchfeatureallowsonecatchclausetocatchtwoormore
exceptions.
14.ShouldyourcodetypicallycatchexceptionsoftypeError?
No.
Chapter10:UsingI/O
1.WhydoesJavadefinebothbyteandcharacterstreams?
ThebytestreamsaretheoriginalstreamsdefinedbyJava.Theyare
especiallyusefulforbinaryI/O,andtheysupportrandomaccessfiles.
ThecharacterstreamsareoptimizedforUnicode.
2.Eventhoughconsoleinputandoutputistextbased,whydoes
Javastillusebytestreamsforthispurpose?
Thepredefinedstreams,System.in,System.out,andSystem.err,
weredefinedbeforeJavaaddedthecharacterstreams.
3.Showhowtoopenafileforreadingbytes.
Hereisonewaytoopenafileforbyteinput:
4.Showhowtoopenafileforreadingcharacters.
Hereisonewaytoopenafileforreadingcharacters:

5.ShowhowtoopenafileforrandomaccessI/O.
Hereisonewaytoopenafileforrandomaccess:
6.Howdoyouconvertanumericstringsuchas"123.23"intoits
binaryequivalent?
Toconvertnumericstringsintotheirbinaryequivalents,usetheparsing
methodsdefinedbythetypewrappers,suchasIntegerorDouble.
7.Writeaprogramthatcopiesatextfile.Intheprocess,haveit
convertallspacesintohyphens.Usethebytestreamfileclasses.
Usethetraditionalapproachtoclosingafilebyexplicitlycalling
close().

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

21/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

8.Rewritetheprograminquestion7sothatitusesthecharacter
streamclasses.Thistime,usethetrywithresourcesstatementto
automaticallyclosethefile.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

22/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

9.WhattypeofstreamisSystem.in?
InputStream
10.Whatdoestheread()methodofInputStreamreturnwhen
theendofthestreamisreached?
1
11.Whattypeofstreamisusedtoreadbinarydata?
DataInputStream
12.ReaderandWriterareatthetopofthe____________
classhierarchies.
characterbasedI/O
13.Thetrywithresourcesstatementisusedfor___________
________________________.
automaticresourcemanagement
14.Ifyouareusingthetraditionalmethodofclosingafile,then
closingafilewithinafinallyblockisgenerallyagoodapproach.
TrueorFalse?
True
Chapter11:MultithreadedProgramming
1.HowdoesJavasmultithreadingcapabilityenableyoutowrite
moreefficientprograms?
Multithreadingallowsyoutotakeadvantageoftheidletimethatis
presentinnearlyallprograms.Whenonethreadcantrun,anothercan.
Inmulticoresystems,twoormorethreadscanexecutesimultaneously.
2.Multithreadingissupportedbythe__________classandthe

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

23/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

__________interface.
MultithreadingissupportedbytheThreadclassandtheRunnable
interface.
3.Whencreatingarunnableobject,whymightyouwantto
extendThreadratherthanimplementRunnable?
YouwillextendThreadwhenyouwanttooverrideoneormoreof
Threadsmethodsotherthanrun().
4.Showhowtousejoin()towaitforathreadobjectcalled
MyThrdtoend.

5.ShowhowtosetathreadcalledMyThrdtothreelevelsabove
normalpriority.
6.Whatistheeffectofaddingthesynchronizedkeywordtoa
method?
Addingsynchronizedtoamethodallowsonlyonethreadatatimeto
usethemethodforanygivenobjectofitsclass.
7.Thewait()andnotify()methodsareusedtoperform
____________________.
interthreadcommunication
8.ChangetheTickTockclasssothatitactuallykeepstime.That
is,haveeachticktakeonehalfsecond,andeachtocktakeonehalf
second.Thus,eachticktockwilltakeonesecond.(Dontworry
aboutthetimeittakestoswitchtasks,etc.)
TomaketheTickTockclassactuallykeeptime,simplyaddcallsto
sleep(),asshownhere:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

24/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

9.Whycantyouusesuspend(),resume(),andstop()for
newprograms?
Thesuspend(),resume(),andstop()methodshavebeendeprecated
becausetheycancauseseriousruntimeproblems.
10.WhatmethoddefinedbyThreadobtainsthenameofa
thread?
getName()
11.WhatdoesisAlive()return?
Itreturnstrueiftheinvokingthreadisstillrunning,andfalseifithas
beenterminated.
Chapter12:Enumerations,Autoboxing,StaticImport,and
Annotations
1.Enumerationconstantsaresaidtobeselftyped.Whatdoesthis
mean?
Inthetermselftyped,theselfreferstothetypeoftheenumerationin
whichtheconstantisdefined.Thus,anenumerationconstantisanobject
oftheenumerationofwhichitisapart.
2.Whatclassdoallenumerationsautomaticallyinherit?
TheEnumclassisautomaticallyinheritedbyallenumerations.
3.Giventhefollowingenumeration,writeaprogramthatuses
values()toshowalistoftheconstantsandtheirordinalvalues.

Thesolutionis

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

25/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

4.ThetrafficlightsimulationdevelopedinTryThis121canbe
improvedwithafewsimplechangesthattakeadvantageofan
enumerationsclassfeatures.Intheversionshown,thedurationof
eachcolorwascontrolledbytheTrafficLightSimulatorclassby
hardcodingthesevaluesintotherun()method.Changethisso
thatthedurationofeachcolorisstoredbytheconstantsinthe
TrafficLightColorenumeration.Todothis,youwillneedtoadd
aconstructor,aprivateinstancevariable,andamethodcalled
getDelay().Aftermakingthesechanges,whatimprovementsdo
yousee?Onyourown,canyouthinkofotherimprovements?
(Hint:Tryusingordinalvaluestoswitchlightcolorsratherthan
relyingonaswitchstatement.)
Theimprovedversionofthetrafficlightsimulationisshownhere.There
aretwomajorimprovements.First,alightsdelayisnowlinkedwithits
enumerationvalue,whichgivesmorestructuretothecode.Second,the
run()methodnolongerneedstouseaswitchstatementtodetermine
thelengthofthedelay.Instead,sleep()ispassedtlc.getDelay(),which
causesthedelayassociatedwiththecurrentcolortobeused
automatically.

5.Defineboxingandunboxing.Howdoesautoboxing/unboxing
affecttheseactions?
Boxingistheprocessofstoringaprimitivevalueinatypewrapper
object.Unboxingistheprocessofretrievingtheprimitivevaluefromthe
typewrapper.Autoboxingautomaticallyboxesaprimitivevaluewithout
havingtoexplicitlyconstructanobject.Autounboxingautomatically
retrievestheprimitivevaluefromatypewrapperwithouthavingto
explicitlycallamethod,suchasintValue().
6.Changethefollowingfragmentsothatitusesautoboxing.
Thesolutionis
7.Inyourownwords,whatdoesstaticimportdo?
Staticimportbringsintotheglobalnamespacethestaticmembersofa
classorinterface.Thismeansthatstaticmemberscanbeusedwithout
havingtobequalifiedbytheirclassorinterfacename.
8.Whatdoesthisstatementdo?
ThestatementbringsintotheglobalnamespacetheparseInt()method
ofthetypewrapperInteger.
9.Isstaticimportdesignedforspecialcasesituations,orisit
goodpracticetobringallstaticmembersofallclassesintoview?
Staticimportisdesignedforspecialcases.Bringingmanystaticmembers
intoviewwillleadtonamespacecollisionsanddestructureyourcode.
10.Anannotationissyntacticallybasedona/an
________________.
interface
11.Whatisamarkerannotation?
Amarkerannotationisonethatdoesnottakearguments.
12.Anannotationcanbeappliedonlytomethods.TrueorFalse?
False.Anytypeofdeclarationcanhaveanannotation.Beginningwith
JDK8,atypeusecanalsohaveanannotation.
Chapter13:Generics
1.GenericsareimportanttoJavabecausetheyenablethe
creationofcodethatis
A.Typesafe
B.Reusable
C.Reliable
D.Alloftheabove

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

26/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

D.Alloftheabove
2.Canaprimitivetypebeusedasatypeargument?
No,typeargumentsmustbeobjecttypes.
3.ShowhowtodeclareaclasscalledFlightSchedthattakestwo
genericparameters.
Thesolutionis
4.Beginningwithyouranswertoquestion3,change
FlightSchedssecondtypeparametersothatitmustextend
Thread.
Thesolutionis
5.Now,changeFlightSchedsothatitssecondtypeparameter
mustbeasubclassofitsfirsttypeparameter.
Thesolutionis
6.Asitrelatestogenerics,whatisthe?andwhatdoesitdo?
The?isthewildcardargument.Itmatchesanyvalidtype.
7.Canthewildcardargumentbebounded?
Yes,awildcardcanhaveeitheranupperorlowerbound.
8.AgenericmethodcalledMyGen()hasonetypeparameter.
Furthermore,MyGen()hasoneparameterwhosetypeisthatof
thetypeparameter.Italsoreturnsanobjectofthattype
parameter.ShowhowtodeclareMyGen().
Thesolutionis
9.Giventhisgenericinterface
showthedeclarationofaclasscalledMyClassthatimplementsIGenIF.
Thesolutionis
10.GivenagenericclasscalledCounter<T>,showhowtocreate
anobjectofitsrawtype.
ToobtainCounter<T>srawtype,simplyuseitsnamewithoutanytype
specification,asshownhere:
11.Dotypeparametersexistatruntime?
No.Alltypeparametersareerasedduringcompilation,andappropriate
castsaresubstituted.Thisprocessiscallederasure.
12.Convertyoursolutiontoquestion10oftheSelfTestfor
Chapter9sothatitisgeneric.Intheprocess,createastack
interfacecalledIGenStackthatgenericallydefinesthe
operationspush()andpop().

13.Whatis<>?
Thediamondoperator.
14.Howcanthefollowingbesimplified?
Itcanbesimplifiedbyuseofthediamondoperatorasshownhere:

Chapter14:LambdaExpressionsandMethodReferences
1.Whatisthelambdaoperator?

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

27/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

Thelambdaoperatoris>.
2.Whatisafunctionalinterface?
Afunctionalinterfaceisaninterfacethatcontainsoneandonlyone
abstractmethod.
3.Howdofunctionalinterfacesandlambdaexpressionsrelate?
Alambdaexpressionprovidestheimplementationfortheabstract
methoddefinedbythefunctionalinterface.Thefunctionalinterface
definesthetargettype.
4.Whatarethetwogeneraltypesoflambdaexpressions?
Thetwotypesoflambdaexpressionsareexpressionlambdasandblock
lambdas.Anexpressionlambdaspecifiesasingleexpression,whose
valueisreturnedbythelambda.Ablocklambdacontainsablockofcode.
Itsvalueisspecifiedbyareturnstatement.
5.Showalambdaexpressionthatreturnstrueifanumberis
between10and20,inclusive.
6.Createafunctionalinterfacethatcansupportthelambda
expressionyoucreatedinquestion5.CalltheinterfaceMyTest
anditsabstractmethodtesting().
7.Createablocklambdathatcomputesthefactorialofaninteger
value.Demonstrateitsuse.UseNumericFunc,showninthis
chapter,forthefunctionalinterface.
8.CreateagenericfunctionalinterfacecalledMyFunc<T>.
Callitsabstractmethodfunc().Havefunc()returnareference
oftypeT.HaveittakeaparameteroftypeT.(Thus,MyFuncwill
beagenericversionofNumericFuncshowninthechapter.)
Demonstrateitsusebyrewritingyouranswerto7soituses
MyFunc<T>ratherthanNumericFunc.
9.UsingtheprogramshowninTryThis141,createalambda
expressionthatremovesallspacesfromastringandreturnsthe
result.DemonstratethismethodbypassingittochangeStr().
Hereisthelambdaexpressionthatremovesspaces.Itisusedtoinitialize
theremovereferencevariable.
Hereisanexampleofitsuse:
10.Canalambdaexpressionusealocalvariable?Ifso,what
constraintmustbemet?
Yes,butthevariablemustbeeffectivelyfinal.
11.Ifalambdaexpressionthrowsacheckedexception,the
abstractmethodinthefunctionalinterfacemusthaveathrows
clausethatincludesthatexception.TrueorFalse?
True
12.Whatisamethodreference?
Amethodreferenceisawaytorefertoamethodwithoutexecutingit.
13.Whenevaluated,amethodreferencecreatesaninstanceof
the_______________________suppliedbyitstargetcontext.
functionalinterface
14.GivenaclasscalledMyClassthatcontainsastaticmethod
calledmyStaticMethod(),showhowtospecifyamethod
referencetomyStaticMethod().
15.GivenaclasscalledMyClassthatcontainsaninstance
methodcalledmyInstMethod()andassuminganobjectof
MyClasscalledmcObj,showhowtocreateamethodreferenceto
myInstMethod()onmcObj.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

28/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

16.TotheMethodRefDemo2program,addanewmethodto
MyIntNumcalledhasCommonFactor().Haveitreturntrueif
itsintargumentandthevaluestoredintheinvokingMyIntNum
objecthaveatleastonefactorincommon.Forexample,9and12
haveacommonfactor,whichis3,but9and16havenocommon
factor.DemonstratehasCommonFactor()viaamethod
reference.
HereisMyIntNumwiththehasCommonFactor()methodadded:
Hereisanexampleofitsusethroughamethodreference:
17.Howisaconstructorreferencespecified?
Aconstructorreferenceiscreatedbyspecifyingtheclassnamefollowed
by::followedbynew.Forexample,MyClass::new.
18.Javadefinesseveralpredefinedfunctionalinterfacesinwhat
package?
java.util.function
Chapter15:Applets,Events,andMiscellaneousTopics
1.Whatmethodiscalledwhenanappletfirstbeginsrunning?
Whatmethodiscalledwhenanappletisremovedfromthesystem?
Whenanappletbegins,thefirstmethodcalledisinit().Whenanapplet
isremoved,destroy()iscalled.
2.Explainwhyanappletmustusemultithreadingifitneedsto
runcontinually.
Anappletmustusemultithreadingifitneedstoruncontinuallybecause
appletsareeventdrivenprogramswhichmustnotenteramodeof
operation.Forexample,ifstart()neverreturns,thenpaint()will
neverbecalled.
3.EnhanceTryThis151sothatitdisplaysthestringpassedtoit
asaparameter.Addasecondparameterthatspecifiesthetime
delay(inmilliseconds)betweeneachrotation.

4.Extrachallenge:Createanappletthatdisplaysthecurrent
time,updatedoncepersecond.
Toaccomplishthis,youwillneedtodoalittleresearch.Hereisahintto
helpyougetstarted:Onewaytoobtainthecurrenttimeistousea
Calendarobject,whichispartofthejava.utilpackage.(Remember,
OracleprovidesonlinedocumentationforallofJavasstandardclasses.)
YoushouldnowbeatthepointwhereyoucanexaminetheCalendar
classonyourownanduseitsmethodstosolvethisproblem.

5.BrieflyexplainJavasdelegationeventmodel.
Inthedelegationeventmodel,asourcegeneratesaneventandsendsit
tooneormorelisteners.Alistenersimplywaitsuntilitreceivesan
event.Oncereceived,thelistenerprocessestheeventandthenreturns.
6.Mustaneventlistenerregisteritselfwithasource?
Yesalistenermustregisterwithasourcetoreceiveevents.
7.Extrachallenge:AnotherofJavasdisplaymethodsis
drawLine().Itdrawsalineinthecurrentlyselectedcolor
betweentwopoints.ItispartoftheGraphicsclass.Using
drawLine(),writeaprogramthattracksmousemovement.Ifthe
buttonispressed,havetheprogramdrawacontinuouslineuntil
themousebuttonisreleased.

8.Brieflydescribetheassertkeyword.
Theassertkeywordcreatesanassertion,whichisaconditionthat

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

29/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

shouldbetrueduringprogramexecution.Iftheassertionisfalse,an
AssertionErroristhrown.
9.Giveonereasonwhyanativemethodmightbeusefultosome
typesofprograms.
Anativemethodisusefulwheninterfacingtoroutineswrittenin
languagesotherthanJava,orwhenoptimizingcodeforaspecificrun
timeenvironment.
Chapter16:IntroducingSwing
1.Ingeneral,AWTcomponentsareheavyweightandSwing
componentsarelightweight.
2.CanthelookandfeelofaSwingcomponentbechanged?Ifso,
whatfeatureenablesthis?
Yes.Swingspluggablelookandfeelisthefeaturethatenablesthis.
3.Whatisthemostcommonlyusedtoplevelcontainerforan
application?
JFrame
4.Toplevelcontainershaveseveralpanes.Towhatpaneare
componentsadded?
Contentpane
5.Showhowtoconstructalabelthatcontainsthemessage"Select
anentryfromthelist".
6.AllinteractionwithGUIcomponentsmusttakeplaceonwhat
thread?
eventdispatchingthread
7.Whatisthedefaultactioncommandassociatedwitha
JButton?Howcantheactioncommandbechanged?
Thedefaultactioncommandstringisthetextshowninsidethebutton.It
canbechangedbycallingsetActionCommand().
8.Whateventisgeneratedwhenapushbuttonispressed?
ActionEvent
9.Showhowtocreateatextfieldthathas32columns.
10.CanaJTextFieldhaveitsactioncommandset?Ifso,how?
Yes,bycallingsetActionCommand().
11.WhatSwingcomponentcreatesacheckbox?Whateventis
generatedwhenacheckboxisselectedordeselected?
JCheckBoxcreatesacheckbox.AnItemEventisgeneratedwhena
checkboxisselectedordeselected.
12.JListdisplaysalistofitemsfromwhichtheusercanselect.
TrueorFalse?
True
13.Whateventisgeneratedwhentheuserselectsordeselectsan
iteminaJList?
ListSelectionEvent
14.WhatmethodsetstheselectionmodeofaJList?Whatmethod
obtainstheindexofthefirstselecteditem?
setSelectionMode()setstheselectionmode.getSelectedIndex()
obtainstheindexofthefirstselecteditem.
15.TocreateaSwingbasedapplet,whatclassmustyouinherit?
JApplet
16.Usually,SwingbasedappletsuseinvokeAndWait()to
createtheinitialGUI.TrueorFalse?
True
17.AddacheckboxtothefilecomparerdevelopedinTryThis161
thathasthefollowingtext:Showpositionofmismatch.Whenthis
boxischecked,havetheprogramdisplaythelocationofthefirst
pointinthefilesatwhichamismatchoccurs.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

30/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

18.ChangetheListDemoprogramsothatitallowsmultipleitems
inthelisttobeselected.

Chapter17:IntroducingJavaFX
1.WhatisthetoplevelpackagenameoftheJavaFXframework?
javafx
2.TwoconceptscentraltoJavaFXareastageandascene.What
classesencapsulatethem?
StageandScene
3.Ascenegraphiscomposedof________.
nodes
4.Thebaseclassforallnodesis________.
Node
5.WhatclasswillallJavaFXapplicationsextend?
Application
6.WhatarethethreeJavaFXlifecyclemethods?
init(),start(),andstop()
7.Inwhatlifecyclemethodcanyouconstructanapplications
stage?
start()
8.Thelaunch()methodiscalledtostartafreestandingJavaFX
application.TrueorFalse?
True
9.WhatarethenamesoftheJavaFXclassesthatsupportalabel
andabutton?
LabelandButton
10.OnewaytoterminateafreestandingJavaFXapplicationisto
callPlatform.exit().Platformispackagedin
javafx.Application.Whencalled,exit()immediatelyterminates
theprogram.Withthisinmind,changetheJavaFXEventDemo
programshowninthischaptersothatithastwobuttonscalledRun
andExit.IfRunispressed,havetheprogramdisplaythatchoicein
alabel.IfExitispressed,havetheapplicationterminate.Use
lambdaexpressionsfortheeventhandlers.

11.WhatJavaFXcontrolimplementsacheckbox?
CheckBox
12.ListViewisacontrolthatdisplaysadirectorylistoffileson
thelocalfilesystem.TrueorFalse?
False.ListViewdisplaysoflistofitemsfromwhichtheusercanchoose.
13.ConverttheSwingbasedfilecomparisonprograminTryThis
161soitusesJavaFXinstead.Intheprocess,makeuseofanother
ofJavaFXsfeatures:itsabilitytofireanactioneventonabutton
underprogramcontrol.Thisisdonebycallingfire()onthebutton
instance.Forexample,assumingaButtoncalledmyButtton,the
followingwillfireanactioneventonit:myButton.fire().Use
thisfactwhenimplementingtheeventhandlersforthetextfields
thatholdthenamesofthefilestocompare.Iftheuserpresses
ENTERwhenineitherofthesefields,simplyfireanactioneventon
theComparebutton.TheeventhandlingcodefortheCompare
buttonwillthenhandlethefilecomparison.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

31/32

4/18/2015

AppendixA:AnswerstoSelfTestsJavaABeginner'sGuide,6thEdition

14.ModifytheEffectsAndTransformsDemoprogramsothe
Rotatebuttonisalsoblurred.Useablurwidthandheightof5and
aniterationcountof2.
ToaddblurtotheRotatebutton,firstcreatetheBoxBlurinstancelike
this:
Thenaddthefollowingline:
Aftermakingthesechanges,theRotatebuttonwillbeblurredandcan
alsoberotated.

Recommended / Queue / Recent / Topics / Tutorials / Settings /


Blog(http://blog.safaribooksonline.com) /
Feedback(http://community.safaribooksonline.com/) / Sign Out
2015 Safari(http://www.safaribooksonline.com/).
Terms of Service / Privacy Policy

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/appendixa.html

32/32

You might also like