You are on page 1of 33

CollectionsandGenerics

FormoredetailsonSUNCertifications,visitJavaScjpDumps

Q:01Given:
34.HashMapprops=newHashMap()
35.props.put("key45","somevalue")
36.props.put("key12","someothervalue")
37.props.put("key39","yetanothervalue")
38.Sets=props.keySet()
39.//insertcodehere
What,insertedatline39,willsortthekeysinthepropsHashMap?
A.Arrays.sort(s)
B.s=newTreeSet(s)
C.Collections.sort(s)
D.s=newSortedSet(s)
Answer:B

Q:02ClicktheExhibitbutton.


Whichstatementistrueaboutthesetvariableonline12?

A.Thesetvariablecontainsallsixelementsfromthecollcollection,andtheorderis
guaranteedtobe
preserved.
B.Thesetvariablecontainsonlythreeelementsfromthecollcollection,andtheorderis
guaranteedtobepreserved.
C.Thesetvariablecontainsallsixelementsfromthecollcollection,buttheorderisNOT
guaranteedtobepreserved.
D.Thesetvariablecontainsonlythreeelementsfromthecollcollection,buttheorderisNOT
guaranteedtobepreserved.
Answer:D

Q:03Given:
23.Object[]myObjects={
24.newInteger(12),
25.newString("foo"),
26.newInteger(5),
27.newBoolean(true)
28.}
29.Arrays.sort(myObjects)
30.for(inti=0i<myObjects.lengthi++){
31.System.out.print(myObjects[i].toString())
32.System.out.print("")
33.}
Whatistheresult?
A.Compilationfailsduetoanerrorinline23.
B.Compilationfailsduetoanerrorinline29.
C.AClassCastExceptionoccursinline29.
D.AClassCastExceptionoccursinline31.
E.Thevalueofallfourobjectsprintsinnaturalorder.
Answer:C

Q:04ClicktheTaskbutton.


Solution:
1.Gen<T>
2.T
3.Gen
4.T
5.T

Q:05ClicktheTaskbutton.


Solution:
1.list.add("foo") Compilationfails
2.list=newArrayList<String>() Compilationsucceeds
3.list=newArrayList<Object>()Compilationfails
4.Strings=list.get(0)Compilationsucceeds
5.Objecto=listCompilationsucceeds

Q:06Given:
1.publicclassPerson{
2.privateStringname
3.publicPerson(Stringname){this.name=name}
4.publicbooleanequals(Personp){
5.returnp.name.equals(this.name)
6.}
7.}
Whichstatementistrue?
A.TheequalsmethoddoesNOTproperlyoverridetheObject.equalsmethod.
B.Compilationfailsbecausetheprivateattributep.namecannotbeaccessedinline5.
C.Toworkcorrectlywithhashbaseddatastructures,thisclassmustalsoimplementthe
hashCodemethod.
D.WhenaddingPersonobjectstoajava.util.Setcollection,theequalsmethodinline4will
preventduplicates.
Answer:A

Q:07Given:
1.importjava.util.*
2.publicclassOld{
3.publicstaticObjectget0(Listlist){
4.returnlist.get(0)
5.}
6.}
Whichthreewillcompilesuccessfully?(Choosethree.)
A.Objecto=Old.get0(newLinkedList())
B.Objecto=Old.get0(newLinkedList<?>())
C.Strings=Old.get0(newLinkedList<String>())
D.Objecto=Old.get0(newLinkedList<Object>())
E.Strings=(String)Old.get0(newLinkedList<String>())
Answer:A,D,E

Q:08Given:
1.importjava.util.*
2.publicclassExample{
3.publicstaticvoidmain(String[]args){
4.//insertcodehere
5.set.add(newInteger(2))
6.set.add(newInteger(1))
7.System.out.println(set)
8.}
9.}
Whichcode,insertedatline4,guaranteesthatthisprogramwilloutput[1,2]?
A.Setset=newTreeSet()
B.Setset=newHashSet()
C.Setset=newSortedSet()
D.Listset=newSortedList()
E.Setset=newLinkedHashSet()
Answer:A

Q:09Given:
11.publicstaticCollectionget(){
12.Collectionsorted=newLinkedList()
13.sorted.add("B")sorted.add("C")sorted.add("A")
14.returnsorted
15.}
16.publicstaticvoidmain(String[]args){
17.for(Objectobj:get()){
18.System.out.print(obj+",")
19.}
20.}
Whatistheresult?
A.A,B,C,
B.B,C,A,
C.Compilationfails.
D.Thecoderunswithnooutput.
E.Anexceptionisthrownatruntime.
Answer:B

Q:10given
ClicktheTaskbutton.

Solution:
1. Compilationofthefirststatementsucceeds,butcompilationfailsduetoanerror
inthesecondstatement.
2. Compilationfailsduetoanerrorinthefirststatement
3. Compilationsucceeds
4.Compilationsucceeds

Q:11Given:
11.publicstaticIteratorreverse(Listlist){
12.Collections.reverse(list)
13.returnlist.iterator()
14.}
15.publicstaticvoidmain(String[]args){
16.Listlist=newArrayList()
17.list.add("1")list.add("2")list.add("3")
18.for(Objectobj:reverse(list))
19.System.out.print(obj+",")
20.}
Whatistheresult?
A.3,2,1, B.1,2,3,
C.Compilationfails. D.Thecoderunswithnooutput.
E.Anexceptionisthrownatruntime.
Answer:C

Q:12ClicktheTaskbutton.


============doesnotcompile================
1.m1(listO)
2.m2(listB)
3.m2(listO)
=====compilesandrunswithouterror=========
1.m1(listA)
2.m1(listB)
3.m2(listA)
Q:13Given:
1.importjava.util.*
2.publicclassPQ{
3.publicstaticvoidmain(String[]args){
4.PriorityQueue<String>pq=newPriorityQueue<String>()
5.pq.add("carrot")
6.pq.add("apple")
7.pq.add("banana")
8.System.out.println(pq.poll()+":"+pq.peek())
9.}
10.}
Whatistheresult?
A.apple:apple
B.carrot:apple
C.apple:banana
D.banana:apple
E.carrot:carrot
F.carrot:banana
Answer:C

Q:14Given:
1.importjava.util.*
2.publicclassWrappedString{
3.privateStrings
4.publicWrappedString(Strings){this.s=s}
5.publicstaticvoidmain(String[]args){
6.HashSet<Object>hs=newHashSet<Object>()
7.WrappedStringws1=newWrappedString("aardvark")
8.WrappedStringws2=newWrappedString("aardvark")
9.Strings1=newString("aardvark")
10.Strings2=newString("aardvark")
11.hs.add(ws1)hs.add(ws2)hs.add(s1)hs.add(s2)
12.System.out.println(hs.size())}}
Whatistheresult?
A.0
B.1
C.2
D.3
E.4
F.Compilationfails.
G.Anexceptionisthrownatruntime.
Answer:D

Q:15Given:
11.publicclassKey{
12.privatelongid1
13.privatelongid2
14.
15.//classKeymethods
16.}
AprogrammerisdevelopingaclassKey,thatwillbeusedasakeyinastandard
java.util.HashMap.WhichtwomethodsshouldbeoverriddentoassurethatKeyworks
correctlyasakey?(Choosetwo.)
A.publicinthashCode()
B.publicbooleanequals(Keyk)
C.publicintcompareTo(Objecto)
D.publicbooleanequals(Objecto)
E.publicbooleancompareTo(Keyk)
Answer:A,D

Q:16Givenapregenericsimplementationofamethod:
11.publicstaticintsum(Listlist){
12.intsum=0
13.for(Iteratoriter=list.iterator()iter.hasNext()){
14.inti=((Integer)iter.next()).intValue()
15.sum+=i
16.}
17.returnsum
18.}
Whichthreechangesmustbemadetothemethodsumtousegenerics?(Choose
three.)
A.removeline14
B.replaceline14with"inti=iter.next()"
C.replaceline13with"for(inti:intList){"
D.replaceline13with"for(Iteratoriter:intList){"
E.replacethemethoddeclarationwith"sum(List<int>intList)"
F.replacethemethoddeclarationwith"sum(List<Integer>intList)"
Answer:A,C,F

Q:17Given:
11.//insertcodehere
12.privateNmin,max
13.publicNgetMin(){returnmin}
14.publicNgetMax(){returnmax}
15.publicvoidadd(Nadded){
16.if(min==null||added.doubleValue()<min.doubleValue())17.min=added
18.if(max==null||added.doubleValue()>max.doubleValue())19.max=added
20.}
21.}
Whichtwo,insertedatline11,willallowthecodetocompile?(Choosetwo.)
A.publicclassMinMax<?>{
B.publicclassMinMax<?extendsNumber>{
C.publicclassMinMax<NextendsObject>{
D.publicclassMinMax<NextendsNumber>{
E.publicclassMinMax<?extendsObject>{
F.publicclassMinMax<NextendsInteger>{
Answer:D,F

Q:18Given:
1.importjava.util.*
2.
3.publicclassLetterASort{
4.publicstaticvoidmain(String[]args){
5.ArrayList<String>strings=newArrayList<String>()
6.strings.add("aAaA")
7.strings.add("AaA")
8.strings.add("aAa")
9.strings.add("AAaa")
10.Collections.sort(strings)
11.for(Strings:strings){System.out.print(s+"")}
12.}
13.}
Whatistheresult?
A.Compilationfails. B.aAaAaAaAAaaAaA
C.AAaaAaAaAaaAaA D.AaAAAaaaAaAaAa
E.aAaAaAaAaAAAaa F.Anexceptionisthrownatruntime.
Answer:C

Q:19ClicktheTaskbutton.

Solution:
publicclassNumberNames{
privateHashMap<String,Integer>map=
newHashMap<String,Integer>()
publicvoidput(Stringname.intValue){
map.put(name,Value)
}
publicSet<String>getNames(){
returnmap.keySet()
}
}

Q:20WhichtwostatementsaretrueaboutthehashCodemethod?(Choosetwo.)
A.ThehashCodemethodforagivenclasscanbeusedtotestforobjectequalityandobject
inequalityforthatclass.
B.ThehashCodemethodisusedbythejava.util.SortedSetcollectionclasstoorderthe
elementswithinthatset.
C.ThehashCodemethodforagivenclasscanbeusedtotestforobjectinequality,butNOT
objectequality,forthatclass.
D.TheonlyimportantcharacteristicofthevaluesreturnedbyahashCodemethodisthatthe
distributionofvaluesmustfollowaGaussiandistribution.
E.ThehashCodemethodisusedbythejava.util.HashSetcollectionclasstogroupthe
elementswithinthatsetintohashbucketsforswiftretrieval.
Answer:C,E

Q:22Aprogrammerhasanalgorithmthatrequiresajava.util.Listthatprovides
anefficientimplementationofadd(0,object),butdoesNOTneedtosupportquick
randomaccess.
Whatsupportstheserequirements?
A.java.util.Queue
B.java.util.ArrayList
C.java.util.LinearList
D.java.util.LinkedList
Answer:D

Q:24Given:
10.interfaceA{voidx()}
11.classBimplementsA{publicvoidx(){}publicvoidy(){}}
12.classCextendsB{publicvoidx(){}}
And:
20.java.util.List<A>list=newjava.util.ArrayList<A>()
21.list.add(newB())
22.list.add(newC())
23.for(Aa:list){
24.a.x()
25.a.y()
26.}
Whatistheresult?
A.Thecoderunswithnooutput.
B.Anexceptionisthrownatruntime.
C.Compilationfailsbecauseofanerrorinline20.
D.Compilationfailsbecauseofanerrorinline21.
E.Compilationfailsbecauseofanerrorinline23.
F.Compilationfailsbecauseofanerrorinline25.
Answer:F

Q:26Given:

Solution:
1. Compilationofthefirststatementsucceeds,butcompilationfailsduetoanerror
inthesecondstatement.
2. Compilationfailsduetoanerrorinthefirststatement
3. Compilationsucceeds
4. Compilationsucceeds

Q:26ClicktheTaskbutton.

Solution:
1.list.add("foo") Compilationfails
2.list=newArrayList<String>() Compilationsucceeds
3.list=newArrayList<Object>()Compilationfails
4.Strings=list.get(0)Compilationsucceeds
5.Objecto=listCompilationsucceeds

Q:27Given:
1.publicclassDrinkimplementsComparable{
2.publicStringname
3.publicintcompareTo(Objecto){
4.return0
5.}
6.}
and:
20.Drinkone=newDrink()
21.Drinktwo=newDrink()
22.one.name="Coffee"
23.two.name="Tea"
23.TreeSetset=newTreeSet()
24.set.add(one)
25.set.add(two)
AprogrammeriteratesovertheTreeSetandprintsthenameofeachDrinkobject.
Whatistheresult?
A.Tea
B.Coffee
C.CoffeeTea
D.Compilationfails.
E.Thecoderunswithnooutput.
F.Anexceptionisthrownatruntime.
Answer:B

Q:30Given:
10.abstractpublicclassEmployee{
11.protectedabstractdoublegetSalesAmount()
12.publicdoublegetCommision(){
13.returngetSalesAmount()*0.15
14.}
15.}
16.classSalesextendsEmployee{
17.//insertmethodhere
18.}
Whichtwomethods,insertedindependentlyatline17,correctlycompletetheSales
class?(Choosetwo.)
A.doublegetSalesAmount(){return1230.45}
B.publicdoublegetSalesAmount(){return1230.45}
C.privatedoublegetSalesAmount(){return1230.45}
D.protecteddoublegetSalesAmount(){return1230.45}
Answer:B,D

Q:31Given:
13.publicstaticvoidsearch(List<String>list){
14.list.clear()
15.list.add("b")
16.list.add("a")
17.list.add("c")
18.System.out.println(Collections.binarySearch(list,"a"))
19.}
WhatistheresultofcallingsearchwithavalidListimplementation?
A.0 B.1
C.2 D.a
E.b F.c
G.Theresultisundefined.
Answer:G

Q:32Given:
11.publicstaticvoidappend(Listlist){list.add("0042")}
12.publicstaticvoidmain(String[]args){
13.List<Integer>intList=newArrayList<Integer>()
14.append(intList)
15.System.out.println(intList.get(0))
16.}
Whatistheresult?
A.42
B.0042
C.Anexceptionisthrownatruntime.
D.Compilationfailsbecauseofanerrorinline13.
E.Compilationfailsbecauseofanerrorinline14.
Answer:B

Q:33Given:
11.publicclassPerson{
12.privatename
13.publicPerson(Stringname){
14.this.name=name
15.}
16.publicinthashCode(){
17.return420
18.}
19.}
Whichstatementistrue?
A.ThetimetofindthevaluefromHashMapwithaPersonkeydependsonthesizeofthe
map.
B.DeletingaPersonkeyfromaHashMapwilldeleteallmapentriesforallkeysoftype
Person.
C.InsertingasecondPersonobjectintoaHashSetwillcausethefirstPersonobjecttobe
removedasaduplicate.
D.ThetimetodeterminewhetheraPersonobjectiscontainedinaHashSetisconstantand
doesNOTdependonthesizeofthemap.
Answer:A

Q:34
AprogrammermustcreateagenericclassMinMaxandthetypeparameter
ofMinMaxmustimplementComparable.WhichimplementationofMinMaxwill
compile?
A.classMinMax<EextendsComparable<E>>{
Emin=null
Emax=null
publicMinMax(){}
publicvoidput(Evalue){/*storeminormax*/}
B.classMinMax<EimplementsComparable<E>>{
Emin=null
Emax=null
publicMinMax(){}
publicvoidput(Evalue){/*storeminormax*/}
C.classMinMax<EextendsComparable<E>>{
<E>Emin=null
<E>Emax=null
publicMinMax(){}
public<E>voidput(Evalue){/*storeminormax*/}
D.classMinMax<EimplementsComparable<E>>{
<E>Emin=null
<E>Emax=null
publicMinMax(){}
public<E>voidput(Evalue){/*storeminormax*/}
Answer:A

Q:35Given:
int[]myArray=newint[]{1,2,3,4,5}Whatallowsyoutocreatealistfromthisarray?
A.ListmyList=myArray.asList()
B.ListmyList=Arrays.asList(myArray)
C.ListmyList=newArrayList(myArray)
D.ListmyList=Collections.fromArray(myArray)
Answer:B

Question:36
Given:
1.publicclassScoreimplementsComparable<Score>{
2.privateintwins,losses
3.publicScore(intw,int1){wins=wlosses=1}
4.publicintgetWins(){returnwins}
5.publicintgetLosses(){returnlosses}
6.publicStringtoString(){
7.return<+wins+,+losses+>
8.}
9.//insertcodehere
10.}
Whichmethodwillcompletethisclass?
A.publicintcompareTo(Objecto){/*modecodehere*/}
B.publicintcompareTo(Scoreother){/*morecodehere*/}
C.publicintcompare(Scores1,Scores2){/*morecodehere*/}
D.publicintcompare(Objecto1,Objecto2){/*morecodehere*/}
Answer:B

Question:37
ClicktheExhibitbutton.
1.importjava.util.*
2.classKeyMaster{
3.publicinti
4.publicKeyMaster(inti){this.i=i}
5.publicbooleanequals(Objecto){returni==((KeyMaster)o).i}
6.publicinthashCode(){returni}
7.}
8.publicclassMapIt{
9.publicstaticvoidmain(String[]args){
10.Set<KeyMaster>set=newHashSet<KeyMaster>()
11.KeyMasterk1=newKeyMaster(1)
12.KeyMasterk2=newKeyMaster(2)
13.set.add(k1)set.add(k1)
14.set.add(k2)set.add(k2)
15.System.out.print(set.size()+:)
16.k2.i=1
17.System.out.print(set.size()+:)
18.set.remove(k1)
19.System.out.print(set.size()+:)
20.set.remove(k2)
21.System.out.print(set.size())
22.}
23.}
Whatistheresult?
A.4:4:2:2 B.4:4:3:2
C.2:2:1:0 D.2:2:0:0
E.2:1:0:0 F.2:2:1:1
G.4:3:2:1
Answer:F

Question:38
Given:
1.importjava.util.*
2.publicclassTest{
3.publicstaticvoidmain(String[]args){
4.List<String>strings=newArrayList<String>()
5.//insertcodehere
6.}
7.}
Whichfour,insertedatline5,willallowcompilationtosucceed?
(Choosefour.)
A.Strings=strings.get(0)
B.Iteratori1=strings.iterator()
C.String[]array1=strings.toArray()
D.Iterator<String>i2=strings.iterator()
E.String[]array2=strings.toArray(newString[1])
F.Iterator<String>i3=strings.iterator<String>()
Answer:ABDE

Question:39
Given:
classA{}
classBextendsA{}
classCextendsA{}
classDextendsB{}
Whichthreestatementsaretrue?(Choosethree.)
A.ThetypeList<A>isassignabletoList.
B.ThetypeList<B>isassignabletoList<A>.
C.ThetypeList<Object>isassignabletoList<?>.
D.ThetypeList<D>isassignabletoList<?extendsB>.
E.ThetypeList<?extendsA>isassignabletoList<A>.
F.ThetypeList<Object>isassignabletoanyListreference.
G.ThetypeList<?extendsB>isassignabletoList<?extendsA>.
Answer:CDG

Question:40
Given:
11.publicvoidaddStrings(Listlist){
12.list.add(foo)
13.list.add(bar)
14.}
Whatmustyouchangeinthismethodtocompilewithoutwarnings?
A.addthiscodeafterline11:
list=(List<String>)list
B.changelines12and13to:
list.add<String>(foo)
list.add<String>(bar)
C.changethemethodsignatureonline11to:
publicvoidaddStrings(List<?extendsString>list){
D.changethemethodsignatureonline11to:
publicvoidaddStrings(List<?superString>list){
E.Nochangesarenecessary.Thismethodcompileswithoutwarnings.
Answer:D

Question:41
Given:
1.publicclassTest{
2.public<TextendsComparable>TfindLarger(Tx,Ty){
3.if(x.compareTo(y)>0){
4.returnx
5.}else{
6.returny
7.}
8.}
9.}
and:
22.Testt=newTest()
23.//insertcodehere
Whichtwowillcompilewithouterrorswheninsertedatline23?
(Choosetwo.)
A.Objectx=t.findLarger(123,456)
B.intx=t.findLarger(123,newDouble(456))
C.intx=t.findLarger(123,newInteger(456))
D.intx=(int)t.findLarger(newDouble(123),newDouble(456))
Answer:AC

Question:42
Given:
11.Listlist=//morecodehere
12.Collections.sort(list,newMyComparator())
Whichcodewillsortthislistintheoppositeorderofthesortinline
12?
A.Collections.reverseSort(list,newMyComparator())
B.Collections.sort(list,newMyComparator())
list.reverse()
C.Collections.sort(list,newInverseComparator(
newMyComparator()))
D.Collections.sort(list,Collections.reverseOrder(
newMyComparator()))
Answer:D

Question:43
Given:
ArrayLista=newArrayList()
containingthevalues{1,2,3,4,5,6,7,8}
Whichcodewillreturn2?
A.Collections.sort(a,a.reverse())
intresult=Collections.binarySearch(a,6)
B.Comparatorc=Collections.reverseOrder()
Collections.sort(a,c)
intresult=Collections.binarySearch(a,6)
C.Comparatorc=Collections.reverseOrder()
Collections.sort(a,c)
intresult=Collections.binarySearch(a,6,c)
D.Comparatorc=Collections.reverseOrder(a)
Collections.sort(a,c)
intresult=Collections.binarySearch(a,6,c)
E.Comparatorc=newInverseComparator(newComparator())
Collections.sort(a)
intresult=Collections.binarySearch(a,6,c)
Answer:C

Question:44
Given:
11.publicclassCounter{
12.publicstaticvoidmain(String[]args){
13.intnumArgs=/*insertcodehere*/
14.}
15.}
andthecommandline:
javaCounteronefred42
Whichcode,insertedatline13,capturesthenumberofarguments
passedintotheprogram?
A.args.count
B.args.length
C.args.count()
D.args.length()
E.args.getLength()
Answer:B

45.Given:
importjava.util.*
classTest{
publicstaticvoidmain(String[]args){
//insertcodehere
x.add("one")
x.add("two")
x.add("TWO")
System.out.println(x.poll())
}
}
Which,insertedat//insertcodehere,willcompile?(Chooseallthatapply.)
A.List<String>x=newLinkedList<String>()
B.TreeSet<String>x=newTreeSet<String>()
C.HashSet<String>x=newHashSet<String>()
D.Queue<String>x=newPriorityQueue<String>()
E.ArrayList<String>x=newArrayList<String>()
F.LinkedList<String>x=newLinkedList<String>()
Answer:
>DandFarecorrect.Thepoll()methodisassociatedwithQueues.TheLinkedListclass
implementstheQueueinterface.
>AisincorrectbecausetheListinterfacedoesnotimplementQueue,

Question:46
ClicktheExhibitbutton.
Given:
1.publicclassTwoThreads{
2
3.privatestaticObjectresource=newObject()
4.
5.privatestaticvoiddelay(longn){
6.try{Thread.sleep(n)}
7.catch(Exceptione){System.out.print(Error)}
8.}
9
10.publicstaticvoidmain(String[]args){
11.System.out.print(StartMain)
12.newThread1().start()
13.delay(1000)
14.Threadt2=newThread2()
15.t2.start()
16.delay(1000)
17.t2.interrupt
18.delay(1000)
19.System.out.print(EndMain)
20.}
21.
22.staticclassThread1extendsThread{
23.publicvoidrun(){
24.synchronized(resource){
25.System.out.print(Startl)
26.delay(6000)
27.System.out.print(End1)
28.}
29.}
30.}
31.
32.staticclassThread2extendsThread{
33.publicvoidrun(){
34.synchronized(resource){
35.System.out.print(Start2)
36.delay(2000)
37.System.out.print(End2)
38.}
39.}
40.}
41.}
Assumethatsleep(n)executesinexactlymmilliseconds,andallother
codeexecutesinaninsignificantamountoftime.Whatistheoutputif
themain()methodisrun?
A.Compilationfails.
B.Deadlockoccurs.
C.StartMainStart1ErrorEndMainEnd1
D.StartMainStart1EndMainEnd1Start2End2
E.StartMainStart1ErrorStart2EndMainEnd2End1
F.StartMainStart1Start2ErrorEnd2EndMainEnd1
G.StartMainStart1EndMainEnd1Start2ErrorEnd2
Answer:G

Question:47
ClicktheExhibitbutton.
10.publicclassTransfers{
11.publicstaticvoidmain(String[]args)throwsException{
12.Recordr1=newRecord()
13.Recordr2=newRecord()
14.doTransfer(r1,r2,5)
15.doTransfer(r2,r1,2)
16.doTransfer(r1,r2,1)
17.//printtheresult
18.System.out.println(rl=+r1.get()+,r2=+r2.get())
19.}
20.privatestaticvoiddoTransfer(
21.finalRecorda,finalRecordb,finalintamount){
22.Threadt=newThread(){
23.publicvoidrun(){
24.newClerk().transfer(a,b,amount)
25.}
26.}
27.t.start()
28.}
29.}
30.classClerk{
31.publicsynchronizedvoidtransfer(Recorda,Recordb,intamount){
32.synchronized(a){
33.synchronized(b){
34.a.add(amount)
35.b.add(amount)
36.}
37.}
38.}
39.}
40.classRecord{
41.intnum=10
42.publicintget(){returnnum}
43.publicvoidadd(intn){num=num+n}
44.}
IfTransfers.main()isrun,whichthreearetrue?(Choosethree.)
A.Theoutputmayber1=6,r2=14.
B.Theoutputmayber1=5,r2=15.
C.Theoutputmayber1=8,r2=12.
D.Thecodemayrun(andcomplete)withnooutput.
E.Thecodemaydeadlock(withoutcompleting)withnooutput.
F.MIllegalStateExceptionorInterruptedExceptionmaybethrownat
runtime.
Answer:ABE

48.Given:
publicclassMessagerimplementsRunnable{
publicstaticvoidmain(String[]args){
newThread(newMessager("Wallace")).start()
newThread(newMessager("Gromit")).start()
}
privateStringname
publicMessager(Stringname){this.name=name}
publicvoidrun(){
message(1)message(2)
}
privatesynchronizedvoidmessage(intn){
System.out.print(name+""+n+"")
}
}
Whichofthefollowingisapossibleresult?(Chooseallthatapply.)
A.Wallace1Wallace2Gromit1
B.Wallace1Gromit2Wallace2Gromit1
C.Wallace1Gromit1Gromit2Wallace2
D.Gromit1Gromit2
E.Gromit2Wallace1Gromit1Wallace2
F.Thecodedoesnotcompile.
G.Anerroroccursatruntime.
Answer:
>Ciscorrect.Boththreadswillprinttwomessageseach.Wallace1mustbebefore
Wallace2,andGromit1mustbebeforeGromit2.Otherthanthat,theWallaceandGromit
messagescanbeintermingledinanyorder.
>A,B,D,E,F,andGareincorrectbasedontheabove.

51.Given:
12.publicclassAccountManager{
13.privateMapaccountTotals=newHashMap()
14.privateintretirementFund
15.
16.publicintgetBalance(StringaccountName){
17.Integertotal=(Integer)accountTotals.get(accountName)
18.if(total==null)
19.total=Integer.valueOf(0)
20.returntotal.intValue()
21.}
23.publicvoidsetBalance(StringaccountName,intamount){
24.accountTotals.put(accountName,Integer.valueOf(amount))
25.}}
Thisclassistobeupdatedtomakeuseofappropriategenerictypes,withnochanges
in
behavior(forbetterorworse).Whichofthesestepscouldbeperformed?(Choose
three.)
A.Replaceline13with
privateMap<String,int>accountTotals=newHashMap<String,int>()
B.Replaceline13with
privateMap<String,Integer>accountTotals=newHashMap<String,Integer>()
C.Replaceline13with
privateMap<String<Integer>>accountTotals=newHashMap<String<Integer>>()
D.Replacelines1720with
inttotal=accountTotals.get(accountName)
if(total==null)total=0
returntotal
E.Replacelines1720with
Integertotal=accountTotals.get(accountName)
if(total==null)total=0
returntotal
F.Replacelines1720with
returnaccountTotals.get(accountName)
G.Replaceline24with
accountTotals.put(accountName,amount)
H.Replaceline24with
accountTotals.put(accountName,amount.intValue())
Answer:
>B,E,andGarecorrect.
>Aiswrongbecauseyoucan'tuseaprimitivetypeasatypeparameter.Ciswrongbecause
aMaptakestwotypeparametersseparatedbyacomma.Diswrongbecauseanintcan't
autoboxtoanull,andFiswrongbecauseanullcan'tunboxto0.Hiswrongbecauseyou
can'tautoboxaprimitivejustbytryingtoinvokeamethodwithit.

52.GivenaproperlypreparedStringarraycontainingfiveelements,whichrangeof
resultscouldaproperinvocationofArrays.binarySearch()produce?
A.0through4
B.0through5
C.1through4
D.1through5
E.5through4
F.5through5
G.6through4
H.6through5

Answer:
>Giscorrect.Ifamatchisfound,binarySearch()willreturntheindexoftheelementthat
wasmatched.Ifnomatchisfound,binarySearch()willreturnanegativenumberthat,
ifinvertedandthendecremented,givesyoutheinsertionpoint(arrayindex)atwhichthe
valuesearchedonshouldbeinsertedintothearraytomaintainapropersort.
>A,B,C,D,E,F,andHareincorrectbasedontheabove.

53.Given:
interfaceHungry<E>{voidmunch(Ex)}
interfaceCarnivore<EextendsAnimal>extendsHungry<E>{}
interfaceHerbivore<EextendsPlant>extendsHungry<E>{}
abstractclassPlant{}
classGrassextendsPlant{}
abstractclassAnimal{}
classSheepextendsAnimalimplementsHerbivore<Sheep>{
publicvoidmunch(Sheepx){}
}
classWolfextendsAnimalimplementsCarnivore<Sheep>{
publicvoidmunch(Sheepx){}
}
Whichofthefollowingchanges(takenseparately)wouldallowthiscodetocompile?
(Chooseallthatapply.)
A.ChangetheCarnivoreinterfaceto
interfaceCarnivore<EextendsPlant>extendsHungry<E>{}
B.ChangetheHerbivoreinterfaceto
interfaceHerbivore<EextendsAnimal>extendsHungry<E>{}
C.ChangetheSheepclassto
classSheepextendsAnimalimplementsHerbivore<Plant>{
publicvoidmunch(Grassx){}
}
D.ChangetheSheepclassto
classSheepextendsPlantimplementsCarnivore<Wolf>{
publicvoidmunch(Wolfx){}
}
E.ChangetheWolfclassto
classWolfextendsAnimalimplementsHerbivore<Grass>{
publicvoidmunch(Grassx){}
}
F.Nochangesarenecessary.
Answer:
>Biscorrect.TheproblemwiththeoriginalcodeisthatSheeptriestoimplement
Herbivore<Sheep>andHerbivoredeclaresthatitstypeparameterEcanbeanytypethat
extendsPlant.SinceaSheepisnotaPlant,Herbivore<Sheep>makesnosensethetype
SheepisoutsidetheallowedrangeofHerbivore'sparameterE.Onlysolutionsthateitheralter
thedefinitionofaSheeporalterthedefinitionofHerbivorewillbeabletofixthis.SoA,E,and
Fareeliminated.Bworks,changingthedefinitionofanHerbivoretoallowittoeatSheep
solvestheproblem.Cdoesn'tworkbecauseanHerbivore<Plant>musthaveamunch(Plant)
method,notmunch(Grass).AndDdoesn'twork,becauseinDwemadeSheepextendPlant,
nowtheWolfclassbreaksbecauseitsmunch(Sheep)methodnolongerfulfillsthecontractof
Carnivore.

54.Whichcollectionclass(es)allowsyoutogroworshrinkitssizeandprovides
indexedaccesstoitselements,butwhosemethodsarenotsynchronized?(Chooseall
thatapply.)
A.java.util.HashSet
B.java.util.LinkedHashSet
C.java.util.List
D.java.util.ArrayList
E.java.util.Vector
F.java.util.PriorityQueue
Answer:
>Discorrect.Allofthecollectionclassesallowyoutogroworshrinkthesizeofyour
collection.ArrayListprovidesanindextoitselements.Thenewercollectionclassestendnot
tohavesynchronizedmethods.VectorisanolderimplementationofArrayListfunctionality
andhassynchronizedmethodsitisslowerthanArrayList.
>A,B,C,E,andFareincorrectbasedonthelogicdescribedaboveNotes:C,Listisan
interface,andF,PriorityQueuedoesnotofferaccessbyindex.

55.Given:
importjava.util.*
publicclassGroupextendsHashSet<Person>{
publicstaticvoidmain(String[]args){
Groupg=newGroup()
g.add(newPerson("Hans"))
g.add(newPerson("Lotte"))
g.add(newPerson("Jane"))
g.add(newPerson("Hans"))
g.add(newPerson("Jane"))
System.out.println("Total:"+g.size())
}
publicbooleanadd(Objecto){
System.out.println("Adding:"+o)
returnsuper.add(o)
}
}
classPerson{
privatefinalStringname
publicPerson(Stringname){this.name=name}
publicStringtoString(){returnname}
}
Whichofthefollowingoccuratleastoncewhenthecodeiscompiledandrun?
(Chooseallthatapply.)
A.AddingHans B.AddingLotte
C.AddingJane D.Total:3
E.Total:5 F.Thecodedoesnotcompile.
G.Anexceptionisthrownatruntime.
Answer:
>Fiscorrect.TheproblemhereisinGroup'sadd()methoditshouldhavebeen
add(Person),sincetheclassextendsHashSet<Person>.Sothisdoesn'tcompile.
PopQuiz:Whatwouldhappenifyoufixedthiscode,changingadd(Object)to
add(Person)?Tryrunningthecodetoseeiftheresultsmatchwhatyouthought.
>A,B,C,D,E,andGareincorrectbasedontheabove.

56.Given:
importjava.util.*
classAlgaeDiesel{
publicstaticvoidmain(String[]args){
String[]sa={"foo","bar","baz"}
//insertmethodinvocationshere
}
}
Whatjava.util.Arraysand/orjava.util.Collectionsmethodscouldyouusetoconvertsa
toaListandthensearchtheListtofindtheindexoftheelementwhosevalueis"foo"?
(Choosefromonetothreemethods.)
A.sort()B.asList()
C.toList() D.search()
E.sortList() F.contains()
G.binarySearch()
Answer:
>A,B,andGarerequired.TheasList()methodconvertsanarraytoaList.Youcanfindthe
indexofanelementinaListwiththebinarySearch()method,butbeforeyoudothatyoumust
sortthelistusingsort().
>Fisincorrectbecausecontains()returnsaboolean,notanindex.C,D,andEareincorrect,
becausethesemethodsarenotdefinedintheListinterface.

57.GiventhatStringimplementsjava.lang.CharSequence,and:
importjava.util.*
publicclassLongWordFinder{
publicstaticvoidmain(String[]args){
String[]array={"123","12345678","1","12","1234567890"}
List<String>list=Arrays.asList(array)
Collection<String>resultList=getLongWords(list)
}
//INSERTDECLARATIONHERE
{
Collection<E>longWords=newArrayList<E>()
for(Eword:coll)
if(word.length()>6)longWords.add(word)
returnlongWords
}}
Whichdeclarationscouldbeinsertedat//INSERTDECLARATIONHEREsothatthe
programwillcompileandrun?(Chooseallthatapply.)
A.publicstatic<EextendsCharSequence>Collection<?extendsCharSequence>
getLongWords(Collection<E>coll)
B.publicstatic<EextendsCharSequence>List<E>
getLongWords(Collection<E>coll)
C.publicstaticCollection<EextendsCharSequence>getLongWords(Collection<E>coll)
D.publicstaticList<CharSequence>
getLongWords(Collection<CharSequence>coll)
E.publicstaticList<?extendsCharSequence>
getLongWords(Collection<?extendsCharSequence>coll)
F.staticpublic<EextendsCharSequence>Collection<E>
getLongWords(Collection<E>coll)
G.staticpublic<EsuperCharSequence>Collection<E>
getLongWords(Collection<E>coll)
Answer:
>Fiscorrect.
>Aisclose,butit'swrongbecausethereturnvalueistoovague.Thelastlineofthe
methodexpectsthereturnvaluetobeCollection<String>,not
Collection<?extendsCharSequence>.BiswrongbecauselongWordshasbeendeclaredas
aCollection<E>,andthatcan'tbeimplicitlyconvertedtoaList<E>tomatchthedeclared
returnvalue.(EventhoughweknowthatlongWordsisreallyanArrayList<E>,thecompiler
onlyknowwhatit'sbeendeclaredas.)C,D,andEarewrongbecausetheydonotdeclarea
typevariableE(there'sno<>beforethereturnvalue)sothegetLongWords()methodbody
willnotcompile.GiswrongbecauseEsuperCharSequencemakesnosensesupercould
beusedinconjunctionwithawildcardbutnotatypevariablelikeE.

58.Given:
12.TreeSetmap=newTreeSet()
13.map.add("one")
14.map.add("two")
15.map.add("three")
16.map.add("four")
17.map.add("one")
18.Iteratorit=map.iterator()
19.while(it.hasNext()){
20.System.out.print(it.next()+"")
21.}
Whatistheresult?
A.Compilationfails.
B.onetwothreefour
C.fourthreetwoone
D.fouronethreetwo
E.onetwothreefourone
F.onefourthreetwoone
G.Anexceptionisthrownatruntime.
H.Theprintorderisnotguaranteed.
Answer:
>Discorrect.TreeSetassuresnoduplicateentriesalso,whenitisaccessedit
willreturnelementsinnaturalorder,whichforStringsmeansalphabetical.
>A,B,C,E,F,G,andHareincorrectbasedonthelogicdescribedabove.Note,even
thoughasofJava5youdon'thavetouseanIterator,youstillcan.

59.Givenamethoddeclaredas:
publicstatic<EextendsNumber>List<?superE>process(List<E>nums)
Aprogrammerwantstousethismethodlikethis:
//INSERTDECLARATIONSHERE
output=process(input)
Whichpairsofdeclarationscouldbeplacedat//INSERTDECLARATIONSHEREto
allowthecodetocompile?(Chooseallthatapply.)

A.ArrayList<Integer>input=null
ArrayList<Integer>output=null
B.ArrayList<Integer>input=null
List<Integer>output=null
C.ArrayList<Integer>input=null
List<Number>output=null
D.List<Number>input=null
ArrayList<Integer>output=null
E.List<Number>input=null
List<Number>output=null
F.List<Integer>input=null
List<Integer>output=null
G.Noneoftheabove.
Answer:
>B,E,andFarecorrect.
>ThereturntypeofprocessisdefinitelydeclaredasaList,notanArrayList,soAandDare
wrong.CiswrongbecausethereturntypeevaluatestoList<Integer>,andthatcan'tbe
assignedtoavariableoftypeList<Number>.Ofcourseallthesewouldprobablycausea
NullPointerExceptionsincethevariablesarestillnullbutthequestiononlyaskedustoget
thecodetocompile.

You might also like