Sie sind auf Seite 1von 11

9/15/2015

00:29:57

Like

Share

Java Programming Test 5


JavaProgramming

1.

Result&Statistics

Givenamethodinaprotectedclass,whataccessmodifierdoyouusetorestrictaccesstothat
methodtoonlytheothermembersofthesameclass?
A.

final

C.

private

E.

volatile

B.
D.

static
protected

Marks:0/20
Totalnumberofquestions

: 20

Numberofansweredquestions

Numberofunansweredquestions : 20

Feedback

Answer:OptionC

QualityoftheTest

Select

Explanation:

DifficultyoftheTest

Select

Theprivateaccessmodifierlimitsaccesstomembersofthesameclass.

Comments:

OptionA,B,D,andEarewrongbecauseprotectedarethewrongaccessmodifiers,andfinal,
static,andvolatilearemodifiersbutnotaccessmodifiers.

...

Learnmoreproblemson:DeclarationsandAccessControl
SubmitFeedback

Discussaboutthisproblem:DiscussinForum

2.

TakeanAnotherRandomTest!

interfaceDoMath
{
doublegetArea(intrad)
}
interfaceMathPlus
{
doublegetVol(intb,inth)
}
/*MissingStatements?*/

GotoOnlineTestPage
GotoHomePage

whichtwocodefragmentsinsertedatendoftheprogram,willallowtocompile?
1.
2.
3.
4.
5.

classAllMathextendsDoMath{doublegetArea(intr)}
interfaceAllMathimplementsMathPlus{doublegetVol(intx,inty)}
interfaceAllMathextendsDoMath{floatgetAvg(inth,intl)}
classAllMathimplementsMathPlus{doublegetArea(intrad)}
abstractclassAllMathimplementsDoMath,MathPlus{publicdoublegetArea(intrad){
returnrad*rad*3.14}}
A.

1only

B.

2only

C.

3and5

D.

1and4

Answer:OptionC
Explanation:
(3)are(5)arecorrectbecauseinterfacesandabstractclassesdonotneedtofullyimplement
theinterfacestheyextendorimplement(respectively).
(1)isincorrectbecauseaclasscannotextendaninterface.(2)isincorrectbecausean
interfacecannotimplementanything.(4)isincorrectbecausethemethodbeingimplemented
isfromthewronginterface.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

3.

Whichthreestatementsaretrue?
1. Thedefaultconstructorinitialisesmethodvariables.
2. Thedefaultconstructorhasthesameaccessasitsclass.

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

1/11

9/15/2015

00:29:57
3. Thedefaultconstructorinvokesthenoargconstructorofthesuperclass.
4. Ifaclasslacksanoargconstructor,thecompileralwayscreatesadefaultconstructor.
5. Thecompilercreatesadefaultconstructoronlywhentherearenootherconstructorsfor
theclass.
A.

1,2and4

B.

2,3and5

C.

3,4and5

D.

1,2and3

Answer:OptionB
Explanation:
(2)soundscorrectasintheexamplebelow
classCoffeeCup{
privateintinnerCoffee
publicCoffeeCup(){
}

publicvoidadd(intamount){
innerCoffee+=amount
}
//...
}
Thecompilergivesdefaultconstructorsthesameaccesslevelastheirclass.Intheexample
above,classCoffeeCupispublic,sothedefaultconstructorispublic.IfCoffeeCuphadbeen
givenpackageaccess,thedefaultconstructorwouldbegivenpackageaccessaswell.
(3)iscorrect.TheJavacompilergeneratesatleastoneinstanceinitialisationmethodforevery
classitcompiles.IntheJavaclassfile,theinstanceinitialisationmethodisnamed"<init>."
Foreachconstructorinthesourcecodeofaclass,theJavacompilergeneratesone<init>()
method.Iftheclassdeclaresnoconstructorsexplicitly,thecompilergeneratesadefaultno
argconstructorthatjustinvokesthesuperclass'snoargconstructor.Aswithanyother
constructor,thecompilercreatesan<init>()methodintheclassfilethatcorrespondstothis
defaultconstructor.
(5)iscorrect.Thecompilercreatesadefaultconstructorifyoudonotdeclareanyconstructors
inyourclass.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

4.

Whatwillbetheoutputoftheprogram?
classTest
{
publicstaticvoidmain(String[]args)
{
intx=20
Stringsup=(x<15)?"small":(x<22)?"tiny":"huge"
System.out.println(sup)
}
}
A.

small

B.

tiny

C.

huge

D.

Compilationfails

Answer:OptionB
Explanation:
Thisisanexampleofanestedternaryoperator.Thesecondevaluation(x<22)istrue,sothe
"tiny"valueisassignedtosup.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

5.

Whichofthefollowingarelegallinesofcode?
1.
2.
3.
4.

intw=(int)888.8
bytex=(byte)1000L
longy=(byte)100
bytez=(byte)100L

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

2/11

9/15/2015

00:29:57
A.

1and2

B.

2and3

C.

3and4

D.

Allstatementsarecorrect.

Answer:OptionD
Explanation:
Statements(1),(2),(3),and(4)arecorrect.(1)iscorrectbecausewhenafloatingpoint
number(adoubleinthiscase)iscasttoanint,itsimplylosesthedigitsafterthedecimal.
(2)and(4)arecorrectbecausealongcanbecastintoabyte.Ifthelongisover127,itloses
itsmostsignificant(leftmost)bits.
(3)actuallyworks,eventhoughacastisnotnecessary,becausealongcanstoreabyte.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

6.

Whichtwostatementsareequivalent?
1.
2.
3.
4.

16*4
16>>2
16/2^2
16>>>2
A.

1and2

B.

2and4

C.

3and4

D.

1and3

Answer:OptionB
Explanation:
(2)iscorrect.16>>2=4
(4)iscorrect.16>>>2=4
(1)iswrong.16*4=64
(3)iswrong.16/2^2=10
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

7.

Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticvoidmain(String[]args)
{
intI=1
dowhile(I<1)
System.out.print("Iis"+I)
while(I>1)
}
}
A.

Iis1

B.

Iis1Iis1

C.

Nooutputisproduced.

D.

Compilationerror

Answer:OptionC
Explanation:
Therearetwodifferentloopingconstructsinthisproblem.Thefirstisadowhileloopandthe
secondisawhileloop,nestedinsidethedowhile.Thebodyofthedowhileisonlyasingle

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

3/11

9/15/2015

00:29:57
statementbracketsarenotneeded.Youareassuredthatthewhileexpressionwillbe
evaluatedatleastonce,followedbyanevaluationofthedowhileexpression.Both
expressionsarefalseandnooutputisproduced.
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

8.

Whatwillbetheoutputoftheprogram?
publicclassRTExcept
{
publicstaticvoidthrowit()
{
System.out.print("throwit")
thrownewRuntimeException()
}
publicstaticvoidmain(String[]args)
{
try
{
System.out.print("hello")
throwit()
}
catch(Exceptionre)
{
System.out.print("caught")
}
finally
{
System.out.print("finally")
}
System.out.println("after")
}
}
A.

hellothrowitcaught

B.

Compilationfails

C.

hellothrowitRuntimeExceptioncaughtafter

D.

hellothrowitcaughtfinallyafter

Answer:OptionD
Explanation:
Themain()methodproperlycatchesandhandlestheRuntimeExceptioninthecatchblock,
finallyruns(asitalwaysdoes),andthenthecodereturnstonormal.
A,BandCareincorrectbasedontheprogramlogicdescribedabove.Rememberthatproperly
handledexceptionsdonotcausetheprogramtostopexecuting.
Learnmoreproblemson:Exceptions
Discussaboutthisproblem:DiscussinForum

9.

Whatwillbetheoutputoftheprogram?
publicclassX
{
publicstaticvoidmain(String[]args)
{
try
{
badMethod()
System.out.print("A")
}
catch(Exceptionex)
{
System.out.print("B")
}
finally
{

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

4/11

9/15/2015

00:29:57
System.out.print("C")
}
System.out.print("D")
}
publicstaticvoidbadMethod(){}
}
A.

AC

B.

BC

C.

ACD

D.

ABCD

Answer:OptionC
Explanation:
Thereisnoexceptionthrown,soallthecodewiththeexceptionofthecatchstatementblock
isrun.
Learnmoreproblemson:Exceptions
Discussaboutthisproblem:DiscussinForum

10. WhichofthefollowingareJavareservedwords?
1.
2.
3.
4.

run
import
default
implement
A.

1and2

B.

2and3

C.

3and4

D.

2and4

Answer:OptionB
Explanation:
(2)ThisisaJavakeyword
(3)ThisisaJavakeyword
(1)IsincorrectbecausealthoughitisamethodofThread/Runnableitisnotakeyword
(4)ThisisnotaJavakeywordthekeywordisimplements
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

11. Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticvoidmain(String[]args)
{
Stringfoo=args[1]
Stringbar=args[2]
Stringbaz=args[3]
System.out.println("baz="+baz)/*Line8*/
}
}
Andthecommandlineinvocation:
>javaTestredgreenblue
A.

baz=

B.

baz=null

C.

baz=blue

D.

RuntimeException

Answer:OptionD
Explanation:
Whenrunningtheprogramyouentered3arguments"red","green"and"blue".When
dealingwitharraysinjavayoumustrememberALLARRAYSINJAVAAREZEROBASED
thereforeargs[0]becomes"red",args[1]becomes"green"andargs[2]becomes"blue".
Whentheprogramentcountersline8aboveatruntimeitlooksforargs[3]whichhasnever

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

5/11

9/15/2015

00:29:57
beencreatedthereforeyougetan
ArrayIndexOutOfBoundsExceptionatruntime.
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

12. Whatwillbetheoutputoftheprogram?
classHappyextendsThread
{
finalStringBuffersb1=newStringBuffer()
finalStringBuffersb2=newStringBuffer()
publicstaticvoidmain(Stringargs[])
{
finalHappyh=newHappy()
newThread()
{
publicvoidrun()
{
synchronized(this)
{
h.sb1.append("A")
h.sb2.append("B")
System.out.println(h.sb1)
System.out.println(h.sb2)
}
}
}.start()
newThread()
{
publicvoidrun()
{
synchronized(this)
{
h.sb1.append("D")
h.sb2.append("C")
System.out.println(h.sb2)
System.out.println(h.sb1)
}
}
}.start()
}
}
A.

ABBCAD

B.

ABCBCAD

C.

CDADACB

D.

Outputdeterminedbytheunderlyingplatform.

Answer:OptionD
Explanation:
Canyouguaranteetheorderinwhichthreadsaregoingtorun?Noyoucan't.Sohowdoyou
knowwhattheoutputwillbe?Theoutputcannotbedetermined.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

13. Whatwillbetheoutputoftheprogram?
classMyThreadextendsThread
{
publicstaticvoidmain(String[]args)
{
MyThreadt=newMyThread()

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

6/11

9/15/2015

00:29:57
Threadx=newThread(t)
x.start()/*Line7*/
}
publicvoidrun()
{
for(inti=0i<3++i)
{
System.out.print(i+"..")
}
}
}
A.

Compilationfails.

B.

1..2..3..

C.

0..1..2..3..

D.

0..1..2..

Answer:OptionD
Explanation:
ThethreadMyThreadwillstartandloopthreetimes(from0to2).
OptionAisincorrectbecausetheThreadclassimplementstheRunnableinterfacetherefore,
inline7,ThreadcantakeanobjectoftypeThreadasanargumentintheconstructor.
OptionBandCareincorrectbecausethevariableiintheforloopstartswithavalueof0and
endswithavalueof2.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

14. Whichstatementistrue?
A.

Astaticmethodcannotbesynchronized.

B.

Ifaclasshassynchronizedcode,multiplethreadscanstillaccessthe
nonsynchronizedcode.

C.

Variablescanbeprotectedfromconcurrentaccessproblemsbymarkingthemwith
thesynchronizedkeyword.

D.

Whenathreadsleeps,itreleasesitslocks.

Answer:OptionB
Explanation:
Biscorrectbecausemultiplethreadsareallowedtoenternonsynchronizedcode,evenwithin
aclassthathassomesynchronizedmethods.
Aisincorrectbecausestaticmethodscanbesynchronizedtheysynchronizeonthelockon
theinstanceofclassjava.lang.Classthatrepresentstheclasstype.
Cisincorrectbecauseonlymethodsnotvariablescanbemarkedsynchronized.
Disincorrectbecauseasleepingthreadstillmaintainsitslocks.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

15. Whichstatementistrue?
A.

CallingRuntime.gc()willcauseeligibleobjectstobegarbagecollected.

B.

Thegarbagecollectorusesamarkandsweepalgorithm.

C.

Ifanobjectcanbeaccessedfromalivethread,itcan'tbegarbagecollected.

D.

Ifobject1referstoobject2,thenobject2can'tbegarbagecollected.

Answer:OptionC
Explanation:
Thisisagreatwaytothinkaboutwhenobjectscanbegarbagecollected.
OptionAandBassumeguaranteesthatthegarbagecollectornevermakes.

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

7/11

9/15/2015

00:29:57
OptionDiswrongbecauseofthenowfamousislandsofisolationscenario.
Learnmoreproblemson:GarbageCollections
Discussaboutthisproblem:DiscussinForum

16. WhichstatementistrueaboutassertionsintheJavaprogramminglanguage?
A.

Assertionexpressionsshouldnotcontainsideeffects.

B.

Assertionexpressionvaluescanbeanyprimitivetype.

C.

Assertionsshouldbeusedforenforcingpreconditionsonpublicmethods.

D.

AnAssertionErrorthrownasaresultofafailedassertionshouldalwaysbehandled
bytheenclosingmethod.

Answer:OptionA
Explanation:
OptionAiscorrect.Becauseassertionsmaybedisabled,programsmustnotassumethatthe
booleanexpressionscontainedinassertionswillbeevaluated.Thustheseexpressionsshould
befreeofsideeffects.Thatis,evaluatingsuchanexpressionshouldnotaffectanystatethat
isvisibleaftertheevaluationiscomplete.Althoughitisnotillegalforabooleanexpression
containedinanassertiontohaveasideeffect,itisgenerallyinappropriate,asitcouldcause
programbehaviourtovarydependingonwhetherassertionsareenabledordisabled.
Assertioncheckingmaybedisabledforincreasedperformance.Typically,assertioncheckingis
enabledduringprogramdevelopmentandtestinganddisabledfordeployment.
OptionBiswrong.Becauseyouassertthatsomethingis"true".TrueisBoolean.So,an
expressionmustevaluatetoBoolean,notintorbyteoranythingelse.Usethesamerulesfor
anassertionexpressionthatyouwoulduseforawhilecondition.
OptionCiswrong.Usually,enforcingapreconditiononapublicmethodisdonebycondition
checkingcodethatyouwriteyourself,togiveyouspecificexceptions.
OptionDiswrong."You'reneversupposedtohandleanassertionfailure"
Notalllegalusesofassertionsareconsideredappropriate.AswithsomuchofJava,youcan
abusetheintendeduseforassertions,despitethebesteffortsofSun'sJavaengineersto
discourageyou.Forexample,you'reneversupposedtohandleanassertionfailure.That
meansdon'tcatchitwithacatchclauseandattempttorecover.Legally,however,
AssertionErrorisasubclassofThrowable,soitcanbecaught.Butjustdon'tdoit!Ifyou're
goingtotrytorecoverfromsomething,itshouldbeanexception.Todiscourageyoufrom
tryingtosubstituteanassertionforanexception,theAssertionErrordoesn'tprovideaccessto
theobjectthatgeneratedit.AllyougetistheStringmessage.
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

17. Whatwillbetheoutputoftheprogram?
publicclassObjComp
{
publicstaticvoidmain(String[]args)
{
intresult=0
ObjCompoc=newObjComp()
Objecto=oc
if(o==oc)
result=1
if(o!=oc)
result=result+10
if(o.equals(oc))
result=result+100
if(oc.equals(o))
result=result+1000
System.out.println("result="+result)
}
}
A.

B.

10

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

8/11

9/15/2015

00:29:57
C.

101

D.

1101

Answer:OptionD
Explanation:
Eventhoughoandocarereferencevariablesofdifferenttypes,theyarebothreferringtothe
sameobject.Thismeansthat==willresolvetotrueandthatthedefaultequals()methodwill
alsoresolvetotrue.
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

18. Whatwillbetheoutputoftheprogram?
publicclassTest178
{
publicstaticvoidmain(String[]args)
{
Strings="foo"
Objecto=(Object)s
if(s.equals(o))
{
System.out.print("AAA")
}
else
{
System.out.print("BBB")
}
if(o.equals(s))
{
System.out.print("CCC")
}
else
{
System.out.print("DDD")
}
}
}
A.

AAACCC

B.

AAADDD

C.

BBBCCC

D.

BBBDDD

Answer:OptionA
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

19. Whatwillbetheoutputoftheprogram?
inti=1,j=10
do
{
if(i++>j)/*Line4*/
{
continue
}
}while(i<5)
System.out.println("i="+i+"andj="+j)/*Line9*/
A.

i=6andj=5

B.

i=5andj=5

C.

i=6andj=6

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

9/11

9/15/2015

00:29:57
D.

i=5andj=6

Answer:OptionD
Explanation:
Thisquestionisnottestingyourknowledgeofthecontinuestatement.Itistestingyour
knowledgeoftheorderofevaluationofoperands.Basicallytheprefixandpostfixunary
operatorshaveahigherorderofevaluationthantherelationaloperators.Soonline4the
variableiisincrementedandthevariablejisdecrementedbeforethegreaterthancomparison
ismade.Astheloopexecutesthecomparisononline4willbe:
if(i>j)
if(2>9)
if(3>8)
if(4>7)
if(5>6)atthispointiisnotlessthan5,thereforetheloopterminatesandline9outputsthe
valuesofiandjas5and6respectively.
Thecontinuestatementnevergetstoexecutebecauseineverreachesavaluethatisgreater
thanj.
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

20. Whatwillbetheoutputoftheprogram?
publicclassExamQuestion7
{
staticintj
staticvoidmethodA(inti)
{
booleanb
do
{
b=i<10|methodB(4)/*Line9*/
b=i<10||methodB(8)/*Line10*/
}while(!b)
}
staticbooleanmethodB(inti)
{
j+=i
returntrue
}
publicstaticvoidmain(String[]args)
{
methodA(0)
System.out.println("j="+j)
}
}
A.

j=0

B.

j=4

C.

j=8

D.

Thecodewillrunwithnooutput

Answer:OptionB
Explanation:
Thelinestowatchherearelines9&10.Line9featuresthenonshortcutversionoftheOR
operatorsobothofitsoperandswillbeevaluatedandthereforemethodB(4)isexecuted.
Howeverline10hastheshortcutversionoftheORoperatorandifthe1stofitsoperands
evaluatestotrue(whichinthiscaseistrue),thenthe2ndoperandisn'tevaluated,so
methodB(8)nevergetscalled.
Theloopisonlyexecutedonce,bisinitializedtofalseandisassignedtrueonline9.Thusj=
4.
Learnmoreproblemson:Java.langClass

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

10/11

9/15/2015

00:29:57
Discussaboutthisproblem:DiscussinForum

SubmitTest

20082015byIndiaBIXTechnologies.AllRightsReserved|Copyright|TermsofUse&PrivacyPolicy

Contactus:info@indiabix.com
Bookmarkto:

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

Followusontwitter!

11/11

Das könnte Ihnen auch gefallen