java basics, cont’d strings and arrays - welcome to...

31
Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Upload: lybao

Post on 10-Apr-2018

238 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

JavaBasics,cont’dStringsandArrays

COMP401,Spring2016Lecture41/21/2016

Page 2: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

lec02.ex3.Example3

•  ifandswitchdemo•  Variablesscopedwithinblock•  Stylehint:– Don’ttestbooleanexpressionagainsttrue/false

•  TesQngrealnumberswithepsilonbounds

Page 3: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Insideamethod•  Thebodyofamethodisasequenceofstatements.•  Astatementendsinasemi-colon–  Typesofstatements:

•  VariabledeclaraQon•  Assignment•  CondiQonal•  Loop•  Methodcall•  Returnstatement

•  Blocks–  Zeroormorestatementsenclosedincurlybraces{}–  Allowedanywhereasinglestatementisallowed.

•  Andviceversa

Page 4: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Loops:while

while (expression) {block

}

do {block

} while (expression);

Page 5: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

whileexampleint sum = 0;int n = 1;while (n < 11) { sum += n; n++;}System.out.println(“The sum of 1 to 10 is: “ + sum);

Page 6: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Loops:for

for (init; test; update) {block

}

Page 7: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

forexampleint sum = 0;for(int n=1; n<11; n++) { sum += n;}System.out.println(“The sum of 1 to 10 is: “ + sum);

•  Notethatvariablenisdeclaredaspartofinitexpressioninforloop.–  Thisisacommonprogrammingidiomifloopvariableisonlyneededfortheloop.

–  Scopeofvariableislimitedtotheloopblock.

Page 8: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Loopoddsandends

•  ToskiptonextiteraQonofloopbodyuse“conQnue”statement.

•  Tobreakoutoftheloopbodyuse“break”statement.

Page 9: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

lec02.ex4.Example4

•  whileandfor•  whileandforequivalence•  scopeofforloopvariable•  break/conQnue

Page 10: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Insideamethod•  Thebodyofamethodisasequenceofstatements.•  Astatementendsinasemi-colon–  Typesofstatements:

•  VariabledeclaraQon•  Assignment•  CondiQonal•  Loop•  Methodcall•  Returnstatement

•  Blocks–  Zeroormorestatementsenclosedincurlybraces{}–  Allowedanywhereasinglestatementisallowed.

•  Andviceversa

Page 11: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

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 12: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Insideamethod•  Thebodyofamethodisasequenceofstatements.•  Astatementendsinasemi-colon–  Typesofstatements:

•  VariabledeclaraQon•  Assignment•  CondiQonal•  Loop•  Methodcall•  Returnstatement

•  Blocks–  Zeroormorestatementsenclosedincurlybraces{}–  Allowedanywhereasinglestatementisallowed.

•  Andviceversa

Page 13: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Return

•  Syntax:return expression;

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

return;

Page 14: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

lec02.ex5.Example5

•  Callingmethods•  Compoundexpressionsaspartofmethodcalltoprovideparametervalue.

•  Returningfrommiddleofmethod– Generally,trytoavoid.

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

Page 15: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

ImportDirecQve

•  Mapsclassnamesfromotherpackagesintocurrentnamespace.– Convenientifgoingtouseoneormoreclassnamesrepeatedly.

•  Mapallnamesfromapackage:import package.*;

•  Mapaspecificnamefromapackage:import package.name;

Page 16: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Example5OtherRevisited

•  import•  Mathrevisited– Classesinjava.langpackageareautomaQcallyimported.

Page 17: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

String,ourfirstobject•  InJava,astringisanimmutablesequenceofcharacters.

–  Stringsareobjects.•  Objectshaveatype.

–  Thenameoftheclassthatdefinesthem.–  Example:String

•  Objectshavemethods–  Dereferencedusingthe“.”operator–  Example:String s = “This is a string”;int length = s.length();

•  Objectshavefields–  ProperQesthatcanbedirectlyaccessedasvalues.–  Accessedviathe“.”operatorlikemethodsreference.field

Page 18: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

CreaQngStrings

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

•  Usingthe“new”operator.– Generallyalmostneverneedtodothis.

•  AstheresultofastringconcatenaQonoperator•  Lecture4,Example1

Page 19: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

UsefulStringmethods

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

Page 20: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

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

•  AnyoperaQonthatmanipulatesastringiscreaQnganewstring.

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

•  Lecture4,Example3

Page 21: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Arrays•  Arraysholdanindexedsequenceofvalues–  Indicesstartat0

•  Anotherobjecttype…withatwist–  Alilledifferentbecauseitisatypethatcombineswithanothertype.•  ThearraystructureitselfisoftypeArray,butthetypeoftheindividualelementsmustalsobespecified.–  Can’thaveanarrayofdifferenttypesmixedtogether.

–  AlsodifferentfromotherobjectsinitscreaQonsyntax.•  Arraysarefixedlength.– Mustbespecifiedwhencreated.–  Oncecreated,cannotberesized.

Page 22: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

CreaQng/IniQalizingArrays•  Typeindicatorforanarrayisthetypenameoftheindividualelementsfollowedby[]

•  Usingthenewoperatortype[] vname = new type[length];–  Arraywillbecreated,andiniQalizedwithdefaultvalues.

•  Fornumerictypesandchar:0•  Forboolean:false•  Forreferencetypes:null

•  Example:String[] names = new String[3];names[0] = “Alice”;names[1] = “Bob”;names[2] = “Carol”;

Page 23: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

CreaQngLiteralLists•  Whenyouknowtheelementsinadvance.– Comma-separated,incurlybraces

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

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

Page 24: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

IndexingArrays

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

•  Sizeofarraycannotchangeoncecreated,butindividualelementsmaychange.

•  Lecture4,Example4

Page 25: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

null

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

Page 26: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

ArraysasReferenceTypes

•  Samereference,samearray–  ImplicaQonforarrayspassedtomethods

• Whenanarrayispassedtoamethod,anychangesthatthemethodmakestoitselementsispermanent.

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

•  Resultwillbeanewarrayofsamesizewithsamevaluesorreferences

•  Lecture4,Example5

Page 27: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

MulQdimensionalArrays•  MulQdimensionalarrayissimplyanarrayofarrays

–  Filloutdimensionsleqtoright.int[][] marray = new int[5][];for(int i=0; i<5; i++) {

marray[i] = new int[10];}

•  Eachsubarraycanhaveanindependentsize.–  SomeQmesknownasasa“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 28: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

ArraysuQlityclass

•  ArraysisalibraryofusefulfuncQonsformanipulaQngarrays– Note“s”inArrays– LikeMathclass,allmethodsarestaQc

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

Page 29: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

Scanner•  Scannerisatypeofobjectthatcanbeusedtoparsetextinputina

varietyofways.•  TocreateaScannerobjectfortheconsolekeyboard:

java.util.Scanner s = new java.util.Scanner(System.in);

•  ScannerdocumentaQon–  hlp://docs.oracle.com/javase/8/docs/api/java/uQl/Scanner.html

•  Bydefault,treatsinputaswhitespaceseparatedtokens.•  Parsethenexttokenand…

–  returnasStringwithnext()–  interpretasinintegerwithnextInt()–  interpretasrealvaluewithnextDouble()

•  IfyouaskforaparQculartype(e.g.,int,double)butthenexttokencant’beinterpretedinthatwaysensibly,yourprogramdies.

Page 30: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

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

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

•  Usesalooptoreadinthatmanyoftheappropriatetypeintothearray.

•  Printsthearray.•  Doesitalloveragainindefinitely.

Page 31: Java Basics, cont’d Strings and Arrays - Welcome to …kmp/comp401sp16/lectures/comp401-sp16...Java Basics, cont’d Strings and Arrays COMP 401, Spring 2016 Lecture 4 1/21/2016

TurningInAssignments

•  CreateasingleJARfile.– Withsourcecode,notcompiledclasses.

•  Openbrowsertoautograder:– hlps://grade.cs.unc.edu/comp401sp16/grades.php– MUSTbeoncampusorusingVPN

•  Autograderrunsonceanhour– 12minutespast

•  Forfutureassignments,feedbackwillbehiddenunQlaqerduedate.