![Page 1: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/1.jpg)
117-214
PrinciplesofSoftwareConstruction:Objects,Design,andConcurrency
IntroductiontoJava
JoshBlochCharlieGarrod
![Page 2: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/2.jpg)
217-214
Administrivia
• Homework1duenextThursday11:59p.m.– Everyonemustreadandsignourcollaborationpolicy
• FirstreadingassignmentdueTuesday– EffectiveJavaItems15and16
![Page 3: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/3.jpg)
317-214
Outline
I. "HelloWorld!"explainedII. ThetypesystemIII. Quick‘n’dirtyI/OIV. Abriefintroductiontocollections
![Page 4: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/4.jpg)
417-214
The“simplest”JavaProgramclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 5: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/5.jpg)
517-214
Complication1:youmustuseaclasseven ifyouaren’tdoingOOprogrammingclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 6: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/6.jpg)
617-214
Complication2:mainmustbepublicclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 7: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/7.jpg)
717-214
Complication3:mainmustbestaticclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 8: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/8.jpg)
817-214
Complication4:mainmustreturnvoidclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 9: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/9.jpg)
917-214
Complication5:mainmustdeclarecommandlineargumentsevenifunusedclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 10: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/10.jpg)
1017-214
Complication6:standardI/Orequiresuseofstatic fieldofSystemclass HelloWorld {
public static void main(String[] args) {System.out.println("Hello world!");
}}
![Page 11: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/11.jpg)
1117-214
Executionisabitcomplicated
• Firstyoucompile thesourcefile– javac HelloWorld.java– ProducesclassfileHelloWorld.class
• Thenyoulaunchtheprogram– java HelloWorld– JavaVirtualMachine(JVM)executesmainmethod
![Page 12: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/12.jpg)
1217-214
Onthebrightside…
• Hasmanygoodpointstobalanceshortcomings• Someverbosityisnotabadthing– Canreduceerrorsandincreasereadability
• ModernIDEseliminatemuchofthepain– Typepsvm insteadofpublic static void main
• Managedruntimehasmanyadvantages– Safe,flexible,enablesgarbagecollection
• ItmaynotbebestlanguageforHelloWorld…– ButJavaisverygoodforlarge-scaleprogramming!
![Page 13: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/13.jpg)
1317-214
Outline
I. “HelloWorld!”explainedII. ThetypesystemIII. Quick‘n’dirtyI/OIV. Abriefintroductiontocollections
![Page 14: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/14.jpg)
1417-214
Javahasabipartite (2-part)typesystem
Primitives ObjectReferenceTypesint, long, byte, short, char, float, double, boolean
Classes,interfaces,arrays,enums,annotations
Noidentityexcepttheirvalue HaveidentitydistinctfromvalueImmutable Somemutable,someimmutableOnstack, existonlywheninuse Onheap,garbagecollectedCan’tachieveunityofexpression UnityofexpressionwithgenericsDirtcheap More costly
![Page 15: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/15.jpg)
1517-214
ProgrammingwithprimitivesAlotlikeC!
public class TrailingZeros {public static void main(String[] args) {
int i = Integer.parseInt(args[0]);System.out.println(trailingZerosInFactorial(i));
}
static int trailingZerosInFactorial(int i) {int result = 0; // Conventional name for return value
while (i >= 5) {i /= 5; // Same as i = i / 5; Remainder discardedresult += i;
}return result;
}}
![Page 16: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/16.jpg)
1617-214
Primitivetypesummary
• int 32-bitsignedinteger• long 64-bitsignedinteger• byte 8-bitsignedinteger• short 16-bitsignedinteger• char 16-bitunsignedinteger/character• float 32-bitIEEE754floatingpointnumber• double 64-bitIEEE754floatingpointnumber• boolean Boolean value:true orfalse
![Page 17: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/17.jpg)
1717-214
Deficientprimitivetypes
• byte,short – useint instead!– byte isbroken– shouldhavebeenunsigned
• float – usedouble instead!– Providestoolittleprecision– Onlycompellingusecaseislargearrays,especiallyinresource-constrainedenvironments
![Page 18: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/18.jpg)
1817-214
PopQuiz!
![Page 19: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/19.jpg)
1917-214
Whatdoesthisfragmentprint?int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i;int sum1 = 0;for (i = 0; i < a.length; i++) {
sum1 += a[i];}
int j;int sum2 = 0;for (j = 0; i < a.length; j++) {
sum2 += a[j];}
System.out.println(sum1 - sum2);
![Page 20: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/20.jpg)
2017-214
Maybenotwhatyouexpect!int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i;int sum1 = 0;for (i = 0; i < a.length; i++) {
sum1 += a[i];}int j;int sum2 = 0;for (j = 0; i < a.length; j++) { // Copy/paste error!
sum2 += a[j];}System.out.println(sum1 - sum2);
Youmightexpectittoprint0,butitprints55
![Page 21: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/21.jpg)
2117-214
Youcouldfixitlikethis…int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i;int sum1 = 0;for (i = 0; i < a.length; i++) {
sum1 += a[i];}int j;int sum2 = 0;for (j = 0; j < a.length; j++) {
sum2 += a[j];}
System.out.println(sum1 - sum2); // Now prints 0, as expected
![Page 22: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/22.jpg)
2217-214
Butthisfixisfarbetter…int sum1 = 0;for (int i = 0; i < a.length; i++) {
sum1 += a[i];}
int sum2 = 0;for (int i = 0; i < a.length; i++) {
sum2 += a[i];}
System.out.println(sum1 - sum2); // Prints 0
• Reducesscopeofindexvariabletoloop• Shorterandlesserrorprone
![Page 23: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/23.jpg)
2317-214
Thisfixisbetterstill!int sum1 = 0;for (int x : a) {
sum1 += x;}
int sum2 = 0;for (int x : a) {
sum2 += x;}
System.out.println(sum1 - sum2); // Prints 0
• Eliminatesscopeofindexvariableentirely!• Evenshorterandlesserrorprone
![Page 24: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/24.jpg)
2417-214
Lessonsfromthequiz
• Minimizescopeoflocalvariables[EJItem57]– Declarevariablesatpointofuse
• Initializevariablesindeclaration• Preferfor-eachloopstoregularfor-loops• Usecommonidioms• Watchoutforbadsmellsincode– Suchasindexvariabledeclaredoutsideloop
![Page 25: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/25.jpg)
2517-214
Objects
• Allnon-primitivesarerepresentedbyobjects.• Anobject isabundleofstateandbehavior• State– thedatacontainedintheobject– InJava,thesearethefields oftheobject
• Behavior– theactionssupportedbytheobject– InJava,thesearecalledmethods– MethodisjustOO-speakforfunction– Invokeamethod=callafunction
![Page 26: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/26.jpg)
2617-214
Classes
• Everyobjecthasaclass– Aclassdefinesmethodsandfields– Methodsandfieldscollectivelyknownasmembers
• Classdefinesbothtypeandimplementation– Type≈wheretheobjectcanbeused– Implementation≈howtheobjectdoesthings
• Looselyspeaking,themethodsofaclassareitsApplicationProgrammingInterface(API)– Defineshowusersinteractwithitsinstances
![Page 27: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/27.jpg)
2717-214
Theclasshierarchy
• TherootisObject(allnon-primitivesareobjects)• AllclassesexceptObjecthaveoneparentclass– Specifiedwithanextends clauseclass Guitar extends Instrument { ... }
– Ifextends clauseomitted,defaultstoObject• Aclassisaninstanceofallitssuperclasses
Object
ToyInstrument
YoyoGuitar
![Page 28: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/28.jpg)
2817-214
Implementationinheritance
• Aclass:– Inheritsvisiblefieldsandmethodsfromitssuperclasses– Canoverridemethodstochangetheirbehavior
• Overridingmethodimplementationmustobeycontract(s)ofitssuperclass(es)– Ensuressubclasscanbeusedanywheresuperclass can– Liskov SubstitutionPrinciple(LSP)– Wewilltalkmoreaboutthisinalaterclass
![Page 29: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/29.jpg)
2917-214
Interfacetypes
• Definesatypewithoutanimplementation• Muchmoreflexiblethanclasstypes– Aninterfacecanextendoneormoreothers– Aclasscanimplementmultipleinterfaces
![Page 30: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/30.jpg)
3017-214
Enum types
• Javahasobject-orientedenums• Insimpleform,theylookjustlikeCenums:
enum Planet { MERCURY, VENUS, EARTH, MARS,JUPITER, SATURN, URANUS, NEPTUNE }
• Buttheyhavemany advantages!– Compile-timetypesafety– Multipleenum typescansharevaluenames– Canaddorreorderwithoutbreakingexistinguses– High-qualityObjectmethodsareprovided– Screamingfastcollections(EnumSet,EnumMap)– Caniterateoverallconstantsofanenum
![Page 31: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/31.jpg)
3117-214
Boxedprimitives
• Immutablecontainersforprimitivetypes• Boolean,Integer,Short,Long,Character,Float,Double
• Letyou“use”primitivesincontextsrequiringobjects• Canonicalusecaseiscollections• Don’tuseboxedprimitivesunlessyouhaveto!• Languagedoesautoboxing andauto-unboxing– Blursbutdoesnoteliminatedistinction– Therebedragons!
![Page 32: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/32.jpg)
3217-214
Comparingvalues
x == y comparesthecontents ofx andyprimitivevalues: returnstrueifxandyhavethesamevalueobjectsrefs: returnstrueifxandyrefertosameobject
x.equals(y) comparesthevaluesoftheobjectsreferredto byx andy
![Page 33: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/33.jpg)
3317-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------
![Page 34: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/34.jpg)
3417-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------true
5j
i 5
![Page 35: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/35.jpg)
3517-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------true
String s = "foo";String t = s;System.out.println(s == t);---------------------------
5j
i 5
![Page 36: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/36.jpg)
3617-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------true
String s = "foo";String t = s;System.out.println(s == t);---------------------------true
5j
i 5
"foo"
t
s
![Page 37: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/37.jpg)
3717-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------true
String s = "foo";String t = s;System.out.println(s == t);---------------------------true
String u = "iPhone";String v = u.toLowerCase();String w = "iphone";System.out.println(v == w);---------------------------
5j
i 5
"foo"
t
s
![Page 38: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/38.jpg)
3817-214
Trueorfalse?
int i = 5;int j = 5;System.out.println(i == j);---------------------------true
String s = "foo";String t = s;System.out.println(s == t);---------------------------true
String u = "iPhone";String v = u.toLowerCase();String w = "iphone";System.out.println(v == w);---------------------------Undefined!(false inpractice)
5j
"foo"
t v
u
w
"iPhone"si 5
"iphone"
"iphone"?
![Page 39: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/39.jpg)
3917-214
Themoral
• Alwaysuse.equals tocompareobjectrefs– (Exceptforenums,whicharespecial)– The==operatorcanfailsilentlyandunpredictably
![Page 40: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/40.jpg)
4017-214
Outline
I. “HelloWorld!”explainedII. TheJavatypesystemIII. Quick‘n’dirtyI/OIV. Abriefintroductiontocollections
![Page 41: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/41.jpg)
4117-214
Output
• UnformattedSystem.out.println("Hello World");System.out.println("Radius: " + r);System.out.println(r * Math.cos(theta));System.out.println();System.out.print("*");
• FormattedSystem.out.printf("%d * %d = %d%n", a, b, a * b); // Varargs
![Page 42: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/42.jpg)
4217-214
Commandlineinputexample
Echos allcommandlineargumentsclass Echo {
public static void main(String[] args) {for (String arg : args) {
System.out.print(arg + " ");}
}}
$ java Echo Woke up this morning, had them weary blues
Woke up this morning, had them weary blues
![Page 43: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/43.jpg)
4317-214
Commandlineinputwithparsing
PrintsGCDoftwocommandlineargumentsclass Gcd {
public static void main(String[] args) {int i = Integer.parseInt(args[0]);int j = Integer.parseInt(args[1]);System.out.println(gcd(i, j));
}
static int gcd(int i, int j) {return i == 0 ? j : gcd(j % i, i);
}}
$ java Gcd 11322 35298666
![Page 44: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/44.jpg)
4417-214
Scannerinput
Countsthewordsonstandardinputclass Wc {
public static void main(String[] args) {Scanner sc = new Scanner(System.in);long result = 0;while (sc.hasNext()) {
sc.next(); // Swallow tokenresult++;
}System.out.println(result);
}}
$ java Wc < Wc.java32
![Page 45: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/45.jpg)
4517-214
Outline
I. “HelloWorld!”explainedII. ThetypesystemIII. Quick‘n’dirtyI/OIV. Abriefintroductiontocollections
![Page 46: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/46.jpg)
4617-214
Primarycollectioninterfaces
Collection
QueueSet List
Deque
Map
![Page 47: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/47.jpg)
4717-214
“Primary”collectionimplementations
Interface ImplementationSet HashSetList ArrayListQueue ArrayDequeDeque ArrayDeque(stack) ArrayDequeMap HashMap
![Page 48: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/48.jpg)
4817-214
Othernoteworthycollectionimplementations
Interface Implementation(s)
Set LinkedHashSetTreeSetEnumSet
Queue PriorityQueue
Map LinkedHashMapTreeMapEnumMap
![Page 49: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/49.jpg)
4917-214
Collectionsusageexample1
Squeezeduplicatewordsoutofcommandline
public class Squeeze {public static void main(String[] args) {
Set<String> s = new LinkedHashSet<>();for (String word : args)
s.add(word);System.out.println(s);
}}
$ java Squeeze I came I saw I conquered[I, came, saw, conquered]
![Page 50: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/50.jpg)
5017-214
Collectionsusageexample2
Printuniquewordsinlexicographicorderpublic class Lexicon {
public static void main(String[] args) {Set<String> s = new TreeSet<>();for (String word : args)
s.add(word);System.out.println(s);
}}
$ java Lexicon I came I saw I conquered[I, came, conquered, saw]
![Page 51: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/51.jpg)
5117-214
Collectionsusageexample3
Printindexoffirstoccurrenceofeachwordclass Index {
public static void main(String[] args) {Map<String, Integer> index = new TreeMap<>();
// Iterate backwards so first occurrence winsfor (int i = args.length - 1; i >= 0; i--) {
index.put(args[i], i);}System.out.println(index);
}}
$ java Index if it is to be it is up to me to do it{be=4, do=11, if=0, is=2, it=1, me=9, to=3, up=7}
![Page 52: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/52.jpg)
5217-214
Moreinformationoncollections
• Formuchmoreinformationoncollections,seetheannotatedoutline:
https://docs.oracle.com/javase/11/docs/technotes/guides/collections/reference.html
• Formoreinfoonany libraryclass,seejavadoc– Searchwebfor<fullyqualifiedclassname>8– e.g.,java.util.scanner 8
![Page 53: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/53.jpg)
5317-214
Whataboutarrays?
• Arraysaren’treallyapartofthecollectionsframework
• Butthereisanadapter:Arrays.asList• Arraysandcollectionsdon’tmix• Ifyoutrytomixthemandgetcompilerwarnings,takethemseriously
• Generallyspeaking,prefercollectionstoarrays• See EffectiveJava Item28fordetails
![Page 54: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/54.jpg)
5417-214
TolearnJavaquickly
![Page 55: Principles of Software Construction: Objects, Design, and Concurrency Introduction to Java · 2020-04-24 · Objects, Design, and Concurrency Introduction to Java Josh Bloch ... –](https://reader035.vdocuments.site/reader035/viewer/2022081405/5f0cb3797e708231d436b4cb/html5/thumbnails/55.jpg)
5517-214
Summary
• Javaiswellsuitedtolargeprograms;smallonesmayseemabitverbose
• Bipartitetypesystem– primitives&objectrefs– Singleimplementationinheritance–Multipleinterfaceinheritance
• AfewsimpleI/Otechniqueswillgetyoustarted• Collectionsframeworkispowerful&easytouse