0% found this document useful (0 votes)
109 views12 pages

Java Programming Test 1

The code doesn't compile because the method GetResult() in class a is final and so cannot be overridden. If both operands are numeric, the + operator will add the two operands?

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)
109 views12 pages

Java Programming Test 1

The code doesn't compile because the method GetResult() in class a is final and so cannot be overridden. If both operands are numeric, the + operator will add the two operands?

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/ 12

9/15/2015

00:29:37

Like

Share

Java Programming Test 1


JavaProgramming

1.

Result&Statistics

Whatwillbetheoutputoftheprogram?
classA
{
finalpublicintGetResult(inta,intb){return0}
}
classBextendsA
{
publicintGetResult(inta,intb){return1}
}
publicclassTest
{
publicstaticvoidmain(Stringargs[])
{
Bb=newB()
System.out.println("x="+b.GetResult(0,1))
}
}
A.

x=0

B.

x=1

C.

Compilationfails.

D.

Anexceptionisthrownatruntime.

Marks:0/20
Totalnumberofquestions

: 20

Numberofansweredquestions

Numberofunansweredquestions : 19

Feedback
QualityoftheTest

Select

DifficultyoftheTest

Select

Comments:
...

SubmitFeedback

TakeanAnotherRandomTest!
GotoOnlineTestPage
GotoHomePage

Answer:OptionC
Explanation:
Thecodedoesn'tcompilebecausethemethodGetResult()inclassAisfinalandsocannotbe
overridden.
Learnmoreproblemson:DeclarationsandAccessControl
Discussaboutthisproblem:DiscussinForum

2.

Whatwillbetheoutputoftheprogram?
classSC2
{
publicstaticvoidmain(String[]args)
{
SC2s=newSC2()
s.start()
}
voidstart()
{
inta=3
intb=4
System.out.print(""+7+2+"")
System.out.print(a+b)
System.out.print(""+a+b+"")
System.out.print(foo()+a+b+"")
System.out.println(a+b+foo())
}
Stringfoo()
{
return"foo"

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

1/12

9/15/2015

00:29:37
}
}
A.

977foo77foo

B.

723434foo3434foo

C.

977foo3434foo

D.

72734foo347foo

Answer:OptionD
Explanation:
Becausealloftheseexpressionsusethe+operator,thereisnoprecedencetoworryabout
andalloftheexpressionswillbeevaluatedfromlefttoright.Ifeitheroperandbeingevaluated
isaString,the+operatorwillconcatenatethetwooperandsifbothoperandsarenumeric,
the+operatorwilladdthetwooperands.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

3.

Whatwillbetheoutputoftheprogram?
classBoolArray
{
boolean[]b=newboolean[3]
intcount=0
voidset(boolean[]x,inti)
{
x[i]=true
++count
}
publicstaticvoidmain(String[]args)
{
BoolArrayba=newBoolArray()
ba.set(ba.b,0)
ba.set(ba.b,2)
ba.test()
}
voidtest()
{
if(b[0]&&b[1]|b[2])
count++
if(b[1]&&b[(++count2)])
count+=7
System.out.println("count="+count)
}
}
A.

count=0

B.

count=2

C.

count=3

D.

count=4

Answer:OptionC
Explanation:
Thereferencevariablesbandxbothrefertothesamebooleanarray.countisincrementedfor
eachcalltotheset()method,andonceagainwhenthefirstiftestistrue.Becauseofthe&&
shortcircuitoperator,countisnotincrementedduringthesecondiftest.
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

4.

Whichtwostatementsareequivalent?
1. 3/2
2. 3<2
3. 3*4

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

2/12

9/15/2015

00:29:37
4. 3<<2
A.

1and2

B.

2and3

C.

3and4

D.

1and4

Answer:OptionC
Explanation:
(1)iswrong.3/2=1(integerarithmetic).
(2)iswrong.3<2=false.
(3)iscorrect.3*4=12.
(4)iscorrect.3<<2=12.Inbinary3is11,nowshiftthebitstwoplacestotheleftandwe
get1100whichis12inbinary(3*2*2).
Learnmoreproblemson:OperatorsandAssignments
Discussaboutthisproblem:DiscussinForum

5.

publicvoidfoo(booleana,booleanb)
{
if(a)
{
System.out.println("A")/*Line5*/
}
elseif(a&&b)/*Line7*/
{
System.out.println("A&&B")
}
else/*Line11*/
{
if(!b)
{
System.out.println("notB")
}
else
{
System.out.println("ELSE")
}
}
}
A.

Ifaistrueandbistruethentheoutputis"A&&B"

B.

Ifaistrueandbisfalsethentheoutputis"notB"

C.

Ifaisfalseandbistruethentheoutputis"ELSE"

D.

Ifaisfalseandbisfalsethentheoutputis"ELSE"

Answer:OptionC
Explanation:
OptionCiscorrect.Theoutputis"ELSE".Onlywhenaisfalsedotheoutputlinesafter11get
somechanceofexecuting.
OptionAiswrong.Theoutputis"A".Whenaistrue,irrespectiveofthevalueofb,onlythe
line5outputwillbeexecuted.Theconditionatline7willneverbeevaluated(whenaistrueit
willalwaysbetrappedbytheline12condition)thereforetheoutputwillneverbe"A&&B".
OptionBiswrong.Theoutputis"A".Whenaistrue,irrespectiveofthevalueofb,onlythe
line5outputwillbeexecuted.
OptionDiswrong.Theoutputis"notB".
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

6.

Whatwillbetheoutputoftheprogram?
Floatf=newFloat("12")

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

3/12

9/15/2015

00:29:37
switch(f)
{
case12:System.out.println("Twelve")
case0:System.out.println("Zero")
default:System.out.println("Default")
}
A.

Zero

B.

Twelve

C.

Default

D.

Compilationfails

Answer:OptionD
Explanation:
Theswitchstatementcanonlybesupportedbyintegersorvariablesmore"narrow"thanan
integeri.e.byte,char,short.HereaFloatwrapperobjectisusedandsothecompilationfails.
Learnmoreproblemson:FlowControl
Discussaboutthisproblem:DiscussinForum

7.

Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticvoidaMethod()throwsException
{
try/*Line5*/
{
thrownewException()/*Line7*/
}
finally/*Line9*/
{
System.out.print("finally")/*Line11*/
}
}
publicstaticvoidmain(Stringargs[])
{
try
{
aMethod()
}
catch(Exceptione)/*Line20*/
{
System.out.print("exception")
}
System.out.print("finished")/*Line24*/
}
}
A.

finally

B.

exceptionfinished

C.

finallyexceptionfinished

D.

Compilationfails

Answer:OptionC
Explanation:
Thisiswhathappens:
(1)Theexecutionofthetryblock(line5)completesabruptlybecauseofthethrowstatement
(line7).
(2)Theexceptioncannotbeassignedtotheparameterofanycatchclauseofthetry
statementthereforethefinallyblockisexecuted(line9)and"finally"isoutput(line11).
(3)Thefinallyblockcompletesnormally,andthenthetrystatementcompletesabruptly
becauseofthethrowstatement(line7).
(4)Theexceptionispropagatedupthecallstackandiscaughtbythecatchinthemain
method(line20).Thisprints"exception".
(5)Lastlyprogramexecutioncontinues,becausetheexceptionhasbeencaught,and

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

4/12

9/15/2015

00:29:37
"finished"isoutput(line24).
Learnmoreproblemson:Exceptions
Discussaboutthisproblem:DiscussinForum

8.

Whichstatementistruefortheclassjava.util.ArrayList?
A.

Theelementsinthecollectionareordered.

B.

Thecollectionisguaranteedtobeimmutable.

C.

Theelementsinthecollectionareguaranteedtobeunique.

D.

Theelementsinthecollectionareaccessedusingauniquekey.

Answer:OptionA
Explanation:
Yes,alwaystheelementsinthecollectionareordered.
Learnmoreproblemson:ObjectsandCollections
Discussaboutthisproblem:DiscussinForum

9.

Whichistrueaboutamethodlocalinnerclass?
A.

Itmustbemarkedfinal.

B.

Itcanbemarkedabstract.

C.

Itcanbemarkedpublic.

D.

Itcanbemarkedstatic.

Answer:OptionB
Explanation:
OptionBiscorrectbecauseamethodlocalinnerclasscanbeabstract,althoughitmeansa
subclassoftheinnerclassmustbecreatediftheabstractclassistobeused(soanabstract
methodlocalinnerclassisprobablynotuseful).
OptionAisincorrectbecauseamethodlocalinnerclassdoesnothavetobedeclaredfinal
(althoughitislegaltodoso).
CandDareincorrectbecauseamethodlocalinnerclasscannotbemadepublic(remember
youcannotmarkanylocalvariablesaspublic),orstatic.
Learnmoreproblemson:InnerClasses
Discussaboutthisproblem:DiscussinForum

10. classXimplementsRunnable
{
publicstaticvoidmain(Stringargs[])
{
/*Missingcode?*/
}
publicvoidrun(){}
}
Whichofthefollowinglineofcodeissuitabletostartathread?
A.

Threadt=newThread(X)

B.

Threadt=newThread(X)t.start()

C.

Xrun=newX()Threadt=newThread(run)t.start()

D.

Threadt=newThread()x.run()

Answer:OptionC
Explanation:

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

5/12

9/15/2015

00:29:37
OptionCissuitabletostartathread.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

11. Whatwillbetheoutputoftheprogram?
classMyThreadextendsThread
{
publicstaticvoidmain(String[]args)
{
MyThreadt=newMyThread()
t.start()
System.out.print("one.")
t.start()
System.out.print("two.")
}
publicvoidrun()
{
System.out.print("Thread")
}
}
A.

Compilationfails

B.

Anexceptionoccursatruntime.

C.

Itprints"Threadone.Threadtwo."

D.

Theoutputcannotbedetermined.

Answer:OptionB
Explanation:
Whenthestart()methodisattemptedasecondtimeonasingleThreadobject,themethod
willthrowanIllegalThreadStateException(youwillnotneedtoknowthisexceptionnamefor
theexam).Evenifthethreadhasfinishedrunning,itisstillillegaltocallstart()again.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

12. Whatwillbetheoutputoftheprogram?
classMyThreadextendsThread
{
MyThread(){}
MyThread(Runnabler){super(r)}
publicvoidrun()
{
System.out.print("InsideThread")
}
}
classMyRunnableimplementsRunnable
{
publicvoidrun()
{
System.out.print("InsideRunnable")
}
}
classTest
{
publicstaticvoidmain(String[]args)
{
newMyThread().start()
newMyThread(newMyRunnable()).start()
}
}
A.

Prints"InsideThreadInsideThread"

B.

Prints"InsideThreadInsideRunnable"

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

6/12

9/15/2015

00:29:37
C.

Doesnotcompile

D.

Throwsexceptionatruntime

Answer:OptionA
Explanation:
IfaRunnableobjectispassedtotheThreadconstructor,thentherunmethodoftheThread
classwillinvoketherunmethodoftheRunnableobject.
Inthiscase,however,therunmethodintheThreadclassisoverriddenbytherunmethodin
MyThreadclass.Thereforetherun()methodinMyRunnableisneverinvoked.
Bothtimes,therun()methodinMyThreadisinvokedinstead.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

13. Whatwillbetheoutputoftheprogram?
classsimplementsRunnable
{
intx,y
publicvoidrun()
{
for(inti=0i<1000i++)
synchronized(this)
{
x=12
y=12
}
System.out.print(x+""+y+"")
}
publicstaticvoidmain(Stringargs[])
{
srun=news()
Threadt1=newThread(run)
Threadt2=newThread(run)
t1.start()
t2.start()
}
}
A.

DeadLock

B.

Itprint12121212

C.

CompilationError

D.

Cannotdetermineoutput.

Answer:OptionB
Explanation:
Theprogramwillexecutewithoutanyproblemsandprint12121212.
Learnmoreproblemson:Threads
Discussaboutthisproblem:DiscussinForum

14. publicclassTest
{
publicvoidfoo()
{
assertfalse/*Line5*/
assertfalse/*Line6*/
}
publicvoidbar()
{
while(true)
{
assertfalse/*Line12*/
}
assertfalse/*Line14*/
}
}

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

7/12

9/15/2015

00:29:37
Whatcausescompilationtofail?
A.

Line5

B.

Line6

C.

Line12

D.

Line14

Answer:OptionD
Explanation:
OptionDiscorrect.Compilationfailsbecauseofanunreachablestatementatline14.Itisa
compiletimeerrorifastatementcannotbeexecutedbecauseitisunreachable.Thequestion
isnow,whyisline20unreachable?Ifitisbecauseoftheassertthensurelyline6wouldalso
beunreachable.Theanswermustbesomethingotherthanassert.
Examinethefollowing:
Awhilestatementcancompletenormallyifandonlyifatleastoneofthefollowingistrue:
Thewhilestatementisreachableandtheconditionexpressionisnotaconstantexpression
withvaluetrue.
Thereisareachablebreakstatementthatexitsthewhilestatement.
Thewhilestatementatline11isinfiniteandthereisnobreakstatementthereforeline14is
unreachable.Youcantestthiswiththefollowingcode:
publicclassTest80
{
publicvoidfoo()
{
assertfalse
assertfalse
}
publicvoidbar()
{
while(true)
{
assertfalse
break
}
assertfalse
}
}
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

15. Whatwillbetheoutputoftheprogram?
publicclassTest
{
publicstaticinty
publicstaticvoidfoo(intx)
{
System.out.print("foo")
y=x
}
publicstaticintbar(intz)
{
System.out.print("bar")
returny=z
}
publicstaticvoidmain(String[]args)
{
intt=0
assertt>0:bar(7)
assertt>1:foo(8)/*Line18*/
System.out.println("done")
}
}
A.

bar

B.

bardone

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

8/12

9/15/2015

00:29:37
C.

foodone

D.

Compilationfails

Answer:OptionD
Explanation:
Thefoo()methodreturnsvoid.Itisaperfectlyacceptablemethod,butbecauseitreturnsvoid
itcannotbeusedinanassertstatement,soline18willnotcompile.
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

16. Whichofthefollowingstatementsistrue?
A.

Inanassertstatement,theexpressionafterthecolon(:)canbeanyJava
expression.

B.

Ifaswitchblockhasnodefault,addinganassertdefaultisconsideredappropriate.

C.

Inanassertstatement,iftheexpressionafterthecolon(:)doesnothavea
value,theassert'serrormessagewillbeempty.

D.

Itisappropriatetohandleassertionfailuresusingacatchclause.

Answer:OptionB
Explanation:
Addinganassertionstatementtoaswitchstatementthatpreviouslyhadnodefaultcaseis
consideredanexcellentuseoftheassertmechanism.
OptionAisincorrectbecauseonlyJavaexpressionsthatreturnavaluecanbeused.For
instance,amethodthatreturnsvoidisillegal.
OptionCisincorrectbecausetheexpressionafterthecolonmusthaveavalue.
OptionDisincorrectbecauseassertionsthrowerrorsandnotexceptions,andassertionerrors
docauseprogramterminationandshouldnotbehandled.
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

17. publicclassTest2
{
publicstaticintx
publicstaticintfoo(inty)
{
returny*2
}
publicstaticvoidmain(String[]args)
{
intz=5
assertz>0/*Line11*/
assertz>2:foo(z)/*Line12*/
if(z<7)
assertz>4/*Line14*/
switch(z)
{
case4:System.out.println("4")
case5:System.out.println("5")
default:assertz<10
}
if(z<10)
assertz>4:z++/*Line22*/
System.out.println(z)
}
}
whichlineisanexampleofaninappropriateuseofassertions?
A.

Line11

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

9/12

9/15/2015

00:29:37
B.

Line12

C.

Line14

D.

Line22

Answer:OptionD
Explanation:
Assertstatementsshouldnotcausesideeffects.Line22changesthevalueofziftheassert
statementisfalse.
OptionAisfineasecondexpressioninanassertstatementisnotrequired.
OptionBisfinebecauseitisperfectlyacceptabletocallamethodwiththesecondexpression
ofanassertstatement.
OptionCisfinebecauseitispropertocallanassertstatementconditionally.
Learnmoreproblemson:Assertions
Discussaboutthisproblem:DiscussinForum

18. Whatwillbetheoutputoftheprogram?
publicclassNFE
{
publicstaticvoidmain(String[]args)
{
Strings="42"
try
{
s=s.concat(".5")/*Line8*/
doubled=Double.parseDouble(s)
s=Double.toString(d)
intx=(int)Math.ceil(Double.valueOf(s).doubleValue())
System.out.println(x)
}
catch(NumberFormatExceptione)
{
System.out.println("badnumber")
}
}
}
A.

42

B.

42.5

C.

43

D.

badnumber

Answer:OptionC
Explanation:
Allofthiscodeislegal,andline8createsanewStringwithavalueof"42.5".Lines9and10
converttheStringtoadoubleandthenbackagain.Line11isfunMath.ceil()'sargument
expressionisevaluatedfirst.WeinvokethevalueOf()methodthatreturnsananonymous
Doubleobject(withavalueof42.5).ThenthedoubleValue()methodiscalled(invokedonthe
newlycreatedDoubleobject),andreturnsadoubleprimitive(thereandbackagain),witha
valueof(youguessedit)42.5.Theceil()methodconvertsthisto43.0,whichiscasttoanint
andassignedtox.
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

19. Whatwillbetheoutputoftheprogram?
publicclassTest138
{
publicstaticvoidstringReplace(Stringtext)
{

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

10/12

9/15/2015

00:29:37
text=text.replace('j','c')/*Line5*/
}
publicstaticvoidbufferReplace(StringBuffertext)
{
text=text.append("c")/*Line9*/
}
publicstaticvoidmain(Stringargs[])
{
StringtextString=newString("java")
StringBuffertextBuffer=newStringBuffer("java")/*Line14*/
stringReplace(textString)
bufferReplace(textBuffer)
System.out.println(textString+textBuffer)
}
}
A.

java

B.

javac

C.

javajavac

D.

Compileerror

Answer:OptionC
Explanation:
Astringisimmutable,itcannotbechanged,that'sthereasonfortheStringBufferclass.The
stringReplacemethoddoesnotchangethestringdeclaredonline14,sothisremainssetto
"java".
Methodparametersarealwayspassedbyvalueacopyispassedintothemethodifthecopy
changes,theoriginalremainsintact,line5changesthereferencei.e.textpointstoanew
Stringobject,howeverthisislostwhenthemethodcompletes.ThetextBufferisa
StringBuffersoitcanbechanged.
Thischangeiscarriedoutonline9,so"java"becomes"javac",thetextreferenceonline9
remainsunchanged.Thisgivesustheoutputof"javajavac"
Learnmoreproblemson:Java.langClass
Discussaboutthisproblem:DiscussinForum

20. Whatwillbetheoutputoftheprogram(injdk1.6orabove)?
publicclassBoolTest
{
publicstaticvoidmain(String[]args)
{
Booleanb1=newBoolean("false")
booleanb2
b2=b1.booleanValue()
if(!b2)
{
b2=true
System.out.print("x")
}
if(b1&b2)/*Line13*/
{
System.out.print("y")
}
System.out.println("z")
}
}
A.

B.

xz

C.

yz

D.

Compilationfails.

Answer:OptionB
Learnmoreproblemson:Java.langClass

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

11/12

9/15/2015

00:29:37
Discussaboutthisproblem:DiscussinForum

SubmitTest

20082015byIndiaBIXTechnologies.AllRightsReserved|Copyright|TermsofUse&PrivacyPolicy

Contactus:[email protected]
Bookmarkto:

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

Followusontwitter!

12/12

You might also like