0% found this document useful (0 votes)
113 views11 pages

Java Programming Test 4

Access modifiers dictate which classes, not which instances, may access features. Private makes a member accessible only from within its own class. Public means that all other classes regardless of the package they belong to, can access the member. Transient indicates that a variable is not part of the persistent state of an object.

Uploaded by

api-287551832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views11 pages

Java Programming Test 4

Access modifiers dictate which classes, not which instances, may access features. Private makes a member accessible only from within its own class. Public means that all other classes regardless of the package they belong to, can access the member. Transient indicates that a variable is not part of the persistent state of an object.

Uploaded by

api-287551832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

9/15/2015

00:29:57

Like

Share

Java Programming Test 4


JavaProgramming

1.

Result&Statistics

Youwantsubclassesinanypackagetohaveaccesstomembersofasuperclass.Whichisthe
mostrestrictiveaccessthataccomplishesthisobjective?
A.
C.

public
protected

B.
D.

private
transient

Answer:OptionC

Marks:0/20
Totalnumberofquestions

: 20

Numberofansweredquestions

Numberofunansweredquestions : 20

Feedback

Explanation:
Accessmodifiersdictatewhichclasses,notwhichinstances,mayaccessfeatures.
Methodsandvariablesarecollectivelyknownasmembers.Methodandvariablemembersare
givenaccesscontrolinexactlythesameway.

QualityoftheTest

Select

DifficultyoftheTest

Select

Comments:
...

privatemakesamemberaccessibleonlyfromwithinitsownclass
protectedmakesamemberaccessibleonlytoclassesinthesamepackageorsubclassofthe
class

SubmitFeedback

defaultaccessisverysimilartoprotected(makesureyouspotthedifference)defaultaccess
makesamemberaccessibleonlytoclassesinthesamepackage.
publicmeansthatallotherclassesregardlessofthepackagethattheybelongto,canaccess
themember(assumingtheclassitselfisvisible)
finalmakesitimpossibletoextendaclass,whenappliedtoamethoditpreventsamethod
frombeingoverriddeninasubclass,whenappliedtoavariableitmakesitimpossibleto
reinitialiseavariableonceithasbeeninitialised

TakeanAnotherRandomTest!
GotoOnlineTestPage
GotoHomePage

abstractdeclaresamethodthathasnotbeenimplemented.
transientindicatesthatavariableisnotpartofthepersistentstateofanobject.
volatileindicatesthatathreadmustreconcileitsworkingcopyofthefieldwiththemaster
copyeverytimeitaccessesthevariable.
Afterexaminingtheaboveitshouldbeobviousthattheaccessmodifierthatprovidesthe
mostrestrictionsformethodstobeaccessedfromthesubclassesoftheclassfromanother
packageisCprotected.AisalsoacontenderbutCismorerestrictive,Bwouldbetheanswer
iftheconstraintwasthe"samepackage"insteadof"anypackage"inotherwordsthe
subclassesclauseinthequestioneliminatesdefault.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

2.

interfaceBase
{
booleanm1()
bytem2(shorts)
}
whichtwocodefragmentswillcompile?
1. interfaceBase2implementsBase{}
2. abstractclassClass2extendsBase
{publicbooleanm1(){returntrue}}
3. abstractclassClass2implementsBase{}
4. abstractclassClass2implementsBase
{publicbooleanm1(){return(7>4)}}
5. abstractclassClass2implementsBase
{protectedbooleanm1(){return(5>7)}}
A.

1and2

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

B.

2and3

1/11

9/15/2015

00:29:57
C.

3and4

D.

1and5

Answer:OptionC
Explanation:
(3)iscorrectbecauseanabstractclassdoesn'thavetoimplementanyorallofitsinterface's
methods.(4)iscorrectbecausethemethodiscorrectlyimplemented((7>4)isaboolean).
(1)isincorrectbecauseinterfacesdon'timplementanything.(2)isincorrectbecauseclasses
don'textendinterfaces.(5)isincorrectbecauseinterfacemethodsareimplicitlypublic,sothe
methodsbeingimplementedmustbepublic.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

3.

classA
{
protectedintmethod1(inta,intb)
{
return0
}
}
WhichisvalidinaclassthatextendsclassA?
A.

publicintmethod1(inta,intb){return0}

B.

privateintmethod1(inta,intb){return0}

C.

publicshortmethod1(inta,intb){return0}

D.

staticprotectedintmethod1(inta,intb){return0}

Answer:OptionA
Explanation:
OptionAiscorrectbecausetheclassthatextendsAisjustsimplyoverridingmethod1.
OptionBiswrongbecauseitcan'toverrideastherearelessaccessprivilegesinthesubclass
method1.
OptionCiswrongbecausetooverrideit,thereturntypeneedstobeaninteger.The
differentreturntypemeansthatthemethodisnotoverridingbutthesameargumentlist
meansthatthemethodisnotoverloading.Conflictcompiletimeerror.
OptionDiswrongbecauseyoucan'toverrideamethodandmakeitaclassmethodi.e.using
static.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

4.

Whatwillbetheoutputoftheprogram?
classTest
{
publicstaticvoidmain(String[]args)
{
Testp=newTest()
p.start()
}
voidstart()
{
booleanb1=false
booleanb2=fix(b1)
System.out.println(b1+""+b2)
}
booleanfix(booleanb1)
{
b1=true
returnb1
}

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

2/11

9/15/2015

00:29:57
}
A.

truetrue

B.

falsetrue

C.

truefalse

D.

falsefalse

Answer:OptionB
Explanation:
Thebooleanb1inthefix()methodisadifferentbooleanthantheb1inthestart()method.
Theb1inthestart()methodisnotupdatedbythefix()method.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

5.

Whatwillbetheoutputoftheprogram?
classPassS
{
publicstaticvoidmain(String[]args)
{
PassSp=newPassS()
p.start()
}
voidstart()
{
Strings1="slip"
Strings2=fix(s1)
System.out.println(s1+""+s2)
}
Stringfix(Strings1)
{
s1=s1+"stream"
System.out.print(s1+"")
return"stream"
}
}
A.

slipstream

B.

slipstreamstream

C.

streamslipstream

D.

slipstreamslipstream

Answer:OptionD
Explanation:
Whenthefix()methodisfirstentered,start()'ss1andfix()'ss1referencevariablesbothrefer
tothesameStringobject(withavalueof"slip").Fix()'ss1isreassignedtoanewobjectthat
iscreatedwhentheconcatenationoccurs(thissecondStringobjecthasavalueof
"slipstream").Whentheprogramreturnstostart(),anotherStringobjectiscreated,referred
tobys2andwithavalueof"stream".
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

6.

Whatwillbetheoutputoftheprogram?
classTest
{
staticints
publicstaticvoidmain(String[]args)
{
Testp=newTest()
p.start()
System.out.println(s)
}

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

3/11

9/15/2015

00:29:57
voidstart()
{
intx=7
twice(x)
System.out.print(x+"")
}
voidtwice(intx)
{
x=x*2
s=x
}
}
A.

77

B.

714

C.

140

D.

1414

Answer:OptionB
Explanation:
Theintxinthetwice()methodisnotthesameintxasinthestart()method.Start()'sxis
notaffectedbythetwice()method.Theinstancevariablesisupdatedbytwice()'sx,whichis
14.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

7.

importjava.awt.*
classTickerextendsComponent
{
publicstaticvoidmain(String[]args)
{
Tickert=newTicker()
/*MissingStatements?*/
}
}
whichtwoofthefollowingstatements,insertedindependently,couldlegallybeinsertedinto
missingsectionofthiscode?
1.
2.
3.
4.

booleantest=(Componentinstanceoft)
booleantest=(tinstanceofTicker)
booleantest=t.instanceof(Ticker)
booleantest=(tinstanceofComponent)
A.

1and4

B.

2and3

C.

1and3

D.

2and4

Answer:OptionD
Explanation:
(2)iscorrectbecauseclasstypeTickerispartoftheclasshierarchyoftthereforeitisalegal
useoftheinstanceofoperator.(4)isalsocorrectbecauseComponentispartofthehierarchy
oft,becauseTickerextendsComponent.
(1)isincorrectbecausethesyntaxiswrong.Avariable(ornull)alwaysappearsbeforethe
instanceofoperator,andatypeappearsafterit.(3)isincorrectbecausethestatementisused
asamethod(t.instanceof(Ticker)),whichisillegal.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

8.

publicvoidtest(intx)
{
intodd=1
if(odd)/*Line4*/
{
System.out.println("odd")
}

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

4/11

9/15/2015

00:29:57
else
{
System.out.println("even")
}
}
Whichstatementistrue?
A.

Compilationfails.

B.

"odd"willalwaysbeoutput.

C.

"even"willalwaysbeoutput.

D.

"odd"willbeoutputforoddvaluesofx,and"even"forevenvalues.

Answer:OptionA
Explanation:
Thecompilerwillcomplainbecauseofincompatibletypes(line4),theifexpectsabooleanbut
itgetsaninteger.
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

9.

Whatwillbetheoutputoftheprogram?
inti=1,j=10
do
{
if(i>j)
{
break
}
j
}while(++i<5)
System.out.println("i="+i+"andj="+j)
A.

i=6andj=5

B.

i=5andj=5

C.

i=6andj=4

D.

i=5andj=6

Answer:OptionD
Explanation:
Thisloopisadowhileloop,whichalwaysexecutesthecodeblockwithintheblockatleast
once,duetothetestingconditionbeingattheendoftheloop,ratherthanatthebeginning.
Thisparticularloopisexitedprematurelyifibecomesgreaterthanj.
Theorderis,testiagainstj,ifbigger,itbreaksfromtheloop,decrementsjbyone,andthen
teststheloopcondition,whereapreincrementedbyoneiistestedforbeinglowerthan5.
Thetestisattheendoftheloop,soicanreachthevalueof5beforeitfails.Soitgoes,start:
1,10
2,9
3,8
4,7
5,6loopconditionfails.
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

10. Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticvoidmain(Stringargs[])
{
inti=1,j=0
switch(i)
{

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

5/11

9/15/2015

00:29:57
case2:j+=6
case4:j+=1
default:j+=2
case0:j+=4
}
System.out.println("j="+j)
}
}
A.

j=0

B.

j=2

C.

j=4

D.

j=6

Answer:OptionD
Explanation:
Becausetherearenobreakstatements,theprogramgetstothedefaultcaseandadds2toj,
thengoestocase0andadds4tothenewj.Theresultisj=6.
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

11. importjava.io.*
publicclassMyProgram
{
publicstaticvoidmain(Stringargs[])
{
FileOutputStreamout=null
try
{
out=newFileOutputStream("test.txt")
out.write(122)
}
catch(IOExceptionio)
{
System.out.println("IOError.")
}
finally
{
out.close()
}
}
}
andgiventhatallmethodsofclassFileOutputStream,includingclose(),throwanIOException,
whichoftheseistrue?
A.

Thisprogramwillcompilesuccessfully.

B.

Thisprogramfailstocompileduetoanerroratline4.

C.

Thisprogramfailstocompileduetoanerroratline6.

D.

Thisprogramfailstocompileduetoanerroratline18.

Answer:OptionD
Explanation:
Anymethod(inthiscase,themain()method)thatthrowsacheckedexception(inthiscase,
out.close())mustbecalledwithinatryclause,orthemethodmustdeclarethatitthrowsthe
exception.Eithermain()mustdeclarethatitthrowsanexception,orthecalltoout.close()in
thefinallyblockmustfallinsidea(inthiscasenested)trycatchblock.
Learnmoreproblemson:Exceptions
Discussaboutthisproblem:DiscussinForum

12. Whichstatementistrue?
A.

catch(Xx)cancatchsubclassesofXwhereXisasubclassofException.

B.

TheErrorclassisaRuntimeException.

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

6/11

9/15/2015

00:29:57
C.

AnystatementthatcanthrowanErrormustbeenclosedinatryblock.

D.

AnystatementthatcanthrowanExceptionmustbeenclosedinatryblock.

Answer:OptionA
Explanation:
OptionAiscorrect.Iftheclassspecifiedinthecatchclausedoeshavesubclasses,any
exceptionobjectthatsubclassesthespecifiedclasswillbecaughtaswell.
OptionBiswrong.TheerrorclassisasubclassofThrowableandnotRuntimeException.
OptionCiswrong.Youdonotcatchthisclassoferror.
OptionDiswrong.Anexceptioncanbethrowntothenextmethodhigherupthecallstack.
Learnmoreproblemson:Exceptions
Discussaboutthisproblem:DiscussinForum

13. Whichisvaliddeclarationofafloat?
A.

floatf=1F

B.

floatf=1.0

C.

floatf="1"

D.

floatf=1.0d

Answer:OptionA
Explanation:
OptionAisvaliddeclarationoffloat.
OptionBisincorrectbecauseanyliteralnumberwithadecimalpointudeclarethecomputer
willimplicitlycasttodoubleunlessyouinclude"Forf"
OptionCisincorrectbecauseitisaString.
OptionDisincorrectbecause"d"tellsthecomputeritisadoublesothereforeyouaretrying
toputadoublevalueintoafloatvariablei.etheremightbealossofprecision.
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

14. Whatwillbetheoutputoftheprogram?
importjava.util.*
classH
{
publicstaticvoidmain(String[]args)
{
Objectx=newVector().elements()
System.out.print((xinstanceofEnumeration)+",")
System.out.print((xinstanceofIterator)+",")
System.out.print(xinstanceofListIterator)
}
}
A.

Prints:false,false,false

B.

Prints:false,false,true

C.

Prints:false,true,false

D.

Prints:true,false,false

Answer:OptionD
Explanation:
TheVector.elementsmethodreturnsanEnumerationovertheelementsofthevector.Vector
implementstheListinterfaceandextendsAbstractListsoitisalsopossibletogetanIterator
overaVectorbyinvokingtheiteratororlistIteratormethod.
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

7/11

9/15/2015

00:29:57

15. Whatwillbetheoutputoftheprogram?
TreeSetmap=newTreeSet()
map.add("one")
map.add("two")
map.add("three")
map.add("four")
map.add("one")
Iteratorit=map.iterator()
while(it.hasNext())
{
System.out.print(it.next()+"")
}
A.

onetwothreefour

B.

fourthreetwoone

C.

fouronethreetwo

D.

onetwothreefourone

Answer:OptionC
Explanation:
TreeSetassuresnoduplicateentriesalso,whenitisaccesseditwillreturnelementsin
naturalorder,whichtypicallymeansalphabetical.
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

16. classFoo
{
classBar{}
}
classTest
{
publicstaticvoidmain(String[]args)
{
Foof=newFoo()
/*Line10:Missingstatement?*/
}
}
whichstatement,insertedatline10,createsaninstanceofBar?
A.

Foo.Barb=newFoo.Bar()

B.

Foo.Barb=f.newBar()

C.

Barb=newf.Bar()

D.

Barb=f.newBar()

Answer:OptionB
Explanation:
OptionBiscorrectbecausethesyntaxiscorrectusingbothnames(theenclosingclassand
theinnerclass)inthereferencedeclaration,thenusingareferencetotheenclosingclassto
invokenewontheinnerclass.
OptionA,CandDalluseincorrectsyntax.Aisincorrectbecauseitdoesn'tuseareferenceto
theenclosingclass,andalsobecauseitincludesbothnamesinthenew.
Cisincorrectbecauseitdoesn'tusetheenclosingclassnameinthereferencevariable
declaration,andbecausethenewsyntaxiswrong.
Disincorrectbecauseitdoesn'tusetheenclosingclassnameinthereferencevariable
declaration.
Learnmoreproblemson:InnerClasses
Discussaboutthisproblem:DiscussinForum

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

8/11

9/15/2015

00:29:57

17. Whichthreeguaranteethatathreadwillleavetherunningstate?
1.
2.
3.
4.
5.
6.
7.

yield()
wait()
notify()
notifyAll()
sleep(1000)
aLiveThread.join()
Thread.killThread()
A.

1,2and4

B.

2,5and6

C.

3,4and7

D.

4,5and7

Answer:OptionB
Explanation:
(2)iscorrectbecausewait()alwayscausesthecurrentthreadtogointotheobject'swaitpool.
(5)iscorrectbecausesleep()willalwayspausethecurrentlyrunningthreadforatleastthe
durationspecifiedinthesleepargument(unlessaninterruptedexceptionisthrown).
(6)iscorrectbecause,assumingthatthethreadyou'recallingjoin()onisalive,thethread
callingjoin()willimmediatelyblockuntilthethreadyou'recallingjoin()onisnolongeralive.
(1)iswrong,buttempting.Theyield()methodisnotguaranteedtocauseathreadtoleave
therunningstate,althoughiftherearerunnablethreadsofthesamepriorityasthecurrently
runningthread,thenthecurrentthreadwillprobablyleavetherunningstate.
(3)and(4)areincorrectbecausetheydon'tcausethethreadinvokingthemtoleavethe
runningstate.
(7)iswrongbecausethere'snosuchmethod.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

18. Whichwillcontainthebodyofthethread?
A.

run()

B.

start()

C.

stop()

D.

main()

Answer:OptionA
Explanation:
OptionAisCorrect.Therun()methodtoathreadislikethemain()methodtoanapplication.
Startingthethreadcausestheobject'srunmethodtobecalledinthatseparatelyexecuting
thread.
OptionBiswrong.Thestart()methodcausesthisthreadtobeginexecutiontheJavaVirtual
Machinecallstherunmethodofthisthread.
OptionCiswrong.Thestop()methodisdeprecated.Itforcesthethreadtostopexecuting.
OptionDiswrong.Isthemainentrypointforanapplication.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

19. Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticvoidmain(String[]args)
{
intx=0
assert(x>0)?"assertionfailed":"assertionpassed"
System.out.println("finished")
}
}
A.

finished

B.

Compiliationfails.

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

9/11

9/15/2015

00:29:57
C.

AnAssertionErroristhrownandfinishedisoutput.

D.

AnAssertionErroristhrownwiththemessage"assertionfailed."

Answer:OptionB
Explanation:
CompilationFails.Youcan'tusetheAssertstatementinasimilarwaytotheternaryoperator.
Don'tconfuse.
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

20. Whatwillbetheoutputoftheprogram?
publicclassBoolTest
{
publicstaticvoidmain(String[]args)
{
intresult=0
Booleanb1=newBoolean("TRUE")
Booleanb2=newBoolean("true")
Booleanb3=newBoolean("tRuE")
Booleanb4=newBoolean("false")
if(b1==b2)/*Line10*/
result=1
if(b1.equals(b2))/*Line12*/
result=result+10
if(b2==b4)/*Line14*/
result=result+100
if(b2.equals(b4))/*Line16*/
result=result+1000
if(b2.equals(b3))/*Line18*/
result=result+10000
System.out.println("result="+result)
}
}
A.

B.

C.

10

D.

10010

Answer:OptionD
Explanation:
Line10failsbecauseb1andb2aretwodifferentobjects.Lines12and18succeedbecause
theBooleanStringconstructorsarecaseinsensitive.Lines14and16failbecausetrueisnot
equaltofalse.
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

SubmitTest

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

10/11

9/15/2015

00:29:57
20082015byIndiaBIXTechnologies.AllRightsReserved|Copyright|TermsofUse&PrivacyPolicy

Contactus:[email protected]
Bookmarkto:

http://www.indiabix.com/onlinetest/javaprogrammingtest/64

Followusontwitter!

11/11

You might also like