strings and arrays - computer sciencekmp/comp401fall17/lectures/comp401-fall...strings and arrays...
TRANSCRIPT
Insideamethod• Thebodyofamethodisasequenceofstatements.• Astatementendsinasemi-colon
– Typesofstatements:• VariabledeclaraIon• Assignment• CondiIonal• Loop• Methodcall• Returnstatement
• Blocks– Zeroormorestatementsenclosedincurlybraces{}– Allowedanywhereasinglestatementisallowed.
• Andviceversa
CallingMethods• Callingaclassmethoddefinedinthesameclass:
methodName(parameters);• Callingaclassmethoddefinedinadifferentclass(samepackage):
ClassName.methodName(parameters);
• Callingaclassmethoddefinedinadifferentpackage:PackageName.ClassName.methodName(parameters)
• Intheabove“parameters”isacommaseparatedlistofvalues.– Mustmatchinnumberandtypeaccordingtomethod’ssignature.
• Amethodcallthatreturnsavalue(i.e.,nota“void”method)canbepartofanexpression.int max_times_min = max(a, b, c) * min(a, b, c);
Insideamethod• Thebodyofamethodisasequenceofstatements.• Astatementendsinasemi-colon
– Typesofstatements:• VariabledeclaraIon• Assignment• CondiIonal• Loop• Methodcall• Returnstatement
• Blocks– Zeroormorestatementsenclosedincurlybraces{}– Allowedanywhereasinglestatementisallowed.
• Andviceversa
Return
• Syntax:return expression;
• EndsexecuIonofamethodandreturnsthevalueoftheexpressionastheresultofthemethod.– Mustmatchtypedeclaredinmethodsignature.– Ifmethodreturntypeis“void”,thensimply:
return;
lec02.ex5.Example5
• Callingmethods• Compoundexpressionsaspartofmethodcalltoprovideparametervalue.
• Returningfrommiddleofmethod– Generally,trytoavoid.
• Unreachablecodeerror• Callingmethodinsame/differentclass,same/differentpackage– lec02.ex5.Example5Other
ImportDirecIve
• Mapsclassnamesfromotherpackagesintocurrentnamespace.– Convenientifgoingtouseoneormoreclassnamesrepeatedly.
• Mapallnamesfromapackage:import package.*;
• Mapaspecificnamefromapackage:import package.name;
String,ourfirstobject• InJava,astringisanimmutablesequenceofcharacters.
– Stringsareobjects.• Objectshaveatype.
– Thenameoftheclassthatdefinesthem.– Example:String
• Objectshavemethods– Dereferencedusingthe“.”operator– Example:String s = “This is a string”;int length = s.length();
• Objectshavefields– ProperIesthatcanbedirectlyaccessedasvalues.– Accessedviathe“.”operatorlikemethodsreference.field
CreaIngStrings
• Asaliteral.– Enclosedindoublequotes.– Escapesequencesforcommonnon-printableoruntypeablecharacters.• \”,\\,\t,\n,\u####
• Usingthe“new”operator.– Generallyalmostneverneedtodothis.
• AstheresultofastringconcatenaIonoperator• Lecture4,Example1
UsefulStringmethods
• length()• charAt()• equals()• substring()• trim()• indexOf()• Lecture4,Example2
Stringsareimmutable• Oncecreated,can’tchange.– Someotherlanguagestreatstringsasanarrayofcharacters.NotJava.
• AnyoperaIonthatmanipulatesastringiscreaInganewstring.
• Whyimmutability?– Ifthesamestringoccurstwice,cansimplyreusethesameobject.• ThisisanopImizaIonthatJavaperformsautomaIcallyifitcan.• Itmayappearthat==canbeusedtotestcharacter-by-characterequality,butyoushouldneverdothat.– Alwaysuse.equals()methodofonestring,passingtheotherastheparameter.
• Lecture4,Example3
Arrays• Arraysholdanindexedsequenceofvalues
– Indicesstartat0• Anotherobjecttype…withatwist
– Alimledifferentbecauseitisatypethatcombineswithanothertype.• ThearraystructureitselfisoftypeArray,butthetypeoftheindividualelementsmustalsobespecified.– Can’thaveanarrayofdifferenttypesmixedtogether.
– AlsodifferentfromotherobjectsinitscreaIonsyntax.• Arraysarefixedlength.
– Mustbespecifiedwhencreated.– Oncecreated,cannotberesized.
CreaIng/IniIalizingArrays• Typeindicatorforanarrayisthetypenameoftheindividualelementsfollowedby[]
• Usingthenewoperatortype[] vname = new type[length];– Arraywillbecreated,andiniIalizedwithdefaultvalues.
• Fornumerictypesandchar:0• Forboolean:false• Forreferencetypes:null
• Example:String[] names = new String[3];names[0] = “Alice”;names[1] = “Bob”;names[2] = “Carol”;
LiteralArrays• Whenyouknowtheelementsinadvance.– Comma-separated,incurlybraces
• SyntaxifcombinedwithvariabledeclaraIonint[] iarray = {1, 2, 3};String[] names = {“Abhinandan”, “Bhagavateeprasaad”, “Chaanakya”};
• SyntaxifusedtosetanexisIngvariable.iarray = new int[] {4, 5, 6};
IndexingArrays
• 0-basedindexing• Lengthisprovidedbylengthfield– Note,forStringobjects,length()wasamethod– Here,lengthisafield
• Sizeofarraycannotchangeoncecreated,butindividualelementsmaychange.
• Lecture4,Example4
null
• Specialvaluethatisalwaysvalidforanyreferencetype.– Indicates“novalue”– Anyreferencetypevariablecanbesettonull.– Defaultvalueforreferencetypearrays.
ArraysasReferenceTypes
• Samereference,samearray– ImplicaIonforarrayspassedtomethods• Whenanarrayispassedtoamethod,anychangesthatthemethodmakestoitselementsispermanent.
• Arraycloning– Easywaytocreatea“shallow”copyofanarray– Justcallclone()method• Resultwillbeanewarrayofsamesizewithsamevaluesorreferences
• Lecture4,Example5
MulIdimensionalArrays• MulIdimensionalarrayissimplyanarrayofarrays
– Filloutdimensionsleqtoright.int[][] marray = new int[5][];for(int i=0; i<5; i++) {
marray[i] = new int[10];}
• Eachsubarraycanhaveanindependentsize.– SomeImesknownasasa“ragged”or“uneven”arrayint[][] marray = new int[5][];for (int i=0; i<5; i++) {
marray[i] = new int[i+1];}
• Ifeachsub-dimensionissamesize,wecancreateitwithasinglenewstatementint[][] marray = new int[5][10];
ArraysuIlityclass
• ArraysisalibraryofusefulfuncIonsformanipulaIngarrays– Note“s”inArrays– LikeMathclass,allmethodsarestaIc
• binarySearch• sort• fillingandcopyingsubranges• hmp://docs.oracle.com/javase/8/docs/api/java/uIl/Arrays.html
Lecture4,Example6• Usesscannertoreadinput.• ExpectsinputtobeanumberindicaIngasizeandthenoneofthefollowingwords:– integer,real,string
• Createsanarrayofthatsizeofthecorrespondingtype(i.e.,int,double,orString)
• Usesalooptoreadinthatmanyoftheappropriatetypeintothearray.
• Printsthearray.• Doesitalloveragainindefinitely.