Download Arguments to method main, Packages, Wrapper Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS2110,Recita.on2
Argumentstomethodmain,
Packages,
WrapperClasses,
Characters,
Strings
Demo: Create application
Tocreateanewprojectthathasamethodcalledmainwitha
bodythatcontainsthestatement
System.out.println(“Hello World”);
dothis:
•  Eclipse:File->New->Project
•  File->New->Class
•  Checkthemethodmainbox
•  Intheclassthatiscreated,writetheabovestatementinthe
bodyofmain
•  HitthegreenplaybuIonordomenuitemRun->Run
Java Application
publicsta.cvoidmain(String[]args){…}
Parameter:Stringarray
AJavaprogramthathasaclasswithastaScproceduremain,as
declaredabove,iscalledanapplicaSon.
Theprogram,i.e.theapplicaSon,isrunbycallingmethodmain.
Eclipsehasaneasywaytodothis.
Method main and its parameter
publicsta.cvoidmain(String[]args){…}
InEclipse,whenyoudomenuitem
Parameter:Stringarray
Run->Run(orclickthegreenPlaybuIon)
Eclipseexecutesthecallmain(arraywith0arguments);
TotellEclipsewhatarrayofStringstogiveastheargument,
startbyusingmenuitem
Run->RunConfiguraSons…
or
Run->DebugConfiguraSon…
(seenextslide)
Window Run Configurations
ThisArgumentspaneofRunConfiguraSonswindowgives
argumentarrayofsize3:
args[0]:“SpeciesData/a0.dat”
args[1]:“2”
args[2]:“whatfor?”
QuotesOK,butnotneeded
ClickArgumentspane
Quotesneeded
becauseofspacechar
DEMO:Givinganargumenttothecallonmain
ChangetheprogramtoprinttheStringthatisinargs[0],i.e.
changethestatementinthebodyto
System.out.println(args[0]);
Then
•  DoRun->RunConfiguraSons
•  ClicktheArgumentstab
•  IntheProgramfield,typein“Haloooothere!”
•  ClicktherunbuIoninthelowerrighttoexecutethecallon
mainwithanarrayofsize1…
PACKAGESANDTHEJAVAAPI
Package
Package:CollecSonofJavaclassesandotherpackages.
SeeJavaSummary.pptx,slide20
AvailableinthecoursewebsiteinthefollowinglocaSon:
hIp://www.cs.cornell.edu/courses/CS2110/2016sp/links.html
Threekindsofpackages
(1)  Thedefaultpackage:inprojectdirectory/src
(2)  Javaclassesthatarecontainedinaspecificdirectoryonyour
harddrive(itmayalsocontainsub-packages)
(3)  PackagesofJavaclassesthatcomewithJava,
e.g.packagesjava.lang,javax.swing.
APIpackagesthatcomewithJava
Visitcoursewebpage,clickLinks,thenJava8APISpecs.
Link:
hIp://www.cs.cornell.edu/courses/CS2110/2016sp/links.html
Scrolldowninlekcol(Packagespane),clickonjava.lang
MorerealisScally:
hIp://lmgly.com/?q=java+8+api
FindingpackagedocumentaSon
Scrollthroughhere
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
statementbeforetheclassdefiniSon:
ImportsonlyclassJFrame.
Usetheasterisk,asinline
importjavax.swing.JFrame;
below,toimportallclasses
inpackage:
publicclassC{
importjavax.swing.*;
…
publicvoidm(…){
JFramejf=newJFrame();
…
}
}
Otherpackagesonyourharddrive
Onecanputabunchoflogicallyrelatedclassesintoapackage,
whichmeanstheywillallbeinthesamedirectoryonharddrive.
Reasonsfordoingthis?Wediscussmuchlater.
ImageofEclipse
PackageExplorer:
3projects:
Defaultpackagehas
2classes:
Rec02,Rec02Tester
pack1has1class:C
projecthas
defaultpackage
and
packagepack1
HarddriveEclipsePackageExplorer
Eclipse
Hashing
I03Demo
recitaSon02
src
Rec02.java
Rec02Tester.java
pack1
C.java
Eclipsedoesnotmakeadirectoryforthedefault
package;itsclassesgorightindirectorysrc
ImporSngthepackage
Everyclassinpackage
pack1muststartwith
thepackagestatement
packagepack1;
publicclassC{
/**Constructor:*/
publicC(){
}
}
Everyclassoutsidethe
packageshouldimportits
classesinordertousethem
importpack1.*;
publicclassRec02{
publicRec02(){
Cv=newC();
}
}
CHARANDCHARACTER
Primitive type char
Usesinglequotes
Unicode:2-byterepresentaSon
Visitwww.unicode.org/charts/
toseeallunicodechars
char fred= 'a';
char wilma= 'b';
System.out.println(fred);
a
Specialchars worthknowingabout
• 
• 
• 
• 
• 
• 
• 
• 
• 
' '
'\t'
'\n'
'\''
'\"'
'\\'
'\b'
'\f'
'\r'
-space
-tabcharacter
-newlinecharacter
-singlequotecharacter
-doublequotecharacter
-backslashcharacter
-backspacecharacter-NEVERUSETHIS
-formfeedcharacter-NEVERUSETHIS
-carriagereturn-NEVERUSETHIS
Backslash,calledthe
escapecharacter
Casting char values
Castachartoanintusingunaryprefixoperator(int),
GivesunicoderepresentaSonofchar,asanint
(int)'a'gives97
(char)97gives'a'
(char)2384gives'ॐ'
Om,orAum,thesoundof
theuniverse(Hinduism)
NooperaSonsonchars(valuesoftypechar)!BUT,if
usedinarelaSonorinarithmeSc,acharisautomaScallycastto
typeint.
RelaSons<><=>===!===
'a' < 'b'
same as
97 < 98, i.e. false
'a' + 1
gives
98
SpecsforClassCharacter
MainpanenowcontainsdescripSonofclassCharacter:
1.  TheheaderofitsdeclaraSon.
2.  AdescripSon,includinginfoaboutUnicode
3.  Nestedclasssummary(skipit)
4.  Fieldsummary(skipit)
5.  Constructorsummary(read) FindmethodcompareTo
Seea1-sentencedescripSon
6.  Methodsummary(read)
7.  Fielddetail(skipit)
Clickonmethodname
8.  Methoddetail(read)
Takesyoutoacomplete
descripSoninMethoddetail
secSon
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)
Class Character
• 
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
…
…
Static methods in class Character
LotsofstaScfuncSons.Youhavetolooktoseewhatisavailable.
Belowareexamples
Thesereturntheobvious
isAlphabetic(c)
booleanvalueforparameter
c,achar
isDigit(c)
isLetter(c)
We’llexplain“staSc”soon
isLowerCase(c)
Whitespacecharsarethespace‘‘,
isUpperCase(c)
tabchar,linefeed,carriagereturn,
isWhitespace(c)
etc.
toLowerCase(c)
Thesereturnachar.
toUpperCase(c)
Youcanimporttheseusing“importstaScjava.lang.Character.*;”
== versus equals
c1 == c2 false
c3 == c1 false
c1 == c1 true
c1.equals(c2) true
c3.equals(c1) Error!!!
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)
STRING
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”
FindoutaboutmethodsofclassString:
length()
docs.oracle.com/javase/8/docs/api/
charAt(int)
index.html?java/lang/String.html
subString(int)
subString(int,int)
equals(Object)
Lotsofmethods.Weexplainbasicones
trim()
contains(String)
Important:Stringobjectisimmutable:
indexOf(String)
can’tchangeitsvalue.AlloperaSons/
startsWith(String)
funcSonscreatenewStringobjects
endsWith(String)
…more…
Operator +
+isoverloaded
"abc" + "12$" evaluatesto"abc12$"
IfoneoperandofconcatenaSonisaStringandtheotherisn’t,
theotherisconvertedtoaString.
Sequenceof+donelektoright
1 + 2
+ "ab$"
"ab$" + 1 + 2
evaluatesto"3ab$"
evaluatesto"ab$12"Watch
out!
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
Picking out pieces of a String
s.length():numberofcharsins—5
01234
Numberingchars:firstoneinposiSon0
"CS 13"
s.charAt(i):charatposiSoni
s.substring(i):newStringcontaining
charsatposiSonsfromitoend
—s.substring(2)is'13'
String@x2
s.substring(i,j):newString
containingcharsatposiSons
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
Other useful String functions
s.trim() – s but with leading/trailing whitespace removed
s.indexOf(s1)
– position of first occurrence of s1 in s
(-1 if none)
s.lastIndexOf(s1) – similar to s.indexOf(s1)
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!