




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter2PrimitiveDataTypesandOperations
1.
Valididentifiers:applet,Applet,$4,appslnvalididentifiers:a++,-a,4#R,#44
2.
Keywords:
class,public,int
3.
doublemiles=100;
finaldoubleMILE_TO_KILOMETER=1.609;
doublekilometer=MILE_TO_KILOMETER*miles;
System.out.println(kilometer);
Thevalueofkilometeris160.9.
4.Therearethreebenefitsofusingconstants:(l)youdon'thavetorepeatedlytypethesame
value;(2)thevaluecanbechangedinasinglelocation,ifnecessary;(3)theprogramiseasyto
read,finalintSIZE=20;
5.
a=46/9;=>a=5
a=46%9+4*4-2;=>a=l+16-2=15
a=45+43%5*(23*3%2);=>a=45+3*(1)=48
a%=3/a+3;=>a%=3+3;a%=6=>a=a%6=l;
d=4+d*d+4;=>4+1.0+4=9.0
d+=1.5*3+(++a);=>d+=4.5+2;d+=6.5;=>d=7.5
d-=1.5*3+a++;=>d-=4.5+1;=>d=1-5.5=-4.5
6.
2
2
-4
-4
0
1
7.
Forbyte,from-128to127,inclusive.
Forshort,from-32768to32767,inclusive.
Forint,from-2147483648to2147483647,inclusive.
Forlong,from-9223372036854775808to9223372036854775807.
Forfloat,thesmallestpositivefloatisl.40129846432481707e-45andthelargestfloat
js3.40282346638528860e+38.
Fordouble,thesmallestpositivedoubleis4.94065645841246544e-324andthelargestdouble
isl.79769313486231570e+308d.
8.
25/4=6.Ifyouwantthequotienttobeafloating-point
number,rewriteitas25.0/4.0.
9.
Yes,thestatementsarecorrect.Theprintoutis
theoutputfor25/4is6;
theoutputfor25/4.0is6.25;
10.4.0/(3.0*(r+34))-9*(a+b*c)+(3.0+d*
(2+a))/(a+b*d)
11.bandcaretrue.
12.
All.
13.
Line2:Missingstaticforthemainmethod.
Line2:stringshouldbeString.
Line3:iisdefinedbutnotinitializedbeforeitis
usedinLine5.
Line4:kisanint,cannotassignadoublevaluetok.
Lines7-8:Thestringcannotbebrokenintotwolines.
14.
Yes.Differenttypesofnumericvaluescanbeusedinthesamecomputationthroughnumeric
conversionsreferredtoascasting.
15.Thefractionalpartistruncated.Castingdoesnotchangethevariablebeingcast.
16.
fis12.5
iis12
17.
System.out.println((int)'l');
System.out.println((int)'A*);
System.out.println((int)'B');
System.out.println((int)'a');
System.out.println((int)'b,);
System.out.println((char)40);
System.out.println((char)59);
System.out.println((char)79);
System.out.println((char)85);
System.out.println((char)90);
System.out.println((char)0X40);
System.out.println((char)0X5A);
System.out.println((char)0X71);
System.out.println((char)0X72);
System.out.println((char)0X7A);
18.'\u345dE'iswrong.Itmusthaveexactlyfourhexnumbers.
19.'\\'and'V
20.
ibecomes49,sincetheASCIIcodeof'1'is49;
jbecome99since(int)'l'is49and(int)*2'is50;
kbecomes97sincetheASCIIcodeof'a'is97;
cbecomescharacter'z'since(int)*z'is90;
21.
charc='A';
i=(int)c;//ibecomes65
booleanb=true;
i=(int)b;//Notallowed
floatf=1000.34f;
inti=(int)f;//ibecomes1000
doubled=1000.34;
inti=(int)d;//ibecomes1000
inti=97;
charc=(char)i;//cbecomes'a'
22.
System.out.println("l"+1);=>11
System.out.println('l'+1);=>50(sincetheUnicodefor1is49
System.out.printlnCl"+1+1);=>111
System.out.println("l"+(1+1));=>12
System.out.println('l'+1+1);=>51
23.
1+"Welcome"+1+1islWelcome11.
1+"Welcome"+(1+1)islWelcome2.
1+"Welcome"+('\u0001'+1)islWelcome2
1+"Welcome"+*a'+1islWelcomeal
24.
UseDouble.parseDouble(string)toconvertadecimalstringintoadoublevalue.
UseInteger.parselnt(string)toconvertanintegerstringintoanintvalue.
25.
longtotalMills=System.currentTimeMillis()returnsthe
millisecondssinceJan1,1970.totalMills%(1000*60
*60)returnsthecurrentminute.
26.
Use//todenoteacommentline,anduse/*paragraph*/todenoteacommentparagraph.
27.
Classnames:Capitalizethefirstletterineachname.
Variablesandmethodnames:Lowercasethefirstword,
capitalizethefirstletterinallsubsequentwords.
Constants:Capitalizeallletters.
28.
publicclassTest{
/**Mainmethod*/
publicstaticvoidmain(String[]args){
//PrintalineSystem.out.println("2%3="+2%3);
29.
Compilationerrorsaredetectedbycompilers.Runtimeerrorsoccurduringexecutionofthe
program.Logicerrorsresultsinincorrectresults.
Chapter3SelectionStatements
1.<,<=,==,!=,>,>=
2.
(true)&&(3>4)false
!(x>0)&&(x>0)false
(x>0)||(x<0)true
(x!=0)11(x==0)true
(x>=0)11(x<0)true
(x!=1)==!(x==1)true
3.(x>1)&&(x<100)
4.((x>1)&&(x<100))||(x<0)
5.
x>y>0incorrect
x=y&&yincorrect
x/=ycorrect
xoryincorrect
xandyincorrect
6.No.Booleanvaluescannotbecasttoothertypes.
7.xis2.
8.xis1.
9.ddfalse-4
10.Note:elsematchesthefirstifclause.Nooutputifx=3andy=2.Output
is"zis7"ififx=3andy=4.Outputis"xis2"ififx=2andy=2.
11.a,c,anddarethesame.(B)and(C)arecorrectlyindented.
12.Nooutputifx=2andy=3.Outputis"xis3"ifx=2andy=2.
Outputis"zis6".
x>2
falsetrue
System.out.println("xis"+x);
V>2
false
true
intz=x+y;
System.out.println("zis"+z);
13.Yes.
14.0.5,0.0,0.234
15.
(int)(Math.random()*20)
10+(int)(Math.random()*10)
10+(int)(Math.random()*41)
x+=34;breakais4
ais1
x+=5;breakx+=10;breakais2
x+=16;breakais3
16.Switchvariablesmustbeofchar,byte,short,orintdatatypes.Ifabreakstatementisnot
used,thenextcasestatementisperformed.Youcanalwaysconvertaswitchstatementtoan
equivalentifstatement,butnotanifstatementtoaswitchstatement.Theuseoftheswitch
statementcanimprovereadabilityoftheprograminsomecases.Thecompiledcodeforthe
switchstatementisalsomoreefficientthanitscorrespondingifstatement.
17.yis2.
18.
switch(a){
case1:x+=5;break;
case2:x+=10;break;
case3:x+=16;break;
case4:x+=34;
}
19.System.out.print((count%10==0)?count+"\n":count+"");
20.
Thespecifiersforoutputtingabooleanvalue,acharacter,adecimalinteger;afloating-point
number,andastringare%b,%c,%d,%f,and%s.
21.
(a)thelastitem3doesnothaveanyspecifier.
(b)Thereisnotenoughitems
(c)Thedatafor%fmustafloating-pointvalue
22.
(a)amountis32.3200003.233000e+01
(b)amountis32.32003.2330e+01
(c)*false〃*denoteaspace
(d)**Java//*denoteaspace
(e)false*****Java
(f)*falseJava
23.UsetheString.formatmethodtocreateaformattedstring.
24.
Theprecedenceorderforbooleanoperatorsis&,八,|,&&,and11
true|true&&falseisfalse
true11true&&falseistrue
true|true&falseistrue.
25.
a.Theoperandsareevaluatedfirstandfromlefttoright.So(-i+i+i++)is-1-1-1.i++return
thevalueofi,theniisincrementedby1.So,inthenextprintinstatementi+++iis0+1.
b.Theoperandsareevaluatedfirstandfromlefttoright.So,theleftibeforethe+operatoris0
andrightiisassignedto1by(i=1).Thereforetheprintinstatementprints1.
c.Theoperandsareevaluatedfirstandfromlefttoright.So,beforeiintherightofthe+
operatorisevaluated,iisassignedto1.Therefore,(i=1)+ievaluatesto2.
26.
a=(a=3)+a;=>a=3+3=6
a=a+(a=3);=>a=l+3=4
a+=a+(a=3);=>thevalueofaintheleftsideof+=isobtained(1),a+(a=3)is
4,therefore,thefinalresultais5.
a=5+5*2%a—;=>a=5+10%a-=5+0=5
a=4+l+4*5%(++a+l)=>a=5+4*5%(++a+1)=5+20%(++a+1)=5+20%
(2+l)=5+20%3=5+2=7;
d+=1.5*3+(++d);=>thevalueofdintheleftsideof+=isobtained(1.0),1.5*3
+(++d)=4.5+(++d)=4.5+2.0=6.5,therefore,thefinalresultais7.5.
d-=1.5*3+d++;=>thevalueofdintheleftsideof+=isobtained(1.0),1.5*3+
d++=4.5+d++=4.5+1.0=5.5,therefore,thefinalresultis1.0-5.5=-4.5.
Chapter4Loops
1.
(A)Theloopbodyisnotexecuted.
(B)Theloopbodyisexecutedninetimes.Theprintoutis2,4,6,8on
separatelines.
2.Thedifferencebetweenado-whileloopandawhileloopistheorderofevaluatingthe
continuation-conditionandexecutingtheloopbody.Inawhileloop,thecontinuation-condition
ischeckedandthen,iftrue,theloopbodyisexecuted.Inado-whileloop,theloopbodyis
executedforthefirsttimebeforethecontinuation-conditionisevaluated.
3.Same.Whenthei++and++iareusedinisolation,theireffectsaresame.
4.
Thethreepartsinaforloopcontrolareasfollows:
Thefirstpartinitializesthecontrolvariable.
ThesecondpartisaBooleanexpressionthatdetermineswhethertheloopwill
repeat.
Thethirdpartistheadjustmentstatement,whichadjuststhecontrolvariable.
for(inti=l,i<=100,i++)
System.out.println(i);
5.Theloopkeepsdoingsomethingindefinitely.
6.No.Thescopeofthevariableisinsidetheloop.
7.Yes.Theadvantagesofforloopsaresimplicityandreadability.Compilerscanproducemore
efficientcodefortheforloopthanforthecorrespondingwhileloop.
8.
whileloop:
longsum=0;
inti=0;
while(i<=1000){
sum+=i++;
}
do-whileloop:
longsum=0;
inti=0;
do{
sum+=i++;
)
while(i<=1000);
9.No.Trynl=3andn2=3.
10.
Thekeywordbreakisusedtoexitthecurrentloop.Theprogramin(A)willterminate.Theoutput
isBalanceis1.Thekeywordcontinuecausestherestoftheloopbodytobeskippedforthe
currentiteration.Thewhileloopwillnotterminatein(B).
11.Yes.
for(inti=l;sum<10000;i++)
sum=sum+i;
12.Ifacontinuestatementisexecutedinsideaforloop,therestoftheiterationisskipped,then
theaction-after-each-iterationisperformedandtheloop-continuation-conditionischecked.Ifa
continuestatementisexecutedinsideawhileloop,therestoftheiterationisskipped,thenthe
loop-continuation-conditionischecked.
Hereisthefix:
inti=0;
while(i<4){
if(i%3==0){
i++;
continue;
)
sum+=i;
i++;
)
13.
classTestBreak{
publicstaticvoidmain(string[]args){
intsum=0;
intnumber=0;
do{
number++;
sum+=number;
}
while(number<2011sum>=100);
System.out.println("Thesumis"+sum);
classTestContinue{
publicstaticvoidmain(String[]args){
intsum=0;
intnumber=0;
do{
number++;
if(number!=10&&number!=11)
sum+=number;
)
while(number<20);
System.out.println("Thesumis"+sum);
)
}
14.Thestatementlabelednext.
15.Thecontrolisintheouterloop,andthenextiterationoftheouterloopisexecuted.
16.
Line3:Thesemicolon(;)attheendoftheforloopheadingshouldberemoved.
Line4:sumnotdefined.
Line5:thesemicolon(;)attheendoftheifstatementshouldberemoved.
Line6:Missingasemicolonforthefirstprintinstatement.
Une6:jnotdefined.
Line10:Thesemicolon(;)attheendofthewhileheadingshouldberemoved.
Line17:Missingasemicolonattheendofthewhileloop.
17.
(A)compileerror:iisnotinitialized.
(B)Line3:The;attheendofforloopshouldberemoved.
for(inti=0;i<10;i++);
18.
(A).0010120123
(B)********2****32****432****
(C).Ixxx2xxx4xxx8xxxl6xxxIxxx2xxx4xxx8xxxIxxx2xxx4xxxlxxx2xxxlxxx
(D).1G1G3G1G3G5G1G3G5G7G1G3G5G7G9G
19.
(A)
publicclassTest{
publicstaticvoidmain(String[]args){
inti=0;
if(i>0)
i++;
else
chargrade;
if(i>=90)
grade='A';
elseif(i>=80)
grade=B;
)
}
(B)
publicclassTest{
publicstaticvoidmain(String[]args){
for(inti=0;i<10;i++)
if(i>0)
i++;
else
Ch叩ter5Methods
1.Atleastthreebenefits:(1)Reusecode;(2)Reducecomplexity;(3)Easytomaintain.
SeetheSections4.2and4.3onhowtodeclareandinvokemethods.
2.void
3.Yes.return(numl>num2)?numl:num2;
4.
True:acalltoamethodwithavoidreturntypeisalwaysastatementitself.
False:acalltoamethodwithanonvoidreturntypeisalwaysacomponentofan
expression.
5.Asyntaxerroroccursifareturnstatementdoesnotappearinanon-voidmethod.Youcan
haveareturnstatementinavoidmethod,whichsimplyexitsthemethod.Butareturnstatement
cannotreturnavaluesuchasreturnx+yinavoidmethod.
6.SeeSection5.2.
7.
Computingasalescommissiongiventhesalesamountandthecommissionrate
publicstaticdoublegetCommission(doublesalesAmount,double
commissionRate)
Printingacalendarforamonth
publicstaticvoidprintCalendar(intmonth,intyear)
Computingasquareroot
publicstaticdoublesqrt(doublevalue)
Testingwhetheranumberisevenandreturntrueifitis
publicstaticbooleanisEven(intvalue)
Printingamessageforaspecifiednumberoftimes
publicstaticvoidprintMessage(Stringmessage,inttimes)
Computingthemonthlypayment,giventheloanamount,
numberofyears,andannualinterestrate.
publicstaticdoublemonthlyPayment(doubleloan,int
numberOfYears,doubleannuallnterestRate)
Findingthecorrespondinguppercaselettergivenalowercaseletter,
publicstaticchargetUpperCase(charletter)
8.
Line2:methodiisnotdefinedcorrectly.Itdoesnothaveareturntypeorvoid.
Line2:typeintshouldbedeclaredforparameterm.
Line8:parametertypefornshouldbedoubletomatchxMethod(3.4).
Line11:if(n<0)shouldberemovedinxMethod,otherwisetheacompilation
errorisreported.
9.
publicclassTest{
publicstaticdoublexMethod(doublei,doublej){
while(i<j){
j-;
}
returnj;
}
}
10.Youpassactualparametersbypassingtherighttypeofvalueintherightorder.Theactual
parametercanhavethesamenameasitsformalparameter.
11."Passbyvalue"istopassacopyofthevaluetothemethod.
(A)Theoutputoftheprogramis0,becausethevariablemaxisnotchangedby
invokingthemethodmax.
(B)Beforethecall,variabletimesis3
n=3
WelcometoJava!
n=2
WelcometoJava!
n=1
WelcometoJava!
Afterthecall,variabletimesis3
(C)
2
24
248
24816
2481632
248163264
①)
1
21
21
421
iis5
12.
Justbeforemaxis
invoked.
Spacerequiredforthe
mainmethod
max:0
Justenteringmax.
Spacerequiredforthe
maxmethod
max:0value2:2valuel:lJustbeforemaxis
returned
Spacerequiredforthe
mainmethod
max:0
Spacerequiredforthe
maxmethod
max:2value2:2valuel:ISpacerequiredforthe
mainmethod
max:OSpacerequiredforthe
mainmethod
max:0
Rightaftermaxis
returned
13.Twomethodswiththesamename,definedinthesameclass,iscalledmethodoverloading.It
isfinetohavesamemethodname,butdifferentparametertypes.Youcannotoverloadmethods
basedonreturntype,ormodifiers.
14.Methodspublicstaticvoidmethod(intx)andpublicstaticintmethod(inty)havethesame
signaturemethod(int).
15.Line8:intn=1iswrongsincenisalreadydeclaredinthemethodsignature.
16.True
17.
(a)34+(int)(Math.random()*(55-34))
(b)(int)(Math.random()*1000)
(c)5.5+(Math.random()*(55.5-5.5))
(d)(char)(H+(Math.random()*(N-'a,+1))
18.
Math.sqrt(4)=2.0
Math.sin(2*Math.PI)=0
Math.cos(2*Math.PI)=1
Math.pow(2,2)=4.0
Math.log(Math.E)=1
Math.exp(l)=2.718
Math.max(2,Math.min(3,4))=3
Math.rint(-2.5)=-2.0
Math.ceil(-2.5)=-2.0
Math.floor(-2.5)=-3.0
Math.round(-2.5f)=-2
Math.round(-2.5)=-2
Math.rint(2.5)=2.0
Math.ceil(2.5)=3.0
Math.floor(2.5)=2.0
Math.round(2.5f)=3
Math.round(-2.5)=-2
Math.round(Math.abs(-2.5))=3
19.Threebenefits:(1)toavoidnamingconflicts.(2)todistributesoftwareconveniently.
(3)Toprotectclasses.
20.Thesourcecode.javafileshouldbestoredinanyDir\java\chapter4,andtheclassfilemaybe
storedinanyOtherDir\java\chapter4.The.javafileand.classmaybeinthesamedirectoryora
differentdirectory.SoanyDirandanyOtherDirmaybesameordifferent.Tomaketheclass
available,addanyOtherDirintheclassspathusingthecommand
setclasspath=%classpath%;anyOtherDir
21.TheMathclassisinthejava.langpackage.Anyclassinthejava.langpackageisautomatically
imported.Sothereisnoneedtoimportitexplicitly.
Chapter6Arrays
1.Seethesection"DeclaringandCreatingArrays."
2.Youaccessanarrayusingitsindex.
3.Nomemoryisallocatedwhenanarrayisdeclared.Thememoryisallocatedwhencreatingthe
array,xis60Thesizeofnumbersis30
4.Indicatetrueorfalseforthefollowingstatements:
1.Everyelementinanarrayhasthesametype.Answer:True
2.Thearraysizeisfixedafteritisdeclared.Answer:False
3.Thearraysizeisfixedafteritiscreated.Answer:True
4.Theelementinthearraymustbeofprimitivedatatype.Answer:False
5.Whichofthefollowingstatementsarevalidarraydeclarations?
inti=newint(30);Answer:Invalid
doubled[]=newdouble[30];Answer:Valid
char[]r=newchar(1..3O);Answer:Invalid
inti[]=(3,4,3,2);Answer:Invalid
floatf[]={2.3,4.5,5.6};Answer:Valid
char[]c=newchar();Answer:Invalid
6.Thearrayindextypeisintanditslowestindexis0.
7.a[2]
8.Aruntimeexceptionoccurs.
9.
Line3:thearraydeclarationiswrong.Itshouldbedoublet].Thearrayneedsto
becreatedbeforeitsbeenused.e.g.newdouble[10]
Line5:Thesemicolon(;)attheendoftheforloopheadingshouldberemoved.
Line5:r.length()shouldber.length.
Line6:randomshouldberandom()
Line6:r(i)shouldber[i].
10.System.arraycopy(source,0,t,0,source.length);
11.ThesecondassignmentstatementmyList=newint[20]createsanewarrayand
assignsitsreferencetomyList.
myListnewint[10]Array
myListnewint[10]Array
newint[20]Array
12.False.Whenanarrayispassedtoamethod,thereferencevalueofthearrayispassed.No
newarrayiscreated.Bothargumentandparameterpointtothesamearray.
13.numbersis0andnumbers[0]is3
14.
Spacerequiredforthe
displayArraymethod
char[]chars:re
A)ESpacerequiredforthe
mainmethod
char[]chars:ref
Heap
Arrayof100
characters
Spacerequiredforthe
createArraymethod
char[]chars:ref
(B)
Spacerequiredforthe
mainmethod
char[]chars:refHeapArrayof100
characters
StackStack
C)ESpacerequiredforthe
mainmethod
char[]chars:ref
Heap
Arrayof100
charactersf
(D)
Spacerequiredforthe
mainmethod
char[]chars:refHeapArrayof100
characters
StackStack
E)ESpacereqidredforthe
mainmethod
int[]counts:ref
char[]chars:ref
Heap
Arrayof100
characters
Spacerequiredforthe
countLettersmethod
int[]counts:ref
char[]chars:ref
(F)
Spacerequiredforthe
mainmethod
int[]counts:refchar[]chars:refHeapArrayof100
characters
StackStack
Arrayof26
integers
Arrayof26
integers
G)ESpacerequiredforthe
mainmethod
int[]counts:ref
char[]chars:ref
Heap
Arrayof100
characters
Spacerequiredforthe
displaycounts
method
int[]counts:ref
(H)
Spacerequiredforthe
mainmethod
int[]counts:refchar[]chars:refHeapArrayof100
characters
StackStack
Arrayof26
integers
Arrayof26
integers
15.Onlyonevariable-lengthparametermaybespecifiedinamethodandthisparametermustbe
thelastparameter.Themethodreturntypecannotbeavariable-lengthparameter.
16.Thelastone
printMax(newint[]{l,2,3});
isincorrect,becausethearraymustofthedoublet]
type.
17.Omitted
18.Omitted
19.Omitted
20Simplychange(currentMax<list[j])onLine10to
(currentMax>list[j])
21Simplychangelist[k]>currentElementonLine9to
list[k]<currentElement
22.Toapplyjava.util.Arrays.binarySearch(array,key),thearraymustbesortedinincreasingorder.
23.Youcansortanarrayofanyprimitivetypesexceptboolean.Thesortmethodisvoid,soit
doesnotreturnanewarray.
24.
Line1:listis[2,4,7,10}
Line2:listis{7,7,7,7}
Line3:listis{7,8,8,7}
Line4:listis{7,8,8,7}
25int[][]m=newint⑷⑸;
26Yes.Theyareraggedarray.
27array[0][l]is2.
28.
r=newint[2];
int[][]Answer:Invalid
=newint[];
int[]xAnswer:Invalid
int[][]y=newint[3][];Answer:Valid
Chapter7ObjectsandClasses
1.Seethesection"DeclaringandCreatingObjects."
2.Constructorsarespecialkindsofmethodsthatarecalledwhencreatinganobjectusingthe
newoperator.Constructorsdonothaveareturntype—notevenvoid.
3.Anarrayisanobject.Thedefaultvaluefortheelementsofanarrayis0fornumeric,falsefor
boolean,'XuOGOO'forchar;nullforobjectelementtype.
4.
(a)ThereissuchconstructorShowErrors(int)intheShowErrorsclass.
TheShowErrorsclassinthebookhasadefaultconstructor.Itisactuallysameas
publicclassShowErrors{
publicstaticvoidmain(String[]args){
ShowErrorst=newShowErrors(5);
}
publicShowErrors(){
)
}
OnLine3,newShowErrors(5)attemptstocreateaninstanceusingaconstructorShowErrors(int),
buttheShowErrorsclassdoesnothavesuchaconstructor.Thatisanerror.
(b)x()isnotamethodintheShowErrorsclass.TheShowErrorsclassinthebookhasadefault
constructor.Itisactuallysameas
publicclassShowErrors{
publicstaticvoidmain(String[]args){
ShowErrorst=newShowErrors();
t.x();
)
publicShowErrors(){
)
)
OnLine4,t.x()isinvoked,buttheShowErrorsclassdoesnothavethemethodnamedx().Thatis
anerror.
(c)Theprogramcompilesfine,butithasaruntimeerrorbecausevariablecisnullwhenthe
printinstatementisexecuted.
(d)newC(5.0)doesnotmatchanyconstructorsinclassC.Theprogramhasacompilationerror
becauseclassCdoesnothaveaconstructorwithadoubleargument.
5.TheprogramdoesnotcompilebecausenewA()isusedinclassTest,butclassAdoesnothave
adefaultconstructor.SeethesecondNOTEintheSection,^Constructors/
6.false
7.UsetheDate'sno-argconstructortocreateaDateforthecurrenttime.UsetheDate'stoString()
methodtodisplayastringrepresentationfortheDate.
8.UsetheJFrame'sno-argconstructortocreateJFrame.UsethesetTitle(String)methodaseta
titleandusethesetVisible(true)methodtodisplaytheframe.
9.Dateisinjava.util.JFrameandJOptionPaneareinjavax.swing.SystemandMatharein
java.lang.
10.
System.out.println(f.i);Answer:Correct
System.out.println(f.s);Answer:Correct
f.imethod();Answer:Correct
f.smethod();Answer:Correct
System.out.println(Foo.i);Answer:Incorrect
System.out.println(Foo.s);Answer:Correct
Foo.imethod();Answer:Incorrect
Foo.smethod();Answer:Correct
11.Addstaticinthemainmethodandinthefactorialmethodbecausethesetwomethodsdon't
needreferenceanyinstanceobjectsorinvokeanyinstancemethodsintheTestclass.
12.Youcannotinvokeaninstancemethodorreferenceaninstancevariablefromastaticmethod.
Youcaninvokeastaticmethodorreferenceastaticvariablefromaninstancemethod?cisan
instancevariable,whichcannotbeaccessedfromthestaticcontextinmethod2.
13.Accessormethodisforretrievingprivatedatavalueandmutatormethodisforchanging
privatedatavalue.ThenamingconventionforaccessormethodisgetDataFieldName()for
non-booleanvaluesandisDataFieldName()forbooleanvalues.Thenamingconventionfor
mutatormethodissetDataFieldName(value).
14.Twobenefits:(1)forprotectingdataand(2)foreasytomaintaintheclass.
15.Yes.Thoughradiusisprivate,myCircle.radiusisusedinsidetheCircleclass.Thus,itisfine.
16.No.Itmustalsocontainnogetmethodsthatwouldreturnareferencetoamutabledatafield
object.
17.Yes.
18.Javauses“passbyvalue“topassparameterstoamethod.Whenpassingavariableofa
primitivetypetoamethod,thevariableremainsunchangedafterthemethodfinishes.However,
whenpassingavariableofareferencetypetoamethod,anychangestotheobjectreferencedby
thevariableinsidethemethodarepermanentchangestotheobjectreferencedbythevariable
outsideofthemethod.Boththeactualparameterandtheformalparametervariablesreference
tothesameobject.
Theoutputoftheprogramisasfollows:count101times0
19.
Remark:Thereferencevalueofcirclelispassedtoxandthereferencevalueofcircle?ispassed
toy.Thecontentsoftheobjectsarenotswappedintheswaplmethod,circlelandcircle?are
notswapped.Toactuallyswapthecontentsoftheseobjects,replacethefollowingthreelines
Circletemp=x;
x=y;
y=temp;
by
doubletemp=x.radius;
x.radius=y.radius;
y.radius=temp;
asinswap2.
20.
a.a[0]=1a[l]=2
b.a[0]=2a[l]=l
c.el=2e2=1
d.tl/si=2tl/sj=l
t2/si=2t2/sj=l
21.i+jis23(becausei(valueof2)isconcatenatedwithstringj+jis,thenj(valueof3)is
concatenatedwithstringi+jis2.)kis2jis0
22.Seethesectiononthethiskeyword.Thevalueofparameterpisassignedtoparameterpin
Line5.Itshouldbethis.p=p;
23.(Line4printsnullsincedates[0]isnull.Line5causesaNullPointerExceptionsinceitinvokes
toString()methodfromthenullreference.)
24.No.TheLoanclasshasthegetLoanDate()methodthatreturnsloanDate.loanDateisanobject
oftheDateclass.SinceDateismutable,thecontentsofloanDatecanbechanged.So,theLoan
classisnotimmutable.
25.TheStackOfIntegerclassisimmutable,becausethecontentsofastackcanbechanged
throughthepopandpushmethods.
Chapter8StringsandTextI/O
1.
si==s2=>true
s2==s3=>false
sl.equals(s2)=>true
s2.equals(s3)=>true
pareTo(s2)=>0
pareTo(s3)=>0
si==s4=>true
sl.charAt(O)=>W
sl.indexOf('j')=>-1
sl.indexOf("to")=>8
sl.lastlndexOf('a')=>14
sl.lastlndexOf("o",15)=>9
sl.length()=>16
sl.substring(5)=>metoJava!
sl.substring(5,11)=>meto
sl.startsWith("Wel")=>true
sl.endsWith("Java")=>true
sl.toLowerCase()=>welcometojava!
sl.toUpperCase()=>WELCOMETOJAVA!
"Welcome".trim()=>Welcome
sl.replace('o',T)=>WelcTmetTJava!
sl.replaceAII("o","T")=>WelcTmetTJava!
sl.replaceFirst("o"z"T")=>WelcTmetTJava!
sl.toCharArray()returnsanarrayofcharactersconsistingofW,e,I,c,o,m,e,,t,o,,J,a,v,a
(Notethatnoneoftheoperationcausethecontentsofastringtochange)
2.
Strings=newString("newstring");Answer:Correct
Strings3=si+s2;Answer:Correct
Strings3=si-s2;Answer:Incorrect
si==s2Answer:Correct
si>=s2Answer:Incorrect
pareTo(s2);Answer:Correct
inti
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 江苏省扬州市2024-2025学年高三上学期期末语文试题(原卷版+解析版)
- 美容美发行业数字化门店管理与服务系统建设方案
- 食品药品安全监管与管理作业指导书
- 电力行业智能电网与用电监测系统方案
- 本科毕业论文完整范文(满足查重要求)汽车发动机、底盘传动系统、启动系统、制动系统的常见故障诊断与维修
- 本科毕业论文完整范文(满足查重要求)共享经济背景下消费者权益的法律保护
- 2024年学年九年级语文上册 第二单元 爱情如歌 第7课《致橡树》教学实录1 沪教版五四制
- 4平平安安回家来 教学设计-2024-2025学年道德与法治一年级上册统编版
- 职场新人成功秘诀与教育培训需求分析报告
- DB3713-T 256-2022 高油酸花生高产栽培技术规程
- 农村宅基地买卖合同的标准版该如何写5篇
- 2025山西国际能源集团社会招聘258人笔试参考题库附带答案详解
- 普华永道中天会计师事务所-人工智能机遇在汽车领域
- 2025年安徽中医药高等专科学校单招职业适应性测试题库及参考答案
- 湖北省武汉市2024-2025学年高三2月调研考试英语试题含答案
- 2025年浙江省现场流行病学调查职业技能竞赛理论参考试指导题库(含答案)
- 2025年皖西卫生职业学院单招职业适应性测试题库新版
- GB/T 45222-2025食品安全事故应急演练要求
- 深静脉的穿刺术课件
- 2025年湖南高速铁路职业技术学院单招职业倾向性测试题库附答案
- 腰椎穿刺的护理
评论
0/150
提交评论