java basics, cont’d strings and arrays - welcome to...
TRANSCRIPT
JavaBasics,cont’dStringsandArrays
COMP401,Spring2016Lecture41/21/2016
lec02.ex3.Example3
• ifandswitchdemo• Variablesscopedwithinblock• Stylehint:– Don’ttestbooleanexpressionagainsttrue/false
• TesQngrealnumberswithepsilonbounds
Insideamethod• Thebodyofamethodisasequenceofstatements.• Astatementendsinasemi-colon– Typesofstatements:
• VariabledeclaraQon• Assignment• CondiQonal• Loop• Methodcall• Returnstatement
• Blocks– Zeroormorestatementsenclosedincurlybraces{}– Allowedanywhereasinglestatementisallowed.
• Andviceversa
Loops:while
while (expression) {block
}
do {block
} while (expression);
whileexampleint sum = 0;int n = 1;while (n < 11) { sum += n; n++;}System.out.println(“The sum of 1 to 10 is: “ + sum);
Loops:for
for (init; test; update) {block
}
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.
Loopoddsandends
• ToskiptonextiteraQonofloopbodyuse“conQnue”statement.
• Tobreakoutoftheloopbodyuse“break”statement.
lec02.ex4.Example4
• whileandfor• whileandforequivalence• scopeofforloopvariable• break/conQnue
Insideamethod• Thebodyofamethodisasequenceofstatements.• Astatementendsinasemi-colon– Typesofstatements:
• VariabledeclaraQon• Assignment• CondiQonal• 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:
• VariabledeclaraQon• Assignment• CondiQonal• Loop• Methodcall• Returnstatement
• Blocks– Zeroormorestatementsenclosedincurlybraces{}– Allowedanywhereasinglestatementisallowed.
• Andviceversa
Return
• Syntax:return expression;
• EndsexecuQonofamethodandreturnsthevalueoftheexpressionastheresultofthemethod.– Mustmatchtypedeclaredinmethodsignature.– Ifmethodreturntypeis“void”,thensimply:
return;
lec02.ex5.Example5
• Callingmethods• Compoundexpressionsaspartofmethodcalltoprovideparametervalue.
• Returningfrommiddleofmethod– Generally,trytoavoid.
• Unreachablecodeerror• Callingmethodinsame/differentclass,same/differentpackage– lec02.ex5.Example5Other
ImportDirecQve
• Mapsclassnamesfromotherpackagesintocurrentnamespace.– Convenientifgoingtouseoneormoreclassnamesrepeatedly.
• Mapallnamesfromapackage:import package.*;
• Mapaspecificnamefromapackage:import package.name;
Example5OtherRevisited
• import• Mathrevisited– Classesinjava.langpackageareautomaQcallyimported.
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
CreaQngStrings
• Asaliteral.– Enclosedindoublequotes.– Escapesequencesforcommonnon-printableoruntypeablecharacters.• \”,\\,\t,\n,\u####
• Usingthe“new”operator.– Generallyalmostneverneedtodothis.
• AstheresultofastringconcatenaQonoperator• Lecture4,Example1
UsefulStringmethods
• length()• charAt()• equals()• substring()• trim()• indexOf()• Lecture4,Example2
Stringsareimmutable• Oncecreated,can’tchange.– Someotherlanguagestreatstringsasanarrayofcharacters.NotJava.
• AnyoperaQonthatmanipulatesastringiscreaQnganewstring.
• Whyimmutability?– Ifthesamestringoccurstwice,cansimplyreusethesameobject.• ThisisanopQmizaQonthatJavaperformsautomaQcallyifitcan.• Itmayappearthat==canbeusedtotestcharacter-by-characterequality,butyoushouldneverdothat.– Alwaysuse.equals()methodofonestring,passingtheotherasatheparameter.
• Lecture4,Example3
Arrays• Arraysholdanindexedsequenceofvalues– Indicesstartat0
• Anotherobjecttype…withatwist– Alilledifferentbecauseitisatypethatcombineswithanothertype.• ThearraystructureitselfisoftypeArray,butthetypeoftheindividualelementsmustalsobespecified.– Can’thaveanarrayofdifferenttypesmixedtogether.
– AlsodifferentfromotherobjectsinitscreaQonsyntax.• Arraysarefixedlength.– Mustbespecifiedwhencreated.– Oncecreated,cannotberesized.
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”;
CreaQngLiteralLists• Whenyouknowtheelementsinadvance.– Comma-separated,incurlybraces
• SyntaxifcombinedwithvariabledeclaraQonint[] iarray = {1, 2, 3};String[] names = {“Abhinandan”, “Bhagavateeprasaad”, “Chaanakya”};
• SyntaxifusedtosetanexisQngvariable.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– ImplicaQonforarrayspassedtomethods
• Whenanarrayispassedtoamethod,anychangesthatthemethodmakestoitselementsispermanent.
• Arraycloning– Easywaytocreatea“shallow”copyofanarray– Justcallclone()method
• Resultwillbeanewarrayofsamesizewithsamevaluesorreferences
• Lecture4,Example5
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];
ArraysuQlityclass
• ArraysisalibraryofusefulfuncQonsformanipulaQngarrays– Note“s”inArrays– LikeMathclass,allmethodsarestaQc
• binarySearch• sort• fillingandcopyingsubranges• hlp://docs.oracle.com/javase/8/docs/api/java/uQl/Arrays.html
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.
Lecture4,Example6• Usesscannertoreadinput.• ExpectsinputtobeanumberindicaQngasizeandthenoneofthefollowingwords:– integer,real,string
• Createsanarrayofthatsizeofthecorrespondingtype(i.e.,int,double,orString)
• Usesalooptoreadinthatmanyoftheappropriatetypeintothearray.
• Printsthearray.• Doesitalloveragainindefinitely.
TurningInAssignments
• CreateasingleJARfile.– Withsourcecode,notcompiledclasses.
• Openbrowsertoautograder:– hlps://grade.cs.unc.edu/comp401sp16/grades.php– MUSTbeoncampusorusingVPN
• Autograderrunsonceanhour– 12minutespast
• Forfutureassignments,feedbackwillbehiddenunQlaqerduedate.