Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
2/4/16 Demo: Create application CS2110,Recita.on2 Argumentstomethodmain, Packages, WrapperClasses, Characters, Strings Java Application publicsta.cvoidmain(String[]args){…} Parameter:Stringarray AJavaprogramthathasaclasswithastaXcproceduremain,as declaredabove,iscalledanapplicaXon. Theprogram,i.e.theapplicaXon,isrunbycallingmethodmain. Eclipsehasaneasywaytodothis. Tocreateanewprojectthathasamethodcalledmainwitha bodythatcontainsthestatement System.out.println(“Hello World”); dothis: • Eclipse:File->New->Project • File->New->Class • Checkthemethodmainbox • Intheclassthatiscreated,writetheabovestatementinthe bodyofmain • HitthegreenplaybuNonordomenuitemRun->Run Method main and its parameter publicsta.cvoidmain(String[]args){…} InEclipse,whenyoudomenuitem Parameter:Stringarray Run->Run(orclickthegreenPlaybuNon) Eclipseexecutesthecallmain(arraywith0arguments); TotellEclipsewhatarrayofStringstogiveastheargument, startbyusingmenuitem Run->RunConfiguraXons… or Run->DebugConfiguraXon… (seenextslide) Window Run Configurations ThisArgumentspaneofRunConfiguraXonswindowgives argumentarrayofsize3: args[0]:“SpeciesData/a0.dat” DEMO:Givinganargumenttothecallonmain ChangetheprogramtoprinttheStringthatisinargs[0],i.e. changethestatementinthebodyto System.out.println(args[0]); args[1]:“2” args[2]:“whatfor?” ClickArgumentspane Then • DoRun->RunConfiguraXons • ClicktheArgumentstab • IntheProgramfield,typein“Haloooothere!” QuotesOK,butnotneeded Quotesneeded becauseofspacechar • ClicktherunbuNoninthelowerrighttoexecutethecallon mainwithanarrayofsize1… 1 2/4/16 Package Package:CollecXonofJavaclassesandotherpackages. SeeJavaSummary.pptx,slide20 AvailableinthecoursewebsiteinthefollowinglocaXon: hNp://www.cs.cornell.edu/courses/CS2110/2016sp/links.html Threekindsofpackages (1) Thedefaultpackage:inprojectdirectory/src PACKAGESANDTHEJAVAAPI (2) Javaclassesthatarecontainedinaspecificdirectoryonyour harddrive(itmayalsocontainsub-packages) (3) PackagesofJavaclassesthatcomewithJava, e.g.packagesjava.lang,javax.swing. APIpackagesthatcomewithJava FindingpackagedocumentaXon Visitcoursewebpage,clickLinks,thenJava8APISpecs. Link: hNp://www.cs.cornell.edu/courses/CS2110/2016sp/links.html Scrolldowninlelcol(Packagespane),clickonjava.lang Scrollthroughhere MorerealisXcally: hNp://lmgmy.com/?q=java+8+api Packagejava.langvs.otherpackages Youcanuseanyclassinpackagejava.lang.Justusethe classname,e.g. Character TouseclassesinotherAPIpackages,youhavetogive thewholename,e.g. javax.swing.JFrame Soyouhavetowrite: javax.swing.JFramejf=newjavax.swing.JFrame(); Usetheimportstatement! TobeabletousejustJFrame,putanimport statementbeforetheclassdefiniXon: ImportsonlyclassJFrame. Usetheasterisk,asinline importjavax.swing.JFrame; below,toimportallclasses inpackage: publicclassC{ importjavax.swing.*; … publicvoidm(…){ JFramejf=newJFrame(); … } } 2 2/4/16 Otherpackagesonyourharddrive Onecanputabunchoflogicallyrelatedclassesintoapackage, whichmeanstheywillallbeinthesamedirectoryonharddrive. Reasonsfordoingthis?Wediscussmuchlater. ImageofEclipse PackageExplorer: projecthas defaultpackage and packagepack1 3projects: Defaultpackagehas 2classes: Rec02,Rec02Tester pack1has1class:C HarddriveEclipsePackageExplorer Eclipse Hashing I03Demo recitaXon02 src Rec02.java Rec02Tester.java pack1 C.java Eclipsedoesnotmakeadirectoryforthedefault package;itsclassesgorightindirectorysrc ImporXngthepackage Everyclassinpackage pack1muststartwith thepackagestatement Everyclassoutsidethe packageshouldimportits classesinordertousethem packagepack1; publicclassC{ /**Constructor:*/ publicC(){ } } importpack1.*; publicclassRec02{ publicRec02(){ Cv=newC(); } } CHARANDCHARACTER Specialchars worthknowingabout Primitive type char Usesinglequotes Unicode:2-byterepresentaXon Visitwww.unicode.org/charts/ toseeallunicodechars char fred= 'a'; char wilma= 'b'; System.out.println(fred); a • • • • • • • • • ' ' '\t' '\n' '\'' '\"' '\\' '\b' '\f' '\r' -space -tabcharacter -newlinecharacter -singlequotecharacter -doublequotecharacter -backslashcharacter -backspacecharacter-NEVERUSETHIS -formfeedcharacter-NEVERUSETHIS -carriagereturn-NEVERUSETHIS Backslash,calledthe escapecharacter 3 2/4/16 Casting char values SpecsforClassCharacter Castachartoanintusingunaryprefixoperator(int), GivesunicoderepresentaXonofchar,asanint (int)'a'gives97 (char)97gives'a' Om,orAum,thesoundof theuniverse(Hinduism) (char)2384gives'ॐ' NooperaXonsonchars(valuesoftypechar)!BUT,if usedinarelaXonorinarithmeXc,acharisautomaXcallycastto typeint. RelaXons<><=>===!=== 'a' < 'b' same as 97 < 98, i.e. false 'a' + 1 gives 98 MainpanenowcontainsdescripXonofclassCharacter: 1. TheheaderofitsdeclaraXon. 2. AdescripXon,includinginfoaboutUnicode 3. Nestedclasssummary(skipit) 4. Fieldsummary(skipit) 5. Constructorsummary(read) FindmethodcompareTo Seea1-sentencedescripXon 6. Methodsummary(read) 7. Fielddetail(skipit) Clickonmethodname 8. Methoddetail(read) Takesyoutoacomplete descripXoninMethoddetail secXon Class Character Class Character AnobjectofclassCharacterwrapsasinglechar (hasafieldthatcontainsasinglechar) Character c1= new Character('b'); Character c2= new Character('c'); c1 Character@a1 Character@a1 ??? 'b' charValue() compareTo(Character) equals(Object) Don’tknow fieldname c2 Character@b9 Character@b9 ??? 'c' charValue() compareTo(Character) equals(Object) Static methods in class Character LotsofstaXcfuncXons.Youhavetolooktoseewhatisavailable. Belowareexamples Thesereturntheobvious isAlphabetic(c) booleanvalueforparameter c,achar isDigit(c) isLetter(c) isLowerCase(c) isUpperCase(c) isWhitespace(c) toLowerCase(c) toUpperCase(c) EachinstanceofclassCharacterwrapsacharvalue—hasa fieldthatcontainsacharvalue.Characterallowsacharvalue tobetreatedasanobject. • • FindmethodsineachobjectbylookingatAPIspecsonweb: docs.oracle.com/javase/8/docs/api/java/lang/Character.html c.charValue() c’swrappedchar,asachar c.equals(c1) Trueiffc1isaCharacterandwrapssamechar c.compareTo(c1) 0ifc==c1.<0ifc<c1.>0ifc>c1. c.toString() c’swrappedchar,asaString … … == versus equals c1 == c2 false c3 == c1 false c1 == c1 true c1.equals(c2) true c3.equals(c1) Error!!! We’llexplain“staXc”soon Whitespacecharsarethespace‘‘, tabchar,linefeed,carriagereturn, etc. Thesereturnachar. Youcanimporttheseusing“importstaXcjava.lang.Character.*;” trueiffc1,c2containsamevalues trueiffc2isalsoaCharacter objectandcontainssamechar asc1 c1 Character@a1 c2 Character@b9 Character@a1 ??? 'b' charValue() compareTo(Character) equals(Object) c3 null Character@b9 ??? 'b' charValue() compareTo(Character) equals(Object) 4 2/4/16 Class String String s= “CS2110”; String: special place in Java: no need for a new-expression. String literal creates object. s String@x2 String@x2 ??? “CS2110” STRING Operator + +isoverloaded "abc" + "12$" evaluatesto"abc12$" IfoneoperandofconcatenaXonisaStringandtheotherisn’t, theotherisconvertedtoaString. Sequenceof+doneleltoright 1 + 2 + "ab$" "ab$" + 1 + 2 evaluatesto"3ab$" evaluatesto"ab$12"Watch out! Picking out pieces of a String s.length():numberofcharsins—5 01234 FindoutaboutmethodsofclassString: docs.oracle.com/javase/8/docs/api/ index.html?java/lang/String.html length() charAt(int) subString(int) subString(int,int) equals(Object) trim() contains(String) indexOf(String) startsWith(String) endsWith(String) …more… Numberingchars:firstoneinposiXon0 Important:Stringobjectisimmutable: can’tchangeitsvalue.AlloperaXons/ funcXonscreatenewStringobjects Operator + System.out.println("c is: " + c + ", d is: " + d + Usingseveral ", e is: " + e); linesincreases readability Canuse+toadvantageinprintlnstatement.Gooddebuggingtool. •Notehoweachoutputnumberisannotatedtoknowwhatitis. Output: cis:32,dis:-3,eis:201 c 32 d -3 e 201 Other useful String functions s.trim() – s but with leading/trailing whitespace removed s.indexOf(s1) "CS 13" – position of first occurrence of s1 in s (-1 if none) s.lastIndexOf(s1) – similar to s.indexOf(s1) s.charAt(i):charatposiXoni s.substring(i):newStringcontaining charsatposiXonsfromitoend —s.substring(2)is'13' Lotsofmethods.Weexplainbasicones String@x2 s.substring(i,j):newString containingcharsatposiXons i..(j-1)—s.substring(2,4)is'13' ? "CS 13" length() charAt(int) subString(int) subString(int,int) …more… Becareful:Charatjnotincluded! s String@x2 s.contains(s1) – true iff String s1 is contained in s2 s.startsWith(s1) – true iff s starts with String s1 s.endsWith(s1) – true iff s ends with String s1 s.compareTo(s1) – 0 if s and s1 contain the same string, < 0 if s is less (dictionary order), > 0 if s is greater (dictionary order) There are more functions! Look at the API specs! 5