Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
ProgrammingLanguages
andTechniques
(CIS120)
Lecture22
March15,2017
Java:StaticMethods&Arrays
Chapters20&21
Announcements
• JavaBootcamp
– Monday,March20th,6-8PM
– Towne100
• Upcoming:Midterm2
– Friday,March31st inclass
– Coverage:mutablestate,queues,deques,GUI,objects,Java
CIS120
2
HowfaralongareyouonHW05?
1. Ihaven'tstartedyet.
2. I'muptoLayout (hlist,vlist)
3. I'muptoLines andPreview
4. I'muptoPoints
5. I'muptoEllipses
6. I'muptoCheckboxes
7. I'muptoCoolNewWidget
8. I'mdone!
JavaCoreLanguage
differencesbetweenOCamlandJava
Expressionsvs.Statements
• OCamlisanexpressionlanguage
– Everyprogramphraseisanexpression(andreturnsavalue)
– Thespecialvalue()oftypeunit isusedastheresultofexpressions
thatareevaluatedonlyfortheirsideeffects
– Semicolonisanoperator thatcombinestwoexpressions(wherethe
left-handonereturnstypeunit)
• Javaisastatementlanguage
– Two-sortsofprogramphrases:expressions(whichcomputevalues)
andstatements(whichdon’t)
– Statementsareterminatedbysemicolons
– Anyexpressioncanbeusedasastatement(butnotvice-versa)
Types
• AsinOCaml,everyJavaexpressionhasatype
• Thetypedescribesthevaluethatanexpressioncomputes
Expressionform
Example
Type
Variablereference
x
Declaredtypeofvariable
Objectcreation
newCounter()
Classoftheobject
Methodcall
c.inc()
Returntypeofmethod
Equalitytest
x ==y
boolean
Assignment
x =5
don’tuseasanexpression!!
TypeSystemOrganization
OCaml
Java
primitivetypes
(valuesstored
“directly”inthe
stack)
int,float, char,bool,…
int, float,double,char,boolean,
…
structuredtypes
(a.k.a.reference
types — values
storedintheheap)
tuples,datatypes,records,
functions,arrays
objects,arrays
(objectsencodedasrecords
offunctions)
(records,tuples,datatypes,
strings,first-classfunctions area
specialcaseofobjects)
generics
‘alist
List<A>
abstracttypes
module types(signatures)
interfaces
public/privatemodifiers
Arithmetic&LogicalOperators
OCaml
Java
=,==
==
equalitytest
<>,!=
!=
inequality
>,>=,<,<=
>,>=,<,<=
comparisons
+
+
addition(andstringconcatenation)
-
-
subtraction (andunaryminus)
*
*
multiplication
/
/
division
mod
%
remainder(modulus)
not
!
logical“not”
&&
&&
logical “and”(short-circuiting)
||
||
logical“or”(short-circuiting)
Java:OperatorOverloading
• Themeaning ofanoperatorinJavaisdeterminedbythe
typesofthevaluesitoperateson:
– Integerdivision
4/3 ⇒ 1
– Floatingpointdivision
4.0/3.0 ⇒ 1.3333333333333333
– Automaticconversionfrominttofloat
4/3.0 ⇒ 1.3333333333333333
• OverloadingisageneralmechanisminJava
– we’llseemoreofitlater
Equality
• likeOCaml,Javahastwowaysoftestingreferencetypesfor
equality:
– “pointerequality”
o1==o2
– “deepequality”
o1.equals(o2)
everyobjectprovidesan“equals”
methodthat“doestherightthing”
dependingontheclassofthe
object
• Normally,youshoulduse==tocompareprimitivetypesand
“.equals”tocompareobjects
Strings
• String isabuiltinJavaclass
• Stringsaresequencesof(unicode)characters
""
"Java"
"3 Stooges" "富士山"
• +meansStringconcatenation(overloaded)
"3" + " " + "Stooges" Þ "3 Stooges"
• TextinaStringisimmutable(likeOCaml)
–
–
–
–
butvariablesthatstorestringsarenot
String x = "OCaml";
String y = x;
Can'tdoanythingtox sothaty changes
• The .equals methodreturnstruewhentwostrings
containthesamesequenceofcharacters
Whatisthevalueofans attheendofthisprogram?
String x = "CIS 120";
String z = "CIS 120";
boolean ans = x.equals(z);
1. true
2. false
3. NullPointerException
Answer:true
Thisisthepreferredmethodofcomparingstrings!
Whatisthevalueofans attheendofthisprogram?
String x1 = "CIS ";
String x2 = "120";
String x = x1 + x2;
String z = "CIS 120";
boolean ans = (x == z);
1. true
2. false
3. NullPointerException
Answer:false
Eventhoughx andz bothcontainthecharacters“CIS120”,
theyarestoredintwodifferentlocationsintheheap.
Whatisthevalueofans attheendofthisprogram?
String x = "CIS 120";
String z = "CIS 120";
boolean ans = (x == z);
1. true
2. false
3. NullPointerException
Answer:true(!)
Why?Sincestringsareimmutable,twoidentical
stringsthatareknownwhentheprogramiscompiledcanbe
aliasedbythecompiler(tosavespace).
Moral
Alwaysuses1.equals(s2)to
comparestrings!
Comparestringswithrespecttotheir
content,notwheretheyhappentobe
allocatedinmemory…
Whatisthevalueofans attheendofthisprogram?
Counter x;
x.inc();
int ans = x.inc();
public class Counter {
private int r;
1.
2.
3.
4.
1
2
3
RaisesNullPointerException
public Counter () {
r = 0;
}
public int inc () {
r = r + 1;
return r;
}
Answer:NullPointerException
}
Whatisthevalueofans attheendofthisprogram?
Counter x = new Counter();
x.inc();
Counter y = x;
y.inc();
int ans = x.inc();
1.
2.
3.
4.
public class Counter {
private int r;
public Counter () {
r = 0;
}
1
2
3
NullPointerException
public int inc () {
r = r + 1;
return r;
}
}
Answer:3
CritiqueofHand-RolledObjects
• “Rollyourownobjects”madefromrecords,functions,and
referencesaregoodforunderstanding...
type counter = {
inc : unit -> int;
dec : unit -> int;
}
• ...butnotthatgreatforprogramming
– minor:syntaxisabitclunky(toomanyparens,etc.)
– major:OCaml’s recordtypesaretoorigid,cannotreusefunctionality
type reset_counter = {
inc
: unit -> int;
dec
: unit -> int;
reset : unit -> unit;
}
CIS120
18
ConstructorswithParameters
Constructormethodscantake
parameters
public class Counter {
private int r;
Constructormusthavethesame
nameastheclass
public Counter (int r0) {
r = r0;
}
public int inc () {
r = r + 1;
return r;
}
}
public int dec () {
r = r - 1;
return r;
}
CIS120
objectcreationanduse
public class Main {
public static void
main (String[] args) {
constructor
invocation
Counter c = new Counter(3);
System.out.println( c.inc() );
}
}
19
Creating Objects
• Declare avariable toholdaCounter object
– Typeoftheobjectisthenameoftheclassthatcreatesit
• Invoke theconstructorfor Counter tocreatea Counter
instance withkeyword"new"andstoreitin thevariable
Counter c = new Counter();
CIS120
20
Creatingobjects
• EveryJavavariableismutable
Counter c = new Counter(2);
c = new Counter(4);
• AJavavariableofreferencetypecanalsocontainsthespecial
value“null”
Counter c = null;
☞ Note:
Single=forassignment
Double==forreferenceequalitytesting
CIS120
21
StaticMethodsandFields
functionsandglobalstate
JavaMainEntryPoint
class MainClass {
public static void main (String[] args) {
…
}
}
• Programstartsrunningatmain
– args isanarrayofStrings (passedinfromthecommandline)
– mustbepublic
– returnsvoid (i.e.isacommand)
• Whatdoesstatic mean?
Howfamiliarareyouwiththeideaof"static"
methodsandfields?
1. Ihaven'theardoftheideaof"static".
2. I'veused"static"beforewithoutreally
understandingwhatitmeans
3. Ihavesomefamiliaritywiththe
differencebetween"static"and
"dynamic"
4. Itotallygetit.
CIS120
Staticmethodexample
public class Max {
public static int max (int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
closestanalogueoftop-level
functionsinOCaml,but
mustbeamemberofsomeclass
public static int max3(int x, int y, int z) {
return max(max(x,y), z);
}
}
public class Main {
Internally(withinthe
sameclass),callwithjust
themethodname
mainmethodmustbe
static;itisinvokedto
starttheprogramrunning
public static void main (String[] args) {
}
}
System.out.println(Max.max(3,4));
return;
Externally,prefixwith
nameoftheclass
mantra
Static==DecidedatCompile Time
Dynamic==DecidedatRun Time
Staticvs.DynamicMethods
• StaticMethodsareindependentofobjectvalues
– SimilartoOCamlfunctions
– Cannotrefertothelocalstateofobjects(fieldsornormalmethods)
• Usestaticmethodsfor:
– Non-OOprogramming
– Programmingwithprimitivetypes:Math.sin(60),Integer.toString(3),
Boolean.valueOf(“true”)
– “public static void main”
• “Normal”methodsaredynamic
– Needaccesstothelocalstateoftheparticularobjectonwhichthey
areinvoked
– Weonlyknowatruntimewhichmethodwillgetcalled
void moveTwice (Displaceable o) {
o.move (1,1); o.move(1,1);
}
Methodcallexamples
•
Calling a (dynamic)method of an object(o) that returns a number:
x = o.m() + 5;
•
Calling a staticmethod of a class(C) that returns a number:
x = C.m() + 5;
•
Calling a methodofthat returns void:
Static
•
o.m();
Dynamic
Calling a staticordynamicmethod inamethodof the same class:
Either
•
C.m();
m();
Static
C.m();
Dynamic
this.m();
Calling (dynamic)methods that returnobjects:
x = o.m().n();
x = o.m().n().x().y().z().a().b().c().d().e();
Whichstatic methodcanweaddtothisclass?
public class Counter {
private int r;
public Counter () {
r = 0;
}
public int inc () {
r = r + 1;
return r;
}
public static int dec () {
r = r – 1;
1.
return r;
}
public static int inc2 () {
inc();
2.
return inc();
}
// 1,2, or 3 here ?
}
3.
public static int getInitialVal () {
return 0;
}
Answer:3