Top Banner
Strings and Arrays COMP 401, Fall 2017 Lecture 4
21

Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Apr 10, 2018

Download

Documents

vucong
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

StringsandArrays

COMP401,Fall2017Lecture4

Page 2: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Insideamethod•  Thebodyofamethodisasequenceofstatements.•  Astatementendsinasemi-colon

–  Typesofstatements:•  VariabledeclaraIon•  Assignment•  CondiIonal•  Loop•  Methodcall•  Returnstatement

•  Blocks–  Zeroormorestatementsenclosedincurlybraces{}–  Allowedanywhereasinglestatementisallowed.

•  Andviceversa

Page 3: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

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);

Page 4: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Insideamethod•  Thebodyofamethodisasequenceofstatements.•  Astatementendsinasemi-colon

–  Typesofstatements:•  VariabledeclaraIon•  Assignment•  CondiIonal•  Loop•  Methodcall•  Returnstatement

•  Blocks–  Zeroormorestatementsenclosedincurlybraces{}–  Allowedanywhereasinglestatementisallowed.

•  Andviceversa

Page 5: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Return

•  Syntax:return expression;

•  EndsexecuIonofamethodandreturnsthevalueoftheexpressionastheresultofthemethod.– Mustmatchtypedeclaredinmethodsignature.–  Ifmethodreturntypeis“void”,thensimply:

return;

Page 6: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

lec02.ex5.Example5

•  Callingmethods•  Compoundexpressionsaspartofmethodcalltoprovideparametervalue.

•  Returningfrommiddleofmethod– Generally,trytoavoid.

•  Unreachablecodeerror•  Callingmethodinsame/differentclass,same/differentpackage–  lec02.ex5.Example5Other

Page 7: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

ImportDirecIve

•  Mapsclassnamesfromotherpackagesintocurrentnamespace.– Convenientifgoingtouseoneormoreclassnamesrepeatedly.

•  Mapallnamesfromapackage:import package.*;

•  Mapaspecificnamefromapackage:import package.name;

Page 8: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Example5OtherRevisited

•  import•  Mathrevisited– Classesinjava.langpackageareautomaIcallyimported.

Page 9: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

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

Page 10: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

CreaIngStrings

•  Asaliteral.–  Enclosedindoublequotes.–  Escapesequencesforcommonnon-printableoruntypeablecharacters.•  \”,\\,\t,\n,\u####

•  Usingthe“new”operator.– Generallyalmostneverneedtodothis.

•  AstheresultofastringconcatenaIonoperator•  Lecture4,Example1

Page 11: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

UsefulStringmethods

•  length()•  charAt()•  equals()•  substring()•  trim()•  indexOf()•  Lecture4,Example2

Page 12: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Stringsareimmutable•  Oncecreated,can’tchange.–  Someotherlanguagestreatstringsasanarrayofcharacters.NotJava.

•  AnyoperaIonthatmanipulatesastringiscreaInganewstring.

•  Whyimmutability?–  Ifthesamestringoccurstwice,cansimplyreusethesameobject.•  ThisisanopImizaIonthatJavaperformsautomaIcallyifitcan.•  Itmayappearthat==canbeusedtotestcharacter-by-characterequality,butyoushouldneverdothat.–  Alwaysuse.equals()methodofonestring,passingtheotherastheparameter.

•  Lecture4,Example3

Page 13: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Arrays•  Arraysholdanindexedsequenceofvalues

–  Indicesstartat0•  Anotherobjecttype…withatwist

–  Alimledifferentbecauseitisatypethatcombineswithanothertype.•  ThearraystructureitselfisoftypeArray,butthetypeoftheindividualelementsmustalsobespecified.–  Can’thaveanarrayofdifferenttypesmixedtogether.

–  AlsodifferentfromotherobjectsinitscreaIonsyntax.•  Arraysarefixedlength.

– Mustbespecifiedwhencreated.–  Oncecreated,cannotberesized.

Page 14: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

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”;

Page 15: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

LiteralArrays•  Whenyouknowtheelementsinadvance.– Comma-separated,incurlybraces

•  SyntaxifcombinedwithvariabledeclaraIonint[] iarray = {1, 2, 3};String[] names = {“Abhinandan”, “Bhagavateeprasaad”, “Chaanakya”};

•  SyntaxifusedtosetanexisIngvariable.iarray = new int[] {4, 5, 6};

Page 16: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

IndexingArrays

•  0-basedindexing•  Lengthisprovidedbylengthfield– Note,forStringobjects,length()wasamethod– Here,lengthisafield

•  Sizeofarraycannotchangeoncecreated,butindividualelementsmaychange.

•  Lecture4,Example4

Page 17: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

null

•  Specialvaluethatisalwaysvalidforanyreferencetype.–  Indicates“novalue”– Anyreferencetypevariablecanbesettonull.– Defaultvalueforreferencetypearrays.

Page 18: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

ArraysasReferenceTypes

•  Samereference,samearray–  ImplicaIonforarrayspassedtomethods• Whenanarrayispassedtoamethod,anychangesthatthemethodmakestoitselementsispermanent.

•  Arraycloning– Easywaytocreatea“shallow”copyofanarray–  Justcallclone()method•  Resultwillbeanewarrayofsamesizewithsamevaluesorreferences

•  Lecture4,Example5

Page 19: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

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];

Page 20: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

ArraysuIlityclass

•  ArraysisalibraryofusefulfuncIonsformanipulaIngarrays– Note“s”inArrays– LikeMathclass,allmethodsarestaIc

•  binarySearch•  sort•  fillingandcopyingsubranges•  hmp://docs.oracle.com/javase/8/docs/api/java/uIl/Arrays.html

Page 21: Strings and Arrays - Computer Sciencekmp/comp401fall17/lectures/comp401-fall...Strings and Arrays COMP 401, Fall 2017 Lecture 4 Inside a method • The body of a method is a sequence

Lecture4,Example6•  Usesscannertoreadinput.•  ExpectsinputtobeanumberindicaIngasizeandthenoneofthefollowingwords:–  integer,real,string

•  Createsanarrayofthatsizeofthecorrespondingtype(i.e.,int,double,orString)

•  Usesalooptoreadinthatmanyoftheappropriatetypeintothearray.

•  Printsthearray.•  Doesitalloveragainindefinitely.