java through exampleswokkil.pair.com/asim/tmp/metaprose/java · java through examples 5 javac...

89
Java Through Examples

Upload: others

Post on 13-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples

Page 2: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples i

Contents

1 Introduction 1

1.1 Instructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Introductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.3 Hands-OnLearning . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 HistoryofJava 1

2.1 JavaVersions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2.2 SupportedPlatforms . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2.3 WhyJava . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

3 Installation 3

3.1 InstallingJava . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3.2 InstallingEclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

4 Basics 4

4.1 HelloWorld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

4.2 HelloWorldEclipse . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4.3 EclipseViews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

4.4 Projects, Packages, Classes . . . . . . . . . . . . . . . . . . . . . . 7

4.5 ProgramStructure . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4.6 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5 Eclipse 10

5.1 Renaming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

5.2 Exporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Page 3: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples ii

6 PrimitiveDataTypes 12

6.1 IntegersandFloating-PointNumbers . . . . . . . . . . . . . . . . . 12

6.2 Variables, Types, Assignment . . . . . . . . . . . . . . . . . . . . . 12

6.3 NamingConventions . . . . . . . . . . . . . . . . . . . . . . . . . 13

6.4 PrintfandFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

6.5 NumericOperators . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6.6 AssignmentOperators . . . . . . . . . . . . . . . . . . . . . . . . . 16

6.7 Increment/DecrementOperators . . . . . . . . . . . . . . . . . . . 18

6.8 BitOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

7 Strings 20

7.1 StringLiterals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

7.2 StringAssignmentOperator . . . . . . . . . . . . . . . . . . . . . . 21

7.3 EscapeSequences . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

7.4 ConvertingBetweenStringsandNumbers . . . . . . . . . . . . . . . 22

7.5 TipCalculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

7.6 PopulationCalculator . . . . . . . . . . . . . . . . . . . . . . . . . 24

7.7 HousePrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

8 Branching 25

8.1 If, If-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

8.2 RelationalOperators . . . . . . . . . . . . . . . . . . . . . . . . . 27

8.3 Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

8.4 BooleanOperators . . . . . . . . . . . . . . . . . . . . . . . . . . 28

8.5 StringComparisonandEquality . . . . . . . . . . . . . . . . . . . . 29

8.6 TernaryOperator . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

8.7 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

8.8 OperatorPrecedence . . . . . . . . . . . . . . . . . . . . . . . . . 33

Page 4: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples iii

9 Looping 34

9.1 LoopingwithWhile . . . . . . . . . . . . . . . . . . . . . . . . . . 34

9.2 Break, Continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

9.3 LoopingwithFor . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

9.4 NestedLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

9.5 LoopingwithDo-While . . . . . . . . . . . . . . . . . . . . . . . . 39

10 StringsandCharacters 40

10.1 CharacterLiterals . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

10.2 AccessingStringCharacters . . . . . . . . . . . . . . . . . . . . . . 41

11 ConstantsandStaticMethods 42

11.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

11.2 StaticFields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

11.3 StaticMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

11.4 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

11.5 Visiblity, Namespaces, Import . . . . . . . . . . . . . . . . . . . . . 45

12 FileI/O 46

12.1 ReadFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

12.2 WritingFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

12.3 AppendingtoFiles . . . . . . . . . . . . . . . . . . . . . . . . . . 47

13 ObjectsandClasses 47

13.1 ObjectsandClasses . . . . . . . . . . . . . . . . . . . . . . . . . . 47

13.2 DefiningandUsingObjects . . . . . . . . . . . . . . . . . . . . . . 47

13.3 ObjectsversusStaticMethods . . . . . . . . . . . . . . . . . . . . . 49

13.4 Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

13.5 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Page 5: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples iv

13.6 In-MemoryFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

13.7 AnonymousClasses . . . . . . . . . . . . . . . . . . . . . . . . . . 51

13.8 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

13.9 EnumTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

13.10NestedClasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

14 Exceptions 55

14.1 CatchingExceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 55

14.2 ThrowingExceptions . . . . . . . . . . . . . . . . . . . . . . . . . 56

14.3 Finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

15 Arrays 58

15.1 ArrayLiterals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

15.2 LoopingthroughArrays . . . . . . . . . . . . . . . . . . . . . . . . 58

16 Collections 60

16.1 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

16.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

16.3 ListMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

16.4 PrimitiveCollections . . . . . . . . . . . . . . . . . . . . . . . . . 62

16.5 WrapperObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

16.6 Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

16.7 MapMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

16.8 MapTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

16.9 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

16.10SetMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

16.11SetTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Page 6: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples v

17 RegularExpressions 68

17.1 RegularExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . 68

17.2 PatternMatching . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

17.3 RegexSummary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

17.4 Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

17.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

18 SystemInteraction 72

18.1 CommandLineArguments . . . . . . . . . . . . . . . . . . . . . . 72

18.2 CapturingCommandOutput . . . . . . . . . . . . . . . . . . . . . 72

19 MoreEclipse 73

19.1 AddingThirdPartyJarFiles . . . . . . . . . . . . . . . . . . . . . . 73

19.2 DebuggingUsingBreakPoints . . . . . . . . . . . . . . . . . . . . 75

19.3 Refactorings: Extract-Method, Extract-Variable . . . . . . . . . . . . 75

20 WebClient 75

20.1 GettingWebContentFromGET Requests . . . . . . . . . . . . . . . 75

20.2 PassingParameterstoPOST Requests . . . . . . . . . . . . . . . . . 76

20.3 RealtimeStockQuotes . . . . . . . . . . . . . . . . . . . . . . . . 76

21 DatabaseUsingJDBC 78

21.1 TestingJDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

21.2 VerifyingDatabaseContents . . . . . . . . . . . . . . . . . . . . . 80

22 JavaUI 81

22.1 TipCalculatorwithUI . . . . . . . . . . . . . . . . . . . . . . . . . 81

Page 7: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 1

1 Introduction

1.1 Instructor

• AsimJalis

• HasworkedassoftwareengineeratMicrosoft, Hewlett-Packard, andSalesforce.

• http://linkedin.com/in/asimjalis

1.2 Introductions

• Whatisyourname? Whatdoyoudo?

• Howareyouplanningtousewhatyoulearnhere?

• Whatisyourperfectoutcome?

1.3 Hands-OnLearning

• Howwillthiscoursework?

– Hands-onclass.

– Learnbydoing.

• Whyhands-on?

– Helpsyougetmostoutofclass.

– Youinteractwithmaterialmoredeeply, learn.

– Encouragessmallmistakes, fasterlearning.

– Helpsgetissuesresolvedhere, now.

– Afterwardsyouretaintheexperience.

2 HistoryofJava

2.1 JavaVersions

Page 8: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 2

Version Released Notes

JDK Alpha/Beta 1995 SunannouncedJavainSeptember23, 1995.

JDK 1.0 January23, 1996 OriginallycalledOak(namedaftertheoaktreeoutsideJamesGosling’soffice). RenamedtoJava1inJDK 1.0.2.

JDK 1.1 February19, 1997 IntroducedAWT eventmodel, innerclass, JavaBean, JDBC,andRMI.

J2SE 1.2 December8, 1998 CodenamePlayground. Rebrandedas”Java2”andrenamedJDK toJ2SE (Java2StandardEdition). AlsoreleasedJ2EE (Java2EnterpriseEdition)andJ2ME (Java2MicroEdition). IncludedJFC (JavaFoundationClasses-Swing, AccessibilityAPI,Java2D,PluggableLookandFeelandDragandDrop). IntroducedCollectionFrameworkandJIT compiler.

J2SE 1.3 May8, 2000 CodenameKestrel. IntroducedHotspotJVM.

J2SE 1.4 February6, 2002 CodenameMerlin. Introducedassert, non-blockingIO (nio), loggingAPI,imageIO,Javawebstart, regularexpressionsupport.

J2SE 5.0 September30, 2004 CodenameTiger. Officiallycalled5.0insteadof1.5. Introducedgenerics, autoboxing/unboxing, annotation, enum, varargs, for-eachloop, staticimport.

JavaSE 6 December11, 2006 CodenameMustang. RenamedJ2SE toJavaSE (JavaStandardEdition).

JavaSE 7 July28, 2011 CodenameDolphin. FirstversionafterOraclepurchasedSun(calledOracleJDK).

JavaSE 8 Expected2013

2.2 SupportedPlatforms

WhichplatformsdoesJavarunon?

Sun’ssloganforJavahasbeen Writeonce, runanywhere orWORA.JavacoderunsunchangedonmostmajorhardwareplatformsandoperatingsystemsincludingWin-dows, Mac, Linux, etc.

2.3 WhyJava

WhyisJavainteresting?

• JavaLibraryEcosystem. Javahasalargelibraryecosystem.

• Concurrency. Javasupportsconcurrencyoutofthebox.

• MemoryManagement. Javatakescareofmemorymanagement.

• RuntimeChecking. Javadatastructurescheckforout-of-boundsexceptionsatruntimetopreventunauthorizedaccesstomemory. Javacodeis”safer”thancodeinC orC++.

Page 9: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 3

• Performance. Java’sperformanceiscomparabletoC andC++onmany bench-marks.

3 Installation

3.1 InstallingJava

Exercise: InstallJavaonyourmachine.

Solution:

• IfyouareonaMacJavacomespreinstalled.

• IfyouareonWindowsgotothislink http://www.oracle.com/technetwork/java/javase/downloads/index.html. IfyousearchGooglefor javajdkdownload thisisthefirstlink.

• Clickonthebuttonthatsays Java and Download.

• Acceptthelicenseagreementandthendownloadtheversionforyouroperatingsystem. x86means32-bit, and x64means64-bit. Ifyouarenotsurewhichonechoosex86(32-bit).

3.2 InstallingEclipse

Exercise: DownloadEclipse.

Solution:

• Goto http://www.eclipse.org/downloads.

• Downloadtheversioncalled EclipseIDE forJavaDevelopers foryouroperatingsystem.

• Ifyouarenotsurewhetheryoursystemis32-bitor64-bitdownloadthe32-bitversion.

Page 10: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 4

Exercise: InstallEclipse.

Solution(Mac):

• OntheMacthiswilldownloadasa tar.gz file.

• Inaterminalwindowrun tar xvzf eclipse-file.tar.gz.

• Thiswillproduceafoldercalled eclipse. Movethistothe Applications folderusingthiscommand.

mv eclipse /Applications

Solution(Windows):

• OnWindowsthiswilldownloadasa zip file.

• Thisfillwilluncompresstoproduceafoldercalled Eclipse.

• Savethistothe C: driveorthedesktop.

4 Basics

4.1 HelloWorld

Exercise: Createahelloworldprogramonthecommandline.

Solution:

• Createafilecalled Hello.java withthesecontents.

public class Hello {public static void main(String[] args) {

System.out.println("Hello, world!");}

}

• Compileitbytypingthisintheconsole.

Page 11: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 5

javac Hello.java

• Notethatthecompilerhascreatedafilecalled Hello.class inthecurrentfolder.

• Runitbytypingthisintheconsole.

java -cp . Hello

Notes:

• Javaseestheworldorganizedintoclasses. Forexample Hello isaclass.

• Thecodelivesinfunctionswiththeclasses. Here main isafunction.

• javac compilestheprogramandgeneratesthe Hello.class file.

• java runsthe Hello.class file.

• -cp standsfor classpath. Thistells java wheretolookfortheclassfile.

• When java starts it looks for the main function in theclassnamethat itwasinvokedwith. Thenitruns main.

4.2 HelloWorldEclipse

Exercise: CreateahelloworldprograminEclipse.

Solution:

• StartEclipse.

• In Selectaworkspace choosethedefaultworkspace. Click OK.

• Clickthe Workbench icon, anarrowcurvingbackwards. Whenyouhoveronthisiconitwillsay Workbench.

• Clickon File --> New --> JavaProject. For Projectname use demo. Click Finish.

• Clickon File --> New --> Package. For Name use core. Click Finish.

• Clickon File --> New --> Class. For Name use Hello. Click Finish.

Page 12: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 6

• The Hello.java filelookslikethis.

package core;

public class Hello {

}

• Changeittothis.

package core;

public class Hello {public static void main(String[] args) {

System.out.println("Hello, world!");}

}

• Clickon Run --> Run. In RunAs select JavaApplication. Click OK.

• Theapplicationwillrun. Youwillsee Hello, world! printedoutintheconsolebelow.

Notes:

• Under thehoodEclipse isdoing thesamethings thatweweredoingon thecommandline. However, itautomatesandstreamlinestherepetitiveparts.

• Eclipsehasautocomplete. Type Syst andthentype Control-Space toseetheautocompleteoptions.

• Eclipsemakesiteasytorenamepackages, classes, functions.

4.3 EclipseViews

ThepanesinEclipsearecalled views. Youcandragthemanddockthemondifferentcorners.

Page 13: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 7

Eclipsealsohasseveralperspectives. Inparticularthe Java and JavaBrowsing onesareusefulforeditingcode.

Exercise: Explorethedifferentperspectives.

Exercise: RestoreEclipseviewstotheiroriginalsettings.

Solution:

Select Window --> ResetPerspective.

4.4 Projects, Packages, Classes

Whyaretheresomanylevels?

• Javaismeantforlargeprojects.

• Projects, packages, andclassesgiveyouagoodlayeredhierarchytoorganizeprojectsspreadoutovermanyteams.

• Projectscontaintheentireapplication. Thinkoftheprojectasasinglefilethatwillbedeployedtoacustomersite.

• Packagesaregroupsofclassesthatarelogicallyrelated. Forexample, allthedatabaseclassesmightbeinasinglepackage.

• Thinkofpackagesasareacodes, andclassesasindividualphonenumbers.

• Classesarecollectionsoffunctionsanddata. ThesearethebuildingblocksofJavaprograms.

4.5 ProgramStructure

Exercise: Createaprogramthatgreetstheuserbyname.

Solution:

• CreateaprojectinEclipsecalled demo.

• Createapackagecalled core.

Page 14: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 8

• Createaclasscalled Util inthepackage.

• Putthecontentsat https://gist.github.com/asimjalis/5475179 intothisfile.

• Createaclassinthefoldercalled Demo.

• Addthefollowingtoit.

package core;

public class Demo {public static void main(String[] args) {

String name =Util.prompt("Enter your name: ");

Util.print("Hello " + name);}

}

• RuntheprogramthroughEclipse.

Notes:

• Javaclassesareplacedinpackages. Theseclassesareinapackagecalled core.

• Javastartsbyrunning main intheclassthatitisinvokedwith. Afterthistheprogramstatementsareexecutedsequentially.

• WhitespaceandindentationincodeisnotimportantandignoredbyJava. Itmakesthecodereadableforprogrammers.

• Allstatementsendwithasemicolon.

• Javastatementsconsistofassignments, functioncalls, andafewprogrammingconstructsthatwewilldiscuss.

• Functioncallsormethodcallshaveoneoftheseforms:

Page 15: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 9

// Class method.Class.method(arg1, arg2, arg3, ...)

// Instance method.instance.method(arg1, arg2, arg3, ...)

Exercise: Is Util.prompt aclassmethodoraninstancemethod?

Solution: Thisisaclassmethod. Classesconventionallystartwithupper-caseletters.Instancesstartwithlower-caseletters.

4.6 Comments

Exercise: Addcommentstothisprogram.

Solution:

package core;

/*** Greets user with name.*/

public class Demo {/*** Main.*/

public static void main(String[] args) {// Get user's name and greet him/her.String name =

Util.prompt("Enter your name: ");Util.print("Hello " + name);

}}

Notes:

• Singlelinecommentsareinsertedlikethis. Theseareusefulforcommentingcode.

Page 16: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 10

// This is a comment.

Thesecommentsstartat // andendattheendoftheline.

• Multilinecommentsareinsertedlikethis. Theseareusefulforlongerdescrip-tionsofalgorithms.

/** This is a multiline comment.*/

Thesecommentsstartat /* andendat */.

• Javadoccommentsareinsertedlikethisjustbeforeaclass, functionorvariable,describingitsintent.

/*** Describes a function.*/

Thesecommentsstartat /* andendat */.

5 Eclipse

5.1 Renaming

Whatis refactoring?

• Refactoringischangingthedesignofaprogramwithoutchangingitsbehavior.

• Thesimplestrefactoringisrenaming.

Exercise: Renamethepackagefrom core to core.examples. Makesurethepro-gramruns. Thenrevertthechange.

Solution:

• Right-clickonthepackage, andselect Refactor --> Rename.

Page 17: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 11

• Typeinthenewpackagenameandthenchooseallthedefaultsettings.

Notes:

• Youcanusethesamefeaturetorenameprojects, classes, methods. Goahead.Tryit.

• Eclipsedoesalotofworkforyouduringtherenamewhichwouldbedifficulttodobyhand. Inarename, youhavetorenameandmovedirectoriesandfiles,andalsomodifythecodethatreferstotheoldnames.

• Eclipsedoesallthis. Andbecauseitisautomateditissaferthaniftherefactoringwasdonebyhand.

5.2 Exporting

Exercise: Exporttheprojectandrunitfromthecommandline.

Solution:

• Right-clicktheproject.

• Select Export. Searchfor jar. Choose RunnableJAR file. Click Next.

• For Launchconfiguration specifytheclassyouwanttorun.

• For Exportdestination specifythefullpathtoajarfilesuchas demo.jar.

• Choosethedefaultsfortheotheroptions.

• Runtheprogrambytypingontheconsole,

java -jar demo.jar

Page 18: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 12

6 PrimitiveDataTypes

6.1 IntegersandFloating-PointNumbers

ThemostbasicdatatypeinJavaisthenumber. Javahasbothintegersaswellasfloatingpointnumbers. Youcanenternumbersliterallyintotheshelltoseetheirvalues.

Exercise: Guessthevaluesandtypesofthesenumberliterals: 123, 0x10, 010, 0, 1.1,1.1e3, 0.0

Solution:

Literal Value Type

123 123 int

0x10 16 int

010 8 int

0 0 int

1.1 1.1 double

1.1e3 1100.0 double

0.0 0.0 double

6.2 Variables, Types, Assignment

Exercise: Writeaprogramthatdividesarestaurantcheckof$43between3friends.

Solution:

public static void main(String[] args) {splitCheck();

}

public static void splitCheck() {int persons = 3;double amount = 43.0;

Page 19: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 13

double split = amount / persons;System.out.println(

"Amount per person: "+ split);

}

Notes:

• Javastoresdatainvariables.

• Allvariablesmustbedeclaredwiththeirtypesthefirsttimetheyareused.

• The = istheassignmentoperator. Ittakesavariableonitsleftandanexpressiononitsright. Theexpressioncanbeanyarithmeticexpressionofvariablesorfunctions.

• The = operatorwritesthevalueoftheexpressionontherightintothevariableontheleft.

• Subtlepoint: = indicatesassignment, not equality. Itisanaction.

6.3 NamingConventions

Whatarevariablenamingconventions?

• Examplesofvariablenames: price, pizzaToppingCount, startDate.

• Variablesnamescancontainletters, numbers, andunderscores. Thefirstchar-acterofthenamemustbealetteroranunderscore.

• TheJavaconventionistouse camel-case names. Soavariablelike startDateshouldnotbewrittenin snake-case as start_date.

• Variablenamesand functionnamesstartwith lower-case letters, whileclassnamesstartwithupper-caseletters.

Hereisasummaryofthenamingconventions.

Page 20: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 14

Entity Convention Example

Constant snake_case EARTH_RADIUS_MILES

Variable camelCase secondsBeforeLaunch

Function camelCase launchSpaceShuttle

Class PascalCase ShuttleCamera

Package snake_case shuttle.camera.filter_algorithms

Project snake_case space_shuttle_avionics

6.4 PrintfandFormat

Exercise: Writeaprogramthatdividesarestaurantcheckof$43between3friends.Printtheoutputwith2decimalplaces, andadollarsign.

Solution:

public static void splitCheck2() {int persons = 3;double amount = 43.0;double split = amount / persons;System.out.printf(

"Amount per person: $%.2f",split);

}

Notes:

• Solution2printstheoutputmorecleanly. Itputsadollarsignontheresultandtrimsittotwodecimalplaces.

• Thefirstargumentfor printf istheformatstring. Thisisatemplatewhichhasplaceholdersforthevariablesthatarepassedinasadditionalarguments.

Whatarethe printf formatcodes?

Page 21: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 15

FormatCode Meaning

%d int asdecimal

%x int ashexadecimal

%f double

%s String

%b boolean

%n newlinecharacter

%c char

%% % characteritself

%.2f double with2digitsafterdecimalpoint

6.5 NumericOperators

WhatarithmeticoperatorsdoesJavahave?

Expression Result

a + b Adding a and b

a - b Subtracting b from a

a * b Multiplying a and b

a / b Dividing a by b

a % b Remainderofdividing a by b

Notes:

• Theseoperatorsdonotchangethevalueof a and b.

• Theyproduceanewvaluewhichcanbeassignedtoavariable.

Page 22: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 16

• In x = a + b thevalueof a and b arenotchanged. Onlythevalueof x. Onlythevariabletotheleftof = changes.

• Theonlywaytochangethevalueofavariableisthroughanassignment.

6.6 AssignmentOperators

Exercise: A large14”pizzaat ExtremePizza costs$14.45. Each topping is$1.70.Supposewewantjalapenos, olives, artichokehearts, andsun-driedtomatoes. Howmuchwillthetotalbe?

Solution1:

public static void pizzaPrice() {

double crust = 14.45;double topping = 1.70;

// Crust.double price = crust;

// Plus 4 toppings.price = price + topping;price = price + topping;price = price + topping;price = price + topping;

System.out.printf("Pizza Price: $%.2f\n",price);

}

Notes:

• A variablecanbeassignedtomultipletimes.

• A variablecanrecycleitsownpreviousvalueontheleftof =.

Page 23: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 17

• = isnotmathematicalequality. So price = price + topping isnotaparadox.

• = issimplyassignment.

Solution2:

public static void pizzaPrice2() {

double crust = 14.45;double topping = 1.70;

// Crust.double price = crust;

// Plus 4 toppings.price += topping;price += topping;price += topping;price += topping;

System.out.printf("Pizza Price: $%.2f\n",price);

}

Notes:

• Becausethepattern x = x + a occursalotthereisashort-handforit: x +=a.

• Readthisas: modify x byadding a toit.

• += iscalledanassignmentoperator.

• Itisarelativeof =.

• Ittoochangesthevalueofthevariableonlyonitslefthandside.

Whatarethedifferentassignmentoperators?

Page 24: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 18

Assignment Meaning

a = b Modify a bysettingitto b

a += b Modify a byadding b toit

a -= b Modify a bysubtracting b fromit

a *= b Modify a bymultiplying b withit

a /= b Modify a bydividingitby b

a %= b Modify a bysettingittotheremainderofdividingitby b

6.7 Increment/DecrementOperators

Exercise: Add$1tothepizzapriceasadollartipforthestaff.

Solution1:

price = price + 1;

Solution2:

price += 1;

Solution3:

price++;

Notes:

• Solution1andSolution2followfromourearliernotes.

• Solution3isanotherwaytoincrementby1. Thisoccursalotinprograms. Anytimeyouwanttocountsomethingyoucountby1. Sothereisaspecialnotationforitcalledthe increment operator.

Whatarethedifferent increment and decrement operators?

Page 25: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 19

Expression Meaning

++a Increment a andreturnitsnewvalue

a++ Increment a andreturnitsoldvalue

--a Decrement a andreturnitsnewvalue

a-- Decrement a andreturnitsoldvalue

Exercise: Whatwillbetheoutputofthiscode?

int i = 0;System.out.printf("%d %d %d\n", i++, i++, i++);

Exercise: Whatwillbetheoutputofthiscode?

int i = 0;System.out.printf("%d %d %d\n", ++i, ++i, ++i);

6.8 BitOperators

Withinthecomputernumbersarestoredinbytes. Eachbyteis8bits.

Howmanybytesareusedbythedifferentnumerictypes?

Type Bytes Min Max

char 2 0 65,535

boolean 1 0 1

byte 1 -128 127

short 2 -32,768 32,767

int 4 -2,147,483,648 2,147,483,647

long 8 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807

float 4 1.4e-45 3.4e+38

double 8 4.9e-324 1.8e+308

Page 26: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 20

Whatarethedifferentbitoperators?

Expression Meaning

a << 1 Shiftbitsof a leftby1

a >> 1 Shiftbitsof a rightby1

a >>> 1 Shiftbitsof a rightby1with0inleft-mostbit

a & b AND thebitsof a and b

a ˆ b XOR thebitsof a and b

a | b OR thebitsof a and b

~a NOT thebitsof a and b

Exercise: Colors are frequently stored as RGB values in browsers. For example0x112233 meansthecolor’s red valueis 0x11, green valueis 0x22, and blue valueis 0x33. Separateoutthered, green, andbluecomponentsofthiscolor.

Solution:

public static void colors() {

int rgb = 0x112233;int red = (rgb & 0xff0000) >> 16;int green = (rgb & 0x00ff00) >> 8;int blue = (rgb & 0x0000ff);System.out.printf("%x = %x %x %x",

rgb, red, green, blue);}

7 Strings

7.1 StringLiterals

Besidesintegersandfloating-pointnumbersyoucanalsousestringsasadatatype.Stringrepresenttext.

Page 27: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 21

Exercise: Createaprogramthatcombinesfirstandlastnamestocreatefullnames.

Solution:

String firstName = "Dmitri";String lastName = "Jones";String fullName = firstName + " " + lastName;

Notes:

• Stringsmarkedbydouble-quotes.

• Stringliteralscannotbespreadacrossmultiplelines.

• Stringscanbejoinedtogetherusing +.

• + producesanewstringanddoesnotchangethevalueofthestringspassedtoit.

7.2 StringAssignmentOperator

Exercise: Therewere3unauthorizedloginsintoasystem, at3:13AM,5:17AM,and6:59AM.Allofthemoccurredon1/13/12. Createasingleerrormessagewiththe3incidents.

Solution:

public static void loginErrors() {

String errors = "";errors += "[1/13/12 3:13 AM] Unauthorized login.\n";errors += "[1/13/12 5:17 AM] Unauthorized login.\n";errors += "[1/13/12 6:59 AM] Unauthorized login.\n";System.out.print(errors);

}

Notes:

Page 28: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 22

• += canbeusedtoaddtothevalueofanexistingstringvariable.

• "\n" producesanewlinecharacterinthestring.

• OnMac/Unixanewlineis "\n".

• OnWindowsanewlineis "\r\n".

• Togetnewlinesinaportablewayuse System.getProperty("line.separator").

Exercise: Createaprogramthatprintshelloandworldontwoseparatelinesandusesaportablenewlinesequence.

7.3 EscapeSequences

Whataresomeotherescapesequences?

Sequence Value

\t Tab

\n Newline

\r Carriagereturn

\' Single-quote

\" Double-quote

\\ Backslash

7.4 ConvertingBetweenStringsandNumbers

Exercise: Convertthestring "1234" intoanumber.

Solution:

String string = "1234";int intvalue = Integer.parseInt(string);System.out.printf("intValue=%d\n", intValue);

Page 29: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 23

Whatarethedifferentfunctionsforconvertingnumberstostrings?

Expression Value Meaning

Integer.parseInt("1234") 1234 Integervalueofstring "1234"

Integer.parseInt("101",2) 5 Integervalueofbinarystring "101"

Double.parseDouble("1234") 1234.0 Doublevalueofstring "1234"

Integer.toString(9) "9" Decimalstringvalueofinteger 9

Integer.toString(9,2) "1001" Binarystringvalueofinteger 9

Double.toString(1234) "1234.0" Stringvalueofdouble 1234.0

Notes:

• Youcanalsoconvertnumberstostringbyconcatenatingthemwithastring, likethis "" + 1234.

• However, unlessthisisnaturallyapartofalongerstringusingthe toStringfunctionsispreferred.

7.5 TipCalculator

Exercise: Writeatipcalculator. Asktheuserfortotalcheckamount, numberofpeople,andtiprate. Printoutthetotaltip, andtheamountperperson.

Solution:

public static void tipCalculator() {

double amount = Double.parseDouble(Util.prompt("Amount: "));

int people = Integer.parseInt(Util.prompt("People: "));

double tipRate = Double.parseDouble(Util.prompt("Tip Rate: "));

double tip = amount * tipRate / 100.0;

Page 30: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 24

double newAmount = amount + tip;double share = newAmount / people;System.out.printf(

"Amount: $%.2f\n" +"People: %d\n" +"Tip Rate: %.2f%%\n" +"Tip: $%.2f\n" +"Share: $%.2f\n",amount,people,tipRate,tip,share);

}

7.6 PopulationCalculator

Exercise: ThepopulationofCaliforniain2012was38,000,000andthegrowthratewas1%. Thepopulationcanbeestimatedas,

pop = popInitial *Math.pow(1 + growthRate, years);

Here years isthenumberofyearssince2012, popInitial isthepopulationin2012.Asktheuserfortheyeartheywanttoprojectoutuntilandpredictthepopulationforthespecifiedyear.

7.7 HousePrices

Exercise: Writeaprogramthatasksuserforcurrentpriceofhouse, appreciationrate,andnumberofyearstoprojectoutintothefuture. Theprogramprintsthepriceafterthespecifiednumberofyears. Iftheinitialpriceofahouseis priceInitial thenitsfinalpriceafteryearswillbe:

price = priceInitial *Math.pow(1 + rate, years);

Here rate istheappreciationrate.

Page 31: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 25

8 Branching

8.1 If, If-Else

Sofarourprogramhashadalinearlogic. Itstartsatthebeginning, runs, andterminates.Thereisnointelligenceordecisionmakingabilityinit.

Exercise: Writeacoin-flippingappthatprintsheadsortails.

Solution1:

public static void coin() {int flip = Util.randomInt(0,1);System.out.println(

"Coin: " + flip);}

Solution2:

public static void coin() {int flip = Util.randomInt(0,1);String flipOutcome;if (flip == 0) {

flipOutcome = "tails";}else {

flipOutcome = "heads";}System.out.println(

"Coin: " + flipOutcome);}

Notes:

• Solution2producesmoreuserfriendlyoutput.

Exercise: Writeaprogramthatcalculatesalettergradebasedonastudent’sGPA.

Page 32: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 26

Grade GPA Minimum

A 3.5

B 2.5

C 1.5

D 1.0

F 0.0

Solution:

public static void gpa() {double gpa =

Double.parseDouble(Util.prompt("GPA: "));

String grade;if (gpa >= 3.5) {

grade = "A";}else if (gpa >= 2.5) {

grade = "B";}else if (gpa >= 1.5) {

grade = "C";}else if (gpa >= 1.0) {

grade = "D";}else {

grade = "F";}System.out.printf(

"Grade: %s\n",grade);

}

Page 33: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 27

Notes:

• The if/else constructrepresentsaforkintheroad.

• Theprogramevaluateseachconditionandtakesthefirstbranchwhosecondi-tionistrue.

• Ifnoconditionistruethenittakesthe else clause.

• The else if andthe else areoptional.

• Soifnoconditionistrue, andthereisno else clausethenitignoresthewholeconstruct.

• gpa >= 3.5 isabooleanexpression. Itiseithertrueorfalse.

• >= isarelationaloperator.

8.2 RelationalOperators

Whatarethedifferentrelationaloperators?

RelationalOperators IsTrueWhen

a < b a islessthan b

a <= b a islessthanorequalto b

a > b a isgreatthan b

a >= b a isgreatthanorequalto b

a == b a isequalto b

a != b a isnotequalto b

Notes:

• Rememberthat = isassignmentandnotequality. Equalityis ==.

• Everyonetripsonthisseveraltimes.

Page 34: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 28

• Notethattheseoperatorsonlyworkonnumbersandnumber-likethings(char-actersandbytes). Theydon’tworkonstringsorotherJavatypes.

8.3 Booleans

Exercise: Amazonoffersfreeshippingifyouspend$25ormore. Computeabooleanvariablecalled isShippingFree, given sales.

Solution:

public void shippingFree() {double sales = 26.00;boolean isShippingFree =

sales >= 25;System.out.printf(

"isShippingFree=%b\n",isShippingFree);

}

8.4 BooleanOperators

Booleanexpressionshavevalues true or false. Theycanbecombinedwithlogicaland, or, and not operations.

Exercise: Createagameinwhichyouflipacointwice. Ifyougettwodifferentthings(headsandtails, ortailsandheads)youwin, otherwiseyoulose.

Solution:

public static void twoCoins() {int flip1 = Util.randomInt(0,1);int flip2 = Util.randomInt(0,1);boolean won =

(flip1 == 0 && flip2 == 1) ||(flip1 == 1 && flip2 == 0);

System.out.printf("flip1=%d\n" +"flip2=%d\n" +

Page 35: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 29

"won=%b\n",flip1, flip2, won);

}

Whatarethedifferentbooleanoperators?

Expression IsTrueWhen

a && b a is true and b is true

a || b a is true or b is true

!a a is false

Notes:

• The &&, || and ! operatorsonlycomputebooleanexpressions. Theydon’tchangethevalueofexistingvariables.

8.5 StringComparisonandEquality

Exercise: ConverttheairportcodeforBayAreaairportsintotheairportname.

Solution:

public static void airports() {String code = "SFO";String airport;if (code.equals("SFO")) {

airport = "San Francisco";}else if (code.equals("OAK")) {

airport = "Oakland";}else if (code.equals("SJC")) {

airport = "San Jose";}

Page 36: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 30

else {airport = "Unknown";

}

System.out.printf("airport=%s\n", airport);

}

Notes:

• == onlyworksforprimitiveandnumerictypes.

• Withnon-primitivenon-numerictypessuchas String (andallotherobjects),checkforequalityusingthe .equals functionratherthanusing ==.

Exercise: Turnthisintoaprogramthatgetstheairportcodefromtheuser.

8.6 TernaryOperator

Exercise: Writeacoinflippingappthatprintsoutheadsortails.

Solution1:

public static void coin() {int flip = Util.randomInt(0,1);String flipOutcome;if (flip == 0) {

flipOutcome = "tails";}else {

flipOutcome = "heads";}System.out.println(

"Coin: " + flipOutcome);}

Solution2:

Page 37: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 31

public static void coin() {int flip = Util.randomInt(0,1);String flipOutcome =

flip == 0 ? "tails" : "heads";System.out.println(

"Coin: " + flipOutcome);}

Notes:

• Theternaryoperatorletsyouwriteconditionalcodemoreconciselyforsimplerexpressions.

• Theternaryoperatorislikethe IF inExcel.

• a ? b : c. If a istrue, thisevaluatesto b. Otherwiseitevaluatesto c.

Exercise: ConverttheairportcodeforBayAreaairportsintotheairportname. Gettheairportcodefromtheuser.

Solution:

public static void airports2() {String code = Util.prompt(

"Airport code: ");String airport =

code.equals("SFO") ? "San Francisco" :code.equals("OAK") ? "Oakland" :code.equals("SJC") ? "San Jose" :"Unknown";

System.out.printf("airport=%s\n", airport);

}

Notes:

• Youcandothisusinganif-thenstatement. However, frequentlyifyouhavealistofcasesyoucandealwiththemwithatablebuiltusingternaryoperators.

Page 38: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 32

8.7 Switch

Exercise: Convertnumericdaysoftheweektowords.

Solution:

public static void daysToWords() {

String input = Util.prompt("Day (1-7): ");

int dayInt = Integer.parseInt(input);String day;switch (dayInt) {

case 1:day = "Sun";break;

case 2:day = "Mon";break;

case 3:day = "Tue";break;

case 4:day = "Wed";break;

case 5:day = "Thu";break;

case 6:day = "Fri";break;

case 7:day = "Sat";break;

default:day = "Unknown";break;

}

Page 39: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 33

System.out.printf("day=%s\n", day);

}

Notes:

• The switch statementisanotherwaytobranch.

• BeforeJava7 switch couldonlyhandlecasesthatwereintegers(orinteger-likesuchas enum whichwewillseelater). InJava7andlateryoucanusestringsaswell.

• The break isimportant. Ifitisleftouttheprogramwillexecutethefollowingcasesaswell.

8.8 OperatorPrecedence

Whatistheorderorprecedenceinwhichoperatorsareapplied?

Hereistheprecedenceindecreasingorder.

Operators Precedence

postfix i++ i--

unary ++i --i +i -i ~ !

multiplicative * / %

additive + -

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwiseAND &

bitwiseexclusiveOR ˆ

bitwiseinclusiveOR |

logicalAND &&

Page 40: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 34

logicalOR ||

ternary ? :

assignment = += -= *= /= %= &= ˆ= |= <<= >>= >>>=

Notes:

• Whileyoucanrelyontheprecedenceitissafertouseexplicitparenthesestocontrolprecedence.

• Thiswaythecodeisalsoeasiertounderstandforsomeoneelse.

9 Looping

9.1 LoopingwithWhile

Exercise: Pickanumberfrom1to10andthenprompttheusertoguessit.

Solution:

public static void guessNumber() {int number = Util.randomInt(1,10);int guess = -1;Util.print("I picked a number.");while (number != guess) {

String guessString = Util.prompt("Guess what number I picked: ");

guess =Integer.parseInt(guessString);

if (number == guess) {Util.print(

"Yes, you guessed right.");}else {

Util.print("You were wrong. " +

Page 41: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 35

"Try again.");}

}

Notes:

• Theprogramkeepsrunningthecodein the while blockuntil theconditionbecomesfalse.

• Youcanuse break tobreakoutofaloop.

• Youcanuse continue toskiptherestoftheblockandrestarttheloop.

Exercise: Theprogramshouldgivetheuserahintandmentionifthenumberishigherorlower.

Exercise: Eliminatetheinelegantdeclarationof guess outsidetheloopandthemag-icalvalueof -1. Dothisbyusing while (true) andthen break whentheuserguessescorrectly. Thiseliminatestheneedfortheearlydeclarationof guess.

9.2 Break, Continue

Exercise: Repeatedlyplaytheguessinggamefromthepreviousexerciseswiththeuser.Exittheprogramwhentheuserpresses "q".

Solution:

public static void guess() {OUTER_LOOP:while (true) {

// Pick number.int number = Util.randomInt(1, 10);System.out.println("Picked number");

// Loop until user guesses.while (true) {

// Get user's guess.

Page 42: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 36

String guessString = Util.prompt("Guess: ");

// Exit if user types "q".if (guessString.equals("q")) {

System.out.println("Exiting");break OUTER_LOOP;

}

// Restart if user types "r".if (guessString.equals("r") {

System.out.println("Restarting");continue OUTER_LOOP;

}

// Check guess.int guess = Integer.parseInt(guessString);if (guess == number) {

System.out.println("You're right!");break;

} else if (guess < number) {System.out.println("Guess too low");

} else {System.out.println("Guess too high");

}}

}}

Notes:

• Labelsareusefulwhenyouhavenestedloopsandyouwant tobreakoutofmultipleloopsatthesametime, orrestartanouterloopfromaninnerloop.

• Labeltheloopyouwanttobreakoutofwithalabelsuchas OUTER_LOOP:.

• Then break OUTER_LOOP willbreakoutoftheloopwiththegivenlabel.

• Also continue OUTER_LOOP willrestarttheouterloop.

Page 43: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 37

9.3 LoopingwithFor

Exercise: Printthemultiplicationtablefor 7.

Solution1:

public static void table1() {int number = 7;

int times = 1;while (times <= 10) {

int product = number * times;System.out.printf("%d * %d = %d %n",

number, times, product);times++;

}}

Solution2:

public static void table2() {int number = 7;

for (times = 1 ; times <= 10 ; ++times) {int product = number * times;System.out.printf("%d * %d = %d %n",

number, times, product);}

}

Notes:

• The for loopisequivalenttothe while loop. Exceptitgroupstheinitializa-tion, condition, andincrementstepsatthebeginning. Thiswayitiseasiertorememberallofthem.

• Youcanbreakoutofa for loopwith break.

Page 44: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 38

• Youcanrestarta for loopatthenextincrementalvaluewith continue.

• Ifyouareusing the for loop forcounting theconvention is touse i as theindex.

Exercise: Flipacoin100times, reportthetotalnumberofheadsandtails, andreportwhichsidewon.

Solution:

public static void manyFlips() {int flipCount = 100;int heads = 0;int tails = 0;for (int i = 0 ; i < flipCount ; ++i) {

int flip = Util.randomInt(0,1);if (flip == 0){ tails++; }else{ heads++; }

}

String winner =heads > tails ? "Heads" :tails > heads ? "Tails" :

"Draw";

System.out.printf("Heads: %d\n" +"Tails: %d\n" +"Winner: %s\n",heads, tails, winner);

}

Notes:

• If youareusing the for loop todo something N numberof times, then theconventionistotake i from0until N - 1.

Page 45: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 39

9.4 NestedLoops

Exercise: Writethemultiplicationtablesforallnumbersfrom1through10.

Solution:

public static void tables() {for (int i = 1 ; i <= 10 ; ++i) {

for (int j = 1 ; j <= 10 ; ++j) {System.out.printf(

"%d * %d = %d\n",i, j, i * j);

}}

}

9.5 LoopingwithDo-While

Exercise: Pickanumberfrom1to10andthenprompttheusertoguessit. Stopiftheuserguesses0oranegativenumber.

Solution:

public static void guessNumber2() {int number = Util.randomInt(1,10);Util.print("I picked a number.");int guess = -1;do {

String guessString = Util.prompt("Guess what number I picked: ");

guess = Integer.parseInt(guessString);if (number == guess) {

Util.print("Yes, you guessed right.");

}else if (number < 0) {

Util.print("Quitting.");}

Page 46: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 40

else {Util.print(

"You were wrong. " +"Try again.");

}}while (guess > 0);

}

Notes:

• Do-whilepushesthecheckattheendoftheloopinsteadofthebeginning.

• Dependingontheproblemyouaresolving, sometimesthisleadstoacleanersolution.

10 StringsandCharacters

10.1 CharacterLiterals

Exercise: Assume a is1, b is2, andsoon. Addupallthelettersinawordandfindoutitsnumericalvalue.

Solution:

public static void numberValue() {while (true) {

// Get user input.String input =

Util.prompt("Text: ");

// Lower-case it.input = input.toLowerCase();

// Check for quit.if (input.equals("q"))

Page 47: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 41

break;

// Calculate value of text.int value = 0;for (int i = 0

; i < input.length(); ++i) {// Get char at position i.char c = input.charAt(i);

// Is it a letter?if ('a' <= c && c <= 'z')

value += c - 'a' + 1;}

// Print the final value.System.out.println(

"Value: " + value);}

}

Notes:

• Stringsaremadeupofcharacters. Youcangetthecharacterataspecificpositioninastringusingthe charAt function.

• Charactersbehavelikeintegers. Youcancomparethemagainstothercharac-ters.

• Youcansubtractcharactersfromeachothertogettheirrelativedistance.

• Charactersarewrittenwithsinglequotes. Forexample, 'a'.

10.2 AccessingStringCharacters

Exercise: Writeaprogramthattakesabinarystringof0’sand1’sandthenprintsitsdecimalvalue.

Solution:

Page 48: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 42

public static void binaryValue() {while (true) {

// Get user input.String input = Util.prompt(

"Enter binary number: ");

// Check for quit.if (input.equals("q")) {

break;}

// Calculate valueint value = 0;int multiplier = 1;for (int i = input.length() - 1 ; i >= 0 ; --i) {

char c = input.charAt(i);int x = c == '0' ? 0 : 1;value += multiplier * x;multiplier *= 2;

}Util.print("Value: " + value);

}}

Notes:

• Characterscanbecomparedforequalityusing ==.

• Youcanscanastringfrombeginningtoendorbackwards, whicheverworksmoreelegantlyforyouralgorithm.

11 ConstantsandStaticMethods

11.1 Constants

Exercise: Addaconstant PI toaclasscalled Constants.Solution:

Page 49: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 43

public class Constants {public static final double PI = 3.141529;

public static void main(String[] args) {System.out.println(

"PI = " + Constants.PI);}

}

11.2 StaticFields

Exercise: Addastaticfieldwhichspecifieswhether theprogramisrunningin trialmodeorofficiallyregistered.

Solution:

public class License {public static boolean isRegistered = false;

public static void main(String[] args) {System.out.println(

"isRegistered= " +License.isRegistered);

}}

11.3 StaticMethods

Exercise: Writeafunctionthatasksauserhisorhernameandthenreturnsagreeting.

Solution:

public static String getGreeting(String name) {String greeting = "Hello, " + name;return greeting;

}

Page 50: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 44

public static void testGetGreeting() {String greeting =

getGreeting("Dmitri");System.out.printf(greeting);

}

Notes:

• The public keywordsaysthatthefunctioncanbeaccessedfromanywhere.

• The static keywordsaysthatthisfunctionshouldbeinvokedas Class.function,where Class isthenameoftheclassthatthisfunctionisin.

• Functionsandmethodsareinterchangeablenamesforthesameconcept. Non-staticfunctionsareusuallycalledmethods.

• String beforethefunctionnameindicatesthereturntype.

• Ifafunctionhasareturntypeof void itdoesnotreturnanything. Itisaproce-durethatdoessomeworkandends.

• String name istheargumentthatispassedtothefunction.

• Withinthefunctionthe return greeting isrequiredbecausethefunctiondeclarationpromisedthatitwasgoingtoreturna String object.

• Theargumentsthatarepassedtothefunctionwhenitisinvokedareaccessiblewithinthefunctionthroughtheparameternames.

11.4 Overloading

Exercise: Writeafunctionthattakesafirstnameandalastnameandreturnsagreeting.

Solution:

public static String getGreeting(String firstName,String lastName) {

String greeting = "Hello, " +

Page 51: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 45

firstName + " " + lastName;return greeting;

}

public static void testGetGreeting() {String greeting =

getGreeting("Dmitri", "Jones");System.out.printf(greeting);

}

Notes:

• Multiplefunctionscancoexistiftheytakedifferenttypesofarguments. Sothesetwo getGreeting functionscanliveinthesameclass.

11.5 Visiblity, Namespaces, Import

Whatarethelevelsofvisibilitiesforfunctions?

Visibility Keyword Visible

Default Inclassandpackage

Public public Inclass, package, andotherpackages

Private private Inclass

Protected protected Inclassandsubclasses

Exercise: Canwemakethefunctionsinthepreviousexercisedefault? Canwemakethemprivate?

Notes:

• Namespacesaredeterminedbypackagenames.

• A classmayrefertootherclasseswithinitspackagedirectlybytheirnames.

Page 52: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 46

• A classmayrefertootherclassesoutsideitspackageeitherbyfullyspecifyingthepackagename. Forexample com.otherpackage.Class.

• import com.otherpackage.Class lets Class bereferredtodirectly.

• import com.otherpackage.* letsallclassesinthatpackagebereferredtodirectly.

• import static com.otherpackage.Class.* letsallmembersof Classbereferredtodirectly.

• import static com.otherpackage.Class.field lets field insideClass bereferredtodirectly.

Whatarethedifferentkindsofimports?

ImportSyntax Meaning

import core.util.Math Useclass Math inpackage core.util as Math

import core.util.* Useallclassesinpackage core.util directly

import static core.util.Math.PI Usemember PI in Math directly

import static core.util.Math.* Useallfunctionsandfieldsof Math directly

Exercise: Createaclasscalled Constants. Create NL as System.getProperty("line.separator").Staticallyimportitandprintit.

Exercise: Addthecontant PI to Constants.

12 FileI/O

12.1 ReadFiles

Exercise: LookatthecodeforreadingafileinUtil.java. Usethattocreatecodetoreadafileline-by-line.

Page 53: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 47

12.2 WritingFiles

Exercise: LookatthecodeforwritingafileinUtil.java.

12.3 AppendingtoFiles

Exercise: LookatthecodeforappendingtoafileinUtil.java.

13 ObjectsandClasses

13.1 ObjectsandClasses

Whydoweneedobjectsandclasses?

• Inproceduralprogramming, theprogramstateisglobal. Anyfunctioncanac-cessanyglobalvariable.

• Objectssplituptheglobalstateintosmallerchunks.

• Thiswayifthereareissueswithaprogramitiseasiertonarrowitdowntoonepartofthecode.

• Object-orientedprogramminghasmadepossiblethecomplexsoftwaresystemsthatwehavetoday. Theinternet, thesmartphone, thevideogamingconsoles,allrelyonobject-orientedprogrammingformanagingcomplexity.

13.2 DefiningandUsingObjects

Exercise: CreateaFileobjectthatisinitializedwithapath, andallowsausertoreadthefile, writethefile, andappendtothefile.

Solution:

CreateaFileclass.

Page 54: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 48

public class File {private String path;

public File(String path) {this.path = path;

}

public String read() {return Util.fileRead(path);

}

public void write(String contents) {Util.fileWrite(path, contents);

}

public void append(String contents) {Util.fileAppend(path, contents);

}}

Nowtestit.

public static void fileTest() {File file = new File("/tmp/file123");file.write("Line 1\n");file.append("Line 2\n");Util.print("File:\n" + file.read());

}

Notes:

• Theinstancevariablesofanobjectarelistedinsidetheclasswiththemethods.Theyarealsoknownasfields.

• Allnon-staticmethodsinaclasshaveaccesstoitsinstancevariablesorfields.

• Theconstructorhasthesamenameastheclass. Itsetthefieldstotheirinitialvalues.

Page 55: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 49

• Todisambiguatetheparameter path fromthefield path themethodscanusethis.path whichalwaysreferstothefield.

• Ifthereisnoparameterorlocalvariablewiththatname path referstothefieldaswell.

• Theobjectiscreatedusing new File(path), whichcallstheconstructor.

• A classcanhavemultipleconstructorsaslongastheyhavedifferentparameters(bycountorbytype).

13.3 ObjectsversusStaticMethods

Whygodoallthistroubleofcreatingclasses? Whynotjusthavestaticmethods?

• Theobject File hidesitsimplementation.

• Youcancompletelyguttheimplementationandtheusersoftheclasswillnotknow.

• Forexample, insteadofstoringthecontentsonthediskyoucouldstorethemonAmazonS3inthecloudoronDropbox.

• Objects create this abstractionboundarybetween the code that implementsfunctionalityandthecodethatusesit.

• Thecodethatusesanobjecttreatsitlikeablackbox.

• Theseobjects are like adriverdrivinga carwithoutunderstandinghow theengineworks.

13.4 Visibility

Whichmethodsandfieldsonanobjectcanothercodeaccess?

• Generallyothercodecanaccessmethodsandfieldsmarked public.

• Code in the samepackagewillalsobeable toaccessfields thataredefault(meaningtheyhavenovisibilityqualifiers).

• Tomakesurenooneoutsideaclasscanaccessafieldmarkit private.

Page 56: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 50

13.5 Interfaces

Exercise: DefineaStorageclassofwhichFileisaspecificinstance.

Solution:

InStorage.java,

public interface Storage {String read();void write(String contents);void append(String contents);

}

InFile.java,

public File implements Storage {// Other code remains unchanged.

}

IntestingFile, replacethe File declarationwith Storage declaration.

Notes:

• Interfacesdefinetheminimalcontractaclasshastofulfillbeforeitcanbeusedbyothercodeasanimplementationoftheinterface.

• Ifyourcodereliesoninterfacesratherthanconcreteclassesyoucaneasilypassindifferentimplementationsindifferentscenarios.

• Forexample, youcanpassinacloudstorageclassinsteadofadisk-basedfilestorageclass.

• Fortestingyoucanpassinamemory-basedstorageclass.

Page 57: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 51

13.6 In-MemoryFile

Exercise: Implementamemory-basedimplementationoftheStorageinterface.

Solution:

package demo;

public class MemoryFileimplements Storage {

private String contents;

public String read() {return contents;

}

public void write(String contents) {this.contents = contents;

}

public void append(String contents) {this.contents += contents;

}}

13.7 AnonymousClasses

Exercise: Implementamemory-basedimplementationoftheStorageinterfaceusingananonymousclass.

Solution:

public static void testStorage() {Storage storage = new Storage() {

private String contents;

public String read() {return contents;

Page 58: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 52

}

public void write(String contents) {this.contents = contents;

}

public void append(String contents) {this.contents += contents;

}};

storage.write("Line 1\n");storage.append("Line 2\n");Util.print("Storage:\n" + storage.read());

}

13.8 Inheritance

Exercise: Createaclasscalled AppendingFile whichappendsbothonwriteandonappend.

Solution:

package demo;

public class AppendingFile extends File {public AppendingFile(String path) {

super(path);}

public void write(String contents) {append(contents);

}}

Page 59: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 53

13.9 EnumTypes

Exercise: Createaclass forcalculatingstatesales taxdependingonthecustomer’sstate.

Solution1:

public enum State {CA,WA,OR

}

public static double getSalesTax(State state, double amount) {double taxRate =

state == State.CA ? 0.075 :state == State.WA ? 0.065 :state == State.OR ? 0.000 :

0.000;return amount * taxRate;

}

public static void checkState() {System.out.println(

getSalesTax(State.CA, 30.0));}

Solution2:

public enum State {CA(0.075),WA(0.065),OR(0.000),UNKNOWN(0.000);

private final double taxRate;

Page 60: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 54

private State(double taxRate) {this.taxRate = taxRate;

}

public double getSalesTax(double amount) {

return amount * taxRate;}

}

public static void checkState() {System.out.println(

State.CA.getSalesTax(30.0));}

Notes:

• Solution1usesenumtypesinthesimplestwayasasimpleenumeratedtype.

• Solution2addssomefunctionalityanddatatoeachenumvalueaswell.

13.10 NestedClasses

Javaletsyounestclassesinsideeachother. Thisisusefulforenumtypesandothertypicallysmallclasses.

Exercise: Createan App class containinganother class called Coin which returnsCoin.Head and Coin.Tails.

Solution:

public class App {public static void main(String[] args) {

Flipper flipper =new Flipper();

System.out.println(flipper.flip());

Page 61: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 55

}

public static enum Coin {HEADS,TAILS;

}

public static class Flipper {Coin flip() {

int flip =Util.randomInt(0,1);

if (flip == 0)return Coin.TAILS;

elsereturn Coin.HEADS;

}}

}

14 Exceptions

14.1 CatchingExceptions

Exercise: Writeafunction promptIntwhichrepeatedlyaskstheuserforan int untiltheusersubmitsavalid int.

Solution:

public static int promptInt(String prompt) {while (true) {

try {String input =

Util.prompt(prompt);return Integer.parseInt(input);

}catch(Exception e) {

Util.print("Invalid input");

Page 62: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 56

}}

}

public static void promptIntTest() {int intValue = promptInt("Integer: ");System.out.println(intValue);

}

Notes:

• Youcancatchallexceptionsbycatching Exception. Youcanalsocatchnar-rowertypesofexceptions.

• A catchlistingaparticularexceptionwillcatchthatexceptiontypeaswellasallofitssubclasses.

Exercise: Havetwocatchclauses: onefor NumberFormatException andanotheroneforallotherexceptions.

14.2 ThrowingExceptions

Exercise: Createaprogramthatthrowsanexceptionrandomlywithaprobabilityof0.5.

Solution:

public static void randomFailure() {if (Util.randomInt(0,1) == 0) {

throw new RuntimeException("Random exception.");}

}

Notes:

• Ifyouthrowa RuntimeException youdonothavetodeclareitinthemethodsignature.

• Testthisbychangingtheexceptiontypeto Exception.

Page 63: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 57

14.3 Finally

Exercise: Createaprogramthatthrowsanexceptionrandomlywithaprobabilityof0.5, andprintsamessagetoshowifexceptionwasthrown.

Solution:

public static void randomFailure() {try {

if (Util.randomInt(0,1) == 0) {throw new RuntimeException("Random exception.");

}System.out.println("No Exception");

}catch (Exception e) {

System.out.println("Exception!");}finally {

System.out.println("Returning");}

}

Notes:

• Codeinthe finally blockisalwaysexecutedregardlessofwhetheranexcep-tionisthrownornot.

• Thisisusefulforcleaningupaftercodeisrun. Thecleanupmustoccurregard-lessofwhetherthecodethrowsanexceptionornot.

• Forexample, whenyouopenafilestreamoradatabasehandle, use finallytoclosethem.

Page 64: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 58

15 Arrays

15.1 ArrayLiterals

Exercise: Defineanarraycontainingthewordsfirst, second, etc. Whenauserpassesinavalueconvertittoaword. Createafunctionforthis.

Solution:

public static void numberNames() {String[] numberNames = {

"one","two","three","four",

};String numberString = Util.prompt(

"Enter number (1-4): ");int number =

Integer.parseInt(numberString);int index = number - 1;String numberName = numberNames[index];System.out.printf(

"You typed %s.\n",numberName);

}

Notes:

• Youcandefinearraysandpopulatetheminyourcode.

• Arrayshavefixedlength. Youcannotaddmoreelementstothem.

15.2 LoopingthroughArrays

Exercise: WriteaprogramthatprintsouttheStarWarsmovietitles.

Page 65: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 59

Year Episode MovieTitle

1977 EpisodeIV A NewHope

1980 EpisodeV TheEmpireStrikesBack

1983 EpisodeVI ReturnOfTheJedi

1999 EpisodeI ThePhantomMenace

2002 EpisodeII AttackOfTheClones

2005 EpisodeIII RevengeOfTheSith

Solution1:

public static void starWars1() {String[] movies = {

"A New Hope","The Empire Strikes Back","Return Of The Jedi","The Phantom Menace","Attack Of The Clones","Revenge Of The Sith"

};

for (int i = 0 ; i < movies.length ; ++i) {System.out.printf(

"%d. %s\n",i, movies[i]);

}}

Solution2:

public static void starWars2() {String[] movies = {

"A New Hope",

Page 66: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 60

"The Empire Strikes Back","Return Of The Jedi","The Phantom Menace","Attack Of The Clones","Revenge Of The Sith"

};

for (String movie : movies) {System.out.printf(

"%s\n",movie);

}}

Notes:

• Solution2ismoreconcise. However, itdoesnothaveaccesstotheindex.

• IfyouneedtheindexyoushoulduseSolution1. OtherwiseuseSolution2.

16 Collections

16.1 Collections

Whatarecollections?

Collectionsaredatastructuresforholdingmultipleobjectsinonevariable.

16.2 Lists

Exercise: PrintthenamesofBayAreacounties:

• Alameda• ContraCosta• SanFrancisco

Page 67: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 61

• SanMateo• SantaClara

Solution:

public static void counties() {// Create array list.List<String> counties =

new ArrayList<String>();

// Add counties to it.counties.add("Alameda");counties.add("Contra Costa");counties.add("San Francisco");counties.add("San Mateo");counties.add("Santa Clara");

// Print all counties.for (String county : counties) {

System.out.println(county);}

}

Notes:

• Thelistneedstohaveatype, inthiscase String.

• List istheinterface, while ArrayList istheimplementation.

• Wecoulddeclarethe counties objectasbeingoftype ArrayList<String>aswellifwewantedto.

• Whatistheadvantageofdeclaringita List<String>? Wecanswapouttheimplementationlaterwithoutchangingalotofthecode.

16.3 ListMethods

Whatareuseful List methods?

Page 68: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 62

Method Result

list.add(item) Add item to list

list.get(i) Gets item atindex i

list.size() Getsnumberofitemsinlist

16.4 PrimitiveCollections

Exercise: Createalistofthenumbers1, 2, 3, andprintthem.

Solution:

public static void numberList() {// Create array list.List<Integer> numbers =

new ArrayList<Integer>();

// Add numbers to it.numbers.add(1);numbers.add(2);numbers.add(3);

// Print all numbers.for (int number : numbers) {

System.out.println(number);}

}

Notes:

• Collectiontypescanonlystoreobjects, notprimitivetypes.

• Soeveryprimitivetypehasawrapperobject. Forexample, int hasawrapperobjectcalled Integer.

Page 69: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 63

• Javaautomaticallyconvertstheprimitivedatatypeintoitswrapperobjectandback. Thisiscalledboxingandunboxing, respectively.

• Youonlyneedtousethewrapperobjectinthedeclarations.

16.5 WrapperObjects

Whatarewrapperobjects?

Primitivedatatypeshavewrapperobjectsthatallowthemtointeractwithcollectionsandotherinterfacesthatrequireobjects. Hereisalistoftheprimitivetypesandtheirwrapperobjects.

PrimitiveType WrapperObject

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

16.6 Maps

Exercise: PrinttheBayAreaairportswiththeirabbreviation.

AirportCode AirportName

SFO SanFrancisco

SJC SanJose

OAK Oakland

Page 70: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 64

Solution:

public static void airports() {// Create map list.Map<String,String> airports =

new LinkedHashMap<String,String>();

// Add airports to it.airports.put("SFO", "San Francisco");airports.put("SJC", "San Jose");airports.put("OAK", "Oakland");

// Print all airports.for (String airportCode : airports.keySet()) {

System.out.printf("%s: %s\n",airportCode,airports.get(airportCode));

}}

Exercise: WriteaprogramthatmapsPLU (productlookup)codestoapplesusingthistable. Itquitswhentheusertypes”quit”.

Fruit PLU Code

RedDelicious 4016

PinkLady 4130

Macintosh 4154

Jazz 3294

Solution:

public static void apples() {// Build map of apples.

Page 71: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 65

Map<String,String> pluMap =new HashMap<String,String>();

pluMap.put("4016", "Red Delicious");pluMap.put("4130", "Pink Lady");pluMap.put("4154", "Macintosh");pluMap.put("3294", "Jazz");

// User loop.while (true) {

String plu =Util.prompt("PLU: ");

if (plu.equals("quit")) {break;

}

else if (!pluMap.containsKey(plu)) {Util.print(

"Unknown PLU " +plu);

continue;}

String fruit = pluMap.get(plu);Util.print(

"Fruit: " + fruit);}

}

Notes:

• Objectsoftype HashMap canbeassignedtovariablesoftype Map. Thismakesiteasytoswitchmapimplementationslateron.

16.7 MapMethods

Whatareuseful Map methods?

Page 72: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 66

Method Result

map.keySet() Keysof map foriteratingin for loop

map.containsKey(key) Trueif map contains key

map.put(key, value) Adds key and value pairto map

map.get(key) Gets value correspondingto key

map.size() Getsnumberofkey-valuepairsinmap

Notes:

• Ifakeydoesnotexistinthemap, get returns null.

• Ifakeydoesnotexistinthemap, andthevalueisaprimitivetype, andlikelytobenull, thenyoushouldgetitasawrapperobjectandthenunboxitaftercheckingfornull; otherwise, anullwrapperobjectwillproduceanullpointerexception.

16.8 MapTypes

WhatarethedifferentkindsofMapobjects?

Type KeySortingPolicy

HashMap Keepskeysinrandomorder

TreeMap Keepskeyssortedorder

LinkedHashMap Keepskeysininsertionorder

Notes:

• HashMap isthefastestandmostspace-efficient.

• Thisisusedunlessthereisarequirementrelatedtokeyorder.

Page 73: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 67

16.9 Sets

Exercise: WriteaprogramthatchecksifanIP addressislocalhost.

Solution:

public static void localhost() {Set<String> localAddresses =

new HashSet<String>();localAddresses.add("127.0.0.1");localAddresses.add("localhost");localAddresses.add("::1");localAddresses.add("");while (true) {

String input =Util.prompt("IP: ");

if (localAddresses.contains(input)) {Util.print("localhost");

}else {

Util.print("NOT localhost");}

}}

Notes:

• Objectsoftype HashSet canbeassignedtovariablesoftype Set. Thismakesiteasytoswitchsetimplementationslateron.

16.10 SetMethods

Whatareuseful Set methods?

Method Result

Page 74: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 68

set.contains(item) Trueif set contains item

set.add(item) Adds item to set

set.size() Getsnumberofitemsin set

16.11 SetTypes

WhatarethedifferentkindsofSetobjects?

Type ElementSortingPolicy

HashSet Keepselementsinrandomorder

TreeSet Keepselementssortedorder

LinkedHashSet Keepselementsininsertionorder

17 RegularExpressions

17.1 RegularExpressions

Whatareregularexpressions?

• Wordprocessorsusuallyhave find and find/replace.

• Thinkofregularexpressionsasthesamefeatureforstrings, exceptonsteriods.

• Regularexpressionsletyoufindpatternsandthenreplacethem.

• Regularexpressionsarealsocalled regex.

17.2 PatternMatching

Exercise: Detectifastringcontainstheword”good”or”bad”. Ifitcontains”good”replywith”It’sgreatisn’tit?”. Ifitcontains”bad”replywith”It’shorrible. It’shorrible.”

Page 75: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 69

Otherwisesay”Um. Okay.”

Solution:

public static void cleverBot1() {while (true) {

String input =Util.prompt("What's up? ");

if (input.matches(".*\\bgood\\b.*")) {Util.print("It's great isn't it?");

}else if (input.matches(".*\\bbad\\b.*")) {

Util.print("It's horrible. It's horrible.");

}else {

Util.print("Um. Okay.");

}}

}

Notes:

• matches returnstrueiftheregularexpressionmatches input andfalseother-wise.

17.3 RegexSummary

Whatarethemainelementsusedtodefineregularexpressions?

Regex Meaning

. matchesanycharacter

\w matchesalphabet, digit, underscore

\W matcheseverythingbut \w

Page 76: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 70

\d matchesdigitcharacter

\D matchesnon-digitcharacter

\s matchesspacecharacter

\S matchesnon-spacecharacter

\b matchesboundary

\B matchesnon-boundary

[abc] matches a or b or c

[ˆabc] matchesanyletterexcept a or b or c

[-abc] matches a or b or c or -

[a-z] matchesanylowercaseletter

[A-Z] matchesanyuppercaseletter

[a-zA-Z] matchesanyletter

\? matchesquestionmark

\. matchesdot

ˆ matchesbeginningofstring

$ matchesendofstring

X* matches0ormoreof X

X+ matches1ormoreof X

X? matches0or1of X

X*? matches0ormorebutnon-greedy

X+? matches1ormorebutnon-greedy

X{1,3} matches1ormoreupto3of X

X{,3} matches0ormoreupto3of X

X{3,} matches3ormoreof X

X{3} matchesexactly3of X

(?s) enablestreatingstringassingleline, . matchesnewline

(?i) enablescaseinsensitivematching

(?x) allowsspacesandcommentsinregex(# toendoflineignored)

Page 77: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 71

Notes:

• Everyregularexpression \ hastobetypedas \\ inthestring.

17.4 Replace

Exercise: Extendthebot. Anytimeitseesastatementthatstartswith”I am”, itreplaces”I am”with”Whyareyou”. Forexample, ”I amtired”becomes”Whyareyoutired?”.

Solution:

public static void cleverBot2() {while (true) {

String input =Util.prompt("What's up? ");

if (input.matches("I\\s+am\\b.*")) {String output = input.replaceAll(

"^I\\s+am\\b(.*?)\\W*$","Why are you$1?");

}else {

Util.print("Um. Okay.");

}}

}

Notes:

• $1matchesthefirstgroupinparenthesesintheregularexpression. $2matchesthesecondgroup. Andsoon.

17.5 Functions

Whatarethemainstringregexfunctions?

Page 78: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 72

Function Effect

s.matches(regex) Trueif s has regex match

s.replaceAll(regex, replace) Replacesall regex with replace

s.replaceFirst(regex, replace) Replacesfirst regex with replace

s.split(regex) Splits s basedon regex

18 SystemInteraction

18.1 CommandLineArguments

Exercise: Print thenumberofcommandlinearguments thatwaspassedintomain.Thenprintthearguments.

public static void commandLine(String[] args) {System.out.printf(

"args.length = %d\n",args.length);

for (int i = 0 ; i < args.length; ++i) {System.out.printf(

"args[%d] = %s\n",i, args[i]);

}

}

18.2 CapturingCommandOutput

Exercise: Write a program that finds the IP address of a givenhost by calling theprogram nslookup. TestitusingGoogle, Yahoo, eBay, localhost.

Solution:

Page 79: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 73

public static void nslookup() {String hostName =

Util.prompt("Host name: ");String output =

Util.shellExecute("nslookup " + hostName);

String address =output.replaceAll(

"(?s)^.*?Name:.*?\nAddress: (.*?)\n.*$","$1");

Util.print("Address: " + address);}

19 MoreEclipse

19.1 AddingThirdPartyJarFiles

Exercise: AddJSON.simpletothe demo project.

Solution:

• Goto https://code.google.com/p/json-simple/

• Clickon Downloads

• Download json-simple-1.1.1.jar

• Right-clickontheproject

• Select BuildPath --> AddExternalArchives

• Select json-simple-1.1.1.jar

• Totestthatthelibraryisavailable, addthiscodetotheproject

public static void testJson() {Map<String,Object> map =

new LinkedHashMap<String,Object>();

Page 80: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 74

map.put("name","foo");

map.put("number",new Integer(100));

map.put("balance",new Double(1000.21));

map.put("isSpecial",new Boolean(true));

map.put("nickname",null);

String jsonText =JSONValue.toJSONString(map);

System.out.println(jsonText);}

• FiximporterrorsbyclickingCtrl-1(onWindows)orCmd-1(onMac)

Exercise: Exportthisprojectasasinglejarfilewiththedependencies.

Solution:

• Followthesamestepsasearlierforexport. Choosedefaultswherepossible.

• Whenyougetthischoice, choosethefirstoptionwhichisthedefault.

– ExtractrequiredlibrariesintogeneratedJAR– PackagerequiredlibrariesintogeneratedJAR– Copyrequiredlibrariesintosub-foldernexttogeneratedJAR

What is the difference between extract required libraries and package required li-braries?

• Extractrequiredlibraries includestheclassfilesfromthejarfileintoyourjar.Packagerequiredlibraries includestheexternallibrariesasajarinsideyourjar.

• Inbothcasesyouhaveastandalonejar.

• The package optionisusefulifyouwanttomakesuretherearenolicensingissueswithputtingexternalclasseswithyourcode.

Page 81: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 75

19.2 DebuggingUsingBreakPoints

Exercise: Debugthetipcalculatorbysteppingthroughitandinspectingallthevariablevalues.

19.3 Refactorings: Extract-Method, Extract-Variable

Exercise: ExtractvariablesandmethodsfromthesamplecodeintheDemoclass.

20 WebClient

20.1 GettingWebContentFromGET Requests

Exercise: Findoutthesizeofthepageat http://www.google.com

Solution:

public static void webPageSize() {String url =

"http://www.google.com";String html =

Util.webGet(url);System.out.println(

"Size: " + html.length());}

Exercise: Inadditiontothesizeofthepage, findouthowlongittakestodownloadit.

public static void webPageSizeAndTime() {String url =

"http://www.google.com";long startTime =

System.currentTimeMillis();String html =

Util.webGet(url);

Page 82: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 76

long endTime =System.currentTimeMillis();

long totalTime =endTime - startTime;

System.out.println("Size: " + html.length());

System.out.println("Time (ms): " + totalTime);

}

20.2 PassingParameterstoPOST Requests

Exercise: Send a POST request to http://www249.pair.com/asim/tmp/request.php withparametersname, city, andstate, andthenprinttheresponse.

Solution:

public static void webPost() {String url =

"http://www249.pair.com/asim/tmp/request.php";String html =

Util.webPost(url,"name", "Dmitri","city", "Hayward","state", "CA");

System.out.println("HTML: " + html);

}

20.3 RealtimeStockQuotes

Exercise: GetrealtimestockquotesfromYahoo’sJSON webservice.

Solution:

// Define the URL and get JSON.String symbol = "T";

Page 83: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 77

String urlString ="http://finance.yahoo.com"+ "/webservice/v1/symbols/"+ symbol+ "/quote?format=json";

String json = Util.webGet(urlString);

// Convert string to JSON object.JSONObject response = (JSONObject)

JSONValue.parseWithException(json);

// Drill down into the JSON object.JSONObject list = (JSONObject)

response.get("list");JSONArray resources = (JSONArray)

list.get("resources");JSONObject resourcesElement = (JSONObject)

resources.get(0);JSONObject resource = (JSONObject)

resourcesElement.get("resource");JSONObject fields = (JSONObject)

resource.get("fields");String priceString = (String)

fields.get("price");

// Convert price to double.double price = Double.parseDouble(

priceString);System.out.println(

"Price: " + price);

Exercise: Writeastaticfunctioncalled getRealtimeQuote whichtakesastocksym-bolasanargumentandreturnstherealtimestockquoteasadoubleeverytimeitiscalled.

Exercise: Writeaclasscalled RealtimeQuote thattakesastocksymbolinthecon-structorandthenreturnstherealtimestockpriceeverytime get() iscalledonit.

Page 84: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 78

21 DatabaseUsingJDBC

21.1 TestingJDBC

Exercise: Createapersondatabase, inserttworecordsinit, andthenselectthem.

Solution:

• Grabsqlite-jdbc3.7.2fromthislocation https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.7.2.jar

• IncludethisfileinEclipsebyfollowingthesesteps.

– Right-clickontheproject

– Select BuildPath --> AddExternalArchives

– Select sqlite-jdbc-3.7.2.jar

• Test database operations by adding this code to the project. Change theDB_FILE asappropriateforyourmachine.

private static finalString DB_FILE = "/tmp/sample.db";

private static void testSqlite()throws ClassNotFoundException {

// Load JDBC driver.Class.forName("org.sqlite.JDBC");

Connection connection = null;try {

// Create database connection.connection =

DriverManager.getConnection("jdbc:sqlite:" + DB_FILE);

Statement statement =connection.createStatement();

statement.setQueryTimeout(30);

Page 85: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 79

// Create table.statement.executeUpdate(

"drop table " +"if exists person");

statement.executeUpdate("create table person " +"(id integer, name string)");

statement.executeUpdate("insert into person " +"values(1, 'alice')");

statement.executeUpdate("insert into person " +"values(2, 'bob')");

// Select table.ResultSet rs =

statement.executeQuery("select * from person");

while (rs.next()) {System.out.println(

"name = " +rs.getString("name"));

System.out.println("id = " + rs.getInt("id"));

}}catch(SQLException e) {

System.err.println(e.getMessage());

}finally {

try {if(connection != null)

connection.close();}catch(SQLException e) {

System.err.println(e);}

Page 86: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 80

}}

• FiximporterrorsbyclickingCtrl-1(onWindows)orCmd-1(onMac)

21.2 VerifyingDatabaseContents

Exercise: Installsqlite3shellifyouareonWindows.

Solution:

• Goto http://www.sqlite.org/download.html.

• Findthe PrecompiledBinariesforWindows section.

• Downloadthe sqlite-shell zipfileandunzipittogettheshell.

Exercise: Verifythatthedatabasewascreated.

Solution:

• Runsqlite3onthedatabasefile.

sqlite3 /tmp/sample.db

• Verifythetablecontentsbytypingthisinthesqlite3prompt.

select * from person;

• Quitsqlite3, bytypingthis.

.quit

Page 87: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 81

22 JavaUI

22.1 TipCalculatorwithUI

Exercise: CreatethetipcalculatorwithaUI.

Solution:

public static void tipUI()throws Exception {

JPanel panel = new JPanel(new GridLayout(0,1));

int width = 15;panel.setBorder(

new EmptyBorder(width, width,width, width));

final JTextField amountField =addTextField(panel,

"Amount");final JTextField peopleField =

addTextField(panel,"People");

final JTextField tipRateField =addTextField(panel,

"TipRate");final JLabel resultLabel =

addValueLabel(panel,"Amount Per Person");

JButton submit =new JButton("Calculate");

submit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

Page 88: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 82

try {String output =

getAmountPerPerson(amountField,peopleField,tipRateField);

resultLabel.setText(output);

}catch (NumberFormatException e) {

resultLabel.setText("Invalid input");

}}

});panel.add(submit);

JFrame frame =new JFrame("Tip Calculator");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setMinimumSize(new Dimension(200, 300));

frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);

}

private static String getAmountPerPerson(JTextField amountField,JTextField peopleField,JTextField tipRateField) {

double amount =Double.parseDouble(

amountField.getText());int people =

Integer.parseInt(peopleField.getText());

Page 89: Java Through Exampleswokkil.pair.com/asim/tmp/metaprose/java · Java Through Examples 5 javac Hello.java • Note that the compiler has created a file calledHello.classin the current

JavaThroughExamples 83

double tipRate =Integer.parseInt(

tipRateField.getText());double amountPerPerson =

amount* (1 + tipRate/100.0)/ people;

String output =String.format(

"$%.2f",amountPerPerson);

return output;}

private static JLabel addValueLabel(JPanel panel, String labelText) {

JLabel valueLabel =new JLabel("");

panel.add(new JLabel(labelText));panel.add(valueLabel);panel.add(new JLabel(""));return valueLabel;

}

private static JTextField addTextField(JPanel panel, String label) {

final JTextField textField =new JTextField("");

panel.add(new JLabel(label));panel.add(textField);panel.add(new JLabel(""));return textField;

}