Tải bản đầy đủ - 0 (trang)
Appendix A. Quick Reference to Java

Appendix A. Quick Reference to Java

Tải bản đầy đủ - 0trang

AppendixA.QuickReferencetoJava

A.1



VARIABLES



A.2



METHODDECLARATIONS



A.3



LOOPS



A.4



CONDITIONALS



A.5



OPERATORS



A.6



STRINGESCAPES



A.7



CLASSES



A.8



FIELDS



A.9



CONSTRUCTORS



A.10 PACKAGES



[Page543(continued)]



A.1.Variables

Variablesallowustoassociatenameswithvalues.InJavayou

mustdeclareavariablebeforeyouuseit.Todeclareavariable

youspecifyatypeandanamefollowedbyasemicolon.

typename;



Youcanalsosetthevalueofthevariablewhenyoudeclareitto

theresultofanexpression.

typename=expression;



Thetypecanbeanyoftheprimitivetypes(int,boolean,byte,

char,double,float,long,short),aclassname,oraninterface

name.Theconventionistostartvariablenameswitha

lowercaseletteranduppercasethefirstletterofeachadditional

word.

>inti;

>doubletotalBill=32.43+20*32.43;

>Stringname="MarkGuzdial";

>PicturepictureObj;

>ListstudentList=null;



[Page544]

Variablenamescanbemadeupofletters,digits,underscores,



orcurrencysymbols.Theycanstartwithanyoftheseexcepta

digit.Variablescanbeanywordexceptthereservedwords.The

reservedwordsare:

abstract



assert



boolean



break



byte



case



catch



char



class



const

(unused)



continue



default



do



double



else



enum



extends



false



final



finally



float



for



goto

(unused)



if



implements



import



instanceof



int



interface



long



native



new



null



package



private



protected



public



return



short



static



strictfp



super



switch



synchronized this



throw



throws



transient



true



try



void



volatile



while











Mostofthereservedwordsarealsokeywords.Theonlyones

thatarenotkeywordsarenull,true,andfalse.AlloftheJava

reservedwordshaveonlylowercaseletters.

WecanuseSystem.out.printorSystem.out.printlntoprintthevalue

ofavariable.Thesecondonewillalsoforceanewlineafterthe

valuehasprinted.



>intx=10

>System.out.println(x);

10

>Stringname="BarbaraEricson";

>System.out.println(name);

BarbaraEricson



[Page544(continued)]



A.2.MethodDeclarations

Declareamethodbyspecifyingthevisibility,thereturntype,

themethodname,andaparameterlist.Methoddeclarations

areusuallyfollowedbycodeinsideofcurlybraceswhicharethe

statementsthatwillbeexecutedwhenthemethodisinvoked.

visibilityreturnTypename(parameterList)

{

//statementsinthemethod

}



Theparameterlistisacomma-separatedlistoftheparameters

thatwillbepassedtothemethod.Foreachparameter,specifya

typeandaname.Parametersarepassedbyvalue,which

meansthatacopyofthevalueispassedtothemethod.So

primitivevariablespassedtoamethodwillnotbeaffectedby

changesinthemethodafterthereturnfromthemethod,but

becausethevalueofanobjectvariableisareferencetothe

object,amethodcanchangethepassedobject,andsuch

changesarepreservedafterthereturnfromthemethod.



[Page545]

publicvoidchangeRedAndGreen(doubleredMult,

doublegreenMult)



Theconventionistostartamethodnamewithlowercaseletters

anduppercasethefirstletterofeachadditionalword.Amethod

canreturnavaluebyusingthereturnstatement.Thetypeof



thevaluebeingreturnedmustmatchthespecifiedreturntype.



/**

*Methodtocreateanewpicturebyrotatingthecurrent

*picturebythegivendegrees

*@paramdegreesthenumberofdegreestorotateby

*@returntheresultingpicture

*/

publicPicturerotate(intdegrees)

{

//createanewpictureobjectbigenoughtoholdtheresult

//nomatterwhattherotationis

Pictureresult=newPicture((int)(Math.ceil(rect.getWidth()

(int)(Math.ceil(rect.getHeight(

//otherstatementsinthemethod

returnresult;

}



Ifamethoddoesn'treturnanyvalue,thereturntypeshouldbe

void.

/**

*Methodtodecreasethegreeninthepictureby30%

*/

publicvoiddecreaseGreen()

{

//methodstatements

}



Ifyouwantallotherclassestobeabletoinvokeamethod,

makethevisibilityofthemethodpublic.Ifyouonlywanttouse



amethodintheclassitisdeclaredin,thenuseprivateasthe

visibility.Ifyouleaveoffthevisibility,thenthemethodcanbe

invokedbyallclassesinthesamepackage.Thisiscalled

packagevisibility.Youcanalsouseprotectedvisibilityifyou

wantsubclassestobeabletooverrideaninheritedmethod,but

beawarethatallclassesinthesamepackagealsohaveaccess

tothemethod.







[Page546]



A.3.Loops

IfyouareusingJava5.0(1.5)youcanuseafor-eachloop.The

syntaxforafor-eachloopis:

for(typename:collection)

{

//statementstoexecute

}



Thetypeisthetypeofobjectsinthecollection.Thenameisthe

localvariablenametouse.Thecollectionisanythingthatholds

acollectionofobjects,suchasanarray,list,orset.The

followingisanexampleofusingafor-eachloop:

//loopthroughallthesamplesinthearray

for(SoundSamplesample:sampleArray)

{

value=sample.getValue();

sample.setValue(value*2);

}



Ifyouknowhowmanytimesaloopshouldrepeat,thenusea

forloop.Thesyntaxforaforloopis:

for(initializationArea;continuationTest;changeArea)

{

//statementsintheforloop

}



Youcandeclareandinitializelocalvariablesintheinitialization

area.Youspecifyabooleanexpressionforthecontinuationtest.

Theloopwillcontinuewhilethetestistrue.Thechangeareais

whereyouspecifyhowtochangevariablesaftereachexecution

oftheloop.

//loopthroughallthepixels

for(inti=0;i
pixelArray[i].setBlue(0);



Ifyoudon'tknowhowmanytimesaloopshouldrepeat,then

useawhileloop.Thesyntaxofawhileloopis:

while(continuationTest)

{

//statementsinthewhileloop

}



Thestatementsinthecurlybraceswillbeexecutedaslongas

thecontinuationtestistrue.Oftenyouwillinitializevariables

beforethewhileloopbeginsandchangethemjustbeforethe

endofthewhileloopstatements.Butyoucandothisinthe

continuationtest.



[Page547]

//Loopwhilethereismoredata

while((line=reader.readLine())!=null)

{

//printthecurrentline

System.out.println(line);



}



[Page547(continued)]



A.4.Conditionals

Aniftakesanexpressionandevaluatesit.Ifit'strue,theif's

blockisexecuted.Ifit'sfalse,theelseblockisexecuted,ifone

exists.Ifyouhavemorethantwopossibilities,youcanaddelse

ifforeachadditionalone.

//tinttheshadowsdarker

if(redValue<60)

{

redValue=redValue*0.9;

greenValue=greenValue*0.9;

blueValue=blueValue*0.9;

}

//tintthemidtonesalightbrown

//byreducingtheblue

elseif(redValue<190)

{

blueValue=blueValue*0.8;

}

//tintthehighlightsalightyellow

//byreducingtheblue

else

{

blueValue=blueValue*0.9;

}



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Appendix A. Quick Reference to Java

Tải bản đầy đủ ngay(0 tr)

×