University Press of Florida

Introduction to Programming Using Java

Buy This Book ( Related URL )
MISSING IMAGE

Material Information

Title:
Introduction to Programming Using Java
Physical Description:
Book
Language:
en-US
Creator:
Eck, David J.

Subjects

Subjects / Keywords:
computer programming, Java programming, Fetch and Execute Cycle, Machine Language, Java Virtual Machine, Object-oriented Programming, Internet, World-Wide Web, Variables, Types, Literals, Strings, Objects, Enums, Subroutines, Text Input, Text Output, Arithmetic Operators, Relational Operators, Boolean Operators, Conditional Operator, Java Development Kit, …
Computer Science Education, Programming, Programming Languages

Notes

Abstract:
This is a free, on-line textbook on introductory programming using Java. This book is directed mainly towards beginning programmers, although it might also be useful for experienced programmers who want to learn more about Java. It is an introductory text and does not provide complete coverage of the Java language. The text is a PDF and is suitable for printing or on-screen reading. It contains internal links for navigation and external links to source code files, exercise solutions, and other resources. Contents: 1) Overview: The Mental Landscape. 2) Programming in the Small I: Names and Things. 3) Programming in the Small II: Control. 4) Programming in the Large I: Subroutines. 5) Programming in the Large II: Objects and Classes. 6) Introduction to GUI Programming. 7) Arrays. 8) Correctness and Robustness. 9) Linked Data Structures and Recursion. 10) Generic Programming and Collection Classes. 11) Files and Networking. 12) Advanced GUI Programming. Appendices: Source Code for All Examples in this Book, and News and Errata.
General Note:
Expositive
General Note:
Community College, Higher Education
General Note:
http://www.ogtp-cart.com/product.aspx?ISBN=9781616100476
General Note:
Abobe PDF Reader
General Note:
Textbook
General Note:
http://florida.theorangegrove.org/og/file/a091ee49-9ae0-c1c7-548d-edf18c8fba34/1/ProgrammingInJava.pdf

Record Information

Source Institution:
University of Florida
Holding Location:
University Press of Florida
Rights Management:
Copyright © 1996--2007, David J. Eck. This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License. (This license allows you to redistribute this book in unmodified form. It allows you to make and distribute modified versions, as long as you include an attribution to the original author, clearly describe the modifications that you have …
Resource Identifier:
isbn - 9781616100476
System ID:
AA00011691:00001


This item is only available as the following downloads:


Full Text

PAGE 1

IntroductiontoProgrammingUsingJava Version5.0,December2006 (Version5.0.2,withminorcorrections,November2007) DavidJ.Eck HobartandWilliamSmithColleges ThisisaPDFversionofanon-linebookthatisavailableat http://math.hws.edu/javanotes/ .ThePDFdoesnotinclude sourcecodeles,solutionstoexercises,oranswerstoquiz zes,but itdoeshaveexternallinkstotheseresources,showninblue Inaddition,eachsectionhasalinktotheon-lineversion. ThePDFalsohasinternallinks,showninred.Theselinkscan beusedin AcrobatReader andsomeotherPDFreaderprograms.

PAGE 2

ii c r 1996{2007,DavidJ.Eck DavidJ.Eck(eck@hws.edu)DepartmentofMathematicsandComputerScienceHobartandWilliamSmithCollegesGeneva,NY14456Thisbookcanbedistributedinunmodiedformwithnorestri ctions. Modiedversionscanbemadeanddistributedprovidedtheya redistributed underthesamelicenseastheoriginal.Morespecically:Th isworkis licensedundertheCreativeCommonsAttribution-ShareAli ke2.5License. Toviewacopyofthislicense,visithttp://creativecommon s.org/licenses/bysa/2.5/orsendalettertoCreativeCommons,543HowardStre et,5th Floor,SanFrancisco,California,94105,USA.Thewebsiteforthisbookis:http://math.hws.edu/javanot es

PAGE 3

Contents Preface x 1TheMentalLandscape 1 1.1MachineLanguage ...................................1 1.2AsynchronousEvents ..................................3 1.3TheJavaVirtualMachine ...............................6 1.4BuildingBlocksofPrograms .............................8 1.5Object-orientedProgramming .............................9 1.6TheModernUserInterface ..............................12 1.7TheInternet ......................................14 QuizonChapter1 ......................................17 2NamesandThings 18 2.1TheBasicJavaApplication ..............................18 2.2VariablesandTypes ..................................21 2.2.1Variables ....................................22 2.2.2TypesandLiterals ...............................23 2.2.3VariablesinPrograms .............................26 2.3ObjectsandSubroutines ................................27 2.3.1Built-inSubroutinesandFunctions ......................28 2.3.2OperationsonStrings .............................31 2.3.3IntroductiontoEnums .............................33 2.4TextInputandOutput ................................35 2.4.1AFirstTextInputExample ..........................36 2.4.2TextOutput ..................................37 2.4.3TextIOInputFunctions ............................38 2.4.4FormattedOutput ...............................40 2.4.5IntroductiontoFileI/O ............................42 2.5DetailsofExpressions .................................43 2.5.1ArithmeticOperators .............................44 2.5.2IncrementandDecrement ...........................45 2.5.3RelationalOperators ..............................45 2.5.4BooleanOperators ...............................46 2.5.5ConditionalOperator .............................47 2.5.6AssignmentOperatorsandType-Casts ....................47 2.5.7TypeConversionofStrings ..........................49 2.5.8PrecedenceRules ................................49 2.6ProgrammingEnvironments ..............................50 i

PAGE 4

CONTENTS ii 2.6.1JavaDevelopmentKit .............................50 2.6.2CommandLineEnvironment .........................51 2.6.3IDEsandEclipse ................................53 2.6.4TheProblemofPackages ...........................55 ExercisesforChapter2 ...................................57 QuizonChapter2 ......................................59 3Control 60 3.1Blocks,Loops,andBranches .............................60 3.1.1Blocks ......................................60 3.1.2TheBasicWhileLoop .............................61 3.1.3TheBasicIfStatement ............................63 3.2AlgorithmDevelopment ................................65 3.2.1PseudocodeandStepwiseRenement ....................65 3.2.2The3N+1Problem ..............................68 3.2.3Coding,Testing,Debugging ..........................71 3.3whileanddo..while ...................................72 3.3.1ThewhileStatement ..............................73 3.3.2Thedo..whileStatement ............................75 3.3.3breakandcontinue ...............................77 3.4TheforStatement ...................................78 3.4.1ForLoops ....................................79 3.4.2Example:CountingDivisors ..........................82 3.4.3NestedforLoops ................................84 3.4.4Enumsandfor-eachLoops ...........................86 3.5TheifStatement ....................................88 3.5.1TheDanglingelseProblem ..........................88 3.5.2Theif...elseifConstruction ..........................88 3.5.3IfStatementExamples .............................90 3.5.4TheEmptyStatement .............................94 3.6TheswitchStatement .................................95 3.6.1TheBasicswitchStatement ..........................95 3.6.2MenusandswitchStatements .........................96 3.6.3EnumsinswitchStatements .........................97 3.6.4DeniteAssignment ..............................98 3.7Exceptionsandtry..catch ...............................99 3.7.1Exceptions ...................................99 3.7.2try..catch ....................................100 3.7.3ExceptionsinTextIO .............................101 3.8GUIProgramming ...................................103 ExercisesforChapter3 ...................................110 QuizonChapter3 ......................................113 4Subroutines 115 4.1BlackBoxes .......................................115 4.2StaticSubroutinesandVariables ...........................117 4.2.1SubroutineDenitions .............................117 4.2.2CallingSubroutines ..............................119

PAGE 5

CONTENTS iii 4.2.3SubroutinesinPrograms ............................120 4.2.4MemberVariables ...............................122 4.3Parameters .......................................125 4.3.1UsingParameters ................................125 4.3.2FormalandActualParameters ........................126 4.3.3Overloading ...................................127 4.3.4SubroutineExamples ..............................128 4.3.5ThrowingExceptions ..............................130 4.3.6GlobalandLocalVariables ..........................131 4.4ReturnValues ......................................132 4.4.1Thereturnstatement .............................132 4.4.2FunctionExamples ...............................133 4.4.33N+1Revisited .................................136 4.5APIs,Packages,andJavadoc .............................138 4.5.1Toolboxes ....................................138 4.5.2Java'sStandardPackages ...........................139 4.5.3UsingClassesfromPackages .........................140 4.5.4Javadoc .....................................142 4.6MoreonProgramDesign ...............................144 4.6.1PreconditionsandPostconditions .......................144 4.6.2ADesignExample ...............................145 4.6.3TheProgram ..................................149 4.7TheTruthAboutDeclarations ............................151 4.7.1InitializationinDeclarations .........................152 4.7.2NamedConstants ...............................153 4.7.3NamingandScopeRules ...........................156 ExercisesforChapter4 ...................................159 QuizonChapter4 ......................................162 5ObjectsandClasses 163 5.1ObjectsandInstanceMethods ............................163 5.1.1Objects,Classes,andInstances ........................164 5.1.2FundamentalsofObjects ...........................165 5.1.3GettersandSetters ...............................170 5.2ConstructorsandObjectInitialization ........................171 5.2.1InitializingInstanceVariables .........................171 5.2.2Constructors ..................................172 5.2.3GarbageCollection ...............................177 5.3ProgrammingwithObjects ..............................177 5.3.1SomeBuilt-inClasses .............................178 5.3.2WrapperClassesandAutoboxing .......................179 5.3.3Theclass\Object" ...............................180 5.3.4Object-orientedAnalysisandDesign .....................181 5.4ProgrammingExample:Card,Hand,Deck ......................183 5.4.1Designingtheclasses ..............................183 5.4.2TheCardClass .................................185 5.4.3Example:ASimpleCardGame ........................189

PAGE 6

CONTENTS iv 5.5InheritanceandPolymorphism ............................192 5.5.1ExtendingExistingClasses ..........................192 5.5.2InheritanceandClassHierarchy .......................194 5.5.3Example:Vehicles ...............................195 5.5.4Polymorphism .................................198 5.5.5AbstractClasses ................................200 5.6thisandsuper ......................................203 5.6.1TheSpecialVariablethis ...........................203 5.6.2TheSpecialVariablesuper ..........................204 5.6.3ConstructorsinSubclasses ..........................206 5.7Interfaces,NestedClasses,andOtherDetails ....................207 5.7.1Interfaces ....................................207 5.7.2NestedClasses .................................209 5.7.3AnonymousInnerClasses ...........................212 5.7.4MixingStaticandNon-static .........................212 5.7.5StaticImport ..................................214 5.7.6EnumsasClasses ................................215 ExercisesforChapter5 ...................................218 QuizonChapter5 ......................................221 6IntroductiontoGUIProgramming 223 6.1TheBasicGUIApplication ..............................223 6.1.1JFrameandJPanel ...............................225 6.1.2ComponentsandLayout ............................227 6.1.3EventsandListeners ..............................228 6.2AppletsandHTML ..................................229 6.2.1JApplet .....................................229 6.2.2ReusingYourJPanels .............................231 6.2.3BasicHTML ..................................233 6.2.4AppletsonWebPages .............................236 6.3GraphicsandPainting .................................238 6.3.1Coordinates ...................................240 6.3.2Colors ......................................241 6.3.3Fonts ......................................242 6.3.4Shapes ......................................243 6.3.5Graphics2D ...................................244 6.3.6AnExample ..................................245 6.4MouseEvents ......................................249 6.4.1EventHandling .................................250 6.4.2MouseEventandMouseListener ........................251 6.4.3MouseCoordinates ...............................254 6.4.4MouseMotionListenersandDragging .....................256 6.4.5AnonymousEventHandlers ..........................260 6.5TimerandKeyboardEvents ..............................262 6.5.1TimersandAnimation .............................262 6.5.2KeyboardEvents ................................264 6.5.3FocusEvents ..................................267

PAGE 7

CONTENTS v 6.5.4StateMachines .................................268 6.6BasicComponents ...................................271 6.6.1JButton .....................................273 6.6.2JLabel ......................................274 6.6.3JCheckBox ...................................275 6.6.4JTextFieldandJTextArea ...........................276 6.6.5JComboBox ...................................277 6.6.6JSlider ......................................278 6.7BasicLayout ......................................280 6.7.1BasicLayoutManagers ............................281 6.7.2Borders .....................................283 6.7.3SliderAndComboBoxDemo ..........................285 6.7.4ASimpleCalculator ..............................287 6.7.5UsinganullLayout ..............................289 6.7.6ALittleCardGame ..............................291 6.8MenusandDialogs ...................................294 6.8.1MenusandMenubars .............................295 6.8.2Dialogs .....................................298 6.8.3FinePointsofFrames .............................300 6.8.4CreatingJarFiles ...............................302 ExercisesforChapter6 ...................................304 QuizonChapter6 ......................................309 7Arrays 311 7.1CreatingandUsingArrays ..............................311 7.1.1Arrays ......................................312 7.1.2UsingArrays ..................................312 7.1.3ArrayInitialization ...............................314 7.2ProgrammingWithArrays ..............................316 7.2.1ArraysandforLoops .............................316 7.2.2Arraysandfor-eachLoops ...........................318 7.2.3ArrayTypesinSubroutines ..........................319 7.2.4RandomAccess .................................320 7.2.5ArraysofObjects ................................322 7.2.6VariableArityMethods ............................325 7.3DynamicArraysandArrayLists ............................327 7.3.1PartiallyFullArrays ..............................327 7.3.2DynamicArrays ................................330 7.3.3ArrrayLists ...................................333 7.3.4ParameterizedTypes ..............................337 7.3.5Vectors .....................................340 7.4SearchingandSorting .................................341 7.4.1Searching ....................................341 7.4.2AssociationLists ................................343 7.4.3InsertionSort ..................................346 7.4.4SelectionSort ..................................347 7.4.5Unsorting ....................................349

PAGE 8

CONTENTS vi 7.5Multi-dimensionalArrays ...............................350 7.5.1CreatingTwo-dimensionalArrays ......................350 7.5.2UsingTwo-dimensionalArrays ........................352 7.5.3Example:Checkers ...............................355 ExercisesforChapter7 ...................................362 QuizonChapter7 ......................................368 8CorrectnessandRobustness 370 8.1IntroductiontoCorrectnessandRobustness .....................370 8.1.1HorrorStories ..................................371 8.1.2JavatotheRescue ...............................372 8.1.3ProblemsRemaininJava ...........................374 8.2WritingCorrectPrograms ...............................375 8.2.1ProvablyCorrectPrograms ..........................375 8.2.2RobustHandlingofInput ...........................378 8.3Exceptionsandtry..catch ...............................382 8.3.1ExceptionsandExceptionClasses ......................383 8.3.2ThetryStatement ...............................385 8.3.3ThrowingExceptions ..............................387 8.3.4MandatoryExceptionHandling ........................389 8.3.5ProgrammingwithExceptions ........................390 8.4Assertions ........................................393 8.5IntroductiontoThreads ................................396 8.5.1CreatingandRunningThreads ........................397 8.5.2OperationsonThreads .............................401 8.5.3MutualExclusionwith\synchronized" ....................402 8.5.4WaitandNotify ................................405 8.5.5VolatileVariables ................................409 8.6AnalysisofAlgorithms .................................410 ExercisesforChapter8 ...................................416 QuizonChapter8 ......................................421 9LinkedDataStructuresandRecursion 423 9.1Recursion ........................................423 9.1.1RecursiveBinarySearch ............................424 9.1.2TowersofHanoi ................................426 9.1.3ARecursiveSortingAlgorithm ........................428 9.1.4BlobCounting .................................431 9.2LinkedDataStructures ................................435 9.2.1RecursiveLinking ...............................435 9.2.2LinkedLists ...................................437 9.2.3BasicLinkedListProcessing .........................437 9.2.4InsertingintoaLinkedList ..........................441 9.2.5DeletingfromaLinkedList ..........................443 9.3Stacks,Queues,andADTs ...............................444 9.3.1Stacks ......................................445 9.3.2Queues .....................................448 9.3.3PostxExpressions ...............................452

PAGE 9

CONTENTS vii 9.4BinaryTrees ......................................455 9.4.1TreeTraversal .................................456 9.4.2BinarySortTrees ...............................458 9.4.3ExpressionTrees ................................463 9.5ASimpleRecursiveDescentParser ..........................466 9.5.1Backus-NaurForm ...............................466 9.5.2RecursiveDescentParsing ...........................468 9.5.3BuildinganExpressionTree ..........................472 ExercisesforChapter9 ...................................475 QuizonChapter9 ......................................478 10GenericProgrammingandCollectionClasses 480 10.1GenericProgramming .................................480 10.1.1GenericProgramminginSmalltalk ......................481 10.1.2GenericProgramminginC++ ........................482 10.1.3GenericProgramminginJava .........................483 10.1.4TheJavaCollectionFramework ........................484 10.1.5Iteratorsandfor-eachLoops ..........................486 10.1.6EqualityandComparison ...........................487 10.1.7GenericsandWrapperClasses ........................490 10.2ListsandSets ......................................491 10.2.1ArrayListandLinkedList ...........................491 10.2.2Sorting .....................................494 10.2.3TreeSetandHashSet ..............................495 10.2.4EnumSet ....................................498 10.3Maps ...........................................499 10.3.1TheMapInterface ...............................500 10.3.2Views,SubSets,andSubMaps ........................501 10.3.3HashTablesandHashCodes .........................504 10.4ProgrammingwiththeCollectionFramework ....................506 10.4.1SymbolTables .................................506 10.4.2SetsInsideaMap ...............................507 10.4.3UsingaComparator ..............................510 10.4.4WordCounting .................................512 10.5WritingGenericClassesandMethods ........................514 10.5.1SimpleGenericClasses .............................515 10.5.2SimpleGenericMethods ............................516 10.5.3TypeWildcards ................................518 10.5.4BoundedTypes .................................522 ExercisesforChapter10 ...................................526 QuizonChapter10 .....................................530 11FilesandNetworking 531 11.1Streams,Readers,andWriters ............................531 11.1.1CharacterandByteStreams .........................531 11.1.2PrintWriter ...................................533 11.1.3DataStreams ..................................534 11.1.4ReadingText ..................................535

PAGE 10

CONTENTS viii 11.1.5TheScannerClass ...............................538 11.1.6SerializedObjectI/O .............................539 11.2Files ...........................................540 11.2.1ReadingandWritingFiles ...........................540 11.2.2FilesandDirectories ..............................543 11.2.3FileDialogBoxes ................................546 11.3ProgrammingWithFiles ................................548 11.3.1CopyingaFile .................................549 11.3.2PersistentData .................................551 11.3.3FilesinGUIPrograms .............................553 11.3.4StoringObjectsinFiles ............................555 11.4Networking .......................................562 11.4.1URLsandURLConnections ..........................563 11.4.2TCP/IPandClient/Server ..........................565 11.4.3Sockets .....................................566 11.4.4ATrivialClient/Server ............................568 11.4.5ASimpleNetworkChat ............................572 11.5NetworkProgrammingandThreads .........................575 11.5.1AThreadedGUIChatProgram. .......................576 11.5.2AMultithreadedServer ............................579 11.5.3DistributedComputing ............................582 11.6ABriefIntroductiontoXML .............................590 11.6.1BasicXMLSyntax ...............................590 11.6.2XMLEncoderandXMLDecoder .......................592 11.6.3WorkingWiththeDOM ............................594 ExercisesforChapter11 ...................................600 QuizonChapter11 .....................................603 12AdvancedGUIProgramming 604 12.1ImagesandResources .................................604 12.1.1ImagesandBueredImages ..........................604 12.1.2WorkingWithPixels ..............................610 12.1.3Resources ....................................613 12.1.4CursorsandIcons ...............................614 12.1.5ImageFileI/O .................................615 12.2FancierGraphics ....................................617 12.2.1MeasuringText .................................618 12.2.2Transparency ..................................620 12.2.3Antialiasing ...................................622 12.2.4StrokesandPaints ...............................623 12.2.5Transforms ...................................626 12.3ActionsandButtons ..................................629 12.3.1ActionandAbstractAction ..........................629 12.3.2IconsonButtons ................................631 12.3.3RadioButtons .................................632 12.3.4Toolbars .....................................635 12.3.5KeyboardAccelerators .............................636

PAGE 11

CONTENTS ix 12.3.6HTMLonButtons ...............................638 12.4ComplexComponentsandMVC ...........................639 12.4.1Model-View-Controller .............................639 12.4.2ListsandListModels ..............................640 12.4.3TablesandTableModels ............................643 12.4.4DocumentsandEditors ............................647 12.4.5CustomComponents ..............................648 12.5FinishingTouches ...................................653 12.5.1TheMandelbrotSet ..............................653 12.5.2DesignoftheProgram .............................655 12.5.3Internationalization ..............................657 12.5.4Events,Events,Events .............................659 12.5.5CustomDialogs .................................661 12.5.6Preferences ...................................662 ExercisesforChapter12 ...................................664 QuizonChapter12 .....................................667 Appendix:SourceFiles 668

PAGE 12

PrefaceI ntroductiontoProgrammingUsingJava isafreeintroductorycomputerprogramming textbookthatusesJavaasthelanguageofinstruction.Itis suitableforuseinanintroductory programmingcourseandforpeoplewhoaretryingtolearnpro grammingontheirown.There arenoprerequisitesbeyondageneralfamiliaritywiththei deasofcomputersandprograms. Thereisenoughmaterialforafullyearofcollege-levelpro gramming.Chapters1through7 canbeusedasatextbookinaone-semestercollege-levelcou rseorinayear-longhighschool course. Thisversionofthebookcovers\Java5.0",andmanyoftheexa mplesusefeaturesthatwere notpresentinearlierversionsofJava.(Sometimes,youwil lseethisversionofJavareferred toasJava1.5insteadofJava5.0.)NotethatJavaappletsapp earthroughoutthepagesofthe on-lineversionofthisbook.Manyofthoseappletswillbeno n-functionalinWebbrowsersthat donotsupportJava5.0. Thehomewebsiteforthisbookis http://math.hws.edu/javanotes/ .Thepageatthat addresscontainslinksfordownloadingacopyofthewebsite andfordownloadingaPDF versionofthebook. Instyle,thisisatextbookratherthanatutorial.Thatis,i tconcentratesonexplaining conceptsratherthangivingstep-by-stephow-to-do-itgui des.Ihavetriedtouseaconversational writingstylethatmightbeclosertoclassroomlecturethan toatypicaltextbook.You'll ndprogrammingexercisesattheendofmostchapters,andyo uwillndadetailedsolution foreachexercise,withthesortofdiscussionthatIwouldgi veifIpresentedthesolutionin class.(Solutionstotheexercisescanbefoundintheon-lin eversiononly.)I strongly advise thatyoureadtheexercisesolutionsifyouwanttogetthemos toutofthisbook.Thisis certainlynotaJavareferencebook,anditisnotevencloset oacomprehensivesurveyofall thefeaturesofJava.Itis not writtenasaquickintroductiontoJavaforpeoplewhoalread y knowanotherprogramminglanguage.Instead,itisdirected mainlytowardspeoplewhoare learningprogrammingforthersttime,anditisasmuchabou tgeneralprogrammingconcepts asitisaboutJavainparticular.Ibelievethat IntroductiontoProgrammingusingJava is fullycompetitivewiththeconventionallypublished,prin tedprogrammingtextbooksthatare availableonthemarket.(Well,allright,I'llconfessthat Ithinkit'sbetter.) ThereareseveralapproachestoteachingJava.Oneapproach usesgraphicaluserinterface programmingfromtheverybeginning.Somepeoplebelieveth atobjectorientedprogramming shouldalsobeemphasizedfromtheverybeginning.Thisis not theapproachthatItake.The approachthatIfavorstartswiththemorebasicbuildingblo cksofprogrammingandbuilds fromthere.Afteranintroductorychapter,Icoverprocedur alprogramminginChapters2,3, and4.Object-orientedprogrammingisintroducedinChapte r5.Chapters6coverstheclosely relatedtopicofevent-orientedprogrammingandgraphical userinterfaces.Arraysarecoveredin Chapter7.Chapter8marksaturningpointinthebook,moving beyondthefundamentalideas x

PAGE 13

Preface xi ofprogrammingtocovermoreadvancedtopics.Chapter8ismo stlyaboutwritingrobustand correctprograms,butitalsohasasectiononparallelproce ssingandthreads.Chapters9and 10coverrecursionanddatastructures,includingtheJavaC ollectionFramework.Chapter11is aboutlesandnetworking.Finally,Chapter12returnstoth etopicofgraphicaluserinterface programmingtocoversomeofJava'smoreadvancedcapabilit ies. Majorchangeshavebeenmadeinthefthedition.Perhapsthe mostsignicantchangeis theuseofparameterizedtypesinthechapterongenericprog ramming.Parameterizedtypes| Java'sversionoftemplates|werethemosteagerlyanticipa tednewfeatureinJava5.0. OthernewfeaturesinJava5.0arealsocovered.Enumeratedt ypesareintroduced,although theyarenotcoveredintheirfullcomplexity.The\for-each "loopiscoveredandisused extensively.Formattedoutputisalsousedextensively,an dthe Scanner classiscovered(though notuntilChapter11).Staticimportiscoveredbriery,asar evariablearitymethods. Thenon-standard TextIO classthatIuseforinputinthersthalfofthebookhasbeen rewrittentosupportformattedoutput.Ihavealsoaddedsom eleI/Ocapabilitiestothisclass tomakeitpossibletocoversomeexamplesthatuselesearly inthebook. Javadoccommentsarecoveredforthersttimeinthiseditio n.Almostallcodeexamples havebeenrevisedtouseJavadoc-stylecomments. Thecoverageofgraphicaluserinterfaceprogramminghasbe enreorganized,muchofithas beenrewritten,andnewmaterialhasbeenadded.Inprevious editions,Iemphasizedapplets. Stand-aloneGUIapplicationswerecoveredattheend,almos tasanafterthought.Inthefth edition,theemphasisonappletsisgone,andalmostallexam plesarepresentedasstand-alone applications.However,appletversionsofeachexampleare stillpresentedonthewebpagesof theon-lineversionofthebook.ThechapteronadvancedGUIp rogramminghasbeenmoved totheend,andasignicantamountofnewmaterialhasbeenad ded,includingcoverageof someofthefeaturesof Graphics2D Asidefromthechangesincontent,theappearanceofthebook hasbeenimproved,especially theappearanceofthePDFversion.Forthersttime,thequal ityofthePDFapproachesthat ofconventionaltextbooks. Thelatestcompleteeditionof IntroductiontoProgrammingusingJava isalwaysavailable onlineat http://math.hws.edu/javanotes/ .Therstversionofthebookwaswrittenin1996, andtherehavebeenseveraleditionssincethen.Alledition sarearchivedatthefollowingWeb addresses: Firstedition: http://math.hws.edu/eck/cs124/javanotes1/ (CoversJava1.0.) Secondedition: http://math.hws.edu/eck/cs124/javanotes2/ (CoversJava1.1.) Thirdedition: http://math.hws.edu/eck/cs124/javanotes3/ (CoversJava1.1.) Fourthedition: http://math.hws.edu/eck/cs124/javanotes4/ (CoversJava1.4.) Fifthedition: http://math.hws.edu/eck/cs124/javanotes5/ (CoversJava5.0.) IntroductiontoProgrammingusingJava is free ,butitisnotinthepublicdomain.Asof Version5.0,itispublishedunderthetermsoftheCreativeC ommonsAttribution-ShareAlike 2.5License.Toviewacopyofthislicense,visit http://creativecommons.org/licenses/by-sa/2.5/ orsendalettertoCreativeCommons,543HowardStreet,5thF loor,SanFrancisco,California,94105,USA.Thislicenseallowsredistributionandmod icationundercertainterms.For example,youcan:

PAGE 14

Preface xii Postanunmodiedcopyoftheon-lineversiononyourownWebs ite(includingtheparts thatlisttheauthorandstatethelicenseunderwhichitisdi stributed!). Giveawayorsellprinted,unmodiedcopiesofthisbook,asl ongastheymeettherequirementsofthelicense. Makemodiedcopiesofthecompletebookorpartsofitandpos tthemonthewebor otherwisedistributethem,providedthatattributiontoth eauthorisgiven,themodicationsareclearlynoted,andthemodiedcopiesaredistribu tedunderthesamelicenseas theoriginal.Thisincludestranslationstootherlanguage s. Whileitisnotactuallyrequiredbythelicense,Idoappreci atehearingfrompeoplewho areusingordistributingmywork. Atechnicalnoteonproduction: Theon-lineandPDFversionsofthisbookarecreated fromasinglesource,whichiswrittenlargelyinXML.Toprod ucethePDFversion,theXML isprocessedintoaformthatcanbeusedbytheTeXtypesettin gprogram.InadditiontoXML les,thesourceincludesDTDs,XSLTtransformations,Java sourcecodeles,imageles,a TeXmacrole,andacoupleofscriptsthatareusedinprocess ing.Ihavenotmadethesource materialsavailablefordownload,sincetheyarenotinacle anenoughformtobepublishable, andbecauseitwouldrequireafairamountofexpertisetomak eanyuseofthem.However, theyarenotmeanttobesecret,andIamwillingtomakethemav ailableonrequest. ProfessorDavidJ.EckDepartmentofMathematicsandComputerScienceHobartandWilliamSmithCollegesGeneva,NewYork14456,USAEmail:eck@hws.eduWWW: http://math.hws.edu/eck/

PAGE 15

Chapter1Overview:TheMentalLandscapeW henyoubegin ajourney,it'sagoodideatohaveamentalmapoftheterrainy ou'll bepassingthrough.Thesameistrueforanintellectualjour ney,suchaslearningtowrite computerprograms.Inthiscase,you'llneedtoknowthebasi csofwhatcomputersareand howtheywork.You'llwanttohavesomeideaofwhatacomputer programisandhowoneis created.SinceyouwillbewritingprogramsintheJavaprogr amminglanguage,you'llwantto knowsomethingaboutthatlanguageinparticularandaboutt hemodern,networkedcomputing environmentforwhichJavaisdesigned. Asyoureadthischapter,don'tworryifyoucan'tunderstand everythingindetail.(Infact, itwouldbeimpossibleforyoutolearnallthedetailsfromth ebriefexpositionsinthischapter.) Concentrateonlearningenoughaboutthebigideastoorient yourself,inpreparationforthe restofthebook.Mostofwhatiscoveredinthischapterwillb ecoveredinmuchgreaterdetail laterinthebook.1.1TheFetchandExecuteCycle:MachineLanguageA computerisacomplexsystem consistingofmanydierentcomponents.Butatthe (online) heart|orthebrain,ifyouwant|ofthecomputerisasingleco mponentthatdoestheactual computing.Thisisthe CentralProcessingUnit ,orCPU.Inamoderndesktopcomputer, theCPUisasingle\chip"ontheorderofonesquareinchinsiz e.ThejoboftheCPUisto executeprograms. A program issimplyalistofunambiguousinstructionsmeanttobefoll owedmechanically byacomputer.Acomputerisbuilttocarryoutinstructionst hatarewritteninaverysimple typeoflanguagecalled machinelanguage .Eachtypeofcomputerhasitsownmachine language,andthecomputercandirectlyexecuteaprogramon lyiftheprogramisexpressedin thatlanguage.(Itcanexecuteprogramswritteninotherlan guagesiftheyarersttranslated intomachinelanguage.) WhentheCPUexecutesaprogram,thatprogramisstoredinthe computer's mainmemory (alsocalledtheRAMorrandomaccessmemory).Inadditionto theprogram,memory canalsoholddatathatisbeingusedorprocessedbytheprogr am.Mainmemoryconsistsofa sequenceof locations .Theselocationsarenumbered,andthesequencenumberofal ocation iscalledits address .Anaddressprovidesawayofpickingoutoneparticularpiec eofinformationfromamongthemillionsstoredinmemory.WhentheCPUne edstoaccesstheprogram instructionordatainaparticularlocation,itsendsthead dressofthatinformationasasignaltothememory;thememoryrespondsbysendingbackthedat acontainedinthespecied 1

PAGE 16

CHAPTER1.THEMENTALLANDSCAPE 2 location.TheCPUcanalsostoreinformationinmemorybyspe cifyingtheinformationtobe storedandtheaddressofthelocationwhereitistobestored Onthelevelofmachinelanguage,theoperationoftheCPUisf airlystraightforward(althoughitisverycomplicatedindetail).TheCPUexecutesap rogramthatisstoredasa sequenceofmachinelanguageinstructionsinmainmemory.I tdoesthisbyrepeatedlyreading, or fetching ,aninstructionfrommemoryandthencarryingout,or executing ,thatinstruction.Thisprocess|fetchaninstruction,executeit,fetch anotherinstruction,executeit,andso onforever|iscalledthe fetch-and-executecycle .Withoneexception,whichwillbecovered inthenextsection,thisisallthattheCPUeverdoes. Thedetailsofthefetch-and-executecyclearenotterribly important,butthereareafew basicthingsyoushouldknow.TheCPUcontainsafewinternal registers ,whicharesmall memoryunitscapableofholdingasinglenumberormachinela nguageinstruction.TheCPU usesoneoftheseregisters|the programcounter ,orPC|tokeeptrackofwhereitisinthe programitisexecuting.ThePCstorestheaddressofthenext instructionthattheCPUshould execute.Atthebeginningofeachfetch-and-executecycle, theCPUchecksthePCtoseewhich instructionitshouldfetch.Duringthecourseofthefetchand-executecycle,thenumberinthe PCisupdatedtoindicatetheinstructionthatistobeexecut edinthenextcycle.(Usually, butnotalways,thisisjusttheinstructionthatsequential lyfollowsthecurrentinstructionin theprogram.) Acomputerexecutesmachinelanguageprogramsmechanicall y|thatiswithoutunderstandingthemorthinkingaboutthem|simplybecauseofthew ayitisphysicallyputtogether. Thisisnotaneasyconcept.Acomputerisamachinebuiltofmi llionsoftinyswitchescalled transistors ,whichhavethepropertythattheycanbewiredtogetherinsu chawaythatan outputfromoneswitchcanturnanotherswitchonoro.Asaco mputercomputes,these switchesturneachotheronoroinapatterndeterminedboth bythewaytheyarewired togetherandbytheprogramthatthecomputerisexecuting. Machinelanguageinstructionsareexpressedasbinarynumb ers.Abinarynumberismade upofjusttwopossibledigits,zeroandone.So,amachinelan guageinstructionisjustasequence ofzerosandones.Eachparticularsequenceencodessomepar ticularinstruction.Thedatathat thecomputermanipulatesisalsoencodedasbinarynumbers. Acomputercanworkdirectly withbinarynumbersbecauseswitchescanreadilyrepresent suchnumbers:Turntheswitchon torepresentaone;turnitotorepresentazero.Machinelan guageinstructionsarestored inmemoryaspatternsofswitchesturnedonoro.Whenamachi nelanguageinstruction isloadedintotheCPU,allthathappensisthatcertainswitc hesareturnedonorointhe patternthatencodesthatparticularinstruction.TheCPUi sbuilttorespondtothispattern byexecutingtheinstructionitencodes;itdoesthissimply becauseofthewayalltheother switchesintheCPUarewiredtogether. So,youshouldunderstandthismuchabouthowcomputerswork :Mainmemoryholds machinelanguageprogramsanddata.Theseareencodedasbin arynumbers.TheCPUfetches machinelanguageinstructionsfrommemoryoneafteranothe randexecutesthem.Itdoes thismechanically,withoutthinkingaboutorunderstandin gwhatitdoes|andthereforethe programitexecutesmustbeperfect,completeinalldetails ,andunambiguousbecausetheCPU candonothingbutexecuteitexactlyaswritten.Hereisasch ematicviewofthisrst-stage understandingofthecomputer:

PAGE 17

CHAPTER1.THEMENTALLANDSCAPE 3 Data to memory Data from memory Address for reading/writing data 1011100001 Programcounter: CPU Memory (Location 0)(Location 1)(Location 2)(Location 3)(Location 10) 0010111011010011010100110001000010111111101001101110100100000111101001100001000100111110 1.2AsynchronousEvents:PollingLoopsandInterruptsT heCPUspendsalmostall ofitstimefetchinginstructionsfrommemoryandexecuting (online) them.However,theCPUandmainmemoryareonlytwooutofmany componentsinareal computersystem.Acompletesystemcontainsotherdevicess uchas: A harddisk forstoringprogramsanddatales.(Notethatmainmemoryho ldsonlya comparativelysmallamountofinformation,andholdsitonl yaslongasthepoweristurned on.Aharddiskisnecessaryforpermanentstorageoflargera mountsofinformation,but programshavetobeloadedfromdiskintomainmemorybeforet heycanactuallybe executed.) A keyboard and mouse foruserinput. A monitor and printer whichcanbeusedtodisplaythecomputer'soutput. A modem thatallowsthecomputertocommunicatewithothercomputer sovertelephone lines. A networkinterface thatallowsthecomputertocommunicatewithothercomputer s thatareconnectedtoitonanetwork. A scanner thatconvertsimagesintocodedbinarynumbersthatcanbest oredand manipulatedonthecomputer. Thelistofdevicesisentirelyopenended,andcomputersyst emsarebuiltsothattheycan easilybeexpandedbyaddingnewdevices.SomehowtheCPUhas tocommunicatewithand controlallthesedevices.TheCPUcanonlydothisbyexecuti ngmachinelanguageinstructions (whichisallitcando,period).Thewaythisworksisthatfor eachdeviceinasystem,there isa devicedriver ,whichconsistsofsoftwarethattheCPUexecuteswhenithas todeal withthedevice.Installinganewdeviceonasystemgenerall yhastwosteps:pluggingthe devicephysicallyintothecomputer,andinstallingthedev icedriversoftware.Withoutthe devicedriver,theactualphysicaldevicewouldbeuseless, sincetheCPUwouldnotbeableto communicatewithit.

PAGE 18

CHAPTER1.THEMENTALLANDSCAPE 4 Acomputersystemconsistingofmanydevicesistypicallyor ganizedbyconnectingthose devicestooneormore busses .Abusisasetofwiresthatcarryvarioussortsofinformatio n betweenthedevicesconnectedtothosewires.Thewirescarr ydata,addresses,andcontrol signals.Anaddressdirectsthedatatoaparticulardevicea ndperhapstoaparticularregister orlocationwithinthatdevice.Controlsignalscanbeused, forexample,byonedevicetoalert anotherthatdataisavailableforitonthedatabus.Afairly simplecomputersystemmight beorganizedlikethis: Input/ Output Controller Data busAddress busControl bus CPU Empty Slot for future Expansion Keyboard Network Interface ... ... Network Cable Video Controller and Monitor Memory Now,devicessuchaskeyboard,mouse,andnetworkinterface canproduceinputthatneeds tobeprocessedbytheCPU.HowdoestheCPUknowthatthedatai sthere?Onesimpleidea, whichturnsouttobenotverysatisfactory,isfortheCPUtok eepcheckingforincomingdata overandover.Wheneveritndsdata,itprocessesit.Thisme thodiscalled polling ,since theCPUpollstheinputdevicescontinuallytoseewhetherth eyhaveanyinputdatatoreport. Unfortunately,althoughpollingisverysimple,itisalsov eryinecient.TheCPUcanwaste anawfullotoftimejustwaitingforinput. Toavoidthisineciency, interrupts areoftenusedinsteadofpolling.Aninterruptis asignalsentbyanotherdevicetotheCPU.TheCPUrespondsto aninterruptsignalby puttingasidewhateveritisdoinginordertorespondtothei nterrupt.Onceithashandled theinterrupt,itreturnstowhatitwasdoingbeforetheinte rruptoccurred.Forexample,when youpressakeyonyourcomputerkeyboard,akeyboardinterru ptissenttotheCPU.The CPUrespondstothissignalbyinterruptingwhatitisdoing, readingthekeythatyoupressed, processingit,andthenreturningtothetaskitwasperformi ngbeforeyoupressedthekey. Again,youshouldunderstandthatthisisapurelymechanica lprocess:Adevicesignalsan interruptsimplybyturningonawire.TheCPUisbuiltsothat whenthatwireisturnedon, theCPUsavesenoughinformationaboutwhatitiscurrentlyd oingsothatitcanreturnto thesamestatelater.Thisinformationconsistsoftheconte ntsofimportantinternalregisters suchastheprogramcounter.ThentheCPUjumpstosomepredet erminedmemorylocation andbeginsexecutingtheinstructionsstoredthere.Thosei nstructionsmakeupan interrupt handler thatdoestheprocessingnecessarytorespondtotheinterru pt.(Thisinterrupthandler ispartofthedevicedriversoftwareforthedevicethatsign alledtheinterrupt.)Attheendof

PAGE 19

CHAPTER1.THEMENTALLANDSCAPE 5 theinterrupthandlerisaninstructionthattellstheCPUto jumpbacktowhatitwasdoing; itdoesthatbyrestoringitspreviouslysavedstate. InterruptsallowtheCPUtodealwith asynchronousevents .Intheregularfetch-andexecutecycle,thingshappeninapredeterminedorder;ever ythingthathappensis\synchronized"witheverythingelse.Interruptsmakeitpossiblefo rtheCPUtodealecientlywith eventsthathappen\asynchronously,"thatis,atunpredict abletimes. Asanotherexampleofhowinterruptsareused,considerwhat happenswhentheCPUneeds toaccessdatathatisstoredontheharddisk.TheCPUcanacce ssdatadirectlyonlyifitis inmainmemory.Dataonthediskhastobecopiedintomemorybe foreitcanbeaccessed. Unfortunately,onthescaleofspeedatwhichtheCPUoperate s,thediskdriveisextremely slow.WhentheCPUneedsdatafromthedisk,itsendsasignalt othediskdrivetellingit tolocatethedataandgetitready.(Thissignalissentsynch ronously,underthecontrolofa regularprogram.)Then,insteadofjustwaitingthelongand unpredictalbleamountoftime thatthediskdrivewilltaketodothis,theCPUgoesonwithso meothertask.Whenthedisk drivehasthedataready,itsendsaninterruptsignaltotheC PU.Theinterrupthandlercan thenreadtherequesteddata. Now,youmighthavenoticedthatallthisonlymakessenseift heCPUactuallyhasseveral taskstoperform.Ifithasnothingbettertodo,itmightaswe llspenditstimepollingforinput orwaitingfordiskdriveoperationstocomplete.Allmodern computersuse multitasking to performseveraltasksatonce.Somecomputerscanbeusedbys everalpeopleatonce.Sincethe CPUissofast,itcanquicklyswitchitsattentionfromoneus ertoanother,devotingafraction ofasecondtoeachuserinturn.Thisapplicationofmultitas kingiscalled timesharing .Buta modernpersonalcomputerwithjustasingleuseralsousesmu ltitasking.Forexample,theuser mightbetypingapaperwhileaclockiscontinuouslydisplay ingthetimeandaleisbeing downloadedoverthenetwork. EachoftheindividualtasksthattheCPUisworkingoniscall eda thread .(Ora process ; therearetechnicaldierencesbetweenthreadsandprocess es,buttheyarenotimportanthere.) Atanygiventime,onlyonethreadcanactuallybeexecutedby aCPU.TheCPUwillcontinue runningthesamethreaduntiloneofseveralthingshappens: Thethreadmightvoluntarily yield control,togiveotherthreadsachancetorun. Thethreadmighthavetowaitforsomeasynchronouseventtoo ccur.Forexample,the threadmightrequestsomedatafromthediskdrive,oritmigh twaitfortheusertopress akey.Whileitiswaiting,thethreadissaidtobe blocked ,andotherthreadshavea chancetorun.Whentheeventoccurs,aninterruptwill\wake up"thethreadsothatit cancontinuerunning. Thethreadmightuseupitsallottedsliceoftimeandbesuspe ndedtoallowotherthreads torun.Notallcomputerscan\forcibly"suspendathreadint hisway;thosethatcan aresaidtouse preemptivemultitasking .Todopreemptivemultitasking,acomputer needsaspecialtimerdevicethatgeneratesaninterruptatr egularintervals,suchas100 timespersecond.Whenatimerinterruptoccurs,theCPUhasa chancetoswitchfrom onethreadtoanother,whetherthethreadthatiscurrentlyr unninglikesitornot. Ordinaryusers,andindeedordinaryprogrammers,havenone edtodealwithinterruptsand interrupthandlers.Theycanconcentrateonthedierentta sksorthreadsthattheywantthe computertoperform;thedetailsofhowthecomputermanages togetallthosetasksdoneare notimportanttothem.Infact,mostusers,andmanyprogramm ers,canignorethreadsand

PAGE 20

CHAPTER1.THEMENTALLANDSCAPE 6 multitaskingaltogether.However,threadshavebecomeinc reasinglyimportantascomputers havebecomemorepowerfulandastheyhavebeguntomakemoreu seofmultitasking.Indeed, threadsarebuiltintotheJavaprogramminglanguageasafun damentalprogrammingconcept. JustasimportantinJavaandinmodernprogrammingingenera listhebasicconceptof asynchronousevents.Whileprogrammersdon'tactuallydea lwithinterruptsdirectly,they dooftenndthemselveswriting eventhandlers ,which,likeinterrupthandlers,arecalled asynchronouslywhenspeciedeventsoccur.Such\event-dr ivenprogramming"hasavery dierentfeelfromthemoretraditionalstraight-through, synchronousprogramming.Wewill beginwiththemoretraditionaltypeofprogramming,whichi sstillusedforprogramming individualtasks,butwewillreturntothreadsandeventsla terinthetext. Bytheway,thesoftwarethatdoesalltheinterrupthandling andthecommunicationwith theuserandwithhardwaredevicesiscalledthe operatingsystem .Theoperatingsystemis thebasic,essentialsoftwarewithoutwhichacomputerwoul dnotbeabletofunction.Other programs,suchaswordprocessorsandWorldWideWebbrowser s,aredependentuponthe operatingsystem.CommonoperatingsystemsincludeLinux, DOS,Windows2000,Windows XP,andtheMacintoshOS.1.3TheJavaVirtualMachineM achinelanguageconsists ofverysimpleinstructionsthatcanbeexecuteddirectlyby (online) theCPUofacomputer.Almostallprograms,though,arewritt enin high-levelprogramming languages suchasJava,Pascal,orC++.Aprogramwritteninahigh-leve llanguagecannot berundirectlyonanycomputer.First,ithastobetranslate dintomachinelanguage.This translationcanbedonebyaprogramcalleda compiler .Acompilertakesahigh-level-language programandtranslatesitintoanexecutablemachine-langu ageprogram.Oncethetranslation isdone,themachine-languageprogramcanberunanynumbero ftimes,butofcourseitcanonly berunononetypeofcomputer(sinceeachtypeofcomputerhas itsownindividualmachine language).Iftheprogramistorunonanothertypeofcompute rithastobere-translated, usingadierentcompiler,intotheappropriatemachinelan guage. Thereisanalternativetocompilingahigh-levellanguagep rogram.Insteadofusinga compiler,whichtranslatestheprogramallatonce,youcanu sean interpreter ,whichtranslates itinstruction-by-instruction,asnecessary.Aninterpre terisaprogramthatactsmuchlikea CPU,withakindoffetch-and-executecycle.Inordertoexec uteaprogram,theinterpreter runsinaloopinwhichitrepeatedlyreadsoneinstructionfr omtheprogram,decideswhatis necessarytocarryoutthatinstruction,andthenperformst heappropriatemachine-language commandstodoso. Oneuseofinterpretersistoexecutehigh-levellanguagepr ograms.Forexample,theprogramminglanguageLispisusuallyexecutedbyaninterprete rratherthanacompiler.However, interpretershaveanotherpurpose:theycanletyouuseamac hine-languageprogrammeantfor onetypeofcomputeronacompletelydierenttypeofcompute r.Forexample,thereisaprogramcalled\VirtualPC"thatrunsonMacintoshcomputers.V irtualPCisaninterpreterthat executesmachine-languageprogramswrittenforIBM-PC-cl onecomputers.IfyourunVirtual PConyourMacintosh,youcanrunanyPCprogram,includingpr ogramswrittenforWindows. (Unfortunately,aPCprogramwillrunmuchmoreslowlythani twouldonanactualIBMclone. TheproblemisthatVirtualPCexecutesseveralMacintoshma chine-languageinstructionsfor

PAGE 21

CHAPTER1.THEMENTALLANDSCAPE 7 eachPCmachine-languageinstructionintheprogramitisin terpreting.Compiledprograms areinherentlyfasterthaninterpretedprograms.) ThedesignersofJavachosetouseacombinationofcompilati onandinterpretation.ProgramswritteninJavaarecompiledintomachinelanguage,bu titisamachinelanguagefor acomputerthatdoesn'treallyexist.Thisso-called\virtu al"computerisknownasthe Java virtualmachine .ThemachinelanguagefortheJavavirtualmachineiscalled Javabytecode .ThereisnoreasonwhyJavabytecodecouldnotbeusedasthem achinelanguageofa realcomputer,ratherthanavirtualcomputer. However,oneofthemainsellingpointsofJavaisthatitcana ctuallybeusedon any computer.AllthatthecomputerneedsisaninterpreterforJ avabytecode.Suchaninterpreter simulatestheJavavirtualmachineinthesamewaythatVirtu alPCsimulatesaPCcomputer. Ofcourse,adierentJavebytecodeinterpreterisneededfo reachtypeofcomputer,but onceacomputerhasaJavabytecodeinterpreter,itcanrunan yJavabytecodeprogram.And thesameJavabytecodeprogramcanberunonanycomputerthat hassuchaninterpreter. ThisisoneoftheessentialfeaturesofJava:thesamecompil edprogramcanberunonmany dierenttypesofcomputers. n r n n Why,youmightwonder,usetheintermediateJavabytecodeat all?Whynotjustdistribute theoriginalJavaprogramandleteachpersoncompileitinto themachinelanguageofwhatever computertheywanttoruniton?Therearemanyreasons.First ofall,acompilerhasto understandJava,acomplexhigh-levellanguage.Thecompil erisitselfacomplexprogram.A Javabytecodeinterpreter,ontheotherhand,isafairlysma ll,simpleprogram.Thismakesit easytowriteabytecodeinterpreterforanewtypeofcompute r;oncethatisdone,thatcomputer canrunanycompiledJavaprogram.Itwouldbemuchhardertow riteaJavacompilerforthe samecomputer. Furthermore,manyJavaprogramsaremeanttobedownloadedo veranetwork.Thisleads toobvioussecurityconcerns:youdon'twanttodownloadand runaprogramthatwilldamage yourcomputeroryourles.Thebytecodeinterpreteractsas abuerbetweenyouandthe programyoudownload.Youarereallyrunningtheinterprete r,whichrunsthedownloaded programindirectly.Theinterpretercanprotectyoufrompo tentiallydangerousactionsonthe partofthatprogram. IshouldnotethatthereisnonecessaryconnectionbetweenJ avaandJavabytecode.AprogramwritteninJavacouldcertainlybecompiledintothemac hinelanguageofarealcomputer. Andprogramswritteninotherlanguagescouldbecompiledin toJavabytecode.However,itis thecombinationofJavaandJavabytecodethatisplatform-i ndependent,secure,andnetworkcompatiblewhileallowingyoutoprograminamodernhigh-le velobject-orientedlanguage.

PAGE 22

CHAPTER1.THEMENTALLANDSCAPE 8 Ishouldalsonotethatthereallyhardpartofplatform-inde pendenceisprovidinga\GraphicalUserInterface"|withwindows,buttons,etc.|thatwil lworkonalltheplatformsthat supportJava.You'llseemoreaboutthisproblemin Section1.6 1.4FundamentalBuildingBlocksofProgramsT herearetwobasicaspects ofprogramming:dataandinstructions.Toworkwith (online) data,youneedtounderstand variables and types ;toworkwithinstructions,youneedto understand controlstructures and subroutines .You'llspendalargepartofthecourse becomingfamiliarwiththeseconcepts. A variable isjustamemorylocation(orseverallocationstreatedasau nit)thathasbeen givenanamesothatitcanbeeasilyreferredtoandusedinapr ogram.Theprogrammeronly hastoworryaboutthename;itisthecompiler'sresponsibil itytokeeptrackofthememory location.Theprogrammerdoesneedtokeepinmindthatthena mereferstoakindof\box" inmemorythatcanholddata,eveniftheprogrammerdoesn'th avetoknowwhereinmemory thatboxislocated. InJavaandmostotherlanguages,avariablehasa type thatindicateswhatsortofdata itcanhold.Onetypeofvariablemightholdintegers|wholen umberssuchas3,-7,and0| whileanotherholdsroatingpointnumbers|numberswithdec imalpointssuchas3.14,-2.7, or17.0.(Yes,thecomputerdoesmakeadistinctionbetweent heinteger17andtheroatingpointnumber17.0;theyactuallylookquitedierentinside thecomputer.)Therecouldalso betypesforindividualcharacters('A',';',etc.),string s(\Hello",\Astringcanincludemany characters",etc.),andlesscommontypessuchasdates,col ors,sounds,oranyothertypeof datathataprogrammightneedtostore. Programminglanguagesalwayshavecommandsforgettingdat aintoandoutofvariables andfordoingcomputationswithdata.Forexample,thefollo wing\assignmentstatement," whichmightappearinaJavaprogram,tellsthecomputertota kethenumberstoredinthe variablenamed\principal",multiplythatnumberby0.07,a ndthenstoretheresultinthe variablenamed\interest": interest=principal*0.07; Therearealso\inputcommands"forgettingdatafromtheuse rorfromlesonthecomputer's disksand\outputcommands"forsendingdataintheotherdir ection. Thesebasiccommands|formovingdatafromplacetoplaceand forperforming computations|arethebuildingblocksforallprograms.The sebuildingblocksarecombined intocomplexprogramsusingcontrolstructuresandsubrout ines. Aprogramisasequenceofinstructions.Intheordinary\row ofcontrol,"thecomputer executestheinstructionsinthesequenceinwhichtheyappe ar,oneaftertheother.However, thisisobviouslyverylimited:thecomputerwouldsoonruno utofinstructionstoexecute. Controlstructures arespecialinstructionsthatcanchangetherowofcontrol. Thereare twobasictypesofcontrolstructure: loops ,whichallowasequenceofinstructionstoberepeated overandover,and branches ,whichallowthecomputertodecidebetweentwoormoredier ent coursesofactionbytestingconditionsthatoccurasthepro gramisrunning. Forexample,itmightbethatifthevalueofthevariable\pri ncipal"isgreaterthan10000, thenthe\interest"shouldbecomputedbymultiplyingthepr incipalby0.05;ifnot,thenthe

PAGE 23

CHAPTER1.THEMENTALLANDSCAPE 9 interestshouldbecomputedbymultiplyingtheprincipalby 0.04.Aprogramneedssome wayofexpressingthistypeofdecision.InJava,itcouldbee xpressedusingthefollowing\if statement": if(principal>10000) interest=principal*0.05; else interest=principal*0.04; (Don'tworryaboutthedetailsfornow.Justrememberthatth ecomputercantestacondition anddecidewhattodonextonthebasisofthattest.) Loopsareusedwhenthesametaskhastobeperformedmorethan once.Forexample, ifyouwanttoprintoutamailinglabelforeachnameonamaili nglist,youmightsay,\Get therstnameandaddressandprintthelabel;getthesecondn ameandaddressandprint thelabel;getthethirdnameandaddressandprintthelabel| "Butthisquicklybecomes ridiculous|andmightnotworkatallifyoudon'tknowinadva ncehowmanynamesthereare. Whatyouwouldliketosayissomethinglike\Whiletherearem orenamestoprocess,getthe nextnameandaddress,andprintthelabel."Aloopcanbeused inaprogramtoexpresssuch repetition. Largeprogramsaresocomplexthatitwouldbealmostimpossi bletowritethemifthere werenotsomewaytobreakthemupintomanageable\chunks."S ubroutinesprovideonewayto dothis.A subroutine consistsoftheinstructionsforperformingsometask,grou pedtogether asaunitandgivenaname.Thatnamecanthenbeusedasasubsti tuteforthewholesetof instructions.Forexample,supposethatoneofthetaskstha tyourprogramneedstoperform istodrawahouseonthescreen.Youcantakethenecessaryins tructions,maketheminto asubroutine,andgivethatsubroutinesomeappropriatenam e|say,\drawHouse()".Then anyplaceinyourprogramwhereyouneedtodrawahouse,youca ndosowiththesingle command: drawHouse(); Thiswillhavethesameeectasrepeatingallthehouse-draw inginstructionsineachplace. Theadvantagehereisnotjustthatyousavetyping.Organizi ngyourprogramintosubroutinesalsohelpsyouorganizeyourthinkingandyourprog ramdesigneort.Whilewriting thehouse-drawingsubroutine,youcanconcentrateonthepr oblemofdrawingahousewithout worryingforthemomentabouttherestoftheprogram.Andonc ethesubroutineiswritten, youcanforgetaboutthedetailsofdrawinghouses|thatprob lemissolved,sinceyouhavea subroutinetodoitforyou.Asubroutinebecomesjustlikeab uilt-inpartofthelanguagewhich youcanusewithoutthinkingaboutthedetailsofwhatgoeson \inside"thesubroutine. Variables,types,loops,branches,andsubroutinesarethe basisofwhatmightbecalled \traditionalprogramming."However,asprogramsbecomela rger,additionalstructureisneeded tohelpdealwiththeircomplexity.Oneofthemosteectivet oolsthathasbeenfoundisobjectorientedprogramming,whichisdiscussedinthenextsectio n. 1.5ObjectsandObject-orientedProgrammingP rogramsmustbedesigned .Noonecanjustsitdownatthecomputerandcomposea (online)

PAGE 24

CHAPTER1.THEMENTALLANDSCAPE 10 programofanycomplexity.Thedisciplinecalled softwareengineering isconcernedwith theconstructionofcorrect,working,well-writtenprogra ms.Thesoftwareengineertendsto useacceptedandprovenmethodsforanalyzingtheproblemto besolvedandfordesigninga programtosolvethatproblem. Duringthe1970sandintothe80s,theprimarysoftwareengin eeringmethodologywas structuredprogramming .Thestructuredprogrammingapproachtoprogramdesignwas basedonthefollowingadvice:Tosolvealargeproblem,brea ktheproblemintoseveralpieces andworkoneachpieceseparately;tosolveeachpiece,treat itasanewproblemwhichcanitself bebrokendownintosmallerproblems;eventually,youwillw orkyourwaydowntoproblems thatcanbesolveddirectly,withoutfurtherdecomposition .Thisapproachiscalled top-down programming Thereisnothingwrongwithtop-downprogramming.Itisaval uableandoften-usedapproachtoproblem-solving.However,itisincomplete.Foro nething,itdealsalmostentirely withproducingthe instructions necessarytosolveaproblem.Butastimewenton,people realizedthatthedesignofthe datastructures foraprogramwasasleastasimportantasthe designofsubroutinesandcontrolstructures.Top-downpro grammingdoesn'tgiveadequate considerationtothedatathattheprogrammanipulates. Anotherproblemwithstricttop-downprogrammingisthatit makesitdiculttoreuse workdoneforotherprojects.Bystartingwithaparticularp roblemandsubdividingitinto convenientpieces,top-downprogrammingtendstoproducea designthatisuniquetothat problem.Itisunlikelythatyouwillbeabletotakealargech unkofprogrammingfromanother programandtitintoyourproject,atleastnotwithoutexte nsivemodication.Producing high-qualityprogramsisdicultandexpensive,soprogram mersandthepeoplewhoemploy themarealwayseagertoreusepastwork. So,inpractice,top-downdesignisoftencombinedwith bottom-updesign .Inbottom-up design,theapproachistostart\atthebottom,"withproble msthatyoualreadyknowhowto solve(andforwhichyoumightalreadyhaveareusablesoftwa recomponentathand).From there,youcanworkupwardstowardsasolutiontotheoverall problem. Thereusablecomponentsshouldbeas\modular"aspossible. A module isacomponentofa largersystemthatinteractswiththerestofthesysteminas imple,well-dened,straightforward manner.Theideaisthatamodulecanbe\pluggedinto"asyste m.Thedetailsofwhatgoeson insidethemodulearenotimportanttothesystemasawhole,a slongasthemodulefulllsits assignedrolecorrectly.Thisiscalled informationhiding ,anditisoneofthemostimportant principlesofsoftwareengineering. Onecommonformatforsoftwaremodulesistocontainsomedat a,alongwithsomesubroutinesformanipulatingthatdata.Forexample,amailing -listmodulemightcontainalistof namesandaddressesalongwithasubroutineforaddinganewn ame,asubroutineforprinting mailinglabels,andsoforth.Insuchmodules,thedataitsel fisoftenhiddeninsidethemodule; aprogramthatusesthemodulecanthenmanipulatethedataon lyindirectly,bycallingthe subroutinesprovidedbythemodule.Thisprotectsthedata, sinceitcanonlybemanipulated inknown,well-denedways.Anditmakesiteasierforprogra mstousethemodule,sincethey don'thavetoworryaboutthedetailsofhowthedataisrepres ented.Informationaboutthe representationofthedataishidden. Modulesthatcouldsupportthiskindofinformation-hiding becamecommoninprogramminglanguagesintheearly1980s.Sincethen,amoreadvance dformofthesameideahas moreorlesstakenoversoftwareengineering.Thislatestap proachiscalled object-oriented

PAGE 25

CHAPTER1.THEMENTALLANDSCAPE 11 programming ,oftenabbreviatedasOOP. Thecentralconceptofobject-orientedprogrammingisthe object ,whichisakindofmodule containingdataandsubroutines.Thepoint-of-viewinOOPi sthatanobjectisakindofselfsuciententitythathasaninternal state (thedataitcontains)andthatcanrespondto messages (callstoitssubroutines).Amailinglistobject,forexamp le,hasastateconsisting ofalistofnamesandaddresses.Ifyousenditamessagetelli ngittoaddaname,itwill respondbymodifyingitsstatetorerectthechange.Ifyouse nditamessagetellingittoprint itself,itwillrespondbyprintingoutitslistofnamesanda ddresses. TheOOPapproachtosoftwareengineeringistostartbyident ifyingtheobjectsinvolvedin aproblemandthemessagesthatthoseobjectsshouldrespond to.Theprogramthatresultsis acollectionofobjects,eachwithitsowndataanditsownset ofresponsibilities.Theobjects interactbysendingmessagestoeachother.Thereisnotmuch \top-down"insuchaprogram, andpeopleusedtomoretraditionalprogramscanhaveahardt imegettingusedtoOOP. However,peoplewhouseOOPwouldclaimthatobject-oriente dprogramstendtobebetter modelsofthewaytheworlditselfworks,andthattheyarethe reforeeasiertowrite,easierto understand,andmorelikelytobecorrect. Youshouldthinkofobjectsas\knowing"howtorespondtocer tainmessages.Dierent objectsmightrespondtothesamemessageindierentways.F orexample,a\print"message wouldproduceverydierentresults,dependingontheobjec titissentto.Thispropertyof objects|thatdierentobjectscanrespondtothesamemessa geindierentways|iscalled polymorphism Itiscommonforobjectstobearakindof\familyresemblance "tooneanother.Objects thatcontainthesametypeofdataandthatrespondtothesame messagesinthesameway belongtothesame class .(Inactualprogramming,theclassisprimary;thatis,acla ssis createdandthenoneormoreobjectsarecreatedusingthatcl assasatemplate.)Butobjects canbesimilarwithoutbeinginexactlythesameclass. Forexample,consideradrawingprogramthatletstheuserdr awlines,rectangles,ovals, polygons,andcurvesonthescreen.Intheprogram,eachvisi bleobjectonthescreencouldbe representedbyasoftwareobjectintheprogram.Therewould beveclassesofobjectsinthe program,oneforeachtypeofvisibleobjectthatcanbedrawn .Allthelineswouldbelongto oneclass,alltherectanglestoanotherclass,andsoon.The seclassesareobviouslyrelated; allofthemrepresent\drawableobjects."Theywould,forex ample,allpresumablybeableto respondtoa\drawyourself"message.Anotherlevelofgroup ing,basedonthedataneeded torepresenteachtypeofobject,islessobvious,butwouldb everyusefulinaprogram:We cangrouppolygonsandcurvestogetheras\multipointobjec ts,"whilelines,rectangles,and ovalsare\two-pointobjects."(Alineisdeterminedbyitse ndpoints,arectanglebytwoofits corners,andanovalbytwocornersoftherectanglethatcont ainsit.)Wecoulddiagramthese relationshipsasfollows:

PAGE 26

CHAPTER1.THEMENTALLANDSCAPE 12 #$ % & $ ( ) #( + + ( % & $ ( / 0 + ( % & $ ( 0 #1 2 3 4 $ 5 + $ 6 $ ( 2 #$ % 4 # DrawableObject,MultipointObject,andTwoPointObjectwo uldbeclassesintheprogram. MultipointObjectandTwoPointObjectwouldbe subclasses ofDrawableObject.Theclass LinewouldbeasubclassofTwoPointObjectand(indirectly) ofDrawableObject.Asubclassof aclassissaidto inherit thepropertiesofthatclass.Thesubclasscanaddtoitsinhe ritanceand itcaneven\override"partofthatinheritance(bydeninga dierentresponsetosomemethod). Nevertheless,lines,rectangles,andsoon are drawableobjects,andtheclassDrawableObject expressesthisrelationship. Inheritanceisapowerfulmeansfororganizingaprogram.It isalsorelatedtotheproblem ofreusingsoftwarecomponents.Aclassistheultimatereus ablecomponent.Notonlycanit bereuseddirectlyifittsexactlyintoaprogramyouaretry ingtowrite,butifitjustalmost ts,youcanstillreuseitbydeningasubclassandmakingon lythesmallchangesnecessary toadaptitexactlytoyourneeds. So,OOPismeanttobebothasuperiorprogram-developmentto olandapartialsolution tothesoftwarereuseproblem.Objects,classes,andobject -orientedprogrammingwillbe importantthemesthroughouttherestofthistext.1.6TheModernUserInterfaceW hencomputerswerefirstintroduced ,ordinarypeople|includingmostprogrammers| (online) couldn'tgetnearthem.Theywerelockedupinroomswithwhit e-coatedattendantswhowould takeyourprogramsanddata,feedthemtothecomputer,andre turnthecomputer'sresponse sometimelater.Whentimesharing|wherethecomputerswitc hesitsattentionrapidlyfrom onepersontoanother|wasinventedinthe1960s,itbecamepo ssibleforseveralpeopleto interactdirectlywiththecomputeratthesametime.Onatim esharingsystem,userssitat \terminals"wheretheytypecommandstothecomputer,andth ecomputertypesbackitsresponse.Earlypersonalcomputersalsousedtypedcommandsa ndresponses,exceptthatthere wasonlyonepersoninvolvedatatime.Thistypeofinteracti onbetweenauserandacomputer iscalleda command-lineinterface Today,ofcourse,mostpeopleinteractwithcomputersinaco mpletelydierentway.They usea GraphicalUserInterface ,orGUI.Thecomputerdrawsinterface components onthe screen.Thecomponentsincludethingslikewindows,scroll bars,menus,buttons,andicons. Usually,a mouse isusedtomanipulatesuchcomponents.Assumingthatyouhav enotjust beenteleportedinfromthe1970s,youarenodoubtalreadyfa miliarwiththebasicsofgraphical userinterfaces! AlotofGUIinterfacecomponentshavebecomefairlystandar d.Thatis,theyhavesimilar appearanceandbehavioronmanydierentcomputerplatform sincludingMacintosh,Windows,

PAGE 27

CHAPTER1.THEMENTALLANDSCAPE 13 andLinux.Javaprograms,whicharesupposedtorunonmanydi erentplatformswithout modicationtotheprogram,canuseallthestandardGUIcomp onents.Theymightvarya littleinappearancefromplatformtoplatform,buttheirfu nctionalityshouldbeidenticalon anycomputeronwhichtheprogramruns. ShownbelowisanimageofaverysimpleJavaprogram|actuall yan\ applet ",sinceitis meanttoappearonaWebpage|thatshowsafewstandardGUIint erfacecomponents.There arefourcomponentsthattheusercaninteractwith:abutton ,acheckbox,atexteld,anda pop-upmenu.Thesecomponentsarelabeled.Thereareafewot hercomponentsintheapplet. Thelabelsthemselvesarecomponents(eventhoughyoucan't interactwiththem).Theright halfoftheappletisatextareacomponent,whichcandisplay multiplelinesoftext,anda scrollbarcomponentappearsalongsidethetextareawhenth enumberoflinesoftextbecomes largerthanwilltinthetextarea.Andinfact,inJavatermi nology,thewholeappletisitself consideredtobea\component." Now,JavaactuallyhastwocompletesetsofGUIcomponents.O neofthese,theAWTor AbstractWindowingToolkit ,wasavailableintheoriginalversionofJava.Theother,wh ich isknownas Swing ,isincludedinJavaversion1.2orlater,andisusedinprefe rencetothe AWTinmostmodernJavaprograms.Theappletthatisshownabo veusescomponentsthat arepartofSwing.IfyourWebbrowserusesanoldversionofJa va,youmightgetanerror whenthebrowsertriestoloadtheapplet.Rememberthatmost oftheappletsinthistextbook requireJava5.0(orhigher). WhenauserinteractswiththeGUIcomponentsinthisapplet, an\event"isgenerated. Forexample,clickingapushbuttongeneratesanevent,andp ressingreturnwhiletypingina texteldgeneratesanevent.Eachtimeaneventisgenerated ,amessageissenttotheapplet tellingitthattheeventhasoccurred,andtheappletrespon dsaccordingtoitsprogram.In fact,theprogramconsistsmainlyof\eventhandlers"thatt elltheapplethowtorespondto varioustypesofevents.Inthisexample,theapplethasbeen programmedtorespondtoeach eventbydisplayingamessageinthetextarea. Theuseoftheterm\message"hereisdeliberate.Messages,a syousawintheprevioussection,aresenttoobjects.Infact,JavaGUIcomponentsareim plementedasobjects.Java includesmanypredenedclassesthatrepresentvarioustyp esofGUIcomponents.Someof theseclassesaresubclassesofothers.Hereisadiagramsho wingsomeofSwing'sGUIclasses andtheirrelationships:

PAGE 28

CHAPTER1.THEMENTALLANDSCAPE 14 7 8 9 : ; 9 < = < > 7 ? @ A = B 7 C A D > E @ F > G H > > 9 < 7 8 9 : A 9 G 9 I 7 J = I > 8 9 : ; 9 < = < > 7 G H > > 9 < 7 J 9 K K B = G H > > 9 < 7 8 L = F M G 9 I 7 N @ O P 9 G H > > 9 < 7 Q F E 9 B B A @ E 7 J = I > R P = B O 7 J = I > C E = @ Don'tworryaboutthedetailsfornow,buttrytogetsomefeel abouthowobject-oriented programmingandinheritanceareusedhere.Notethatallthe GUIclassesaresubclasses, directlyorindirectly,ofaclasscalled JComponent ,whichrepresentsgeneralpropertiesthatare sharedbyallSwingcomponents.Twoofthedirectsubclasses of JComponent themselveshave subclasses.Theclasses JTextArea and JTextField ,whichhavecertainbehaviorsincommon, aregroupedtogetherassubclassesof JTextComponent .Similarly JButton and JToggleButton aresubclassesof JAbstractButton ,whichrepresentspropertiescommontobothbuttonsand checkboxes.( JComboBox ,bytheway,istheSwingclassthatrepresentspop-upmenus. ) Justfromthisbriefdiscussion,perhapsyoucanseehowGUIp rogrammingcanmakeeectiveuseofobject-orienteddesign.Infact,GUI's,withthe ir\visibleobjects,"areprobablya majorfactorcontributingtothepopularityofOOP. ProgrammingwithGUIcomponentsandeventsisoneofthemost interestingaspectsof Java.However,wewillspendseveralchaptersonthebasicsb eforereturningtothistopicin Chapter6 1.7TheInternetandtheWorld-WideWebC omputerscanbeconnected togetheron networks .Acomputeronanetworkcan (online) communicatewithothercomputersonthesamenetworkbyexch angingdataandlesorby sendingandreceivingmessages.Computersonanetworkcane venworktogetheronalarge computation. Today,millionsofcomputersthroughouttheworldareconne ctedtoasinglehugenetwork calledthe Internet .NewcomputersarebeingconnectedtotheInterneteveryday .Computers canjointheInternetbyusingamodemtoestablishaconnecti onthroughtelephonelines. Broadbandconnections totheInternet,suchasDSLandcablemodems,areincreasing ly common.Theyallowfasterdatatransmissionthanispossibl ethroughtelephonemodems. Thereareelaborate protocols forcommunicationovertheInternet.Aprotocolissimplya detailedspecicationofhowcommunicationistoproceed.F ortwocomputerstocommunicate atall,theymustbothbeusingthesameprotocols.Themostba sicprotocolsontheInternetare the InternetProtocol (IP),whichspecieshowdataistobephysicallytransmitte dfromone computertoanother,andthe TransmissionControlProtocol (TCP),whichensuresthat datasentusingIPisreceivedinitsentiretyandwithouterr or.Thesetwoprotocols,whichare referredtocollectivelyasTCP/IP,provideafoundationfo rcommunication.Otherprotocols

PAGE 29

CHAPTER1.THEMENTALLANDSCAPE 15 useTCP/IPtosendspecictypesofinformationsuchaswebpa ges,electronicmail,anddata les. AllcommunicationovertheInternetisintheformof packets .Apacketconsistsofsome databeingsentfromonecomputertoanother,alongwithaddr essinginformationthatindicates whereontheInternetthatdataissupposedtogo.Thinkofapa cketasanenvelopewithan addressontheoutsideandamessageontheinside.(Themessa geisthedata.)Thepacket alsoincludesa\returnaddress,"thatis,theaddressofthe sender.Apacketcanholdonly alimitedamountofdata;longermessagesmustbedividedamo ngseveralpackets,whichare thensentindividuallyoverthenetandreassembledattheir destination. EverycomputerontheInternethasan IPaddress ,anumberthatidentiesituniquely amongallthecomputersonthenet.TheIPaddressisusedfora ddressingpackets.Acomputer canonlysenddatatoanothercomputerontheInternetifitkn owsthatcomputer'sIPaddress. Sincepeopleprefertousenamesratherthannumbers,mostco mputersarealsoidentiedby names,called domainnames .Forexample,themaincomputeroftheMathematicsDepartmentatHobartandWilliamSmithCollegeshasthedomainname math.hws.edu.(Domain namesarejustforconvenience;yourcomputerstillneedsto knowIPaddressesbeforeitcan communicate.TherearecomputersontheInternetwhosejobi tistotranslatedomainnames toIPaddresses.Whenyouuseadomainname,yourcomputersen dsamessagetoadomain nameservertondoutthecorrespondingIPaddress.Then,yo urcomputerusestheIPaddress, ratherthanthedomainname,tocommunicatewiththeotherco mputer.) TheInternetprovidesanumberofservicestothecomputersc onnectedtoit(and,ofcourse, totheusersofthosecomputers).TheseservicesuseTCP/IPt osendvarioustypesofdataover thenet.Amongthemostpopularservicesareinstantmessagi ng,lesharing,electronicmail, andtheWorld-WideWeb.Eachservicehasitsownprotocols,w hichareusedtocontrol transmissionofdataoverthenetwork.Eachservicealsohas somesortofuserinterface,which allowstheusertoview,send,andreceivedatathroughthese rvice. Forexample,theemailserviceusesaprotocolknownas SMTP (SimpleMailTransfer Protocol)totransferemailmessagesfromonecomputertoan other.Otherprotocols,suchas POPandIMAP,areusedtofetchmessagesfromanemailaccount sothattherecipientcan readthem.Apersonwhousesemail,however,doesn'tneedtou nderstandorevenknowabout theseprotocols.Instead,theyareusedbehindthescenesby theprogramsthatthepersonuses tosendandreceiveemailmessages.Theseprogramsprovidea neasy-to-useuserinterfaceto theunderlyingnetworkprotocols. TheWorld-WideWebisperhapsthemostexcitingofnetworkse rvices.TheWorld-Wide Weballowsyoutorequest pages ofinformationthatarestoredoncomputersalloverthe Internet.AWebpagecancontain links tootherpagesonthesamecomputerfromwhichit wasobtainedortoothercomputersanywhereintheworld.Aco mputerthatstoressuchpages ofinformationiscalleda webserver .TheuserinterfacetotheWebisthetypeofprogram knownasa webbrowser .CommonwebbrowsersincludeInternetExplorerandFirefox .You useaWebbrowsertorequestapageofinformation.Thebrowse rwillsendarequestforthat pagetothecomputeronwhichthepageisstored,andwhenares ponseisreceivedfromthat computer,thewebbrowserdisplaysittoyouinaneatlyforma ttedform.Awebbrowserisjust auserinterfacetotheWeb.Behindthescenes,thewebbrowse rusesaprotocolcalled HTTP (HyperTextTransferProtocol)tosendeachpagerequestand toreceivetheresponsefromthe webserver. Nowjustwhat,youmightbethinking,doesallthishavetodow ithJava?Infact,Java

PAGE 30

CHAPTER1.THEMENTALLANDSCAPE 16 isintimatelyassociatedwiththeInternetandtheWorld-Wi deWeb.Asyouhaveseeninthe previoussection,specialJavaprogramscalledappletsare meanttobetransmittedoverthe InternetanddisplayedonWebpages.AWebservertransmitsa Javaappletjustasitwould transmitanyothertypeofinformation.AWebbrowserthatun derstandsJava|thatis,that includesaninterpreterfortheJavavirtualmachine|canth enruntheappletrightontheWeb page.Sinceappletsareprograms,theycandoalmostanythin g,includingcomplexinteraction withtheuser.WithJava,aWebpagebecomesmorethanjustapa ssivedisplayofinformation. Itbecomesanythingthatprogrammerscanimagineandimplem ent. ButappletsareonlyoneaspectofJava'srelationshipwitht heInternet,andnotthemajor one.Infact,asbothJavaandtheInternethavematured,appl etshavebecomelessimportant. Atthesametime,however,Javahasincreasinglybeenusedto writecomplex,stand-alone applicationsthatdonotdependonawebbrowser.Manyofthes eprogramsarenetworkrelated.Forexamplemanyofthelargestandmostcomplexweb sitesusewebserversoftware thatiswritteninJava.Javaincludesexcellentsupportfor networkprotocols,anditsplatform independencemakesitpossibletowritenetworkprogramsth atworkonmanydierenttypes ofcomputer. ItsassociationwiththeInternetisnotJava'sonlyadvanta ge.Butmanygoodprogramming languageshavebeeninventedonlytobesoonforgotten.Java hashadthegoodlucktorideon thecoattailsoftheInternet'simmenseandincreasingpopu larity.

PAGE 31

Quiz 17 QuizonChapter1 (answers) 1. Oneofthecomponentsofacomputerisits CPU. WhatisaCPUandwhatroledoesit playinacomputer? 2. Explainwhatismeantbyan\asynchronousevent."Givesomee xamples. 3. Whatisthedierencebetweena\compiler"andan\interpret er"? 4. Explainthedierencebetween high-levellanguages and machinelanguage. 5. IfyouhavethesourcecodeforaJavaprogram,andyouwanttor unthatprogram,you willneedbotha compiler andan interpreter. WhatdoestheJavacompilerdo,andwhat doestheJavainterpreterdo? 6. Whatisa subroutine? 7. Javaisanobject-orientedprogramminglanguage.Whatisan object ? 8. Whatisa variable? (Therearefourdierentideasassociatedwithvariablesin Java.Try tomentionallfouraspectsinyouranswer.Hint:Oneoftheas pectsisthevariable's name.) 9. Javaisa\platform-independentlanguage."Whatdoesthism ean? 10. Whatisthe\Internet"?Givesomeexamplesofhowitisused.( Whatkindofservices doesitprovide?)

PAGE 32

Chapter2ProgrammingintheSmallI:NamesandThingsO nabasiclevel (thelevelofmachinelanguage),acomputercanperformonly verysimple operations.Acomputerperformscomplextasksbystringing togetherlargenumbersofsuch operations.Suchtasksmustbe\scripted"incompleteandpe rfectdetailbyprograms.Creating complexprogramswillneverbereallyeasy,butthediculty canbehandledtosomeextentby givingtheprogramaclearoverall structure .Thedesignoftheoverallstructureofaprogram iswhatIcall\programminginthelarge." Programminginthesmall,whichissometimescalled coding ,wouldthenrefertollingin thedetailsofthatdesign.Thedetailsaretheexplicit,ste p-by-stepinstructionsforperforming fairlysmall-scaletasks.Whenyoudocoding,youareworkin gfairly\closetothemachine," withsomeofthesameconceptsthatyoumightuseinmachinela nguage:memorylocations, arithmeticoperations,loopsandbranches.Inahigh-level languagesuchasJava,yougetto workwiththeseconceptsonalevelseveralstepsabovemachi nelanguage.However,youstill havetoworryaboutgettingallthedetailsexactlyright. Thischapterandthenextexaminethefacilitiesforprogram minginthesmallintheJava programminglanguage.Don'tbemisledbytheterm\programm inginthesmall"intothinking thatthismaterialiseasyorunimportant.Thismaterialisa nessentialfoundationforalltypes ofprogramming.Ifyoudon'tunderstandit,youcan'twritep rograms,nomatterhowgood yougetatdesigningtheirlarge-scalestructure.2.1TheBasicJavaApplicationA programisasequence ofinstructionsthatacomputercanexecutetoperformsome (online) task.Asimpleenoughidea,butforthecomputertomakeanyus eoftheinstructions,they mustbewritteninaformthatthecomputercanuse.Thismeans thatprogramshavetobe writtenin programminglanguages .Programminglanguagesdierfromordinaryhuman languagesinbeingcompletelyunambiguousandverystricta boutwhatisandisnotallowed inaprogram.Therulesthatdeterminewhatisallowedarecal ledthe syntax ofthelanguage. Syntaxrulesspecifythebasicvocabularyofthelanguagean dhowprogramscanbeconstructed usingthingslikeloops,branches,andsubroutines.Asynta cticallycorrectprogramisonethat canbesuccessfullycompiledorinterpreted;programsthat havesyntaxerrorswillberejected (hopefullywithausefulerrormessagethatwillhelpyouxt heproblem). So,tobeasuccessfulprogrammer,youhavetodevelopadetai ledknowledgeofthesyntax 18

PAGE 33

CHAPTER2.NAMESANDTHINGS 19 oftheprogramminglanguagethatyouareusing.However,syn taxisonlypartofthestory.It's notenoughtowriteaprogramthatwillrun|youwantaprogram thatwillrunandproduce thecorrectresult!Thatis,the meaning oftheprogramhastoberight.Themeaningofa programisreferredtoasits semantics .Asemanticallycorrectprogramisonethatdoeswhat youwantitto. Furthermore,aprogramcanbesyntacticallyandsemantical lycorrectbutstillbeapretty badprogram.Usingthelanguagecorrectlyisnotthesameasu singit well .Forexample,a goodprogramhas\style."Itiswritteninawaythatwillmake iteasyforpeopletoreadand tounderstand.Itfollowsconventionsthatwillbefamiliar tootherprogrammers.Andithas anoveralldesignthatwillmakesensetohumanreaders.Thec omputeriscompletelyoblivious tosuchthings,buttoahumanreader,theyareparamount.The seaspectsofprogrammingare sometimesreferredtoas pragmatics. WhenIintroduceanewlanguagefeature,Iwillexplainthesy ntax,thesemantics,and someofthepragmaticsofthatfeature.Youshouldmemorizet hesyntax;that'stheeasypart. Thenyoushouldgetafeelingforthesemanticsbyfollowingt heexamplesgiven,makingsure thatyouunderstandhowtheywork,andmaybewritingshortpr ogramsofyourowntotest yourunderstanding.Andyoushouldtrytoappreciateandabs orbthepragmatics|thismeans learninghowtousethelanguagefeature well ,withstylethatwillearnyoutheadmirationof otherprogrammers. Ofcourse,evenwhenyou'vebecomefamiliarwithalltheindi vidualfeaturesofthelanguage, thatdoesn'tmakeyouaprogrammer.Youstillhavetolearnho wtoconstructcomplexprograms tosolveparticularproblems.Forthat,you'llneedbothexp erienceandtaste.You'llndhints aboutsoftwaredevelopmentthroughoutthistextbook. WebeginourexplorationofJavawiththeproblemthathasbec ometraditionalforsuch beginnings:towriteaprogramthatdisplaysthemessage\He lloWorld!".Thismightseemlike atrivialproblem,butgettingacomputertodothisisreally abigrststepinlearninganew programminglanguage(especiallyifit'syourrstprogram minglanguage).Itmeansthatyou understandthebasicprocessof: 1. gettingtheprogramtextintothecomputer, 2. compilingtheprogram,and 3. runningthecompiledprogram. Thersttimethrough,eachofthesestepswillprobablytake youafewtriestogetright.I won'tgointothedetailshereofhowyoudoeachofthesesteps ;itdependsontheparticular computerandJavaprogrammingenvironmentthatyouareusin g.See Section2.6 forinformationaboutcreatingandrunningJavaprogramsinspecicpro grammingenvironments.Butin general,youwilltypetheprogramusingsomesortoftextedi torandsavetheprogramina le.Then,youwillusesomecommandtotrytocompilethele. You'lleithergetamessage thattheprogramcontainssyntaxerrors,oryou'llgetacomp iledversionoftheprogram.In thecaseofJava,theprogramiscompiledintoJavabytecode, notintomachinelanguage.Finally,youcanrunthecompiledprogrambygivingsomeapprop riatecommand.ForJava,you willactuallyuseaninterpretertoexecutetheJavabytecod e.Yourprogrammingenvironment mightautomatesomeofthestepsforyou,butyoucanbesureth atthesamethreestepsare beingdoneinthebackground. HereisaJavaprogramtodisplaythemessage\HelloWorld!". Don'texpecttounderstand what'sgoingonherejustyet|someofityouwon'treallyunde rstanduntilafewchaptersfrom

PAGE 34

CHAPTER2.NAMESANDTHINGS 20 now: //Aprogramtodisplaythemessage//"HelloWorld!"onstandardoutputpublicclassHelloWorld{ publicstaticvoidmain(String[]args){ System.out.println("HelloWorld!"); } }//endofclassHelloWorld Thecommandthatactuallydisplaysthemessageis: System.out.println("HelloWorld!"); Thiscommandisanexampleofa subroutinecallstatement .Itusesa\built-insubroutine" named System.out.println todotheactualwork.Recallthatasubroutineconsistsofth e instructionsforperformingsometask,chunkedtogetheran dgivenaname.Thatnamecanbe usedto\call"thesubroutinewheneverthattaskneedstobep erformed.A built-insubroutine isonethatisalreadydenedaspartofthelanguageandthere foreautomaticallyavailablefor useinanyprogram. Whenyourunthisprogram,themessage\HelloWorld!"(witho utthequotes)willbe displayedonstandardoutput.Unfortunately,Ican'tsayex actlywhatthatmeans!Javais meanttorunonmanydierentplatforms,andstandardoutput willmeandierentthingson dierentplatforms.However,youcanexpectthemessagetos howupinsomeconvenientplace. (Ifyouuseacommand-lineinterface,likethatinSunMicros ystem'sJavaDevelopmentKit, youtypeinacommandtotellthecomputertoruntheprogram.T hecomputerwilltypethe outputfromtheprogram,HelloWorld!,onthenextline.) Youmustbecuriousaboutalltheotherstuintheaboveprogr am.Partofitconsistsof comments .Commentsinaprogramareentirelyignoredbythecomputer; theyaretherefor humanreadersonly.Thisdoesn'tmeanthattheyareunimport ant.Programsaremeanttobe readbypeopleaswellasbycomputers,andwithoutcomments, aprogramcanbeverydicult tounderstand.Javahastwotypesofcomments.Thersttype, usedintheaboveprogram, beginswith//andextendstotheendofaline.Thecomputerig noresthe//andeverything thatfollowsitonthesameline.Javahasanotherstyleofcom mentthatcanextendovermany lines.Thattypeofcommentbeginswith/*andendswith*/. EverythingelseintheprogramisrequiredbytherulesofJav asyntax.Allprogrammingin Javaisdoneinside\classes."Therstlineintheaboveprog ram(notcountingthecomments) saysthatthisisaclassnamed HelloWorld .\HelloWorld,"thenameoftheclass,alsoservesas thenameoftheprogram.Noteveryclassisaprogram.Inorder todeneaprogram,aclass mustincludeasubroutinenamed main ,withadenitionthattakestheform: publicstaticvoidmain(String[]args){ h statements i } WhenyoutelltheJavainterpretertoruntheprogram,theint erpretercallsthe main() subroutine,andthestatementsthatitcontainsareexecute d.Thesestatementsmakeupthe scriptthattellsthecomputerexactlywhattodowhenthepro gramisexecuted.The main() routinecancallsubroutinesthataredenedinthesameclas soreveninotherclasses,butitis the main() routinethatdetermineshowandinwhatordertheothersubro utinesareused.

PAGE 35

CHAPTER2.NAMESANDTHINGS 21 Theword\public"intherstlineof main() meansthatthisroutinecanbecalledfromoutsidetheprogram.Thisisessentialbecausethe main() routineiscalledbytheJavainterpreter, whichissomethingexternaltotheprogramitself.Theremai nderoftherstlineoftheroutine ishardertoexplainatthemoment;fornow,justthinkofitas partoftherequiredsyntax. Thedenitionofthesubroutine|thatis,theinstructionst hatsaywhatitdoes|consistsof thesequenceof\statements"enclosedbetweenbraces, { and } .Here,I'veused h statements i as aplaceholderfortheactualstatementsthatmakeuptheprog ram.Throughoutthistextbook, Iwillalwaysuseasimilarformat:anythingthatyouseein h thisstyleoftext i (italicinangle brackets)isaplaceholderthatdescribessomethingyounee dtotypewhenyouwriteanactual program. Asnotedabove,asubroutinecan'texistbyitself.Ithastob epartofa\class".Aprogram isdenedbyapublicclassthattakestheform: publicclass h program-name i { h optional-variable-declarations-and-subroutines i publicstaticvoidmain(String[]args){ h statements i }h optional-variable-declarations-and-subroutines i } Thenameontherstlineisthenameoftheprogram,aswellast henameoftheclass.Ifthe nameoftheclassisHelloWorld,thentheclassmustbesavedi nalecalled HelloWorld.java Whenthisleiscompiled,anotherlenamed HelloWorld.class willbeproduced.Thisclass le, HelloWorld.class ,containstheJavabytecodethatisexecutedbyaJavainterp reter. HelloWorld.java iscalledthe sourcecode fortheprogram.Toexecutetheprogram,you onlyneedthecompiled class le,notthesourcecode. Thelayoutoftheprogramonthepage,suchastheuseofblankl inesandindentation,is notpartofthesyntaxorsemanticsofthelanguage.Thecompu terdoesn'tcareaboutlayout| youcouldruntheentireprogramtogetherononelineasfaras itisconcerned.However, layoutisimportanttohumanreaders,andtherearecertains tyleguidelinesforlayoutthatare followedbymostprogrammers.Thesestyleguidelinesarepa rtofthepragmaticsoftheJava programminglanguage. Alsonotethataccordingtotheabovesyntaxspecication,a programcancontainother subroutinesbesides main() ,aswellasthingscalled\variabledeclarations."You'lll earnmore abouttheselater,butnotuntil Chapter4 2.2VariablesandthePrimitiveTypesN amesarefundamentaltoprogramming .Inprograms,namesareusedtorefertomany (online) dierentsortsofthings.Inordertousethosethings,aprog rammermustunderstandtherules forgivingnamestothingsandtherulesforusingthenamesto workwiththosethings.That is,theprogrammermustunderstandthesyntaxandthesemant icsofnames. AccordingtothesyntaxrulesofJava,anameisasequenceofo neormorecharacters.Itmust beginwithaletterorunderscoreandmustconsistentirelyo fletters,digits,andunderscores. (\Underscore"referstothecharacter' '.)Forexample,herearesomelegalnames: Nnratex15quite a long nameHelloWorld

PAGE 36

CHAPTER2.NAMESANDTHINGS 22 Nospacesareallowedinidentiers; HelloWorld isalegalidentier,but\HelloWorld"is not.Uppercaseandlowercaselettersareconsideredtobedi erent,sothat HelloWorld helloworld HELLOWORLD ,and hElloWorLD arealldistinctnames.Certainnamesarereserved forspecialusesinJava,andcannotbeusedbytheprogrammer forotherpurposes.These reservedwords include: class public static if else while ,andseveraldozenother words. Javaisactuallyprettyliberalaboutwhatcountsasaletter oradigit.Javausesthe Unicode characterset,whichincludesthousandsofcharactersfrom manydierentlanguages anddierentalphabets,andmanyofthesecharacterscounta slettersordigits.However,Iwill bestickingtowhatcanbetypedonaregularEnglishkeyboard Thepragmaticsofnamingincludesstyleguidelinesaboutho wtochoosenamesforthings. Forexample,itiscustomaryfornamesofclassestobeginwit huppercaseletters,whilenames ofvariablesandofsubroutinesbeginwithlowercaseletter s;youcanavoidalotofconfusion byfollowingthesameconventioninyourownprograms.MostJ avaprogrammersdonotuse underscoresinnames,althoughsomedousethematthebeginn ingofthenamesofcertainkinds ofvariables.Whenanameismadeupofseveralwords,suchas HelloWorld or interestRate itiscustomarytocapitalizeeachword,exceptpossiblythe rst;thisissometimesreferred toas camelcase ,sincetheuppercaselettersinthemiddleofanamearesuppo sedtolook somethinglikethehumpsonacamel'sback. Finally,I'llnotethatthingsareoftenreferredtoby compoundnames whichconsist ofseveralordinarynamesseparatedbyperiods.(Compoundn amesarealsocalled qualied names .)You'vealreadyseenanexample: System.out.println .Theideahereisthatthings inJavacancontainotherthings.Acompoundnameisakindofp athtoanitemthroughone ormorelevelsofcontainment.Thename System.out.println indicatesthatsomethingcalled \System"containssomethingcalled\out"whichinturncont ainssomethingcalled\println". Non-compoundnamesarecalled simpleidentiers .I'llusetheterm identier toreferto anyname|simpleorcompound|thatcanbeusedtorefertosome thinginJava.(Notethat thereservedwordsare not identiers,sincetheycan'tbeusedasnamesforthings.) 2.2.1VariablesProgramsmanipulatedatathatarestoredinmemory.Inmachi nelanguage,datacanonly bereferredtobygivingthenumericaladdressofthelocatio ninmemorywhereitisstored. Inahigh-levellanguagesuchasJava,namesareusedinstead ofnumberstorefertodata.It isthejobofthecomputertokeeptrackofwhereinmemorythed ataisactuallystored;the programmeronlyhastorememberthename.Anameusedinthisw ay|torefertodatastored inmemory|iscalleda variable Variablesareactuallyrathersubtle.Properlyspeaking,a variableisnotanameforthe dataitselfbutforalocationinmemorythatcanholddata.Yo ushouldthinkofavariableas acontainerorboxwhereyoucanstoredatathatyouwillneedt ouselater.Thevariablerefers directlytotheboxandonlyindirectlytothedatainthebox. Sincethedataintheboxcan change,avariablecanrefertodierentdatavaluesatdier enttimesduringtheexecutionof theprogram,butitalwaysreferstothesamebox.Confusionc anarise,especiallyforbeginning programmers,becausewhenavariableisusedinaprograminc ertainways,itreferstothe container,butwhenitisusedinotherways,itreferstothed atainthecontainer.You'llsee examplesofbothcasesbelow. (Inthisway,avariableissomethinglikethetitle,\ThePre sidentoftheUnitedStates." Thistitlecanrefertodierentpeopleatdierenttimes,bu titalwaysreferstothesameoce.

PAGE 37

CHAPTER2.NAMESANDTHINGS 23 IfIsay\thePresidentwentshing,"ImeanthatGeorgeW.Bus hwentshing.ButifIsay \HillaryClintonwantstobePresident"Imeanthatshewants tolltheoce,notthatshe wantstobeGeorgeBush.) InJava,the only waytogetdataintoavariable|thatis,intotheboxthatthev ariable names|iswithan assignmentstatement .Anassignmentstatementtakestheform: h variable i = h expression i ; where h expression i representsanythingthatreferstoorcomputesadatavalue. Whenthe computercomestoanassignmentstatementinthecourseofex ecutingaprogram,itevaluates theexpressionandputstheresultingdatavalueintothevar iable.Forexample,considerthe simpleassignmentstatement rate=0.07; The h variable i inthisassignmentstatementis rate ,andthe h expression i isthenumber0.07. Thecomputerexecutesthisassignmentstatementbyputting thenumber0.07inthevariable rate ,replacingwhateverwastherebefore.Now,considerthefol lowingmorecomplicated assignmentstatement,whichmightcomelaterinthesamepro gram: interest=rate*principal; Here,thevalueoftheexpression\ rate*principal "isbeingassignedtothevariable interest .Intheexpression,the isa\multiplicationoperator"thattellsthecomputer tomultiply rate times principal .Thenames rate and principal arethemselvesvariables, anditisreallythe values storedinthosevariablesthataretobemultiplied.Weseeth atwhen avariableisusedinanexpression,itisthevaluestoredint hevariablethatmatters;inthis case,thevariableseemstorefertothedatainthebox,rathe rthantotheboxitself.When thecomputerexecutesthisassignmentstatement,ittakest he value of rate ,multipliesitby the value of principal ,andstorestheanswerinthe box referredtoby interest .Whena variableisusedontheleft-handsideofanassignmentstate ment,itreferstotheboxthatis namedbythevariable. (Note,bytheway,thatanassignmentstatementisacommandt hatisexecutedbythe computeratacertaintime.Itisnotastatementoffact.Fore xample,supposeaprogram includesthestatement\ rate=0.07; ".Ifthestatement\ interest=rate*principal; isexecutedlaterintheprogram,canwesaythatthe principal ismultipliedby0.07?No! Thevalueof rate mighthavebeenchangedinthemeantimebyanotherstatement .The meaningofanassignmentstatementiscompletelydierentf romthemeaningofanequation inmathematics,eventhoughbothusethesymbol\=".)2.2.2TypesandLiteralsAvariableinJavaisdesignedtoholdonlyoneparticulartyp eofdata;itcanlegallyholdthat typeofdataandnoother.Thecompilerwillconsiderittobea syntaxerrorifyoutryto violatethisrule.WesaythatJavaisa stronglytyped languagebecauseitenforcesthisrule. Thereareeightso-called primitivetypes builtintoJava.Theprimitivetypesarenamed byte short int long roat double char ,and boolean .Therstfourtypesholdintegers (wholenumberssuchas17,-38477,and0).Thefourintegerty pesaredistinguishedbythe rangesofintegerstheycanhold.The roat and double typesholdrealnumbers(suchas3.6and -145.99).Again,thetworealtypesaredistinguishedbythe irrangeandaccuracy.Avariable oftype char holdsasinglecharacterfromtheUnicodecharacterset.And avariableoftype boolean holdsoneofthetwologicalvalues true or false

PAGE 38

CHAPTER2.NAMESANDTHINGS 24 Anydatavaluestoredinthecomputer'smemorymustberepres entedasabinarynumber, thatisasastringofzerosandones.Asinglezerooroneiscal leda bit .Astringofeight bitsiscalleda byte .Memoryisusuallymeasuredintermsofbytes.Notsurprisin gly,the byte datatypereferstoasinglebyteofmemory.Avariableoftype byte holdsastringofeight bits,whichcanrepresentanyoftheintegersbetween-128an d127,inclusive.(Thereare256 integersinthatrange;eightbitscanrepresent256|tworai sedtothepowereight|dierent values.)Asfortheotherintegertypes, short correspondstotwobytes(16bits).Variablesoftype short havevaluesintherange -32768to32767. int correspondstofourbytes(32bits).Variablesoftype int havevaluesintherange -2147483648to2147483647. long correspondstoeightbytes(64bits).Variablesoftype long havevaluesintherange -9223372036854775808to9223372036854775807. Youdon'thavetorememberthesenumbers,buttheydogiveyou someideaofthesizeof integersthatyoucanworkwith.Usually,youshouldjuststi cktothe int datatype,whichis goodenoughformostpurposes. The roat datatypeisrepresentedinfourbytesofmemory,usingastan dardmethodfor encodingrealnumbers.Themaximumvaluefora roat isabout10raisedtothepower38. A roat canhaveabout7signicantdigits.(Sothat32.3989231134a nd32.3989234399would bothhavetoberoundedotoabout32.398923inordertobesto redinavariableoftype roat .)A double takesup8bytes,canrangeuptoabout10tothepower308,andh asabout 15signicantdigits.Ordinarily,youshouldsticktothe double typeforrealvalues. Avariableoftype char occupiestwobytesinmemory.Thevalueofa char variableisa singlecharactersuchasA,*,x,oraspacecharacter.Theval uecanalsobeaspecialcharacter suchataboracarriagereturnoroneofthemanyUnicodechara ctersthatcomefromdierent languages.Whenacharacteristypedintoaprogram,itmustb esurroundedbysinglequotes; forexample:'A','*',or'x'.Withoutthequotes,Awouldbea nidentierand*wouldbea multiplicationoperator.Thequotesarenotpartofthevalu eandarenotstoredinthevariable; theyarejustaconventionfornamingaparticularcharacter constantinaprogram. Anameforaconstantvalueiscalleda literal .Aliteraliswhatyouhavetotypeina programtorepresentavalue.'A'and'*'areliteralsoftype char ,representingthecharacter valuesAand*.Certainspecialcharactershavespeciallite ralsthatuseabackslash, \ ,asan \escapecharacter".Inparticular,atabisrepresentedas '\t' ,acarriagereturnas '\r' ,a linefeedas '\n' ,thesinglequotecharacteras '\'' ,andthebackslashitselfas '\\' .Notethat eventhoughyoutypetwocharactersbetweenthequotesin '\t' ,thevaluerepresentedbythis literalisasingletabcharacter. Numericliteralsarealittlemorecomplicatedthanyoumigh texpect.Ofcourse,there aretheobviousliteralssuchas317and17.42.Butthereareo therpossibilitiesforexpressing numbersinaJavaprogram.Firstofall,realnumberscanbere presentedinanexponential formsuchas1.3e12or12.3737e-108.The\e12"and\e-108"re presentpowersof10,sothat 1.3e12means1.3times10 12 and12.3737e-108means12.3737times10 108 .Thisformatcan beusedtoexpressverylargeandverysmallnumbers.Anynume ricalliteralthatcontainsa decimalpointorexponentialisaliteraloftype double .Tomakealiteraloftype roat ,you havetoappendan\F"or\f"totheendofthenumber.Forexampl e,\1.2F"standsfor1.2 consideredasavalueoftype roat .(Occasionally,youneedtoknowthisbecausetherulesof Javasaythatyoucan'tassignavalueoftype double toavariableoftype roat ,soyoumightbe

PAGE 39

CHAPTER2.NAMESANDTHINGS 25 confrontedwitharidiculous-seemingerrormessageifyout rytodosomethinglike\ x=1.2; when x isavariableoftype roat .Youhavetosay\ x=1.2F;" .ThisisonereasonwhyI advisestickingtotype double forrealnumbers.) Evenforintegerliterals,therearesomecomplications.Or dinaryintegerssuchas177777 and-32areliteralsoftype byte short ,or int ,dependingontheirsize.Youcanmakealiteral oftype long byadding\L"asasux.Forexample:17Lor728476874368L.As another complication,Javaallowsoctal(base-8)andhexadecimal( base-16)literals.Idon'twantto coverbase-8andbase-16indetail,butincaseyourunintoth eminotherpeople'sprograms, it'sworthknowingafewthings:Octalnumbersuseonlythedi gits0through7.InJava,a numericliteralthatbeginswitha0isinterpretedasanocta lnumber;forexample,theliteral 045representsthenumber37,notthenumber45.Hexadecimal numbersuse16digits,the usualdigits0through9andthelettersA,B,C,D,E,andF.Upp ercaseandlowercaseletters canbeusedinterchangeablyinthiscontext.Thelettersrep resentthenumbers10through15. InJava,ahexadecimalliteralbeginswith 0x or 0X ,asin 0x45 or 0xFF7A Hexadecimalnumbersarealsousedincharacterliteralstor epresentarbitraryUnicode characters.AUnicodeliteralconsistsof \u followedbyfourhexadecimaldigits.Forexample, thecharacterliteral '\u00E9' representstheUnicodecharacterthatisan\e"withanacute accent. Forthetype boolean ,therearepreciselytwoliterals: true and false .Theseliteralsare typedjustasI'vewrittenthemhere,withoutquotes,butthe yrepresentvalues,notvariables. Booleanvaluesoccurmostoftenasthevaluesofconditional expressions.Forexample, rate>0.05 isaboolean-valuedexpressionthatevaluatesto true ifthevalueofthevariable rate isgreater than0.05,andto false ifthevalueof rate isnotgreaterthan0.05.Asyou'llseein Chapter3 boolean-valuedexpressionsareusedextensivelyincontro lstructures.Ofcourse,booleanvalues canalsobeassignedtovariablesoftype boolean Javahasothertypesinadditiontotheprimitivetypes,buta lltheothertypesrepresent objectsratherthan\primitive"datavalues.Forthemostpa rt,wearenotconcernedwith objectsforthetimebeing.However,thereisonepredenedo bjecttypethatisveryimportant: thetype String .A String isasequenceofcharacters.You'vealreadyseenastringlit eral: "HelloWorld!" .Thedoublequotesarepartoftheliteral;theyhavetobetyp edinthe program.However,theyarenotpartoftheactualstringvalu e,whichconsistsofjustthe charactersbetweenthequotes.Withinastring,specialcha racterscanberepresentedusing thebackslashnotation.Withinthiscontext,thedoublequo teisitselfaspecialcharacter.For example,torepresentthestring value Isaid,"Areyoulistening!" withalinefeedattheend,youwouldhavetotypethestring literal : "Isaid,\"Areyoulistening!\"\n" Youcanalsouse \t \r \\ ,andunicodesequencessuchas \u00E9 torepresentotherspecial charactersinstringliterals.Becausestringsareobjects ,theirbehaviorinprogramsispeculiar insomerespects(tosomeonewhoisnotusedtoobjects).I'll havemoretosayaboutthemin thenextsection.

PAGE 40

CHAPTER2.NAMESANDTHINGS 26 2.2.3VariablesinProgramsAvariablecanbeusedinaprogramonlyifithasrstbeen declared .A variabledeclaration statement isusedtodeclareoneormorevariablesandtogivethemnames .Whenthecomputer executesavariabledeclaration,itsetsasidememoryforth evariableandassociatesthevariable's namewiththatmemory.Asimplevariabledeclarationtakest heform: h type-name ih variable-name-or-names i ; The h variable-name-or-names i canbeasinglevariablenameoralistofvariablenames separatedbycommas.(We'llseelaterthatvariabledeclara tionstatementscanactuallybe somewhatmorecomplicatedthanthis.)Goodprogrammingsty leistodeclareonlyonevariable inadeclarationstatement,unlessthevariablesareclosel yrelatedinsomeway.Forexample: intnumberOfStudents;Stringname;doublex,y;booleanisFinished;charfirstInitial,middleInitial,lastInitial; Itisalsogoodstyletoincludeacommentwitheachvariabled eclarationtoexplainits purposeintheprogram,ortogiveotherinformationthatmig htbeusefultoahumanreader. Forexample: doubleprincipal;//Amountofmoneyinvested.doubleinterestRate;//Rateasadecimal,notpercentage. Inthischapter,wewillonlyusevariablesdeclaredinsidet he main() subroutineofaprogram.Variablesdeclaredinsideasubroutinearecalled localvariables forthatsubroutine. Theyexistonlyinsidethesubroutine,whileitisrunning,a ndarecompletelyinaccessiblefrom outside.Variabledeclarationscanoccuranywhereinsidet hesubroutine,aslongaseachvariable isdeclaredbeforeitisusedinanyexpression.Somepeoplel iketodeclareallthevariablesat thebeginningofthesubroutine.Othersliketowaittodecla reavariableuntilitisneeded.My preference:Declareimportantvariablesatthebeginningo fthesubroutine,anduseacomment toexplainthepurposeofeachvariable.Declare\utilityva riables"whicharenotimportantto theoveralllogicofthesubroutineatthepointinthesubrou tinewheretheyarerstused.Here isasimpleprogramusingsomevariablesandassignmentstat ements: /** *Thisclassimplementsasimpleprogramthat*willcomputetheamountofinterestthatis*earnedon$17,000investedataninterest*rateof0.07foroneyear.Theinterestand*thevalueoftheinvestmentafteroneyearare*printedtostandardoutput.*/ publicclassInterest{ publicstaticvoidmain(String[]args){ /*Declarethevariables.*/doubleprincipal;//Thevalueoftheinvestment.doublerate;//Theannualinterestrate.doubleinterest;//Interestearnedinoneyear.

PAGE 41

CHAPTER2.NAMESANDTHINGS 27 /*Dothecomputations.*/principal=17000;rate=0.07;interest=principal*rate;//Computetheinterest.principal=principal+interest; //Computevalueofinvestmentafteroneyear,withinterest //(Note:Thenewvaluereplacestheoldvalueofprincipal.) /*Outputtheresults.*/System.out.print("Theinterestearnedis$");System.out.println(interest);System.out.print("Thevalueoftheinvestmentafteroneye aris$"); System.out.println(principal); }//endofmain() }//endofclassInterest Thisprogramusesseveralsubroutinecallstatementstodis playinformationtotheuserofthe program.Twodierentsubroutinesareused: System.out.print and System.out.println Thedierencebetweentheseisthat System.out.println addsalinefeedaftertheendofthe informationthatitdisplays,while System.out.print doesnot.Thus,thevalueof interest whichisdisplayedbythesubroutinecall\ System.out.println(interest); ",followsonthe samelineafterthestringdisplayedbytheprevious System.out.print statement.Notethat thevaluetobedisplayedby System.out.print or System.out.println isprovidedinparenthesesafterthesubroutinename.Thisvalueiscalleda parameter tothesubroutine.A parameterprovidesasubroutinewithinformationitneedst operformitstask.Inasubroutine callstatement,anyparametersarelistedinparenthesesaf terthesubroutinename.Notall subroutineshaveparameters.Iftherearenoparametersina subroutinecallstatement,the subroutinenamemustbefollowedbyanemptypairofparenthe ses. Allthesampleprogramsforthistextbookareavailableinse paratesourcecodelesinthe on-lineversionofthistextat http://math.hws.edu/javanotes/source .Theyarealsoincluded inthedownloadablearchivesofthewebsite.Thesourcecode forthe Interest program,for example,canbefoundinthele Interest.java 2.3Strings,Objects,Enums,andSubroutinesT heprevioussection introducedtheeightprimitivedatatypesandthetype String .There (online) isafundamentaldierencebetweentheprimitivetypesandt he String type:Valuesoftype String areobjects.Whilewewillnotstudyobjectsindetailuntil Chapter5 ,itwillbeuseful foryoutoknowalittleaboutthemandaboutacloselyrelated topic:classes.Thisisnot justbecausestringsareusefulbutbecauseobjectsandclas sesareessentialtounderstanding anotherimportantprogrammingconcept,subroutines. Anotherreasonforconsideringclassesandobjectsatthisp ointissothatwecanintroduce enums .AnenumisadatatypethatcanbecreatedbyaJavaprogrammer torepresenta smallcollectionofpossiblevalues.Technically,anenumi saclassanditspossiblevaluesare objects.Enumswillbeourrstexampleofaddinganewtypeto theJavalanguage.Wewill lookatthemlaterinthissection.

PAGE 42

CHAPTER2.NAMESANDTHINGS 28 2.3.1Built-inSubroutinesandFunctionsRecallthatasubroutineisasetofprograminstructionstha thavebeenchunkedtogetherand givenaname.In Chapter4 ,you'lllearnhowtowriteyourownsubroutines,butyoucan getalotdoneinaprogramjustbycallingsubroutinesthatha vealreadybeenwrittenfor you.InJava,everysubroutineiscontainedinaclassorinan object.Someclassesthatare standardpartsoftheJavalanguagecontainpredenedsubro utinesthatyoucanuse.Avalue oftype String ,whichisanobject,containssubroutinesthatcanbeusedto manipulatethat string.Thesesubroutinesare\builtinto"theJavalanguag e.Youcancallallthesesubroutines withoutunderstandinghowtheywerewrittenorhowtheywork .Indeed,that'sthewholepoint ofsubroutines:Asubroutineisa\blackbox"whichcanbeuse dwithoutknowingwhatgoes oninside. ClassesinJavahavetwoverydierentfunctions.Firstofal l,aclasscangrouptogether variablesandsubroutinesthatarecontainedinthatclass. Thesevariablesandsubroutines arecalled staticmembers oftheclass.You'veseenoneexample:Inaclassthatdenesa program,the main() routineisastaticmemberoftheclass.Thepartsofaclassde nitionthat denestaticmembersaremarkedwiththereservedword\ static ",justlikethe main() routine ofaprogram.However,classeshaveasecondfunction.Theya reusedtodescribeobjects.In thisrole,theclassofanobjectspecieswhatsubroutinesa ndvariablesarecontainedinthat object.Theclassisa type |inthetechnicalsenseofaspecicationofacertaintypeof data value|andtheobjectisavalueofthattype.Forexample, String isactuallythenameofa classthatisincludedasastandardpartoftheJavalanguage String isalsoatype,andliteral stringssuchas "HelloWorld" representvaluesoftype String So,everysubroutineiscontainedeitherinaclassorinanob ject.Classes contain subroutinescalledstaticmembersubroutines.Classesalso describe objectsandthesubroutinesthat arecontainedinthoseobjects. Thisdualusecanbeconfusing,andinpracticemostclassesa redesignedtoperformprimarilyorexclusivelyinonlyoneofthetwopossibleroles.F orexample,althoughthe String classdoescontainafewrarely-usedstaticmembersubrouti nes,itexistsmainlytospecifya largenumberofsubroutinesthatarecontainedinobjectsof type String .Anotherstandard class,named Math ,existsentirelytogrouptogetheranumberofstaticmember subroutines thatcomputevariouscommonmathematicalfunctions. Tobegintogetahandleonallofthiscomplexity,let'slooka tthesubroutine System.out.print asanexample.Asyouhaveseenearlierinthischapter,thiss ubroutine isusedtodisplayinformationtotheuser.Forexample, System.out.print("HelloWorld") displaysthemessage,HelloWorld. System isoneofJava'sstandardclasses.Oneofthestaticmemberva riablesinthisclassis named out .Sincethisvariableiscontainedintheclass System ,itsfullname|whichyouhave tousetorefertoitinyourprograms|is System.out .Thevariable System.out referstoan object,andthatobjectinturncontainsasubroutinenamed print .Thecompoundidentier System.out.print referstothesubroutine print intheobject out intheclass System (Asanaside,Iwillnotethattheobjectreferredtoby System.out isanobjectoftheclass PrintStream PrintStream isanotherclassthatisastandardpartofJava. Any objectof type PrintStream isadestinationtowhichinformationcanbeprinted; any objectoftype PrintStream hasa print subroutinethatcanbeusedtosendinformationtothatdesti nation. Theobject System.out isjustonepossibledestination,and System.out.print isthesubrou-

PAGE 43

CHAPTER2.NAMESANDTHINGS 29 tinethatsendsinformationtothatparticulardestination .Otherobjectsoftype PrintStream mightsendinformationtootherdestinationssuchaslesor acrossanetworktoothercomputers.Thisisobject-orientedprogramming:Manydieren tthingswhichhavesomethingin common|theycanallbeusedasdestinationsforinformation |canallbeusedinthesame way|througha print subroutine.The PrintStream classexpressesthecommonalitiesamong alltheseobjects.) Sinceclassnamesandvariablenamesareusedinsimilarways ,itmightbehardtotell whichiswhich.Rememberthatallthebuilt-in,predenedna mesinJavafollowtherulethat classnamesbeginwithanuppercaseletterwhilevariablena mesbeginwithalowercaseletter. Whilethisisnotaformalsyntaxrule,Irecommendthatyoufo llowitinyourownprogramming. Subroutinenamesshouldalsobeginwithlowercaseletters. Thereisnopossibilityofconfusing avariablewithasubroutine,sinceasubroutinenameinapro gramisalwaysfollowedbyaleft parenthesis. (Asonenalgeneralnote,youshouldbeawarethatsubroutin esinJavaareoftenreferred toas methods .Generally,theterm\method"meansasubroutinethatiscon tainedinaclass orinanobject.SincethisistrueofeverysubroutineinJava ,everysubroutineinJavais amethod.Thesameisnottrueforotherprogramminglanguage s.Nevertheless,theterm \method"ismostlyusedinthecontextofobject-orientedpr ogramming,anduntilwestart doingrealobject-orientedprogrammingin Chapter5 ,Iwillprefertousethemoregeneral term,\subroutine.") Classescancontainstaticmembersubroutines,aswellasst aticmembervariables.For example,the System classcontainsasubroutinenamed exit .Inaprogram,ofcourse,this subroutinemustbereferredtoas System.exit .Callingthissubroutinewillterminatethe program.Youcoulduseitifyouhadsomereasontoterminatet heprogrambeforetheend ofthe main routine.Forhistoricalreasons,thissubroutinetakesani ntegerasaparameter, sothesubroutinecallstatementmightlooklike\ System.exit(0); "or\ System.exit(1); ". (Theparametertellsthecomputerwhytheprogramwastermin ated.Aparametervalueof0 indicatesthattheprogramendednormally.Anyothervaluei ndicatesthattheprogramwas terminatedbecauseanerrorwasdetected.Butinpractice,t hevalueoftheparameterisusually ignored.) Everysubroutineperformssomespecictask.Forsomesubro utines,thattaskistocompute orretrievesomedatavalue.Subroutinesofthistypearecal led functions .Wesaythata function returns avalue.Thereturnedvaluemustthenbeusedsomehowinthepr ogram. Youarefamiliarwiththemathematicalfunctionthatcomput esthesquarerootofanumber.Javahasacorrespondingfunctioncalled Math.sqrt .Thisfunctionisastaticmember subroutineoftheclassnamed Math .If x isanynumericalvalue,then Math.sqrt(x) computes andreturnsthesquarerootofthatvalue.Since Math.sqrt(x) representsavalue,itdoesn't makesensetoputitonalinebyitselfinasubroutinecallsta tementsuchas Math.sqrt(x);//Thisdoesn'tmakesense! What,afterall,wouldthecomputerdowiththevaluecompute dbythefunctioninthiscase? Youhavetotellthecomputertodosomethingwiththevalue.Y oumighttellthecomputerto displayit: System.out.print(Math.sqrt(x));//Displaythesquarero otofx. oryoumightuseanassignmentstatementtotellthecomputer tostorethatvalueinavariable:

PAGE 44

CHAPTER2.NAMESANDTHINGS 30 lengthOfSide=Math.sqrt(x); Thefunctioncall Math.sqrt(x) representsavalueoftype double ,anditcanbeusedanyplace whereanumericliteraloftypedoublecouldbeused. The Math classcontainsmanystaticmemberfunctions.Hereisalisto fsomeofthemore importantofthem: Math.abs(x) ,whichcomputestheabsolutevalueof x Theusualtrigonometricfunctions, Math.sin(x) Math.cos(x) ,and Math.tan(x) .(For allthetrigonometricfunctions,anglesaremeasuredinrad ians,notdegrees.) Theinversetrigonometricfunctionsarcsin,arccos,andar ctan,whicharewrittenas: Math.asin(x) Math.acos(x) ,and Math.atan(x) .Thereturnvalueisexpressedinradians,notdegrees. Theexponentialfunction Math.exp(x) forcomputingthenumbereraisedtothepower x ,andthenaturallogarithmfunction Math.log(x) forcomputingthelogarithmof x in thebasee. Math.pow(x,y) forcomputing x raisedtothepower y Math.floor(x) ,whichrounds x downtothenearestintegervaluethatislessthanor equalto x .Eventhoughthereturnvalueismathematicallyaninteger, itisreturned asavalueoftype double ,ratherthanoftype int asyoumightexpect.Forexample, Math.floor(3.76) is3.0.Thefunction Math.round(x) returnstheintegerthatisclosest to x Math.random() ,whichreturnsarandomlychosen double intherange 0.0<= Math.random()<1.0 .(Thecomputeractuallycalculatesso-called\pseudorand om" numbers,whicharenottrulyrandombutarerandomenoughfor mostpurposes.) Forthesefunctions,thetypeoftheparameter|the x or y insidetheparentheses|canbe anyvalueofanynumerictype.Formostofthefunctions,thev aluereturnedbythefunction isoftype double nomatterwhatthetypeoftheparameter.However,for Math.abs(x) ,the valuereturnedwillbethesametypeas x ;if x isoftype int ,thensois Math.abs(x) .So,for example,while Math.sqrt(9) isthe double value3.0, Math.abs(9) isthe int value9. Notethat Math.random() doesnothaveanyparameter.Youstillneedtheparentheses, even thoughthere'snothingbetweenthem.Theparenthesesletth ecomputerknowthatthisisasubroutineratherthanavariable.Anotherexampleofasubrout inethathasnoparametersisthe function System.currentTimeMillis() ,fromthe System class.Whenthisfunctionisexecuted, itretrievesthecurrenttime,expressedasthenumberofmil lisecondsthathavepassedsincea standardizedbasetime(thestartoftheyear1970inGreenwi chMeanTime,ifyoucare).One millisecondisone-thousandthofasecond.Thereturnvalue of System.currentTimeMillis() isoftype long .Thisfunctioncanbeusedtomeasurethetimethatittakesth ecomputerto performatask.Justrecordthetimeatwhichthetaskisbegun andthetimeatwhichitis nishedandtakethedierence. Hereisasampleprogramthatperformsafewmathematicaltas ksandreportsthetime thatittakesfortheprogramtorun.Onsomecomputers,theti mereportedmightbezero, becauseitistoosmalltomeasureinmilliseconds.Evenifit 'snotzero,youcanbesurethat mostofthetimereportedbythecomputerwasspentdoingoutp utorworkingontasksother thantheprogram,sincethecalculationsperformedinthisp rogramoccupyonlyatinyfraction ofasecondofacomputer'stime.

PAGE 45

CHAPTER2.NAMESANDTHINGS 31 /** *Thisprogramperformssomemathematicalcomputationsand displays *theresults.Itthenreportsthenumberofsecondsthatthe*computerspentonthistask.*/ publicclassTimedComputation{ publicstaticvoidmain(String[]args){ longstartTime;//Startingtimeofprogram,inmillisecond s. longendTime;//Timewhencomputationsaredone,inmillise conds. doubletime;//Timedifference,inseconds.startTime=System.currentTimeMillis();doublewidth,height,hypotenuse;//sidesofatrianglewidth=42.0;height=17.0;hypotenuse=Math.sqrt(width*width+height*height);System.out.print("Atrianglewithsides42and17hashypot enuse"); System.out.println(hypotenuse);System.out.println("\nMathematically,sin(x)*sin(x)+ +"cos(x)*cos(x)-1shouldbe0."); System.out.println("Let'scheckthisforx=1:");System.out.print("sin(1)*sin(1)+cos(1)*cos(1)-1is") ; System.out.println(Math.sin(1)*Math.sin(1) +Math.cos(1)*Math.cos(1)-1); System.out.println("(Therecanberound-offerrorswhen" +"computingwithrealnumbers!)"); System.out.print("\nHereisarandomnumber:");System.out.println(Math.random());endTime=System.currentTimeMillis();time=(endTime-startTime)/1000.0;System.out.print("\nRuntimeinsecondswas:");System.out.println(time); }//endmain() }//endclassTimedComputation 2.3.2OperationsonStringsAvalueoftype String isanobject.Thatobjectcontainsdata,namelythesequence ofcharacters thatmakeupthestring.Italsocontainssubroutines.Allof thesesubroutinesareinfact functions.Forexample,everystringobjectcontainsafunc tionnamed length thatcomputes thenumberofcharactersinthatstring.Supposethat advice isavariablethatreferstoa String .Forexample, advice mighthavebeendeclaredandassignedavalueasfollows: Stringadvice;advice="Seizetheday!";

PAGE 46

CHAPTER2.NAMESANDTHINGS 32 Then advice.length() isafunctioncallthatreturnsthenumberofcharactersinth estring \Seizetheday!".Inthiscase,thereturnvaluewouldbe14.I ngeneral,foranystringvariable str ,thevalueof str.length() isan int equaltothenumberofcharactersinthestringthatis thevalueof str .Notethatthisfunctionhasnoparameter;theparticularst ringwhoselength isbeingcomputedisthevalueof str .The length subroutineisdenedbytheclass String anditcanbeusedwithanyvalueoftype String .Itcanevenbeusedwith String literals,which are,afterall,justconstantvaluesoftype String .Forexample,youcouldhaveaprogramcount thecharactersin\HelloWorld"foryoubysaying System.out.print("Thenumberofcharactersin");System.out.println("thestring\"HelloWorld\"is");System.out.println("HelloWorld".length()); The String classdenesalotoffunctions.Herearesomethatyoumight nduseful.Assume that s1 and s2 refertovaluesoftype String : s1.equals(s2) isafunctionthatreturnsa boolean value.Itreturns true if s1 consists ofexactlythesamesequenceofcharactersas s2 ,andreturns false otherwise. s1.equalsIgnoreCase(s2) isanotherboolean-valuedfunctionthatcheckswhether s1 isthesamestringas s2 ,butthisfunctionconsidersupperandlowercaseletters tobeequivalent.Thus,if s1 is\cat",then s1.equals("Cat") is false ,while s 1.equalsIgnoreCase("Cat") is true s1.length() ,asmentionedabove,isaninteger-valuedfunctionthatgiv esthenumberof charactersin s1 s1.charAt(N) ,where N isaninteger,returnsavalueoftype char .Itreturnsthe N thcharacterinthestring.Positionsarenumberedstarting with0,so s1.charAt(0) is actuallytherstcharacter, s1.charAt(1) isthesecond,andsoon.Thenalpositionis s1.length()-1 .Forexample,thevalueof "cat".charAt(1) is'a'.Anerroroccursif thevalueoftheparameterislessthanzeroorgreaterthan s1.length()-1 s1.substring(N,M) ,where N and M areintegers,returnsavalueoftype String .The returnedvalueconsistsofthecharactersin s1 inpositions N N+1 ,..., M-1 .Notethatthe characterinposition M isnotincluded.Thereturnedvalueiscalledasubstringof s1 s1.indexOf(s2) returnsaninteger.If s2 occursasasubstringof s1 ,thenthereturned valueisthestartingpositionofthatsubstring.Otherwise ,thereturnedvalueis-1.You canalsouse s1.indexOf(ch) tosearchforaparticularcharacter, ch ,in s1 .Tondthe rstoccurrenceof x atorafterposition N ,youcanuse s1.indexOf(x,N) s1.compareTo(s2) isaninteger-valuedfunctionthatcomparesthetwostrings .Ifthe stringsareequal,thevaluereturnediszero.If s1 islessthan s2 ,thevaluereturnedis anumberlessthanzero,andif s1 isgreaterthan s2 ,thevaluereturnedissomenumber greaterthanzero.(Ifbothofthestringsconsistentirelyo flowercaseletters,then\less than"and\greaterthan"refertoalphabeticalorder.Other wise,theorderingismore complicated.) s1.toUpperCase() isa String -valuedfunctionthatreturnsanewstringthatisequalto s1 exceptthatanylowercaselettersin s1 havebeenconvertedtouppercase.Forexample, "Cat".toUpperCase() isthestring "CAT" .Thereisalsoafunction s1.toLowerCase() s1.trim() isa String -valuedfunctionthatreturnsanewstringthatisequalto s1 except thatanynon-printingcharacterssuchasspacesandtabshav ebeentrimmedfromthe

PAGE 47

CHAPTER2.NAMESANDTHINGS 33 beginningandfromtheendofthestring.Thus,if s1 hasthevalue "fred" ,then s1.trim() isthestring "fred" Forthefunctions s1.toUpperCase() s1.toLowerCase() ,and s1.trim() ,notethatthe valueof s1 is not modied.Insteadanewstringiscreatedandreturnedasthev alueof thefunction.Thereturnedvaluecouldbeused,forexample, inanassignmentstatement suchas\ smallLetters=s1.toLowerCase(); ".Tochangethevalueof s1 ,youcouldusean assignment\ s1=s1.toLowerCase(); ". Hereisanotherextremelyusefulfactaboutstrings:Youcan usetheplusoperator, + ,to concatenate twostrings.Theconcatenationoftwostringsisanewstring consistingofallthe charactersoftherststringfollowedbyallthecharacters ofthesecondstring.Forexample, "Hello"+"World" evaluatesto "HelloWorld" .(Gottawatchthosespaces,ofcourse|ifyou wantaspaceintheconcatenatedstring,ithastobesomewher eintheinputdata,asin "Hello"+"World" .) Let'ssupposethat name isavariableoftype String andthatitalreadyreferstothename ofthepersonusingtheprogram.Then,theprogramcouldgree ttheuserbyexecutingthe statement: System.out.println("Hello,"+name+".Pleasedtomeetyou !"); Evenmoresurprisingisthatyoucanactuallyconcatenateva luesof any typeontoa String usingthe + operator.Thevalueisconvertedtoastring,justasitwould beifyouprinteditto thestandardoutput,andthenitisconcatenatedontothestr ing.Forexample,theexpression "Number"+42 evaluatestothestring "Number42" .Andthestatements System.out.print("After");System.out.print(years);System.out.print("years,thevalueis");System.out.print(principal); canbereplacedbythesinglestatement: System.out.print("After"+years+ "years,thevalueis"+principal); Obviously,thisisveryconvenient.Itwouldhaveshortened someoftheexamplespresented earlierinthischapter.2.3.3IntroductiontoEnumsJavacomeswitheightbuilt-inprimitivetypesandalargese toftypesthataredenedby classes,suchas String .Buteventhislargecollectionoftypesisnotsucienttoco verallthe possiblesituationsthataprogrammermighthavetodealwit h.So,anessentialpartofJava, justlikealmostanyotherprogramminglanguage,istheabil itytocreate new types.Forthe mostpart,thisisdonebydeningnewclasses;youwilllearn howtodothatin Chapter5 .But wewilllookhereatoneparticularcase:theabilitytodene enums (shortfor enumerated types ).EnumsarearecentadditiontoJava.Theywereonlyaddedin Version5.0.Many programminglanguageshavesomethingsimilar,andmanypeo plebelievethatenumsshould havebeenpartofJavafromthebeginning. Technically,anenumisconsideredtobeaspecialkindofcla ss,butthatisnotimportant fornow.Inthissection,wewilllookatenumsinasimpliedf orm.Inpractice,mostusesof enumswillonlyneedthesimpliedformthatispresentedher e.

PAGE 48

CHAPTER2.NAMESANDTHINGS 34 Anenumisatypethathasaxedlistofpossiblevalues,which isspeciedwhentheenum iscreated.Insomeways,anenumissimilartothe boolean datatype,whichhas true and false asitsonlypossiblevalues.However, boolean isaprimitivetype,whileanenumisnot. Thedenitionofanenumtypeshasthe(simplied)form: enum h enum-type-name i { h list-of-enum-values i } Thisdenitioncannotbeinsideasubroutine.Youcanplacei t outside the main() routine oftheprogram.The h enum-type-name i canbeanysimpleidentier.Thisidentierbecomes thenameoftheenumtype,inthesamewaythat\boolean"isthe nameofthe boolean type and\String"isthenameofthe String type.Eachvalueinthe h list-of-enum-values i mustbea simpleidentier,andtheidentiersinthelistareseparat edbycommas.Forexample,hereis thedenitionofanenumtypenamed Season whosevaluesarethenamesofthefourseasons oftheyear: enumSeason{SPRING,SUMMER,FALL,WINTER} Byconvention,enumvaluesaregivennamesthataremadeupof uppercaseletters,but thatisastyleguidelineandnotasyntaxrule.Enumvaluesar enotvariables.Eachvalueis a constant thatalwayshasthesamevalue.Infact,thepossiblevalueso fanenumtypeare usuallyreferredtoas enumconstants Notethattheenumconstantsoftype Season areconsideredtobe\containedin" Season whichmeans|followingtheconventionthatcompoundidenti ersareusedforthingsthatare containedinotherthings|thenamesthatyouactuallyusein yourprogramtorefertothem are Season.SPRING Season.SUMMER Season.FALL ,and Season.WINTER Onceanenumtypehasbeencreated,itcanbeusedtodeclareva riablesinexactlythesame waysthatothertypesareused.Forexample,youcandeclarea variablenamed vacation of type Season withthestatement: Seasonvacation; Afterdeclaringthevariable,youcanassignavaluetoitusi nganassignmentstatement.The valueontheright-handsideoftheassignmentcanbeoneofth eenumconstantsoftype Season Remembertousethefullnameoftheconstant,including\Sea son"!Forexample: vacation=Season.SUMMER; Youcanprintoutanenumvaluewithanoutputstatementsucha s System.out.print(vacation) Theoutputvaluewillbethenameoftheenumconstant(withou tthe\Season.").Inthiscase, theoutputwouldbe\SUMMER". Becauseanenumistechnicallyaclass,theenumvaluesarete chnicallyobjects.Asobjects,theycancontainsubroutines.Oneofthesubroutines ineveryenumvalueisnamed ordinal() .Whenusedwithanenumvalue,itreturnsthe ordinalnumber ofthevaluein thelistofvaluesoftheenum.Theordinalnumbersimplytell sthepositionofthevaluein thelist.Thatis, Season.SPRING.ordinal() isthe int value0, Season.SUMMER.ordinal() is 1, Season.FALL.ordinal() is2,and Season.WINTER.ordinal() is3.(Youwillseeoverand overagainthatcomputerscientistsliketostartcountinga tzero!)Youcan,ofcourse,use the ordinal() methodwithavariableoftype Season ,suchas vacation.ordinal() inour example. Rightnow,itmightnotseemtoyouthatenumsareallthatusef ul.Asyouworkthough therestofthebook,youshouldbeconvincedthattheyare.Fo rnow,youshouldatleast appreciatethemastherstexampleofanimportantconcept: creatingnewtypes.Hereisa littleexamplethatshowsenumsbeingusedinacompleteprog ram:

PAGE 49

CHAPTER2.NAMESANDTHINGS 35 publicclassEnumDemo{ //Definetwoenumtypes--rememberthatthedefinitions//goOUTSIDEThemain()routine! enumDay{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FR IDAY,SATURDAY} enumMonth{JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,N OV,DEC} publicstaticvoidmain(String[]args){ Daytgif;//DeclareavariableoftypeDay.Monthlibra;//DeclareavariableoftypeMonth.tgif=Day.FRIDAY;//AssignavalueoftypeDaytotgif.libra=Month.OCT;//AssignavalueoftypeMonthtolibra.System.out.print("Mysignislibra,sinceIwasbornin");System.out.println(libra);//Outputvaluewillbe:OCTSystem.out.print("That'sthe");System.out.print(libra.ordinal());System.out.println("-thmonthoftheyear.");System.out.println("(Countingfrom0,ofcourse!)");System.out.print("Isn'titnicetogetto");System.out.println(tgif);//Outputvaluewillbe:FRIDAYSystem.out.println(tgif+"isthe"+tgif.ordinal() +"-thdayoftheweek."); //YoucanconcatenateenumvaluesontoStrings! } } 2.4TextInputandOutputF orsomeunfathomablereason ,Javahasnevermadeiteasytoreaddatatypedin (online) bytheuserofaprogram.You'vealreadyseenthatoutputcanb edisplayedtotheuser usingthesubroutine System.out.print .Thissubroutineispartofapre-denedobjectcalled System.out .Thepurposeofthisobjectispreciselytodisplayoutputto theuser.Thereis acorrespondingobjectcalled System.in thatexiststoreaddatainputbytheuser,butit providesonlyveryprimitiveinputfacilities,anditrequi ressomeadvancedJavaprogramming skillstouseiteectively. Java5.0nallymakesinputalittleeasierwithanew Scanner class.However,itrequires someknowledgeofobject-orientedprogrammingtousethisc lass,soit'snotappropriatefor usehereatthebeginningofthiscourse.(Furthermore,inmy opinion, Scanner stilldoesnot getthingsquiteright.) Thereissomeexcuseforthislackofconcernwithinput,sinc eJavaismeantmainlyto writeprogramsforGraphicalUserInterfaces,andthosepro gramshavetheirownstyleof input/output,which is implementedinJava.However,basicsupportisneededforin put/output inold-fashionednon-GUIprograms.Fortunately,itisposs ibleto extend Javabycreatingnew classesthatprovidesubroutinesthatarenotavailableint hestandardpartofthelanguage. Assoonasanewclassisavailable,thesubroutinesthatitco ntainscanbeusedinexactlythe samewayasbuilt-inroutines.

PAGE 50

CHAPTER2.NAMESANDTHINGS 36 Alongtheselines,I'vewrittenaclasscalled TextIO thatdenessubroutinesforreading valuestypedbytheuserofanon-GUIprogram.Thesubroutine sinthisclassmakeitpossible togetinputfromthestandardinputobject, System.in ,withoutknowingabouttheadvanced aspectsofJavathatareneededtouse Scanner ortouse System.in directly. TextIO also containsasetofoutputsubroutines.Theoutputsubroutine saresimilartothoseprovidedin System.out ,buttheyprovideafewadditionalfeatures.Youcanusewhic heversetofoutput subroutinesyouprefer,andyoucanevenmixtheminthesamep rogram. Tousethe TextIO class,youmustmakesurethattheclassisavailabletoyourp rogram. WhatthismeansdependsontheJavaprogrammingenvironment thatyouareusing.Ingeneral, youjusthavetoaddthesourcecodele, TextIO.java ,tothesamedirectorythatcontainsyour mainprogram.See Section2.6 formoreinformationabouthowtouse TextIO 2.4.1AFirstTextInputExampleTheinputroutinesinthe TextIO classarestaticmemberfunctions.(Staticmemberfunction s wereintroducedintheprevioussection.)Let'ssupposetha tyouwantyourprogramtoread anintegertypedinbytheuser.The TextIO classcontainsastaticmemberfunctionnamed getlnInt thatyoucanuseforthispurpose.Sincethisfunctioniscont ainedinthe TextIO class, youhavetorefertoitinyourprogramas TextIO.getlnInt .Thefunctionhasnoparameters, soacompletecalltothefunctiontakestheform\ TextIO.getlnInt() ".Thisfunctioncall representsthe int valuetypedbytheuser,andyouhavetodosomethingwithther eturned value,suchasassignittoavariable.Forexample,if userInput isavariableoftype int (createdwithadeclarationstatement\ intuserInput; "),thenyoucouldusetheassignment statement userInput=TextIO.getlnInt(); Whenthecomputerexecutesthisstatement,itwillwaitfort heusertotypeinaninteger value.Thevaluetypedwillbereturnedbythefunction,andi twillbestoredinthevariable, userInput .Hereisacompleteprogramthatuses TextIO.getlnInt toreadanumbertyped bytheuserandthenprintsoutthesquareofthenumberthatth eusertypes: /** *Aprogramthatreadsanintegerthatistypedinbythe*userandcomputesandprintsthesquareofthatinteger.*/ publicclassPrintSquare{ publicstaticvoidmain(String[]args){ intuserInput;//Thenumberinputbytheuser.intsquare;//TheuserInput,multipliedbyitself.System.out.print("Pleasetypeanumber:");userInput=TextIO.getlnInt();square=userInput*userInput;System.out.print("Thesquareofthatnumberis");System.out.println(square); }//endofmain() }//endofclassPrintSquare

PAGE 51

CHAPTER2.NAMESANDTHINGS 37 Whenyourunthisprogram,itwilldisplaythemessage\Pleas etypeanumber:"andwill pauseuntilyoutypearesponse,includingacarriagereturn afterthenumber. 2.4.2TextOutputThe TextIO classcontainsstaticmembersubroutines TextIO.put and TextIO.putln thatcan beusedinthesamewayas System.out.print and System.out.println .Forexample,althoughthereisnoparticularadvantageindoingsointhisca se,youcouldreplacethetwo lines System.out.print("Thesquareofthatnumberis");System.out.println(square); with TextIO.put("Thesquareofthatnumberis");TextIO.putln(square); Forthenextfewchapters,Iwilluse TextIO forinputinallmyexamples,andIwilloftenuse itforoutput.Keepinmindthat TextIO canonlybeusedinaprogramifitisavailabletothat program.ItisnotbuiltintoJavainthewaythatthe System classis. Let'slookalittlemorecloselyatthebuilt-inoutputsubro utines System.out.print and System.out.println .Eachofthesesubroutinescanbeusedwithoneparameter,wh erethe parametercanbeavalueofanyoftheprimitivetypes byte short int long roat double char or boolean .Theparametercanalsobea String ,avaluebelongingtoanenumtype,orindeed anyobject.Thatis,youcansay\ System.out.print(x); "or\ System.out.println(x) ;", where x isanyexpressionwhosevalueisofanytypewhatsoever.Thee xpressioncanbeaconstant,avariable,orevensomethingmorecomplicatedsucha s 2*distance*time .Now,infact, the System classactuallyincludesseveraldierentsubroutinestoha ndledierentparameter types.Thereisone System.out.print forprintingvaluesoftype double ,oneforvaluesof type int ,anotherforvaluesthatareobjects,andsoon.Thesesubrou tinescanhavethesame namesincethecomputercantellwhichoneyoumeaninagivens ubroutinecallstatement, dependingonthetypeofparameterthatyousupply.Havingse veralsubroutinesofthesame namethatdierinthetypesoftheirparametersiscalled overloading .Manyprogramming languagesdonotpermitoverloading,butitiscommoninJava programs. Thedierencebetween System.out.print and System.out.println isthatthe println versionoutputsacarriagereturnafteritoutputsthespeci edparametervalue.Thereisa versionof System.out.println thathasnoparameters.Thisversionsimplyoutputsacarria ge return,andnothingelse.Asubroutinecallstatementforth isversionoftheprogramlookslike \ System.out.println(); ",withemptyparentheses.Notethat\ System.out.println(x) ;"is exactlyequivalentto\ System.out.print(x);System.out.println(); ";thecarriagereturn comes after thevalueof x .(Thereisnoversionof System.out.print withoutparameters. Doyouseewhy?) Asmentionedabove,the TextIO subroutines TextIO.put and TextIO.putln canbeused asreplacementsfor System.out.print and System.out.println .The TextIO functionswork inexactlythesamewayasthe System functions,exceptthat,aswewillseebelow, TextIO can alsobeusedtowritetootherdestinations.

PAGE 52

CHAPTER2.NAMESANDTHINGS 38 2.4.3TextIOInputFunctionsThe TextIO classisalittlemoreversatileatdoingoutputthanis System.out .However,it's inputforwhichwereallyneedit. With TextIO ,inputisdoneusingfunctions.Forexample, TextIO.getlnInt() ,whichwas discussedabove,makestheusertypeinavalueoftype int andreturnsthatinputvaluesothat youcanuseitinyourprogram. TextIO includesseveralfunctionsforreadingdierenttypesof inputvalues.Hereareexamplesoftheonesthatyouaremostl ikelytouse: j=TextIO.getlnInt();//Readsavalueoftypeint.y=TextIO.getlnDouble();//Readsavalueoftypedouble.a=TextIO.getlnBoolean();//Readsavalueoftypeboolean.c=TextIO.getlnChar();//Readsavalueoftypechar.w=TextIO.getlnWord();//Readsone"word"asavalueoftype String. s=TextIO.getln();//ReadsanentireinputlineasaString. Forthesestatementstobelegal,thevariablesontheleftsi deofeachassignmentstatement mustalreadybedeclaredandmustbeofthesametypeasthatre turnedbythefunctionon therightside.Notecarefullythatthesefunctionsdonotha veparameters.Thevaluesthat theyreturncomefromoutsidetheprogram,typedinbytheuse rastheprogramisrunning. To\capture"thatdatasothatyoucanuseitinyourprogram,y ouhavetoassignthereturn valueofthefunctiontoavariable.Youwillthenbeabletore fertotheuser'sinputvalueby usingthenameofthevariable. Whenyoucalloneofthesefunctions,youareguaranteedthat itwillreturnalegalvalueof thecorrecttype.Iftheusertypesinanillegalvalueasinpu t|forexample,ifyouaskforan int andtheusertypesinanon-numericcharacteroranumberthat isoutsidethelegalrange ofvaluesthatcanbestoredininavariableoftype int |thenthecomputerwillasktheuserto re-enterthevalue,andyourprogramneverseestherst,ill egalvaluethattheuserentered.For TextIO.getlnBoolean() ,theuserisallowedtotypeinanyofthefollowing:true,fal se,t,f,yes, no,y,n,1,or0.Furthermore,theycanuseeitherupperorlow ercaseletters.Inanycase,the user'sinputisinterpretedasatrue/falsevalue.It'sconv enienttouse TextIO.getlnBoolean() toreadtheuser'sresponsetoaYes/Noquestion. You'llnoticethattherearetwoinputfunctionsthatreturn Strings.Therst, getlnWord() returnsastringconsistingofnon-blankcharactersonly.W henitiscalled,itskipsoverany spacesandcarriagereturnstypedinbytheuser.Thenitread snon-blankcharactersuntilitgets tothenextspaceorcarriagereturn.Itreturnsa String consistingofallthenon-blankcharacters thatithasread.Thesecondinputfunction, getln() ,simplyreturnsastringconsistingofall thecharacterstypedinbytheuser,includingspaces,uptot henextcarriagereturn.Itgetsan entirelineofinputtext.Thecarriagereturnitselfisnotr eturnedaspartoftheinputstring, butitisreadanddiscardedbythecomputer.NotethattheStr ingreturnedbythisfunction mightbethe emptystring "" ,whichcontainsnocharactersatall.Youwillgetthisretur n valueiftheusersimplypressesreturn,withouttypinganyt hingelserst. Alltheotherinputfunctionslisted| getlnInt() getlnDouble() getlnBoolean() ,and getlnChar() |behavelike getWord() inthattheywillskippastanyblanksandcarriagereturns intheinputbeforereadingavalue. Furthermore,iftheusertypesextracharactersonthelinea ftertheinputvalue, allthe extracharacterswillbediscarded,alongwiththecarriage returnattheendofthe line .Iftheprogramexecutesanotherinputfunction,theuserwi llhavetotypeinanotherline ofinput.Itmightnotsoundlikeagoodideatodiscardanyoft heuser'sinput,butitturnsout tobethesafestthingtodoinmostprograms.Sometimes,howe ver,youdowanttoreadmore

PAGE 53

CHAPTER2.NAMESANDTHINGS 39 thanonevaluefromthesamelineofinput. TextIO providesthefollowingalternativeinput functionstoallowyoutodothis: j=TextIO.getInt();//Readsavalueoftypeint.y=TextIO.getDouble();//Readsavalueoftypedouble.a=TextIO.getBoolean();//Readsavalueoftypeboolean.c=TextIO.getChar();//Readsavalueoftypechar.w=TextIO.getWord();//Readsone"word"asavalueoftypeSt ring. Thenamesofthesefunctionsstartwith\get"insteadof\get ln".\Getln"isshortfor\get line"andshouldremindyouthatthefunctionswhosenamesbe ginwith\getln"willgetan entirelineofdata.Afunctionwithoutthe\ln"willreadani nputvalueinthesameway,but willthensavetherestoftheinputlineinachunkofinternal memorycalledthe inputbuer Thenexttimethecomputerwantstoreadaninputvalue,itwil llookintheinputbuerbefore promptingtheuserforinput.Thisallowsthecomputertorea dseveralvaluesfromoneline oftheuser'sinput.Strictlyspeaking,thecomputeractual lyreads only fromtheinputbuer. Thersttimetheprogramtriestoreadinputfromtheuser,th ecomputerwillwaitwhilethe usertypesinanentirelineofinput. TextIO storesthatlineintheinputbueruntilthedata onthelinehasbeenreadordiscarded(byoneofthe\getln"fu nctions).Theuseronlygetsto typewhenthebuerisempty. Clearly,thesemanticsofinputismuchmorecomplicatedtha nthesemanticsofoutput! Fortunately,forthemajorityofapplications,it'spretty straightforwardinpractice.Youonly needtofollowthedetailsifyouwanttodosomethingfancy.I nparticular,I strongly advise youtousethe\getln"versionsoftheinputroutines,rather thanthe\get"versions,unlessyou reallywanttoreadseveralitemsfromthesamelineofinput, preciselybecausethesemantics ofthe\getln"versionsismuchsimpler. Note,bytheway,thatalthoughthe TextIO inputfunctionswillskippastblankspacesand carriagereturnswhilelookingforinput,theywill not skippastothercharacters.Forexample, ifyoutrytoreadtwo int sandtheusertypes\2,3",thecomputerwillreadtherstnum ber correctly,butwhenittriestoreadthesecondnumber,itwil lseethecomma.Itwillregardthis asanerrorandwillforcetheusertoretypethenumber.Ifyou wanttoinputseveralnumbers fromoneline,youshouldmakesurethattheuserknowstosepa ratethemwithspaces,not commas.Alternatively,ifyouwanttorequireacommabetwee nthenumbers,use getChar() toreadthecommabeforereadingthesecondnumber. Thereisanothercharacterinputfunction, TextIO.getAnyChar() ,whichdoesnotskippast blanksorcarriagereturns.Itsimplyreadsandreturnsthen extcharactertypedbytheuser, evenifit'sablankorcarriagereturn.Iftheusertypedacar riagereturn,thenthe char returned by getAnyChar() isthespeciallinefeedcharacter' \ n'.Thereisalsoafunction, TextIO.peek() thatletsyoulookaheadatthenextcharacterintheinputwit houtactuallyreadingit.After you\peek"atthenextcharacter,itwillstillbetherewheny oureadthenextitemfrominput. Thisallowsyoutolookaheadandseewhat'scomingupinthein put,sothatyoucantake dierentactionsdependingonwhat'sthere. The TextIO classprovidesanumberofotherfunctions.Tolearnmoreabo utthem,youcan lookatthecommentsinthesourcecodele, TextIO.java (Youmightbewonderingwhythereareonlytwooutputroutine s, print and println whichcanoutputdatavaluesofanytype,whilethereisasepa rateinputroutineforeachdata type.Asnotedabove,inrealitytherearemany print and println routines,oneforeachdata type.Thecomputercantellthemapartbasedonthetypeofthe parameterthatyouprovide. However,theinputroutinesdon'thaveparameters,sothedi erentinputroutinescanonlybe

PAGE 54

CHAPTER2.NAMESANDTHINGS 40 distinguishedbyhavingdierentnames.) Using TextIO forinputandoutput,wecannowimprovetheprogramfrom Section2.2 for computingthevalueofaninvestment.Wecanhavetheusertyp eintheinitialvalueofthe investmentandtheinterestrate.Theresultisamuchmoreus efulprogram|foronething,it makessensetorunitmorethanonce! /** *Thisclassimplementsasimpleprogramthatwillcompute*theamountofinterestthatisearnedonaninvestmentover*aperiodofoneyear.Theinitialamountoftheinvestment*andtheinterestrateareinputbytheuser.Thevalueof*theinvestmentattheendoftheyearisoutput.The*ratemustbeinputasadecimal,notapercentage(for*example,0.05ratherthan5).*/ publicclassInterest2{ publicstaticvoidmain(String[]args){ doubleprincipal;//Thevalueoftheinvestment.doublerate;//Theannualinterestrate.doubleinterest;//Theinterestearnedduringtheyear.TextIO.put("Entertheinitialinvestment:");principal=TextIO.getlnDouble();TextIO.put("Entertheannualinterestrate(decimal,notp ercentage!):"); rate=TextIO.getlnDouble();interest=principal*rate;//Computethisyear'sinterest principal=principal+interest;//Addittoprincipal.TextIO.put("Thevalueoftheinvestmentafteroneyearis$" ); TextIO.putln(principal); }//endofmain() }//endofclassInterest2 2.4.4FormattedOutputIfyouranthepreceding Interest2 example,youmighthavenoticedthattheanswerisnot alwayswrittenintheformatthatisusuallyusedfordollara mounts.Ingeneral,dollaramounts arewrittenwithtwodigitsafterthedecimalpoint.Butthep rogram'soutputcanbeanumber like1050.0or43.575.Itwouldbebetterifthesenumberswer eprintedas1050.00and43.58. Java5.0introducedaformattedoutputcapabilitythatmake sitmucheasierthanitused tobetocontroltheformatofoutputnumbers.Alotofformatt ingoptionsareavailable.Iwill coverjustafewofthesimplestandmostcommonlyusedpossib ilitieshere. Youcanusethefunction System.out.printf toproduceformattedoutput.(Thename \printf,"whichstandsfor\printformatted,"iscopiedfro mtheCandC++programming languages,whichhavealwayshaveasimilarformattingcapa bility). System.out.printf takes twoormoreparameters.Therstparameterisa String thatspeciestheformatoftheoutput. Thisparameteriscalledthe formatstring .Theremainingparametersspecifythevaluesthat

PAGE 55

CHAPTER2.NAMESANDTHINGS 41 aretobeoutput.Hereisastatementthatwillprintanumberi ntheproperformatforadollar amount,where amount isavariableoftype double : System.out.printf("%1.2f",amount); TextIO canalsodoformattedoutput.Thefunction TextIO.putf hasthesame functionalityas System.out.printf .Using TextIO ,theaboveexamplewouldbe: TextIO.printf("%1.2",amount); andyoucouldsay TextIO.putln("%1.2f",principal); insteadof TextIO.putln(principal); inthe Interest2 programtogettheoutputinthe rightformat. Theoutputformatofavalueisspeciedbya formatspecier .Theformatstring(in thesimplecasesthatIcoverhere)containsoneformatspeci erforeachofthevaluesthatis tobeoutput.Sometypicalformatspeciersare %d %12d %10s %1.2f %15.8e and %1.8g Everyformatspecierbeginswithapercentsign( % )andendswithaletter,possiblywithsome extraformattinginformationinbetween.Theletterspeci esthetypeofoutputthatistobe produced.Forexample,in %d and %12d ,the\d"speciesthatanintegeristobewritten.The \12"in %12d speciestheminimumnumberofspacesthatshouldbeusedfor theoutput.If theintegerthatisbeingoutputtakesupfewerthan12spaces ,extrablankspacesareadded infrontoftheintegertobringthetotalupto12.Wesaythatt heoutputis\right-justied inaeldoflength12."Thevalueisnotforcedinto12spaces; ifthevaluehasmorethan12 digits,allthedigitswillbeprinted,withnoextraspaces. Thespecier %d meansthesameas %1d ;thatisanintegerwillbeprintedusingjustasmanyspacesa snecessary.(The\d,"bythe way,standsfor\decimal"(base-10)numbers.Youcanusean\ x"tooutputanintegervalue inhexadecimalform.) Theletter\s"attheendofaformatspeciercanbeusedwitha nytypeofvalue.It meansthatthevalueshouldbeoutputinitsdefaultformat,j ustasitwouldbeinunformatted output.Anumber,suchasthe\10"in %10s canbeaddedtospecifythe(minimum)number ofcharacters.The\s"standsfor\string,"meaningthatthe valueisconvertedintoa String valueintheusualway. Theformatspeciersforvaluesoftype double areevenmorecomplicated.An\f",as in %1.2f ,isusedtooutputanumberin\roating-point"form,thatisw ithdigitsafterthe decimalpoint.In %1.2f ,the\2"speciesthenumberofdigitstouseafterthedecima lpoint. The\1"speciesthe(minimum)numberofcharacterstooutpu t,whicheectivelymeansthat justasmanycharactersasarenecessaryshouldbeused.Simi larly, %12.3f wouldspecifya roating-pointformatwith3digitsafterthedecimalpoint, right-justiedinaeldoflength12. Verylargeandverysmallnumbersshouldbewritteninexpone ntialformat,suchas 6.00221415e23,representing\6.00221415times10raisedt othepower23."Aformatspeciersuchas %15.8e speciesanoutputinexponentialform,withthe\8"telling howmany digitstouseafterthedecimalpoint.Ifyouuse\g"insteado f\e",theoutputwillbein roating-pointformforsmallvaluesandinexponentialform forlargevalues.In %1.8g ,the 8givesthetotalnumberofdigitsintheanswer,includingbo ththedigitsbeforethedecimal pointandthedigitsafterthedecimalpoint. Inadditiontoformatspeciers,theformatstringina printf statementcanincludeother characters.Theseextracharactersarejustcopiedtotheou tput.Thiscanbeaconvenientway toinsertvaluesintothemiddleofanoutputstring.Forexam ple,if x and y arevariablesof type int ,youcouldsay System.out.printf("Theproductof%dand%dis%d",x,y,x*y ); Whenthisstatementisexecuted,thevalueof x issubstitutedfortherst %d inthestring,the

PAGE 56

CHAPTER2.NAMESANDTHINGS 42 valueof y forthesecond %d ,andthevalueoftheexpression x*y forthethird,sotheoutput wouldbesomethinglike\Theproductof17and42is714"(quot ationmarksnotincludedin output!).2.4.5IntroductiontoFileI/OSystem.out sendsitsoutputtotheoutputdestinationknownas\standar doutput."Butstandardoutputisjustonepossibleoutputdestination.Forexa mple,datacanbewrittentoa le thatisstoredontheuser'sharddrive.Theadvantagetothis ,ofcourse,isthatthedatais savedintheleevenaftertheprogramends,andtheusercanp rintthele,emailittosomeone else,edititwithanotherprogram,andsoon. TextIO hastheabilitytowritedatatolesandtoreaddatafromles .Whenyouwrite outputusingthe put putln ,or putf methodin TextIO ,theoutputissenttothe current outputdestination. Bydefault,thecurrentoutputdestinationisstandardoutp ut.However, TextIO hassomesubroutinesthatcanbeusedtochangethecurrentou tputdestination.To writetoalenamed\result.txt",forexample,youwoulduse thestatement: TextIO.writeFile("result.txt"); Afterthisstatementisexecuted,anyoutputfrom TextIO outputstatementswillbesenttothe lenamed\result.txt"insteadoftostandardoutput.Thel eshouldbecreatedinthesame directorythatcontainstheprogram.Notethatifalewitht hesamenamealreadyexists,its previouscontentswillbeerased!Inmanycases,youwanttol ettheuserselectthelethat willbeusedforoutput.Thestatement TextIO.writeUserSelectedFile(); willopenatypicalgraphical-user-interfaceleselectio ndialogwheretheusercanspecifythe outputle.Ifyouwanttogobacktosendingoutputtostandar doutput,youcansay TextIO.writeStandardOutput(); Youcanalsospecifytheinputsourcefor TextIO's various\get"functions.Thedefaultinput sourceisstandardinput.Youcanusethestatement TextIO.readFile("data.txt") toread fromalenamed\data.txt"instead,oryoucanlettheuserse lecttheinputlebysaying TextIO.readUserSelectedFile() ,andyoucangobacktoreadingfromstandardinputwith TextIO.readStandardInput() Whenyourprogramisreadingfromstandardinput,theuserge tsachancetocorrectany errorsintheinput.Thisisnotpossiblewhentheprogramisr eadingfromale.Ifillegaldata isfoundwhenaprogramtriestoreadfromale,anerroroccur sthatwillcrashtheprogram. (Later,wewillseethatisispossibleto\catch"sucherrors andrecoverfromthem.)Errorscan alsooccur,thoughmorerarely,whenwritingtoles. Acompleteunderstandingofleinput/outputinJavarequir esaknowledgeofobjectorientedprogramming.Wewillreturntothetopiclater,in Chapter11 .TheleI/Ocapabilities in TextIO areratherprimitivebycomparison.Nevertheless,theyare sucientformanyapplications,andtheywillallowyoutogetsomeexperiencewith lessoonerratherthanlater. Asasimpleexample,hereisaprogramthataskstheusersomeq uestionsandoutputsthe user'sresponsestoalenamed\prole.txt": publicclassCreateProfile{ publicstaticvoidmain(String[]args){

PAGE 57

CHAPTER2.NAMESANDTHINGS 43 Stringname;//Theuser'sname.Stringemail;//Theuser'semailaddress.doublesalary;//theuser'syearlysalary.StringfavColor;//Theuser'sfavoritecolor.TextIO.putln("GoodAfternoon!Thisprogramwillcreate") ; TextIO.putln("yourprofilefile,ifyouwilljustanswer") ; TextIO.putln("afewsimplequestions.");TextIO.putln();/*Gatherresponsesfromtheuser.*/TextIO.put("Whatisyourname?");name=TextIO.getln();TextIO.put("Whatisyouremailaddress?");email=TextIO.getln();TextIO.put("Whatisyouryearlyincome?");salary=TextIO.getlnDouble();TextIO.put("Whatisyourfavoritecolor?");favColor=TextIO.getln();/*Writetheuser'sinformationtothefilenamedprofile.tx t.*/ TextIO.writeFile("profile.txt");//subsequentoutputg oestothefile TextIO.putln("Name:"+name);TextIO.putln("Email:"+email);TextIO.putln("FavoriteColor:"+favColor);TextIO.putf("YearlyIncome:%1.2f\n",salary); //The"/n"inthepreviouslineisacarriagereturn. /*Printafinalmessagetostandardoutput.*/TextIO.writeStandardOutput();TextIO.putln("Thankyou.Yourprofilehasbeenwrittentop rofile.txt."); } } 2.5DetailsofExpressionsT hissectiontakesacloserlook atexpressions.Recallthatanexpressionisapieceof (online) programcodethatrepresentsorcomputesavalue.Anexpress ioncanbealiteral,avariable, afunctioncall,orseveralofthesethingscombinedwithope ratorssuchas + and > .Thevalue ofanexpressioncanbeassignedtoavariable,usedasaparam eterinasubroutinecall,or combinedwithothervaluesintoamorecomplicatedexpressi on.(Thevaluecaneven,insome cases,beignored,ifthat'swhatyouwanttodo;thisismorec ommonthanyoumightthink.) Expressionsareanessentialpartofprogramming.Sofar,th esenoteshavedealtonlyinformally withexpressions.Thissectiontellsyouthemore-or-lessc ompletestory(leavingoutsomeof thelesscommonlyusedoperators). Thebasicbuildingblocksofexpressionsareliterals(such as 674 3.14 true ,and 'X' ), variables,andfunctioncalls.Recallthatafunctionisasu broutinethatreturnsavalue.You've alreadyseensomeexamplesoffunctions,suchastheinputro utinesfromthe TextIO classand themathematicalfunctionsfromthe Math class.

PAGE 58

CHAPTER2.NAMESANDTHINGS 44 The Math classalsocontainsacoupleofmathematicalconstantsthat areusefulinmathematicalexpressions: Math.PI represents (theratioofthecircumferenceofacircletoits diameter),and Math.E represents e (thebaseofthenaturallogarithms).These\constants" areactuallymembervariablesin Math oftype double .Theyareonlyapproximationsforthe mathematicalconstants,whichwouldrequireaninnitenum berofdigitstospecifyexactly. Literals,variables,andfunctioncallsaresimpleexpress ions.Morecomplexexpressions canbebuiltupbyusing operators tocombinesimplerexpressions.Operatorsinclude + for addingtwonumbers, > forcomparingtwovalues,andsoon.Whenseveraloperatorsa ppear inanexpression,thereisaquestionof precedence ,whichdetermineshowtheoperatorsare groupedforevaluation.Forexample,intheexpression\ A+B*C ", B*C iscomputedrst andthentheresultisaddedto A .Wesaythatmultiplication( )has higherprecedence thanaddition( + ).Ifthedefaultprecedenceisnotwhatyouwant,youcanusep arenthesesto explicitlyspecifythegroupingyouwant.Forexample,youc oulduse\ (A+B)*C "ifyou wanttoadd A to B rstandthenmultiplytheresultby C TherestofthissectiongivesdetailsofoperatorsinJava.T henumberofoperatorsinJava isquitelarge,andIwillnotcoverthemallhere.Mostofthei mportantonesarehere;afew willbecoveredinlaterchaptersastheybecomerelevant.2.5.1ArithmeticOperatorsArithmeticoperatorsincludeaddition,subtraction,mult iplication,anddivision.Theyare indicatedby + ,and / .Theseoperationscanbeusedonvaluesofanynumerictype: byte short int long roat ,or double .Whenthecomputeractuallycalculatesoneofthese operations,thetwovaluesthatitcombinesmustbeofthesam etype.Ifyourprogramtells thecomputertocombinetwovaluesofdierenttypes,thecom puterwillconvertoneofthe valuesfromonetypetoanother.Forexample,tocompute37.4 +10,thecomputerwillconvert theinteger10toarealnumber10.0andwillthencompute37.4 +10.0.Thisiscalleda type conversion .Ordinarily,youdon'thavetoworryabouttypeconversioni nexpressions,because thecomputerdoesitautomatically. Whentwonumericalvaluesarecombined(afterdoingtypecon versionononeofthem,if necessary),theanswerwillbeofthesametype.Ifyoumultip lytwo int s,yougetan int ;ifyou multiplytwo double s,yougeta double .Thisiswhatyouwouldexpect,butyouhavetobe verycarefulwhenyouusethedivisionoperator / .Whenyoudividetwointegers,theanswer willalwaysbeaninteger;ifthequotienthasafractionalpa rt,itisdiscarded.Forexample,the valueof 7/2 is 3 ,not 3.5 .If N isanintegervariable,then N/100 isaninteger,and 1/N isequal tozeroforany N greaterthanone!Thisfactisacommonsourceofprogramming errors.You canforcethecomputertocomputearealnumberastheanswerb ymakingoneoftheoperands real:Forexample,whenthecomputerevaluates 1.0/N ,itrstconverts N toarealnumberin ordertomatchthetypeof 1.0 ,soyougetarealnumberastheanswer. Javaalsohasanoperatorforcomputingtheremainderwhenon eintegerisdividedby another.Thisoperatorisindicatedby % .If A and B areintegers,then A%B representsthe remainderwhen A isdividedby B .(However,fornegativeoperands, % isnotquitethesameas theusualmathematical\modulus"operator,sinceifoneof A or B isnegative,thenthevalue of A%B willbenegative.)Forexample, 7%2 is 1 ,while 34577%100 is 77 ,and 50%8 is 2 .Acommonuseof % istotestwhetheragivenintegerisevenorodd. N isevenif N%2 is zero,anditisoddif N%2 is 1 .Moregenerally,youcancheckwhetheraninteger N isevenly divisiblebyaninteger M bycheckingwhether N%M iszero. Finally,youmightneedthe unaryminus operator,whichtakesthenegativeofanumber.

PAGE 59

CHAPTER2.NAMESANDTHINGS 45 Forexample, -X hasthesamevalueas (-1)*X .Forcompleteness,Javaalsohasaunaryplus operator,asin +X ,eventhoughitdoesn'treallydoanything. Bytheway,recallthatthe + operatorcanalsobeusedtoconcatenateavalueofany typeontoa String .Thisisanotherexampleoftypeconversion.InJava,anytyp ecanbe automaticallyconvertedintotype String 2.5.2IncrementandDecrementYou'llndthatadding 1 toavariableisanextremelycommonoperationinprogrammin g. Subtracting 1 fromavariableisalsoprettycommon.Youmightperformtheo perationof adding 1 toavariablewithassignmentstatementssuchas: counter=counter+1;goalsScored=goalsScored+1; Theeectoftheassignmentstatement x=x+1 istotaketheoldvalueofthevariable x ,computetheresultofadding 1 tothatvalue,andstoretheanswerasthenewvalueof x .Thesameoperationcanbeaccomplishedbywriting x++ (or,ifyouprefer, ++x ).This actuallychangesthevalueof x ,sothatithasthesameeectaswriting\ x=x+1 ".Thetwo statementsabovecouldbewritten counter++;goalsScored++; Similarly,youcouldwrite x-(or --x )tosubtract 1 from x .Thatis, x-performsthesame computationas x=x-1 .Adding 1 toavariableiscalled incrementing thatvariable, andsubtracting 1 iscalled decrementing .Theoperators ++ and -arecalledtheincrement operatorandthedecrementoperator,respectively.Theseo peratorscanbeusedonvariables belongingtoanyofthenumericaltypesandalsoonvariables oftype char Usually,theoperators ++ or -areusedinstatementslike\ x++ ;"or\ x-;".Thesestatementsarecommandstochangethevalueof x .However,itisalsolegaltouse x++ ++x x-, or --x asexpressions,oraspartsoflargerexpressions.Thatis,y oucanwritethingslike: y=x++;y=++x;TextIO.putln(--x);z=(++x)*(y--); Thestatement\ y=x++ ;"hastheeectsofadding 1 tothevalueof x and,inaddition,assigning somevalueto y .Thevalueassignedto y isthevalueoftheexpression x++ ,whichisdened tobethe old valueof x ,beforethe 1 isadded.Thus,ifthevalueof x is 6 ,thestatement\ y =x++ ;"willchangethevalueof x to 7 ,butitwillchangethevalueof y to 6 sincethevalue assignedto y isthe old valueof x .Ontheotherhand,thevalueof ++x isdenedtobethe new valueof x ,afterthe 1 isadded.Soif x is 6 ,thenthestatement\ y=++x ;"changesthe valuesofboth x and y to 7 .Thedecrementoperator, -,worksinasimilarway. Thiscanbeconfusing.Myadviceis:Don'tbeconfused.Use ++ and -onlyinstand-alone statements,notinexpressions.Iwillfollowthisadvicein alltheexamplesinthesenotes. 2.5.3RelationalOperatorsJavahasbooleanvariablesandboolean-valuedexpressions thatcanbeusedtoexpressconditionsthatcanbeeither true or false .Onewaytoformaboolean-valuedexpressionis

PAGE 60

CHAPTER2.NAMESANDTHINGS 46 tocomparetwovaluesusinga relationaloperator .Relationaloperatorsareusedtotest whethertwovaluesareequal,whetheronevalueisgreaterth ananother,andsoforth.The relationaloperatorsinJavaare: == != < > <= ,and >= .Themeaningsoftheseoperatorsare: A==BIsA"equalto"B?A!=BIsA"notequalto"B?ABIsA"greaterthan"B?A<=BIsA"lessthanorequalto"B?A>=BIsA"greaterthanorequalto"B? Theseoperatorscanbeusedtocomparevaluesofanyofthenum erictypes.Theycanalsobe usedtocomparevaluesoftype char .Forcharacters, < and > aredenedaccordingthenumeric Unicodevaluesofthecharacters.(Thismightnotalwaysbew hatyouwant.Itisnotthesame asalphabeticalorderbecausealltheuppercaseletterscom ebeforeallthelowercaseletters.) Whenusingbooleanexpressions,youshouldrememberthatas farasthecomputerisconcerned,thereisnothingspecialaboutbooleanvalues.Inth enextchapter,youwillseehowto usetheminloopandbranchstatements.Butyoucanalsoassig nboolean-valuedexpressions tobooleanvariables,justasyoucanassignnumericvaluest onumericvariables. Bytheway,theoperators == and != canbeusedtocomparebooleanvalues.Thisis occasionallyuseful.Forexample,canyougureoutwhatthi sdoes: booleansameSign;sameSign=((x>0)==(y>0)); Onethingthatyou cannot dowiththerelationaloperators < > <= ,and <= istousethem tocomparevaluesoftype String .Youcanlegallyuse == and != tocompare Strings ,but becauseofpeculiaritiesinthewayobjectsbehave,theymig htnotgivetheresultsyouwant. (The == operatorcheckswhethertwoobjectsarestoredinthesameme morylocation,rather thanwhethertheycontainthesamevalue.Occasionally,for someobjects,youdowanttomake suchacheck|butrarelyforstrings.I'llgetbacktothisina laterchapter.)Instead,youshould usethesubroutines equals() equalsIgnoreCase() ,and compareTo() ,whichweredescribed in Section2.3 ,tocomparetwo Strings 2.5.4BooleanOperatorsInEnglish,complicatedconditionscanbeformedusingthew ords\and",\or",and\not."For example,\Ifthereisatest and youdid not studyforit...".\And",\or",and\not"are booleanoperators ,andtheyexistinJavaaswellasinEnglish. InJava,thebooleanoperator\and"isrepresentedby && .The && operatorisusedto combinetwobooleanvalues.Theresultisalsoabooleanvalu e.Theresultis true if both ofthecombinedvaluesare true ,andtheresultis false if either ofthecombinedvaluesis false .Forexample,\ (x==0)&&(y==0) "is true ifandonlyifboth x isequalto0and y isequalto0. Thebooleanoperator\or"isrepresentedby || .(That'ssupposedtobetwoofthevertical linecharacters, | .)Theexpression\ A||B "is true ifeither A is true or B is true ,orifboth aretrue.\ A||B "is false onlyifboth A and B arefalse. Theoperators && and || aresaidtobe short-circuited versionsofthebooleanoperators. Thismeansthatthesecondoperandof && or || isnotnecessarilyevaluated.Considerthetest (x!=0)&&(y/x>1)

PAGE 61

CHAPTER2.NAMESANDTHINGS 47 Supposethatthevalueof x isinfactzero.Inthatcase,thedivision y/x isundenedmathmatically.However,thecomputerwillneverperformthediv ision,sincewhenthecomputer evaluates (x!=0) ,itndsthattheresultis false ,andsoitknowsthat( (x!=0)&& anything )hastobefalse.Therefore,itdoesn'tbothertoevaluateth esecondoperand, (y/x>1) Theevaluationhasbeenshort-circuitedandthedivisionby zeroisavoided.Withouttheshortcircuiting,therewouldhavebeenadivisionbyzero.(Thism ayseemlikeatechnicality,andit is.Butattimes,itwillmakeyourprogramminglifealittlee asier.) Thebooleanoperator\not"isaunaryoperator.InJava,itis indicatedby andiswritten infrontofitssingleoperand.Forexample,if test isabooleanvariable,then test=!test; willreversethevalueoftest,changingitfrom true to false ,orfrom false to true 2.5.5ConditionalOperatorAnygoodprogramminglanguagehassomeniftylittlefeature sthataren'treallynecessarybut thatletyoufeelcoolwhenyouusethem.Javahastheconditio naloperator.It'saternary operator|thatis,ithasthreeoperands|anditcomesintwop ieces,?and:,thathavetobe usedtogether.Ittakestheform h boolean-expression i ? h expression1 i : h expression2 i Thecomputerteststhevalueof h boolean-expression i .Ifthevalueis true ,itevaluates h expression1 i ;otherwise,itevaluates h expression2 i .Forexample: next=(N%2==0)?(N/2):(3*N+1); willassignthevalue N/2 to next if N iseven(thatis,if N%2==0 is true ),anditwillassign thevalue (3*N+1) to next if N isodd.(Theparenthesesinthisexamplearenotrequired,bu t theydomaketheexpressioneasiertoread.)2.5.6AssignmentOperatorsandType-CastsYouarealreadyfamiliarwiththeassignmentstatement,whi chusesthesymbol\="toassign thevalueofanexpressiontoavariable.Infact,=isreallya noperatorinthesensethatan assignmentcanitselfbeusedasanexpressionoraspartofam orecomplexexpression.The valueofanassignmentsuchas A=B isthesameasthevaluethatisassignedto A .So,ifyou wanttoassignthevalueof B to A andtestatthesametimewhetherthatvalueiszero,you couldsay: if((A=B)==0)... Usually,Iwouldsay, don'tdothingslikethat Ingeneral,thetypeoftheexpressionontheright-handside ofanassignmentstatement mustbethesameasthetypeofthevariableontheleft-handsi de.However,insomecases, thecomputerwillautomaticallyconvertthevaluecomputed bytheexpressiontomatchthe typeofthevariable.Considerthelistofnumerictypes: byte short int long roat double Avalueofatypethatoccursearlierinthislistcanbeconver tedautomaticallytoavaluethat occurslater.Forexample: intA;doubleX;shortB;

PAGE 62

CHAPTER2.NAMESANDTHINGS 48 A=17;X=A;//OK;AisconvertedtoadoubleB=A;//illegal;noautomaticconversion //frominttoshort Theideaisthatconversionshouldonlybedoneautomaticall ywhenitcanbedonewithout changingthesemanticsofthevalue.Any int canbeconvertedtoa double withthesame numericvalue.However,thereare int valuesthatlieoutsidethelegalrangeof short s.There issimplynowaytorepresentthe int 100000asa short ,forexample,sincethelargestvalueof type short is32767. Insomecases,youmightwanttoforceaconversionthatwould n'tbedoneautomatically. Forthis,youcanusewhatiscalleda typecast .Atypecastisindicatedbyputtingatype name,inparentheses,infrontofthevalueyouwanttoconver t.Forexample, intA;shortB;A=17;B=(short)A;//OK;Aisexplicitlytypecast //toavalueoftypeshort Youcandotypecastsfromanynumerictypetoanyothernumeri ctype.However,youshould notethatyoumightchangethenumericvalueofanumberbytyp e-castingit.Forexample, (short)100000 is-31072.(The-31072isobtainedbytakingthe4-byte int 100000andthrowing awaytwoofthosebytestoobtaina short |you'velosttherealinformationthatwasinthose twobytes.) Asanotherexampleoftypecasts,considertheproblemofget tingarandomintegerbetween 1and6.Thefunction Math.random() givesarealnumberbetween0.0and0.9999...,andso 6*Math.random() isbetween0.0and5.999....Thetype-castoperator, (int) ,canbeusedto convertthistoaninteger: (int)(6*Math.random()) .Arealnumberiscasttoanintegerby discardingthefractionalpart.Thus, (int)(6*Math.random()) isoneoftheintegers0,1,2,3, 4,and5.Togetanumberbetween1and6,wecanadd1:\ (int)(6*Math.random())+1 ". Youcanalsotype-castbetweenthetype char andthenumerictypes.Thenumericvalue ofa char isitsUnicodecodenumber.Forexample, (char)97 is 'a' ,and (int)'+' is 43 (However,atypeconversionfrom char to int isautomaticanddoesnothavetobeindicated withanexplicittypecast.) Javahasseveralvariationsontheassignmentoperator,whi chexisttosavetyping.For example,\ A+=B "isdenedtobethesameas\ A=A+B ".EveryoperatorinJavathat appliestotwooperandsgivesrisetoasimilarassignmentop erator.Forexample: x-=y;//sameas:x=x-y;x*=y;//sameas:x=x*y;x/=y;//sameas:x=x/y;x%=y;//sameas:x=x%y;(forintegersxandy)q&&=p;//sameas:q=q&&p;(forbooleansqandp) Thecombinedassignmentoperator += evenworkswithstrings.Recallthatwhenthe + operator isusedwithastringasoneoftheoperands,itrepresentscon catenation.Since str+=x is equivalentto str=str+x ,when += isusedwithastringontheleft-handside,itappends thevalueontheright-handsideontothestring.Forexample ,if str hasthevalue\tire",then thestatement str+='d'; changesthevalueof str to\tired".

PAGE 63

CHAPTER2.NAMESANDTHINGS 49 2.5.7TypeConversionofStringsInadditiontoautomatictypeconversionsandexplicittype casts,therearesomeothercases whereyoumightwanttoconvertavalueofonetypeintoavalue ofadierenttype.One commonexampleistheconversionofa String valueintosomeothertype,suchasconverting thestring "10" intothe int value10orthestring "17.42e-2" intothe double value0.1742.In Java,theseconversionsarehandledbybuilt-infunctions. Thereisastandardclassnamed Integer thatcontainsseveralsubroutinesandvariables relatedtothe int datatype.(Recallthatsince int isnotaclass, int itselfcan'tcontain anysubroutinesorvariables.)Inparticular,if str isanyexpressionoftype String ,then Integer.parseInt(str) isafunctioncallthatattemptstoconvertthevalueof str intoa valueoftype int .Forexample,thevalueof Integer.parseInt("10") isthe int value10.If theparameterto Integer.parseInt doesnotrepresentalegal int value,thenanerroroccurs. Similarly,thestandardclassnamed Double includesafunction Double.parseDouble that triestoconvertaparameteroftype String intoavalueoftype double .Forexample,the valueofthefunctioncall Double.parseDouble("3.14") isthe double value3.14.(Ofcourse, inpractice,theparameterusedin Double.parseDouble or Integer.parseInt wouldbea variableorexpressionratherthanaconstantstring.) Typeconversionfunctionsalsoexistforconvertingstring sintoenumeratedtypevalues. (Enumeratedtypes,orenums,wereintroducedin Subsection2.3.3 .)Foranyenumtype,a predenedfunctionnamed valueOf isautomaticallydenedforthattype.Thisisafunction thattakesastringasparameterandtriestoconvertittoava luebelongingtotheenum.The valueOf functionispartoftheenumtype,sothenameoftheenumispar tofthefullnameof thefunction.Forexample,ifanenum Suit isdenedas enumSuit{SPADE,DIAMOND,CLUB,HEART} thenthenameofthetypeconversionfunctionwouldbe Suit.valueOf .Thevalueofthe functioncall Suit.valueOf("CLUB") wouldbetheenumeratedtypevalue Suit.CLUB .Forthe conversiontosucceed,thestringmustexactlymatchthesim plenameofoneoftheenumerated typeconstants( without the\Suit."infront). 2.5.8PrecedenceRulesIfyouuseseveraloperatorsinoneexpression,andifyoudon 'tuseparenthesestoexplicitly indicatetheorderofevaluation,thenyouhavetoworryabou ttheprecedencerulesthatdeterminetheorderofevaluation.(Advice:don'tconfuseyourse lforthereaderofyourprogram; useparenthesesliberally.) Hereisalistingoftheoperatorsdiscussedinthissection, listedinorderfromhighest precedence(evaluatedrst)tolowestprecedence(evaluat edlast): Unaryoperators:++,--,!,unary-and+,type-castMultiplicationanddivision:*,/,%Additionandsubtraction:+,-Relationaloperators:<,>,<=,>=Equalityandinequality:==,!=Booleanand:&&Booleanor:||Conditionaloperator:?:Assignmentoperators:=,+=,-=,*=,/=,%=

PAGE 64

CHAPTER2.NAMESANDTHINGS 50 Operatorsonthesamelinehavethesameprecedence.Whenope ratorsofthesameprecedence arestrungtogetherintheabsenceofparentheses,unaryope ratorsandassignmentoperatorsare evaluatedright-to-left,whiletheremainingoperatorsar eevaluatedleft-to-right.Forexample, A*B/C means (A*B)/C ,while A=B=C means A=(B=C) .(Canyouseehowtheexpression A=B=C mightbeuseful,giventhatthevalueof B=C asanexpressionisthesameasthevaluethatis assignedto B ?) 2.6ProgrammingEnvironmentsA lthoughtheJavalanguage ishighlystandardized,theproceduresforcreating,compi l(online) ing,andeditingJavaprogramsvarywidelyfromoneprogramm ingenvironmenttoanother. Therearetwobasicapproaches:a commandlineenvironment ,wheretheusertypescommandsandthecomputerresponds,andan integrateddevelopmentenvironment (IDE), wheretheuserusesthekeyboardandmousetointeractwithag raphicaluserinterface.While thereisjustonecommoncommandlineenvironmentforJavapr ogramming,thereisawide varietyofIDEs. IcannotgivecompleteordenitiveinformationonJavaprog rammingenvironmentsinthis section,butIwilltrytogiveenoughinformationtoletyouc ompileandruntheexamplesfrom thistextbook,atleastinacommandlineenvironment.There aremanyIDEs,andIcan't coverthemallhere.Iwillconcentrateon Eclipse ,oneofthemostpopularIDEsforJava programming,butsomeoftheinformationthatispresentedw illapplytootherIDEsaswell. Onethingtokeepinmindisthatyoudonothavetopayanymoney todoJavaprogramming (asidefrombuyingacomputer,ofcourse).Everythingthaty ouneedcanbedownloadedfor freeontheInternet.2.6.1JavaDevelopmentKitThebasicdevelopmentsystemforJavaprogrammingisusuall yreferredtoasthe JDK (Java DevelopmentKit).ItisapartofJ2SE,theJava2PlatformSta ndardEdition.Thisbook requiresJ2SEversion5.0(orhigher).Confusingly,theJDK thatispartofJ2SEversion5.0 issometimesreferredtoasJDK1.5insteadof5.0.NotethatJ 2SEcomesintwoversions, aDevelopmentKitversionandaRuntimeversion.TheRuntime canbeusedtorunJava programsandtoviewJavaappletsinWebpages,butitdoesnot allowyoutocompileyour ownJavaprograms.TheDevelopmentKitincludestheRuntime andaddstoittheJDKwhich letsyoucompileprograms.YouneedaJDKforusewiththistex tbook. JavawasdevelopedbySunMicrosystems,Inc.,whichmakesit sJDKforWindowsandLinux availableforfreedownloadatitsJavaWebsite, java.sun.com .IfyouhaveaWindowscomputer, itmighthavecomewithaJavaRuntime,butyoumightstillnee dtodownloadtheJDK.Some versionsofLinuxcomewiththeJDKeitherinstalledbydefau ltorontheinstallationmedia.If youneedtodownloadandinstalltheJDK,besuretogetJDK5.0 (orhigher).AsofJune,2006, thedownloadpageforJDK5.0canbefoundat http://java.sun.com/j2se/1.5.0/download.jsp MacOScomeswithJava.TheversionincludedwithMacOS10.4i s1.4.2,theversion previoustoJava5.0.However,JDKVersion5.0isavailablef orMacOS10.4on Apple'sWeb site andcanalsobeinstalledthroughthestandardMacOSSoftwar eUpdateapplication. IfaJDKisinstalledonyourcomputer,youcanusethecommand lineenvironmentto compileandrunJavaprograms.SomeIDEsdependontheJDK,so evenifyouplantousean IDEforprogramming,youmightstillneedaJDK.

PAGE 65

CHAPTER2.NAMESANDTHINGS 51 2.6.2CommandLineEnvironmentManymoderncomputerusersndthecommandlineenvironment tobeprettyalienandunintuitive.Itiscertainlyverydierentfromthegraphicalus erinterfacesthatmostpeopleareused to.However,ittakesonlyalittlepracticetolearnthebasi csofthecommandlineenvironment andtobecomeproductiveusingit. Touseacommandlineprogrammingenvironment,youwillhave toopenawindowwhere youcantypeincommands.InWindows,youcanopensuchacomma ndwindowbyrunning theprogramnamed cmd .Onewaytorun cmd istousethe\RunProgram"featureinthe Startmenu,andenter\cmd"asthenameoftheprogram.InMacO S,youwanttorunthe Terminal program,whichcanbebefoundintheUtilitiesfolderinside theApplicationsfolder. InLinux,thereareseveralpossibilities,including Konsole gterm ,and xterm Nomatterwhattypeofcomputeryouareusing,whenyouopenac ommandwindow,it willdisplayapromptofsomesort.Typeinacommandatthepro mptandpressreturn.The computerwillcarryoutthecommand,displayinganyoutputi nthecommandwindow,andwill thenredisplaythepromptsothatyoucantypeanothercomman d.Oneofthecentralconcepts inthecommandlineenvironmentisthe currentdirectory whichcontainsthelestowhich commandsthatyoutypeapply.(Thewords\directory"and\fo lder"meanthesamething.) Often,thenameofthecurrentdirectoryispartofthecomman dprompt.Youcangetalistof thelesinthecurrentdirectorybytypinginthecommand dir (onWindows)or ls (onLinux andMacOS).Whenthewindowrstopens,thecurrentdirector yisyour homedirectory whereallyourlesarestored.Youcanchangethecurrentdir ectoryusingthe cd command withthenameofthedirectorythatyouwanttouse.Forexampl e,tochangeintoyourDesktop directory,typeinthecommand cdDesktop andpressreturn. Youshouldcreateadirectory(thatis,afolder)toholdyour Javawork.Forexample,createa directorynamed javawork inyourhomedirectory.Youcandothisusingyourcomputer's GUI; anotherwaytodoitistoopenacommandwindowandentertheco mmand mkdirjavawork Whenyouwanttoworkonprogramming,openacommandwindowan denterthecommand cdjavawork tochangeintoyourworkdirectory.Ofcourse,youcanhavemo rethanone workingdirectoryforyourJavawork;youcanorganizeyour lesanywayyoulike. ThemostbasiccommandsforusingJavaonthecommandlineare javac and java ; javac isusedtocompileJavasourcecode,and java isusedtorunJavastand-aloneapplications.Ifa JDKiscorrectlyinstalledonyourcomputer,itshouldrecog nizethesecommandswhenyoutype theminonthecommandline.Trytypingthecommands java-version and javac-version whichshouldtellyouwhichversionofJavaisinstalled.Ify ougetamessagesuchas\Command notfound,"thenJavaisnotcorrectlyinstalled.Ifthe\jav a"commandworks,but\javac"does not,itmeansthataJavaRuntimeisinstalledratherthanaDe velopmentKit. Totestthe javac command,placeacopyof TextIO.java intoyourworkingdirectory.(Ifyou downloadedtheWebsiteofthisbook,youcannditinthedire ctorynamed source ;youcan useyourcomputer'sGUItocopy-and-pastethisleintoyour workingdirectory.Alternatively, youcannavigateto TextIO.java onthebook'sWebsiteandusethe\SaveAs"commandin yourWebbrowsertosaveacopyoftheleintoyourworkingdir ectory.)Typethecommand: javacTextIO.java Thiswillcompile TextIO.java andwillcreateabytecodelenamed TextIO.class inthesame directory.Notethatifthecommandsucceeds,youwillnotge tanyresponsefromthecomputer; itwilljustredisplaythecommandprompttotellyouit'srea dyforanothercommand.

PAGE 66

CHAPTER2.NAMESANDTHINGS 52 Totestthe java command,copysampleprogram Interest2.java fromthisbook'ssource directoryintoyourworkingdirectory.First,compilethep rogramwiththecommand javacInterest2.java Rememberthatforthistosucceed, TextIO mustalreadybeinthesamedirectory.Thenyou canexecutetheprogramusingthecommand javaInterest2 Becarefultouse justthename oftheprogram, Interest2 ,notthenameoftheJavasource codeleorthenameofthecompiledclassle.Whenyougiveth iscommand,theprogramwill run.Youwillbeaskedtoentersomeinformation,andyouwill respondbytypingyouranswers intothecommandwindow,pressingreturnattheendofthelin e.Whentheprogramends,you willseethecommandprompt,andyoucanenteranothercomman d. Youcanfollowthesameproceduretorunalloftheexamplesin theearlysectionsofthis book.Whenyoustartworkwithapplets,youwillneedadiere ntcommandtoexecutethe applets.Thatcommandwillbeintroducedlaterinthebook. Tocreateyourownprograms,youwillneeda texteditor .Atexteditorisacomputer programthatallowsyoutocreateandsavedocumentsthatcon tainplaintext.Itisimportant thatthedocumentsbesavedasplaintext,thatiswithoutany specialencodingorformatting information.Wordprocessordocumentsarenotappropriate ,unlessyoucangetyourword processortosaveasplaintext.Agoodtexteditorcanmakepr ogrammingalotmorepleasant. Linuxcomeswithseveraltexteditors.OnWindows,youcanus enotepadinapinch,butyou willprobablywantsomethingbetter.ForMacOS,youmightdo wnloadthefree TextWrangler application.Onepossibilitythatwillworkonanyplatform istouse jedit ,agoodprogrammer's texteditorthatisitselfwritteninJavaandthatcanbedown loadedforfreefrom www.jedit.org Tocreateyourownprograms,youshouldopenacommandlinewi ndowand cd intothe workingdirectorywhereyouwillstoreyoursourcecodeles .Startupyourtexteditorprogram, suchasbydouble-clickingitsiconorselectingitfromaSta rtmenu.Typeyourcodeintothe editorwindow,oropenanexistingsourcecodelethatyouwa nttomodify.Savethele. RememberthatthenameofaJavasourcecodelemustendin\.j ava",andtherestofthe lenamemustmatchthenameoftheclassthatisdenedinthe le.Oncetheleissavedin yourworkingdirectory,gotothecommandwindowandusethe javac commandtocompileit, asdiscussedabove.Iftherearesyntaxerrorsinthecode,th eywillbelistedinthecommand window.Eacherrormessagecontainsthelinenumberinthel ewherethecomputerfoundthe error.Gobacktotheeditorandtrytoxtheerrors, saveyourchanges ,andtheytrythe javac commandagain.(It'susuallyagoodideatojustworkonther stfewerrors;sometimes xingthosewillmakeothererrorsgoaway.)Rememberthatwh enthe javac commandnally succeeds,youwillgetnomessageatall.Thenyoucanusethe java commandtorunyour program,asdescribedabove.Onceyou'vecompiledtheprogr am,youcanrunitasmanytimes asyoulikewithoutrecompilingit. That'sreallyallthereistoit:Keepbotheditorandcommand -linewindowopen.Edit, save,andcompileuntilyouhaveeliminatedallthesyntaxer rors.(Alwaysremembertosave thelebeforecompilingit|thecompileronlyseesthesaved le,nottheversionintheeditor window.)Whenyouruntheprogram,youmightndthatithasse manticerrorsthatcauseit torunincorrectly.Itthatcase,youhavetogobacktotheedi t/save/compilelooptotryto ndandxtheproblem.

PAGE 67

CHAPTER2.NAMESANDTHINGS 53 2.6.3IDEsandEclipseInanIntegratedDevelopmentEnvironment,everythingyoun eedtocreate,compile,andrun programsisintegratedintoasinglepackage,withagraphic aluserinterfacethatwillbefamiliar tomostcomputerusers.TherearemanydierentIDEsforJava programdevelopment,ranging fromfairlysimplewrappersaroundtheJDKtohighlycomplex applicationswithamultitude offeatures.Forabeginningprogrammer,thereisadangerin usinganIDE,sincethediculty oflearningtousetheIDE,ontopofthedicultyoflearningt oprogram,canbeoverwhelming. Recently,however,IhavebegunusingoneIDE, Eclipse ,inmyintroductoryprogramming courses.Eclipsehasavarietyoffeaturesthatareveryusef ulforabeginningprogrammer. Andeventhoughithasmanyadvancedfeatures,itsdesignmak esitpossibletouseEclipse withoutunderstandingitsfullcomplexity.Itislikelytha tothermodernIDEshavesimilar properties,butmyonlyin-depthexperienceiswithEclipse .Eclipseisusedbymanyprofessional programmersandisprobablythemostcommonlyusedJavaIDE. (Infact,Eclipseisactually ageneraldevelopmentplatformthatcanbeusedforotherpur posesbesidesJavadevelopment, butitsmostcommonuseisJava.) EclipseisitselfwritteninJava.ItrequiresJava1.4(orhi gher)torun,soitworksonany computerplatformthatsupportsJava1.4,includingLinux, Windows,andrecentversionsof MacOS.IfyouwanttouseEclipsetocompileandrunJava5.0pr ograms,youneedEclipse version3.1(orhigher).Furthermore,EclipserequiresaJD K.Youshouldmakesurethat JDK5.0(orhigher)isinstalledonyourcomputer,asdescrib edabove, before youinstall Eclipse.Eclipsecanbedownloadedforfreefrom www.eclipse.org ThersttimeyoustartEclipse,youwillbeaskedtospecifya workspace ,whichisthe directorywhereallyourworkwillbestored.Youcanacceptt hedefaultname,orprovideone ofyourown.Whenstartupiscomplete,theEclipsewindowwil lbelledbyalarge\Welcome" screenthatincludeslinkstoextensivedocumentationandt utorials.Youcanclosethisscreen, byclickingthe\X"nexttotheword\Welcome";youcangetbac ktoitlaterbychoosing \Welcome"fromthe\Help"menu. TheEclipseGUIconsistsofonelargewindowthatisdividedi ntoseveralsections.Each sectioncontainsoneormore views .Ifthereareseveralviewsinonesection,theretherewill betabsatthetopofthesectiontoselecttheviewthatisdisp layedinthatsection.Eachview displaysadierenttypeofinformation.Thewholesetofvie wsiscalleda perspective .Eclipse usesdierentperspectives,thatisdierentsetsofviewso fdierenttypesofinformation,for dierenttasks.Theonlyperspectivethatyouwillneedisth e\JavaPerspective."Selectthe \JavaPerspective"fromthe\OpenPerspective"submenuoft he\Window"menu.(Youwill onlyhavetodothisonce,thersttimeyoustartEclipse.)Th eJavaperspectiveincludesa largeareainthecenterofthewindowwhereyouwillcreatean dedityourJavaprograms.To theleftofthisisthePackageExplorerview,whichwillcont ainalistofyourJavaprojectsand sourcecodeles.Totherightisan\Outline"viewwhichshow sanoutlineofthelethatyou arecurrentlyediting;Idon'tndthisveryuseful,andIsug gestthatyouclosetheOutlineview byclickingthe\X"nexttothewordOutline.Severalothervi ewsthatwillbeusefulwhileyou arecompilingandrunningprogramsappearinasectionofthe windowbelowtheeditingarea. Ifyouaccidentlycloseoneoftheimportantviews,suchasth ePackageExplorer,youcanget itbackbyselectingitformthe\ShowView"submenuofthe\Wi ndow"menu. TodoanyworkinEclipse,youneeda project .TostartaJavaproject,gotothe\New" submenuinthe\File"menu,andselectthe\Project"command .Inthewindowthatpops

PAGE 68

CHAPTER2.NAMESANDTHINGS 54 up,makesure\JavaProject"isselected,andclickthe\Next "button.Inthenextwindow, itshouldonlybenecessarytollina\ProjectName"forthep rojectandclickthe\Finish" button.Theprojectshouldappearinthe\PackageExplorer" view.Clickonthesmalltriangle nexttotheprojectnametoseethecontentsoftheproject.At thebeginning,itcontainsonly the\JRESystemLibrary";thisisthecollectionofstandard built-inclassesthatcomewith Java. Torunthe TextIO basedexamplesfromthistextbook,youmustaddthesourceco dele TextIO.java toyourproject.IfyouhavedownloadedtheWebsiteofthisbo ok,youcannda copyof TextIO.java inthesourcedirectory.Alternatively,youcannavigateto theleon-line andusethe\SaveAs"commandofyourWebbrowsertosaveacopy oftheleontoyour computer.Theeasiestwaytoget TextIO intoyourprojectistolocatethesourcecodeleon yourcomputeranddragtheleiconontotheprojectnameinth eEclipsewindow.Ifthat doesn'twork,youcantryusingcopy-and-paste:Right-clic ktheleicon(orcontrol-clickon MacOS),select\Copy"fromthepop-upmenu,right-clickthe projectnameintheEclipse window,andselect\Paste".Ifyoualsohavetroublewiththa t,youcantryusingthe\Import" commandinthe\File"menu;select\Filesystem"inthewindo wthatpopsup,click\Next", andprovidethenecessaryinformationinthenextwindow.(U nfortunately,usingtheleimport windowisrathercomplicated.Ifyoundthatyouhavetousei t,youshouldconsulttheEclipse documentationaboutit.)Inanycase, TextIO shouldappearinyourproject,insidea package named\defaultpackage".Youwillneedtoclickthesmalltri anglenextto\defaultpackage" toseethele.Oncealeisinthislist,youcanopenitbydoub le-clickingit;itwillappearin theeditingareaoftheEclipsewindow. TorunanyoftheJavaprogramsfromthistextbook,copytheso urcecodeleintoyour EclipseJavaproject.Toruntheprogram,right-clickthel enameinthePackageExplorer view(orcontrol-clickinMacOS).Inthemenuthatpopsup,go tothe\RunAs"submenu,and select\JavaApplication".Theprogramwillbeexecuted.If theprogramwritestostandard output,theoutputwillappearinthe\Console"view,undert heeditingarea.Iftheprogram uses TextIO forinput,youwillhavetotypetherequiredinputintothe\C onsole"view|click the\Console"viewbeforeyoustarttyping,sothatthechara ctersthatyoutypewillbesentto thecorrectpartofthewindow.(Notethatifyoudon'tlikedo ingI/Ointhe\Console"view, youcanuseanalternativeversionof TextIO.java thatopensaseparatewindowforI/O.You canndthis\GUI"versionofTextIOinadirectorynamed TextIO-GUI insidethistextbook's sourcedirectory.) YoucanhavemorethanoneprograminthesameEclipseproject ,oryoucancreateadditionalprojectstoorganizeyourworkbetter.Remembertopl aceacopyof TextIO.java inany projectthatrequiresit. TocreateyourownJavaprogram,youmustcreateanewJavacla ss.Todothis,right-click theJavaprojectnameinthe\ProjectExplorer"view.Gototh e\New"submenuofthepopup menu,andselect\Class".Inthewindowthatopens,typeinth enameoftheclass,andclick the\Finish"button.Notethatyouwantthenameoftheclass, notthenameofthesourcecode le,sodon'tadd\.java"attheendofthename.Theclassshou ldappearinsidethe\default package,"anditshouldautomaticallyopenintheeditingar easothatyoucanstarttypingin yourprogram. Eclipsehasseveralfeaturesthataidyouasyoutypeyourcod e.Itwillunderlineanysyntax errorwithajaggedredline,andinsomecaseswillplaceaner rormarkerintheleftborder oftheeditwindow.Ifyouhoverthemousecursorovertheerro rmarker,adescriptionofthe

PAGE 69

CHAPTER2.NAMESANDTHINGS 55 errorwillappear.Notethatyoudonothavetogetridofevery errorimmediatelyasyoutype; someerrorswillgoawayasyoutypeinmoreoftheprogram.Ifa nerrormarkerdisplaysa small\lightbulb,"Eclipseisoeringtotrytoxtheerrorf oryou.Clickthelightbulbtoget alistofpossiblexes,thendoubleclickthexthatyouwant toapply.Forexample,ifyou useanundeclaredvariableinyourprogram,Eclipsewilloe rtodeclareitforyou.Youcan actuallyusethiserror-correctingfeaturetogetEclipset owritecertaintypesofcodeforyou! Unfortunately,you'llndthatyouwon'tunderstandalotof theproposedxesuntilyoulearn moreabouttheJavalanguage. AnotherniceEclipsefeatureis codeassist .CodeassistcanbeinvokedbytypingControlSpace.Itwilloerpossiblecompletionsofwhateveryouare typingatthemoment.Forexample, ifyoutypepartofanidentierandhitControl-Space,youwi llgetalistofidentiersthatstart withthecharactersthatyouhavetyped;usetheupanddownar rowkeystoselectoneofthe itemsinthelist,andpressReturnorEnter.(OrhitEscapeto dismissthelist.)Ifthereis onlyonepossiblecompletionwhenyouhitControl-Space,it willbeinsertedautomatically.By default,CodeAssistwillalsopopupautomatically,aftera shortdelay,whenyoutypeaperiod orcertainothercharacters.Forexample,ifyoutype\ TextIO. "andpauseforjustafraction ofasecond,youwillgetalistofallthesubroutinesinthe TextIO class.Personally,Indthis auto-activationannoying.YoucandisableitintheEclipse Preferences.(LookunderJava/ Editor/CodeAssist,andturnothe\Enableautoactivation "option.)Youcanstillcallup CodeAssistmanuallywithControl-Space. Onceyouhaveanerror-freeprogram,youcanrunitasdescrib edabove,byright-clickingits nameinthePackageExplorerandusing\RunAs/JavaApplicat ion".Ifyoundaproblem whenyourunit,it'sveryeasytogobacktotheeditor,makech anges,andrunitagain.Note thatusingEclipse,thereisnoexplicit\compile"command. Thesourcecodelesinyour projectareautomaticallycompiled,andarere-compiledwh eneveryoumodifythem. AlthoughIhaveonlytalkedaboutEclipsehere,ifyouareusi ngadierentIDE,youwill probablyndalotofsimilarities.MostIDEsusetheconcept ofa\project"towhichyouhave toaddyoursourcecodeles,andmostofthemhavemenucomman dsforrunningaprogram. Allofthem,ofcourse,comewithbuilt-intexteditors.2.6.4TheProblemofPackagesEveryclassinJavaiscontainedinsomethingcalleda package .Classesthatarenotexplicitly putintoadierentpackageareinthe\default"package.Alm ostalltheexamplesinthis textbookareinthedefaultpackage,andIwillnotevendiscu sspackagesinanydepthuntil Section4.5 .However,someIDEsmightforceyoutopayattentiontopacka ges. WhenyoucreateaclassinEclipse,youmightnoticeamessage thatsaysthat\Theuse ofthedefaultpackageisdiscouraged."Althoughthisistru e,Ihavechosentouseitanyway, sinceitseemseasierforbeginningprogrammerstoavoidthe wholeissueofpackages,atleast atrst.SomeIDEsmightbeevenlesswillingthanEclipsetou sethedefaultpackage.Ifyou createaclassinapackage,thesourcecodestartswithaline thatspecieswhichpackagethe classisin.Forexample,iftheclassisinapackagenamed testpkg ,thentherstlineofthe sourcecodewillbe packagetestpkg; InanIDE,thiswillnotcauseanyproblemunlesstheprogramy ouarewritingdependson TextIO .Youwillnotbeabletouse TextIO inaprogramunless TextIO isplacedintothesame packageastheprogram.Thismeansthatyouhavetomodifythe sourcecodele TextIO.java

PAGE 70

CHAPTER2.NAMESANDTHINGS 56 tospecifythepackage;justadda package statementusingthesamepackagenameasthe program.Thenaddthemodied TextIO.java tothesamefolderthatcontainstheprogram sourcecode.Onceyou'vedonethis,theexampleshouldrunin thesamewayasifitwerein thedefaultpackage. Bytheway,ifyouusepackagesinacommand-lineenvironment ,othercomplicationsarise. Forexample,ifaclassisinapackagenamed testpkg ,thenthesourcecodelemustbein asubdirectorynamed testpkg thatisinsideyourmainJavaworkingdirectory.Neverthele ss, whenyoucompileorexecutetheprogram,youshouldbeinthem aindirectory,notinthe subdirectory.Whenyoucompilethesourcecodele,youhave toincludethenameofthe directoryinthecommand:Use\ javactestpkg/ClassName.java "onLinuxorMacOS,or \ javactestpkg\ClassName.java "onWindows.Thecommandforexecutingtheprogramis then\ javatestpkg.ClassName ",withaperiodseparatingthepackagenamefromtheclass name.Sincepackagescancontainsubpackages,itcangeteve nworsethanthis!However,you willnotneedtoworryaboutanyofthatwhenusingtheexample sinthisbook.

PAGE 71

Exercises 57 ExercisesforChapter2 1. Writeaprogramthatwillprintyourinitialstostandardout putinlettersthatarenine (solution) linestall.Eachbiglettershouldbemadeupofabunchof*'s. Forexample,ifyourinitials were\DJE",thentheoutputwouldlooksomethinglike: ******************************************************************************************************************** 2. Writeaprogramthatsimulatesrollingapairofdice.Youcan simulaterollingonedieby (solution) choosingoneoftheintegers1,2,3,4,5,or6atrandom.Thenu mberyoupickrepresents thenumberonthedieafteritisrolled.Aspointedoutin Section2.5 ,Theexpression (int)(Math.random()*6)+1 doesthecomputationyouneedtoselectarandomintegerbetw een1and6.Youcan assignthisvaluetoavariabletorepresentoneofthediceth atarebeingrolled.Dothis twiceandaddtheresultstogethertogetthetotalroll.Your programshouldreportthe numbershowingoneachdieaswellasthetotalroll.Forexamp le: Thefirstdiecomesup3Theseconddiecomesup5Yourtotalrollis8 3. Writeaprogramthataskstheuser'sname,andthengreetsthe userbyname.Before (solution) outputtingtheuser'sname,convertittouppercaseletters .Forexample,iftheuser's nameisFred,thentheprogramshouldrespond\Hello,FRED,n icetomeetyou!". 4. Writeaprogramthathelpstheusercounthischange.Theprog ramshouldaskhowmany (solution) quarterstheuserhas,thenhowmanydimes,thenhowmanynick els,thenhowmany pennies.Thentheprogramshouldtelltheuserhowmuchmoney hehas,expressedin dollars. 5. Ifyouhave N eggs,thenyouhave N/12 dozeneggs,with N%12 eggsleftover.(Thisis (solution) essentiallythedenitionofthe / and % operatorsforintegers.)Writeaprogramthatasks theuserhowmanyeggsshehasandthentellstheuserhowmanyd ozeneggsshehasand howmanyextraeggsareleftover. Agrossofeggsisequalto144eggs.Extendyourprogramsotha titwilltelltheuser howmanygross,howmanydozen,andhowmanyleftovereggsshe has.Forexample,if theusersaysthatshehas1342eggs,thenyourprogramwouldr espondwith Yournumberofeggsis9gross,3dozen,and10

PAGE 72

Exercises 58 since1342isequalto9*144+3*12+10. 6. Supposethatalenamed\testdata.txt"containsthefollow inginformation:Therst (solution) lineoftheleisthenameofastudent.Eachofthenextthreel inescontainsaninteger. Theintegersarethestudent'sscoresonthreeexams.Writea programthatwillread theinformationintheleanddisplay(onstandardoutput)a messagethecontainsthe nameofthestudentandthestudent'saveragegradeonthethr eeexams.Theaverageis obtainedbyaddinguptheindividualexamgradesandthendiv idingbythenumberof exams.

PAGE 73

Quiz 59 QuizonChapter2 (answers) 1. Brieryexplainwhatismeantbythe syntax andthe semantics ofaprogramminglanguage. Giveanexampletoillustratethedierencebetweenasyntax errorandasemanticserror. 2. Whatdoesthecomputerdowhenitexecutesavariabledeclara tionstatement.Givean example. 3. Whatisa type, asthistermrelatestoprogramming? 4. OneoftheprimitivetypesinJavais boolean. Whatisthe boolean type?Whereare booleanvaluesused?Whatareitspossiblevalues? 5. GivethemeaningofeachofthefollowingJavaoperators: a)++b)&&c)!= 6. Explainwhatismeantbyan assignmentstatement, andgiveanexample.Whatare assignmentstatementsusedfor? 7. Whatismeantby precedence ofoperators? 8. Whatisa literal ? 9. InJava,classeshavetwofundamentallydierentpurposes. Whatarethey? 10. Whatisthedierencebetweenthestatement\ x=TextIO.getDouble(); "andthestatement\ x=TextIO.getlnDouble(); 11. Explainwhythevalueoftheexpression 2+3+"test" isthestring "5test" whilethe valueoftheexpression "test"+2+3 isthestring "test23" .Whatisthevalueof "test"+2*3 ? 12. IntegratedDevelopmentEnvironmentssuchasEclipseoften use syntaxcoloring ,which assignsvariouscolorstothecharactersinaprogramtorere ctthesyntaxofthelanguage. AstudentnoticesthatEclipsecolorstheword String dierentlyfrom int double ,and boolean .Thestudentaskswhy String shouldbeadierentcolor,sinceallthesewords arenamesoftypes.What'stheanswertothestudent'squesti on?

PAGE 74

Chapter3ProgrammingintheSmallII:ControlT hebasicbuildingblocks ofprograms|variables,expressions,assignmentstatemen ts,and subroutinecallstatements|werecoveredinthepreviousch apter.Startingwiththischapter, welookathowthesebuildingblockscanbeputtogethertobui ldcomplexprogramswithmore interestingbehavior. Sincewearestillworkingonthelevelof\programminginthe small"inthischapter,weare interestedinthekindofcomplexitythatcanoccurwithinas inglesubroutine.Onthislevel, complexityisprovidedby controlstructures .Thetwotypesofcontrolstructures,loopsand branches,canbeusedtorepeatasequenceofstatementsover andoverortochooseamongtwo ormorepossiblecoursesofaction.Javaincludesseveralco ntrolstructuresofeachtype,and wewilllookateachoftheminsomedetail. Thischapterwillalsobeginthestudyofprogramdesign.Giv enaproblem,howcanyou comeupwithaprogramtosolvethatproblem?We'lllookatapa rtialanswertothisquestion in Section3.2 3.1Blocks,Loops,andBranchesT heabilityofacomputertoperform complextasksisbuiltonjustafewwaysof (online) combiningsimplecommandsintocontrolstructures.InJava ,therearejustsixsuchstructures thatareusedtodeterminethenormalrowofcontrolinaprogr am|and,infact,justthree ofthemwouldbeenoughtowriteprogramstoperformanytask. Thesixcontrolstructures are:the block ,the whileloop ,the do..whileloop ,the forloop ,the ifstatement ,andthe switchstatement .Eachofthesestructuresisconsideredtobeasingle\state ment,"buteach isinfacta structured statementthatcancontainoneormoreotherstatementsinsi deitself. 3.1.1BlocksThe block isthesimplesttypeofstructuredstatement.Itspurposeis simplytogroupa sequenceofstatementsintoasinglestatement.Theformato fablockis: { h statements i } 60

PAGE 75

CHAPTER3.CONTROL 61 Thatis,itconsistsofasequenceofstatementsenclosedbet weenapairofbraces,\ { "and\ } ". (Infact,itispossibleforablocktocontainnostatementsa tall;suchablockiscalledan emptyblock ,andcanactuallybeusefulattimes.Anemptyblockconsists ofnothingbut anemptypairofbraces.)Blockstatementsusuallyoccurins ideotherstatements,wheretheir purposeistogrouptogetherseveralstatementsintoaunit. However,ablockcanbelegally usedwhereverastatementcanoccur.Thereisoneplacewhere ablockisrequired:Asyou mighthavealreadynoticedinthecaseofthe main subroutineofaprogram,thedenitionofa subroutineisablock,sinceitisasequenceofstatementsen closedinsideapairofbraces. IshouldprobablynoteagainatthispointthatJavaiswhatis calledafree-formatlanguage. Therearenosyntaxrulesabouthowthelanguagehastobearra ngedonapage.So,forexample, youcouldwriteanentireblockononelineifyouwant.Butasa matterofgoodprogramming style,youshouldlayoutyourprogramonthepageinawaythat willmakeitsstructureas clearaspossible.Ingeneral,thismeansputtingonestatem entperlineandusingindentation toindicatestatementsthatarecontainedinsidecontrolst ructures.ThisistheformatthatI willgenerallyuseinmyexamples. Herearetwoexamplesofblocks: { System.out.print("Theansweris");System.out.println(ans); }{//Thisblockexchangesthevaluesofxandy inttemp;//Atemporaryvariableforuseinthisblock.temp=x;//Saveacopyofthevalueofxintemp.x=y;//Copythevalueofyintox.y=temp;//Copythevalueoftempintoy. } Inthesecondexample,avariable, temp ,isdeclaredinsidetheblock.Thisisperfectlylegal, anditisgoodstyletodeclareavariableinsideablockiftha tvariableisusednowhereelse butinsidetheblock.Avariabledeclaredinsideablockisco mpletelyinaccessibleandinvisible fromoutsidethatblock.Whenthecomputerexecutesthevari abledeclarationstatement,it allocatesmemorytoholdthevalueofthevariable.Whentheb lockends,thatmemoryis discarded(thatis,madeavailableforreuse).Thevariable issaidtobe local totheblock. Thereisageneralconceptcalledthe\scope"ofanidentier .The scope ofanidentieristhe partoftheprograminwhichthatidentierisvalid.Thescop eofavariabledenedinsidea blockislimitedtothatblock,andmorespecicallytothepa rtoftheblockthatcomesafter thedeclarationofthevariable.3.1.2TheBasicWhileLoopTheblockstatementbyitselfreallydoesn'taecttherowof controlinaprogram.Theve remainingcontrolstructuresdo.Theycanbedividedintotw oclasses:loopstatementsand branchingstatements.Youreallyjustneedonecontrolstru cturefromeachcategoryinorderto haveacompletelygeneral-purposeprogramminglanguage.M orethanthatisjustconvenience. Inthissection,I'llintroducethe while loopandthe if statement.I'llgivethefulldetailsof thesestatementsandoftheotherthreecontrolstructuresi nlatersections. A whileloop isusedtorepeatagivenstatementoverandover.Ofcourse,i t'snotlikely thatyouwouldwanttokeeprepeatingitforever.Thatwouldb ean inniteloop ,whichis

PAGE 76

CHAPTER3.CONTROL 62 generallyabadthing.(Thereisanoldstoryaboutcomputerp ioneerGraceMurrayHopper, whoreadinstructionsonabottleofshampootellingherto\l ather,rinse,repeat."Asthestory goes,sheclaimsthatshetriedtofollowthedirections,but sheranoutofshampoo.(Incase youdon'tgetit,thisisajokeaboutthewaythatcomputersmi ndlesslyfollowinstructions.)) Tobemorespecic,a while loopwillrepeatastatementoverandover,butonlysolong asaspeciedconditionremainstrue.A while loophastheform: while( h boolean-expression i ) h statement i Sincethestatementcanbe,andusuallyis,ablock,many while loopshavetheform: while( h boolean-expression i ){ h statements i } Thesemanticsofthisstatementgolikethis:Whenthecomput ercomestoa while statement,itevaluatesthe h boolean-expression i ,whichyieldseither true or false asthevalue.If thevalueis false ,thecomputerskipsovertherestofthe while loopandproceedstothenext commandintheprogram.Ifthevalueoftheexpressionis true ,thecomputerexecutesthe h statement i orblockof h statements i insidetheloop.Thenitreturnstothebeginningofthe while loopandrepeatstheprocess.Thatis,itre-evaluatesthe h boolean-expression i ,endsthe loopifthevalueis false ,andcontinuesitifthevalueis true .Thiswillcontinueoverandover untilthevalueoftheexpressionis false ;ifthatneverhappens,thentherewillbeaninnite loop. Hereisanexampleofa while loopthatsimplyprintsoutthenumbers1,2,3,4,5: intnumber;//Thenumbertobeprinted.number=1;//Startwith1.while(number<6){//Keepgoingaslongasnumberis<6. System.out.println(number);number=number+1;//Goontothenextnumber. }System.out.println("Done!"); Thevariable number isinitializedwiththevalue1.Sothersttimethroughthe while loop, whenthecomputerevaluatestheexpression\ number<6 ",itisaskingwhether1islessthan6, whichis true .Thecomputerthereforproceedstoexecutethetwostatemen tsinsidetheloop. Therststatementprintsout\1".Thesecondstatementadds 1to number andstoresthe resultbackintothevariable number ;thevalueof number hasbeenchangedto2.Thecomputer hasreachedtheendoftheloop,soitreturnstothebeginning andasksagainwhether number is lessthan6.Onceagainthisistrue,sothecomputerexecutes theloopagain,thistimeprinting out2asthevalueof number andthenchangingthevalueof number to3.Itcontinuesinthis wayuntileventually number becomesequalto6.Atthatpoint,theexpression\ number<6 evaluatesto false .So,thecomputerjumpspasttheendofthelooptothenextsta tement andprintsoutthemessage\Done!".Notethatwhentheloopen ds,thevalueof number is6, butthelastvaluethatwasprintedwas5. Bytheway,youshouldrememberthatyou'llneverseea while loopstandingbyitself inarealprogram.Itwillalwaysbeinsideasubroutinewhich isitselfdenedinsidesome class.Asanexampleofa while loopusedinsideacompleteprogram,hereisalittleprogram thatcomputestheinterestonaninvestmentoverseveralyea rs.Thisisanimprovementover examplesfromthepreviouschapterthatjustreportedthere sultsforoneyear:

PAGE 77

CHAPTER3.CONTROL 63 publicclassInterest3{ /* Thisclassimplementsasimpleprogramthatwillcomputetheamountofinterestthatisearnedonaninvestmentoveraperiodof5years.Theinitialamountoftheinvestmentandtheinterestrateareinputbytheuser.Thevalueoftheinvestmentattheendofeachyearisoutput. */publicstaticvoidmain(String[]args){ doubleprincipal;//Thevalueoftheinvestment.doublerate;//Theannualinterestrate./*Gettheinitialinvestmentandinterestratefromtheuser .*/ TextIO.put("Entertheinitialinvestment:");principal=TextIO.getlnDouble();TextIO.put("Entertheannualinterestrate:");rate=TextIO.getlnDouble();/*Simulatetheinvestmentfor5years.*/intyears;//Countsthenumberofyearsthathavepassed.years=0;while(years<5){ doubleinterest;//Interestforthisyear.interest=principal*rate;principal=principal+interest;//Addittoprincipal.years=years+1;//Countthecurrentyear.System.out.print("Thevalueoftheinvestmentafter");System.out.print(years);System.out.print("yearsis$");System.out.printf("%1.2f",principal);System.out.println(); }//endofwhileloop }//endofmain() }//endofclassInterest3 Youshouldstudythisprogram,andmakesurethatyouunderst andwhatthecomputerdoes step-by-stepasitexecutesthe while loop. 3.1.3TheBasicIfStatementAn ifstatement tellsthecomputertotakeoneoftwoalternativecoursesofa ction,depending onwhetherthevalueofagivenboolean-valuedexpressionis trueorfalse.Itisanexampleof a\branching"or\decision"statement.An if statementhastheform:

PAGE 78

CHAPTER3.CONTROL 64 if( h boolean-expression i ) h statement i else h statement i Whenthecomputerexecutesan if statement,itevaluatesthebooleanexpression.Ifthevalu e is true ,thecomputerexecutestherststatementandskipsthestat ementthatfollowsthe \ else ".Ifthevalueoftheexpressionis false ,thenthecomputerskipstherststatementand executesthesecondone.Notethatinanycase,oneandonlyon eofthetwostatementsinside the if statementisexecuted.Thetwostatementsrepresentaltern ativecoursesofaction;the computerdecidesbetweenthesecoursesofactionbasedonth evalueofthebooleanexpression. Inmanycases,youwantthecomputertochoosebetweendoings omethingandnotdoing it.Youcandothiswithan if statementthatomitsthe else part: if( h boolean-expression i ) h statement i Toexecutethisstatement,thecomputerevaluatestheexpre ssion.Ifthevalueis true ,the computerexecutesthe h statement i thatiscontainedinsidethe if statement;ifthevalueis false ,thecomputerskipsthat h statement i Ofcourse,eitherorbothofthe h statement i 'sinan if statementcanbeablock,sothatan if statementoftenlookslike: if( h boolean-expression i ){ h statements i }else{ h statements i } or: if( h boolean-expression i ){ h statements i } Asanexample,hereisan if statementthatexchangesthevalueoftwovariables, x and y butonlyif x isgreaterthan y tobeginwith.Afterthis if statementhasbeenexecuted,we canbesurethatthevalueof x isdenitelylessthanorequaltothevalueof y : if(x>y){ inttemp;//Atemporaryvariableforuseinthisblock.temp=x;//Saveacopyofthevalueofxintemp.x=y;//Copythevalueofyintox.y=temp;//Copythevalueoftempintoy. } Finally,hereisanexampleofan if statementthatincludesan else part.Seeifyoucan gureoutwhatitdoes,andwhyitwouldbeused: if(years>1){//handlecasefor2ormoreyears System.out.print("Thevalueoftheinvestmentafter");System.out.print(years);System.out.print("yearsis$"); }else{//handlecasefor1year

PAGE 79

CHAPTER3.CONTROL 65 System.out.print("Thevalueoftheinvestmentafter1year is$"); }//endofifstatementSystem.out.printf("%1.2f",principal);//thisisdonein anycase I'llhavemoretosayaboutcontrolstructureslaterinthisc hapter.Butyoualreadyknow theessentials.Ifyouneverlearnedanythingmoreaboutcon trolstructures,youwouldalready knowenoughtoperformanypossiblecomputingtask.Simplel oopingandbranchingareall youreallyneed!3.2AlgorithmDevelopmentP rogrammingisdifficult (likemanyactivitiesthatareusefulandworthwhile|andli ke (online) mostofthoseactivities,itcanalsoberewardingandalotof fun).Whenyouwriteaprogram, youhavetotellthecomputereverysmalldetailofwhattodo. Andyouhavetogeteverything exactlyright,sincethecomputerwillblindlyfollowyourp rogramexactlyaswritten.How, then,dopeoplewriteanybutthemostsimpleprograms?It'sn otabigmystery,actually.It's amatteroflearningtothinkintherightway. Aprogramisanexpressionofanidea.Aprogrammerstartswit hageneralideaofatask forthecomputertoperform.Presumably,theprogrammerhas someideaofhowtoperform thetaskbyhand,atleastingeneraloutline.Theproblemist oreshoutthatoutlineintoa complete,unambiguous,step-by-stepprocedureforcarryi ngoutthetask.Suchaprocedureis calledan\algorithm."(Technically,an algorithm isanunambiguous,step-by-stepprocedure thatterminatesafteranitenumberofsteps;wedon'twantt ocountproceduresthatgoon forever.)Analgorithmisnotthesameasaprogram.Aprogram iswritteninsomeparticular programminglanguage.Analgorithmismorelikethe idea behindtheprogram,butit'sthe ideaofthe steps theprogramwilltaketoperformitstask,notjusttheideaof the task itself. Thestepsofthealgorithmdon'thavetobelledinincomplet edetail,aslongasthestepsare unambiguousandit'sclearthatcarryingoutthestepswilla ccomplishtheassignedtask.An algorithmcanbeexpressedinanylanguage,includingEngli sh.Ofcourse,analgorithmcan onlybeexpressedasaprogramifallthedetailshavebeenll edin. So,wheredoalgorithmscomefrom?Usually,theyhavetobede veloped,oftenwithalotof thoughtandhardwork.Skillatalgorithmdevelopmentissom ethingthatcomeswithpractice, buttherearetechniquesandguidelinesthatcanhelp.I'llt alkhereaboutsometechniquesand guidelinesthatarerelevantto\programminginthesmall," andIwillreturntothesubject severaltimesinlaterchapters.3.2.1PseudocodeandStepwiseRenementWhenprogramminginthesmall,youhaveafewbasicstoworkwi th:variables,assignment statements,andinput/outputroutines.Youmightalsohave somesubroutines,objects,or otherbuildingblocksthathavealreadybeenwrittenbyyouo rsomeoneelse.(Input/output routinesfallintothisclass.)Youcanbuildsequencesofth esebasicinstructions,andyoucan alsocombinethemintomorecomplexcontrolstructuressuch as while loopsand if statements. Supposeyouhaveataskinmindthatyouwantthecomputertope rform.Onewayto proceedistowriteadescriptionofthetask,andtakethatde scriptionasanoutlineofthe algorithmyouwanttodevelop.Thenyoucanreneandelabora tethatdescription,gradually addingstepsanddetail,untilyouhaveacompletealgorithm thatcanbetranslateddirectly intoprogramminglanguage.Thismethodiscalled stepwiserenement ,anditisatypeof

PAGE 80

CHAPTER3.CONTROL 66 top-downdesign.Asyouproceedthroughthestagesofstepwi serenement,youcanwriteout descriptionsofyouralgorithmin pseudocode |informalinstructionsthatimitatethestructure ofprogramminglanguageswithoutthecompletedetailandpe rfectsyntaxofactualprogram code. Asanexample,let'sseehowonemightdeveloptheprogramfro mtheprevioussection,which computesthevalueofaninvestmentoverveyears.Thetaskt hatyouwanttheprogramto performis:\Computeanddisplaythevalueofaninvestmentf oreachofthenextveyears, wheretheinitialinvestmentandinterestratearetobespec iedbytheuser."Youmightthen write|oratleastthink|thatthiscanbeexpandedas: Gettheuser'sinputComputethevalueoftheinvestmentafter1yearDisplaythevalueComputethevalueafter2yearsDisplaythevalueComputethevalueafter3yearsDisplaythevalueComputethevalueafter4yearsDisplaythevalueComputethevalueafter5yearsDisplaythevalue Thisiscorrect,butratherrepetitive.Andseeingthatrepe tition,youmightnoticean opportunitytousealoop.Aloopwouldtakelesstyping.More important,itwouldbemore general :Essentiallythesameloopwillworknomatterhowmanyyears youwanttoprocess. So,youmightrewritetheabovesequenceofstepsas: Gettheuser'sinputwhiletherearemoreyearstoprocess: ComputethevalueafterthenextyearDisplaythevalue Followingthisalgorithmwouldcertainlysolvetheproblem ,butforacomputer,we'llhave tobemoreexplicitabouthowto\Gettheuser'sinput,"howto \Computethevalueafterthe nextyear,"andwhatitmeanstosay\therearemoreyearstopr ocess."Wecanexpandthe step,\Gettheuser'sinput"into AsktheuserfortheinitialinvestmentReadtheuser'sresponseAsktheuserfortheinterestrateReadtheuser'sresponse Tollinthedetailsofthestep\Computethevalueafterthen extyear,"youhaveto knowhowtodothecomputationyourself.(Maybeyouneedtoas kyourbossorprofessorfor clarication?)Let'ssayyouknowthatthevalueiscomputed byaddingsomeinteresttothe previousvalue.Thenwecanrenethe while loopto: whiletherearemoreyearstoprocess: ComputetheinterestAddtheinteresttothevalueDisplaythevalue Asfortestingwhethertherearemoreyearstoprocess,theon lywaythatwecandothatis bycountingtheyearsourselves.Thisdisplaysaverycommon pattern,andyoushouldexpect tousesomethingsimilarinalotofprograms:Wehavetostart withzeroyears,addoneeach

PAGE 81

CHAPTER3.CONTROL 67 timeweprocessayear,andstopwhenwereachthedesirednumb erofyears.Sothe while loopbecomes: years=0whileyears<5: years=years+1ComputetheinterestAddtheinteresttothevalueDisplaythevalue Westillhavetoknowhowtocomputetheinterest.Let'ssayth attheinterestistobe computedbymultiplyingtheinterestratebythecurrentval ueoftheinvestment.Putting thistogetherwiththepartofthealgorithmthatgetstheuse r'sinputs,wehavethecomplete algorithm: AsktheuserfortheinitialinvestmentReadtheuser'sresponseAsktheuserfortheinterestrateReadtheuser'sresponseyears=0whileyears<5: years=years+1Computeinterest=value*interestrateAddtheinteresttothevalueDisplaythevalue Finally,weareatthepointwherewecantranslateprettydir ectlyintoproperprogramminglanguagesyntax.Westillhavetochoosenamesforthevariab les,decideexactlywhatwewant tosaytotheuser,andsoforth.Havingdonethis,wecouldexp ressouralgorithminJavaas: doubleprincipal,rate,interest;//declarethevariablesintyears;System.out.print("Typeinitialinvestment:");principal=TextIO.getlnDouble();System.out.print("Typeinterestrate:");rate=TextIO.getlnDouble();years=0;while(years<5){ years=years+1;interest=principal*rate;principal=principal+interest;System.out.println(principal); } Thisstillneedstobewrappedinsideacompleteprogram,its tillneedstobecommented, anditreallyneedstoprintoutmoreinformationinanicerfo rmatfortheuser.Butit's essentiallythesameprogramastheoneintheprevioussecti on.(Notethatthepseudocode algorithmusesindentationtoshowwhichstatementsareins idetheloop.InJava,indentation iscompletelyignoredbythecomputer,soyouneedapairofbr acestotellthecomputerwhich statementsareintheloop.Ifyouleaveoutthebraces,theon lystatementinsidetheloopwould be\ years=years+1;" .Theotherstatementswouldonlybeexecutedonce,afterthe loop ends.Thenastythingisthatthecomputerwon'tnoticethise rrorforyou,likeitwouldifyou leftouttheparenthesesaround\ (years<5) ".Theparenthesesarerequiredbythesyntaxof

PAGE 82

CHAPTER3.CONTROL 68 the while statement.Thebracesareonlyrequiredsemantically.Thec omputercanrecognize syntaxerrorsbutnotsemanticerrors.) Onethingyoushouldhavenoticedhereisthatmyoriginalspe cicationoftheproblem| \Computeanddisplaythevalueofaninvestmentforeachofth enextveyears"|wasfarfrom beingcomplete.Beforeyoustartwritingaprogram,youshou ldmakesureyouhaveacomplete specicationofexactlywhattheprogramissupposedtodo.I nparticular,youneedtoknow whatinformationtheprogramisgoingtoinputandoutputand whatcomputationitisgoing toperform.Hereiswhatareasonablycompletespecication oftheproblemmightlooklikein thisexample: \Writeaprogramthatwillcomputeanddisplaythevalueof aninvestmentforeachofthenextveyears.Eachyear,inter est isaddedtothevalue.Theinterestiscomputedbymultiplyin g thecurrentvaluebyaxedinterestrate.Assumethattheini tial valueandtherateofinterestaretobeinputbytheuserwhent he programisrun." 3.2.2The3N+1ProblemLet'sdoanotherexample,workingthistimewithaprogramth atyouhaven'talreadyseen.The assignmenthereisanabstractmathematicalproblemthatis oneofmyfavoriteprogramming exercises.Thistime,we'llstartwithamorecompletespeci cationofthetasktobeperformed: \Givenapositiveinteger,N,denethe'3N+1'sequencestar tingfromNasfollows:IfNisanevennumber,thendivideNbytwo;butifNisodd,thenmultiplyNby3andadd1.ContinuetogeneratenumbersinthiswayuntilNbecomesequalto1.Forexample,startingfromN=3,whichisodd,wemultiplyby3andadd1,givingN=3*3+1=10.Then,sinceNiseven,wedivideby2,givingN=10/2=5.Wecontinueinthisway,stoppingwhenwereach1,givingthecompletesequence:3,10,5,16,8, 4, 2,1. \Writeaprogramthatwillreadapositiveintegerfromthe userandwillprintoutthe3N+1sequencestartingfromthatinteger.Theprogramshouldalsocountandprintoutthenumb er oftermsinthesequence." Ageneraloutlineofthealgorithmfortheprogramwewantis: GetapositiveintegerNfromtheuser;Compute,print,andcounteachnumberinthesequence;Outputthenumberofterms; Thebulkoftheprogramisinthesecondstep.We'llneedaloop ,sincewewanttokeep computingnumbersuntilweget1.Toputthisintermsappropr iatefora while loop,wewant to continue aslongasthenumberis not 1.So,wecanexpandourpseudocodealgorithmto: GetapositiveintegerNfromtheuser;whileNisnot1: ComputeN=nextterm;OutputN;Countthisterm; Outputthenumberofterms;

PAGE 83

CHAPTER3.CONTROL 69 Inordertocomputethenextterm,thecomputermusttakedie rentactionsdependingon whetherNisevenorodd.Weneedan if statementtodecidebetweenthetwocases: GetapositiveintegerNfromtheuser;whileNisnot1: ifNiseven: ComputeN=N/2; else ComputeN=3*N+1; OutputN;Countthisterm; Outputthenumberofterms; Wearealmostthere.Theoneproblemthatremainsiscounting .Countingmeansthatyou startwithzero,andeverytimeyouhavesomethingtocount,y ouaddone.Weneedavariable todothecounting.(Again,thisisacommonpatternthatyous houldexpecttoseeoverand over.)Withthecounteradded,weget: GetapositiveintegerNfromtheuser;Letcounter=0;whileNisnot1: ifNiseven: ComputeN=N/2; else ComputeN=3*N+1; OutputN;Add1tocounter; Outputthecounter; Westillhavetoworryabouttheveryrststep.Howcanwegeta positive integerfromthe user?Ifwejustreadinanumber,it'spossiblethattheuserm ighttypeinanegativenumber orzero.IfyoufollowwhathappenswhenthevalueofNisnegat iveorzero,you'llseethatthe programwillgoonforever,sincethevalueofNwillneverbec omeequalto1.Thisisbad.In thiscase,theproblemisprobablynobigdeal,butingeneral youshouldtrytowriteprograms thatarefoolproof.Onewaytoxthisistokeepreadinginnum bersuntiltheusertypesina positivenumber: Askusertoinputapositivenumber;LetNbetheuser'sresponse;whileNisnotpositive: Printanerrormessage;ReadanothervalueforN; Letcounter=0;whileNisnot1: ifNiseven: ComputeN=N/2; else ComputeN=3*N+1; OutputN;Add1tocounter; Outputthecounter; Therst while loopwillendonlywhenNisapositivenumber,asrequired.(A common beginningprogrammer'serroristousean if statementinsteadofa while statementhere: \IfNisnotpositive,asktheusertoinputanothervalue."Th eproblemarisesifthesecond

PAGE 84

CHAPTER3.CONTROL 70 numberinputbytheuserisalsonon-positive.The if statementisonlyexecutedonce,sothe secondinputnumberisnevertested.Withthe while loop,afterthesecondnumberisinput, thecomputerjumpsbacktothebeginningoftheloopandtests whetherthesecondnumber ispositive.Ifnot,itaskstheuserforathirdnumber,andit willcontinueaskingfornumbers untiltheuserentersanacceptableinput.) HereisaJavaprogramimplementingthisalgorithm.Itusest heoperators <= tomean\is lessthanorequalto"and != tomean\isnotequalto."TotestwhetherNiseven,ituses \ N%2==0 ".Alltheoperatorsusedherewerediscussedin Section2.5 /** *Thisprogramprintsouta3N+1sequencestartingfromaposi tive *integerspecifiedbytheuser.Italsocountsthenumberof*termsinthesequence,andprintsoutthatnumber.*/publicclassThreeN1{ publicstaticvoidmain(String[]args){ intN;//forcomputingtermsinthesequenceintcounter;//forcountingthetermsTextIO.put("Startingpointforsequence:");N=TextIO.getlnInt();while(N<=0){ TextIO.put("Thestartingpointmustbepositive.Pleasetr yagain:"); N=TextIO.getlnInt(); }//Atthispoint,weknowthatN>0counter=0;while(N!=1){ if(N%2==0) N=N/2; else N=3*N+1; TextIO.putln(N);counter=counter+1; }TextIO.putln();TextIO.put("Therewere");TextIO.put(counter);TextIO.putln("termsinthesequence."); }//endofmain() }//endofclassThreeN1 Twonalnotesonthisprogram:First,youmighthavenoticed thatthersttermofthe sequence|thevalueofNinputbytheuser|isnotprintedorco untedbythisprogram.Is thisanerror?It'shardtosay.Wasthespecicationofthepr ogramcarefulenoughtodecide? Thisisthetypeofthingthatmightsendyoubacktotheboss/p rofessorforclarication.The problem(ifitisone!)canbexedeasilyenough.Justreplac etheline\counter=0"before thewhileloopwiththetwolines:

PAGE 85

CHAPTER3.CONTROL 71 TextIO.putln(N);//printoutinitialtermcounter=1;//andcountit Second,thereisthequestionofwhythisproblemisatallint eresting.Well,it'sinteresting tomathematiciansandcomputerscientistsbecauseofasimp lequestionabouttheproblemthat theyhaven'tbeenabletoanswer:Willtheprocessofcomputi ngthe3N+1sequencenishafter anitenumberofstepsforallpossiblestartingvaluesofN? Althoughindividualsequencesare easytocompute,noonehasbeenabletoanswerthegeneralque stion.Toputthisanother way,nooneknowswhethertheprocessofcomputing3N+1seque ncescanproperlybecalled analgorithm,sinceanalgorithmisrequiredtoterminateaf teranitenumberofsteps!(This discussionassumesthatthevalueof N cantakeonarbitrarilylargeintegervalues,whichisnot trueforavariableoftype int inaJavaprogram.) 3.2.3Coding,Testing,DebuggingItwouldbeniceif,havingdevelopedanalgorithmforyourpr ogram,youcouldrelax,pressa button,andgetaperfectlyworkingprogram.Unfortunately ,theprocessofturninganalgorithm intoJavasourcecodedoesn'talwaysgosmoothly.Andwhenyo udogettothestageofaworking program,it'softenonlyworkinginthesensethatitdoes something .Unfortunatelynotwhat youwantittodo. Afterprogramdesigncomescoding:translatingthedesigni ntoaprogramwritteninJava orsomeotherlanguage.Usually,nomatterhowcarefulyouar e,afewsyntaxerrorswillcreep infromsomewhere,andtheJavacompilerwillrejectyourpro gramwithsomekindoferror message.Unfortunately,whileacompilerwillalwaysdetec tsyntaxerrors,it'snotverygood abouttellingyouexactlywhat'swrong.Sometimes,it'snot evengoodabouttellingyouwhere therealerroris.Aspellingerrorormissing\ { "online45mightcausethecompilertochoke online105.Youcanavoidlotsoferrorsbymakingsurethatyo ureallyunderstandthesyntax rulesofthelanguageandbyfollowingsomebasicprogrammin gguidelines.Forexample,I nevertypea\ { "withouttypingthematching\ } ".ThenIgobackandllinthestatements betweenthebraces.Amissingorextrabracecanbeoneoftheh ardesterrorstondinalarge program.Always,alwaysindentyourprogramnicely.Ifyouc hangetheprogram,changethe indentationtomatch.It'sworththetrouble.Useaconsiste ntnamingscheme,soyoudon't havetostruggletorememberwhetheryoucalledthatvariabl e interestrate or interestRate Ingeneral,whenthecompilergivesmultipleerrormessages ,don'ttrytoxtheseconderror messagefromthecompileruntilyou'vexedtherstone.Onc ethecompilerhitsanerrorin yourprogram,itcangetconfused,andtherestoftheerrorme ssagesmightjustbeguesses. Maybethebestadviceis:Takethetimetounderstandtheerro rbeforeyoutrytoxit. Programmingisnotanexperimentalscience. Whenyourprogramcompileswithouterror,youarestillnotd one.Youhavetotestthe programtomakesureitworkscorrectly.Rememberthatthego alisnottogettherightoutput forthetwosampleinputsthattheprofessorgaveinclass.Th egoalisaprogramthatwill workcorrectlyforallreasonableinputs.Ideally,whenfac edwithanunreasonableinput,it willrespondbygentlychidingtheuserratherthanbycrashi ng.Testyourprogramonawide varietyofinputs.Trytondasetofinputsthatwilltestthe fullrangeoffunctionalitythat you'vecodedintoyourprogram.Asyoubeginwritinglargerp rograms,writetheminstages andtesteachstagealongtheway.Youmightevenhavetowrite someextracodetodothe testing|forexampletocallasubroutinethatyou'vejustwr itten.Youdon'twanttobefaced, ifyoucanavoidit,with500newlywrittenlinesofcodethath aveanerrorinthere somewhere.

PAGE 86

CHAPTER3.CONTROL 72 Thepointoftestingistond bugs |semanticerrorsthatshowupasincorrectbehavior ratherthanascompilationerrors.Andthesadfactisthatyo uwillprobablyndthem.Again, youcanminimizebugsbycarefuldesignandcarefulcoding,b utnoonehasfoundawayto avoidthemaltogether.Onceyou'vedetectedabug,it'stime for debugging .Youhaveto trackdownthecauseofthebugintheprogram'ssourcecodean deliminateit.Debuggingisa skillthat,likeotheraspectsofprogramming,requirespra cticetomaster.Sodon'tbeafraidof bugs.Learnfromthem.Oneessentialdebuggingskillisthea bilitytoreadsourcecode|the abilitytoputasidepreconceptionsaboutwhatyou think itdoesandtofollowitthewaythe computerdoes|mechanically,step-by-step|toseewhatitr eallydoes.Thisishard.Icanstill rememberthetimeIspenthourslookingforabugonlytondth atalineofcodethatIhad lookedattentimeshada\1"whereitshouldhavehadan\i",or thetimewhenIwrotea subroutinenamed WindowClosing whichwouldhavedoneexactlywhatIwantedexceptthat thecomputerwaslookingfor windowClosing (withalowercase\w").Sometimesitcanhelp tohavesomeonewhodoesn'tshareyourpreconceptionslooka tyourcode. Often,it'saproblemjusttondthepartoftheprogramthatc ontainstheerror.Most programmingenvironmentscomewitha debugger ,whichisaprogramthatcanhelpyound bugs.Typically,yourprogramcanberununderthecontrolof thedebugger.Thedebugger allowsyoutoset\breakpoints"inyourprogram.Abreakpoin tisapointintheprogramwhere thedebuggerwillpausetheprogramsoyoucanlookatthevalu esoftheprogram'svariables. Theideaistotrackdownexactlywhenthingsstarttogowrong duringtheprogram'sexecution. Thedebuggerwillalsoletyouexecuteyourprogramonelinea tatime,sothatyoucanwatch whathappensindetailonceyouknowthegeneralareainthepr ogramwherethebugislurking. IwillconfessthatIonlyrarelyusedebuggersmyself.Amore traditionalapproachto debuggingistoinsert debuggingstatements intoyourprogram.Theseareoutputstatements thatprintoutinformationaboutthestateoftheprogram.Ty pically,adebuggingstatement wouldsaysomethinglike System.out.println("Atstartofwhileloop,N="+N); Youneedtobeabletotellfromtheoutputwhereinyourprogra mtheoutputiscomingfrom, andyouwanttoknowthevalueofimportantvariables.Someti mes,youwillndthatthe computerisn'tevengettingtoapartoftheprogramthatyout hinkitshouldbeexecuting. Rememberthatthegoalistondtherstpointintheprogramw herethestateisnotwhat youexpectittobe.That'swherethebugis. Andnally,rememberthegoldenruleofdebugging:Ifyouare absolutelysurethateverythinginyourprogramisright,andifitstilldoesn'twork,t henoneofthethingsthatyouare absolutelysureofiswrong.3.3Thewhileanddo..whileStatementsS tatementsinJavacan beeithersimplestatementsorcompoundstatements.Simple (online) statements,suchasassignmentstatementsandsubroutinec allstatements,arethebasicbuilding blocksofaprogram.Compoundstatements,suchas while loopsand if statements,areusedto organizesimplestatementsintocomplexstructures,which arecalledcontrolstructuresbecause theycontroltheorderinwhichthestatementsareexecuted. Thenextvesectionsexplore thedetailsofcontrolstructuresthatareavailableinJava ,startingwiththe while statement andthe do..while statementinthissection.Atthesametime,we'lllookatexa mplesof programmingwitheachcontrolstructureandapplythetechn iquesfordesigningalgorithms

PAGE 87

CHAPTER3.CONTROL 73 thatwereintroducedintheprevioussection.3.3.1ThewhileStatementThe while statementwasalreadyintroducedin Section3.1 .A while loophastheform while( h boolean-expression i ) h statement i The h statement i can,ofcourse,beablockstatementconsistingofseveralst atementsgrouped togetherbetweenapairofbraces.Thisstatementiscalledt he bodyoftheloop .Thebody oftheloopisrepeatedaslongasthe h boolean-expression i istrue.Thisbooleanexpressionis calledthe continuationcondition ,ormoresimplythe test ,oftheloop.Thereareafew pointsthatmightneedsomeclarication.Whathappensifth econditionisfalseintherst place,beforethebodyoftheloopisexecutedevenonce?Inth atcase,thebodyoftheloopis neverexecutedatall.Thebodyofawhileloopcanbeexecuted anynumberoftimes,including zero.Whathappensiftheconditionistrue,butitbecomesfa lsesomewhereinthe middle of theloopbody?Doestheloopendassoonasthishappens?Itdoe sn't,becausethecomputer continuesexecutingthebodyoftheloopuntilitgetstothee nd.Onlythendoesitjumpback tothebeginningoftheloopandtestthecondition,andonlyt hencantheloopend. Let'slookatatypicalproblemthatcanbesolvedusinga while loop:ndingtheaverage ofasetofpositiveintegersenteredbytheuser.Theaverage isthesumoftheintegers,divided bythenumberofintegers.Theprogramwillasktheusertoent eroneintegeratatime.It willkeepcountofthenumberofintegersentered,anditwill keeparunningtotalofallthe numbersithasreadsofar.Hereisapseudocodealgorithmfor theprogram: Letsum=0Letcount=0whiletherearemoreintegerstoprocess: ReadanintegerAddittothesumCountit DividesumbycounttogettheaveragePrintouttheaverage Buthowcanwetestwhethertherearemoreintegerstoprocess ?Atypicalsolutionisto telltheusertotypeinzeroafterallthedatahavebeenenter ed.Thiswillworkbecausewe areassumingthatallthedataarepositivenumbers,sozeroi snotalegaldatavalue.Thezero isnotitselfpartofthedatatobeaveraged.It'sjusttheret omarktheendoftherealdata. Adatavalueusedinthiswayissometimescalleda sentinelvalue .Sonowthetestinthe whileloopbecomes\whiletheinputintegerisnotzero".But thereisanotherproblem!The rsttimethetestisevaluated,beforethebodyoftheloopha severbeenexecuted,nointeger hasyetbeenread.Thereisno\inputinteger"yet,sotesting whethertheinputintegeriszero doesn'tmakesense.So,wehavetodosomething before thewhilelooptomakesurethatthe testmakessense.Settingthingsupsothatthetestina while loopmakessensethersttime itisexecutediscalled primingtheloop .Inthiscase,wecansimplyreadtherstinteger beforethebeginningoftheloop.Hereisarevisedalgorithm : Letsum=0Letcount=0Readanintegerwhiletheintegerisnotzero:

PAGE 88

CHAPTER3.CONTROL 74 AddtheintegertothesumCountitReadaninteger DividesumbycounttogettheaveragePrintouttheaverage NoticethatI'verearrangedthebodyoftheloop.Sinceanint egerisreadbeforetheloop,the loophastobeginbyprocessingthatinteger.Attheendofthe loop,thecomputerreadsanew integer.Thecomputerthenjumpsbacktothebeginningofthe loopandteststheintegerthat ithasjustread.Notethatwhenthecomputernallyreadsthe sentinelvalue,theloopends beforethesentinelvalueisprocessed.Itisnotaddedtothe sum,anditisnotcounted.This isthewayit'ssupposedtowork.Thesentinelisnotpartofth edata.Theoriginalalgorithm, evenifitcouldhavebeenmadetoworkwithoutpriming,wasin correctsinceitwouldhave summedandcountedalltheintegers,includingthesentinel .(Sincethesentineliszero,thesum wouldstillbecorrect,butthecountwouldbeobyone.Suchs o-called o-by-oneerrors areverycommon.Countingturnsouttobeharderthanitlooks !) Wecaneasilyturnthealgorithmintoacompleteprogram.Not ethattheprogramcannot usethestatement\ average=sum/count ;"tocomputetheaverage.Since sum and count arebothvariablesoftype int ,thevalueof sum/count isaninteger.Theaverageshouldbe arealnumber.We'veseenthisproblembefore:wehavetoconv ertoneofthe int valuesto a double toforcethecomputertocomputethequotientasarealnumber .Thiscanbedone bytype-castingoneofthevariablestotype double .Thetypecast\(double)sum"converts thevalueof sum toarealnumber,sointheprogramtheaverageiscomputedas\ average= ((double)sum)/count ;".Anothersolutioninthiscasewouldhavebeentodeclare sum to beavariableoftype double intherstplace. Oneotherissueisaddressedbytheprogram:Iftheuserenter szeroastherstinputvalue, therearenodatatoprocess.Wecantestforthiscasebycheck ingwhether count isstillequal tozeroafterthe while loop.Thismightseemlikeaminorpoint,butacarefulprogra mmer shouldcoverallthebases. Hereistheprogram: /* *Thisprogramreadsasequenceofpositiveintegersinput*bytheuser,anditwillprintouttheaverageofthose*integers.Theuserispromptedtoenteroneintegerata*time.Theusermustentera0tomarktheendofthe*data.(Thezeroisnotcountedaspartofthedatato*beaveraged.)Theprogramdoesnotcheckwhetherthe*user'sinputispositive,soitwillactuallyworkfor*bothpositiveandnegativeinputvalues.*/ publicclassComputeAverage{ publicstaticvoidmain(String[]args){ intinputNumber;//Oneoftheintegersinputbytheuser.intsum;//Thesumofthepositiveintegers.intcount;//Thenumberofpositiveintegers.doubleaverage;//Theaverageofthepositiveintegers./*Initializethesummationandcountingvariables.*/sum=0;

PAGE 89

CHAPTER3.CONTROL 75 count=0;/*Readandprocesstheuser'sinput.*/TextIO.put("Enteryourfirstpositiveinteger:");inputNumber=TextIO.getlnInt();while(inputNumber!=0){ sum+=inputNumber;//AddinputNumbertorunningsum.count++;//Counttheinputbyadding1tocount.TextIO.put("Enteryournextpositiveinteger,or0toend:" ); inputNumber=TextIO.getlnInt(); }/*Displaytheresult.*/if(count==0){ TextIO.putln("Youdidn'tenteranydata!"); }else{ average=((double)sum)/count;TextIO.putln();TextIO.putln("Youentered"+count+"positiveintegers." ); TextIO.putf("Theiraverageis%1.3f.\n",average); } }//endmain() }//endclassComputeAverage 3.3.2Thedo..whileStatementSometimesitismoreconvenienttotestthecontinuationcon ditionattheendofaloop,instead ofatthebeginning,asisdoneinthe while loop.The do..while statementisverysimilar tothe while statement,exceptthattheword\while,"alongwiththecond itionthatittests, hasbeenmovedtotheend.Theword\do"isaddedtomarkthebeg inningoftheloop.A do..while statementhastheform do h statement i while( h boolean-expression i ); or,since,asusual,the h statement i canbeablock, do{ h statements i }while( h boolean-expression i ); Notethesemicolon,';',attheveryend.Thissemicolonispa rtofthestatement,justas thesemicolonattheendofanassignmentstatementordeclar ationispartofthestatement. Omittingitisasyntaxerror.(Moregenerally, every statementinJavaendseitherwitha semicolonorarightbrace,' } '.) Toexecutea do loop,thecomputerrstexecutesthebodyoftheloop|thatis ,thestatement orstatementsinsidetheloop|andthenitevaluatesthebool eanexpression.Ifthevalueof theexpressionis true ,thecomputerreturnstothebeginningofthe do loopandrepeatsthe process;ifthevalueis false ,itendstheloopandcontinueswiththenextpartoftheprogr am.

PAGE 90

CHAPTER3.CONTROL 76 Sincetheconditionisnottesteduntiltheendoftheloop,th ebodyofa do loopisalways executedatleastonce. Forexample,considerthefollowingpseudocodeforagame-p layingprogram.The do loop makessensehereinsteadofa while loopbecausewiththe do loop,youknowtherewillbeat leastonegame.Also,thetestthatisusedattheendoftheloo pwouldn'tevenmakesenseat thebeginning: do{ PlayaGameAskuserifhewantstoplayanothergameReadtheuser'sresponse }while(theuser'sresponseisyes); Let'sconvertthisintoproperJavacode.SinceIdon'twantt otalkaboutgameplayingatthe moment,let'ssaythatwehaveaclassnamed Checkers ,andthatthe Checkers classcontains astaticmembersubroutinenamed playGame() thatplaysonegameofcheckersagainstthe user.Then,thepseudocode\Playagame"canbeexpressedast hesubroutinecallstatement \ Checkers.playGame(); ".Weneedavariabletostoretheuser'sresponse.The TextIO class makesitconvenienttousea boolean variabletostoretheanswertoayes/noquestion.The inputfunction TextIO.getlnBoolean() allowstheusertoenterthevalueas\yes"or\no". \Yes"isconsideredtobe true ,and\no"isconsideredtobe false .So,thealgorithmcanbe codedas booleanwantsToContinue;//Trueifuserwantstoplayagain do{ Checkers.playGame();TextIO.put("Doyouwanttoplayagain?");wantsToContinue=TextIO.getlnBoolean(); }while(wantsToContinue==true); Whenthevalueofthe boolean variableissetto false ,itisasignalthattheloopshouldend. Whena boolean variableisusedinthisway|asasignalthatissetinonepart oftheprogram andtestedinanotherpart|itissometimescalleda rag or ragvariable (inthesenseofa signalrag). Bytheway,amore-than-usually-pedanticprogrammerwould sneeratthetest \ while(wantsToContinue==true) ".Thistestisexactlyequivalentto\ while (wantsToContinue) ".Testingwhether\ wantsToContinue==true "istrueamountstothe samethingastestingwhether\ wantsToContinue "istrue.Alittlelessoensiveisanexpression oftheform\ flag==false ",where flag isabooleanvariable.Thevalueof\ flag==false isexactlythesameasthevalueof\ !flag ",where isthebooleannegationoperator.So youcanwrite\ while(!flag) "insteadof\ while(flag==false) ",andyoucanwrite \ if(!flag) "insteadof\ if(flag==false) ". Althougha do..while statementissometimesmoreconvenientthana while statement, havingtwokindsofloopsdoesnotmakethelanguagemorepowe rful.Anyproblemthatcanbe solvedusing do..while loopscanalsobesolvedusingonly while statements,andviceversa. Infact,if h doSomething i representsanyblockofprogramcode,then do{ h doSomething i }while( h boolean-expression i ); hasexactlythesameeectas

PAGE 91

CHAPTER3.CONTROL 77 h doSomething i while( h boolean-expression i ){ h doSomething i } Similarly, while( h boolean-expression i ){ h doSomething i } canbereplacedby if( h boolean-expression i ){ do{ h doSomething i }while( h boolean-expression i ); } withoutchangingthemeaningoftheprograminanyway.3.3.3breakandcontinueThesyntaxofthe while and do..while loopsallowsyoutotestthecontinuationconditionat eitherthebeginningofalooporattheend.Sometimes,itism orenaturaltohavethetest inthemiddleoftheloop,ortohaveseveraltestsatdierent placesinthesameloop.Java providesageneralmethodforbreakingoutofthemiddleofan yloop.It'scalledthe break statement,whichtakestheform break; Whenthecomputerexecutesa break statementinaloop,itwillimmediatelyjumpout oftheloop.Itthencontinuesontowhateverfollowstheloop intheprogram.Considerfor example: while(true){//lookslikeitwillrunforever! TextIO.put("Enterapositivenumber:");N=TextIO.getlnInt();if(N>0)//inputisOK;jumpoutofloop break; TextIO.putln("Youranswermustbe>0."); }//continuehereafterbreak Ifthenumberenteredbytheuserisgreaterthanzero,the break statementwillbeexecuted andthecomputerwilljumpoutoftheloop.Otherwise,thecom puterwillprintout\Your answermustbe > 0."andwilljumpbacktothestartofthelooptoreadanotheri nputvalue. (Therstlineofthisloop,\ while(true) "mightlookabitstrange,butit'sperfectly legitimate.Theconditionina while loopcanbeanyboolean-valuedexpression.Thecomputer evaluatesthisexpressionandcheckswhetherthevalueis true or false .Thebooleanliteral \ true "isjustabooleanexpressionthatalwaysevaluatestotrue. So\ while(true) "canbe usedtowriteaninniteloop,oronethatwillbeterminatedb ya break statement.) A break statementterminatestheloopthatimmediatelyenclosesth e break statement.It ispossibletohave nested loops,whereoneloopstatementiscontainedinsideanother .Ifyou usea break statementinsideanestedloop,itwillonlybreakoutofthat loop,notoutof

PAGE 92

CHAPTER3.CONTROL 78 theloopthatcontainsthenestedloop.Thereissomethingca lleda labeledbreak statement thatallowsyoutospecifywhichloopyouwanttobreak.Thisi snotverycommon,soIwill gooveritquickly.Labelsworklikethis:Youcanputa label infrontofanyloop.Alabel consistsofasimpleidentierfollowedbyacolon.Forexamp le,a while withalabelmight looklike\ mainloop:while... ".Insidethisloopyoucanusethelabeledbreakstatement \ breakmainloop; "tobreakoutofthelabeledloop.Forexample,hereisacodes egmentthat checkswhethertwostrings, s1 and s2 ,haveacharacterincommon.Ifacommoncharacteris found,thevalueoftheragvariable nothingInCommon issetto false ,andalabeledbreakis isusedtoendtheprocessingatthatpoint: booleannothingInCommon;nothingInCommon=true;//Assumes1ands2havenocharsinco mmon. inti,j;//Variablesforiteratingthroughthecharsins1an ds2. i=0;bigloop:while(i
PAGE 93

CHAPTER3.CONTROL 79 3.4.1ForLoopsThe for statementmakesacommontypeofwhileloopeasiertowrite.M anywhileloopshave thegeneralform: h initialization i while( h continuation-condition i ){ h statements i h update i } Forexample,considerthisexample,copiedfromanexamplei n Section3.2 : years=0;//initializethevariableyearswhile(years<5){//conditionforcontinuingloop interest=principal*rate;//principal+=interest;//dothreestatementsSystem.out.println(principal);//years++;//updatethevalueofthevariable,years } Thisloopcanbewrittenasthefollowingequivalent for statement: for(years=0;years<5;years++){ interest=principal*rate;principal+=interest;System.out.println(principal); } Theinitialization,continuationcondition,andupdating haveallbeencombinedintherstline ofthe for loop.Thiskeepseverythinginvolvedinthe\control"ofthe loopinoneplace,which helpsmakestheloopeasiertoreadandunderstand.The for loopisexecutedinexactlythe samewayastheoriginalcode:Theinitializationpartisexe cutedonce,beforetheloopbegins. Thecontinuationconditionisexecutedbeforeeachexecuti onoftheloop,andtheloopends whenthisconditionis false .Theupdatepartisexecutedattheendofeachexecutionofth e loop,justbeforejumpingbacktocheckthecondition. Theformalsyntaxofthe for statementisasfollows: for( h initialization i ; h continuation-condition i ; h update i ) h statement i or,usingablockstatement: for( h initialization i ; h continuation-condition i ; h update i ){ h statements i } The h continuation-condition i mustbeaboolean-valuedexpression.The h initialization i can beanyexpression,butisusuallyanassignmentstatement.T he h update i canalsobeany expression,butisusuallyanincrement,adecrement,orana ssignmentstatement.Anyof thethreecanbeempty.Ifthecontinuationconditionisempt y,itistreatedasifitwere \ true ,"sotheloopwillberepeatedforeveroruntilitendsforsom eotherreason,suchas a break statement.(Somepeopleliketobeginaninniteloopwith\ for(;;) "insteadof \ while(true) ".)

PAGE 94

CHAPTER3.CONTROL 80 Usually,theinitializationpartofa for statementassignsavaluetosomevariable,andthe updatechangesthevalueofthatvariablewithanassignment statementorwithanincrement ordecrementoperation.Thevalueofthevariableistestedi nthecontinuationcondition,and theloopendswhenthisconditionevaluatesto false .Avariableusedinthiswayiscalleda loopcontrolvariable .Inthe for statementgivenabove,theloopcontrolvariableis years Certainly,themostcommontypeof for loopisthe countingloop ,wherealoopcontrol variabletakesonallintegervaluesbetweensomeminimuman dsomemaximumvalue.A countingloophastheform for( h variable i = h min i ; h variable i <= h max i ; h variable i ++){ h statements i } where h min i and h max i areinteger-valuedexpressions(usuallyconstants).The h variable i takes onthevalues h min i h min i +1, h min i +2,..., h max i .Thevalueoftheloopcontrolvariableis oftenusedinthebodyoftheloop.The for loopatthebeginningofthissectionisacounting loopinwhichtheloopcontrolvariable, years ,takesonthevalues1,2,3,4,5.Hereisaneven simplerexample,inwhichthenumbers1,2,...,10aredispla yedonstandardoutput: for(N=1;N<=10;N++) System.out.println(N); Forvariousreasons,Javaprogrammersliketostartcountin gat0insteadof1,andthey tendtousea\ < "inthecondition,ratherthana\ <= ".Thefollowingvariationoftheabove loopprintsoutthetennumbers0,1,2,...,9: for(N=0;N<10;N++) System.out.println(N); Using < insteadof <= inthetest,orviceversa,isacommonsourceofo-by-oneerr orsin programs.Youshouldalwaysstopandthink,DoIwantthenal valuetobeprocessedornot? It'seasytocountdownfrom10to1insteadofcountingup.Jus tstartwith10,decrement theloopcontrolvariableinsteadofincrementingit,andco ntinueaslongasthevariableis greaterthanorequaltoone. for(N=10;N>=1;N--) System.out.println(N); Now,infact,theocialsyntaxofa for statemenentactuallyallowsboththeinitialization partandtheupdateparttoconsistofseveralexpressions,s eparatedbycommas.Sowecan evencountupfrom1to10andcountdownfrom10to1atthesamet ime! for(i=1,j=10;i<=10;i++,j--){ TextIO.putf("%5d",i);//Outputiina5-characterwidecol umn. TextIO.putf("%5d",j);//Outputjina5-charactercolumnTextIO.putln();//andendtheline. } Asanalexample,let'ssaythatwewanttousea for loopthatprintsoutjusttheeven numbersbetween2and20,thatis:2,4,6,8,10,12,14,16,18, 20.Thereareseveralwaysto dothis.Justtoshowhowevenaverysimpleproblemcanbesolv edinmanyways,hereare fourdierentsolutions(threeofwhichwouldgetfullcredi t):

PAGE 95

CHAPTER3.CONTROL 81 (1)//Thereare10numberstoprint. //Useaforlooptocount1,2,//...,10.Thenumberswewant//toprintare2*1,2*2,...2*10.for(N=1;N<=10;N++){ System.out.println(2*N); } (2)//Useaforloopthatcounts //2,4,...,20directlyby//adding2toNeachtimethrough//theloop.for(N=2;N<=20;N=N+2){ System.out.println(N); } (3)//Countoffallthenumbers //2,3,4,...,19,20,but//onlyprintoutthenumbers//thatareeven.for(N=2;N<=20;N++){ if(N%2==0)//isNeven? System.out.println(N); } (4)//Irritatetheprofessorwith //asolutionthatfollowsthe//letterofthissillyassignment//whilemakingfunofit.for(N=1;N<=1;N++){ System.out.print("2468101214161820"); } Perhapsitisworthstressingonemoretimethata for statement,likeanystatement,never occursonitsowninarealprogram.Astatementmustbeinside the main routineofaprogram orinsidesomeothersubroutine.Andthatsubroutinemustbe denedinsideaclass.Ishould alsoremindyouthateveryvariablemustbedeclaredbeforei tcanbeused,andthatincludes theloopcontrolvariableina for statement.Inalltheexamplesthatyouhaveseensofarin thissection,theloopcontrolvariablesshouldbedeclared tobeoftype int .Itisnotrequired thataloopcontrolvariablebeaninteger.Here,forexample ,isa for loopinwhichthevariable, ch ,isoftype char ,usingthefactthatthe ++ operatorcanbeappliedtocharactersaswellas tonumbers: //Printoutthealphabetononelineofoutput.charch;//Theloopcontrolvariable; //oneoftheletterstobeprinted. for(ch='A';ch<='Z';ch++) System.out.print(ch); System.out.println();

PAGE 96

CHAPTER3.CONTROL 82 3.4.2Example:CountingDivisorsLet'slookatalesstrivialproblemthatcanbesolvedwitha for loop.If N and D arepositive integers,wesaythat D isa divisor of N iftheremainderwhen D isdividedinto N iszero. (Equivalently,wecouldsaythat N isanevenmultipleof D .)IntermsofJavaprogramming, D isadivisorof N if N%D iszero. Let'swriteaprogramthatinputsapositiveinteger, N ,fromtheuserandcomputeshow manydierentdivisors N has.Thenumbersthatcouldpossiblybedivisorsof N are1,2,..., N Tocomputethenumberofdivisorsof N ,wecanjusttesteachpossibledivisorof N andcount theonesthatactuallydodivide N evenly.Inpseudocode,thealgorithmtakestheform Getapositiveinteger,N,fromtheuserLetdivisorCount=0foreachnumber,testDivisor,intherangefrom1toN: iftestDivisorisadivisorofN: Countitbyadding1todivisorCount Outputthecount Thisalgorithmdisplaysacommonprogrammingpatternthati susedwhensome,butnotall, ofasequenceofitemsaretobeprocessed.Thegeneralpatter nis foreachiteminthesequence: iftheitempassesthetest: processit The for loopinourdivisor-countingalgorithmcanbetranslatedin toJavacodeas for(testDivisor=1;testDivisor<=N;testDivisor++){ if(N%testDivisor==0) divisorCount++; } Onamoderncomputer,thisloopcanbeexecutedveryquickly. Itisnotimpossibletorun itevenforthelargestlegal int value,2147483647.(Ifyouwantedtorunitforevenlarger values,youcouldusevariablesoftype long ratherthan int .)However,itdoestakeanoticeable amountoftimeforverylargenumbers.SowhenIimplementedt hisalgorithm,Idecidedto outputadoteverytimethecomputerhastestedonemillionpo ssibledivisors.Intheimproved versionoftheprogram,therearetwotypesofcountinggoing on.Wehavetocountthenumber ofdivisorsandwealsohavetocountthenumberofpossibledi visorsthathavebeentested. Sotheprogramneedstwocounters.Whenthesecondcounterre aches1000000,theprogram outputsa'.'andresetsthecountertozerosothatwecanstar tcountingthenextgroupofone million.Revertingtopseudocode,thealgorithmnowlooksl ike Getapositiveinteger,N,fromtheuserLetdivisorCount=0//Numberofdivisorsfound.LetnumberTested=0//Numberofpossibledivisorstested //sincethelastperiodwasoutput. foreachnumber,testDivisor,intherangefrom1toN: iftestDivisorisadivisorofN: Countitbyadding1todivisorCount Add1tonumberTestedifnumberTestedis1000000: printouta'.'LetnumberTested=0 Outputthecount

PAGE 97

CHAPTER3.CONTROL 83 Finally,wecantranslatethealgorithmintoacompleteJava program: /** *Thisprogramreadsapositiveintegerfromtheuser.*Itcountshowmanydivisorsthatnumberhas,and*thenitprintstheresult.*/ publicclassCountDivisors{ publicstaticvoidmain(String[]args){ intN;//Apositiveintegerenteredbytheuser. //Divisorsofthisnumberwillbecounted. inttestDivisor;//Anumberbetween1andNthatisa //possibledivisorofN. intdivisorCount;//NumberofdivisorsofNthathavebeenfo und. intnumberTested;//Usedtocounthowmanypossibledivisor s //ofNhavebeentested.Whenthenumber//reaches1000000,aperiodisoutputand//thevalueofnumberTestedisresettozero. /*Getapositiveintegerfromtheuser.*/while(true){ TextIO.put("Enterapositiveinteger:");N=TextIO.getlnInt();if(N>0) break; TextIO.putln("Thatnumberisnotpositive.Pleasetryagai n."); }/*Countthedivisors,printinga"."afterevery1000000tes ts.*/ divisorCount=0;numberTested=0;for(testDivisor=1;testDivisor<=N;testDivisor++){ if(N%testDivisor==0) divisorCount++; numberTested++;if(numberTested==1000000){ TextIO.put('.');numberTested=0; } }/*Displaytheresult.*/TextIO.putln();TextIO.putln("Thenumberofdivisorsof"+N +"is"+divisorCount); }//endmain() }//endclassCountDivisors

PAGE 98

CHAPTER3.CONTROL 84 3.4.3NestedforLoopsControlstructuresinJavaarestatementsthatcontainstat ements.Inparticular,controlstructurescancontaincontrolstructures.You'vealreadyseens everalexamplesof if statements insideloops,andoneexampleofa while loopinsideanother while ,butanycombinationofone controlstructureinsideanotherispossible.Wesaythaton estructureis nested insideanother. Youcanevenhavemultiplelevelsofnesting,suchasa while loopinsidean if statementinside another while loop.ThesyntaxofJavadoesnotsetalimitonthenumberofle velsofnesting. Asapracticalmatter,though,it'sdiculttounderstandap rogramthathasmorethanafew levelsofnesting. Nested for loopsarisenaturallyinmanyalgorithms,anditisimportan ttounderstandhow theywork.Let'slookatacoupleofexamples.First,conside rtheproblemofprintingouta multiplicationtablelikethisone: 12345678910111224681012141618202224369121518212427303336481216202428323640444851015202530354045505560612182430364248546066727142128354249566370778481624324048566472808896918273645546372819099108 1020304050607080901001101201122334455667788991101211321224364860728496108120132144 Thedatainthetablearearrangedinto12rowsand12columns. Theprocessofprintingthem outcanbeexpressedinapseudocodealgorithmas foreachrowNumber=1,2,3,...,12: PrintthefirsttwelvemultiplesofrowNumberononelineOutputacarriagereturn Therststepinthe for loopcanitselfbeexpressedasa for loop.Wecanexpand\Printthe rsttwelvemultiplesof rowNumber ononeline"as: forN=1,2,3,...,12: PrintN*rowNumber soarenedalgorithmforprintingthetablehasone for loopnestedinsideanother: foreachrowNumber=1,2,3,...,12: forN=1,2,3,...,12: PrintN*rowNumber Outputacarriagereturn Wewanttoprinttheoutputinneatcolumns,witheachoutputn umbertakingupfourspaces. Thiscanbedoneusingformattedoutputwithformatspecier %4d .Assumingthat rowNumber and N havebeendeclaredtobevariablesoftype int ,thealgorithmcanbeexpressedinJavaas for(rowNumber=1;rowNumber<=12;rowNumber++){ for(N=1;N<=12;N++){ //printin4-charactercolumns System.out.printf("%4d;",N*rowNumber);//Nocarriager eturn! }

PAGE 99

CHAPTER3.CONTROL 85 System.out.println();//Addacarriagereturnatendofthe line. } Thissectionhasbeenweigheddownwithlotsofexamplesofnu mericalprocessing.Forour nextexample,let'sdosometextprocessing.Considerthepr oblemofndingwhichofthe26 lettersofthealphabetoccurinagivenstring.Forexample, thelettersthatoccurin\Hello World"areD,E,H,L,O,R,andW.Morespecically,wewillwri teaprogramthatwilllistall theletterscontainedinastringandwillalsocountthenumb erofdierentletters.Thestring willbeinputbytheuser.Let'sstartwithapseudocodealgor ithmfortheprogram. AsktheusertoinputastringReadtheresponseintoavariable,strLetcount=0(forcountingthenumberofdifferentletters)foreachletterofthealphabet: iftheletteroccursinstr: PrinttheletterAdd1tocount Outputthecount Sincewewanttoprocesstheentirelineoftextthatisentere dbytheuser,we'lluse TextIO.getln() toreadit.Thelineofthealgorithmthatreads\foreachlett erofthealphabet"canbeexpressedas\ for(letter='A';letter<='Z';letter++) ".Butthebody ofthis for loopneedsmorethought.Howdowecheckwhetherthegivenlet ter, letter ,occurs in str ?Oneideaistolookateachcharacterinthestringinturn,an dcheckwhetherthat characterisequalto letter .Wecangetthe i -thcharacterof str withthefunctioncall str.charAt(i) ,where i rangesfrom0to str.length()-1 .Onemorediculty:Aletter suchas'A'canoccurin str ineitherupperorlowercase,'A'or'a'.Wehavetocheckforb oth ofthese.Butwecanavoidthisdicultybyconverting str touppercasebeforeprocessing it.Then,weonlyhavetocheckfortheuppercaseletter.Weca nnowreshoutthealgorithm fully.Notetheuseof break inthenested for loop.Itisrequiredtoavoidprintingorcounting agivenlettermorethanonce(inthecasewhereitoccursmore thanonceinthestring).The break statementbreaksoutoftheinner for loop,butnottheouter for loop.Uponexecuting the break ,thecomputercontinuestheouterloopwiththenextvalueof letter AsktheusertoinputastringReadtheresponseintoavariable,strConvertstrtouppercaseLetcount=0forletter='A','B',...,'Z': fori=0,1,...,str.length()-1: ifletter==str.charAt(i): PrintletterAdd1tocountbreak//jumpoutoftheloop Outputthecount Hereisthecompleteprogram: /** *Thisprogramreadsalineoftextenteredbytheuser.*Itprintsalistofthelettersthatoccurinthetext,*anditreportshowmanydifferentletterswerefound.*/

PAGE 100

CHAPTER3.CONTROL 86 publicclassListLetters{ publicstaticvoidmain(String[]args){ Stringstr;//Lineoftextenteredbytheuser.intcount;//Numberofdifferentlettersfoundinstr.charletter;//Aletterofthealphabet.TextIO.putln("Pleasetypeinalineoftext.");str=TextIO.getln();str=str.toUpperCase();count=0;TextIO.putln("Yourinputcontainsthefollowingletters: "); TextIO.putln();TextIO.put("");for(letter='A';letter<='Z';letter++){ inti;//Positionofacharacterinstr.for(i=0;i=0) ". Ifweusedthistechniqueintheaboveprogram,wewouldn'tne edanested for loop.Thisgives youapreviewofhowsubroutinescanbeusedtodealwithcompl exity. 3.4.4Enumsandfor-eachLoopsJava5.0introducesanew\enhanced"formofthe for loopthatisdesignedtobeconvenient forprocessingdatastructures.A datastructure isacollectionofdataitems,consideredas aunit.Forexample,a list isadatastructurethatconsistssimplyofasequenceofitem s. Theenhanced for loopmakesiteasytoapplythesameprocessingtoeveryeleme ntofalist orotherdatastructure.Datastructuresareamajortopicin computerscience,butwewon't encountertheminanyseriouswayuntil Chapter7 .However,oneoftheapplicationsofthe enhanced for loopisto enum types,andsoweconsideritbrieryhere.(Enumswereintrodu ced in Subsection2.3.3 .)

PAGE 101

CHAPTER3.CONTROL 87 Theenhancedforloopcanbeusedtoperformthesameprocessi ngoneachoftheenum constantsthatarethepossiblevaluesofanenumeratedtype .Thesyntaxfordoingthisis: for( h enum-type-name ih variable-name i : h enum-type-name i .values()) h statement i or for( h enum-type-name ih variable-name i : h enum-type-name i .values()){ h statements i } If MyEnum isthenameofanyenumeratedtype,then MyEnum.values() isafunctioncallthat returnsalistcontainingallofthevaluesoftheenum.( values() isastaticmemberfunction in MyEnum andofanyother enum .)Forthisenumeratedtype,the for loopwouldhavethe form: for(MyEnum h variable-name i :MyEnum.values()) h statement i Theintentofthisistoexecutethe h statement i onceforeachofthepossiblevaluesofthe MyEnum type.The h variable-name i istheloopcontrolvariable.Inthe h statement i ,itrepresentstheenumeratedtypevaluethatiscurrentlybeingproc essed.Thisvariableshould not be declaredbeforethe for loop;itisessentiallybeingdeclaredintheloopitself. Togiveaconcreteexample,supposethatthefollowingenume ratedtypehasbeendened torepresentthedaysoftheweek: enumDay{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SA TURDAY,SUNDAY} Thenwecouldwrite: for(Dayd:Day.values()){ System.out.print(d);System.out.print("isdaynumber");System.out.println(d.ordinal()); } Day.values() representsthelistcontainingthesevenconstantsthatmak euptheenumerated type.Thersttimethroughthisloop,thevalueof d wouldbetherstenumeratedtypevalue Day.MONDAY ,whichhasordinalnumber0,sotheoutputwouldbe\MONDAYis daynumber0". Thesecondtimethroughtheloop,thevalueof d wouldbe Day.TUESDAY ,andsoonthrough Day.SUNDAY .Thebodyoftheloopisexecutedonceforeachiteminthelist Day.values() with d takingoneachofthosevaluesinturn.Thefulloutputfromth isloopwouldbe: MONDAYisdaynumber0TUESDAYisdaynumber1WEDNESDAYisdaynumber2THURSDAYisdaynumber3FRIDAYisdaynumber4SATURDAYisdaynumber5SUNDAYisdaynumber6 Sincetheintentoftheenhancedforloopistodosomething\f oreach"iteminadata structure,itisoftencalleda for-eachloop .Thesyntaxforthistypeofloopisunfortunate.It wouldbebetterifitwerewrittensomethinglike\ foreachDaydinDay.values() ",which conveysthemeaningmuchbetterandissimilartothesyntaxu sedinotherprogramming languagesforsimilartypesofloops.It'shelpfultothinko fthecolon(:)intheloopasmeaning \in."

PAGE 102

CHAPTER3.CONTROL 88 3.5TheifStatementT hefirstofthetwobranchingstatements inJavaisthe if statement,whichyou (online) havealreadyseenin Section3.1 .Ittakestheform if( h boolean-expression i ) h statement-1 i else h statement-2 i Asusual,thestatementsinsidean if statementscanbeblocks.The if statementrepresents atwo-waybranch.The else partofan if statement|consistingoftheword\else"andthe statementthatfollowsit|canbeomitted.3.5.1TheDanglingelseProblemNow,an if statementis,inparticular,astatement.Thismeansthatei ther h statement-1 i or h statement-2 i intheabove if statementcanitselfbean if statement.Aproblemarises, however,if h statement-1 i isan if statementthathasno else part.Thisspecialcaseis eectivelyforbiddenbythesyntaxofJava.Suppose,forexa mple,thatyoutype if(x>0) if(y>0) System.out.println("Firstcase"); else System.out.println("Secondcase"); Now,rememberthatthewayyou'veindentedthisdoesn'tmean anythingatalltothecomputer. Youmightthinkthatthe else partisthesecondhalfofyour\ if(x>0) "statement,but therulethatthecomputerfollowsattachesthe else to\ if(y>0) ",whichiscloser.That is,thecomputerreadsyourstatementasifitwereformatted : if(x>0) if(y>0) System.out.println("Firstcase"); else System.out.println("Secondcase"); Youcanforcethecomputertousetheotherinterpretationby enclosingthenested if ina block: if(x>0){ if(y>0) System.out.println("Firstcase"); }else System.out.println("Secondcase"); Thesetwo if statementshavedierentmeanings:Inthecasewhen x<=0 ,therststatement doesn'tprintanything,butthesecondstatementprints\Se condcase.". 3.5.2Theif...elseifConstructionMuchmoreinterestingthanthistechnicalityisthecasewhe re h statement-2 i ,the else part ofthe if statement,isitselfan if statement.Thestatementwouldlooklikethis(perhaps withoutthenalelsepart):

PAGE 103

CHAPTER3.CONTROL 89 if( h boolean-expression-1 i ) h statement-1 i else if( h boolean-expression-2 i ) h statement-2 i else h statement-3 i However,sincethecomputerdoesn'tcarehowaprogramislai doutonthepage,thisisalmost alwayswrittenintheformat: if( h boolean-expression-1 i ) h statement-1 i elseif( h boolean-expression-2 i ) h statement-2 i else h statement-3 i Youshouldthinkofthisasasinglestatementrepresentinga three-waybranch.Whenthe computerexecutesthis,oneandonlyoneofthethreestateme nts| h statement-1 i h statement2 i ,or h statement-3 i |willbeexecuted.Thecomputerstartsbyevaluating h boolean-expression1 i .Ifitis true ,thecomputerexecutes h statement-1 i andthenjumpsallthewaytotheendof theouterifstatement,skippingtheothertwo h statement i s.If h boolean-expression-1 i is false thecomputerskips h statement-1 i andexecutesthesecond,nestedifstatement.Todothis, itteststhevalueof h boolean-expression-2 i andusesittodecidebetween h statement-2 i and h statement-3 i Hereisanexamplethatwillprintoutoneofthreedierentme ssages,dependingonthe valueofavariablenamed temperature : if(temperature<50) System.out.println("It'scold."); elseif(temperature<80) System.out.println("It'snice."); else System.out.println("It'shot."); If temperature is,say,42,thersttestis true .Thecomputerprintsoutthemessage\It's cold",andskipstherest|withoutevenevaluatingthesecon dcondition.Foratemperatureof 75,thersttestis false ,sothecomputergoesontothesecondtest.Thistestis true ,so thecomputerprints\It'snice"andskipstherest.Ifthetem peratureis173,bothofthetests evaluateto false ,sothecomputersays\It'shot"(unlessitscircuitshavebe enfriedbythe heat,thatis). Youcangoonstringingtogether\else-if's"tomakemulti-w aybrancheswithanynumber ofcases: if( h boolean-expression-1 i ) h statement-1 i elseif( h boolean-expression-2 i ) h statement-2 i elseif( h boolean-expression-3 i ) h statement-3 i ..//(morecases).

PAGE 104

CHAPTER3.CONTROL 90 elseif( h boolean-expression-N i ) h statement-N i else h statement-(N+1) i Thecomputerevaluatesbooleanexpressionsoneaftertheot heruntilitcomestoonethatis true .Itexecutestheassociatedstatementandskipstherest.If noneofthebooleanexpressions evaluateto true ,thenthestatementinthe else partisexecuted.Thisstatementiscalled amulti-waybranchbecauseonlyoneofthestatementswillbe executed.Thenal else part canbeomitted.Inthatcase,ifallthebooleanexpressionsa refalse,noneofthestatementsis executed.Ofcourse,eachofthestatementscanbeablock,co nsistingofanumberofstatements enclosedbetween { and } .(Admittedly,thereislotofsyntaxhere;asyoustudyandpr actice, you'llbecomecomfortablewithit.)3.5.3IfStatementExamplesAsanexampleofusing if statements,letssupposethat x y ,and z arevariablesoftype int andthateachvariablehasalreadybeenassignedavalue.Con sidertheproblemofprintingout thevaluesofthethreevariablesinincreasingorder.Forex amples,ifthevaluesare42,17,and 20,thentheoutputshouldbeintheorder17,20,42. Onewaytoapproachthisistoask,wheredoes x belonginthelist?Itcomesrstifit's lessthanboth y and z .Itcomeslastifit'sgreaterthanboth y and z .Otherwise,itcomesin themiddle.Wecanexpressthiswitha3-way if statement,butwestillhavetoworryabout theorderinwhich y and z shouldbeprinted.Inpseudocode, if(xy&&x>z){ outputyandzintheircorrectorder,followedbyx }else{ outputxinbetweenyandzintheircorrectorder } Determiningtherelativeorderof y and z requiresanother if statement,sothisbecomes if(xy&&x>z){//xcomeslast if(y
PAGE 105

CHAPTER3.CONTROL 91 System.out.println(z+""+x+""+y); } Youmightcheckthatthiscodewillworkcorrectlyevenifsom eofthevaluesarethesame.If thevaluesoftwovariablesarethesame,itdoesn'tmatterwh ichorderyouprintthemin. Note,bytheway,thateventhoughyoucansayinEnglish\ifxi slessthanyandz,", youcan'tsayinJava\ if(xy)//zcomeslast System.out.println(x+""+y+""+z); else//zisinthemiddle System.out.println(x+""+z+""+y); }else{//ycomesbeforex if(zx)//zcomeslast System.out.println(y+""+x+""+z); else//zisinthemiddle System.out.println(y+""+z+""+x); } Onceagain,weseehowthesameproblemcanbesolvedinmanydi erentways.Thetwo approachestothisproblemhavenotexhaustedallthepossib ilities.Forexample,youmight startbytestingwhether x isgreaterthan y .Ifso,youcouldswaptheirvalues.Onceyou've donethat,youknowthat x shouldbeprintedbefore y Finally,let'swriteacompleteprogramthatusesan if statementinaninterestingway.I wantaprogramthatwillconvertmeasurementsoflengthfrom oneunitofmeasurementto another,suchasmilestoyardsorinchestofeet.Sofar,thep roblemisextremelyunderspecied.Let'ssaythattheprogramwillonlydealwithmeas urementsininches,feet,yards, andmiles.Itwouldbeeasytoextenditlatertodealwithothe runits.Theuserwilltypein ameasurementinoneoftheseunits,suchas\17feet"or\2.73 miles".Theoutputwillshow thelengthintermsof each ofthefourunitsofmeasure.(Thisiseasierthanaskingtheu ser whichunitstouseintheoutput.)Anoutlineoftheprocessis Readtheuser'sinputmeasurementandunitsofmeasureExpressthemeasurementininches,feet,yards,andmilesDisplaythefourresults Theprogramcanreadbothpartsoftheuser'sinputfromthesa melinebyusing TextIO.getDouble() toreadthenumericalmeasurementand TextIO.getlnWord() toread theunitofmeasure.Theconversionintodierentunitsofme asurecanbesimpliedbyrst

PAGE 106

CHAPTER3.CONTROL 92 convertingtheuser'sinputintoinches.Fromthere,thenum berofinchescaneasilybeconvertedintofeet,yards,andmiles.Beforeconvertingintoi nches,wehavetotesttheinputto determinewhichunitofmeasuretheuserhasspecied: Letmeasurement=TextIO.getDouble()Letunits=TextIO.getlnWord()iftheunitsareinches Letinches=measurement elseiftheunitsarefeet Letinches=measurement*12//12inchesperfoot elseiftheunitsareyards Letinches=measurement*36//36inchesperyard elseiftheunitsaremiles Letinches=measurement*12*5280//5280feetpermile else Theunitsareillegal!Printanerrormessageandstopprocessing Letfeet=inches/12.0Letyards=inches/36.0Letmiles=inches/(12.0*5280.0)Displaytheresults Since units isa String ,wecanuse units.equals("inches") tocheckwhetherthespeciedunitofmeasureis\inches".However,itwouldbeniceto allowtheunitstobespeciedas\inch"orabbreviatedto\in".Toallowthesethreepo ssibilities,wecancheck if (units.equals("inches")||units.equals("inch")||unit s.equals("in")) .Itwould alsobenicetoallowuppercaseletters,asin\Inches"or\IN ".Wecandothisbyconverting units tolowercasebeforetestingitorbysubstitutingthefuncti on units.equalsIgnoreCase for units.equals Inmynalprogram,Idecidedtomakethingsmoreinteresting byallowingtheusertoenter awholesequenceofmeasurements.Theprogramwillendonlyw hentheuserinputs0.Todo this,Ijusthavetowraptheabovealgorithminsidea while loop,andmakesurethattheloop endswhentheuserinputsa0.Here'sthecompleteprogram: /* *Thisprogramwillconvertmeasurementsexpressedininche s, *feet,yards,ormilesintoeachofthepossibleunitsof*measure.Themeasurementisinputbytheuser,followedby*theunitofmeasure.Forexample:"17feet","1inch",*"2.73mi".Abbreviationsin,ft,yd,andmiareaccepted.*Theprogramwillcontinuetoreadandconvertmeasurements*untiltheuserentersaninputof0.*/publicclassLengthConverter{ publicstaticvoidmain(String[]args){ doublemeasurement;//Numericalmeasurement,inputbyuse r. Stringunits;//Theunitofmeasurefortheinput,also //specifiedbytheuser. doubleinches,feet,yards,miles;//Measurementexpresse din //eachpossibleunitof//measure.

PAGE 107

CHAPTER3.CONTROL 93 TextIO.putln("Entermeasurementsininches,feet,yards, ormiles."); TextIO.putln("Forexample:1inch17feet2.73miles");TextIO.putln("Youcanuseabbreviations:inftydmi");TextIO.putln("Iwillconvertyourinputintotheotherunit s"); TextIO.putln("ofmeasure.");TextIO.putln();while(true){ /*Gettheuser'sinput,andconvertunitstolowercase.*/TextIO.put("Enteryourmeasurement,or0toend:");measurement=TextIO.getDouble();if(measurement==0) break;//Terminatethewhileloop. units=TextIO.getlnWord();units=units.toLowerCase();/*Converttheinputmeasurementtoinches.*/if(units.equals("inch")||units.equals("inches") ||units.equals("in")){ inches=measurement; }elseif(units.equals("foot")||units.equals("feet") ||units.equals("ft")){ inches=measurement*12; }elseif(units.equals("yard")||units.equals("yards") ||units.equals("yd")){ inches=measurement*36; }elseif(units.equals("mile")||units.equals("miles") ||units.equals("mi")){ inches=measurement*12*5280; }else{ TextIO.putln("Sorry,butIdon'tunderstand\"" +units+"\"."); continue;//backtostartofwhileloop }/*Convertmeasurementininchestofeet,yards,andmiles.* / feet=inches/12;yards=inches/36;miles=inches/(12*5280);/*Outputmeasurementintermsofeachunitofmeasure.*/TextIO.putln();TextIO.putln("That'sequivalentto:");TextIO.putf("%12.5g",inches);TextIO.putln("inches");TextIO.putf("%12.5g",feet);TextIO.putln("feet");TextIO.putf("%12.5g",yards);

PAGE 108

CHAPTER3.CONTROL 94 TextIO.putln("yards");TextIO.putf("%12.5g",miles);TextIO.putln("miles");TextIO.putln(); }//endwhileTextIO.putln();TextIO.putln("OK!Byefornow."); }//endmain() }//endclassLengthConverter (Notethatthisprogramusesformattedoutputwiththe\g"fo rmatspecier.Inthisprogram,wehavenocontroloverhowlargeorhowsmallthenumber smightbe.Itcouldeasily makesensefortheusertoenterverylargeorverysmallmeasu rements.The\g"formatwill printarealnumberinexponentialformifitisverylargeorv erysmall,andintheusualdecimal formotherwise.Rememberthatintheformatspecication %12.5g ,the5isthetotalnumber ofsignicantdigitsthataretobeprinted,sowewillalways getthesamenumberofsignifant digitsintheoutput,nomatterwhatthesizeofthenumber.If wehadusedan\f"format speciersuchas %12.5f ,theoutputwouldbeindecimalformwith5digitsafterthede cimal point.Thiswouldprintthenumber0.0000000007454as 0.00000 ,withno signicant digits atall!Withthe\g"formatspecier,theoutputwouldbe 7.454e-10 .) 3.5.4TheEmptyStatementAsanalnoteinthissection,Iwillmentiononemoretypeofs tatementinJava:the empty statement .Thisisastatementthatconsistssimplyofasemicolonandw hichtellsthecomputer todonothing.Theexistenceoftheemptystatementmakesthe followinglegal,eventhough youwouldnotordinarilyseeasemicolonaftera } : if(x<0){ x=-x; }; Thesemicolonislegalafterthe } ,butthecomputerconsidersittobeanemptystatement, notpartofthe if statement.Occasionally,youmightndyourselfusingthee mptystatement whenwhatyoumeanis,infact,\donothing".Forexample,the rathercontrived if statement if(done) ;//Emptystatement else System.out.println("Notdoneyet.); doesnothingwhenthe boolean variable done istrue,andprintsout\Notdoneyet"when itisfalse.Youcan'tjustleaveoutthesemicoloninthisexa mple,sinceJavasyntaxrequires anactualstatementbetweenthe if andthe else .Iprefer,though,touseanemptyblock, consistingof { and } withnothingbetween,forsuchcases. Occasionally,strayemptystatementscancauseannoying,h ard-to-nderrorsinaprogram. Forexample,thefollowingprogramsegmentprintsout\Hell o"just once ,nottentimes: for(inti=0;i<10;i++); System.out.println("Hello");

PAGE 109

CHAPTER3.CONTROL 95 Why?Becausethe\;"attheendoftherstlineisastatement, anditisthisstatement thatisexecutedtentimes.The System.out.println statementisnotreallyinsidethe for statementatall,soitisexecutedjustonce,afterthe for loophascompleted. 3.6TheswitchStatementT hesecondbranchingstatement inJavaisthe switch statement,whichisintroduced (online) inthissection.The switch statementisusedfarlessoftenthanthe if statement,butitis sometimesusefulforexpressingacertaintypeofmulti-way branch. 3.6.1TheBasicswitchStatementAswitchstatementallowsyoutotestthevalueofanexpressi onand,dependingonthatvalue, tojumpdirectlytosomelocationwithintheswitchstatemen t.Onlyexpressionsofcertain typescanbeused.Thevalueoftheexpressioncanbeoneofthe primitiveintegertypes int short ,or byte .Itcanbetheprimitive char type.Or,aswewillseelaterinthissection, itcanbeanenumueratedtype.Inparticular,theexpression cannot bea String orareal number.Thepositionsthatyoucanjumptoaremarkedwith caselabels thattakethe form:\case h constant i :".Thismarksthepositionthecomputerjumpstowhentheexp ression evaluatestothegiven h constant i .Asthenalcaseinaswitchstatementyoucan,optionally, usethelabel\default:",whichprovidesadefaultjumppoin tthatisusedwhenthevalueofthe expressionisnotlistedinanycaselabel. A switch statement,asitismostofternused,hastheform: switch( h expression i ){ case h constant-1 i : h statements-1 i break; case h constant-2 i : h statements-2 i break;..//(morecases). case h constant-N i : h statements-N i break; default://optionaldefaultcase h statements-(N+1) i }//endofswitchstatement The break statementsaretechnicallyoptional.Theeectofa break istomakethecomputer jumptotheendoftheswitchstatement.Ifyouleaveoutthebr eakstatement,thecomputer willjustforgeaheadaftercompletingonecaseandwillexec utethestatementsassociatedwith thenextcaselabel.Thisisrarelywhatyouwant,butitisleg al.(Iwillnotehere|although youwon'tunderstandituntilyougettothenextchapter|tha tinsideasubroutine,the break statementissometimesreplacedbya return statement.) Notethatyoucanleaveoutoneofthegroupsofstatementsent irely(includingthe break ). Youthenhavetwocaselabelsinarow,containingtwodieren tconstants.Thisjustmeans

PAGE 110

CHAPTER3.CONTROL 96 thatthecomputerwilljumptothesameplaceandperformthes ameactionforeachofthetwo constants. Hereisanexampleofaswitchstatement.Thisisnotausefule xample,butitshouldbe easyforyoutofollow.Note,bytheway,thattheconstantsin thecaselabelsdon'thavetobe inanyparticularorder,aslongastheyarealldierent: switch(N){//(AssumeNisanintegervariable.) case1: System.out.println("Thenumberis1.");break; case2:case4:case8: System.out.println("Thenumberis2,4,or8.");System.out.println("(That'sapowerof2!)");break; case3:case6:case9: System.out.println("Thenumberis3,6,or9.");System.out.println("(That'samultipleof3!)");break; case5: System.out.println("Thenumberis5.");break; default: System.out.println("Thenumberis7orisoutsidetherange 1to9."); } Theswitchstatementisprettyprimitiveascontrolstructu resgo,andit'seasytomakemistakeswhenyouuseit.Javatakesallitscontrolstructuresd irectlyfromtheolderprogramming languagesCandC++.Theswitchstatementiscertainlyonepl acewherethedesignersofJava shouldhaveintroducedsomeimprovements.3.6.2MenusandswitchStatementsOneapplicationof switch statementsisinprocessingmenus.Amenuisalistofoptions Theuserselectsoneoftheoptions.Thecomputerhastorespo ndtoeachpossiblechoiceina dierentway.Iftheoptionsarenumbered1,2,...,thenthen umberofthechosenoptioncan beusedina switch statementtoselecttheproperresponse. Ina TextIO -basedprogram,themenucanbepresentedasanumberedlisto foptions,and theusercanchooseanoptionbytypinginitsnumber.Hereisa nexamplethatcouldbeused inavariationofthe LengthConverter examplefromtheprevioussection: intoptionNumber;//Optionnumberfrommenu,selectedbyus er. doublemeasurement;//Anumericalmeasurement,inputbyth euser. //Theunitofmeasurementdependsonwhich//optiontheuserhasselected. doubleinches;//Thesamemeasurement,convertedintoinch es. /*Displaymenuandgetuser'sselectedoptionnumber.*/TextIO.putln("Whatunitofmeasurementdoesyourinputuse ?"); TextIO.putln();

PAGE 111

CHAPTER3.CONTROL 97 TextIO.putln("1.inches");TextIO.putln("2.feet");TextIO.putln("3.yards");TextIO.putln("4.miles");TextIO.putln();TextIO.putln("Enterthenumberofyourchoice:");optionNumber=TextIO.getlnInt();/*Readuser'smeasurementandconverttoinches.*/switch(optionNumber){ case1: TextIO.putln("Enterthenumberofinches:");measurement=TextIO.getlnDouble();inches=measurement;break; case2: TextIO.putln("Enterthenumberoffeet:");measurement=TextIO.getlnDouble();inches=measurement*12;break; case3: TextIO.putln("Enterthenumberofyards:");measurement=TextIO.getlnDouble();inches=measurement*36;break; case4: TextIO.putln("Enterthenumberofmiles:");measurement=TextIO.getlnDouble();inches=measurement*12*5280;break; default: TextIO.putln("Error!Illegaloptionnumber!Iquit!");System.exit(1); }//endswitch/*Nowgoontoconvertinchestofeet,yards,andmiles...*/ 3.6.3EnumsinswitchStatementsThetypeoftheexpressionina switch canbeanenumeratedtype.Inthatcase,theconstants inthe case labelsmustbevaluesfromtheenumeratedtype.Forexample, ifthetypeofthe expressionistheenumeratedtype Season denedby enumSeason{SPRING,SUMMER,FALL,WINTER} thentheconstantsinthecaselabelmustbechosenfromamong thevalues Season.SPRING Season.SUMMER Season.FALL ,or Season.WINTER .However,thereisanotherquirkinthesyntax:whenanenumconstantisusedina case label,onlythesimplename,suchas\ SPRING canbeused,notthefullname\ Season.SPRING ".Ofcourse,thecomputeralreadyknowsthat thevalueinthe case labelmustbelongtotheenumeratedtype,sinceitcantellth atfromthe typeofexpressionused,sothereisreallynoneedtospecify thetypenameintheconstant.As anexample,supposethat currentSeason isavariableoftype Season .Thenwecouldhavethe switch statement:

PAGE 112

CHAPTER3.CONTROL 98 switch(currentSeason){ caseWINTER://(NOTSeason.WINTER!) System.out.println("December,January,February");break; caseSPRING: System.out.println("March,April,May");break; caseSUMMER: System.out.println("June,July,August");break; caseFALL: System.out.println("September,October,November");break; } 3.6.4DeniteAssignmentAsasomwhatmorerealisticexample,thefollowing switch statementmakesarandomchoiceamongthreepossiblealternatives.Recallthatt hevalueoftheexpression (int)(3*Math.random()) isoneoftheintegers0,1,or2,selectedatrandomwithequal probability,sothe switch statementbelowwillassignoneofthevalues "Rock" "Scissors" "Paper" to computerMove ,withprobability1/3foreachcase.Althoughtheswitchsta tement inthisexampleiscorrect,thiscodesegmentasawholeillus tratesasubtlesyntaxerrorthat sometimescomesup: StringcomputerMove;switch((int)(3*Math.random())){ case0: computerMove="Rock";break; case1: computerMove="Scissors";break; case2: computerMove="Paper";break; }System.out.println("Computer'smoveis"+computerMove) ;//ERROR! Youprobablyhaven'tspottedtheerror,sinceit'snotanerr orfromahumanpointofview. Thecomputerreportsthelastlinetobeanerror,becausethe variable computerMove might nothavebeenassignedavalue.InJava,itisonlylegaltouse thevalueofavariableifa valuehasalreadybeen denitelyassigned tothatvariable.Thismeansthatthecomputer mustbeabletoprove,justfromlookingatthecodewhenthepr ogramiscompiled,thatthe variablemusthavebeenassignedavalue.Unfortunately,th ecomputeronlyhasafewsimple rulesthatitcanapplytomakethedetermination.Inthiscas e,itseesa switch statementin whichthetypeofexpressionis int andinwhichthecasesthatarecoveredare0,1,and2.For othervaluesoftheexpression, computerMove isneverassignedavalue.So,thecomputerthinks computerMove mightstillbeundenedafterthe switch statement.Now,infact,thisisn'ttrue: 0,1,and2areactuallytheonlypossiblevaluesoftheexpres sion (int)(3*Math.random()) butthecomputerisn'tsmartenoughtogurethatout.Theeas iestwaytoxtheproblemis

PAGE 113

CHAPTER3.CONTROL 99 toreplacethecaselabel case2 with default .Thecomputercanseethatavalueisassigned to computerMove inallcases. Moregenerally,wesaythatavaluehasbeendenitelyassign edtoavariableatagiven pointinaprogramifeveryexecutionpathleadingfromthede clarationofthevariabletothat pointinthecodeincludesanassignmenttothevariable.Thi sruletakesintoaccountloops and if statementsaswellas switch statements.Forexample,thefollowingtwo if statements bothdothesamethingasthe switch statementgivenabove,butonlytheoneontheright denitelyassignsavalueto computerMove : StringcomputerMove;StringcomputerMove;intrand; intrand; rand=(int)(3*Math.random());rand=(int)(3*Math.rando m()); if(rand==0)if(rand==0) computerMove="Rock";computerMove="Rock"; elseif(rand==1)elseif(rand==1) computerMove="Scissors";computerMove="Scissors"; else if(rand==2) else computerMove="Paper";computerMove="Paper"; Inthecodeontheleft,thetest\ if(rand==2) "inthenal else clauseisunnecessary becauseif rand isnot0or1,theonlyremainingpossibilityisthat rand==2 .Thecomputer, however,can'tgurethatout.3.7IntroductiontoExceptionsandtry..catchI nadditiontothecontrol structuresthatdeterminethenormalrowofcontrolinapro(online) gram,Javahasawaytodealwith\exceptional"casesthatthr owtherowofcontroloits normaltrack.Whenanerroroccursduringtheexecutionofap rogram,thedefaultbehavior istoterminatetheprogramandtoprintanerrormessage.How ever,Javamakesitpossibleto \catch"sucherrorsandprogramaresponsedierentfromsim plylettingtheprogramcrash. Thisisdonewiththe try..catch statement.Inthissection,wewilltakeapreliminary,inco mpletelookatusing try..catch tohandleerrors.Errorhandlingisacomplextopic,whichwe willreturntoin Chapter8 3.7.1ExceptionsTheterm exception isusedtorefertothetypeoferrorthatonemightwanttohand lewith a try..catch .Anexceptionisanexceptiontothenormalrowofcontrolint heprogram. Thetermisusedinpreferenceto\error"becauseinsomecase s,anexceptionmightnotbe consideredtobeanerroratall.Youcansometimesthinkofan exceptionasjustanotherway toorganizeaprogram. ExceptionsinJavaarerepresentedasobjectsoftype Exception .Actualexceptionsaredenedbysubclassesof Exception .Dierentsubclassesrepresentdierenttypesofexceptio nsWe willlookatonlytwotypesofexceptioninthissection: NumberFormatException and IllegalArgumentException A NumberFormatException canoccurwhenanattemptismadetoconvertastring intoanumber.Suchconversionsaredonebythefunctions Integer.parseInt and Integer.parseDouble .(See Subsection2.5.7 .)Considerthefunctioncall Integer.parseInt(str) where str isavariableoftype String .Ifthevalueof str isthe string "42" ,thenthefunctioncallwillcorrectlyconvertthestringin tothe int 42.However,

PAGE 114

CHAPTER3.CONTROL 100 ifthevalueof str is,say, "fred" ,thefunctioncallwillfailbecause "fred" isnotalegal stringrepresentationofan int value.Inthiscase,anexceptionoftype NumberFormatException occurs.Ifnothingisdonetohandletheexception,theprogr amwillcrash. An IllegalArgumentException canoccurwhenanillegalvalueispassedasaparametertoa subroutine.Forexample,ifasubroutinerequiresthatapar ameterbegreaterthanorequalto zero,an IllegalArgumentException mightoccurwhenanegativevalueispassedtothesubroutine Howtorespondtotheillegalvalueisuptothepersonwhowrot ethesubroutine,sowe can'tsimplysaythateveryillegalparametervaluewillres ultinan IllegalArgumentException However,itisacommonresponse. Onecasewherean IllegalArgumentException canoccurisinthe valueOf functionofan enumeratedtype.Recallfrom Subsection2.3.3 thatthisfunctiontriestoconvertastringinto oneofthevaluesoftheenumeratedtype.Ifthestringthatis passedasaparameterto valueOf isnotthenameofoneoftheenumeratedtype'svalues,thenan IllegalArgumentException occurs. Forexample,giventheenumeratedtype enumToss{HEADS,TAILS} Toss.valueOf("HEADS") correctlyreturnsthevalue Toss.HEADS ,while Toss.valueOf("FEET") resultsinan IllegalArgumentException 3.7.2try..catchWhenanexceptionoccurs,wesaythattheexceptionis\throw n".Forexample,wesaythat Integer.parseInt(str) throws anexceptionoftype NumberFormatException whenthevalue of str isillegal.Whenanexceptionisthrown,itispossibleto\ca tch"theexceptionand preventitfromcrashingtheprogram.Thisisdonewitha try..catch statement.Insomewhat simpliedform,thesyntaxfora try..catch is: try{ h statements-1 i }catch( h exception-class-name ih variable-name i ){ h statements-2 i } The h exception-class-name i couldbe NumberFormatException IllegalArgumentException ,or someotherexceptionclass.Whenthecomputerexecutesthis statement,itexecutesthestatementsinthe try part.Ifnoerroroccursduringtheexecutionof h statements-1 i ,thenthe computerjustskipsoverthe catch partandproceedswiththerestoftheprogram.However, ifanexceptionoftype h exception-class-name i occursduringtheexecutionof h statements-1 i thecomputerimmediatelyjumpstothe catch partandexecutes h statements-2 i ,skippingany remainingstatementsin h statements-1 i .Duringtheexecutionof h statements-2 i ,the h variablename i representstheexceptionobject,sothatyoucan,forexampl e,printitout.Attheend ofthe catch part,thecomputerproceedswiththerestoftheprogram;the exceptionhasbeen caughtandhandledanddoesnotcrashtheprogram.Notethato nlyonetypeofexceptionis caught;ifsomeothertypeofexceptionoccursduringtheexe cutionof h statements-1 i ,itwill crashtheprogramasusual. (Bytheway,notethatthebraces, { and } ,arepartofthesyntaxofthe try..catch statement.Theyarerequiredevenifthereisonlyonestatem entbetweenthebraces.Thisis dierentfromtheotherstatementswehaveseen,wherethebr acesaroundasinglestatement areoptional.)

PAGE 115

CHAPTER3.CONTROL 101 Asanexample,supposethat str isavariableoftype String whosevaluemightormight notrepresentalegalrealnumber.Thenwecouldsay: try{ doublex;x=Double.parseDouble(str);System.out.println("Thenumberis"+x); }catch(NumberFormatExceptione){ System.out.println("Notalegalnumber."); } Ifanerroristhrownbythecallto Double.parseDouble(str) ,thentheoutputstatementin the try partisskipped,andthestatementinthe catch partisexecuted. It'snotalwaysagoodideatocatchexceptionsandcontinuew iththeprogram.Oftenthat canjustleadtoanevenbiggermesslateron,anditmightbebe tterjusttolettheexception crashtheprogramatthepointwhereitoccurs.However,some timesit'spossibletorecover fromanerror.Forexample,supposethatwehavetheenumerat edtype enumDay{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SA TURDAY,SUNDAY} andwewanttheusertoinputavaluebelongingtothistype. TextIO doesnotknowabout thistype,sowecanonlyreadtheuser'sresponseasastring. Thefunction Day.valueOf can beusedtoconverttheuser'sresponsetoavalueoftype Day .Thiswillthrowanexception oftype IllegalArgumentException iftheuser'sresponseisnotthenameofoneofthevaluesof type Day ,butwecanrespondtotheerroreasilyenoughbyaskingtheus ertoenteranother response.Hereisacodesegmentthatdoesthis.(Converting theuser'sresponsetouppercase willallowresponsessuchas\Monday"or\monday"inadditio nto\MONDAY".) Dayweekday;//User'sresponseasavalueoftypeDay.while(true){ Stringresponse;//User'sresponseasaString.TextIO.put("Pleaseenteradayoftheweek:");response=TextIO.getln();response=response.toUpperCase();try{ weekday=Day.valueOf(response);break; }catch(IllegalArgumentExceptione){ TextIO.putln(response+"isnotthenameofadayoftheweek. "); } } The break statementwillbereachedonlyiftheuser'sresponseisacce ptable,andsotheloop willendonlywhenalegalvaluehasbeenassignedto weekday 3.7.3ExceptionsinTextIOWhen TextIO readsanumericvaluefromtheuser,itmakessurethattheuse r'sresponseis legal,usingatechniquesimilartothe while loopand try..catch inthepreviousexample. However, TextIO canreaddatafromothersourcesbesidestheuser.(See Subsection2.4.5 .) Whenitisreadingfromale,thereisnoreasonablewayfor TextIO torecoverfromanillegal valueintheinput,soitrespondsbythrowinganexception.T okeepthingssimple, TextIO only

PAGE 116

CHAPTER3.CONTROL 102 throwsexceptionsoftype IllegalArgumentException ,nomatterwhattypeoferroritencounters. Forexample,anexceptionwilloccurifanattemptismadetor eadfromaleafterallthedata inthelehasalreadybeenread.In TextIO ,theexceptionisoftype IllegalArgumentException .If youhaveabetterresponsetoleerrorsthantolettheprogra mcrash,youcanusea try..catch tocatchexceptionsoftype IllegalArgumentException Forexample,supposethatalecontainsnothingbutrealnum bers,andwewantaprogram thatwillreadthenumbersandndtheirsumandtheiraverage .Sinceitisunknownhowmany numbersareinthele,thereisthequestionofwhentostopre ading.Oneapproachissimply totrytokeepreadingindenitely.Whentheendoftheleisr eached,anexceptionoccurs. Thisexceptionisnotreallyanerror|it'sjustawayofdetec tingtheendofthedata,sowe cancatchtheexceptionandnishuptheprogram.Wecanreadt hedataina while(true) loopandbreakoutoftheloopwhenanexceptionoccurs.Thisi sanexampleofthesomewhat unusualtechniqueofusinganexceptionaspartoftheexpect edrowofcontrolinaprogram. Toreadfromthele,weneedtoknowthele'sname.Tomakethe programmoregeneral, wecanlettheuserenterthelename,insteadofhard-coding axedlenameintheprogram. However,itispossiblethattheuserwillenterthenameofa lethatdoesnotexist.When weuse TextIO.readfile toopenalethatdoesnotexist,anexceptionoftype IllegalArgumentException occurs.Wecancatchthisexceptionandasktheusertoentera dierentle name.Hereisacompleteprogramthatusesalltheseideas: /** *Thisprogramreadsnumbersfromafile.Itcomputesthesuma nd *theaverageofthenumbersthatitreads.Thefileshouldcon tain *nothingbutnumbersoftypedouble;ifthisisnotthecase,t he *outputwillbethesumandaverageofhowevermanynumberswe re *successfullyreadfromthefile.Thenameofthefilewillbe*inputbytheuser.*/ publicclassReadNumbersFromFile{ publicstaticvoidmain(String[]args){ while(true){ StringfileName;//Thenameofthefile,tobeinputbytheuse r. TextIO.put("Enterthenameofthefile:");fileName=TextIO.getln();try{ TextIO.readFile(fileName);//Trytoopenthefileforinpu t. break;//Ifthatsucceeds,breakoutoftheloop. }catch(IllegalArgumentExceptione){ TextIO.putln("Can'treadfromthefile\""+fileName+"\". "); TextIO.putln("Pleasetryagain.\n"); } }//Atthispoint,TextIOisreadingfromthefile.doublenumber;//Anumberreadfromthedatafile.doublesum;//Thesumofallthenumbersreadsofar.intcount;//Thenumberofnumbersthatwereread.sum=0;

PAGE 117

CHAPTER3.CONTROL 103 count=0;try{ while(true){//Loopendswhenanexceptionoccurs. number=TextIO.getDouble();count++;//Thisisskippedwhentheexceptionoccurssum+=number; } }catch(IllegalArgumentExceptione){ //Weexpectthistooccurwhentheend-of-fileisencountere d. //Wedon'tconsiderthistobeanerror,sothereisnothingto do //inthiscatchclause.Justproceedwiththerestoftheprog ram. }//Atthispoint,we'vereadtheentirefile.TextIO.putln();TextIO.putln("Numberofdatavaluesread:"+count);TextIO.putln("Thesumofthedatavalues:"+sum);if(count==0) TextIO.putln("Can'tcomputeanaverageof0values."); else TextIO.putln("Theaverageofthevalues:"+(sum/count)); } } 3.8IntroductiontoGUIProgrammingF orthepasttwochapters ,you'vebeenlearningthesortofprogrammingthatisdone (online) insideasinglesubroutine.Intherestofthetext,we'llbem oreconcernedwiththelarger scalestructureofprograms,butthematerialthatyou'veal readylearnedwillbeanimportant foundationforeverythingtocome. Inthissection,beforemovingontoprogramming-in-the-la rge,we'lltakealookathow programming-in-the-smallcanbeusedinothercontextsbes idestext-based,command-linestyleprograms.We'lldothisbytakingashort,introductor ylookatappletsandgraphical programming. An applet isaJavaprogramthatrunsonaWebpage.Anappletisnotastan d-alone application,anditdoesnothavea main() routine.Infact,anappletisan object ratherthan a class .WhenJavarstappearedonthescene,appletswereoneofits majorappeals.Since then,theyhavebecomelessimportant,althoughtheycansti llbeveryuseful.Whenwestudy GUIprogrammingin Chapter6 ,wewillconcentrateonstand-aloneGUIprogramsrathertha n onapplets,butappletsareagoodplacetostartforourrstl ookatthesubject. WhenanappletisplacedonaWebpage,itisassignedarectang ularareaonthepage.It isthejoboftheapplettodrawthecontentsofthatrectangle .Whentheregionneedstobe drawn,theWebpagecallsasubroutineintheapplettodoso.T hisisnotsodierentfrom whathappenswithstand-aloneprograms.Whensuchaprogram needstoberun,thesystem callsthe main() routineoftheprogram.Similarly,whenanappletneedstobe drawn,the Webpagecallsthe paint() routineoftheapplet.Theprogrammerspecieswhathappens whentheseroutinesarecalledbyllinginthebodiesofther outines.Programminginthe

PAGE 118

CHAPTER3.CONTROL 104 small!Appletscandootherthingsbesidesdrawthemselves, suchasrespondingwhentheuser clicksthemouseontheapplet.Eachoftheapplet'sbehavior sisdenedbyasubroutine. Theprogrammerspecieshowtheappletbehavesbyllingint hebodiesoftheappropriate subroutines. Averysimpleapplet,whichdoesnothingbutdrawitself,can bedenedbyaclassthat containsnothingbuta paint() routine.Thesourcecodefortheclasswouldthenhavethe form: importjava.awt.*;importjava.applet.*;publicclass h name-of-applet i extendsApplet{ publicvoidpaint(Graphicsg){ h statements i } } where h name-of-applet i isanidentierthatnamestheclass,andthe h statements i arethecode thatactuallydrawstheapplet.Thislookssimilartothede nitionofastand-aloneprogram, butthereareafewthingsherethatneedtobeexplained,star tingwiththersttwolines. Whenyouwriteaprogram,therearecertainbuilt-inclasses thatareavailableforyouto use.Thesebuilt-inclassesinclude System and Math .Ifyouwanttouseoneoftheseclasses, youdon'thavetodoanythingspecial.Youjustgoaheadandus eit.ButJavaalsohasalarge numberofstandardclassesthatarethereifyouwantthembut thatarenotautomatically availabletoyourprogram.(Therearejusttoomanyofthem.) Ifyouwanttousethese classesinyourprogram,youhavetoaskforthemrst.Thesta ndardclassesaregrouped intoso-called\packages."Twoofthesepackagesarecalled \java.awt"and\java.applet".The directive\importjava.awt.*;"makesalltheclassesfromt hepackagejava.awtavailablefor useinyourprogram.Thejava.awtpackagecontainsclassesr elatedtographicaluserinterface programming,includingaclasscalled Graphics .The Graphics classisreferredtointhe paint() routineabove.Thejava.appletpackagecontainsclassessp ecicallyrelatedtoapplets, includingtheclassnamed Applet Therstlineoftheclassdenitionabovesaysthattheclass \extends Applet ." Applet is astandardclassthatisdenedinthejava.appletpackage.I tdenesallthebasicproperties andbehaviorsofappletobjects.Byextendingthe Applet class,thenewclasswearedening inheritsallthosepropertiesandbehaviors.Weonlyhaveto denethewaysinwhichourclass diersfromthebasic Applet class.Inourcase,theonlydierenceisthatourappletwill draw itselfdierently,soweonlyhavetodenethe paint() routinethatdoesthedrawing.Thisis oneofthemainadvantagesofobject-orientedprogramming. (Actually,inthefuture,ourappletswillbedenedtoexten d JApplet ratherthan Applet The JApplet classisitselfanextensionof Applet .The Applet classhasexistedsincethe originalversionofJava,while JApplet ispartofthenewer\Swing"setofgraphicaluser interfacecomponents.Forthemoment,thedistinctionisno timportant.) Onemorethingneedstobementioned|andthisisapointwhere Java'ssyntaxgetsunfortunatelyconfusing.Appletsareobjects,notclasses.I nsteadofbeingstaticmembersofa class,thesubroutinesthatdenetheapplet'sbehaviorare partoftheappletobject.Wesay thattheyare\non-static"subroutines.Ofcourse,objects arerelatedtoclassesbecauseevery objectisdescribedbyaclass.Nowhereisthepartthatcange tconfusing:Eventhougha non-staticsubroutineisnotactuallypartofaclass(inthe senseofbeingpartofthebehavior

PAGE 119

CHAPTER3.CONTROL 105 oftheclass),itisneverthelessdenedinaclass(inthesen sethattheJavacodethatdenes thesubroutineispartoftheJavacodethatdenestheclass) .Manyobjectscanbedescribed bythesameclass.Eachobjecthasitsownnon-staticsubrout ine.Butthecommondenition ofthosesubroutines|theactualJavasourcecode|isphysic allypartoftheclassthatdescribes alltheobjects.Toputitbriery:staticsubroutinesinacla ssdenitionsaywhattheclassdoes; non-staticsubroutinessaywhatalltheobjectsdescribedb ytheclassdo.Anapplet's paint() routineisanexampleofanon-staticsubroutine.Astand-al oneprogram's main() routineisan exampleofastaticsubroutine.Thedistinctiondoesn'trea llymattertoomuchatthispoint: Whenworkingwithstand-aloneprograms,markeverythingwi ththereservedword,\ static "; leaveitoutwhenworkingwithapplets.However,thedistinc tionbetweenstaticandnon-static willbecomemoreimportantlaterinthecourse. Let'swriteanappletthatdrawssomething.Inordertowrite anappletthatdrawssomething,youneedtoknowwhatsubroutinesareavailablefordr awing,justasinwritingtextorientedprogramsyouneedtoknowwhatsubroutinesareavai lableforreadingandwriting text.InJava,thebuilt-indrawingsubroutinesarefoundin objectsoftheclass Graphics ,one oftheclassesinthejava.awtpackage.Inanapplet's paint() routine,youcanusethe Graphics object g fordrawing.(Thisobjectisprovidedasaparametertothe paint() routinewhen thatroutineiscalled.) Graphics objectscontainmanysubroutines.I'llmentionjustthreeo f themhere.You'llencountermoreofthemin Chapter6 g.setColor(c) ,iscalledtosetthecolorthatisusedfordrawing.Theparam eter, c is anobjectbelongingtoaclassnamed Color ,anotheroneoftheclassesinthejava.awt package.Aboutadozenstandardcolorsareavailableasstat icmembervariablesin the Color class.Thesestandardcolorsinclude Color.BLACK Color.WHITE Color.RED Color.GREEN ,and Color.BLUE .Forexample,ifyouwanttodrawinred,youwouldsay \ g.setColor(Color.RED); ".Thespeciedcolorisusedforallsubsequentdrawingoper ationsupuntilthenexttime setColor iscalled. g.drawRect(x,y,w,h) drawstheoutlineofarectangle.Theparameters x y w ,and h mustbeinteger-valuedexpressions.Thissubroutinedraws theoutlineoftherectangle whosetop-leftcorneris x pixelsfromtheleftedgeoftheappletand y pixelsdownfrom thetopoftheapplet.Thewidthoftherectangleis w pixels,andtheheightis h pixels. g.fillRect(x,y,w,h) issimilarto drawRect exceptthatitllsintheinsideoftherectangleinsteadofjustdrawinganoutline. Thisisenoughinformationtowriteanappletthatwilldrawt hefollowingimageonaWeb page:

PAGE 120

CHAPTER3.CONTROL 106 Theappletrstllsitsentirerectangularareawithred.Th enitchangesthedrawingcolor toblackanddrawsasequenceofrectangles,whereeachrecta ngleisnestedinsidetheprevious one.Therectanglescanbedrawnwitha while loop.Eachtimethroughtheloop,therectangle getssmalleranditmovesdownandoverabit.We'llneedvaria blestoholdthewidthandheight oftherectangleandavariabletorecordhowfarthetop-left corneroftherectangleisinset fromtheedgesoftheapplet.Thewhileloopendswhentherect angleshrinkstonothing.In generaloutline,thealgorithmfordrawingtheappletis Setthedrawingcolortored(usingtheg.setColorsubroutin e) Fillintheentireapplet(usingtheg.fillRectsubroutine)SetthedrawingcolortoblackSetthetop-leftcornerinsettobe0Settherectanglewidthandheighttobeasbigastheappletwhilethewidthandheightaregreaterthanzero: drawarectangle(usingtheg.drawRectsubroutine)increasetheinsetdecreasethewidthandtheheight Inmyapplet,eachrectangleis15pixelsawayfromtherectan glethatsurroundsit,sothe inset isincreasedby15eachtimethroughthe while loop.Therectangleshrinksby15pixels ontheleft and by15pixelsontheright,sothewidthoftherectangleshrink sby30eachtime throughtheloop.Theheightalsoshrinksby30pixelseachti methroughtheloop. ItisnothardtocodethisalgorithmintoJavaanduseittode nethe paint() methodof anapplet.I'veassumedthattheapplethasaheightof160pix elsandawidthof300pixels. ThesizeisactuallysetinthesourcecodeoftheWebpagewher etheappletappears.Inorder foranapplettoappearonapage,thesourcecodeforthepagem ustincludeacommandthat specieswhichapplettorunandhowbigitshouldbe.(We'lls eehowtodothatlater.)It's notagreatideatoassumethatweknowhowbigtheappletisgoi ngtobe.Ontheotherhand, it'salsonotagreatideatowriteanappletthatdoesnothing butdrawastaticpicture.I'll addressboththeseissuesbeforetheendofthissection.But fornow,hereisthesourcecode fortheapplet: importjava.awt.*;importjava.applet.Applet;publicclassStaticRectsextendsApplet{ publicvoidpaint(Graphicsg){ //Drawasetofnestedblackrectanglesonaredbackground.//Eachnestedrectangleisseparatedby15pixelson//allsidesfromtherectanglethatenclosesit. intinset;//Gapbetweenbordersofapplet //andoneoftherectangles. intrectWidth,rectHeight;//Thesizeofoneoftherectangl es. g.setColor(Color.red);g.fillRect(0,0,300,160);//Filltheentireappletwithre d. g.setColor(Color.black);//Drawtherectanglesinblack.inset=0;rectWidth=299;//Setsizeoffirstrecttosizeofapplet.

PAGE 121

CHAPTER3.CONTROL 107 rectHeight=159;while(rectWidth>=0&&rectHeight>=0){ g.drawRect(inset,inset,rectWidth,rectHeight);inset+=15;//Rectsare15pixelsapart.rectWidth-=30;//Widthdecreasesby15pixels //onleftand15onright. rectHeight-=30;//Heightdecreasesby15pixels //ontopand15onbottom. } }//endpaint() }//endclassStaticRects (Youmightwonderwhytheinitial rectWidth issetto299,insteadofto300,sincethe widthoftheappletis300pixels.It'sbecauserectanglesar edrawnasifwithapenwhosenib hangsbelowandtotherightofthepointwherethepenisplace d.Ifyourunthepenexactly alongtherightedgeoftheapplet,thelineitdrawsisactual lyoutsidetheappletandtherefore isnotseen.Soinstead,werunthepenalongalineonepixelto theleftoftheedgeofthe applet.Thesamereasoningappliesto rectHeight .Carefulgraphicsprogrammingdemands attentiontodetailslikethese.) Whenyouwriteanapplet,yougettobuildontheworkofthepeo plewhowrotethe Applet class.The Applet classprovidesaframeworkonwhichyoucanhangyourownwork .Any programmercancreateadditionalframeworksthatcanbeuse dbyotherprogrammersasabasis forwritingspecictypesofappletsorstand-aloneprogram s.I'vewrittenasmallframework thatmakesitpossibletowriteappletsthatdisplaysimplea nimations.Oneexamplethatwe willconsiderisananimatedversionofthenestedrectangle sappletfromearlierinthissection. Youcanseetheappletinactionatthebottomoftheon-lineve rsionofthispage. A computeranimation isreallyjustasequenceofstillimages.Thecomputerdispl aysthe imagesoneaftertheother.Eachimagediersabitfromthepr ecedingimageinthesequence. Ifthedierencesarenottoobigandifthesequenceisdispla yedquicklyenough,theeyeis trickedintoperceivingcontinuousmotion. Intheexample,rectanglesshrinkcontinuallytowardsthec enteroftheapplet,whilenew rectanglesappearattheedge.Theperpetualmotionis,ofco urse,anillusion.Ifyouthink aboutit,you'llseethattheappletloopsthroughthesamese tofimagesoverandover.Ineach image,thereisagapbetweenthebordersoftheappletandthe outermostrectangle.Thisgap getswiderandwideruntilanewrectangleappearsatthebord er.Onlyit'snotanewrectangle. Whathasreallyhappenedisthattheapplethasstartedovera gainwiththerstimageinthe sequence. Theproblemofcreatingananimationisreallyjusttheprobl emofdrawingeachofthestill imagesthatmakeuptheanimation.Eachstillimageiscalled a frame .Inmyframeworkfor animation,whichisbasedonanon-standardclasscalled SimpleAnimationApplet2 ,allyou havetodoisllinthecodethatsayshowtodrawoneframe.The basicformatisasfollows: importjava.awt.*;publicclass h name-of-class i extendsSimpleAnimationApplet2{ publicvoiddrawFrame(Graphicsg){ h statements i //todrawoneframeoftheanimation

PAGE 122

CHAPTER3.CONTROL 108 } } The\ importjava.awt.*; "isrequiredtogetaccesstographics-relatedclassessuch as Graphics and Color .Yougettollinanynameyouwantfortheclass,andyougetto llinthestatementsinsidethesubroutine.The drawFrame() subroutinewillbecalledbythe systemeachtimeaframeneedstobedrawn.Allyouhavetodois saywhathappenswhen thissubroutineiscalled.Ofcourse,youhavetodrawadier entpictureforeachframe,andto dothatyouneedtoknowwhichframeyouaredrawing.Theclass SimpleAnimationApplet2 providesafunctionnamed getFrameNumber() thatyoucancalltondoutwhichframeto draw.Thisfunctionreturnsanintegervaluethatrepresent stheframenumber.Ifthevalue returnedis0,youaresupposedtodrawtherstframe;ifthev alueis1,youaresupposedto drawthesecondframe,andsoon. Inthesampleapplet,thethingthatdiersfromoneframetoa notheristhedistancebetween theedgesoftheappletandtheoutermostrectangle.Sinceth erectanglesare15pixelsapart, thisdistanceincreasesfrom0to14andthenjumpsbackto0wh ena\new"rectangleappears. Theappropriatevaluecanbecomputedverysimplyfromthefr amenumber,withthestatement \ inset=getFrameNumber()%15 ;".Thevalueoftheexpression getFrameNumber()%15 is between0and14.Whentheframenumberreaches15oranymulti pleof15,thevalueof getFrameNumber()%15 jumpsbackto0. Drawingoneframeinthesampleanimatedappletisverysimil artodrawingthesingle imageofthe StaticRects applet,asgivenabove.The paint() methodinthe StaticRects appletbecomes,withonlyminormodication,the drawFrame() methodofmy MovingRects animationapplet.I'vechosentomakeoneimprovement:The StaticRects appletassumes thattheappletis300by160pixels.The MovingRects appletwillworkforanyappletsize. Toimplementthis,the drawFrame() routinehastoknowhowbigtheappletis.Thereare twofunctionsthatcanbecalledtogetthisinformation.The function getWidth() returnsan integervaluerepresentingthewidthoftheapplet,andthef unction getHeight() returnsthe height.Thewidthandheight,togetherwiththeframenumber ,areusedtocomputethesize oftherstrectanglethatisdrawn.Hereisthecompletesour cecode: importjava.awt.*;publicclassMovingRectsextendsSimpleAnimationApplet2 { publicvoiddrawFrame(Graphicsg){ //Drawoneframeintheanimationbyfillinginthebackgroun d //withasolidredandthendrawingasetofnestedblack//rectangles.Theframenumbertellshowmuchthefirst//rectangleistobeinsetfromthebordersoftheapplet. intwidth;//Widthoftheapplet,inpixels.intheight;//Heightoftheapplet,inpixels.intinset;//Gapbetweenbordersofappletandarectangle. //Theinsetfortheoutermostrectanglegoes//from0to14thenbackto0,andsoon,//astheframeNumbervaries. intrectWidth,rectHeight;//Thesizeofoneoftherectangl es. width=getWidth();//Findoutthesizeofthedrawingarea.

PAGE 123

CHAPTER3.CONTROL 109 height=getHeight();g.setColor(Color.red);//Filltheframewithred.g.fillRect(0,0,width,height);g.setColor(Color.black);//Switchcolortoblack.inset=getFrameNumber()%15;//Gettheinsetforthe //outermostrect. rectWidth=width-2*inset-1;//Setsizeofoutermostrect.rectHeight=height-2*inset-1;while(rectWidth>=0&&rectHeight>=0){ g.drawRect(inset,inset,rectWidth,rectHeight);inset+=15;//Rectsare15pixelsapart.rectWidth-=30;//Widthdecreasesby15pixels //onleftand15onright. rectHeight-=30;//Heightdecreasesby15pixels //ontopand15onbottom. } }//enddrawFrame() }//endclassMovingRects Themainpointhereisthatbybuildingonanexistingframewo rk,youcandointeresting thingsusingthetypeoflocal,inside-a-subroutineprogra mmingthatwascoveredin Chapter2 and Chapter3 .AsyoulearnmoreaboutprogrammingandmoreaboutJava,you 'llbeable todomoreonyourown|butnomatterhowmuchyoulearn,you'll alwaysbedependenton otherpeople'sworktosomeextent.

PAGE 124

Exercises 110 ExercisesforChapter3 1. Howmanytimesdoyouhavetorollapairofdicebeforetheycom eupsnakeeyes?You (solution) coulddotheexperimentbyrollingthedicebyhand.Writeaco mputerprogramthat simulatestheexperiment.Theprogramshouldreportthenum berofrollsthatitmakes beforethedicecomeupsnakeeyes.(Note:\Snakeeyes"means thatbothdiceshowa valueof1.)Exercise2.2explainedhowtosimulaterollinga pairofdice. 2. Whichintegerbetween1and10000hasthelargestnumberofdi visors,andhowmany (solution) divisorsdoesithave?Writeaprogramtondtheanswersandp rintouttheresults.Itis possiblethatseveralintegersinthisrangehavethesame,m aximumnumberofdivisors. Yourprogramonlyhastoprintoutoneofthem. Subsection3.4.2 discusseddivisors.The sourcecodeforthatexampleis CountDivisors.java Youmightneedsomehintsabouthowtondamaximumvalue.The basicideais togothroughalltheintegers,keepingtrackofthelargestn umberofdivisorsthatyou've seen sofar .Also,keeptrackoftheintegerthathadthatnumberofdivis ors. 3. Writeaprogramthatwillevaluatesimpleexpressionssucha s17+3and3.14159*4.7. (solution) Theexpressionsaretobetypedinbytheuser.Theinputalway sconsistofanumber, followedbyanoperator,followedbyanothernumber.Theope ratorsthatareallowedare +,-,*,and/.Youcanreadthenumberswith TextIO.getDouble() andtheoperator with TextIO.getChar() .Yourprogramshouldreadanexpression,printitsvalue,re ad anotherexpression,printitsvalue,andsoon.Theprograms houldendwhentheuser enters0astherstnumberontheline. 4. Writeaprogramthatreadsonelineofinputtextandbreaksit upintowords.The (solution) wordsshouldbeoutputoneperline.Awordisdenedtobeaseq uenceofletters.Any charactersintheinputthatarenotlettersshouldbediscar ded.Forexample,iftheuser inputstheline Hesaid,"That'snotagoodidea." thentheoutputoftheprogramshouldbe Hesaidthatsnotagoodidea Animprovedversionoftheprogramwouldlist\that's"asasi ngleword.Anapostrophe canbeconsideredtobepartofawordifthereisaletteroneac hsideoftheapostrophe. Totestwhetheracharacterisaletter,youmightuse (ch>='a'&&ch<='z')|| (ch>='A'&&ch<='Z') .However,thisonlyworksinEnglishandsimilarlanguages. Abetterchoiceistocallthestandardfunction Character.isLetter(ch) ,whichreturns abooleanvalueof true if ch isaletterand false ifitisnot.ThisworksforanyUnicode character.

PAGE 125

Exercises 111 5. Supposethatalecontainsinformationaboutsalesguresf oracompanyinvariouscities. (solution) Eachlineofthelecontainsacityname,followedbyacolon( :)followedbythedatafor thatcity.Thedataisanumberoftype double. However,forsomecities,nodatawas available.Intheselines,thedataisreplacedbyacommente xplainingwhythedatais missing.Forexample,severallinesfromthelemightlookl ike: SanFrancisco:19887.32Chicago:noreportreceivedNewYork:298734.12 Writeaprogramthatwillcomputeandprintthetotalsalesfr omallthecitiestogether. Theprogramshouldalsoreportthenumberofcitiesforwhich datawasnotavailable. Thenameoftheleis\sales.dat". Tocompletethisprogram,you'llneedonefactaboutleinpu twith TextIO thatwas notcoveredin Subsection2.4.5 .Sinceyoudon'tknowinadvancehowmanylinesthere areinthele,youneedawaytotellwhenyouhavegottentothe endofthele.When TextIO isreadingfromale,thefunction TextIO.eof() canbeusedtotestfor endof le .This boolean -valuedfunctionreturns true ifthelehasbeenentirelyreadand returns false ifthereismoredatatoreadinthele.Thismeansthatyoucan readthe linesoftheleinaloop while(TextIO.eof()==false)... .Theloopwillendwhen allthelinesofthelehavebeenread. Suggestion:Foreachline,readandignorecharactersuptot hecolon.Thenreadthe restofthelineintoavariableoftype String .Trytoconvertthestringintoanumber,and use try..catch totestwhethertheconversionsucceeds. 6. Writeanappletthatdrawsacheckerboard.Assumethatthesi zeoftheappletis160 (solution) by160pixels.Eachsquareinthecheckerboardis20by20pixe ls.Thecheckerboard contains8rowsofsquaresand8columns.Thesquaresarereda ndblack.Hereisatricky waytodeterminewhetheragivensquareisredorblack:Ifthe rownumberandthe columnnumberareeitherbothevenorbothodd,thenthesquar eisred.Otherwise,itis black.Notethatasquareisjustarectangleinwhichtheheig htisequaltothewidth,so youcanusethesubroutine g.fillRect() todrawthesquares.Hereisanimageofthe checkerboard: (Torunanapplet,youneedaWebpagetodisplayit.Averysimp lepagewilldo. Assumethatyourappletclassiscalled Checkerboard ,sothatwhenyoucompileityou getaclasslenamed Checkerboard.class Makealethatcontainsonlythelines:

PAGE 126

Exercises 112 Callthisle Checkerboard.html .ThisisthesourcecodeforasimpleWebpagethat showsnothingbutyourapplet.YoucanopentheleinaWebbro wserorwithSun's appletviewerprogram.Thecompiledclassle, Checkerboard.class ,mustbeinthesame directorywiththeWeb-pagele, Checkerboard.html (IfyouareusingtheEclipseIntegratedDevelopmentEnviro nment,youcansimply right-clickthenameofthesourcecodeleinthePackageExp lorer.Inthepop-upmenu, goto\RunAs"thento\JavaApplet".Thiswillopenthewindow inwhichtheapplet appears.Thedefaultsizeforthewindowisbiggerthan160-b y-160,sothedrawingofthe checkerboardwillnotlltheentirewindow.) 7. Writeananimationappletthatshowsacheckerboardpattern inwhichtheevennumbered (solution) rowsslidetotheleftwhiletheoddnumberedrowsslidetothe right.Youcanassumethat theappletis160by160pixels.Eachrowshouldbeosetfromi tsusualpositionbythe amount getFrameNumber()%40 .Hints:Anythingyoudrawoutsidetheboundariesof theappletwillbeinvisible,soyoucandrawmorethan8squar esinarow.Youcanuse negativevaluesofxin g.fillRect(x,y,w,h) .(Beforetryingtodothisexercise,itwould beagoodideatolookataworkingapplet,whichcanbefoundin theon-lineversionof thisbook.) Yourappletwillextendthenon-standardclass, SimpleAnimationApplet2 ,whichwas introducedin Section3.8 .Thecompiledclassles, SimpleAnimationApplet2.class and SimpleAnimationApplet2$1.class ,mustbeinthesamedirectoryasyourWeb-page sourcelealongwiththecompiledclassleforyourownclas s.Theselesareproduced whenyoucompile SimpleAnimationApplet2.java .Assumingthatthenameofyourclass is SlidingCheckerboard ,thenthesourcelefortheWebpageshouldcontainthelines :

PAGE 127

Quiz 113 QuizonChapter3 (answers) 1. Whatisan algorithm ? 2. Explainbrierywhatismeantby\pseudocode"andhowisituse fulinthedevelopment ofalgorithms. 3. Whatisa blockstatement? HowareblockstatementsusedinJavaprograms? 4. Whatisthemaindierencebetweena while loopanda do..while loop? 5. Whatdoesitmeanto prime aloop? 6. Explainwhatismeantbyan animation andhowacomputerdisplaysananimation. 7. Writea for loopthatwillprintoutallthemultiplesof3from3to36,tha tis:36912 1518212427303336. 8. Fillinthefollowing main() routinesothatitwillasktheusertoenteraninteger,read theuser'sresponse,andtelltheuserwhetherthenumberent eredisevenorodd.(Youcan use TextIO.getInt() toreadtheinteger.Recallthataninteger n isevenif n%2==0 .) publicstaticvoidmain(String[]args){ //Fillinthebodyofthissubroutine! } 9. Supposethat s1 and s2 arevariablesoftype String ,whosevaluesareexpectedtobe stringrepresentationsofvaluesoftype int .Writeacodesegmentthatwillcomputeand printtheintegersumofthosevalues,orwillprintanerrorm essageifthevaluescannot successfullybeconvertedintointegers.(Usea try..catch statement.) 10. Showtheexactoutputthatwouldbeproducedbythefollowing main() routine: publicstaticvoidmain(String[]args){ intN;N=1;while(N<=32){ N=2*N;System.out.println(N); } } 11. Showtheexactoutputproducedbythefollowing main() routine: publicstaticvoidmain(String[]args){ intx,y;x=5;y=1;while(x>0){ x=x-1;y=y*x;System.out.println(y); } }

PAGE 128

Quiz 114 12. Whatoutputisproducedbythefollowingprogramsegment? Why? (Recallthat name.charAt(i) isthei-thcharacterinthestring, name .) Stringname;inti;booleanstartWord;name="RichardM.Nixon";startWord=true;for(i=0;i
PAGE 129

Chapter4ProgrammingintheLargeI:SubroutinesO newaytobreakupacomplexprogram intomanageablepiecesistouse subroutines Asubroutineconsistsoftheinstructionsforcarryingouta certaintask,groupedtogetherand givenaname.Elsewhereintheprogram,thatnamecanbeuseda sastand-inforthewholeset ofinstructions.Asacomputerexecutesaprogram,whenever itencountersasubroutinename, itexecutesalltheinstructionsnecessarytocarryoutthet askassociatedwiththatsubroutine. Subroutinescanbeusedoverandover,atdierentplacesint heprogram.Asubroutine canevenbeusedinsideanothersubroutine.Thisallowsyout owritesimplesubroutinesand thenusethemtohelpwritemorecomplexsubroutines,whichc anthenbeusedinturninother subroutines.Inthisway,verycomplexprogramscanbebuilt upstep-by-step,whereeachstep intheconstructionisreasonablysimple. Asmentionedin Section3.8 ,subroutinesinJavacanbeeitherstaticornon-static.Thi s chaptercoversstaticsubroutinesonly.Non-staticsubrou tines,whichareusedintrueobjectorientedprogramming,willbecoveredinthenextchapter.4.1BlackBoxesA subroutineconsistsofinstructions forperformingsometask,chunkedtogetherand (online) givenaname.\Chunking"allowsyoutodealwithapotentiall yverycomplicatedtaskas asingleconcept.Insteadofworryingaboutthemany,manyst epsthatthecomputermight havetogothoughtoperformthattask,youjustneedtorememb erthenameofthesubroutine. Wheneveryouwantyourprogramtoperformthetask,youjustc allthesubroutine.Subroutines areamajortoolfordealingwithcomplexity. Asubroutineissometimessaidtobea\blackbox"becauseyou can'tseewhat's\inside" it(or,tobemoreprecise,youusuallydon't want toseeinsideit,becausethenyouwould havetodealwithallthecomplexitythatthesubroutineisme anttohide).Ofcourse,ablack boxthathasnowayofinteractingwiththerestoftheworldwo uldbeprettyuseless.Ablack boxneedssomekindof interface withtherestoftheworld,whichallowssomeinteraction betweenwhat'sinsidetheboxandwhat'soutside.Aphysical blackboxmighthavebuttons ontheoutsidethatyoucanpush,dialsthatyoucanset,andsl otsthatcanbeusedforpassing informationbackandforth.Sincewearetryingtohidecompl exity,notcreateit,wehavethe rstruleofblackboxes: 115

PAGE 130

CHAPTER4.SUBROUTINES 116 Theinterfaceofablackboxshouldbefairlystraightforward,well-dened,andeasytounderstand. Arethereanyexamplesofblackboxesintherealworld?Yes;i nfact,youaresurroundedby them.Yourtelevision,yourcar,yourVCR,yourrefrigerato r....Youcanturnyourtelevision onando,changechannels,andsetthevolumebyusingelemen tsofthetelevision'sinterface| dials,remotecontrol,don'tforgettopluginthepower|wit houtunderstandinganythingabout howthethingactuallyworks.ThesamegoesforaVCR,althoug hifthestoriesaretrueabout howhardpeoplendittosetthetimeonaVCR,thenmaybetheVC Rviolatesthesimple interfacerule. Now,ablackboxdoeshaveaninside|thecodeinasubroutinet hatactuallyperforms thetask,alltheelectronicsinsideyourtelevisionset.Th einsideofablackboxiscalledits implementation .Thesecondruleofblackboxesisthat: Touseablackbox,youshouldn'tneedtoknowanythingaboutitsimplementation;allyouneedtoknowisitsinterface. Infact,itshouldbepossibleto change theimplementation,aslongasthebehaviorofthe box,asseenfromtheoutside,remainsunchanged.Forexampl e,whentheinsidesofTVsets wentfromusingvacuumtubestousingtransistors,theusers ofthesetsdidn'tevenneedto knowaboutit|orevenknowwhatitmeans.Similarly,itshoul dbepossibletorewritethe insideofasubroutine,tousemoreecientcode,forexample ,withoutaectingtheprograms thatusethatsubroutine. Ofcourse,tohaveablackbox,someonemusthavedesignedand builttheimplementation intherstplace.Theblackboxideaworkstotheadvantageof theimplementoraswellas oftheuseroftheblackbox.Afterall,theblackboxmightbeu sedinanunlimitednumber ofdierentsituations.Theimplementoroftheblackboxdoe sn'tneedtoknowaboutanyof that.Theimplementorjustneedstomakesurethattheboxper formsitsassignedtaskand interfacescorrectlywiththerestoftheworld.Thisisthet hirdruleofblackboxes: Theimplementorofablackboxshouldnotneedto knowanythingaboutthelargersystemsinwhichtheboxwillbeused. Inaway,ablackboxdividestheworldintotwoparts:theinsi de(implementation)andthe outside.Theinterfaceisattheboundary,connectingthose twoparts. Bytheway,youshould not thinkofaninterfaceasjustthephysicalconnectionbetwee n theboxandtherestoftheworld.Theinterfacealsoincludes a specication ofwhatthe boxdoesandhowitcanbecontrolledbyusingtheelementsoft hephysicalinterface.It'snot enoughtosaythataTVsethasapowerswitch;youneedtospeci fythatthepowerswitchis usedtoturntheTVonando! Toputthisincomputerscienceterms,theinterfaceofasubr outinehasasemanticaswell asasyntacticcomponent.Thesyntacticpartoftheinterfac etellsyoujustwhatyouhave totypeinordertocallthesubroutine.Thesemanticcompone ntspeciesexactlywhattask thesubroutinewillaccomplish.Towritealegalprogram,yo uneedtoknowthesyntactic specicationofthesubroutine.Tounderstandthepurposeo fthesubroutineandtouseit eectively,youneedtoknowthesubroutine'ssemanticspec ication.Iwillrefertobothparts oftheinterface|syntacticandsemantic|collectivelyast he contract ofthesubroutine.

PAGE 131

CHAPTER4.SUBROUTINES 117 Thecontractofasubroutinesays,essentially,\Hereiswha tyouhavetodotouseme, andhereiswhatIwilldoforyou,guaranteed."Whenyouwrite asubroutine,thecomments thatyouwriteforthesubroutineshouldmakethecontractve ryclear.(Ishouldadmitthat inpractice,subroutines'contractsareofteninadequatel yspecied,muchtotheregretand annoyanceoftheprogrammerswhohavetousethem.) Fortherestofthischapter,Iturnfromgeneralideasaboutb lackboxesandsubroutines ingeneraltothespecicsofwritingandusingsubroutinesi nJava.Butkeepthegeneralideas andprinciplesinmind.Theyarethereasonsthatsubroutine sexistintherstplace,andthey areyourguidelinesforusingthem.Thisshouldbeespeciall yclearin Section4.6 ,whereIwill discusssubroutinesasatoolinprogramdevelopment. Youshouldkeepinmindthatsubroutinesarenottheonlyexam pleofblackboxesin programming.Forexample,aclassisalsoablackbox.We'lls eethataclasscanhavea \public"part,representingitsinterface,anda\private" partthatisentirelyinsideitshidden implementation.Alltheprinciplesofblackboxesapplytoc lassesaswellastosubroutines. 4.2StaticSubroutinesandStaticVariablesE verysubroutineinJava mustbedenedinsidesomeclass.ThismakesJavarather (online) unusualamongprogramminglanguages,sincemostlanguages allowfree-roating,independent subroutines.Onepurposeofaclassistogrouptogetherrela tedsubroutinesandvariables. PerhapsthedesignersofJavafeltthateverythingmustbere latedtosomething.Asaless philosophicalmotivation,Java'sdesignerswantedtoplac ermcontrolsonthewaysthingsare named,sinceaJavaprogrampotentiallyhasaccesstoahugen umberofsubroutinescreatedby manydierentprogrammers.Thefactthatthosesubroutines aregroupedintonamedclasses (andclassesaregroupedintonamed\packages")helpscontr oltheconfusionthatmightresult fromsomanydierentnames. Asubroutinethatisamemberofaclassisoftencalleda method ,and\method"isthe termthatmostpeoplepreferforsubroutinesinJava.Iwills tartusingtheterm\method" occasionally;however,Iwillcontinuetopreferthemorege neralterm\subroutine"forstatic subroutines.Iwillusetheterm\method"mostoftentorefer tonon-staticsubroutines,which belongtoobjectsratherthantoclasses.Thischapterwilld ealwithstaticsubroutinesalmost exclusively.We'llturntonon-staticmethodsandobject-o rientedprogramminginthenext chapter.4.2.1SubroutineDenitionsAsubroutinedenitioninJavatakestheform: h modifiers ih return-type ih subroutine-name i ( h parameter-list i ){ h statements i } Itwilltakeusawhile|mostofthechapter|togetthroughwha tallthismeansindetail.Of course,you'vealreadyseenexamplesofsubroutinesinprev iouschapters,suchasthe main() routineofaprogramandthe paint() routineofanapplet.Soyouarefamiliarwiththegeneral format. The h statements i betweenthebraces, { and } ,inasubroutinedenitionmakeupthe body ofthesubroutine.Thesestatementsaretheinside,orimple mentationpart,ofthe\blackbox",

PAGE 132

CHAPTER4.SUBROUTINES 118 asdiscussedintheprevioussection.Theyaretheinstructi onsthatthecomputerexecuteswhen themethodiscalled.Subroutinescancontainanyofthestat ementsdiscussedin Chapter2 and Chapter3 The h modiers i thatcanoccuratthebeginningofasubroutinedenitionare wordsthat setcertaincharacteristicsofthesubroutine,suchaswhet heritisstaticornot.Themodiers thatyou'veseensofarare\ static "and\ public ".Thereareonlyaboutahalf-dozenpossible modiersaltogether. Ifthesubroutineisafunction,whosejobistocomputesomev alue,thenthe h return-type i is usedtospecifythetypeofvaluethatisreturnedbythefunct ion.We'llbelookingatfunctions andreturntypesinsomedetailin Section4.4 .Ifthesubroutineisnotafunction,thenthe h return-type i isreplacedbythespecialvalue void ,whichindicatesthatnovalueisreturned. Theterm\void"ismeanttoindicatethatthereturnvalueise mptyornon-existent. Finally,wecometothe h parameter-list i ofthemethod.Parametersarepartoftheinterface ofasubroutine.Theyrepresentinformationthatispassedi ntothesubroutinefromoutside, tobeusedbythesubroutine'sinternalcomputations.Forac oncreteexample,imagineaclass named Television thatincludesamethodnamed changeChannel() .Theimmediatequestion is:Whatchannelshoulditchangeto?Aparametercanbeusedt oanswerthisquestion.Since thechannelnumberisaninteger,thetypeoftheparameterwo uldbe int ,andthedeclaration ofthe changeChannel() methodmightlooklike publicvoidchangeChannel(intchannelNum){...} Thisdeclarationspeciesthat changeChannel() hasaparameternamed channelNum oftype int .However, channelNum doesnotyethaveanyparticularvalue.Avaluefor channelNum is providedwhenthesubroutineiscalled;forexample: changeChannel(17); Theparameterlistinasubroutinecanbeempty,oritcancons istofoneormoreparameter declarationsoftheform h type ih parameter-name i .Ifthereareseveraldeclarations,theyare separatedbycommas.Notethateachdeclarationcannameonl yoneparameter.Forexample, ifyouwanttwoparametersoftype double ,youhavetosay\ doublex,doubley ",rather than\ doublex,y ". Parametersarecoveredinmoredetailinthenextsection.Hereareafewexamplesofsubroutinedenitions,leavingou tthestatementsthatdene whatthesubroutinesdo: publicstaticvoidplayGame(){ //"public"and"static"aremodifiers;"void"isthe//return-type;"playGame"isthesubroutine-name;//theparameter-listisempty....//StatementsthatdefinewhatplayGamedoesgohere. }intgetNextN(intN){ //Therearenomodifiers;"int"inthereturn-type//"getNextN"isthesubroutine-name;theparameter-list//includesoneparameterwhosenameis"N"andwhose//typeis"int"....//StatementsthatdefinewhatgetNextNdoesgohere. }staticbooleanlessThan(doublex,doubley){ //"static"isamodifier;"boolean"isthe//return-type;"lessThan"isthesubroutine-name;the

PAGE 133

CHAPTER4.SUBROUTINES 119 //parameter-listincludestwoparameterswhosenamesare//"x"and"y",andthetypeofeachoftheseparameters//is"double"....//StatementsthatdefinewhatlessThandoesgohere. } Inthesecondexamplegivenhere, getNextN isanon-staticmethod,sinceitsdenitiondoes notincludethemodier\ static "|andsoit'snotanexamplethatweshouldbelookingatin thischapter!Theothermodiershownintheexamplesis\ public ".Thismodierindicates thatthemethodcanbecalledfromanywhereinaprogram,even fromoutsidetheclasswhere themethodisdened.Thereisanothermodier,\ private ",whichindicatesthatthemethod canbecalled only frominsidethesameclass.Themodiers public and private arecalled accessspeciers .Ifnoaccessspecierisgivenforamethod,thenbydefault, thatmethod canbecalledfromanywhereinthe\package"thatcontainsth eclass,butnotfromoutside thatpackage.(Packageswereintroducedin Subsection2.6.4 ,andyou'lllearnmoreaboutthem laterinthischapter,in Section4.5 .)Thereisoneotheraccessmodier, protected ,whichwill onlybecomerelevantwhenweturntoobject-orientedprogra mmingin Chapter5 Note,bytheway,thatthe main() routineofaprogramfollowstheusualsyntaxrulesfor asubroutine.In publicstaticvoidmain(String[]args){...} themodiersare public and static ,thereturntypeis void ,thesubroutinenameis main ,and theparameterlistis\ String[]args ".Theonlyquestionmightbeabout\ String[] ",which hastobeatypeifitistomatchthesyntaxofaparameterlist. Infact, String[] represents aso-called\arraytype",sothesyntaxisvalid.Wewillcove rarraysin Chapter7 .(The parameter, args ,representsinformationprovidedtotheprogramwhenthe main() routineis calledbythesystem.Incaseyouknowtheterm,theinformati onconsistsofany\command-line arguments"speciedinthecommandthattheusertypedtorun theprogram.) You'vealreadyhadsomeexperiencewithllingintheimplem entationofasubroutine.In thischapter,you'lllearnallaboutwritingyourowncomple tesubroutinedenitions,including theinterfacepart.4.2.2CallingSubroutinesWhenyoudeneasubroutine,allyouaredoingistellingthec omputerthatthesubroutine existsandwhatitdoes.Thesubroutinedoesn'tactuallyget executeduntilitiscalled.(This istrueevenforthe main() routineinaclass|eventhough you don'tcallit,itiscalledbythe systemwhenthesystemrunsyourprogram.)Forexample,the playGame() methodgivenas anexampleabovecouldbecalledusingthefollowingsubrout inecallstatement: playGame(); Thisstatementcouldoccuranywhereinthesameclassthatin cludesthedenitionof playGame() ,whetherina main() methodorinsomeothersubroutine.Since playGame() isa public method,itcanalsobecalledfromotherclasses,butinthatc ase,youhavetotell thecomputerwhichclassitcomesfrom.Since playGame() isa static method,itsfullname includesthenameoftheclassinwhichitisdened.Let'ssay ,forexample,that playGame() is denedinaclassnamed Poker .Thentocall playGame() from outside the Poker class,you wouldhavetosay Poker.playGame();

PAGE 134

CHAPTER4.SUBROUTINES 120 Theuseoftheclassnameheretellsthecomputerwhichclasst olookintondthemethod.It alsoletsyoudistinguishbetween Poker.playGame() andotherpotential playGame() methods denedinotherclasses,suchas Roulette.playGame() or Blackjack.playGame() Moregenerally,a subroutinecallstatement fora static subroutinetakestheform h subroutine-name i ( h parameters i ); ifthesubroutinethatisbeingcalledisinthesameclass,or h class-name i h subroutine-name i ( h parameters i ); ifthesubroutineisdenedelsewhere,inadierentclass.( Non-staticmethodsbelongtoobjects ratherthanclasses,andtheyarecalledusingobjectnamesi nsteadofclassnames.Moreon thatlater.)Notethattheparameterlistcanbeempty,asint he playGame() example,butthe parenthesesmustbethereevenifthereisnothingbetweenth em. 4.2.3SubroutinesinProgramsIt'stimetogiveanexampleofwhatacompleteprogramlooksl ike,whenitincludesother subroutinesinadditiontothe main() routine.Let'swriteaprogramthatplaysaguessing gamewiththeuser.Thecomputerwillchoosearandomnumberb etween1and100,andthe userwilltrytoguessit.Thecomputertellstheuserwhether theguessishighorloworcorrect. Iftheusergetsthenumberaftersixguessesorfewer,theuse rwinsthegame.Aftereachgame, theuserhastheoptionofcontinuingwithanothergame. Sinceplayingonegamecanbethoughtofasasingle,coherent task,itmakessensetowrite asubroutinethatwillplayoneguessinggamewiththeuser.T he main() routinewillusea looptocallthe playGame() subroutineoverandover,asmanytimesastheuserwantstopl ay. Weapproachtheproblemofdesigningthe playGame() subroutinethesamewaywewritea main() routine:Startwithanoutlineofthealgorithmandapplyste pwiserenement.Hereis ashortpseudocodealgorithmforaguessinggameprogram: Pickarandomnumberwhilethegameisnotover: Gettheuser'sguessTelltheuserwhethertheguessishigh,low,orcorrect. Thetestforwhetherthegameisoveriscomplicated,sinceth egameendsifeithertheuser makesacorrectguessorthenumberofguessesissix.Asinman ycases,theeasiestthingto doistousea\ while(true) "loopanduse break toendtheloopwheneverwendareason todoso.Also,ifwearegoingtoendthegameaftersixguesses ,we'llhavetokeeptrackofthe numberofguessesthattheuserhasmade.Fillingoutthealgo rithmgives: LetcomputersNumberbearandomnumberbetween1and100LetguessCount=0while(true): Gettheuser'sguessCounttheguessbyadding1toguesscountiftheuser'sguessequalscomputersNumber: Telltheuserhewonbreakoutoftheloop ifthenumberofguessesis6: Telltheuserhelostbreakoutoftheloop iftheuser'sguessislessthancomputersNumber:

PAGE 135

CHAPTER4.SUBROUTINES 121 Telltheusertheguesswaslow elseiftheuser'sguessishigherthancomputersNumber: Telltheusertheguesswashigh WithvariabledeclarationsaddedandtranslatedintoJava, thisbecomesthedenitionofthe playGame() routine.Arandomintegerbetween1and100canbecomputedas (int)(100* Math.random())+1 .I'vecleaneduptheinteractionwiththeusertomakeitrowb etter. staticvoidplayGame(){ intcomputersNumber;//Arandomnumberpickedbythecomput er. intusersGuess;//Anumberenteredbyuserasaguess.intguessCount;//Numberofguessestheuserhasmade.computersNumber=(int)(100*Math.random())+1; //ThevalueassignedtocomputersNumberisarandomly//chosenintegerbetween1and100,inclusive. guessCount=0;TextIO.putln();TextIO.put("Whatisyourfirstguess?");while(true){ usersGuess=TextIO.getInt();//Gettheuser'sguess.guessCount++;if(usersGuess==computersNumber){ TextIO.putln("Yougotitin"+guessCount +"guesses!Mynumberwas"+computersNumber); break;//Thegameisover;theuserhaswon. }if(guessCount==6){ TextIO.putln("Youdidn'tgetthenumberin6guesses.");TextIO.putln("Youlose.Mynumberwas"+computersNumber) ; break;//Thegameisover;theuserhaslost. }//Ifwegettothispoint,thegamecontinues.//Telltheuseriftheguesswastoohighortoolow.if(usersGuesscomputersNumber) TextIO.put("That'stoohigh.Tryagain:"); }TextIO.putln(); }//endofplayGame() Now,whereexactlyshouldyouputthis?Itshouldbepartofth esameclassasthe main() routine,but not insidethemainroutine.Itisnotlegaltohaveonesubroutin ephysically nestedinsideanother.The main() routinewill call playGame() ,butnotcontainitphysically. Youcanputthedenitionof playGame() eitherbeforeorafterthe main() routine.Javaisnot verypickyabouthavingthemembersofaclassinanyparticul arorder. It'sprettyeasytowritethemainroutine.You'vedonething slikethisbefore.Here'swhat thecompleteprogramlookslike(exceptthataseriousprogr amneedsmorecommentsthanI've includedhere). publicclassGuessingGame{ publicstaticvoidmain(String[]args){ TextIO.putln("Let'splayagame.I'llpickanumberbetween "); TextIO.putln("1and100,andyoutrytoguessit.");

PAGE 136

CHAPTER4.SUBROUTINES 122 booleanplayAgain;do{ playGame();//callsubroutinetoplayonegameTextIO.put("Wouldyouliketoplayagain?");playAgain=TextIO.getlnBoolean(); }while(playAgain);TextIO.putln("Thanksforplaying.Goodbye."); }//endofmain()staticvoidplayGame(){ intcomputersNumber;//Arandomnumberpickedbythecomput er. intusersGuess;//Anumberenteredbyuserasaguess.intguessCount;//Numberofguessestheuserhasmade.computersNumber=(int)(100*Math.random())+1; //ThevalueassignedtocomputersNumberisarandomly//chosenintegerbetween1and100,inclusive. guessCount=0;TextIO.putln();TextIO.put("Whatisyourfirstguess?");while(true){ usersGuess=TextIO.getInt();//Gettheuser'sguess.guessCount++;if(usersGuess==computersNumber){ TextIO.putln("Yougotitin"+guessCount +"guesses!Mynumberwas"+computersNumber); break;//Thegameisover;theuserhaswon. }if(guessCount==6){ TextIO.putln("Youdidn'tgetthenumberin6guesses.");TextIO.putln("Youlose.Mynumberwas"+computersNumber) ; break;//Thegameisover;theuserhaslost. }//Ifwegettothispoint,thegamecontinues.//Telltheuseriftheguesswastoohighortoolow.if(usersGuesscomputersNumber) TextIO.put("That'stoohigh.Tryagain:"); }TextIO.putln(); }//endofplayGame() }//endofclassGuessingGame Takesometimetoreadtheprogramcarefullyandgureouthow itworks.Andtryto convinceyourselfthateveninthisrelativelysimplecase, breakinguptheprogramintotwo methodsmakestheprogrameasiertounderstandandprobably madeiteasiertowriteeach piece.4.2.4MemberVariablesAclasscanincludeotherthingsbesidessubroutines.Inpar ticular,itcanalsoincludevariable declarations.Ofcourse,youcandeclarevariables inside subroutines.Thosearecalled local variables. However,youcanalsohavevariablesthatarenotpartofanys ubroutine.To

PAGE 137

CHAPTER4.SUBROUTINES 123 distinguishsuchvariablesfromlocalvariables,wecallth em membervariables ,sincethey aremembersofaclass. Justaswithsubroutines,membervariablescanbeeithersta ticornon-static.Inthis chapter,we'llsticktostaticvariables.Astaticmemberva riablebelongstotheclassitself,and itexistsaslongastheclassexists.Memoryisallocatedfor thevariablewhentheclassisrst loadedbytheJavainterpreter.Anyassignmentstatementth atassignsavaluetothevariable changesthecontentofthatmemory,nomatterwherethatassi gnmentstatementislocatedin theprogram.Anytimethevariableisusedinanexpression,t hevalueisfetchedfromthat samememory,nomatterwheretheexpressionislocatedinthe program.Thismeansthatthe valueofastaticmembervariablecanbesetinonesubroutine andusedinanothersubroutine. Staticmembervariablesare\shared"byallthestaticsubro utinesintheclass.Alocalvariable inasubroutine,ontheotherhand,existsonlywhilethatsub routineisbeingexecuted,andis completelyinaccessiblefromoutsidethatonesubroutine. Thedeclarationofamembervariablelooksjustlikethedecl arationofalocalvariable exceptfortwothings:Themembervariableisdeclaredoutsi deanysubroutine(althoughit stillhastobeinsideaclass),andthedeclarationcanbemar kedwithmodierssuchas static public ,and private .Sinceweareonlyworkingwithstaticmembervariablesforn ow,every declarationofamembervariableinthischapterwillinclud ethemodier static .Theymight alsobemarkedas public or private .Forexample: staticStringusersName;publicstaticintnumberOfPlayers;privatestaticdoublevelocity,time; Astaticmembervariablethatisnotdeclaredtobe private canbeaccessedfromoutside theclasswhereitisdened,aswellasinside.Whenitisused insomeotherclass,itmustbe referredtowithacompoundidentieroftheform h class-name i h variable-name i .Forexample, the System classcontainsthepublicstaticmembervariablenamed out ,andyouusethis variableinyourownclassesbyreferringto System.out .If numberOfPlayers isapublic staticmembervariableinaclassnamed Poker ,thensubroutinesinthe Poker classwould refertoitsimplyas numberOfPlayers ,whilesubroutinesinanotherclasswouldrefertoitas Poker.numberOfPlayers Asanexample,let'saddastaticmembervariabletothe GuessingGame classthatwewrote earlierinthissection.Thisvariablewillbeusedtokeeptr ackofhowmanygamestheuserwins. We'llcallthevariable gamesWon anddeclareitwiththestatement\ staticintgamesWon; ". Inthe playGame() routine,weadd1to gamesWon iftheuserwinsthegame.Attheendofthe main() routine,weprintoutthevalueof gamesWon .Itwouldbeimpossibletodothesame thingwithalocalvariable,sinceweneedaccesstothesamev ariablefrombothsubroutines. Whenyoudeclarealocalvariableinasubroutine,youhaveto assignavaluetothatvariable beforeyoucandoanythingwithit.Membervariables,ontheo therhandareautomatically initializedwithadefaultvalue.Fornumericvariables,th edefaultvalueiszero.For boolean variables,thedefaultis false .Andfor char variables,it'stheunprintablecharacterthathas Unicodecodenumberzero.(Forobjects,suchas Strings ,thedefaultinitialvalueisaspecial valuecalled null ,whichwewon'tencounterociallyuntillater.) Sinceitisoftype int ,thestaticmembervariable gamesWon automaticallygetsassignedan initialvalueofzero.Thishappenstobethecorrectinitial valueforavariablethatisbeing usedasacounter.Youcan,ofcourse,assignadierentvalue tothevariableatthebeginning ofthe main() routineifyouarenotsatisedwiththedefaultinitialvalu e.

PAGE 138

CHAPTER4.SUBROUTINES 124 Here'sarevisedversionof GuessingGame.java thatincludesthe gamesWon variable.The changesfromtheaboveversionareshowninitalic: publicclassGuessingGame2{ staticintgamesWon;//Thenumberofgameswonby //theuser. publicstaticvoidmain(String[]args){ gamesWon=0;//Thisisactuallyredundant,since0is //thedefaultinitialvalue. TextIO.putln("Let'splayagame.I'llpickanumberbetween "); TextIO.putln("1and100,andyoutrytoguessit.");booleanplayAgain;do{ playGame();//callsubroutinetoplayonegameTextIO.put("Wouldyouliketoplayagain?");playAgain=TextIO.getlnBoolean(); }while(playAgain);TextIO.putln();TextIO.putln("Youwon"+gamesWon+"games.");TextIO.putln("Thanksforplaying.Goodbye."); }//endofmain()staticvoidplayGame(){ intcomputersNumber;//Arandomnumberpickedbythecomput er. intusersGuess;//Anumberenteredbyuserasaguess.intguessCount;//Numberofguessestheuserhasmade.computersNumber=(int)(100*Math.random())+1; //ThevalueassignedtocomputersNumberisarandomly//chosenintegerbetween1and100,inclusive. guessCount=0;TextIO.putln();TextIO.put("Whatisyourfirstguess?");while(true){ usersGuess=TextIO.getInt();//Gettheuser'sguess.guessCount++;if(usersGuess==computersNumber){ TextIO.putln("Yougotitin"+guessCount +"guesses!Mynumberwas"+computersNumber); gamesWon++;//CountthisgamebyincrementinggamesWon.break;//Thegameisover;theuserhaswon. }if(guessCount==6){ TextIO.putln("Youdidn'tgetthenumberin6guesses.");TextIO.putln("Youlose.Mynumberwas"+computersNumber) ; break;//Thegameisover;theuserhaslost. }//Ifwegettothispoint,thegamecontinues.//Telltheuseriftheguesswastoohighortoolow.if(usersGuesscomputersNumber) TextIO.put("That'stoohigh.Tryagain:"); }

PAGE 139

CHAPTER4.SUBROUTINES 125 TextIO.putln(); }//endofplayGame() }//endofclassGuessingGame2 4.3ParametersI fasubroutineisablackbox ,thenaparameterprovidesamechanismforpassinginfor(online) mationfromtheoutsideworldintothebox.Parametersarepa rtoftheinterfaceofasubroutine. Theyallowyoutocustomizethebehaviorofasubroutinetoad aptittoaparticularsituation. Asananalogy,considerathermostat|ablackboxwhosetaski tistokeepyourhouse atacertaintemperature.Thethermostathasaparameter,na melythedialthatisusedto setthedesiredtemperature.Thethermostatalwaysperform sthesametask:maintaininga constanttemperature.However,theexacttaskthatitperfo rms|thatis, which temperature itmaintains|iscustomizedbythesettingonitsdial.4.3.1UsingParametersAsanexample,let'sgobacktothe\3N+1"problemthatwasdis cussedin Subsection3.2.2 (Recallthata3N+1sequenceiscomputedaccordingtotherul e,\ifNisodd,multiplyby3 andadd1;ifNiseven,divideby2;continueuntilNisequalto 1."Forexample,startingfrom N=3wegetthesequence:3,10,5,16,8,4,2,1.)Supposethatw ewanttowriteasubroutine toprintoutsuchsequences.Thesubroutinewillalwaysperf ormthesametask:Printouta 3N+1sequence.Buttheexactsequenceitprintsoutdependso nthestartingvalueofN.So,the startingvalueofNwouldbeaparametertothesubroutine.Th esubroutinecouldbewritten likethis: /** *Thissubroutineprintsa3N+1sequencetostandardoutput, using *startingValueastheinitialvalueofN.Italsoprintsthen umber *oftermsinthesequence.Thevalueoftheparameter,starti ngValue, *mustbeapositiveinteger.*/ staticvoidprint3NSequence(intstartingValue){ intN;//Oneofthetermsinthesequence.intcount;//Thenumberofterms.N=startingValue;//Thefirsttermiswhatevervalue //ispassedtothesubroutineas//aparameter. intcount=1;//Wehaveoneterm,thestartingvalue,sofar.System.out.println("The3N+1sequencestartingfrom"+N) ; System.out.println();System.out.println(N);//printinitialtermofsequencewhile(N>1){ if(N%2==1)//isNodd? N=3*N+1; else N=N/2;

PAGE 140

CHAPTER4.SUBROUTINES 126 count++;//countthistermSystem.out.println(N);//printthisterm }System.out.println();System.out.println("Therewere"+count+"termsintheseq uence."); }//endprint3NSequence Theparameterlistofthissubroutine,\ (intstartingValue) ",speciesthatthesubroutine hasoneparameter,oftype int .Withinthebodyofthesubroutine,theparameternamecan beusedinthesamewayasavariablename.However,theparame tergetsitsinitialvalue from outside thesubroutine.Whenthesubroutineiscalled,avaluemustb eprovidedfor thisparameterinthesubroutinecallstatement.Thisvalue willbeassignedtotheparameter, startingValue ,beforethebodyofthesubroutineisexecuted.Forexample, thesubroutinecouldbecalledusingthesubroutinecallstatement\ print3NSequence(17); ".Whenthe computerexecutesthisstatement,thecomputerassignsthe value17to startingValue and thenexecutesthestatementsinthesubroutine.Thisprints the3N+1sequencestartingfrom 17.If K isavariableoftype int ,thenwhenthecomputerexecutesthesubroutinecallstatement\ print3NSequence(K); ",itwilltakethevalueofthevariable K ,assignthatvalueto startingValue ,andexecutethebodyofthesubroutine. Theclassthatcontains print3NSequence cancontaina main() routine(orothersubroutines)thatcall print3NSequence .Forexample,hereisa main() programthatprintsout3N+1 sequencesforvariousstartingvaluesspeciedbytheuser: publicstaticvoidmain(String[]args){ TextIO.putln("Thisprogramwillprintout3N+1sequences" ); TextIO.putln("forstartingvaluesthatyouspecify.");TextIO.putln();intK;//Inputfromuser;loopendswhenK<0.do{ TextIO.putln("Enterastartingvalue;")TextIO.put("Toendtheprogram,enter0:");K=TextIO.getInt();//Getstartingvaluefromuser.if(K>0)//Printsequence,butonlyifKis>0. print3NSequence(K); }while(K>0);//ContinueonlyifK>0. }//endmain Rememberthatbeforeyoucanusethisprogram,thedenition sof main andof print3NSequence mustbothbewrappedinsideaclassdenition. 4.3.2FormalandActualParametersNotethattheterm\parameter"isusedtorefertotwodieren t,butrelated,concepts.There areparametersthatareusedinthedenitionsofsubroutine s,suchas startingValue inthe aboveexample.Andthereareparametersthatareusedinsubr outinecallstatements,such asthe K inthestatement\ print3NSequence(K); ".Parametersinasubroutinedenitionare called formalparameters or dummyparameters .Theparametersthatarepassedtoa subroutinewhenitiscalledarecalled actualparameters or arguments .Whenasubroutine iscalled,theactualparametersinthesubroutinecallstat ementareevaluatedandthevalues areassignedtotheformalparametersinthesubroutine'sde nition.Thenthebodyofthe subroutineisexecuted.

PAGE 141

CHAPTER4.SUBROUTINES 127 Aformalparametermustbea name ,thatis,asimpleidentier.Aformalparameteris verymuchlikeavariable,and|likeavariable|ithasaspeci edtypesuchas int boolean ,or String .Anactualparameterisa value ,andsoitcanbespeciedbyanyexpression,provided thattheexpressioncomputesavalueofthecorrecttype.The typeoftheactualparametermust beonethatcouldlegallybeassignedtotheformalparameter withanassignmentstatement. Forexample,iftheformalparameterisoftype double ,thenitwouldbelegaltopassan int as theactualparametersince int scanlegallybeassignedto double s.Whenyoucallasubroutine, youmustprovideoneactualparameterforeachformalparame terinthesubroutine'sdenition. Consider,forexample,asubroutine staticvoiddoTask(intN,doublex,booleantest){ //statementstoperformthetaskgohere } Thissubroutinemightbecalledwiththestatement doTask(17,Math.sqrt(z+1),z>=10); Whenthecomputerexecutesthisstatement,ithasessential lythesameeectastheblockof statements: { intN;//Allocatememorylocationsfortheformalparameter s. doublex;booleantest;N=17;//Assign17tothefirstformalparameter,N.x=Math.sqrt(z+1);//ComputeMath.sqrt(z+1),andassigni tto //thesecondformalparameter,x. test=(z>=10);//Evaluate"z>=10"andassigntheresulting //true/falsevaluetothethirdformal//parameter,test. //statementstoperformthetaskgohere } (Thereareafewtechnicaldierencesbetweenthisand\ doTask(17,Math.sqrt(z+1),z>=10); |besidestheamountoftyping|becauseofquestionsaboutsc opeofvariablesandwhathappenswhenseveralvariablesorparametershavethesamename .) Beginningprogrammingstudentsoftenndparameterstobes urprisinglyconfusing.Callingasubroutinethatalreadyexistsisnotaproblem|theide aofprovidinginformationtothe subroutineinaparameterisclearenough.Writingthesubro utinedenitionisanothermatter. Acommonmistakeistoassignvaluestotheformalparameters atthebeginningofthesubroutine,ortoasktheusertoinputtheirvalues.Thisrepresent safundamentalmisunderstanding. Whenthestatementsinthesubroutineareexecuted,theform alparameterswillalreadyhave values.Thevaluescomefromthesubroutinecallstatement. Rememberthatasubroutineis notindependent.Itiscalledbysomeotherroutine,anditis thecallingroutine'sresponsibility toprovideappropriatevaluesfortheparameters.4.3.3OverloadingInordertocallasubroutinelegally,youneedtoknowitsnam e,youneedtoknowhowmany formalparametersithas,andyouneedtoknowthetypeofeach parameter.Thisinformationis calledthesubroutine's signature .Thesignatureofthesubroutine doTask ,usedasanexample above,canbeexpressedasas: doTask(int,double,boolean) .Notethatthesignaturedoes

PAGE 142

CHAPTER4.SUBROUTINES 128 not includethenamesoftheparameters;infact,ifyoujustwant to use thesubroutine,you don'tevenneedtoknowwhattheformalparameternamesare,s othenamesarenotpartof theinterface. Javaissomewhatunusualinthatitallowstwodierentsubro utinesinthesameclassto havethesamename,providedthattheirsignaturesaredier ent.(ThelanguageC++on whichJavaisbasedalsohasthisfeature.)Whenthishappens ,wesaythatthenameofthe subroutineis overloaded becauseithasseveraldierentmeanings.Thecomputerdoes n'tget thesubroutinesmixedup.Itcantellwhichoneyouwanttocal lbythenumberandtypesof theactualparametersthatyouprovideinthesubroutinecal lstatement.Youhavealreadyseen overloadingusedinthe TextIO class.Thisclassincludesmanydierentmethodsnamed putln forexample.Thesemethodsallhavedierentsignatures,su chas: putln(int)putln(double)putln(String)putln(char)putln(boolean)putln() Thecomputerknowswhichofthesesubroutinesyouwanttouse basedonthetype oftheactualparameterthatyouprovide. TextIO.putln(17) callsthesubroutinewith signature putln(int) ,while TextIO.putln("Hello") callsthesubroutinewithsignature putln(String) .Ofcourseallthesedierentsubroutinesaresemantically related,whichis whyitisacceptableprogrammingstyletousethesamenamefo rthemall.Butasfarasthe computerisconcerned,printingoutan int isverydierentfromprintingouta String ,whichis dierentfromprintingouta boolean ,andsoforth|sothateachoftheseoperationsrequires adierentmethod. Note,bytheway,thatthesignaturedoes not includethesubroutine'sreturntype.Itis illegaltohavetwosubroutinesinthesameclassthathaveth esamesignaturebutthathave dierentreturntypes.Forexample,itwouldbeasyntaxerro rforaclasstocontaintwo methodsdenedas: intgetln(){...}doublegetln(){...} Soitshouldbenosurprisethatinthe TextIO class,themethodsforreadingdierenttypes arenotallnamed getln() .Inagivenclass,therecanonlybeoneroutinethathasthena me getln andhasnoparameters.So,theinputroutinesin TextIO aredistinguishedbyhaving dierentnames,suchas getlnInt() and getlnDouble() Java5.0introducedanothercomplication:Itispossibleto haveasinglesubroutinethat takesavariablenumberofactualparameters.Youhavealrea dyusedsubroutinesthatdo this|theformattedoutputroutines System.out.printf and TextIO.putf .Whenyoucall thesesubroutines,thenumberofparametersinthesubrouti necallcanbearbitrarilylarge,so itwouldbeimpossibletohavedierentsubroutinestohandl eeachcase.Unfortunately,writing thedenitionofsuchasubroutinerequiressomeknowledgeo farrays,whichwillnotbecovered until Chapter7 .Whenwegettothatchapter,you'lllearnhowtowritesubrou tineswitha variablenumberofparameters.Fornow,wewillignorethisc omplication. 4.3.4SubroutineExamplesLet'sdoafewexamplesofwritingsmallsubroutinestoperfo rmassignedtasks.Ofcourse, thisisonlyonesideofprogrammingwithsubroutines.Theta skperformedbyasubroutineis alwaysasubtaskinalargerprogram.Theartofdesigningtho seprograms|ofdecidinghowto

PAGE 143

CHAPTER4.SUBROUTINES 129 breakthemupintosubtasks|istheothersideofprogramming withsubroutines.We'llreturn tothequestionofprogramdesignin Section4.6 Asarstexample,let'swriteasubroutinetocomputeandpri ntoutallthedivisorsofa givenpositiveinteger.Theintegerwillbeaparametertoth esubroutine.Rememberthatthe syntaxofanysubroutineis: h modifiers ih return-type ih subroutine-name i ( h parameter-list i ){ h statements i } Writingasubroutinealwaysmeansllingoutthisformat.In thiscase,thestatementofthe problemtellsusthatthereisoneparameter,oftype int ,andittellsuswhatthestatements inthebodyofthesubroutineshoulddo.Sinceweareonlywork ingwithstaticsubroutines fornow,we'llneedtouse static asamodier.Wecouldaddanaccessmodier( public or private ),butintheabsenceofanyinstructions,I'llleaveitout.S incewearenottoldto returnavalue,thereturntypeis void .Sincenonamesarespecied,we'llhavetomakeup namesfortheformalparameterandforthesubroutineitself .I'lluse N fortheparameterand printDivisors forthesubroutinename.Thesubroutinewilllooklike staticvoidprintDivisors(intN){ h statements i } andallwehavelefttodoistowritethestatementsthatmakeu pthebodyoftheroutine.This isnotdicult.Justrememberthatyouhavetowritethebodya ssumingthat N alreadyhas avalue!Thealgorithmis:\Foreachpossibledivisor D intherangefrom 1 to N ,if D evenly divides N ,thenprint D ."WritteninJava,thisbecomes: /** *PrintallthedivisorsofN.*WeassumethatNisapositiveinteger.*/ staticvoidprintDivisors(intN){ intD;//OneofthepossibledivisorsofN.System.out.println("Thedivisorsof"+N+"are:");for(D=1;D<=N;D++){ if(N%D==0) System.out.println(D); } } I'veaddedacommentbeforethesubroutinedenitionindica tingthecontractofthe subroutine|thatis,whatitdoesandwhatassumptionsitmak es.Thecontractincludesthe assumptionthat N isapositiveinteger.Itisuptothecallerofthesubroutine tomakesure thatthisassumptionissatised. Asasecondshortexample,considertheproblem:Writeasubr outinenamed printRow .It shouldhaveaparameter ch oftype char andaparameter N oftype int .Thesubroutineshould printoutalineoftextcontaining N copiesofthecharacter ch Here,wearetoldthenameofthesubroutineandthenamesofth etwoparameters,sowe don'thavemuchchoiceabouttherstlineofthesubroutined enition.Thetaskinthiscaseis prettysimple,sothebodyofthesubroutineiseasytowrite. Thecompletesubroutineisgiven by

PAGE 144

CHAPTER4.SUBROUTINES 130 /** *WriteonelineofoutputcontainingNcopiesofthe*characterch.IfN<=0,anemptylineisoutput.*/ staticvoidprintRow(charch,intN){ inti;//Loop-controlvariableforcountingoffthecopies.for(i=1;i<=N;i++){ System.out.print(ch); }System.out.println(); } Notethatinthiscase,thecontractmakesnoassumptionabou t N ,butitmakesitclearwhat willhappeninallcases,includingtheunexpectedcasethat N<0 Finally,let'sdoanexamplethatshowshowonesubroutineca nbuildonanother.Let's writeasubroutinethattakesa String asaparameter.Foreachcharacterinthestring,itwill printalineofoutputcontaining25copiesofthatcharacter .Itshouldusethe printRow() subroutinetoproducetheoutput. Again,wegettochooseanameforthesubroutineandanamefor theparameter.I'llcall thesubroutine printRowsFromString andtheparameter str .Thealgorithmisprettyclear: Foreachposition i inthestring str ,call printRow(str.charAt(i),25) toprintonelineof theoutput.So,weget: /** *Foreachcharacterinstr,writealineofoutput*containing25copiesofthatcharacter.*/ staticvoidprintRowsFromString(Stringstr){ inti;//Loop-controlvariableforcountingoffthechars.for(i=0;i
PAGE 145

CHAPTER4.SUBROUTINES 131 parameters.Thequestionarises,though,whatshouldthesu broutinedowhenthecallerviolates thecontractbyprovidingbadparametervalues? We'vealreadyseenthatsomesubroutinesrespondtobadpara metervaluesbythrowingexceptions.(See Section3.7 .)Forexample,thecontractofthebuilt-insubroutine Double.parseDouble saysthattheparametershouldbeastringrepresentationof anumberoftype double ;ifthisistrue,thenthesubroutinewillconvertthestring intotheequivalent numericvalue.Ifthecallerviolatesthecontractbypassin ganinvalidstringastheactual parameter,thesubroutinerespondsbythrowinganexceptio noftype NumberFormatException Manysubroutinesthrow IllegalArgumentExceptions inresponsetobadparametervalues. Youmightwanttotakethisresponseinyourownsubroutines. Thiscanbedonewitha throw statement .Anexceptionisanobject,andinordertothrowanexception ,youmustcreate anexceptionobject.Youwon'tociallylearnhowtodothisu ntil Chapter5 ,butfornow,you canusethefollowingsyntaxfora throw statementthatthrowsan IllegalArgumentException : thrownewIllegalArgumentException( h error-message i ); where h error-message i isastringthatdescribestheerrorthathasbeendetected.( Theword \new"inthisstatementiswhatcreatestheobject.)Touseth isstatementinasubroutine, youwouldcheckwhetherthevaluesoftheparametersarelega l.Ifnot,youwouldthrowthe exception.Forexample,considerthe print3NSequence subroutinefromthebeginningofthis section.Theparameterof print3NSequence issupposedtobeapositiveinteger.Wecan modifythesubroutinedenitiontomakeitthrowanexceptio nwhenthisconditionisviolated: staticvoidprint3NSequence(intstartingValue){ if(startingValue < =0)//Thecontractisviolated! thrownewIllegalArgumentException("Startingvaluemust bepositive."); ..//(Therestofthesubroutineisthesameasbefore.). Ifthestartvalueisbad,thecomputerexecutesthe throw statement.Thiswillimmediate terminatethesubroutine,withoutexecutingtherestofthe bodyofthesubroutine.Furthermore,theprogramasawholewillcrashunlesstheexceptioni s\caught"andhandledelsewhere intheprogrambya try..catch statement,asdiscussedin Section3.7 4.3.6GlobalandLocalVariablesI'llnishthissectiononparametersbynotingthatwenowha vethreedierentsortsofvariablesthatcanbeusedinsideasubroutine:localvariablesd eclaredinthesubroutine,formal parameternames,andstaticmembervariablesthataredecla redoutsidethesubroutinebut insidethesameclassasthesubroutine. Localvariableshavenoconnectiontotheoutsideworld;the yarepurelypartoftheinternal workingofthesubroutine.Parametersareusedto\drop"val uesintothesubroutinewhenit iscalled,butoncethesubroutinestartsexecuting,parame tersactmuchlikelocalvariables. Changesmadeinsideasubroutinetoaformalparameterhaven oeectontherestofthe program(atleastifthetypeoftheparameterisoneofthepri mitivetypes|thingsaremore complicatedinthecaseofobjects,aswe'llseelater). Thingsaredierentwhenasubroutineusesavariablethatis denedoutsidethesubroutine. Thatvariableexistsindependentlyofthesubroutine,andi tisaccessibletootherpartsofthe program,aswellastothesubroutine.Suchavariableissaid tobe global tothesubroutine,

PAGE 146

CHAPTER4.SUBROUTINES 132 asopposedtothelocalvariablesdenedinsidethesubrouti ne.Thescopeofaglobalvariable includestheentireclassinwhichitisdened.Changesmade toaglobalvariablecanhaveeects thatextendoutsidethesubroutinewherethechangesaremad e.You'veseenhowthisworks inthelastexampleintheprevioussection,wherethevalueo ftheglobalvariable, gamesWon iscomputedinsideasubroutineandisusedinthe main() routine. It'snotalwaysbadtouseglobalvariablesinsubroutines,b utyoushouldrealizethatthe globalvariablethenhastobeconsideredpartofthesubrout ine'sinterface.Thesubroutine usestheglobalvariabletocommunicatewiththerestofthep rogram.Thisisakindofsneaky, back-doorcommunicationthatislessvisiblethancommunic ationdonethroughparameters, anditrisksviolatingtherulethattheinterfaceofablackb oxshouldbestraightforwardand easytounderstand.Sobeforeyouuseaglobalvariableinasu broutine,youshouldconsider whetherit'sreallynecessary. Idon'tadviseyoutotakeanabsolutestandagainstusingglo balvariablesinsidesubroutines. Thereisatleastonegoodreasontodoit:Ifyouthinkofthecl assasawholeasbeingakind ofblackbox,itcanbeveryreasonabletoletthesubroutines insidethatboxbealittlesneaky aboutcommunicatingwitheachother,ifthatwillmakethecl assasawholelooksimplerfrom theoutside.4.4ReturnValuesA subroutinethatreturnsavalue iscalleda function .Agivenfunctioncanonly (online) returnavalueofaspeciedtype,calledthe returntype ofthefunction.Afunctioncall generallyoccursinapositionwherethecomputerisexpecti ngtondavalue,suchastheright sideofanassignmentstatement,asanactualparameterinas ubroutinecall,orinthemiddle ofsomelargerexpression.Aboolean-valuedfunctioncanev enbeusedasthetestconditionin an if while for or do..while statement. (Itisalsolegaltouseafunctioncallasastand-alonestate ment,justasifitwerearegularsubroutine.Inthiscase,thecomputerignoresthevalu ecomputedbythesubroutine. Sometimesthismakessense.Forexample,thefunction TextIO.getln() ,withareturntype of String ,readsandreturnsalineofinputtypedinbytheuser.Usuall y,thelinethatis returnedisassignedtoavariabletobeusedlaterintheprog ram,asinthestatement\ name =TextIO.getln(); ".However,thisfunctionisalsousefulasasubroutinecall statement \ TextIO.getln(); ",whichstillreadsallinputuptoandincludingthenextcar riagereturn. Sincethereturnvalueisnotassignedtoavariableorusedin anexpression,itissimplydiscarded.So,theeectofthesubroutinecallistoread anddiscard someinput.Sometimes, discardingunwantedinputisexactlywhatyouneedtodo.)4.4.1ThereturnstatementYou'vealreadyseenhowfunctionssuchas Math.sqrt() and TextIO.getInt() canbeused. Whatyouhaven'tseenishowtowritefunctionsofyourown.Af unctiontakesthesameform asaregularsubroutine,exceptthatyouhavetospecifythev aluethatistobereturnedbythe subroutine.Thisisdonewitha returnstatement ,whichhasthefollowingsyntax: return h expression i ; Sucha return statementcanonlyoccurinsidethedenitionofafunction, andthetype ofthe h expression i mustmatchthereturntypethatwasspeciedforthefunction .(More exactly,itmustbelegaltoassigntheexpressiontoavariab lewhosetypeisspeciedbythe

PAGE 147

CHAPTER4.SUBROUTINES 133 returntype.)Whenthecomputerexecutesthis return statement,itevaluatestheexpression, terminatesexecutionofthefunction,andusesthevalueoft heexpressionasthereturnedvalue ofthefunction. Forexample,considerthefunctiondenition staticdoublepythagoras(doublex,doubley){ //Computesthelengthofthehypotenuseofaright//triangle,wherethesidesofthetrianglearexandy. returnMath.sqrt(x*x+y*y); } Supposethecomputerexecutesthestatement\ totalLength=17+pythagoras(12,5); ". Whenitgetstotheterm pythagoras(12,5) ,itassignstheactualparameters 12 and 5 to theformalparameters x and y inthefunction.Inthebodyofthefunction,itevaluates Math.sqrt(12.0*12.0+5.0*5.0) ,whichworksoutto 13.0 .Thisvalueis\returned"bythe function,sothe 13.0 essentiallyreplacesthefunctioncallinthestatement\ totalLength= 17+pythagoras(12,5); ".Thereturnvalueisaddedto 17 ,andtheresult,30.0,isstoredin thevariable, totalLength .Theeectisthesameasifthestatementhadbeen\ totalLength =17+13.0; ". Notethata return statementdoesnothavetobethelaststatementinthefuncti on denition.Atanypointinthefunctionwhereyouknowtheval uethatyouwanttoreturn,you canreturnit.Returningavaluewillendthefunctionimmedi ately,skippinganysubsequent statementsinthefunction.However,itmustbethecasethat thefunctiondenitelydoesreturn somevalue,nomatterwhatpaththeexecutionofthefunction takesthroughthecode. Youcanusea return statementinsideanordinarysubroutine,onewithdeclared return type\ void ".Sinceavoidsubroutinedoesnotreturnavalue,the return statementdoesnot includeanexpression;itsimplytakestheform\ return; ".Theeectofthisstatementisto terminateexecutionofthesubroutineandreturncontrolba cktothepointintheprogramfrom whichthesubroutinewascalled.Thiscanbeconvenientifyo uwanttoterminateexecution somewhereinthemiddleofthesubroutine,but return statementsareoptionalinnon-function subroutines.Inafunction,ontheotherhand,areturnstate ment,withexpression,isalways required.4.4.2FunctionExamplesHereisaverysimplefunctionthatcouldbeusedinaprogramt ocompute3N+1sequences. (The3N+1sequenceproblemisonewe'velookedatseveraltim esalready,includinginthe previoussection).Givenonetermina3N+1sequence,thisfu nctioncomputesthenextterm ofthesequence: staticintnextN(intcurrentN){ if(currentN%2==1)//testifcurrentNisodd return3*currentN+1;//ifso,returnthisvalue else returncurrentN/2;//ifnot,returnthisinstead } Thisfunctionhastwo return statements.Exactlyoneofthetwo return statementsisexecuted togivethevalueofthefunction.Somepeopleprefertouseas ingle return statementatthe veryendofthefunctionwhenpossible.Thisallowsthereade rtondthe return statement easily.Youmightchoosetowrite nextN() likethis,forexample:

PAGE 148

CHAPTER4.SUBROUTINES 134 staticintnextN(intcurrentN){ intanswer;//answerwillbethevaluereturnedif(currentN%2==1)//testifcurrentNisodd answer=3*currentN+1;//ifso,thisistheanswer else answer=currentN/2;//ifnot,thisistheanswer returnanswer;//(Don'tforgettoreturntheanswer!) } Hereisasubroutinethatusesthis nextN function.Inthiscase,theimprovementfromthe versionofthissubroutinein Section4.3 isnotgreat,butif nextN() werealongfunctionthat performedacomplexcomputation,thenitwouldmakealotofs ensetohidethatcomplexity insideafunction: staticvoidprint3NSequence(intstartingValue){ intN;//Oneofthetermsinthesequence.intcount;//Thenumberoftermsfound.N=startingValue;//StartthesequencewithstartingValue count=1;TextIO.putln("The3N+1sequencestartingfrom"+N);TextIO.putln();TextIO.putln(N);//printinitialtermofsequencewhile(N>1){ N=nextN(N);//Computenextterm,usingthefunctionnextN.count++;//Countthisterm.TextIO.putln(N);//Printthisterm. }TextIO.putln();TextIO.putln("Therewere"+count+"termsinthesequence. "); } Hereareafewmoreexamplesoffunctions.Therstonecomput esalettergradecorrespondingtoagivennumericalgrade,onatypicalgradingsca le: /** *Returnsthelettergradecorrespondingtothenumerical*gradethatispassedtothisfunctionasaparameter.*/ staticcharletterGrade(intnumGrade){ if(numGrade>=90) return'A';//90orabovegetsanA elseif(numGrade>=80) return'B';//80to89getsaB elseif(numGrade>=65) return'C';//65to79getsaC elseif(numGrade>=50) return'D';//50to64getsaD else

PAGE 149

CHAPTER4.SUBROUTINES 135 return'F';//anythingelsegetsanF }//endoffunctionletterGrade Thetypeofthereturnvalueof letterGrade() is char .Functionscanreturnvaluesofany typeatall.Here'safunctionwhosereturnvalueisoftype boolean .Itdemonstratessome interestingprogrammingpoints,soyoushouldreadthecomm ents: /** *ThefunctionreturnstrueifNisaprimenumber.Aprimenumb er *isanintegergreaterthan1thatisnotdivisiblebyanyposi tive *integer,exceptitselfand1.IfNhasanydivisor,D,inther ange *1=0;i--){

PAGE 150

CHAPTER4.SUBROUTINES 136 //Appendi-thcharofstrtocopy. copy=copy+str.charAt(i); }returncopy; } A palindrome isastringthatreadsthesamebackwardsandforwards,sucha s\radar".The reverse() functioncouldbeusedtocheckwhetherastring, word ,isapalindromebytesting \ if(word.equals(reverse(word))) ". Bytheway,atypicalbeginner'serrorinwritingfunctionsi stoprintouttheanswer,instead ofreturningit.Thisrepresentsafundamentalmisundersta nding.Thetaskofafunctionisto computeavalueandreturnittothepointintheprogramwhere thefunctionwascalled.That's wherethevalueisused.Maybeitwillbeprintedout.Maybeit willbeassignedtoavariable. Maybeitwillbeusedinanexpression.Butit'snotforthefun ctiontodecide. 4.4.33N+1RevisitedI'llnishthissectionwithacompletenewversionofthe3N+ 1program.Thiswillgivemea chancetoshowthefunction nextN() ,whichwasdenedabove,usedinacompleteprogram. I'llalsotaketheopportunitytoimprovetheprogrambygett ingittoprintthetermsofthe sequenceincolumns,withvetermsoneachline.Thiswillma ketheoutputmorepresentable. Thisideaisthis:Keeptrackofhowmanytermshavebeenprint edonthecurrentline;when thatnumbergetsupto5,startanewlineofoutput.Tomakethe termslineupintoneat columns,Iuseformattedoutput. /** *Aprogramthatcomputesanddisplaysseveral3N+1sequence s.Starting *valuesforthesequencesareinputbytheuser.Termsinthes equence *areprintedincolumns,withfivetermsoneachlineofoutpu t. *Afterasequencehasbeendisplayed,thenumberoftermsint hat *sequenceisreportedtotheuser.*/ publicclassThreeN2{ publicstaticvoidmain(String[]args){ TextIO.putln("Thisprogramwillprintout3N+1sequences" ); TextIO.putln("forstartingvaluesthatyouspecify.");TextIO.putln();intK;//Startingpointforsequence,specifiedbytheuser.do{ TextIO.putln("Enterastartingvalue;");TextIO.put("Toendtheprogram,enter0:");K=TextIO.getInt();//getstartingvaluefromuserif(K>0)//printsequence,butonlyifKis>0 print3NSequence(K); }while(K>0);//continueonlyifK>0 }//endmain/** *print3NSequenceprintsa3N+1sequencetostandardoutput ,using

PAGE 151

CHAPTER4.SUBROUTINES 137 *startingValueastheinitialvalueofN.Italsoprintsthen umber *oftermsinthesequence.Thevalueoftheparameter,starti ngValue, *mustbeapositiveinteger.*/ staticvoidprint3NSequence(intstartingValue){ intN;//Oneofthetermsinthesequence.intcount;//Thenumberoftermsfound.intonLine;//Thenumberoftermsthathavebeenoutput //sofaronthecurrentline. N=startingValue;//StartthesequencewithstartingValue ; count=1;//Wehaveonetermsofar.TextIO.putln("The3N+1sequencestartingfrom"+N);TextIO.putln();TextIO.put(N,8);//Printinitialterm,using8characters onLine=1;//There'snow1termoncurrentoutputline.while(N>1){ N=nextN(N);//computenexttermcount++;//countthistermif(onLine==5){//Ifcurrentoutputlineisfull TextIO.putln();//...thenoutputacarriagereturnonLine=0;//...andnotethattherearenoterms //onthenewline. }TextIO.putf("%8d",N);//Printthisterminan8-charcolum n. onLine++;//Add1tothenumberoftermsonthisline. }TextIO.putln();//endcurrentlineofoutputTextIO.putln();//andthenaddablanklineTextIO.putln("Therewere"+count+"termsinthesequence. "); }//endofPrint3NSequence/** *nextNcomputesandreturnsthenexttermina3N+1sequence,*giventhatthecurrenttermiscurrentN.*/ staticintnextN(intcurrentN){ if(currentN%2==1) return3*currentN+1; else returncurrentN/2; }//endofnextN() }//endofclassThreeN2 Youshouldreadthisprogramcarefullyandtrytounderstand howitworks.(Tryusing27for thestartingvalue!)

PAGE 152

CHAPTER4.SUBROUTINES 138 4.5APIs,Packages,andJavadocA scomputersandtheiruserinterfaces havebecomeeasiertouse,theyhavealso (online) becomemorecomplexforprogrammerstodealwith.Youcanwri teprogramsforasimple console-styleuserinterfaceusingjustafewsubroutinest hatwriteoutputtotheconsoleand readtheuser'stypedreplies.Amoderngraphicaluserinter face,withwindows,buttons,scroll bars,menus,text-inputboxes,andsoon,mightmakethingse asierfortheuser,butitforces theprogrammertocopewithahugelyexpandedarrayofpossib ilities.Theprogrammersees thisincreasedcomplexityintheformofgreatnumbersofsub routinesthatareprovidedfor managingtheuserinterface,aswellasforotherpurposes.4.5.1ToolboxesSomeonewhowantstoprogramforMacintoshcomputers|andto produceprogramsthatlook andbehavethewayusersexpectthemto|mustdealwiththeMac intoshToolbox,acollectionof welloverathousanddierentsubroutines.Thereareroutin esforopeningandclosingwindows, fordrawinggeometricguresandtexttowindows,foradding buttonstowindows,andfor respondingtomouseclicksonthewindow.Thereareotherrou tinesforcreatingmenusand forreactingtouserselectionsfrommenus.Asidefromtheus erinterface,thereareroutines foropeninglesandreadingdatafromthem,forcommunicati ngoveranetwork,forsending outputtoaprinter,forhandlingcommunicationbetweenpro grams,andingeneralfordoing allthestandardthingsthatacomputerhastodo.MicrosoftW indowsprovidesitsownset ofsubroutinesforprogrammerstouse,andtheyarequiteabi tdierentfromthesubroutines usedontheMac.LinuxhasseveraldierentGUItoolboxesfor theprogrammertochoosefrom. Theanalogyofa\toolbox"isagoodonetokeepinmind.Everyp rogrammingproject involvesamixtureofinnovationandreuseofexistingtools .Aprogrammerisgivenasetof toolstoworkwith,startingwiththesetofbasictoolsthata rebuiltintothelanguage:things likevariables,assignmentstatements,ifstatements,and loops.Tothese,theprogrammercan addexistingtoolboxesfullofroutinesthathavealreadybe enwrittenforperformingcertain tasks.Thesetools,iftheyarewell-designed,canbeusedas trueblackboxes:Theycanbecalled toperformtheirassignedtaskswithoutworryingaboutthep articularstepstheygothroughto accomplishthosetasks.Theinnovativepartofprogramming istotakeallthesetoolsandapply themtosomeparticularprojectorproblem(word-processin g,keepingtrackofbankaccounts, processingimagedatafromaspaceprobe,Webbrowsing,comp utergames,...).Thisiscalled applicationsprogramming Asoftwaretoolboxisakindofblackbox,anditpresentsacer taininterfacetotheprogrammer.Thisinterfaceisaspecicationofwhatroutinesarein thetoolbox,whatparametersthey use,andwhattaskstheyperform.Thisinformationconstitu testhe API ,or Applications ProgrammingInterface ,associatedwiththetoolbox.TheMacintoshAPIisaspecic ation ofalltheroutinesavailableintheMacintoshToolbox.Acom panythatmakessomehardwaredevice|sayacardforconnectingacomputertoanetwork |mightpublishanAPIfor thatdeviceconsistingofalistofroutinesthatprogrammer scancallinordertocommunicate withandcontrolthedevice.Scientistswhowriteasetofrou tinesfordoingsomekindof complexcomputation|suchassolving\dierentialequatio ns,"say|wouldprovideanAPIto allowotherstousethoseroutineswithoutunderstandingth edetailsofthecomputationsthey perform.

PAGE 153

CHAPTER4.SUBROUTINES 139 TheJavaprogramminglanguageissupplementedbyalarge,st andardAPI.You'veseen partofthisAPIalready,intheformofmathematicalsubrout inessuchas Math.sqrt() ,the String datatypeanditsassociatedroutines,andthe System.out.print() routines.The standardJavaAPIincludesroutinesforworkingwithgraphi caluserinterfaces,fornetwork communication,forreadingandwritingles,andmore.It's temptingtothinkoftheseroutines asbeingbuiltintotheJavalanguage,buttheyaretechnical lysubroutinesthathavebeen writtenandmadeavailableforuseinJavaprograms. Javaisplatform-independent.Thatis,thesameprogramcan runonplatformsasdiverseas Macintosh,Windows,Linux,andothers.ThesameJavaAPImus tworkonalltheseplatforms. Butnoticethatitisthe interface thatisplatform-independent;the implementation varies fromoneplatformtoanother.AJavasystemonaparticularco mputerincludesimplementations ofallthestandardAPIroutines.AJavaprogramincludesonl y calls tothoseroutines.When theJavainterpreterexecutesaprogramandencountersacal ltooneofthestandardroutines, itwillpullupandexecutetheimplementationofthatroutin ewhichisappropriateforthe particularplatformonwhichitisrunning.Thisisaverypow erfulidea.Itmeansthatyouonly needtolearnoneAPItoprogramforawidevarietyofplatform s. 4.5.2Java'sStandardPackagesLikeallsubroutinesinJava,theroutinesinthestandardAP Iaregroupedintoclasses.To providelarger-scaleorganization,classesinJavacanbeg roupedinto packages ,whichwere introducedbrieryin Subsection2.6.4 .Youcanhaveevenhigherlevelsofgrouping,since packagescanalsocontainotherpackages.Infact,theentir estandardJavaAPIisimplemented inseveralpackages.Oneofthese,whichisnamed\ java ",containsseveralnon-GUIpackages aswellastheoriginalAWTgraphicsuserinterfaceclasses. Anotherpackage,\ javax ",was addedinJavaversion1.2andcontainstheclassesusedbythe Swinggraphicaluserinterface andotheradditionstotheAPI. Apackagecancontainbothclassesandotherpackages.Apack agethatiscontainedin anotherpackageissometimescalleda\sub-package."Botht he java packageandthe javax packagecontainsub-packages.Oneofthesub-packagesof java ,forexample,iscalled\ awt ". Since awt iscontainedwithin java ,itsfullnameisactually java.awt .ThispackagecontainsclassesthatrepresentGUIcomponentssuchasbuttons andmenusintheAWT,the olderofthetwoJavaGUItoolboxes,whichisnolongerwidely used.However, java.awt also containsanumberofclassesthatformthefoundationforall GUIprogramming,suchasthe Graphics classwhichprovidesroutinesfordrawingonthescreen,the Color classwhichrepresentscolors,andthe Font classwhichrepresentsthefontsthatareusedtodisplaycha racters onthescreen.Sincetheseclassesarecontainedinthepacka ge java.awt ,theirfullnames areactually java.awt.Graphics java.awt.Color ,and java.awt.Font .(Ihopethatbynow you'vegottenthehangofhowthisnamingthingworksinJava. )Similarly, javax contains asub-packagenamed javax.swing, whichincludessuchclassesas javax.swing.JButton javax.swing.JMenu ,and javax.swing.JFrame .TheGUIclassesin javax.swing ,together withthefoundationalclassesin java.awt ,areallpartoftheAPIthatmakesitpossibleto programgraphicaluserinterfacesinJava. The java packageincludesseveralothersub-packages,suchas java.io ,whichprovidesfacilitiesforinput/output, java.net ,whichdealswithnetworkcommunication,and java.util whichprovidesavarietyof\utility"classes.Themostbasi cpackageiscalled java.lang .This packagecontainsfundamentalclassessuchas String Math Integer ,and Double Itmightbehelpfultolookatagraphicalrepresentationoft helevelsofnestinginthe

PAGE 154

CHAPTER4.SUBROUTINES 140 java package,itssub-packages,theclassesinthosesub-packag es,andthesubroutinesinthose classes.Thisisnotacompletepicture,sinceitshowsonlya veryfewofthemanyitemsineach element: S T U T VT W X T Y Z [ Z \ V ] T Z ^ ` T a ^ \b c c d ` Z e f ` T W g h i e f g ` T Y j k b Z e f c k Z l h Vh ` e f m Z ` \ W X n h W Z o W Z k X k ` l h Vh ` p q r s t q u v w x y w x y u x z v w { | } y y x y w x y u x z v w u ~ t | } x s y t €  } { ‚ } ƒ x y „ … † x € q | | w } ‡ x t € y ˆ s u ‰ Š v y ‹ } Œ } „ | } w ƒ „  } u † „ y ˆ s u ‰ Š TheocialdocumentationforthestandardJava5.0APIlists 165dierentpackages,includingsub-packages,anditlists3278classesinthesepac kages.Manyofthesearerather obscureorveryspecialized,butyoumightwanttobrowsethr oughthedocumentationtosee whatisavailable.AsIwritethis,thedocumentationforthe completeAPIcanbefoundat http://java.sun.com/j2se/1.5.0/docs/api/index.html Evenanexpertprogrammerwon'tbefamiliarwiththeentireA PI,orevenamajorityofit.In thisbook,you'llonlyencounterseveraldozenclasses,and thosewillbesucientforwritinga widevarietyofprograms.4.5.3UsingClassesfromPackagesLet'ssaythatyouwanttousetheclass java.awt.Color inaprogramthatyouarewriting. Likeanyclass, java.awt.Color isatype,whichmeansthatyoucanuseittodeclarevariables andparametersandtospecifythereturntypeofafunction.O newaytodothisistousethe fullnameoftheclassasthenameofthetype.Forexample,sup posethatyouwanttodeclare avariablenamed rectColor oftype java.awt.Color .Youcouldsay: java.awt.ColorrectColor; Thisisjustanordinaryvariabledeclarationoftheform\ h type-name ih variable-name i ;".Of course,usingthefullnameofeveryclasscangettiresome,s oJavamakesitpossibletoavoid usingthefullnameofaclassby importing theclass.Ifyouput importjava.awt.Color; atthebeginningofaJavasourcecodele,then,intherestof thele,youcanabbreviatethe fullname java.awt.Color tojustthesimplenameoftheclass, Color .Notethatthe import

PAGE 155

CHAPTER4.SUBROUTINES 141 linecomesatthestartofaleandisnotinsideanyclass.Alt houghitissometimesreferred toasastatement,itismoreproperlycalledan importdirective sinceitisnotastatement intheusualsense.Usingthis import directivewouldallowyoutosay ColorrectColor; todeclarethevariable.Notethattheonlyeectofthe import directiveistoallowyoutouse simpleclassnamesinsteadoffull\package.class"names;y ouaren'treallyimportinganything substantial.Ifyouleaveoutthe import directive,youcanstillaccesstheclass|youjusthave touseitsfullname.Thereisashortcutforimportingallthe classesfromagivenpackage.You canimportalltheclassesfrom java.awt bysaying importjava.awt.*; The\ "isa wildcard thatmatcheseveryclassinthepackage.(However,itdoesno tmatch sub-packages;you cannot importtheentirecontentsofallthesub-packagesofthe java package bysaying importjava.* .) Someprogrammersthinkthatusingawildcardinan import statementisbadstyle,since itcanmakealargenumberofclassnamesavailablethatyouar enotgoingtouseandmight notevenknowabout.Theythinkitisbettertoexplicitlyimp orteachindividualclassthat youwanttouse.Inmyownprogramming,Ioftenusewildcardst oimportalltheclassesfrom themostrelevantpackages,anduseindividualimportswhen Iamusingjustoneortwoclasses fromagivenpackage. Infact,anyJavaprogramthatusesagraphicaluserinterfac eislikelytousemany classesfromthe java.awt and java.swing packagesaswellasfromanotherpackagenamed java.awt.event ,andIusuallybeginsuchprogramswith importjava.awt.*;importjava.awt.event.*;importjavax.swing.*; Aprogramthatworkswithnetworkingmightincludetheline\ importjava.net.*; ",while onethatreadsorwriteslesmightuse\ importjava.io.*; ".(Butwhenyoustartimporting lotsofpackagesinthisway,youhavetobecarefulaboutonet hing:It'spossiblefortwoclasses thatareindierentpackagestohavethesamename.Forexamp le,boththe java.awt package andthe java.util packagecontainclassesnamed List .Ifyouimportboth java.awt.* and java.util.* ,thesimplename List willbeambiguous.Ifyoutrytodeclareavariableoftype List ,youwillgetacompilererrormessageaboutanambiguouscla ssname.Thesolutionis simple:Usethefullnameoftheclass,either java.awt.List or java.util.List .Another solution,ofcourse,istouse import toimporttheindividualclassesyouneed,insteadof importingentirepackages.) Becausethepackage java.lang issofundamental,alltheclassesin java.lang are automatically importedintoeveryprogram.It'sasifeveryprogrambeganw iththestatement \ importjava.lang.*; ".Thisiswhywehavebeenabletousetheclassname String instead of java.lang.String ,and Math.sqrt() insteadof java.lang.Math.sqrt() .Itwouldstill, however,beperfectlylegaltousethelongerformsofthenam es. Programmerscancreatenewpackages.Supposethatyouwants omeclassesthatyouare writingtobeinapackagenamed utilities .Thenthesourcecodelethatdenesthose classesmustbeginwiththeline packageutilities;

PAGE 156

CHAPTER4.SUBROUTINES 142 Thiswouldcomeevenbeforeany import directiveinthatle.Furthermore,asmentionedin Subsection2.6.4 ,thesourcecodelewouldbeplacedinafolderwiththesamen ameasthe package.Aclassthatisinapackageautomaticallyhasacces stootherclassesinthesame package;thatis,aclassdoesn'thavetoimportthepackagei nwhichitisdened. Inprojectsthatdenelargenumbersofclasses,itmakessen setoorganizethoseclasses intopackages.Italsomakessenseforprogrammerstocreate newpackagesastoolboxesthat providefunctionalityandAPI'sfordealingwithareasnotc overedinthestandardJavaAPI. (Andinfactsuch\toolmaking"programmersoftenhavemorep restigethantheapplications programmerswhousetheirtools.) However,Iwillnotbecreatinganypackagesinthistextbook .Forthepurposesofthis book,youneedtoknowaboutpackagesmainlysothatyouwillb eabletoimportthestandard packages.Thesepackagesarealwaysavailabletotheprogra msthatyouwrite.Youmight wonderwherethestandardclassesareactuallylocated.Aga in,thatcandependtosomeextent ontheversionofJavathatyouareusing,butinthestandardJ ava5.0,theyarestoredin jar les inasubdirectoryofthemainJavainstallationdirectory.A jar(or\Javaarchive")le isasinglelethatcancontainmanyclasses.Mostofthestan dardclassescanbefoundina jarlenamed classes.jar .Infact,Javaprogramsaregenerallydistributedinthefor mofjar les,insteadofasindividualclassles. Althoughwewon'tbecreatingpackagesexplicitly, every classisactuallypartofapackage. Ifaclassisnotspecicallyplacedinapackage,thenitispu tinsomethingcalledthe default package ,whichhasnoname.Alltheexamplesthatyouseeinthisbooka reinthedefault package.4.5.4JavadocTouseanAPIeectively,youneedgooddocumentationforit. Thedocumentationformost JavaAPIsispreparedusingasystemcalled Javadoc .Forexample,thissystemisusedto preparethedocumentationforJava'sstandardpackages.An dalmosteveryonewhocreatesa toolboxinJavapublishesJavadocdocumentationforit. Javadocdocumentationispreparedfromspecialcommentsth atareplacedintheJava sourcecodele.RecallthatonetypeofJavacommentbeginsw ith /* andendswith */ .A Javadoccommenttakesthesameform,butitbeginswith /** ratherthansimply /* .You havealreadyseencommentsofthisforminsomeoftheexample sinthisbook,suchasthis subroutinefrom Section4.3 : /** *Thissubroutineprintsa3N+1sequencetostandardoutput, using *startingValueastheinitialvalueofN.Italsoprintsthen umber *oftermsinthesequence.Thevalueoftheparameter,starti ngValue, *mustbeapositiveinteger.*/ staticvoidprint3NSequence(intstartingValue){... NotethattheJavadoccommentisplacedjust before thesubroutinethatitiscommenting on.Thisruleisalwaysfollowed.YoucanhaveJavadoccommen tsforsubroutines,formember variables,andforclasses.TheJavadoccommentalwaysimme diatelyprecedesthethingitis commentingon. Likeanycomment,aJavadoccommentisignoredbythecompute rwhentheleiscompiled. Butthereisatoolcalled javadoc thatreadsJavasourcecodeles,extractsanyJavadoc

PAGE 157

CHAPTER4.SUBROUTINES 143 commentsthatitnds,andcreatesasetofWebpagescontaini ngthecommentsinanicely formatted,interlinkedform.Bydefault, javadoc willonlycollectinformationabout public classes,subroutines,andmembervariables,butitallowst heoptionofcreatingdocumentation fornon-publicthingsaswell.If javadoc doesn'tndanyJavadoccommentforsomething,it willconstructone,butthecommentwillcontainonlybasici nformationsuchasthenameand typeofamembervariableorthename,returntype,andparame terlistofasubroutine.This is syntactic information.Toaddinformationaboutsemanticsandpragma tics,youhaveto writeaJavadoccomment. Asanexample,youcanlookatthedocumentationWebpagefor TextIO .Thedocumentation pagewascreatedbyapplyingthe javadoc tooltothesourcecodele, TextIO.java .Ifyou havedownloadedtheon-lineversionofthisbook,thedocume ntationcanbefoundinthe TextIO Javadoc directory,oryoucanndalinktoitintheon-lineversionof thissection. InaJavadoccomment,the 'satthestartofeachlineareoptional.The javadoc tool willremovethem.Inadditiontonormaltext,thecommentcan containcertainspecialcodes. Foronething,thecommentcancontain HTMLmark-up commands.HTMListhelanguage thatisusedtocreatewebpages,andJavadoccommentsaremea nttobeshownonwebpages. The javadoc toolwillcopyanyHTMLcommandsinthecommentstothewebpag esthatit creates.You'lllearnsomebasicHTMLin Section6.2 ,butasanexample,youcanadd

to indicatethestartofanewparagraph.(Generally,intheabs enceofHTMLcommands,blank linesandextraspacesinthecommentareignored.) InadditiontoHTMLcommands,Javadoccommentscaninclude doctags ,whichare processedascommandsbythe javadoc tool.Adoctaghasanamethatbeginswiththe character @ .Iwillonlydiscussthreetags: @param @return ,and @throws .Thesetagsareused inJavadoccommentsforsubroutinestoprovideinformation aboutitsparameters,itsreturn value,andtheexceptionsthatitmightthrow.Thesetagsare alwaysplacedattheendofthe comment,afteranydescriptionofthesubroutineitself.Th esyntaxforusingthemis: @param h parameter-name ih description-of-parameter i @return h description-of-return-value i @throws h exception-class-name ih description-of-exception i The h descriptions i canextendoverseverallines.Thedescriptionendsatthene xttagoratthe endofthecomment.Youcanincludea @param tagforeveryparameterofthesubroutineanda @throws forasmanytypesofexceptionasyouwanttodocument.Yousho uldhavea @return tagonlyforanon-voidsubroutine.Thesetagsdonothavetob egiveninanyparticularorder. Hereisanexamplethatdoesn'tdoanythingexcitingbutthat doesuseallthreetypesof doctag: /** *Thissubroutinecomputestheareaofarectangle,givenits width *anditsheight.Thelengthandthewidthshouldbepositiven umbers. *@paramwidththelengthofonesideoftherectangle*@paramheightthelengththesecondsideoftherectangle*@returntheareaoftherectangle*@throwsIllegalArgumentExceptionifeitherthewidthort heheight *isanegativenumber.*/ publicstaticdoubleareaOfRectangle(doublelength,doub lewidth){ if(width<0||height<0) thrownewIllegalArgumentException("Sidesmusthaveposi tivelength.");

PAGE 158

CHAPTER4.SUBROUTINES 144 doublearea;area=width*height;returnarea; } IwilluseJavadoccommentsforsomeofmyexamples.Iencoura geyoutousetheminyour owncode,evenifyoudon'tplantogenerateWebpagedocument ationofyourwork,sinceit's astandardformatthatotherJavaprogrammerswillbefamili arwith. IfyoudowanttocreateWeb-pagedocumentation,youneedtor unthe javadoc tool.This toolisavailableasacommandintheJavaDevelopmentKittha twasdiscussedin Section2.6 Youcanuse javadoc inacommandlineinterfacesimilarlytothewaythatthe javac and java commandsareused.JavadoccanalsobeappliedintheEclipse integrateddevelopment environmentthatwasalsodiscussedin Section2.6 :Justright-clicktheclassorpackagethat youwanttodocumentinthePackageExplorer,select\Export ,"andselect\Javadoc"inthe windowthatpopsup.Iwon'tgointoanyofthedetailshere;se ethedocumentation. 4.6MoreonProgramDesignU nderstandinghowprogramswork isonething.Designingaprogramtoperformsome (online) particulartaskisanotherthingaltogether.In Section3.2 ,Idiscussedhowpseudocodeand stepwiserenementcanbeusedtomethodicallydevelopanal gorithm.Wecannowseehow subroutinescantintotheprocess. Stepwiserenementisinherentlyatop-downprocess,butth eprocessdoeshavea\bottom," thatis,apointatwhichyoustopreningthepseudocodealgo rithmandtranslatewhatyouhave directlyintoproperprogramminglanguage.Intheabsenceo fsubroutines,theprocesswould notbottomoutuntilyougetdowntothelevelofassignmentst atementsandveryprimitive input/outputoperations.Butifyouhavesubroutineslying aroundtoperformcertainuseful tasks,youcanstopreningassoonasyou'vemanagedtoexpre ssyouralgorithmintermsof thosetasks. Thisallowsyoutoaddabottom-upelementtothetop-downapp roachofstepwiserenement.Givenaproblem,youmightstartbywritingsomesub routinesthatperformtasks relevanttotheproblemdomain.Thesubroutinesbecomeatoo lboxofready-madetoolsthat youcanintegrateintoyouralgorithmasyoudevelopit.(Alt ernatively,youmightbeableto buyorndasoftwaretoolboxwrittenbysomeoneelse,contai ningsubroutinesthatyoucan useinyourprojectasblackboxes.) Subroutinescanalsobehelpfuleveninastricttop-downapp roach.Asyoureneyour algorithm,youarefreeatanypointtotakeanysub-taskinth ealgorithmandmakeitintoa subroutine.Developingthatsubroutinethenbecomesasepa rateproblem,whichyoucanwork onseparately.Yourmainalgorithmwillmerelycallthesubr outine.This,ofcourse,isjust awayofbreakingyourproblemdownintoseparate,smallerpr oblems.Itisstillatop-down approachbecausethetop-downanalysisoftheproblemtells youwhatsubroutinestowrite. Inthebottom-upapproach,youstartbywritingorobtaining subroutinesthatarerelevantto theproblemdomain,andyoubuildyoursolutiontotheproble montopofthatfoundationof subroutines.4.6.1PreconditionsandPostconditionsWhenworkingwithsubroutinesasbuildingblocks,itisimpo rtanttobeclearabouthowa subroutineinteractswiththerestoftheprogram.Thisinte ractionisspeciedbythe contract

PAGE 159

CHAPTER4.SUBROUTINES 145 ofthesubroutine,asdiscussedin Section4.1 .Aconvenientwaytoexpressthecontractofa subroutineisintermsof preconditions and postconditions Thepreconditionofasubroutineissomethingthatmustbetr uewhenthesubroutine iscalled,ifthesubroutineistoworkcorrectly.Forexampl e,forthebuilt-infunction Math.sqrt(x) ,apreconditionisthattheparameter, x ,isgreaterthanorequaltozero,sinceit isnotpossibletotakethesquarerootofanegativenumber.I ntermsofacontract,apreconditionrepresentsanobligationofthe caller ofthesubroutine.Ifyoucallasubroutinewithout meetingitsprecondition,thenthereisnoreasontoexpecti ttoworkproperly.Theprogram mightcrashorgiveincorrectresults,butyoucanonlyblame yourself,notthesubroutine. Apostconditionofasubroutinerepresentstheothersideof thecontract.Itissomething thatwillbetrueafterthesubroutinehasrun(assumingthat itspreconditionsweremet|and thattherearenobugsinthesubroutine).Thepostcondition ofthefunction Math.sqrt() is thatthesquareofthevaluethatisreturnedbythisfunction isequaltotheparameterthatis providedwhenthesubroutineiscalled.Ofcourse,thiswill onlybetrueifthepreconditiion| thattheparameterisgreaterthanorequaltozero|ismet.Ap ostconditionofthebuilt-in subroutine System.out.print() isthatthevalueoftheparameterhasbeendisplayedonthe screen. Preconditionsmostoftengiverestrictionsontheacceptab levaluesofparameters,asinthe exampleof Math.sqrt(x) .However,theycanalsorefertoglobalvariablesthatareus edin thesubroutine.Thepostconditionofasubroutinespecies thetaskthatitperforms.Fora function,thepostconditionshouldspecifythevaluethatt hefunctionreturns. Subroutinesareoftendescribedbycommentsthatexplicitl yspecifytheirpreconditionsand postconditions.Whenyouaregivenapre-writtensubroutin e,astatementofitspreconditions andpostconditionstellsyouhowtouseitandwhatitdoes.Wh enyouareassignedtowrite asubroutine,thepreconditionsandpostconditionsgiveyo uanexactspecicationofwhatthe subroutineisexpectedtodo.Iwillusethisapproachinthee xamplethatconstitutestherest ofthissection.ThecommentsaregivenintheformofJavadoc comments,butIwillexplicitly labelthepreconditionsandpostconditions.(Manycompute rscientiststhinkthatnewdoc tags @precondition and @postcondition shouldbeaddedtotheJavadocsystemforexplicit labelingofpreconditionsandpostconditions,butthathas notyetbeendone.) 4.6.2ADesignExampleLet'sworkthroughanexampleofprogramdesignusingsubrou tines.Inthisexample,wewill useprewrittensubroutinesasbuildingblocksandwewillal sodesignnewsubroutinesthatwe needtocompletetheproject. SupposethatIhavefoundanalready-writtenclasscalled Mosaic .Thisclassallowsa programtoworkwithawindowthatdisplayslittlecoloredre ctanglesarrangedinrowsand columns.Thewindowcanbeopened,closed,andotherwiseman ipulatedwithstaticmember subroutinesdenedinthe Mosaic class.Infact,theclassdenesatoolboxorAPIthatcanbe usedforworkingwithsuchwindows.Herearesomeoftheavail ableroutinesintheAPI,with Javadoc-stylecomments: /** *Opensa"mosaic"windowonthescreen.**Precondition:Theparametersrows,cols,w,andhareposit iveintegers. *Postcondition:Awindowisopenonthescreenthatcandispl ayrowsand *columnsofcoloredrectangles.Eachrectangleiswpixels

PAGE 160

CHAPTER4.SUBROUTINES 146 *wideandhpixelshigh.Thenumberofrowsisgivenby*thefirstparameterandthenumberofcolumnsbythe*second.Initially,allrectanglesareblack.*Note:Therowsarenumberedfrom0torows-1,andthecolumns are *numberedfrom0tocols-1.*/ publicstaticvoidopen(introws,intcols,intw,inth)/** *Setsthecolorofoneoftherectanglesinthewindow.**Precondition:rowandcolareinthevalidrangeofrowandco lumnnumbers, *andr,g,andbareintherange0to255,inclusive.*Postcondition:Thecoloroftherectangleinrownumberrow andcolumn *numbercolhasbeensettothecolorspecifiedbyr,g,*andb.rgivestheamountofredinthecolorwith0*representingnoredand255representingthemaximum*possibleamountofred.Thelargerthevalueofr,the*moreredinthecolor.gandbworksimilarlyforthe*greenandbluecolorcomponents.*/ publicstaticvoidsetColor(introw,intcol,intr,intg,in tb) /** *Getstheredcomponentofthecolorofoneoftherectangles.**Precondition:rowandcolareinthevalidrangeofrowandco lumnnumbers. *Postcondition:Theredcomponentofthecolorofthespecif iedrectangleis *returnedasanintegerintherange0to255inclusive.*/ publicstaticintgetRed(introw,intcol)/** *LikegetRed,butreturnsthegreencomponentofthecolor.*/ publicstaticintgetGreen(introw,intcol)/** *LikegetRed,butreturnsthebluecomponentofthecolor.*/ publicstaticintgetBlue(introw,intcol)/** *Testswhetherthemosaicwindowiscurrentlyopen.**Precondition:None.*Postcondition:Thereturnvalueistrueifthewindowisope nwhenthis *functioniscalled,anditisfalseifthewindowis*closed.*/ publicstaticbooleanisOpen()/**

PAGE 161

CHAPTER4.SUBROUTINES 147 *Insertsadelayintheprogram(toregulatethespeedatwhic hthecolors *arechanged,forexample).**Precondition:millisecondsisapositiveinteger.*Postcondition:Theprogramhaspausedforatleastthespec ifiednumber *ofmilliseconds,whereonesecondisequalto1000*milliseconds.*/ publicstaticvoiddelay(intmilliseconds) Rememberthatthesesubroutinesaremembersofthe Mosaic class,sowhentheyarecalled fromoutside Mosaic ,thenameoftheclassmustbeincludedaspartofthenameofth eroutine. Forexample,we'llhavetousethename Mosaic.isOpen() ratherthansimply isOpen() Myideaistousethe Mosaic classasthebasisforaneatanimation.Iwanttollthe windowwithrandomlycoloredsquares,andthenrandomlycha ngethecolorsinaloopthat continuesaslongasthewindowisopen.\Randomlychangethe colors"couldmeanalot ofdierentthings,butafterthinkingforawhile,Idecidei twouldbeinterestingtohavea \disturbance"thatwandersrandomlyaroundthewindow,cha ngingthecolorofeachsquare thatitencounters.Here'sapictureshowingwhattheconten tsofthewindowmightlooklike atonepointintime: Withbasicroutinesformanipulatingthewindowasafoundat ion,Icanturntothespecic problemathand.Abasicoutlineformyprogramis OpenaMosaicwindowFillwindowwithrandomcolors;Movearound,changingsquaresatrandom. Fillingthewindowwithrandomcolorsseemslikeanicecoher enttaskthatIcanworkon separately,solet'sdecidetowriteaseparatesubroutinet odoit.Thethirdstepcanbe expandedabitmore,intothesteps:Startinthemiddleofthe window,thenkeepmovingtoa newsquareandchangingthecolorofthatsquare.Thisshould continueaslongasthemosaic windowisstillopen.Thuswecanrenethealgorithmto: OpenaMosaicwindowFillwindowwithrandomcolors;Setthecurrentpositiontothemiddlesquareinthewindow;Aslongasthemosaicwindowisopen: Randomlychangecolorofthesquareatthecurrentposition;Movecurrentpositionup,down,left,orright,atrandom;

PAGE 162

CHAPTER4.SUBROUTINES 148 Ineedtorepresentthecurrentpositioninsomeway.Thatcan bedonewithtwo int variables named currentRow and currentColumn thatholdtherownumberandthecolumnnumberof thesquarewherethedisturbanceiscurrentlylocated.I'll use10rowsand20columnsofsquares inmymosaic,sosettingthecurrentpositiontobeinthecent ermeanssetting currentRow to5 and currentColumn to10.Ialreadyhaveasubroutine, Mosaic.open() ,toopenthewindow, andIhaveafunction, Mosaic.isOpen() ,totestwhetherthewindowisopen.Tokeepthe mainroutinesimple,IdecidethatIwillwritetwomoresubro utinesofmyowntocarryout thetwotasksinthewhileloop.Thealgorithmcanthenbewrit teninJavaas: Mosaic.open(10,20,10,10)fillWithRandomColors();currentRow=5;//Middlerow,halfwaydownthewindow.currentColumn=10;//Middlecolumn.while(Mosaic.isOpen()){ changeToRandomColor(currentRow,currentColumn);randomMove(); } Withtheproperwrapper,thisisessentiallythe main() routineofmyprogram.ItturnsoutI havetomakeonesmallmodication:Topreventtheanimation fromrunningtoofast,theline \ Mosaic.delay(20); "isaddedtothe while loop. The main() routineistakencareof,buttocompletetheprogram,Istill havetowritethe subroutines fillWithRandomColors() changeToRandomColor(int,int) ,and randomMove() Writingeachofthesesubroutinesisaseparate,smalltask. The fillWithRandomColors() routineisdenedbythepostconditionthat\eachoftherect anglesinthemosaichasbeen changedtoarandomcolor."Pseudocodeforanalgorithmtoac complishthistaskcanbegiven as: Foreachrow: Foreachcolumn: setthesquareinthatrowandcolumntoarandomcolor \Foreachrow"and\foreachcolumn"canbeimplementedasfor loops.We'vealreadyplanned towriteasubroutine changeToRandomColor thatcanbeusedtosetthecolor.(Thepossibilityofreusingsubroutinesinseveralplacesisoneofthe bigpayosofusingthem!)So, fillWithRandomColors() canbewritteninproperJavaas: staticvoidfillWithRandomColors(){ for(introw=0;row<10;row++) for(intcolumn=0;column<20;column++) changeToRandomColor(row,column); } Turningtothe changeToRandomColor subroutine,wealreadyhaveamethodinthe Mosaic class, Mosaic.setColor() ,thatcanbeusedtochangethecolorofasquare.Ifwewantara ndomcolor,wejusthavetochooserandomvaluesfor r g ,and b .Accordingtotheprecondition ofthe Mosaic.setColor() subroutine,theserandomvaluesmustbeintegersintherang efrom 0to255.Aformulaforrandomlyselectingsuchanintegeris\ (int)(256*Math.random()) ". Sotherandomcolorsubroutinebecomes: staticvoidchangeToRandomColor(introwNum,intcolNum){ intred=(int)(256*Math.random());intgreen=(int)(256*Math.random());intblue=(int)(256*Math.random());

PAGE 163

CHAPTER4.SUBROUTINES 149 mosaic.setColor(rowNum,colNum,red,green,blue); } Finally,considerthe randomMove subroutine,whichissupposedtorandomlymovethe disturbanceup,down,left,orright.Tomakearandomchoice amongfourdirections,we canchoosearandomintegerintherange0to3.Iftheintegeri s0,moveinonedirection; ifitis1,moveinanotherdirection;andsoon.Thepositiono fthedisturbanceisgiven bythevariables currentRow and currentColumn .To\moveup"meanstosubtract1from currentRow .Thisleavesopenthequestionofwhattodoif currentRow becomes-1,which wouldputthedisturbanceabovethewindow.Ratherthanlett hishappen,Idecidetomove thedisturbancetotheoppositeedgeoftheappletbysetting currentRow to9.(Remember thatthe10rowsarenumberedfrom0to9.)Movingthedisturba ncedown,left,orrightis handledsimilarly.Ifweusea switch statementtodecidewhichdirectiontomove,thecode for randomMove becomes: intdirectionNum;directionNum=(int)(4*Math.random());switch(directionNum){ case0://moveup currentRow--;if(currentRow<0)//CurrentRowisoutsidethemosaic; currentRow=9;//moveittotheoppositeedge. break; case1://moveright currentColumn++;if(currentColumn>=20) currentColumn=0; break; case2://movedown currentRow++;if(currentRow>=10) currentRow=0; break; case3://moveleft currentColumn--;if(currentColumn<0) currentColumn=19; break; } 4.6.3TheProgramPuttingthisalltogether,wegetthefollowingcompletepro gram.NotethatI'veaddedJavadocstylecommentsfortheclassitselfandforeachofthesubrou tines.Thevariables currentRow and currentColumn aredenedasstaticmembersoftheclass,ratherthanlocalv ariables, becauseeachofthemisusedinseveraldierentsubroutines .Thisprogramactuallydepends ontwootherclasses, Mosaic andanotherclasscalled MosaicCanvas thatisusedby Mosaic Ifyouwanttocompileandrunthisprogram,bothoftheseclas sesmustbeavailabletothe program.

PAGE 164

CHAPTER4.SUBROUTINES 150 /** *Thisprogramopensawindowfullofrandomlycoloredsquare s.A"disturbance" *movesrandomlyaroundinthewindow,randomlychangingthe colorofeach *squarethatitvisits.Theprogramrunsuntiltheuserclose sthewindow. */ publicclassRandomMosaicWalk{ staticintcurrentRow;//Rowcurrentlycontainingthedist urbance. staticintcurrentColumn;//Columncurrentlycontainingd isturbance. /** *Themainprogramcreatesthewindow,fillsitwithrandomco lors, *andthenmovesthedisturbancesinarandomwalkaroundthew indow *aslongasthewindowisopen.*/ publicstaticvoidmain(String[]args){ Mosaic.open(10,20,10,10);fillWithRandomColors();currentRow=5;//startatcenterofwindowcurrentColumn=10;while(Mosaic.isOpen()){ changeToRandomColor(currentRow,currentColumn);randomMove();Mosaic.delay(20); } }//endmain/** *Fillsthewindowwithrandomlycoloredsquares.*Precondition:Themosaicwindowisopen.*Postcondition:Eachsquarehasbeensettoarandomcolor.*/ staticvoidfillWithRandomColors(){ for(introw=0;row<10;row++){ for(intcolumn=0;column<20;column++){ changeToRandomColor(row,column); } } }//endfillWithRandomColors/** *Changesonesquaretoanewrandomlyselectedcolor.*Precondition:ThespecifiedrowNumandcolNumareintheva lidrange *ofrowandcolumnnumbers.*Postcondition:Thesquareinthespecifiedrowandcolumnh as *beensettoarandomcolor.*@paramrowNumtherownumberofthesquare,countingrowsdo wn *from0atthetop*@paramcolNumthecolumnnumberofthesquare,countingcol umnsover *from0attheleft*/ staticvoidchangeToRandomColor(introwNum,intcolNum){ intred=(int)(256*Math.random());//Chooserandomlevel sinrange intgreen=(int)(256*Math.random());//0to255forred,gr een, intblue=(int)(256*Math.random());//andbluecolorcomp onents.

PAGE 165

CHAPTER4.SUBROUTINES 151 Mosaic.setColor(rowNum,colNum,red,green,blue); }//endofchangeToRandomColor()/** *Movethedisturbance.*Precondition:TheglobalvariablescurrentRowandcurren tColumn *arewithinthelegalrangeofrowandcolumnnumbers.*Postcondition:currentRoworcurrentColumnischangedto oneofthe *neighboringpositionsinthegrid--up,down,left,or*rightfromthecurrentposition.Ifthismovesthe*positionoutsideofthegrid,thenitismovedtothe*oppositeedgeofthegrid.*/ staticvoidrandomMove(){ intdirectionNum;//Randomlysetto0,1,2,or3tochoosedir ection. directionNum=(int)(4*Math.random());switch(directionNum){ case0://moveup currentRow--;if(currentRow<0) currentRow=9; break; case1://moveright currentColumn++;if(currentColumn>=20) currentColumn=0; break; case2://movedown currentRow++;if(currentRow>=10) currentRow=0; break; case3://moveleft currentColumn--;if(currentColumn<0) currentColumn=19; break; } }//endrandomMove }//endclassRandomMosaicWalk 4.7TheTruthAboutDeclarationsN amesarefundamentaltoprogramming ,asIsaidafewchaptersago.Therearealot (online) ofdetailsinvolvedindeclaringandusingnames.Ihavebeen avoidingsomeofthosedetails. Inthissection,I'llrevealmostofthetruth(althoughstil lnotthefulltruth)aboutdeclaring andusingvariablesinJava.Thematerialinthesubsections \InitializationinDeclarations" and\NamedConstants"isparticularlyimportant,sinceIwi llbeusingitregularlyinfuture chapters.

PAGE 166

CHAPTER4.SUBROUTINES 152 4.7.1InitializationinDeclarationsWhenavariabledeclarationisexecuted,memoryisallocate dforthevariable.Thismemory mustbeinitializedtocontainsomedenitevaluebeforethe variablecanbeusedinanexpression.Inthecaseofalocalvariable,thedeclarationisofte nfollowedcloselybyanassignment statementthatdoestheinitialization.Forexample, intcount;//Declareavariablenamedcount.count=0;//Givecountitsinitialvalue. However,thetruthaboutdeclarationstatementsisthatiti slegaltoincludetheinitializationofthevariableinthedeclarationstatement.Thetwost atementsabovecanthereforebe abbreviatedas intcount=0;//Declarecountandgiveitaninitialvalue. Thecomputerstillexecutesthisstatementintwosteps:Dec larethevariable count ,thenassign thevalue0tothenewlycreatedvariable.Theinitialvalued oesnothavetobeaconstant.It canbeanyexpression.Itislegaltoinitializeseveralvari ablesinonedeclarationstatement. Forexample, charfirstInitial='D',secondInitial='E';intx,y=1;//OK,butonlyyhasbeeninitialized!intN=3,M=N+2;//OK,Nisinitialized //beforeitsvalueisused. Thisfeatureisespeciallycommonin for loops,sinceitmakesitpossibletodeclarealoopcontrol variableatthesamepointintheloopwhereitisinitialized .Sincetheloopcontrolvariable generallyhasnothingtodowiththerestoftheprogramoutsi detheloop,it'sreasonableto haveitsdeclarationinthepartoftheprogramwhereit'sact uallyused.Forexample: for(inti=0;i<10;i++){ System.out.println(i); } Again,youshouldrememberthatthisissimplyanabbreviati onforthefollowing,whereI've addedanextrapairofbracestoshowthat i isconsideredtobelocaltothe for statementand nolongerexistsafterthe for loopends: { inti;for(i=0;i<10;i++){ System.out.println(i); } } (Youmightrecall,bytheway,thatfor\for-each"loops,the specialtypeof for statement thatisusedwithenumeratedtypes,declaringthevariablei nthe for is required .See Subsection3.4.4 .) Amembervariablecanalsobeinitializedatthepointwherei tisdeclared,justasfora localvariable.Forexample: publicclassBank{ staticdoubleinterestRate=0.05;staticintmaxWithdrawal=200;

PAGE 167

CHAPTER4.SUBROUTINES 153 ..//Morevariablesandsubroutines.. } Astaticmembervariableiscreatedassoonastheclassisloa dedbytheJavainterpreter,and theinitializationisalsodoneatthattime.Inthecaseofme mbervariables,thisisnotsimply anabbreviationforadeclarationfollowedbyanassignment statement.Declarationstatements aretheonlytypeofstatementthatcanoccuroutsideofasubr outine.Assignmentstatements cannot,sothefollowingisillegal: publicclassBank{ staticdoubleinterestRate;interestRate=0.05;// ILLEGAL: .// Can'tbeoutsideasubroutine! : .. Becauseofthis,declarationsofmembervariablesofteninc ludeinitialvalues.Infact,as mentionedin Subsection4.2.4 ,ifnoinitialvalueisprovidedforamembervariable,thena defaultinitialvalueisused.Forexample,whendeclaringa nintegermembervariable, count \ staticintcount; "isequivalentto\ staticintcount=0; ". 4.7.2NamedConstantsSometimes,thevalueofavariableisnotsupposedtochangea fteritisinitialized.Forexample, intheaboveexamplewhere interestRate isinitializedtothevalue 0.05 ,it'squitepossible thatthatismeanttobethevaluethroughouttheentireprogr am.Inthiscase,theprogrammer isprobablydeningthevariable, interestRate ,togiveameaningfulnametotheotherwise meaninglessnumber, 0.05 .It'seasiertounderstandwhat'sgoingonwhenaprogramsay s \ principal+=principal*interestRate; "ratherthan\ principal+=principal*0.05; ". InJava,themodier\ final "canbeappliedtoavariabledeclarationtoensurethatthe valuestoredinthevariablecannotbechangedafterthevari ablehasbeeninitialized.For example,ifthemembervariable interestRate isdeclaredwith finalstaticdoubleinterestRate=0.05; thenitwouldbeimpossibleforthevalueof interestRate tochangeanywhereelseinthe program.Anyassignmentstatementthattriestoassignaval ueto interestRate willbe rejectedbythecomputerasasyntaxerrorwhentheprogramis compiled. Itislegaltoapplythe final modiertolocalvariablesandeventoformalparameters, butitismostusefulformembervariables.Iwilloftenrefer toastaticmembervariablethat isdeclaredtobe final asa namedconstant ,sinceitsvalueremainsconstantforthewhole timethattheprogramisrunning.Thereadabilityofaprogra mcanbegreatlyenhancedby usingnamedconstantstogivemeaningfulnamestoimportant quantitiesintheprogram.A recommendedstylerulefornamedconstantsistogivethemna mesthatconsistentirelyof uppercaseletters,withunderscorecharacterstoseparate wordsifnecessary.Forexample,the preferredstylefortheinterestrateconstantwouldbe finalstaticdoubleINTEREST RATE=0.05; ThisisthestylethatisgenerallyusedinJava'sstandardcl asses,whichdenemanynamed constants.Forexample,wehavealreadyseenthatthe Math classcontainsavariable Math.PI Thisvariableisdeclaredinthe Math classasa\publicnalstatic"variableoftype double

PAGE 168

CHAPTER4.SUBROUTINES 154 Similarly,the Color classcontainsnamedconstantssuchas Color.RED and Color.YELLOW whicharepublicnalstaticvariablesoftype Color .Manynamedconstantsarecreatedjustto givemeaningfulnamestobeusedasparametersinsubroutine calls.Forexample,thestandard classnamed Font containsnamedconstants Font.PLAIN Font.BOLD ,and Font.ITALIC .These constantsareusedforspecifyingdierentstylesoftextwh encallingvarioussubroutinesinthe Font class. Enumeratedtypeconstants(See Subsection2.3.3 .)arealsoexamplesofnamedconstants. Theenumeratedtypedenition enumAlignment{LEFT,RIGHT,CENTER} denestheconstants Alignment.LEFT Alignment.RIGHT ,and Alignment.CENTER .Technically, Alignment isaclass,andthethreeconstantsarepublicnalstaticmem bersofthatclass. Deningtheenumeratedtypeissimilartodeningthreecons tantsoftype,say, int : publicstaticfinalintALIGNMENT LEFT=0; publicstaticfinalintALIGNMNENT RIGHT=1; publicstaticfinalintALIGNMENT CENTER=2; Infact,thisishowthingsweregenerallydonebeforetheint roductionofenumeratedtypesin Java5.0,anditiswhatisdonewiththeconstants Font.PLAIN Font.BOLD ,and Font.ITALIC mentionedabove.Usingtheintegerconstants,youcouldde neavariableoftype int andassign itthevalues ALIGNMENT LEFT ALIGNMENT RIGHT ,or ALIGNMENT CENTER torepresentdierent typesofalignment.Theonlyproblemwiththisisthatthecom puterhasnowayofknowing thatyouintendthevalueofthevariabletorepresentanalig nment,anditwillnotraiseany objectionifthevaluethatisassignedtothevariableisnot oneofthethreevalidalignment values. Withtheenumeratedtype,ontheotherhand,theonlyvaluest hatcanbeassignedto avariableoftype Alignment aretheconstantvaluesthatarelistedinthedenitionofth e enumeratedtype.Anyattempttoassignaninvalidvaluetoth evariableisasyntaxerror whichthecomputerwilldetectwhentheprogramiscompiled. Thisextrasafetyisoneofthe majoradvantagesofenumeratedtypes. Curiouslyenough,oneofthemajorreasonstousenamedconst antsisthatit'seasyto changethevalueofanamedconstant.Ofcourse,thevaluecan 'tchangewhiletheprogram isrunning.Butbetweenrunsoftheprogram,it'seasytochan gethevalueinthesourcecode andrecompiletheprogram.Considertheinterestrateexamp le.It'squitepossiblethatthe valueoftheinterestrateisusedmanytimesthroughoutthep rogram.Supposethatthebank changestheinterestrateandtheprogramhastobemodied.I ftheliteralnumber0.05were usedthroughouttheprogram,theprogrammerwouldhavetotr ackdowneachplacewhere theinterestrateisusedintheprogramandchangetherateto thenewvalue.(Thisismade evenharderbythefactthatthenumber0.05mightoccurinthe programwithothermeanings besidestheinterestrate,aswellasbythefactthatsomeone mighthaveused0.025torepresent halftheinterestrate.)Ontheotherhand,ifthenamedconst ant INTEREST RATE isdeclared andusedconsistentlythroughouttheprogram,thenonlythe singlelinewheretheconstantis initializedneedstobechanged. Asanextendedexample,Iwillgiveanewversionofthe RandomMosaicWalk programfrom theprevioussection.Thisversionusesnamedconstantstor epresentthenumberofrowsin themosaic,thenumberofcolumns,andthesizeofeachlittle square.Thethreeconstantsare declaredas finalstatic membervariableswiththelines:

PAGE 169

CHAPTER4.SUBROUTINES 155 finalstaticintROWS=30;//Numberofrowsinmosaic.finalstaticintCOLUMNS=30;//Numberofcolumnsinmosaic.finalstaticintSQUARE SIZE=15;//Sizeofeachsquareinmosaic. Therestoftheprogramiscarefullymodiedtousethenamedc onstants.Forexample,in thenewversionoftheprogram,theMosaicwindowisopenedwi ththestatement Mosaic.open(ROWS,COLUMNS,SQUARE SIZE,SQUARE SIZE); Sometimes,it'snoteasytondalltheplaceswhereanamedco nstantneedstobeused.If youdon'tusethenamedconstantconsistently,you'vemoreo rlessdefeatedthepurpose.It's alwaysagoodideatorunaprogramusingseveraldierentval uesforanynamedconstants,to testthatitworksproperlyinallcases. Hereisthecompletenewprogram, RandomMosaicWalk2 ,withallmodicationsfromthe previousversionshowninitalic.I'veleftoutsomeoftheco mmentstosavespace. publicclassRandomMosaicWalk2{ finalstaticintROWS=30;//Numberofrowsinmosaic.finalstaticintCOLUMNS=30;//Numberofcolumnsinmosaic.finalstaticintSQUARE SIZE=15;//Sizeofeachsquareinmosaic. staticintcurrentRow;//Rowcurrentlycontainingthedist urbance. staticintcurrentColumn;//Columncurrentlycontainingd isturbance. publicstaticvoidmain(String[]args){ Mosaic.open(ROWS,COLUMNS,SQUARE SIZE,SQUARE SIZE) ; fillWithRandomColors();currentRow=ROWS/2 ;//startatcenterofwindow currentColumn=COLUMNS/2 ; while(Mosaic.isOpen()){ changeToRandomColor(currentRow,currentColumn);randomMove();Mosaic.delay(20); } }//endmainstaticvoidfillWithRandomColors(){ for( introw=0;row < ROWS;row++ ){ for( intcolumn=0;column < COLUMNS;column++ ){ changeToRandomColor(row,column); } } }//endfillWithRandomColorsstaticvoidchangeToRandomColor(introwNum,intcolNum){ intred=(int)(256*Math.random());//Chooserandomlevel sinrange intgreen=(int)(256*Math.random());//0to255forred,gr een, intblue=(int)(256*Math.random());//andbluecolorcomp onents. Mosaic.setColor(rowNum,colNum,red,green,blue); }//endchangeToRandomColorstaticvoidrandomMove(){ intdirectionNum;//Randomlysetto0,1,2,or3tochoosedir ection. directionNum=(int)(4*Math.random());switch(directionNum){ case0://moveup

PAGE 170

CHAPTER4.SUBROUTINES 156 currentRow--;if(currentRow<0) currentRow=ROWS-1; break; case1://moveright currentColumn++;if( currentColumn > =COLUMNS ) currentColumn=0; break; case2://movedown currentRow++;if( currentRow > =ROWS ) currentRow=0; break; case3://moveleft currentColumn--;if(currentColumn<0) currentColumn=COLUMNS-1 ; break; } }//endrandomMove }//endclassRandomMosaicWalk2 4.7.3NamingandScopeRulesWhenavariabledeclarationisexecuted,memoryisallocate dforthatvariable.Thevariable namecanbeusedinatleastsomepartoftheprogramsourcecod etorefertothatmemoryor tothedatathatisstoredinthememory.Theportionofthepro gramsourcecodewherethe variablenameisvalidiscalledthe scope ofthevariable.Similarly,wecanrefertothescope ofsubroutinenamesandformalparameternames. Forstaticmembersubroutines,scopeisstraightforward.T hescopeofastaticsubroutine istheentiresourcecodeoftheclassinwhichitisdened.Th atis,itispossibletocallthe subroutinefromanypointintheclass,includingatapointi nthesourcecodebeforethepoint wherethedenitionofthesubroutineappears.Itisevenpos sibletocallasubroutinefrom withinitself.Thisisanexampleofsomethingcalled\recur sion,"afairlyadvancedtopicthat wewillreturntolater. Foravariablethatisdeclaredasastaticmembervariablein aclass,thesituationissimilar, butwithonecomplication.Itislegaltohavealocalvariabl eoraformalparameterthathas thesamenameasamembervariable.Inthatcase,withinthesc opeofthelocalvariableor parameter,themembervariableis hidden .Consider,forexample,aclassnamed Game that hastheform: publicclassGame{ staticintcount;//membervariablestaticvoidplayGame(){ intcount;//localvariable ..//SomestatementstodefineplayGame(). }

PAGE 171

CHAPTER4.SUBROUTINES 157 ..//Morevariablesandsubroutines.. }//endGame Inthestatementsthatmakeupthebodyofthe playGame() subroutine,thename\ count referstothelocalvariable.Intherestofthe Game class,\ count "referstothemembervariable,unlesshiddenbyotherlocalvariablesorparametersn amed count .However,thereis onefurthercomplication.Themembervariablenamed count canalsobereferredtobythe fullname Game.count .Usually,thefullnameisonlyusedoutsidetheclasswhere count is dened.However,thereisnoruleagainstusingitinsidethe class.Thefullname, Game.count canbeusedinsidethe playGame() subroutinetorefertothemembervariable.So,thefull scoperuleisthatthescopeofastaticmembervariableinclu destheentireclassinwhichit isdened,butwherethesimplenameofthemembervariableis hiddenbyalocalvariable orformalparametername,themembervariablemustbereferr edtobyitsfullnameofthe form h className i h variableName i .(Scoperulesfornon-staticmembersaresimilartothose forstaticmembers,exceptthat,asweshallsee,non-static memberscannotbeusedinstatic subroutines.) Thescopeofaformalparameterofasubroutineistheblockth atmakesupthebodyofthe subroutine.Thescopeofalocalvariableextendsfromthede clarationstatementthatdenes thevariabletotheendoftheblockinwhichthedeclarationo ccurs.Asnotedabove,itis possibletodeclarealoopcontrolvariableofa for loopinthe for statement,asin\ for(int i=0;i<10;i++) ".Thescopeofsuchadeclarationisconsideredasaspecialc ase:Itis validonlywithinthe for statementanddoesnotextendtotheremainderoftheblockth at containsthe for statement. Itisnotlegaltoredenethenameofaformalparameterorloc alvariablewithinitsscope, eveninanestedblock.Forexample,thisisnotallowed: voidbadSub(inty){ intx;while(y>0){ intx;// ERROR:xisalreadydefined. ... } } Inmanylanguages,thiswouldbelegal;thedeclarationof x inthe while loopwouldhide theoriginaldeclaration.ItisnotlegalinJava;however,o ncetheblockinwhichavariableis declaredends,itsnamedoesbecomeavailableforreuseinJa va.Forexample: voidgoodSub(inty){ while(y>10){ intx; ... //Thescopeofxendshere. }while(y>0){

PAGE 172

CHAPTER4.SUBROUTINES 158 intx;//OK:Previousdeclarationofxhasexpired. ... } } Youmightwonderwhetherlocalvariablenamescanhidesubro utinenames.Thiscan't happen,forareasonthatmightbesurprising.Thereisnorul ethatvariablesandsubroutines havetohavedierentnames.Thecomputercanalwaystellwhe theranamereferstoavariable ortoasubroutine,becauseasubroutinenameisalwaysfollo wedbyaleftparenthesis.It's perfectlylegaltohaveavariablecalled count andasubroutinecalled count inthesameclass. (ThisisonereasonwhyIoftenwritesubroutinenameswithpa rentheses,aswhenItalkabout the main() routine.It'sagoodideatothinkoftheparenthesesasparto fthename.)Even moreistrue:It'slegaltoreuseclassnamestonamevariable sandsubroutines.Thesyntax rulesofJavaguaranteethatthecomputercanalwaystellwhe nanameisbeingusedasaclass name.Aclassnameisatype,andsoitcanbeusedtodeclarevar iablesandformalparameters andtospecifythereturntypeofafunction.Thismeansthaty oucouldlegallyhaveaclass called Insanity inwhichyoudeclareafunction staticInsanityInsanity(InsanityInsanity){...} Therst Insanity isthereturntypeofthefunction.Thesecondisthefunction name,the thirdisthetypeoftheformalparameter,andthefourthisaf ormalparametername.However, pleaserememberthatnoteverythingthatispossibleisagoo didea!

PAGE 173

Exercises 159 ExercisesforChapter4 1. To\capitalize"astringmeanstochangetherstletterofea chwordinthestringtoupper (solution) case(ifitisnotalreadyuppercase).Forexample,acapital izedversionof\Nowisthetime toact!"is\NowIsTheTimeToAct!".Writeasubroutinenamed printCapitalized thatwillprintacapitalizedversionofastringtostandard output.Thestringtobeprinted shouldbeaparametertothesubroutine.Testyoursubroutin ewitha main() routinethat getsalineofinputfromtheuserandappliesthesubroutinet oit. Notethataletteristherstletterofawordifitisnotimmed iatelyprecededin thestringbyanotherletter.Recallthatthereisastandard boolean -valuedfunction Character.isLetter(char) thatcanbeusedtotestwhetheritsparameterisaletter. Thereisanotherstandard char -valuedfunction, Character.toUpperCase(char) ,that returnsacapitalizedversionofthesinglecharacterpasse dtoitasaparameter.Thatis, iftheparameterisaletter,itreturnstheupper-caseversi on.Iftheparameterisnota letter,itjustreturnsacopyoftheparameter. 2. Thehexadecimaldigitsaretheordinary,base-10digits'0' through'9'plustheletters'A' (solution) through'F'.Inthehexadecimalsystem,thesedigitsrepres entthevalues0through15, respectively.Writeafunctionnamed hexValue thatusesa switch statementtondthe hexadecimalvalueofagivencharacter.Thecharacterisapa rametertothefunction,and itshexadecimalvalueisthereturnvalueofthefunction.Yo ushouldcountlowercase letters'a'through'f'ashavingthesamevalueasthecorres pondinguppercaseletters. Iftheparameterisnotoneofthelegalhexadecimaldigits,r eturn -1 asthevalueofthe function. Ahexadecimalintegerisasequenceofhexadecimaldigits,s uchas34A7,FF8,174204, orFADE.If str isastringcontainingahexadecimalinteger,thenthecorre sponding base-10integercanbecomputedasfollows: value=0;for(i=0;i
PAGE 174

Exercises 160 aparametertothesubroutine.Theaveragenumberofrollsis thereturnvalue.Each individualexperimentshouldbedonebycallingthefunctio nyouwroteforExercise4.3. Now,writeamainprogramthatwillcallyourfunctiononcefo reachofthepossibletotals (2,3,...,12).Itshouldmakeatableoftheresults,somethi nglike: TotalOnDiceAverageNumberofRolls-----------------------------------235.8382318.0607.... 5. Thesampleprogram RandomMosaicWalk.java from Section4.6 showsa\disturbance" (solution) thatwandersaroundagridofcoloredsquares.Whenthedistu rbancevisitsasquare,the colorofthatsquareischanged.Theappletatthebottomof Section4.7 intheon-line versionofthisbookshowsavariationonthisidea.Inthisap plet,allthesquaresstart outwiththedefaultcolor,black.Everytimethedisturbanc evisitsasquare,asmall amountisaddedtotheredcomponentofthecolorofthatsquar e.Writeasubroutine thatwilladd25totheredcomponentofoneofthesquaresinth emosaic.Therowand columnnumbersofthesquareshouldbepassedasparameterst othesubroutine.Recall thatyoucandiscoverthecurrentredcomponentofthesquare inrow r andcolumn c withthefunctioncall Mosaic.getRed(r,c) .Useyoursubroutineasasubstituteforthe changeToRandomColor() subroutineintheprogram RandomMosaicWalk2.java .(Thisis theimprovedversionoftheprogramfrom Section4.7 thatusesnamedconstantsforthe numberofrows,numberofcolumns,andsquaresize.)Setthen umberofrowsandthe numberofcolumnsto80.Setthesquaresizeto5. 6. Forthisexercise,youwillwriteanotherprogrambasedonth enon-standard Mosaic class (solution) thatwaspresentedin Section4.6 .Whiletheprogramdoesnotdoanythingparticularly interesting,it'sinterestingasaprogrammingproblem.An appletthatdoesthesame thingastheprogramcanbeseenintheon-lineversionofthis book.Hereisapicture showingwhatitlookslikeatseveraldierenttimes: Theprogramwillshowarectanglethatgrowsfromthecentero ftheapplettotheedges, gettingbrighterasitgrows.Therectangleismadeupofthel ittlesquaresofthemosaic. Youshouldrstwriteasubroutinethatdrawsarectangleona Mosaic window.More specically,writeasubroutinenamed rectangle suchthatthesubroutinecallstatement rectangle(top,left,height,width,r,g,b);

PAGE 175

Exercises 161 willcall Mosaic.setColor(row,col,r,g,b) foreachlittlesquarethatliesontheoutline ofarectangle.Thetopmostrowoftherectangleisspeciedb y top .Thenumberof rowsintherectangleisspeciedby height (sothebottommostrowis top+height-1 ). Theleftmostcolumnoftherectangleisspeciedby left .Thenumberofcolumnsinthe rectangleisspeciedby width (sotherightmostcolumnis left+width-1 .) Theanimationloopsthroughthesamesequenceofstepsovera ndover.Ineachstep, arectangleisdrawningray(thatis,withallthreecolorcom ponentshavingthesame value).Thereisapauseof200millisecondssotheusercanse etherectangle.Thenthe verysamerectangleisdrawninblack,eectivelyerasingth egrayrectangle.Finally,the variablesgivingthetoprow,leftcolumn,size,andcolorle veloftherectangleareadjusted togetreadyforthenextstep.Intheapplet,thecolorlevels tartsat50andincreasesby 10aftereachstep.Whentherectanglegetstotheouteredgeo ftheapplet,theloopends. Theanimationthenstartsagainatthebeginningoftheloop. Youmightwanttomakea subroutinethatdoesoneloopthroughallthestepsoftheani mation. The main() routinesimplyopensaMosaicwindowandthendoestheanimat ionloop overandoveruntiltheuserclosesthewindow.Thereisa1000 milliseconddelaybetween oneanimationloopandthenext.UseaMosaicwindowthathas4 1rowsand41columns. (Iadviseyou not tousednamedconstantsforthenumbersofrowsandcolumns,s ince theproblemiscomplicatedenoughalready.)

PAGE 176

Quiz 162 QuizonChapter4 (answers) 1. A\blackbox"hasaninterfaceandanimplementation.Explai nwhatismeantbythe terms interface and implementation 2. Asubroutineissaidtohavea contract .Whatismeantbythecontractofasubroutine? Whenyouwanttouseasubroutine,whyisitimportanttounder standitscontract?The contracthasboth\syntactic"and\semantic"aspects.What isthesyntacticaspect? Whatisthesemanticaspect? 3. Brieryexplainhowsubroutinescanbeausefultoolinthetop -downdesignofprograms. 4. Discusstheconceptof parameters. Whatareparametersfor?Whatisthedierence between formalparameters and actualparameters ? 5. Givetwodierentreasonsforusingnamedconstants(declar edwiththe final modier). 6. WhatisanAPI?Giveanexample. 7. Writeasubroutinenamed\stars"thatwilloutputalineofst arstostandardoutput.(A staristhecharacter\*".)Thenumberofstarsshouldbegive nasaparametertothe subroutine.Usea for loop.Forexample,thecommand\stars(20)"wouldoutput ******************** 8. Writea main() routinethatusesthesubroutinethatyouwroteforQuestion 7tooutput 10linesofstarswith1starintherstline,2starsinthesec ondline,andsoon,asshown below. ******************************************************* 9. Writeafunctionnamed countChars thathasa String anda char asparameters.The functionshouldcountthenumberoftimesthecharacteroccu rsinthestring,anditshould returntheresultasthevalueofthefunction. 10. Writeasubroutinewiththreeparametersoftype int. Thesubroutineshoulddetermine whichofitsparametersissmallest.Thevalueofthesmalles tparametershouldbereturned asthevalueofthesubroutine.

PAGE 177

Chapter5ProgrammingintheLargeII:ObjectsandClassesW hereasasubroutine representsasingletask,anobjectcanencapsulatebothdat a(in theformofinstancevariables)andanumberofdierenttask sor\behaviors"relatedtothat data(intheformofinstancemethods).Thereforeobjectspr ovideanother,moresophisticated typeofstructurethatcanbeusedtohelpmanagethecomplexi tyoflargeprograms. ThischaptercoversthecreationanduseofobjectsinJava. Section5.5 coversthecentral ideasofobject-orientedprogramming:inheritanceandpol ymorphism.However,inthistextbook,wewillgenerallyusetheseideasinalimitedform,byc reatingindependentclassesand buildingonexistingclassesratherthanbydesigningentir ehierarchiesofclassesfromscratch. Section5.6 and Section5.7 coversomeofthemanydetailsofobjectorientedprogrammin gin Java.Althoughthesedetailsareusedoccasionallylaterin thebook,youmightwanttoskim throughthemnowandreturntothemlaterwhentheyareactual lyneeded. 5.1Objects,InstanceMethods,andInstanceVariablesO bject-orientedprogramming (OOP)representsanattempttomakeprogramsmore (online) closelymodelthewaypeoplethinkaboutanddealwiththewor ld.Intheolderstylesof programming,aprogrammerwhoisfacedwithsomeproblemmus tidentifyacomputingtask thatneedstobeperformedinordertosolvetheproblem.Prog rammingthenconsistsof ndingasequenceofinstructionsthatwillaccomplishthat task.Butattheheartofobjectorientedprogramming,insteadoftaskswendobjects|enti tiesthathavebehaviors,thathold information,andthatcaninteractwithoneanother.Progra mmingconsistsofdesigningaset ofobjectsthatsomehowmodeltheproblemathand.Softwareo bjectsintheprogramcan representrealorabstractentitiesintheproblemdomain.T hisissupposedtomakethedesign oftheprogrammorenaturalandhenceeasiertogetrightande asiertounderstand. Tosomeextent,OOPisjustachangeinpointofview.Wecanthi nkofanobjectinstandard programmingtermsasnothingmorethanasetofvariablestog etherwithsomesubroutinesfor manipulatingthosevariables.Infact,itispossibletouse object-orientedtechniquesinany programminglanguage.However,thereisabigdierencebet weenalanguagethatmakesOOP possibleandonethatactivelysupportsit.Anobject-orien tedprogramminglanguagesuchas Javaincludesanumberoffeaturesthatmakeitverydierent fromastandardlanguage.In ordertomakeeectiveuseofthosefeatures,youhaveto\ori ent"yourthinkingcorrectly. 163

PAGE 178

CHAPTER5.OBJECTSANDCLASSES 164 5.1.1Objects,Classes,andInstancesObjectsarecloselyrelatedtoclasses.Wehavealreadybeen workingwithclassesforseveral chapters,andwehaveseenthataclasscancontainvariables andsubroutines.Ifanobjectis alsoacollectionofvariablesandsubroutines,howdotheyd ierfromclasses?Andwhydoesit requireadierenttypeofthinkingtounderstandandusethe meectively?Intheonesection whereweworkedwithobjectsratherthanclasses, Section3.8 ,itdidn'tseemtomakemuch dierence:Wejustlefttheword\ static "outofthesubroutinedenitions! Ihavesaidthatclasses\describe"objects,ormoreexactly thatthenon-staticportionsof classesdescribeobjects.Butit'sprobablynotveryclearw hatthismeans.Themoreusual terminologyistosaythatobjects belongto classes,butthismightnotbemuchclearer.(There isarealshortageofEnglishwordstoproperlydistinguisha lltheconceptsinvolved.Anobject certainlydoesn't\belong"toaclassinthesamewaythatame mbervariable\belongs"toa class.)Fromthepointofviewofprogramming,itismoreexac ttosaythatclassesareused tocreateobjects.Aclassisakindoffactoryforconstructi ngobjects.Thenon-staticpartsof theclassspecify,ordescribe,whatvariablesandsubrouti nestheobjectswillcontain.Thisis partoftheexplanationofhowobjectsdierfromclasses:Ob jectsarecreatedanddestroyedas theprogramruns,andtherecanbemanyobjectswiththesames tructure,iftheyarecreated usingthesameclass. Considerasimpleclasswhosejobistogrouptogetherafewst aticmembervariables.For example,thefollowingclasscouldbeusedtostoreinformat ionaboutthepersonwhoisusing theprogram: classUserData{ staticStringname;staticintage; } Inaprogramthatusesthisclass,thereisonlyonecopyofeac hofthevariables UserData.name and UserData.age .Therecanonlybeone\user,"sinceweonlyhavememoryspace tostore dataaboutoneuser.Theclass, UserData ,andthevariablesitcontainsexistaslongasthe programruns.Now,considerasimilarclassthatincludesno n-staticvariables: classPlayerData{ Stringname;intage; } Inthiscase,thereisnosuchvariableas PlayerData.name or PlayerData.age ,since name and age arenotstaticmembersof PlayerData .So,thereisnothingmuchintheclassatall| exceptthepotentialtocreateobjects.But,it'salotofpot ential,sinceitcanbeusedtocreate anynumberofobjects!Eachobjectwillhaveits own variablescalled name and age .There canbemany\players"becausewecanmakenewobjectstorepre sentnewplayersondemand. Aprogrammightusethisclasstostoreinformationaboutmul tipleplayersinagame.Each playerhasanameandanage.Whenaplayerjoinsthegame,anew PlayerData objectcan becreatedtorepresentthatplayer.Ifaplayerleavesthega me,the PlayerData objectthat representsthatplayercanbedestroyed.Asystemofobjects intheprogramisbeingusedto dynamicallymodelwhatishappeninginthegame.Youcan'tdo thiswith\static"variables! In Section3.8 ,weworkedwithapplets,whichareobjects.Thereasontheyd idn'tseemto beanydierentfromclassesisbecausewewereonlyworkingw ithoneappletineachclassthat welookedat.Butoneclasscanbeusedtomakemanyapplets.Th inkofanappletthatscrolls

PAGE 179

CHAPTER5.OBJECTSANDCLASSES 165 amessageacrossaWebpage.Therecouldbeseveralsuchapple tsonthesamepage,allcreated fromthesameclass.Ifthescrollingmessageintheappletis storedinanon-staticvariable, theneachappletwillhaveitsownvariable,andeachappletc anshowadierentmessage.The situationisevenclearerifyouthinkaboutwindows,which, likeapplets,areobjects.Asa programruns,manywindowsmightbeopenedandclosed,butal lthosewindowscanbelong tothesameclass.Hereagain,wehaveadynamicsituationwhe remultipleobjectsarecreated anddestroyedasaprogramruns. Anobjectthatbelongstoaclassissaidtobean instance ofthatclass.Thevariablesthat theobjectcontainsarecalled instancevariables .Thesubroutinesthattheobjectcontains arecalled instancemethods .(Recallthatinthecontextofobject-orientedprogrammin g, method isasynonymfor\subroutine".Fromnowon,sincewearedoing object-oriented programming,Iwillprefertheterm\method.")Forexample, ifthe PlayerData class,as denedabove,isusedtocreateanobject,thenthatobjectis aninstanceofthe PlayerData class,and name and age areinstancevariablesintheobject.Itisimportanttoreme mberthat theclassofanobjectdeterminesthe types oftheinstancevariables;however,theactualdata iscontainedinsidetheindividualobjects,nottheclass.T hus,eachobjecthasitsownsetof data. AnappletthatscrollsamessageacrossaWebpagemightinclu deasubroutinenamed scroll() .Sincetheappletisanobject,thissubroutineisaninstanc emethodoftheapplet. Thesourcecodeforthemethodisintheclassthatisusedtocr eatetheapplet.Still,it'sbetter tothinkoftheinstancemethodasbelongingtotheobject,no ttotheclass.Thenon-static subroutinesintheclassmerelyspecifytheinstancemethod sthateveryobjectcreatedfromthe classwillcontain.The scroll() methodsintwodierentappletsdothesamethinginthe sensethattheybothscrollmessagesacrossthescreen.Butt hereisarealdierencebetween thetwo scroll() methods.Themessagesthattheyscrollcanbedierent.Youm ightsaythat themethoddenitionintheclassspecieswhattypeofbehav iortheobjectswillhave,but thespecicbehaviorcanvaryfromobjecttoobject,dependi ngonthevaluesoftheirinstance variables. Asyoucansee,thestaticandthenon-staticportionsofacla ssareverydierentthingsand serveverydierentpurposes.Manyclassescontainonlysta ticmembers,oronlynon-static. However,itispossibletomixstaticandnon-staticmembers inasingleclass,andwe'llsee afewexampleslaterinthischapterwhereitisreasonableto doso.Youshoulddistiguish betweenthe sourcecode fortheclass,andthe classitself .Thesourcecodedeterminesboth theclassandtheobjectsthatarecreatedfromthatclass.Th e\static"denitionsinthesource codespecifythethingsthatarepartoftheclassitself,whe reasthenon-staticdenitionsinthe sourcecodespecifythingsthatwillbecomepartofeveryins tanceobjectthatiscreatedfrom theclass.Bytheway,staticmembervariablesandstaticmem bersubroutinesinaclassare sometimescalled classvariables and classmethods ,sincetheybelongtotheclassitself, ratherthantoinstancesofthatclass.5.1.2FundamentalsofObjectsSofar,I'vebeentalkingmostlyingeneralities,andIhaven 'tgivenyoumuchideawhatyou havetoputinaprogramifyouwanttoworkwithobjects.Let's lookataspecicexampleto seehowitworks.Considerthisextremelysimpliedversion ofa Student class,whichcouldbe usedtostoreinformationaboutstudentstakingacourse:

PAGE 180

CHAPTER5.OBJECTSANDCLASSES 166 publicclassStudent{ publicStringname;//Student'sname.publicdoubletest1,test2,test3;//Gradesonthreetests.publicdoublegetAverage(){//computeaveragetestgrade return(test1+test2+test3)/3; } }//endofclassStudent Noneofthemembersofthisclassaredeclaredtobe static ,sotheclassexistsonlyfor creatingobjects.Thisclassdenitionsaysthatanyobject thatisaninstanceofthe Student classwillincludeinstancevariablesnamed name test1 test2 ,and test3 ,anditwillincludean instancemethodnamed getAverage() .Thenamesandtestsindierentobjectswillgenerally havedierentvalues.Whencalledforaparticularstudent, themethod getAverage() will computeanaverageusing thatstudent's testgrades.Dierentstudentscanhavedierent averages.(Again,thisiswhatitmeanstosaythataninstanc emethodbelongstoanindividual object,nottotheclass.) InJava,aclassisa type ,similartothebuilt-intypessuchas int and boolean .So,aclass namecanbeusedtospecifythetypeofavariableinadeclarat ionstatement,thetypeofa formalparameter,orthereturntypeofafunction.Forexamp le,aprogramcoulddenea variablenamed std oftype Student withthestatement Studentstd; However,declaringavariabledoes not createanobject!Thisisanimportantpoint,whichis relatedtothisVeryImportantFact: InJava,novariablecaneverholdanobject. Avariablecanonlyholdareferencetoanobject. Youshouldthinkofobjectsasroatingaroundindependently inthecomputer'smemory.In fact,thereisaspecialportionofmemorycalledthe heap whereobjectslive.Insteadofholding anobjectitself,avariableholdstheinformationnecessar ytondtheobjectinmemory.This informationiscalleda reference or pointer totheobject.Ineect,areferencetoanobject istheaddressofthememorylocationwheretheobjectisstor ed.Whenyouuseavariableof classtype,thecomputerusesthereferenceinthevariablet ondtheactualobject. Inaprogram,objectsarecreatedusinganoperatorcalled new ,whichcreatesanobject andreturnsareferencetothatobject.Forexample,assumin gthat std isavariableoftype Student ,declaredasabove,theassignmentstatement std=newStudent(); wouldcreateanewobjectwhichisaninstanceoftheclass Student ,anditwouldstorea referencetothatobjectinthevariable std .Thevalueofthevariableisareferencetothe object,nottheobjectitself.Itisnotquitetrue,then,tos aythattheobjectisthe\valueof thevariable std "(thoughsometimesitishardtoavoidusingthisterminolog y).Itiscertainly notatalltrue tosaythattheobjectis\storedinthevariable std ."Theproperterminology isthat\thevariable std refersto theobject,"andIwilltrytosticktothatterminologyas muchaspossible. So,supposethatthevariable std referstoanobjectbelongingtotheclass Student .That objecthasinstancevariables name test1 test2 ,and test3 .Theseinstancevariablescan

PAGE 181

CHAPTER5.OBJECTSANDCLASSES 167 bereferredtoas std.name std.test1 std.test2 ,and std.test3 .Thisfollowstheusual namingconventionthatwhen B ispartof A ,thenthefullnameof B is A.B .Forexample,a programmightincludethelines System.out.println("Hello,"+std.name+".Yourtestgrad esare:"); System.out.println(std.test1);System.out.println(std.test2);System.out.println(std.test3); Thiswouldoutputthenameandtestgradesfromtheobjecttow hich std refers.Similarly, std canbeusedtocallthe getAverage() instancemethodintheobjectbysaying std.getAverage() .Toprintoutthestudent'saverage,youcouldsay: System.out.println("Youraverageis"+std.getAverage() ); Moregenerally,youcoulduse std.name anyplacewhereavariableoftype String islegal. Youcanuseitinexpressions.Youcanassignavaluetoit.You canevenuseittocallsubroutines fromthe String class.Forexample, std.name.length() isthenumberofcharactersinthe student'sname. Itispossibleforavariablelike std ,whosetypeisgivenbyaclass,torefertonoobjectat all.Wesayinthiscasethat std holdsa nullreference .ThenullreferenceiswritteninJava as\ null ".Youcanstoreanullreferenceinthevariable std bysaying std=null; andyoucouldtestwhetherthevalueof std isnullbytesting if(std==null)... Ifthevalueofavariableis null ,thenitis,ofcourse,illegaltorefertoinstancevariable s orinstancemethodsthroughthatvariable|sincethereisno object,andhencenoinstance variablestoreferto.Forexample,ifthevalueofthevariab le std is null ,thenitwouldbe illegaltoreferto std.test1 .Ifyourprogramattemptstouseanullreferenceillegallyl ikethis, theresultisanerrorcalleda nullpointerexception Let'slookatasequenceofstatementsthatworkwithobjects : Studentstd,std1,//Declarefourvariablesof std2,std3;//typeStudent. std=newStudent();//Createanewobjectbelonging //totheclassStudent,and//storeareferencetothat//objectinthevariablestd. std1=newStudent();//CreateasecondStudentobject //andstoreareferenceto//itinthevariablestd1. std2=std1;//Copythereferencevalueinstd1 //intothevariablestd2. std3=null;//Storeanullreferenceinthe //variablestd3. std.name="JohnSmith";//Setvaluesofsomeinstancevaria bles. std1.name="MaryJones"; //(Otherinstancevariableshavedefault//initialvaluesofzero.)

PAGE 182

CHAPTER5.OBJECTSANDCLASSES 168 Afterthecomputerexecutesthesestatements,thesituatio ninthecomputer'smemorylooks likethis: Thispictureshowsvariablesaslittleboxes,labeledwitht henamesofthevariables.Objects areshownasboxeswithroundcorners.Whenavariablecontai nsareferencetoanobject,the valueofthatvariableisshownasanarrowpointingtotheobj ect.Thevariable std3 ,witha valueof null ,doesn'tpointanywhere.Thearrowsfrom std1 and std2 bothpointtothesame object.ThisillustratesaVeryImportantPoint: Whenoneobjectvariableisassigned toanother,onlyareferenceiscopied. Theobjectreferredtoisnotcopied. Whentheassignment\ std2=std1 ;"wasexecuted,nonewobjectwascreated.Instead, std2 wassettorefertotheverysameobjectthat std1 refersto.Thishassomeconsequencesthat mightbesurprising.Forexample, std1.name and std2.name aretwodierentnamesforthe samevariable,namelytheinstancevariableintheobjectth atboth std1 and std2 referto. Afterthestring "MaryJones" isassignedtothevariable std1.name ,itisalsotruethatthe valueof std2.name is "MaryJones" .Thereisapotentialforalotofconfusionhere,butyou canhelpprotectyourselffromitifyoukeeptellingyoursel f,\Theobjectisnotinthevariable. Thevariablejustholdsapointertotheobject." Youcantestobjectsforequalityandinequalityusingtheop erators == and != ,but hereagain,thesemanticsaredierentfromwhatyouareused to.Whenyoumakeatest \ if(std1==std2) ",youaretestingwhetherthevaluesstoredin std1 and std2 arethe same.Butthevaluesarereferencestoobjects,notobjects. So,youaretestingwhether std1 and std2 refertothesameobject,thatis,whethertheypointtothesa melocation

PAGE 183

CHAPTER5.OBJECTSANDCLASSES 169 inmemory.Thisisne,ifitswhatyouwanttodo.Butsometime s,whatyouwantto checkiswhethertheinstancevariablesintheobjectshavet hesamevalues.Todothat,you wouldneedtoaskwhether\ std1.test1==std2.test1&&std1.test2==std2.test2&& std1.test3==std2.test3&&std1.name.equals(std2.name) ". I'veremarkedpreviouslythat Strings areobjects,andI'veshownthestrings "MaryJones" and "JohnSmith" asobjectsintheaboveillustration.Avariableoftype String canonlyhold areferencetoastring,notthestringitself.Itcouldalsoh oldthevalue null ,meaningthat itdoesnotrefertoanystringatall.Thisexplainswhyusing the == operatortoteststrings forequalityisnotagoodidea.Supposethat greeting isavariableoftype String ,andthat thestringitreferstois "Hello" .Thenwouldthetest greeting=="Hello" betrue?Well, maybe,maybenot.Thevariable greeting andthe String literal "Hello" eachrefertoa stringthatcontainsthecharactersH-e-l-l-o.Butthestri ngscouldstillbedierentobjects, thatjusthappentocontainthesamecharacters.Thefunctio n greeting.equals("Hello") testswhether greeting and "Hello" containthesamecharacters,whichisalmostcertainly thequestionyouwanttoask.Theexpression greeting=="Hello" testswhether greeting and "Hello" containthesamecharacters storedinthesamememorylocation Thefactthatvariablesholdreferencestoobjects,notobje ctsthemselves,hasacoupleof otherconsequencesthatyoushouldbeawareof.Theyfollowl ogically,ifyoujustkeepinmind thebasicfactthattheobjectisnotstoredinthevariable.T heobjectissomewhereelse;the variablepointstoit. Supposethatavariablethatreferstoanobjectisdeclaredt obe final .Thismeansthat thevaluestoredinthevariablecanneverbechanged,onceth evariablehasbeeninitialized. Thevaluestoredinthevariableisareferencetotheobject. Sothevariablewillcontinueto refertothesameobjectaslongasthevariableexists.Howev er,thisdoesnotpreventthedata intheobject fromchanging.Thevariableis final ,nottheobject.It'sperfectlylegaltosay finalStudentstu=newStudent();stu.name="JohnDoe";//Changedataintheobject; //Thevaluestoredinstuisnotchanged!//Itstillreferstothesameobject. Next,supposethat obj isavariablethatreferstoanobject.Let'sconsiderwhatha ppens when obj ispassedasanactualparametertoasubroutine.Thevalueof obj isassignedto aformalparameterinthesubroutine,andthesubroutineise xecuted.Thesubroutinehasno powertochangethevaluestoredinthevariable, obj .Itonlyhasacopyofthatvalue.However, thatvalueisareferencetoanobject.Sincethesubroutineh asareferencetotheobject,itcan changethedatastoredintheobject.Afterthesubroutineen ds, obj stillpointstothesame object,butthedatastored intheobject mighthavechanged.Suppose x isavariableoftype int and stu isavariableoftype Student .Compare: voiddontChange(intz){voidchange(Students){ z=42; s.name="Fred"; } } Thelines:Thelines: x=17; stu.name="Jane"; dontChange(x);change(stu);System.out.println(x);System.out.println(stu.name);

PAGE 184

CHAPTER5.OBJECTSANDCLASSES 170 outputthevalue17.outputthevalue"Fred".ThevalueofxisnotThevalueofstuisnotchangedbythesubroutine,changed,butstu.nameis.whichisequivalenttoThisisequivalentto z=x; s=stu; z=42; s.name="Fred"; 5.1.3GettersandSettersWhenwritingnewclasses,it'sagoodideatopayattentionto theissueofaccesscontrol.Recall thatmakingamemberofaclass public makesitaccessiblefromanywhere,includingfrom otherclasses.Ontheotherhand,a private membercanonlybeusedintheclasswhereitis dened. Intheopinionofmanyprogrammers,almostallmembervariab lesshouldbedeclared private .Thisgivesyoucompletecontroloverwhatcanbedonewithth evariable.Even ifthevariableitselfisprivate,youcanallowotherclasse stondoutwhatitsvalueisbyprovidinga public accessormethod thatreturnsthevalueofthevariable.Forexample,ifyour classcontainsa private membervariable, title ,oftype String ,youcanprovideamethod publicStringgetTitle(){ returntitle; } thatreturnsthevalueof title .Byconvention,thenameofanaccessormethodforavariable isobtainedbycapitalizingthenameofvariableandadding\ get"infrontofthename.So,for thevariable title ,wegetanaccessormethodnamed\get" + \Title",or getTitle() .Because ofthisnamingconvention,accessormethodsaremoreoftenr eferredtoas gettermethods .A gettermethodprovides\readaccess"toavariable. Youmightalsowanttoallow\writeaccess"toa private variable.Thatis,youmight wanttomakeitpossibleforotherclassestospecifyanewval ueforthevariable.Thisisdone witha settermethod .(Ifyoudon'tlikesimple,Anglo-Saxonwords,youcanuseth efancier term mutatormethod .)Thenameofasettermethodshouldconsistof\set"followe dbya capitalizedcopyofthevariable'sname,anditshouldhavea parameterwiththesametypeas thevariable.Asettermethodforthevariable title couldbewritten publicvoidsetTitle(StringnewTitle){ title=newTitle; } Itisactuallyverycommontoprovidebothagetterandasette rmethodforaprivate membervariable.Sincethisallowsotherclassesbothtosee andtochangethevalueofthe variable,youmightwonderwhynotjustmakethevariable public ?Thereasonisthatgetters andsettersarenotrestrictedtosimplyreadingandwriting thevariable'svalue.Infact,they cantakeanyactionatall.Forexample,agettermethodmight keeptrackofthenumberof timesthatthevariablehasbeenaccessed: publicStringgetTitle(){ titleAccessCount++;//IncrementmembervariabletitleAc cessCount. returntitle; } andasettermethodmightcheckthatthevaluethatisbeingas signedtothevariableislegal:

PAGE 185

CHAPTER5.OBJECTSANDCLASSES 171 publicvoidsetTitle(StringnewTitle){ if(newTitle==null)//Don'tallownullstringsastitles! title="(Untitled)";//Useanappropriatedefaultvaluein stead. else title=newTitle; } Evenifyoucan'tthinkofanyextrachorestodoinagetterors ettermethod,youmightchange yourmindinthefuturewhenyouredesignandimproveyourcla ss.Ifyou'veusedagetterand setterfromthebeginning,youcanmakethemodicationtoyo urclasswithoutaectinganyof theclassesthatuseyourclass.The private membervariableisnotpartofthepublicinterface ofyourclass;onlythe public getterandsettermethodsare.Ifyou haven't usedgetandset fromthebeginning,you'llhavetocontacteveryonewhouses yourclassandtellthem,\Sorry guys,you'llhavetotrackdowneveryusethatyou'vemadeoft hisvariableandchangeyour codetousemynewgetandsetmethodsinstead." Acoupleofnalnotes:SomeadvancedaspectsofJavarelyont henamingconvention forgetterandsettermethods,soit'sagoodideatofollowth econventionrigorously.And thoughI'vebeentalkingaboutusinggetterandsettermetho dsforavariable,youcandene getandsetmethodsevenifthereisnovariable.Agetterand/ orsettermethoddenesa property oftheclass,thatmightormightnotcorrespondtoavariable .Forexample,ifaclass includesa publicvoid instancemethodwithsignature setValue(double) ,thentheclasshas a\property"named value oftype double ,andithasthispropertywhetherornottheclass hasamembervariablenamed value 5.2ConstructorsandObjectInitializationO bjecttypesinJava areverydierentfromtheprimitivetypes.Simplydeclarin gavariable (online) whosetypeisgivenasaclassdoesnotautomaticallycreatea nobjectofthatclass.Objects mustbeexplicitly constructed .Forthecomputer,theprocessofconstructinganobjectmea ns, rst,ndingsomeunusedmemoryintheheapthatcanbeusedto holdtheobjectand,second, llingintheobject'sinstancevariables.Asaprogrammer, youdon'tcarewhereinmemory theobjectisstored,butyouwillusuallywanttoexerciseso mecontroloverwhatinitialvalues arestoredinanewobject'sinstancevariables.Inmanycase s,youwillalsowanttodomore complicatedinitializationorbookkeepingeverytimeanob jectiscreated. 5.2.1InitializingInstanceVariablesAninstancevariablecanbeassignedaninitialvalueinitsd eclaration,justlikeanyother variable.Forexample,consideraclassnamed PairOfDice .Anobjectofthisclasswillrepresent apairofdice.Itwillcontaintwoinstancevariablestorepr esentthenumbersshowingonthe diceandaninstancemethodforrollingthedice: publicclassPairOfDice{ publicintdie1=3;//Numbershowingonthefirstdie.publicintdie2=4;//Numbershowingontheseconddie.publicvoidroll(){ //Rollthedicebysettingeachofthedicetobe//arandomnumberbetween1and6. die1=(int)(Math.random()*6)+1;

PAGE 186

CHAPTER5.OBJECTSANDCLASSES 172 die2=(int)(Math.random()*6)+1; } }//endclassPairOfDice Theinstancevariables die1 and die2 areinitializedtothevalues3and4respectively.These initializationsareexecutedwhenevera PairOfDice objectisconstructed.It'simportantto understandwhenandhowthishappens.Therecanbemany PairOfDice objects.Eachtimeone iscreated,itgetsitsowninstancevariables,andtheassig nments\ die1=3 "and\ die2=4 areexecutedtollinthevaluesofthosevariables.Tomaket hisclearer,consideravariation ofthe PairOfDice class: publicclassPairOfDice{ publicintdie1=(int)(Math.random()*6)+1;publicintdie2=(int)(Math.random()*6)+1;publicvoidroll(){ die1=(int)(Math.random()*6)+1;die2=(int)(Math.random()*6)+1; } }//endclassPairOfDice Here,thediceareinitializedtorandomvalues,asifanewpa irofdicewerebeingthrownonto thegamingtable.Sincetheinitializationisexecutedfore achnewobject,asetofrandominitial valueswillbecomputedforeachnewpairofdice.Dierentpa irsofdicecanhavedierent initialvalues.Forinitializationof static membervariables,ofcourse,thesituationisquite dierent.Thereisonlyonecopyofa static variable,andinitializationofthatvariableis executedjustonce,whentheclassisrstloaded. Ifyoudon'tprovideanyinitialvalueforaninstancevariab le,adefaultinitialvalueisprovidedautomatically.Instancevariablesofnumericaltype ( int double ,etc.)areautomatically initializedtozeroifyouprovidenoothervalues; boolean variablesareinitializedto false ;and char variables,totheUnicodecharacterwithcodenumberzero.A ninstancevariablecanalso beavariableofobjecttype.Forsuchvariables,thedefault initialvalueis null .(Inparticular, since Strings areobjects,thedefaultinitialvaluefor String variablesis null .) 5.2.2ConstructorsObjectsarecreatedwiththeoperator, new .Forexample,aprogramthatwantstousea PairOfDice objectcouldsay: PairOfDicedice;//DeclareavariableoftypePairOfDice.dice=newPairOfDice();//Constructanewobjectandstorea //referencetoitinthevariable. Inthisexample,\ newPairOfDice() "isanexpressionthatallocatesmemoryfortheobject, initializestheobject'sinstancevariables,andthenretu rnsareferencetotheobject.This referenceisthevalueoftheexpression,andthatvalueisst oredbytheassignmentstatementin thevariable, dice ,sothataftertheassignmentstatementisexecuted, dice referstothenewly createdobject.Partofthisexpression,\ PairOfDice() ",lookslikeasubroutinecall,andthat isnoaccident.Itis,infact,acalltoaspecialtypeofsubro utinecalleda constructor .This mightpuzzleyou,sincethereisnosuchsubroutineinthecla ssdenition.However,everyclass hasatleastoneconstructor.Iftheprogrammerdoesn'twrit eaconstructordenitioninaclass,

PAGE 187

CHAPTER5.OBJECTSANDCLASSES 173 thenthesystemwillprovidea defaultconstructor forthatclass.Thisdefaultconstructor doesnothingbeyondthebasics:allocatememoryandinitial izeinstancevariables.Ifyouwant morethanthattohappenwhenanobjectiscreated,youcaninc ludeoneormoreconstructors intheclassdenition. Thedenitionofaconstructorlooksmuchlikethedenition ofanyothersubroutine,with threeexceptions.Aconstructordoesnothaveanyreturntyp e(noteven void ).Thenameof theconstructormustbethesameasthenameoftheclassinwhi chitisdened.Theonly modiersthatcanbeusedonaconstructordenitionarethea ccessmodiers public private and protected .(Inparticular,aconstructorcan'tbedeclared static .) However,aconstructordoeshaveasubroutinebodyoftheusu alform,ablockofstatements. Therearenorestrictionsonwhatstatementscanbeused.And itcanhavealistofformal parameters.Infact,theabilitytoincludeparametersison eofthemainreasonsforusing constructors.Theparameterscanprovidedatatobeusedint heconstructionoftheobject. Forexample,aconstructorforthe PairOfDice classcouldprovidethevaluesthatareinitially showingonthedice.Hereiswhattheclasswouldlooklikeint hatcase: publicclassPairOfDice{ publicintdie1;//Numbershowingonthefirstdie.publicintdie2;//Numbershowingontheseconddie.publicPairOfDice(intval1,intval2){ //Constructor.Createsapairofdicethat//areinitiallyshowingthevaluesval1andval2. die1=val1;//Assignspecifiedvaluesdie2=val2;//totheinstancevariables. }publicvoidroll(){ //Rollthedicebysettingeachofthedicetobe//arandomnumberbetween1and6. die1=(int)(Math.random()*6)+1;die2=(int)(Math.random()*6)+1; } }//endclassPairOfDice Theconstructorisdeclaredas\ publicPairOfDice(intval1,intval2)... ",withno returntypeandwiththesamenameasthenameoftheclass.Thi sishowtheJavacompilerrecognizesaconstructor.Theconstructorhastwopar ameters,andvaluesforthese parametersmustbeprovidedwhentheconstructoriscalled. Forexample,theexpression \ newPairOfDice(3,4) "wouldcreatea PairOfDice objectinwhichthevaluesoftheinstance variables die1 and die2 areinitially3and4.Ofcourse,inaprogram,thevalueretur nedby theconstructorshouldbeusedinsomeway,asin PairOfDicedice;//DeclareavariableoftypePairOfDice.dice=newPairOfDice(1,1);//LetdicerefertoanewPairOfD ice //objectthatinitiallyshows1,1. Nowthatwe'veaddedaconstructortothe PairOfDice class,wecannolongercreate anobjectbysaying\ newPairOfDice() "!Thesystemprovidesadefaultconstructorfora class only iftheclassdenitiondoesnotalreadyincludeaconstructo r,sothereisonlyone constructorintheclass,anditrequirestwoactualparamet ers.However,thisisnotabig

PAGE 188

CHAPTER5.OBJECTSANDCLASSES 174 problem,sincewecanaddasecondconstructortotheclass,o nethathasnoparameters.In fact,youcanhaveasmanydierentconstructorsasyouwant, aslongastheirsignaturesare dierent,thatis,aslongastheyhavedierentnumbersorty pesofformalparameters.Inthe PairOfDice class,wemighthaveaconstructorwithnoparameterswhichp roducesapairof diceshowingrandomnumbers: publicclassPairOfDice{ publicintdie1;//Numbershowingonthefirstdie.publicintdie2;//Numbershowingontheseconddie.publicPairOfDice(){ //Constructor.Rollsthedice,sothattheyinitially//showsomerandomvalues. roll();//Calltheroll()methodtorollthedice. }publicPairOfDice(intval1,intval2){ //Constructor.Createsapairofdicethat//areinitiallyshowingthevaluesval1andval2. die1=val1;//Assignspecifiedvaluesdie2=val2;//totheinstancevariables. }publicvoidroll(){ //Rollthedicebysettingeachofthedicetobe//arandomnumberbetween1and6. die1=(int)(Math.random()*6)+1;die2=(int)(Math.random()*6)+1; } }//endclassPairOfDice Nowwehavetheoptionofconstructinga PairOfDice objecteitherwith\ newPairOfDice() orwith\ newPairOfDice(x,y) ",where x and y are int -valuedexpressions. Thisclass,onceitiswritten,canbeusedinanyprogramthat needstoworkwithone ormorepairsofdice.Noneofthoseprogramswilleverhaveto usetheobscureincantation \ (int)(Math.random()*6)+1 ",becauseit'sdoneinsidethe PairOfDice class.Andtheprogrammer,havingoncegottenthedice-rollingthingstraigh twillneverhavetoworryaboutit again.Here,forexample,isamainprogramthatusesthe PairOfDice classtocounthowmany timestwopairsofdicearerolledbeforethetwopairscomeup showingthesamevalue.This illustratesonceagainthatyoucancreateseveralinstance softhesameclass: publicclassRollTwoPairs{ publicstaticvoidmain(String[]args){ PairOfDicefirstDice;//Referstothefirstpairofdice.firstDice=newPairOfDice();PairOfDicesecondDice;//Referstothesecondpairofdice.secondDice=newPairOfDice();intcountRolls;//Countshowmanytimesthetwopairsof //dicehavebeenrolled. inttotal1;//Totalshowingonfirstpairofdice.inttotal2;//Totalshowingonsecondpairofdice.

PAGE 189

CHAPTER5.OBJECTSANDCLASSES 175 countRolls=0;do{//Rollthetwopairsofdiceuntiltotalsarethesame. firstDice.roll();//Rollthefirstpairofdice.total1=firstDice.die1+firstDice.die2;//Gettotal.System.out.println("Firstpaircomesup"+total1);secondDice.roll();//Rollthesecondpairofdice.total2=secondDice.die1+secondDice.die2;//Gettotal.System.out.println("Secondpaircomesup"+total2);countRolls++;//Countthisroll.System.out.println();//Blankline. }while(total1!=total2);System.out.println("Ittook"+countRolls +"rollsuntilthetotalswerethesame."); }//endmain() }//endclassRollTwoPairs Constructorsaresubroutines,buttheyaresubroutinesofa specialtype.Theyarecertainly notinstancemethods,sincetheydon'tbelongtoobjects.Si ncetheyareresponsibleforcreating objects,theyexistbeforeanyobjectshavebeencreated.Th eyaremorelike static member subroutines,buttheyarenotandcannotbedeclaredtobe static .Infact,accordingtothe Javalanguagespecication,theyaretechnicallynotmembe rsoftheclassatall!Inparticular, constructorsare not referredtoas\methods." Unlikeothersubroutines,aconstructorcanonlybecalledu singthe new operator,inan expressionthathastheform new h class-name i ( h parameter-list i ) wherethe h parameter-list i ispossiblyempty.Icallthisanexpressionbecauseitcompu tesand returnsavalue,namelyareferencetotheobjectthatiscons tructed.Mostoften,youwillstore thereturnedreferenceinavariable,butitisalsolegaltou seaconstructorcallinotherways, forexampleasaparameterinasubroutinecalloraspartofam orecomplexexpression.Of course,ifyoudon'tsavethereferenceinavariable,youwon 'thaveanywayofreferringtothe objectthatwasjustcreated. Aconstructorcallismorecomplicatedthananordinarysubr outineorfunctioncall.Itis helpfultounderstandtheexactstepsthatthecomputergoes throughtoexecuteaconstructor call: 1. First,thecomputergetsablockofunusedmemoryintheheap, largeenoughtoholdan objectofthespeciedtype. 2. Itinitializestheinstancevariablesoftheobject.Ifthed eclarationofaninstancevariable speciesaninitialvalue,thenthatvalueiscomputedandst oredintheinstancevariable. Otherwise,thedefaultinitialvalueisused. 3. Theactualparametersintheconstructor,ifany,areevalua ted,andthevaluesareassigned totheformalparametersoftheconstructor.

PAGE 190

CHAPTER5.OBJECTSANDCLASSES 176 4. Thestatementsinthebodyoftheconstructor,ifany,areexe cuted. 5. Areferencetotheobjectisreturnedasthevalueoftheconst ructorcall. Theendresultofthisisthatyouhaveareferencetoanewlyco nstructedobject.Youcan usethisreferencetogetattheinstancevariablesinthatob jectortocallitsinstancemethods. Foranotherexample,let'srewritethe Student classthatwasusedinSection1.I'lladda constructor,andI'llalsotaketheopportunitytomakethei nstancevariable, name ,private. publicclassStudent{ privateStringname;//Student'sname.publicdoubletest1,test2,test3;//Gradesonthreetests.Student(StringtheName){ //ConstructorforStudentobjects;//providesanamefortheStudent. name=theName; }publicStringgetName(){ //Gettermethodforreadingthevalueoftheprivate//instancevariable,name. returnname; }publicdoublegetAverage(){ //Computeaveragetestgrade. return(test1+test2+test3)/3; } }//endofclassStudent Anobjectoftype Student containsinformationaboutsomeparticularstudent.Theco nstructorinthisclasshasaparameteroftype String ,whichspeciesthenameofthatstudent. Objectsoftype Student canbecreatedwithstatementssuchas: std=newStudent("JohnSmith");std1=newStudent("MaryJones"); Intheoriginalversionofthisclass,thevalueof name hadtobeassignedbyaprogramafter itcreatedtheobjectoftype Student .Therewasnoguaranteethattheprogrammerwould alwaysremembertosetthe name properly.Inthenewversionoftheclass,thereisnowayto createa Student objectexceptbycallingtheconstructor,andthatconstruc torautomatically setsthe name .Theprogrammer'slifeismadeeasier,andwholehordesoffr ustratingbugsare squashedbeforetheyevenhaveachancetobeborn. Anothertypeofguaranteeisprovidedbythe private modier.Sincetheinstancevariable, name ,is private ,thereisnowayforanypartoftheprogramoutsidethe Student classto getatthe name directly.Theprogramsetsthevalueof name ,indirectly,whenitcallsthe constructor.I'veprovidedafunction, getName() ,thatcanbeusedfromoutsidetheclassto ndoutthe name ofthestudent.ButIhaven'tprovidedanysettermethodorot herwayto changethename.Onceastudentobjectiscreated,itkeepsth esamenameaslongasitexists.

PAGE 191

CHAPTER5.OBJECTSANDCLASSES 177 5.2.3GarbageCollectionSofar,thissectionhasbeenaboutcreatingobjects.Whatab outdestroyingthem?InJava, thedestructionofobjectstakesplaceautomatically. Anobjectexistsintheheap,anditcanbeaccessedonlythrou ghvariablesthathold referencestotheobject.Whatshouldbedonewithanobjecti ftherearenovariablesthat refertoit?Suchthingscanhappen.Considerthefollowingt wostatements(thoughinreality, you'dneverdoanythinglikethis): Studentstd=newStudent("JohnSmith");std=null; Intherstline,areferencetoanewlycreated Student objectisstoredinthevariable std Butinthenextline,thevalueof std ischanged,andthereferencetothe Student objectis gone.Infact,therearenownoreferenceswhatsoevertothat objectstoredinanyvariable.So thereisnowayfortheprogramevertousetheobjectagain.It mightaswellnotexist.Infact, thememoryoccupiedbytheobjectshouldbereclaimedtobeus edforanotherpurpose. Javausesaprocedurecalled garbagecollection toreclaimmemoryoccupiedbyobjects thatarenolongeraccessibletoaprogram.Itistheresponsi bilityofthesystem,notthe programmer,tokeeptrackofwhichobjectsare\garbage."In theaboveexample,itwasvery easytoseethatthe Student objecthadbecomegarbage.Usually,it'smuchharder.Ifan objecthasbeenusedforawhile,theremightbeseveralrefer encestotheobjectstoredinseveral variables.Theobjectdoesn'tbecomegarbageuntilallthos ereferenceshavebeendropped. Inmanyotherprogramminglanguages,it'stheprogrammer's responsibilitytodeletethe garbage.Unfortunately,keepingtrackofmemoryusageisve ryerror-prone,andmanyserious programbugsarecausedbysucherrors.Aprogrammermightac cidentlydeleteanobjecteven thoughtherearestillreferencestothatobject.Thisiscal leda danglingpointererror ,and itleadstoproblemswhentheprogramtriestoaccessanobjec tthatisnolongerthere.Another typeoferrorisa memoryleak ,whereaprogrammerneglectstodeleteobjectsthatareno longerinuse.Thiscanleadtollingmemorywithobjectstha tarecompletelyinaccessible, andtheprogrammightrunoutofmemoryeventhough,infact,l argeamountsofmemoryare beingwasted. BecauseJavausesgarbagecollection,sucherrorsaresimpl yimpossible.Garbagecollection isanoldideaandhasbeenusedinsomeprogramminglanguages sincethe1960s.Youmight wonderwhyalllanguagesdon'tusegarbagecollection.Inth epast,itwasconsideredtooslow andwasteful.However,researchintogarbagecollectionte chniquescombinedwiththeincredible speedofmoderncomputershavecombinedtomakegarbagecoll ectionfeasible.Programmers shouldrejoice.5.3ProgrammingwithObjectsT hereareseveralways inwhichobject-orientedconceptscanbeappliedtotheproc ess (online) ofdesigningandwritingprograms.Thebroadestoftheseis object-orientedanalysisand design whichappliesanobject-orientedmethodologytotheearlie ststagesofprogramdevelopment,duringwhichtheoveralldesignofaprogramiscreat ed.Here,theideaistoidentify thingsintheproblemdomainthatcanbemodeledasobjects.O nanotherlevel,object-oriented programmingencouragesprogrammerstoproduce generalizedsoftwarecomponents that canbeusedinawidevarietyofprogrammingprojects.

PAGE 192

CHAPTER5.OBJECTSANDCLASSES 178 Ofcourse,forthemostpart,youwillexperience\generaliz edsoftwarecomponents"by usingthestandardclassesthatcomealongwithJava.Webegi nthissectionbylookingatsome built-inclassesthatareusedforcreatingobjects.Atthee ndofthesection,wewillgetback togeneralities.5.3.1SomeBuilt-inClassesAlthoughthefocusofobject-orientedprogrammingisgener allyonthedesignandimplementationofnewclasses,it'simportantnottoforgetthatthedes ignersofJavahavealreadyprovided alargenumberofreusableclasses.Someoftheseclassesare meanttobeextendedtoproduce newclasses,whileotherscanbeuseddirectlytocreateusef ulobjects.AtruemasteryofJava requiresfamiliaritywithalargenumberofbuilt-inclasse s|somethingthattakesalotoftime andexperiencetodevelop.Inthenextchapter,wewillbegin thestudyofJava'sGUIclasses, andyouwillencounterotherbuilt-inclassesthroughoutth eremainderofthisbook.Butlet's takeamomenttolookatafewbuilt-inclassesthatyoumight nduseful. Astringcanbebuiltupfromsmallerpiecesusingthe + operator,butthisisnotveryecient. If str isa String and ch isacharacter,thenexecutingthecommand\ str=str+ch; involvescreatingawholenewstringthatisacopyof str ,withthevalueof ch appended ontotheend.Copyingthestringtakessometime.Buildingup alongstringletterbyletter wouldrequireasurprisingamountofprocessing.Theclass StringBuer makesitpossibletobe ecientaboutbuildingupalongstringfromanumberofsmall erpieces.Todothis,youmust makeanobjectbelongingtothe StringBuer class.Forexample: StringBufferbuffer=newStringBuffer(); (Thisstatementbothdeclaresthevariable buffer andinitializesittorefertoanewlycreated StringBuer object.Combiningdeclarationwithinitializationwascov eredin Subsection4.7.1 andworksforobjectsjustasitdoesforprimitivetypes.) Likea String ,a StringBuer containsasequenceofcharacters.However,itispossiblet o addnewcharactersontotheendofa StringBuffer withoutmakingacopyofthedatathat italreadycontains.If x isavalueofanytypeand buffer isthevariabledenedabove,then thecommand buffer.append(x) willadd x ,convertedintoastringrepresentation,ontothe endofthedatathatwasalreadyinthebuer.Thiscommandact uallymodiesthebuer, ratherthanmakingacopy,andthatcanbedoneeciently.Alo ngstringcanbebuiltup ina StringBuer usingasequenceof append() commands.Whenthestringiscomplete,the function buffer.toString() willreturnacopyofthestringinthebuerasanordinaryval ue oftype String .The StringBuer classisinthestandardpackage java.lang ,soyoucanuseits simplenamewithoutimportingit. Anumberofusefulclassesarecollectedinthepackage java.util .Forexample,thispackage containsclassesforworkingwithcollectionsofobjects.W ewillstudythesecollectionclassesin Chapter10 .Anotherclassinthispackage, java.util.Date ,isusedtorepresenttimes.When a Date objectisconstructedwithoutparameters,theresultrepre sentsthecurrentdateand time,soaneasywaytodisplaythisinformationis: System.out.println(newDate()); Ofcourse,tousethe Date classinthisway,youmustmakeitavailablebyimportingitw ithone ofthestatements\ importjava.util.Date; "or\ importjava.util.*; "atthebeginningof yourprogram.(See Subsection4.5.3 foradiscussionofpackagesand import .) Iwillalsomentiontheclass java.util.Random .Anobjectbelongingtothisclassisa source ofrandomnumbers(or,morepreciselypseudorandomnumbers ).Thestandardfunction

PAGE 193

CHAPTER5.OBJECTSANDCLASSES 179 Math.random() usesoneoftheseobjectsbehindthescenestogenerateitsra ndomnumbers. Anobjectoftype Random cangeneraterandomintegers,aswellasrandomrealnumbers .If randGen iscreatedwiththecommand: RandomrandGen=newRandom(); andif N isapositiveinteger,then randGen.nextInt(N) generatesarandomintegerintherange from 0 to N-1 .Forexample,thismakesitalittleeasiertorollapairofdi ce.Insteadofsaying\ die1=(int)(6*Math.random())+1; ",onecansay\ die1=randGen.nextInt(6)+1; ". (Sinceyoualsohavetoimporttheclass java.util.Random andcreatethe Random object,you mightnotagreethatitisactuallyeasier.)Anobjectoftype Random canalsobeusedtogenerate so-calledGaussiandistributedrandomrealnumbers. Themainpointhere,again,isthatmanyproblemshavealread ybeensolved,andthe solutionsareavailableinJava'sstandardclasses.Ifyoua refacedwithataskthatlookslike itshouldbefairlycommon,itmightbeworthlookingthrough aJavareferencetoseewhether someonehasalreadywrittenaclassthatyoucanuse.5.3.2WrapperClassesandAutoboxingWehavealreadyencounteredtheclasses Double and Integer in Subsection2.5.7 .Theseclasses containthe static methods Double.parseDouble and Integer.parseInteger thatareused toconvertstringstonumericalvalues.Wehavealsoencount eredthe Character classinsome examples,andstaticmethodssuchas Character.isLetter ,whichcanbeusedtotestwhether agivenvalueoftype char isaletter.Thereisasimilarclassforeachoftheotherprim itivetypes, Long Short Byte Float ,and Boolean .Theseclassesarecalled wrapperclasses .Although theycontainuseful static members,theyhaveanotheruseaswell:Theyareusedforcrea ting objectsthatrepresentprimitivetypevalues. Rememberthattheprimitivetypesarenotclasses,andvalue sofprimitivetypearenot objects.However,sometimesit'susefultotreataprimitiv evalueasifitwereanobject.You can'tdothatliterally,butyoucan\wrap"theprimitivetyp evalueinanobjectbelongingto oneofthewrapperclasses. Forexample,anobjectoftype Double containsasingleinstancevariable,oftype double Theobjectisawrapperforthe double value.Forexample,youcancreateanobjectthatwraps the double value 6.0221415e23 with Doubled=newDouble(6.0221415e23); Thevalueof d containsthesameinformationasthevalueoftype double ,butitisanobject.If youwanttoretrievethe double valuethatiswrappedintheobject,youcancallthefunction d.doubleValue() .Similarly,youcanwrapan int inanobjectoftype Integer ,a boolean value inanobjectoftype Boolean ,andsoon.(Asanexampleofwherethiswouldbeuseful,the collectionclassesthatwillbestudiedin Chapter10 canonlyholdobjects.Ifyouwanttoadd aprimitivetypevaluetoacollection,ithastobeputintoaw rapperobjectrst.) InJava5.0,wrapperclasseshavebecomeeasiertouse.Java5 .0introducedautomatic conversionbetweenaprimitivetypeandthecorrespondingw rapperclass.Forexample,if youuseavalueoftype int inacontextthatrequiresanobjectoftype Integer ,the int will automaticallybewrappedinan Integer object.Forexample,youcansay Integeranswer=42; andthecomputerwillsilentlyreadthisasifitwere

PAGE 194

CHAPTER5.OBJECTSANDCLASSES 180 Integeranswer=newInteger(42); Thisiscalled autoboxing .Itworksintheotherdirection,too.Forexample,if d referstoan objectoftype Double ,youcanuse d inanumericalexpressionsuchas 2*d .The double value inside d isautomatically unboxed andmultipliedby2.Autoboxingandunboxingalsoapply tosubroutinecalls.Forexample,youcanpassanactualpara meteroftype int toasubroutine thathasaformalparameteroftype Integer .Infact,autoboxingandunboxingmakeitpossible inmanycircumstancestoignorethedierencebetweenprimi tivetypesandobjects. Thewrapperclassescontainafewotherthingsthatdeservet obementioned. Integer ,for example,containsconstants Integer.MIN VALUE and Integer.MAX VALUE ,whichareequalto thelargestandsmallestpossiblevaluesoftype int ,thatis,to-2147483648and2147483647 respectively.It'scertainlyeasiertorememberthenamest hanthenumericalvalues.Thereare similarnamedconstantsin Long Short ,and Byte Double and Float alsohaveconstantsnamed MIN VALUE and MAX VALUE MAX VALUE stillgivesthelargestnumberthatcanberepresented inthegiventype,but MIN VALUE representsthesmallestpossible positive value.Fortype double Double.MIN VALUE is4.9times10 324 .Since double valueshaveonlyaniteaccuracy, theycan'tgetarbitrarilyclosetozero.Thisistheclosest theycangetwithoutactuallybeing equaltozero. Theclass Double deservesspecialmention,since double saresomuchmorecomplicatedthan integers.Theencodingofrealnumbersintovaluesoftype double hasroomforafewspecialvaluesthatarenotrealnumbersatallinthemathematicalsense .Thesevaluesaregivenbynamed constantsinclass Double : Double.POSITIVE INFINITY Double.NEGATIVE INFINITY ,and Double.NaN .Theinnitevaluescanoccurasthevaluesofcertainmathem aticalexpressions.For example,dividingapositivenumberbyzerowillgivetheres ult Double.POSITIVE INFINITY (It'sevenmorecomplicatedthanthis,actually,becauseth e double typeincludesavalue called\negativezero",written -0.0 .Dividingapositivenumberbynegativezerogives Double.NEGATIVE INFINITY .)Youalsoget Double.POSITIVE INFINITY wheneverthemathematicalvalueofanexpressionisgreaterthan Double.MAX VALUE .Forexample, 1e200*1e200 isconsideredtobeinnite.Thevalue Double.NaN isevenmoreinteresting.\NaN"standsfor NotaNumber ,anditrepresentsanundenedvaluesuchasthesquarerooto fanegative numberortheresultofdividingzerobyzero.Becauseofthee xistenceof Double.NaN ,nomathematicaloperationonrealnumberswilleverthrowanexcept ion;itsimplygives Double.NaN astheresult. Youcantestwhetheravalue, x ,oftype double isinniteorundenedbycallingthe boolean-valuedstaticfunctions Double.isInfinite(x) and Double.isNaN(x) .(It'sespecially importanttouse Double.isNaN() totestforundenedvalues,because Double.NaN hasreallyweirdbehaviorwhenusedwithrelationaloperatorssuc has == .Infact,thevaluesof x==Double.NaN and x!=Double.NaN are bothfalse ,nomatterwhatthevalueof x ,so youreallycan'tusetheseexpressionstotestwhether x is Double.NaN .) 5.3.3Theclass\Object"Wehavealreadyseenthatoneofthemajorfeaturesofobjectorientedprogrammingisthe abilitytocreatesubclassesofaclass.Thesubclassinheri tsallthepropertiesorbehaviorsof theclass,butcanmodifyandaddtowhatitinherits.In Section5.5 ,you'lllearnhowtocreate subclasses.Whatyoudon'tknowyetisthat every classinJava(withjustoneexception)is asubclassofsomeotherclass.Ifyoucreateaclassanddon't explicitlymakeitasubclassof

PAGE 195

CHAPTER5.OBJECTSANDCLASSES 181 someotherclass,thenitautomaticallybecomesasubclasso fthespecialclassnamed Object ( Object istheoneclassthatisnotasubclassofanyotherclass.) Class Object denesseveralinstancemethodsthatareinheritedbyevery otherclass.These methodscanbeusedwithanyobjectwhatsoever.Iwillmentio njustoneofthemhere.You willencountermoreofthemlaterinthebook. Theinstancemethod toString() inclass Object returnsavalueoftype String thatis supposedtobeastringrepresentationoftheobject.You've alreadyusedthismethodimplicitly, anytimeyou'veprintedoutanobjectorconcatenatedanobje ctontoastring.Whenyouuse anobjectinacontextthatrequiresastring,theobjectisau tomaticallyconvertedtotype String bycallingits toString() method. Theversionof toString thatisdenedin Object justreturnsthenameoftheclassthat theobjectbelongsto,concatenatedwithacodenumbercalle dthe hashcode oftheobject; thisisnotveryuseful.Whenyoucreateaclass,youcanwrite anew toString() methodfor it,whichwillreplacetheinheritedversion.Forexample,w emightaddthefollowingmethod toanyofthe PairOfDice classesfromtheprevioussection: publicStringtoString(){ //ReturnaStringrepresentationofapairofdice,wheredie 1 //anddie2areinstancevariablescontainingthenumbersth atare //showingonthetwodice. if(die1==die2) return"double"+die1; else returndie1+"and"+die2; } If dice referstoa PairOfDice object,then dice.toString() willreturnstringssuchas \3and6",\5and1",and\double2",dependingonthenumberss howingonthedice.This methodwouldbeusedautomaticallytoconvert dice totype String inastatementsuchas System.out.println("Thedicecameup"+dice); sothisstatementmightoutput,\Thedicecameup5and1"or\T hedicecameupdouble2". You'llseeanotherexampleofa toString() methodinthenextsection. 5.3.4Object-orientedAnalysisandDesignEveryprogrammerbuildsupastockoftechniquesandexperti seexpressedassnippetsofcode thatcanbereusedinnewprogramsusingthetried-and-truem ethodofcut-and-paste:Theold codeisphysicallycopiedintothenewprogramandthenedite dtocustomizeitasnecessary. Theproblemisthattheeditingiserror-proneandtime-cons uming,andthewholeenterpriseis dependentontheprogrammer'sabilitytopulloutthatparti cularpieceofcodefromlastyear's projectthatlookslikeitmightbemadetot.(Onthelevelof acorporationthatwantsto savemoneybynotreinventingthewheelforeachnewproject, justkeepingtrackofalltheold wheelsbecomesamajortask.) Well-designedclassesaresoftwarecomponentsthatcanber eusedwithoutediting.Awelldesignedclassisnotcarefullycraftedtodoaparticularjo binaparticularprogram.Instead, itiscraftedtomodelsomeparticulartypeofobjectorasing lecoherentconcept.Sinceobjects andconceptscanrecurinmanyproblems,awell-designedcla ssislikelytobereusablewithout modicationinavarietyofprojects.

PAGE 196

CHAPTER5.OBJECTSANDCLASSES 182 Furthermore,inanobject-orientedprogramminglanguage, itispossibletomake subclasses ofanexistingclass.Thismakesclassesevenmorereusable. Ifaclassneedstobecustomized, asubclasscanbecreated,andadditionsormodicationscan bemadeinthesubclasswithout makinganychangestotheoriginalclass.Thiscanbedoneeve niftheprogrammerdoesn't haveaccesstothesourcecodeoftheclassanddoesn'tknowan ydetailsofitsinternal,hidden implementation. The PairOfDice classintheprevioussectionisalreadyanexampleofagener alizedsoftware component,althoughonethatcouldcertainlybeimproved.T heclassrepresentsasingle, coherentconcept,\apairofdice."Theinstancevariablesh oldthedatarelevanttothestate ofthedice,thatis,thenumbershowingoneachofthedice.Th einstancemethodrepresents thebehaviorofapairofdice,thatis,theabilitytoberolle d.Thisclasswouldbereusablein manydierentprogrammingprojects. Ontheotherhand,the Student classfromtheprevioussectionisnotveryreusable.It seemstobecraftedtorepresentstudentsinaparticularcou rsewherethegradewillbebased onthreetests.Iftherearemoretestsorquizzesorpapers,i t'suseless.Iftherearetwopeople intheclasswhohavethesamename,weareintrouble(onereas onwhynumericalstudentID's areoftenused).Admittedly,it'smuchmorediculttodevel opageneral-purposestudentclass thanageneral-purposepair-of-diceclass.Butthispartic ular Student classisgoodmostlyas anexampleinaprogrammingtextbook. Alargeprogrammingprojectgoesthroughanumberofstages, startingwith specication oftheproblemtobesolved,followedby analysis oftheproblemand design ofaprogram tosolveit.Thencomes coding ,inwhichtheprogram'sdesignisexpressedinsomeactual programminglanguage.Thisisfollowedby testing and debugging oftheprogram.Afterthat comesalongperiodof maintenance ,whichmeansxinganynewproblemsthatarefound intheprogramandmodifyingittoadaptittochangingrequir ements.Together,thesestages formwhatiscalledthe softwarelifecycle .(Intherealworld,theidealofconsecutivestages isseldomifeverachieved.Duringtheanalysisstage,itmig htturnoutthatthespecications areincompleteorinconsistent.Aproblemfoundduringtest ingrequiresatleastabriefreturn tothecodingstage.Iftheproblemisseriousenough,itmigh tevenrequireanewdesign. Maintenanceusuallyinvolvesredoingsomeoftheworkfromp reviousstages....) Large,complexprogrammingprojectsareonlylikelytosucc eedifacareful,systematic approachisadoptedduringallstagesofthesoftwarelifecy cle.Thesystematicapproachto programming,usingacceptedprinciplesofgooddesign,isc alled softwareengineering .The softwareengineertriestoecientlyconstructprogramsth atveriablymeettheirspecications andthatareeasytomodifyifnecessary.Thereisawiderange of\methodologies"thatcan beappliedtohelpinthesystematicdesignofprograms.(Mos tofthesemethodologiesseemto involvedrawinglittleboxestorepresentprogramcomponen ts,withlabeledarrowstorepresent relationshipsamongtheboxes.) Wehavebeendiscussingobjectorientationinprogrammingl anguages,whichisrelevantto thecodingstageofprogramdevelopment.Buttherearealsoo bject-orientedmethodologiesfor analysisanddesign.Thequestioninthisstageofthesoftwa relifecycleis,Howcanonediscover orinventtheoverallstructureofaprogram?Asanexampleof arathersimpleobject-oriented approachtoanalysisanddesign,considerthisadvice:Writ edownadescriptionoftheproblem. Underlineallthenounsinthatdescription.Thenounsshoul dbeconsideredascandidatesfor becomingclassesorobjectsintheprogramdesign.Similarl y,underlinealltheverbs.These

PAGE 197

CHAPTER5.OBJECTSANDCLASSES 183 arecandidatesformethods.Thisisyourstartingpoint.Fur theranalysismightuncoverthe needformoreclassesandmethods,anditmightrevealthatsu bclassingcanbeusedtotake advantageofsimilaritiesamongclasses. Thisisperhapsabitsimple-minded,buttheideaisclearand thegeneralapproachcanbe eective:Analyzetheproblemtodiscovertheconceptsthat areinvolved,andcreateclassesto representthoseconcepts.Thedesignshouldarisefromthep roblemitself,andyoushouldend upwithaprogramwhosestructurererectsthestructureofth eprobleminanaturalway. 5.4ProgrammingExample:Card,Hand,DeckInthissection,welookatsomespecicexamplesofobject-o rienteddesigninadomainthat issimpleenoughthatwehaveachanceofcomingupwithsometh ingreasonablyreusable. Considercardgamesthatareplayedwithastandarddeckofpl ayingcards(aso-called\poker" deck,sinceitisusedinthegameofpoker).5.4.1DesigningtheclassesInatypicalcardgame,eachplayergetsahandofcards.Thede ckisshuedandcardsare dealtoneatatimefromthedeckandaddedtotheplayers'hand s.Insomegames,cardscan beremovedfromahand,andnewcardscanbeadded.Thegameisw onorlostdepending onthevalue(ace,2,...,king)andsuit(spades,diamonds,c lubs,hearts)ofthecardsthata playerreceives.Ifwelookfornounsinthisdescription,th ereareseveralcandidatesforobjects: game,player,hand,card,deck,value,andsuit.Ofthese,th evalueandthesuitofacardare simplevalues,andtheywilljustberepresentedasinstance variablesina Card object.Ina completeprogram,theothervenounsmightberepresentedb yclasses.Butlet'sworkonthe onesthataremostobviouslyreusable:card,hand,anddeck. Ifwelookforverbsinthedescriptionofacardgame,weseeth atwecanshueadeckand dealacardfromadeck.Thisgivesuseustwocandidatesforin stancemethodsina Deck class: shuffle() and dealCard() .Cardscanbeaddedtoandremovedfromhands.Thisgivestwo candidatesforinstancemethodsina Hand class: addCard() and removeCard() .Cardsare relativelypassivethings,butweneedtobeabletodetermin etheirsuitsandvalues.Wewill discovermoreinstancemethodsaswegoalong. First,we'lldesignthedeckclassindetail.Whenadeckofca rdsisrstcreated,itcontains 52cardsinsomestandardorder.The Deck classwillneedaconstructortocreateanewdeck. Theconstructorneedsnoparametersbecauseanynewdeckist hesameasanyother.Therewill beaninstancemethodcalled shuffle() thatwillrearrangethe52cardsintoarandomorder. The dealCard() instancemethodwillgetthenextcardfromthedeck.Thiswil lbeafunction withareturntypeof Card ,sincethecallerneedstoknowwhatcardisbeingdealt.Itha sno parameters|whenyoudealthenextcardfromthedeck,youdon 'tprovideanyinformationto thedeck;youjustgetthenextcard,whateveritis.Whatwill happeniftherearenomore cardsinthedeckwhenits dealCard() methodiscalled?Itshouldprobablybeconsideredan errortotrytodealacardfromanemptydeck,sothedeckcanth rowanexceptioninthatcase. Butthisraisesanotherquestion:Howwilltherestofthepro gramknowwhetherthedeckis empty?Ofcourse,theprogramcouldkeeptrackofhowmanycar dsithasused.Butthedeck itselfshouldknowhowmanycardsithasleft,sotheprograms houldjustbeabletoaskthe deckobject.Wecanmakethispossiblebyspecifyinganother instancemethod, cardsLeft() thatreturnsthenumberofcardsremaininginthedeck.Thisl eadstoafullspecicationofall

PAGE 198

CHAPTER5.OBJECTSANDCLASSES 184 thesubroutinesinthe Deck class: ConstructorandinstancemethodsinclassDeck: publicDeck() //Constructor.Createanunshuffleddeckofcards. publicvoidshuffle() //Putalltheusedcardsbackintothedeck,//andshuffleitintoarandomorder. publicintcardsLeft() //Ascardsaredealtfromthedeck,thenumberof//cardsleftdecreases.Thisfunctionreturnsthe//numberofcardsthatarestillleftinthedeck. publicCarddealCard() //Dealsonecardfromthedeckandreturnsit.//Throwsanexceptionifnomorecardsareleft. Thisiseverythingyouneedtoknowinordertousethe Deck class.Ofcourse,itdoesn'ttell ushowtowritetheclass.Thishasbeenanexerciseindesign, notinprogramming.Infact, writingtheclassinvolvesaprogrammingtechnique,arrays ,whichwillnotbecovereduntil Chapter7 .Nevertheless,youcanlookatthesourcecode, Deck.java ,ifyouwant.Eventhough youwon'tunderstandtheimplementation,theJavadoccomme ntsgiveyoualltheinformation thatyouneedtounderstandtheinterface.Withthisinforma tion,youcanusetheclassinyour programswithoutunderstandingtheimplementation. Wecandoasimilaranalysisforthe Hand class.Whenahandobjectisrstcreated,it hasnocardsinit.An addCard() instancemethodwilladdacardtothehand.Thismethod needsaparameteroftype Card tospecifywhichcardisbeingadded.Forthe removeCard() method,aparameterisneededtospecifywhichcardtoremove .Butshouldwespecifythe carditself(\Removetheaceofspades"),orshouldwespecif ythecardbyitspositioninthe hand(\Removethethirdcardinthehand")?Actually,wedon' thavetodecide,sincewecan allowforbothoptions.We'llhavetwo removeCard() instancemethods,onewithaparameter oftype Card specifyingthecardtoberemovedandonewithaparameteroft ype int specifying thepositionofthecardinthehand.(Rememberthatyoucanha vetwomethodsinaclasswith thesamename,providedtheyhavedierenttypesofparamete rs.)Sinceahandcancontain avariablenumberofcards,it'sconvenienttobeabletoaska handobjecthowmanycardsit contains.So,weneedaninstancemethod getCardCount() thatreturnsthenumberofcards inthehand.WhenIplaycards,Iliketoarrangethecardsinmy handsothatcardsofthe samevaluearenexttoeachother.Sincethisisagenerallyus efulthingtobeabletodo,we canprovideinstancemethodsforsortingthecardsinthehan d.Hereisafullspecicationfor areusable Hand class: ConstructorandinstancemethodsinclassHand: publicHand(){ //CreateaHandobjectthatisinitiallyempty. publicvoidclear(){ //Discardallcardsfromthehand,makingthehandempty. publicvoidaddCard(Cardc){ //Addthecardctothehand.cshouldbenon-null.//Ifcisnull,aNullPointerExceptionisthrown.

PAGE 199

CHAPTER5.OBJECTSANDCLASSES 185 publicvoidremoveCard(Cardc){ //Ifthespecifiedcardisinthehand,itisremoved. publicvoidremoveCard(intposition){ //Removethecardinthespecifiedpositionfromthe//hand.Cardsarenumberedcountingfromzero.If//thespecifiedpositiondoesnotexist,thenan//exceptionisthrown. publicintgetCardCount(){ //Returnthenumberofcardsinthehand. publicCardgetCard(intposition){ //Getthecardfromthehandingivenposition,where//positionsarenumberedstartingfrom0.Ifthe//specifiedpositionisnotthepositionnumberof//acardinthehand,anexceptionisthrown. publicvoidsortBySuit(){ //Sortsthecardsinthehandsothatcardsofthesame//suitaregroupedtogether,andwithinasuitthecards//aresortedbyvalue.Notethatacesareconsidered//tohavethelowestvalue,1. publicvoidsortByValue(){ //Sortsthecardsinthehandsothatcardsaresortedinto//orderofincreasingvalue.Cardswiththesamevalue//aresortedbysuit.Notethatacesareconsidered//tohavethelowestvalue. Again,youdon'tyetknowenoughtoimplementthisclass.But giventhesourcecode, Hand.java ,youcanusetheclassinyourownprogrammingprojects. 5.4.2TheCardClassWe have coveredenoughmaterialtowritea Card class.Theclasswillhaveaconstructor thatspeciesthevalueandsuitofthecardthatisbeingcrea ted.Therearefoursuits,which canberepresentedbytheintegers0,1,2,and3.Itwouldbeto ughtorememberwhich numberrepresentswhichsuit,soI'vedenednamedconstant sinthe Card classtorepresent thefourpossibilities.Forexample, Card.SPADES isaconstantthatrepresentsthesuit,spades. (Theseconstantsaredeclaredtobe publicfinalstaticints .Itmightbebettertouse anenumeratedtype,butfornowwewillsticktointeger-valu edconstants.I'llreturntothe questionofusingenumeratedtypesinthisexampleattheend ofthechapter.)Thepossible valuesofacardarethenumbers1,2,...,13,with1standingf oranace,11forajack,12for aqueen,and13foraking.Again,I'vedenedsomenamedconst antstorepresentthevalues ofacesandfacecards.(Whenyoureadthe Card class,you'llseethatI'vealsoaddedsupport forJokers.) A Card objectcanbeconstructedknowingthevalueandthesuitofth ecard.Forexample, wecancalltheconstructorwithstatementssuchas: card1=newCard(Card.ACE,Card.SPADES);//Constructaceo fspades. card2=newCard(10,Card.DIAMONDS);//Construct10ofdiam onds. card3=newCard(v,s);//ThisisOK,aslongasvands //areintegerexpressions.

PAGE 200

CHAPTER5.OBJECTSANDCLASSES 186 A Card objectneedsinstancevariablestorepresentitsvalueands uit.I'vemadethese private sothattheycannotbechangedfromoutsidetheclass,andI'v eprovidedgettermethods getSuit() and getValue() sothatitwillbepossibletodiscoverthesuitandvaluefrom outside theclass.Theinstancevariablesareinitializedinthecon structor,andareneverchangedafter that.Infact,I'vedeclaredtheinstancevariables suit and value tobe final ,sincetheyare neverchangedaftertheyareinitialized.(Aninstancevari ablecanbedeclared final provided itiseithergivenaninitialvalueinitsdeclarationorisin itializedineveryconstructorinthe class.) Finally,I'veaddedafewconveniencemethodstotheclassto makeiteasiertoprintout cardsinahuman-readableform.Forexample,Iwanttobeable toprintoutthesuitofa cardastheword\Diamonds",ratherthanasthemeaninglessc odenumber2,whichisused intheclasstorepresentdiamonds.Sincethisissomethingt hatI'llprobablyhavetodoin manyprograms,itmakessensetoincludesupportforitinthe class.So,I'veprovidedinstance methods getSuitAsString() and getValueAsString() toreturnstringrepresentationsofthe suitandvalueofacard.Finally,I'vedenedtheinstanceme thod toString() toreturna stringwithboththevalueandsuit,suchas\QueenofHearts" .Recallthatthismethodwillbe usedwhenevera Card needstobeconvertedintoa String ,suchaswhenthecardisconcatenated ontoastringwiththe + operator.Thus,thestatement System.out.println("Yourcardisthe"+card); isequivalentto System.out.println("Yourcardisthe"+card.toString()) ; Ifthecardisthequeenofhearts,eitherofthesewillprinto ut\YourcardistheQueenof Hearts". Hereisthecomplete Card class.Itisgeneralenoughtobehighlyreusable,sothework that wentintodesigning,writing,andtestingitpaysohandsom elyinthelongrun. /** *AnobjectoftypeCardrepresentsaplayingcardfroma*standardPokerdeck,includingJokers.Thecardhasasuit, which *canbespades,hearts,diamonds,clubs,orjoker.Aspade,h eart, *diamond,orclubhasoneofthe13values:ace,2,3,4,5,6,7,*8,9,10,jack,queen,orking.Notethat"ace"isconsidered tobe *thesmallestvalue.Ajokercanalsohaveanassociatedvalu e; *thisvaluecanbeanythingandcanbeusedtokeeptrackofsev eral *differentjokers.*/ publicclassCard{ publicfinalstaticintSPADES=0;//Codesforthe4suits,pl usJoker. publicfinalstaticintHEARTS=1;publicfinalstaticintDIAMONDS=2;publicfinalstaticintCLUBS=3;publicfinalstaticintJOKER=4;publicfinalstaticintACE=1;//Codesforthenon-numericc ards. publicfinalstaticintJACK=11;//Cards2through10haveth eir publicfinalstaticintQUEEN=12;//numericalvaluesforth eircodes. publicfinalstaticintKING=13;/**

PAGE 201

CHAPTER5.OBJECTSANDCLASSES 187 *Thiscard'ssuit,oneoftheconstantsSPADES,HEARTS,DIAM ONDS, *CLUBS,orJOKER.Thesuitcannotbechangedafterthecardis*constructed.*/ privatefinalintsuit;/** *Thecard'svalue.Foranormalcards,thisisoneofthevalue s *1through13,with1representingACE.ForaJOKER,thevalue*canbeanything.Thevaluecannotbechangedafterthecard*isconstructed.*/ privatefinalintvalue;/** *CreatesaJoker,with1astheassociatedvalue.(Notethat*"newCard()"isequivalentto"newCard(1,Card.JOKER)".)*/ publicCard(){ suit=JOKER;value=1; }/** *Createsacardwithaspecifiedsuitandvalue.*@paramtheValuethevalueofthenewcard.Foraregularcard (non-joker), *thevaluemustbeintherange1through13,with1representi nganAce. *YoucanusetheconstantsCard.ACE,Card.JACK,Card.QUEEN ,andCard.KING. *ForaJoker,thevaluecanbeanything.*@paramtheSuitthesuitofthenewcard.Thismustbeoneofth evalues *Card.SPADES,Card.HEARTS,Card.DIAMONDS,Card.CLUBS,o rCard.JOKER. *@throwsIllegalArgumentExceptioniftheparametervalue sarenotinthe *permissibleranges*/ publicCard(inttheValue,inttheSuit){ if(theSuit!=SPADES&&theSuit!=HEARTS&&theSuit!=DIAMO NDS&& theSuit!=CLUBS&&theSuit!=JOKER) thrownewIllegalArgumentException("Illegalplayingcar dsuit"); if(theSuit!=JOKER&&(theValue<1||theValue>13)) thrownewIllegalArgumentException("Illegalplayingcar dvalue"); value=theValue;suit=theSuit; }/** *Returnsthesuitofthiscard.*@returnsthesuit,whichisoneoftheconstantsCard.SPADE S, *Card.HEARTS,Card.DIAMONDS,Card.CLUBS,orCard.JOKER*/ publicintgetSuit(){ returnsuit; }/** *Returnsthevalueofthiscard.*@returnthevalue,whichisonethenumbers1through13,inc lusivefor

PAGE 202

CHAPTER5.OBJECTSANDCLASSES 188 *aregularcard,andwhichcanbeanyvalueforaJoker.*/ publicintgetValue(){ returnvalue; }/** *ReturnsaStringrepresentationofthecard'ssuit.*@returnoneofthestrings"Spades","Hearts","Diamonds" ,"Clubs" *or"Joker".*/ publicStringgetSuitAsString(){ switch(suit){caseSPADES:return"Spades";caseHEARTS:return"Hearts";caseDIAMONDS:return"Diamonds";caseCLUBS:return"Clubs";default:return"Joker";} }/** *ReturnsaStringrepresentationofthecard'svalue.*@returnforaregularcard,oneofthestrings"Ace","2",*"3",...,"10","Jack","Queen",or"King".ForaJoker,the*stringisalwaysanumerical.*/ publicStringgetValueAsString(){ if(suit==JOKER) return""+value; else{ switch(value){case1:return"Ace";case2:return"2";case3:return"3";case4:return"4";case5:return"5";case6:return"6";case7:return"7";case8:return"8";case9:return"9";case10:return"10";case11:return"Jack";case12:return"Queen";default:return"King";} } }/** *Returnsastringrepresentationofthiscard,includingbo th *itssuitanditsvalue(exceptthatforaJokerwithvalue1,*thereturnvalueisjust"Joker").Samplereturnvalues*are:"QueenofHearts","10ofDiamonds","AceofSpades",*"Joker","Joker#2"

PAGE 203

CHAPTER5.OBJECTSANDCLASSES 189 */ publicStringtoString(){ if(suit==JOKER){ if(value==1) return"Joker"; else return"Joker#"+value; }else returngetValueAsString()+"of"+getSuitAsString(); } }//endclassCard 5.4.3Example:ASimpleCardGameIwillnishthissectionbypresentingacompleteprogramth atusesthe Card and Deck classes. TheprogramletstheuserplayaverysimplecardgamecalledH ighLow.Adeckofcardsis shued,andonecardisdealtfromthedeckandshowntotheuse r.Theuserpredictswhether thenextcardfromthedeckwillbehigherorlowerthanthecur rentcard.Iftheuserpredicts correctly,thenthenextcardfromthedeckbecomesthecurre ntcard,andtheusermakes anotherprediction.Thiscontinuesuntiltheusermakesani ncorrectprediction.Thenumber ofcorrectpredictionsistheuser'sscore. MyprogramhasasubroutinethatplaysonegameofHighLow.Th issubroutinehasa returnvaluethatrepresentstheuser'sscoreinthegame.Th e main() routineletstheuserplay severalgamesofHighLow.Attheend,itreportstheuser'sav eragescore. Iwon'tgothroughthedevelopmentofthealgorithmsusedint hisprogram,butIencourage youtoreaditcarefullyandmakesurethatyouunderstandhow itworks.Noteinparticular thatthesubroutinethatplaysonegameofHighLowreturnsth euser'sscoreinthegameasits returnvalue.Thisgetsthescorebacktothemainprogram,wh ereitisneeded.Hereisthe program: /** *ThisprogramletstheuserplayHighLow,asimplecardgame*thatisdescribedintheoutputstatementsatthebeginning of *themain()routine.Aftertheuserplaysseveralgames,*theuser'saveragescoreisreported.*/ publicclassHighLow{ publicstaticvoidmain(String[]args){ System.out.println("Thisprogramletsyouplaythesimple cardgame,"); System.out.println("HighLow.Acardisdealtfromadeckof cards."); System.out.println("Youhavetopredictwhetherthenextc ardwillbe"); System.out.println("higherorlower.Yourscoreinthegam eisthe"); System.out.println("numberofcorrectpredictionsyouma kebefore"); System.out.println("youguesswrong.");System.out.println();intgamesPlayed=0;//Numberofgamesuserhasplayed.intsumOfScores=0;//Thesumofallthescoresfrom

PAGE 204

CHAPTER5.OBJECTSANDCLASSES 190 //allthegamesplayed. doubleaverageScore;//Averagescore,computedbydividin g //sumOfScoresbygamesPlayed. booleanplayAgain;//Recorduser'sresponsewhenuseris //askedwhetherhewantstoplay//anothergame. do{ intscoreThisGame;//Scoreforonegame.scoreThisGame=play();//Playthegameandgetthescore.sumOfScores+=scoreThisGame;gamesPlayed++;TextIO.put("Playagain?");playAgain=TextIO.getlnBoolean(); }while(playAgain);averageScore=((double)sumOfScores)/gamesPlayed;System.out.println();System.out.println("Youplayed"+gamesPlayed+"games." ); System.out.printf("Youraveragescorewas%1.3f.\n",ave rageScore); }//endmain()/** *LetstheuserplayonegameofHighLow,andreturnsthe*user'sscoreonthatgame.Thescoreisthenumberof*correctguessesthattheusermakes.*/ privatestaticintplay(){ Deckdeck=newDeck();//Getanewdeckofcards,and //storeareferencetoitin//thevariable,deck. CardcurrentCard;//Thecurrentcard,whichtheusersees.CardnextCard;//Thenextcardinthedeck.Theusertries //topredictwhetherthisishigherorlower//thanthecurrentcard. intcorrectGuesses;//Thenumberofcorrectpredictionsth e //userhasmade.Attheendofthegame,//thiswillbetheuser'sscore. charguess;//Theuser'sguess.'H'iftheuserpredictsthat //thenextcardwillbehigher,'L'iftheuser//predictsthatitwillbelower. deck.shuffle();//Shufflethedeckintoarandomorderbefo re //startingthegame. correctGuesses=0;currentCard=deck.dealCard();TextIO.putln("Thefirstcardisthe"+currentCard);while(true){//Loopendswhenuser'spredictioniswrong. /*Gettheuser'sprediction,'H'or'L'(or'h'or'l').*/

PAGE 205

CHAPTER5.OBJECTSANDCLASSES 191 TextIO.put("Willthenextcardbehigher(H)orlower(L)?") ; do{ guess=TextIO.getlnChar();guess=Character.toUpperCase(guess);if(guess!='H'&&guess!='L') TextIO.put("PleaserespondwithHorL:"); }while(guess!='H'&&guess!='L');/*Getthenextcardandshowittotheuser.*/nextCard=deck.dealCard();TextIO.putln("Thenextcardis"+nextCard);/*Checktheuser'sprediction.*/if(nextCard.getValue()==currentCard.getValue()){ TextIO.putln("Thevalueisthesameasthepreviouscard.") ; TextIO.putln("Youloseonties.Sorry!");break;//Endthegame. }elseif(nextCard.getValue()>currentCard.getValue()){ if(guess=='H'){ TextIO.putln("Yourpredictionwascorrect.");correctGuesses++; }else{ TextIO.putln("Yourpredictionwasincorrect.");break;//Endthegame. } }else{//nextCardislower if(guess=='L'){ TextIO.putln("Yourpredictionwascorrect.");correctGuesses++; }else{ TextIO.putln("Yourpredictionwasincorrect.");break;//Endthegame. } }/*Tosetupforthenextiterationoftheloop,thenextCard becomesthecurrentCard,sincethecurrentCardhastobethecardthattheusersees,andthenextCardwillbesettothenextcardinthedeckaftertheusermakeshisprediction.*/ currentCard=nextCard;TextIO.putln();TextIO.putln("Thecardis"+currentCard); }//endofwhileloopTextIO.putln();TextIO.putln("Thegameisover.");TextIO.putln("Youmade"+correctGuesses

PAGE 206

CHAPTER5.OBJECTSANDCLASSES 192 +"correctpredictions."); TextIO.putln();returncorrectGuesses; }//endplay() }//endclass 5.5Inheritance,Polymorphism,andAbstractClassesA classrepresentsasetofobjects whichsharethesamestructureandbehaviors. (online) Theclassdeterminesthestructureofobjectsbyspecifying variablesthatarecontainedineach instanceoftheclass,anditdeterminesbehaviorbyprovidi ngtheinstancemethodsthatexpress thebehavioroftheobjects.Thisisapowerfulidea.However ,somethinglikethiscanbedone inmostprogramminglanguages.Thecentralnewideainobjec t-orientedprogramming|the ideathatreallydistinguishesitfromtraditionalprogram ming|istoallowclassestoexpress thesimilaritiesamongobjectsthatshare some ,butnotall,oftheirstructureandbehavior. Suchsimilaritiescanbeexpressedusing inheritance and polymorphism 5.5.1ExtendingExistingClassesThetopicscoveredlaterinthissectionarerelativelyadva ncedaspectsofobject-orientedprogramming.Anyprogrammershouldknowwhatismeantbysubcla ss,inheritance,andpolymorphism.However,itwillprobablybeawhilebeforeyouactual lydoanythingwithinheritance exceptforextendingclassesthatalreadyexist.Intherst partofthissection,welookathow thatisdone. Inday-to-dayprogramming,especiallyforprogrammerswho arejustbeginningtowork withobjects,subclassingisusedmainlyinonesituation:T hereisanexistingclassthatcanbe adaptedwithafewchangesoradditions.Thisismuchmorecom monthandesigninggroupsof classesandsubclassesfromscratch.Theexistingclasscan be extended tomakeasubclass. Thesyntaxforthisis publicclass h subclass-name i extends h existing-class-name i { ..//Changesandadditions.. } Asanexample,supposeyouwanttowriteaprogramthatplayst hecardgame,Blackjack. Youcanusethe Card Hand ,and Deck classesdevelopedin Section5.4 .However,ahandinthe gameofBlackjackisalittledierentfromahandofcardsing eneral,sinceitmustbepossible tocomputethe\value"ofaBlackjackhandaccordingtotheru lesofthegame.Therulesare asfollows:Thevalueofahandisobtainedbyaddinguptheval uesofthecardsinthehand. Thevalueofanumericcardsuchasathreeoratenisitsnumeri calvalue.ThevalueofaJack, Queen,orKingis10.ThevalueofanAcecanbeeither1or11.An Aceshouldbecounted as11unlessdoingsowouldputthetotalvalueofthehandover 21.Notethatthismeansthat thesecond,third,orfourthAceinthehandwillalwaysbecou ntedas1. Onewaytohandlethisistoextendtheexisting Hand classbyaddingamethodthat computestheBlackjackvalueofthehand.Here'sthedeniti onofsuchaclass:

PAGE 207

CHAPTER5.OBJECTSANDCLASSES 193 publicclassBlackjackHandextendsHand{ /** *Computesandreturnsthevalueofthishandinthegame*ofBlackjack.*/ publicintgetBlackjackValue(){ intval;//Thevaluecomputedforthehand.booleanace;//Thiswillbesettotrueifthe //handcontainsanace. intcards;//Numberofcardsinthehand.val=0;ace=false;cards=getCardCount();for(inti=0;i10){ cardVal=10;//ForaJack,Queen,orKing. }if(cardVal==1){ ace=true;//Thereisatleastoneace. }val=val+cardVal; }//Now,valisthevalueofthehand,countinganyaceas1.//Ifthereisanace,andifchangingitsvaluefrom1to//11wouldleavethescorelessthanorequalto21,//thendosobyaddingtheextra10pointstoval.if(ace==true&&val+10<=21) val=val+10; returnval; }//endgetBlackjackValue() }//endclassBlackjackHand Since BlackjackHand isasubclassof Hand ,anobjectoftype BlackjackHand contains alltheinstancevariablesandinstancemethodsdenedin Hand ,plusthenewinstancemethodnamed getBlackjackValue() .Forexample,if bjh isavariableoftype BlackjackHand ,thenthefollowingarealllegal: bjh.getCardCount() bjh.removeCard(0) and bjh.getBlackjackValue() .Thersttwomethodsaredenedin Hand ,butareinherited by BlackjackHand Inheritedvariablesandmethodsfromthe Hand classcanalsobeusedinthedenition of BlackjackHand (exceptforanythataredeclaredtobe private ,whichpreventsaccess evenbysubclasses).Thestatement\ cards=getCardCount(); "intheabovedenitionof getBlackjackValue() callstheinstancemethod getCardCount() ,whichwasdenedin Hand

PAGE 208

CHAPTER5.OBJECTSANDCLASSES 194 Extendingexistingclassesisaneasywaytobuildonpreviou swork.We'llseethatmany standardclasseshavebeenwrittenspecicallytobeusedas thebasisformakingsubclasses. Accessmodierssuchas public and private areusedtocontrolaccesstomembersofa class.Thereisonemoreaccessmodier, protected ,thatcomesintothepicturewhensubclasses aretakenintoconsideration.When protected isappliedasanaccessmodiertoamethodor membervariableinaclass,thatmembercanbeusedinsubclas ses|direcctorindirect|ofthe classinwhichitisdened,butitcannotbeusedinnon-subcl asses.(Thereisoneexception: A protected membercanalsobeaccessedbyanyclassinthesamepackageas theclassthat containstheprotectedmember.Recallthatusingnoaccessm odiermakesamemberaccessible toclassesinthesamepackage,andnowhereelse.Usingthe protected modierisstrictlymore liberalthanusingnomodieratall:Itallowsaccessfromcl assesinthesamepackageandfrom subclasses thatarenotinthesamepackage.) Whenyoudeclareamethodormembervariabletobe protected ,youaresayingthatit ispartoftheimplementationoftheclass,ratherthanparto fthepublicinterfaceoftheclass. However,youareallowingsubclassestouseandmodifythatp artoftheimplementation. Forexample,considera PairOfDice classthathasinstancevariables die1 and die2 to representthenumbersappearingonthetwodice.Wecouldmak ethosevariables private to makeitimpossibletochangetheirvaluesfromoutsidethecl ass,whilestillallowingreadaccess throughgettermethods.However,ifwethinkitpossibletha t PairOfDice willbeusedtocreate subclasses,wemightwanttomakeitpossibleforsubclasses tochangethenumbersonthedice. Forexample,a GraphicalDice subclassthatdrawsthedicemightwanttochangethenumbers atothertimesbesideswhenthedicearerolled.Inthatcase, wecouldmake die1 and die2 protected ,whichwouldallowthesubclasstochangetheirvalueswitho utmakingthempublic totherestoftheworld.(Anevenbetterideawouldbetodene protected settermethodsfor thevariables.Asettermethodcould,forexample,ensureth atthevaluethatisbeingassigned tothevariableisinthelegalrange1through6.)5.5.2InheritanceandClassHierarchyTheterm inheritance referstothefactthatoneclasscaninheritpartorallofits structure andbehaviorfromanotherclass.Theclassthatdoestheinhe ritingissaidtobea subclass of theclassfromwhichitinherits.IfclassBisasubclassofcl assA,wealsosaythatclassAisa superclass ofclassB.(Sometimestheterms derivedclass and baseclass areusedinstead ofsubclassandsuperclass;thisisthecommonterminologyi nC++.)Asubclasscanaddtothe structureandbehaviorthatitinherits.Itcanalsoreplace ormodifyinheritedbehavior(though notinheritedstructure).Therelationshipbetweensubcla ssandsuperclassissometimesshown byadiagraminwhichthesubclassisshownbelow,andconnect edto,itssuperclass,asshown hereontheleft.

PAGE 209

CHAPTER5.OBJECTSANDCLASSES 195 InJava,tocreateaclassnamed\B"asasubclassofaclassnam ed\A",youwouldwrite classBextendsA{ ..//additionsto,andmodificationsof,.//stuffinheritedfromclassA. } Severalclassescanbedeclaredassubclassesofthesamesup erclass.Thesubclasses,which mightbereferredtoas\siblingclasses,"sharesomestruct uresandbehaviors|namely,theones theyinheritfromtheircommonsuperclass.Thesuperclasse xpressesthesesharedstructures andbehaviors.Inthediagramshownontheright,above,clas sesB,C,andDaresiblingclasses. Inheritancecanalsoextendoverseveral\generations"ofc lasses.Thisisshowninthediagram, whereclassEisasubclassofclassDwhichisitselfasubclas sofclassA.Inthiscase,classE isconsideredtobeasubclassofclassA,eventhoughitisnot adirectsubclass.Thiswholeset ofclassesformsasmall classhierarchy 5.5.3Example:VehiclesLet'slookatanexample.Supposethataprogramhastodealwi thmotorvehicles,including cars,trucks,andmotorcycles.(Thismightbeaprogramused byaDepartmentofMotor Vehiclestokeeptrackofregistrations.)Theprogramcould useaclassnamed Vehicle to representalltypesofvehicles.Sincecars,trucks,andmot orcyclesaretypesofvehicles,they wouldberepresentedbysubclassesofthe Vehicle class,asshowninthisclasshierarchydiagram: The Vehicle classwouldincludeinstancevariablessuchas registrationNumber and owner and instancemethodssuchas transferOwnership() .Thesearevariablesandmethodscommon toallvehicles.Thethreesubclassesof Vehicle | Car Truck ,and Motorcycle |couldthenbe usedtoholdvariablesandmethodsspecictoparticulartyp esofvehicles.The Car class mightaddaninstancevariable numberOfDoors ,the Truck classmighthave numberOfAxles

PAGE 210

CHAPTER5.OBJECTSANDCLASSES 196 andthe Motorcycle classcouldhaveabooleanvariable hasSidecar .(Well,itcould intheory atleast,evenifitmightgiveachuckletothepeopleattheDe partmentofMotorVehicles.) ThedeclarationsoftheseclassesinaJavaprogramwouldloo k,inoutline,likethis(although inpractice,theywouldprobablybe public classes,denedinseparateles): classVehicle{ intregistrationNumber;Personowner;//(AssumingthataPersonclasshasbeendefin ed!) voidtransferOwnership(PersonnewOwner){ ... }... }classCarextendsVehicle{ intnumberOfDoors;... }classTruckextendsVehicle{ intnumberOfAxles;... }classMotorcycleextendsVehicle{ booleanhasSidecar;... } Supposethat myCar isavariableoftype Car thathasbeendeclaredandinitializedwiththe statement CarmyCar=newCar(); Giventhisdeclaration,aprogramcouldreferto myCar.numberOfDoors ,since numberOfDoors isaninstancevariableintheclass Car .Butsinceclass Car extendsclass Vehicle ,acaralso hasallthestructureandbehaviorofavehicle.Thismeansth at myCar.registrationNumber myCar.owner ,and myCar.transferOwnership() alsoexist. Now,intherealworld,cars,trucks,andmotorcyclesareinf actvehicles.Thesameistrue inaprogram.Thatis,anobjectoftype Car or Truck or Motorcycle isautomaticallyanobject oftype Vehicle too.ThisbringsustothefollowingImportantFact: Avariablethatcanholdareference toanobjectofclassAcanalsoholdareference toanobjectbelongingtoanysubclassofA. Thepracticaleectofthisinourexampleisthatanobjectof type Car canbeassignedtoa variableoftype Vehicle .Thatis,itwouldbelegaltosay VehiclemyVehicle=myCar; oreven VehiclemyVehicle=newCar();

PAGE 211

CHAPTER5.OBJECTSANDCLASSES 197 Aftereitherofthesestatements,thevariable myVehicle holdsareferencetoa Vehicle object thathappenstobeaninstanceofthesubclass, Car .Theobject\remembers"thatitisinfact a Car ,andnot just a Vehicle .Informationabouttheactualclassofanobjectisstoredas part ofthatobject.Itisevenpossibletotestwhetheragivenobj ectbelongstoagivenclass,using the instanceof operator.Thetest: if(myVehicleinstanceofCar)... determineswhethertheobjectreferredtoby myVehicle isinfactacar. Ontheotherhand,theassignmentstatement myCar=myVehicle; wouldbeillegalbecause myVehicle couldpotentiallyrefertoothertypesofvehiclesthatare notcars.Thisissimilartoaproblemwesawpreviouslyin Subsection2.5.6 :Thecomputer willnotallowyoutoassignan int valuetoavariableoftype short ,becausenotevery int isa short .Similarly,itwillnotallowyoutoassignavalueoftype Vehicle toavariableoftype Car becausenoteveryvehicleisacar.Asinthecaseof int sand short s,thesolutionhereistouse type-casting.If,forsomereason,youhappentoknowthat myVehicle doesinfactrefertoa Car ,youcanusethetypecast (Car)myVehicle totellthecomputertotreat myVehicle asif itwereactuallyoftype Car .So,youcouldsay myCar=(Car)myVehicle; andyoucouldevenreferto ((Car)myVehicle).numberOfDoors .Asanexampleofhowthis couldbeusedinaprogram,supposethatyouwanttoprintoutr elevantdataaboutavehicle. Youcouldsay: System.out.println("VehicleData:");System.out.println("Registrationnumber:" +myVehicle.registrationNumber); if(myVehicleinstanceofCar){ System.out.println("Typeofvehicle:Car");Carc;c=(Car)myVehicle;System.out.println("Numberofdoors:"+c.numberOfDoors ); }elseif(myVehicleinstanceofTruck){ System.out.println("Typeofvehicle:Truck");Truckt;t=(Truck)myVehicle;System.out.println("Numberofaxles:"+t.numberOfAxles ); }elseif(myVehicleinstanceofMotorcycle){ System.out.println("Typeofvehicle:Motorcycle");Motorcyclem;m=(Motorcycle)myVehicle;System.out.println("Hasasidecar:"+m.hasSidecar); } Notethatforobjecttypes,whenthecomputerexecutesaprog ram,itcheckswhether type-castsarevalid.So,forexample,if myVehicle referstoanobjectoftype Truck ,then thetypecast (Car)myVehicle wouldbeanerror.Whenthishappes,anexceptionoftype ClassCastException isthrown.

PAGE 212

CHAPTER5.OBJECTSANDCLASSES 198 5.5.4PolymorphismAsanotherexample,consideraprogramthatdealswithshape sdrawnonthescreen.Let'ssay thattheshapesincluderectangles,ovals,androundrectso fvariouscolors.(A\roundrect"is justarectanglewithroundedcorners.) Threeclasses, Rectangle Oval ,and RoundRect ,couldbeusedtorepresentthethreetypesof shapes.Thesethreeclasseswouldhaveacommonsuperclass, Shape ,torepresentfeaturesthat allthreeshapeshaveincommon.The Shape classcouldincludeinstancevariablestorepresent thecolor,position,andsizeofashape,anditcouldinclude instancemethodsforchangingthe color,position,andsize.Changingthecolor,forexample, mightinvolvechangingthevalueof aninstancevariable,andthenredrawingtheshapeinitsnew color: classShape{ Colorcolor;//Coloroftheshape.(RecallthatclassColor //isdefinedinpackagejava.awt.Assume//thatthisclasshasbeenimported.) voidsetColor(ColornewColor){ //Methodtochangethecoloroftheshape. color=newColor;//changevalueofinstancevariableredraw();//redrawshape,whichwillappearinnewcolor }voidredraw(){ //methodfordrawingtheshape ???//whatcommandsshouldgohere? }...//moreinstancevariablesandmethods }//endofclassShape Now,youmightseeaproblemherewiththemethod redraw() .Theproblemisthateach dierenttypeofshapeisdrawndierently.Themethod setColor() canbecalledforanytype ofshape.Howdoesthecomputerknowwhichshapetodrawwheni texecutesthe redraw() ? Informally,wecananswerthequestionlikethis:Thecomput erexecutes redraw() byasking theshapetoredraw itself .Everyshapeobjectknowswhatithastodotoredrawitself. Inpractice,thismeansthateachofthespecicshapeclasse shasitsown redraw() method: classRectangleextendsShape{ voidredraw(){ ...//commandsfordrawingarectangle

PAGE 213

CHAPTER5.OBJECTSANDCLASSES 199 }...//possibly,moremethodsandvariables }classOvalextendsShape{ voidredraw(){ ...//commandsfordrawinganoval }...//possibly,moremethodsandvariables }classRoundRectextendsShape{ voidredraw(){ ...//commandsfordrawingaroundedrectangle }...//possibly,moremethodsandvariables } If oneShape isavariableoftype Shape ,itcouldrefertoanobjectofanyofthetypes, Rectangle Oval ,or RoundRect .Asaprogramexecutes,andthevalueof oneShape changes,it couldevenrefertoobjectsofdierenttypesatdierenttim es!Wheneverthestatement oneShape.redraw(); isexecuted,theredrawmethodthatisactuallycalledisthe oneappropriateforthetypeof objecttowhich oneShape actuallyrefers.Theremaybenowayoftelling,fromlooking atthe textoftheprogram,whatshapethisstatementwilldraw,sin ceitdependsonthevaluethat oneShape happenstohavewhentheprogramisexecuted.Evenmoreistru e.Supposethe statementisinaloopandgetsexecutedmanytimes.Iftheval ueof oneShape changesasthe loopisexecuted,itispossiblethattheverysamestatement \ oneShape.redraw(); "willcall dierentmethodsanddrawdierentshapesasitisexecutedo verandover.Wesaythatthe redraw() methodis polymorphic .Amethodispolymorphiciftheactionperformedbythe methoddependsontheactualtypeoftheobjecttowhichtheme thodisapplied.Polymorphism isoneofthemajordistinguishingfeaturesofobject-orien tedprogramming. Perhapsthisbecomesmoreunderstandableifwechangeourte rminologyabit:Inobjectorientedprogramming,callingamethodisoftenreferredto assendinga message toanobject. Theobjectrespondstothemessagebyexecutingtheappropri atemethod.Thestatement \ oneShape.redraw(); "isamessagetotheobjectreferredtoby oneShape .Sincethatobject knowswhattypeofobjectitis,itknowshowitshouldrespond tothemessage.Fromthispoint ofview,thecomputeralwaysexecutes\ oneShape.redraw(); "inthesameway:bysending amessage.Theresponsetothemessagedepends,naturally,o nwhoreceivesit.Fromthis pointofview,objectsareactiveentitiesthatsendandrece ivemessages,andpolymorphismis anatural,evennecessary,partofthisview.Polymorphismj ustmeansthatdierentobjects canrespondtothesamemessageindierentways. Oneofthemostbeautifulthingsaboutpolymorphismisthati tletscodethatyouwritedo thingsthatyoudidn'tevenconceiveof,atthetimeyouwrote it.SupposethatIdecidetoadd beveledrectanglestothetypesofshapesmyprogramcandeal with.Abeveledrectanglehas atrianglecutoeachcorner:

PAGE 214

CHAPTER5.OBJECTSANDCLASSES 200 Toimplementbeveledrectangles,Icanwriteanewsubclass, BeveledRect ,ofclass Shape andgiveititsown redraw() method.Automatically,codethatIwrotepreviously|sucha s thestatement oneShape.redraw() |cannowsuddenlystartdrawingbeveledrectangles,even thoughthebeveledrectangleclassdidn'texistwhenIwrote thestatement! Inthestatement\ oneShape.redraw(); ",the redraw messageissenttotheobject oneShape .Lookbackatthemethodfromthe Shape classforchangingthecolorofashape: voidsetColor(ColornewColor){ color=newColor;//changevalueofinstancevariableredraw();//redrawshape,whichwillappearinnewcolor } A redraw messageissenthere,butwhichobjectisitsentto?Well,the setColor method isitselfamessagethatwassenttosomeobject.Theansweris thatthe redraw messageissent tothatsameobject,theonethatreceivedthe setColor message.Ifthatobjectisarectangle, thenitisthe redraw() methodfromthe Rectangle classthatisexecuted.Iftheobjectisan oval,thenitisthe redraw() methodfromthe Oval class.Thisiswhatyoushouldexpect,but itmeansthatthe\ redraw(); "statementinthe setColor() methoddoes not necessarilycall the redraw() methodinthe Shape class!The redraw() methodthatisexecutedcouldbein anysubclassof Shape Again,thisisnotarealsurpriseifyouthinkaboutitinther ightway.Rememberthat aninstancemethodisalwayscontainedinanobject.Theclas sonlycontainsthesourcecode forthemethod.Whena Rectangle objectiscreated,itcontainsa redraw() method.The sourcecodeforthatmethodisinthe Rectangle class.Theobjectalsocontainsa setColor() method.Sincethe Rectangle classdoesnotdenea setColor() method,the sourcecode for therectangle's setColor() methodcomesfromthesuperclass, Shape ,butthe methoditself isintheobjectoftype Rectangle .Eventhoughthesourcecodesforthetwomethodsarein dierentclasses,themethodsthemselvesarepartofthesam eobject.Whentherectangle's setColor() methodisexecutedandcalls redraw() ,the redraw() methodthatisexecutedis theoneinthesameobject.5.5.5AbstractClassesWhenevera Rectangle Oval ,or RoundRect objecthastodrawitself,itisthe redraw() methodin theappropriateclassthatisexecuted.Thisleavesopenthe question,Whatdoesthe redraw() methodinthe Shape classdo?Howshoulditbedened? Theanswermaybesurprising:Weshouldleaveitblank!Thefa ctisthattheclass Shape representstheabstractideaofashape,andthereisnowayto drawsuchathing.Only particular,concreteshapeslikerectanglesandovalscanb edrawn.So,whyshouldthere

PAGE 215

CHAPTER5.OBJECTSANDCLASSES 201 evenbea redraw() methodinthe Shape class?Well,ithastobethere,oritwouldbe illegaltocallitinthe setColor() methodofthe Shape class,anditwouldbeillegaltowrite \ oneShape.redraw() ;",where oneShape isavariableoftype Shape .Thecompilerwould complainthat oneShape isavariableoftype Shape andthere'sno redraw() methodinthe Shape class. Neverthelesstheversionof redraw() inthe Shape classitselfwillneveractuallybecalled. Infact,ifyouthinkaboutit,therecanneverbeanyreasonto constructanactualobjectof type Shape !Youcanhave variables oftype Shape ,buttheobjectstheyrefertowillalways belongtooneofthesubclassesof Shape .Wesaythat Shape isan abstractclass .Anabstract classisonethatisnotusedtoconstructobjects,butonlyas abasisformakingsubclasses.An abstractclassexists only toexpressthecommonpropertiesofallitssubclasses.Acla ssthat isnotabstractissaidtobe concrete .Youcancreateobjectsbelongingtoaconcreteclass, butnottoanabstractclass.Avariablewhosetypeisgivenby anabstractclasscanonlyrefer toobjectsthatbelongtoconcretesubclassesoftheabstrac tclass. Similarly,wesaythatthe redraw() methodinclass Shape isan abstractmethod ,since itisnevermeanttobecalled.Infact,thereisnothingforit todo|anyactualredrawingis doneby redraw() methodsinthesubclassesof Shape .The redraw() methodin Shape has tobethere.Butitisthereonlytotellthecomputerthatall Shapes understandthe redraw message.Asanabstractmethod,itexistsmerelytospecifyt hecommoninterfaceofallthe actual,concreteversionsof redraw() inthesubclassesof Shape .Thereisnoreasonforthe abstract redraw() inclass Shape tocontainanycodeatall. Shape andits redraw() methodaresemanticallyabstract.Youcanalsotellthecomp uter, syntactically,thattheyareabstractbyaddingthemodier \ abstract "totheirdenitions. Foranabstractmethod,theblockofcodethatgivestheimple mentationofanordinarymethod isreplacedbyasemicolon.Animplementationmustbeprovid edfortheabstractmethodin anyconcretesubclassoftheabstractclass.Here'swhatthe Shape classwouldlooklikeasan abstractclass: publicabstractclassShape{ Colorcolor;//colorofshape.voidsetColor(ColornewColor){ //methodtochangethecoloroftheshape color=newColor;//changevalueofinstancevariableredraw();//redrawshape,whichwillappearinnewcolor }abstractvoidredraw(); //abstractmethod---mustbedefinedin//concretesubclasses ...//moreinstancevariablesandmethods }//endofclassShape Onceyouhavedeclaredtheclasstobe abstract ,itbecomesillegaltotrytocreateactual objectsoftype Shape ,andthecomputerwillreportasyntaxerrorifyoutrytodoso Recallfrom Subsection5.3.3 thataclassthatisnotexplicitlydeclaredtobeasubclasso f someotherclassisautomaticallymadeasubclassofthestan dardclass Object .Thatis,aclass declarationwithno\ extends "partsuchas

PAGE 216

CHAPTER5.OBJECTSANDCLASSES 202 publicclassmyClass{... isexactlyequivalentto publicclassmyClassextendsObject{... Thismeansthatclass Object isatthetopofahugeclasshierarchythatincludesevery otherclass.(Semantially, Object isanabstractclass,infactthemostabstractclassofall. Curiously,however,itisnotdeclaredtobe abstract syntactially,whichmeansthatyoucan createobjectsoftype Object .Whatyouwoulddowiththem,however,Ihavenoidea.) Sinceeveryclassisasubclassof Object ,avariableoftype Object canrefertoanyobject whatsoever,ofanytype.Javahasseveralstandarddatastru cturesthataredesignedtohold Object s,butsinceeveryobjectisaninstanceofclass Object ,thesedatastructurescanactually holdanyobjectwhatsoever.Oneexampleisthe\ArrayList"d atastructure,whichisdenedby theclass ArrayList inthepackage java.util .( ArrayList isdiscussedmorefullyin Section7.3 .) An ArrayList issimplyalistof Object s.Thisclassisveryconvenient,becausean ArrayList can holdanynumberofobjects,anditwillgrow,whennecessary, asobjectsareaddedtoit.Since theitemsinthelistareoftype Object ,thelistcanactuallyholdobjectsofanytype. Aprogramthatwantstokeeptrackofvarious Shape sthathavebeendrawnonthescreen canstorethoseshapesinan ArrayList .Supposethatthe ArrayList isnamed listOfShapes Ashape, oneShape ,canbeaddedtotheendofthelistbycallingtheinstancemet hod \ listOfShapes.add(oneShape); ".Theshapecanberemovedfromthelistwiththeinstance method\ listOfShapes.remove(oneShape); ".Thenumberofshapesinthelistisgivenby thefunction\ listOfShapes.size() ".Anditispossibletoretrievethei-thobjectfromthe listwiththefunctioncall\ listOfShapes.get(i) ".(Itemsinthelistarenumberedfrom0to listOfShapes.size()-1 .)However,notethatthismethodreturnsan Object ,nota Shape (Ofcourse,thepeoplewhowrotethe ArrayList classdidn'tevenknowabout Shapes ,sothe methodtheywrotecouldhardlyhaveareturntypeof Shape !)Sinceyouknowthattheitems inthelistare,infact, Shape sandnotjust Object s,youcantype-castthe Object returnedby listOfShapes.get(i) tobeavalueoftype Shape : oneShape=(Shape)listOfShapes.get(i); Let'ssay,forexample,thatyouwanttoredrawalltheshapes inthelist.Youcoulddo thiswithasimple for loop,whichislovelyexampleofobject-orientedprogrammi ngandof polymorphism: for(inti=0;i
PAGE 217

CHAPTER5.OBJECTSANDCLASSES 203 tothisexampleinlaterchapterswhenyouknowmoreaboutGUI programming.However,it wouldstillbeworthwhiletolookatthedenitionofthe Shape classanditssubclassesinthe sourcecode.Youmightalsocheckhowan ArrayList isusedtoholdthelistofshapes. Intheapplettheonlytimewhentheactualclassofashapeisu sediswhenthatshapeis addedtothescreen.Oncetheshapehasbeencreated,itisman ipulatedentirelyasanabstract shape.Theroutinethatimplementsdragging,forexample,w orksonlywithvariablesoftype Shape .Asthe Shape isbeingdragged,thedraggingroutinejustcallsthe Shape's drawmethod eachtimetheshapehastobedrawn,soitdoesn'thavetoknowh owtodrawtheshapeoreven whattypeofshapeitis.Theobjectisresponsiblefordrawin gitself.IfIwantedtoaddanew typeofshapetotheprogram,Iwoulddeneanewsubclassof Shape ,addanotherbuttonto theapplet,andprogramthebuttontoaddthecorrecttypeofs hapetothescreen.Noother changesintheprogrammingwouldbenecessary. Ifyouwanttotryouttheapplet,youcannditattheendofthe on-lineversionofthis section.5.6thisandsuperA lthoughthebasicideas ofobject-orientedprogrammingarereasonablysimpleandc lear, (online) theyaresubtle,andtheytaketimetogetusedto.Andunfortu nately,beyondthebasicideas therearealotofdetails.Thissectionandthenextcovermor eofthoseannoyingdetails.You shouldnotnecessarilymastereverythinginthesetwosecti onsthersttimethrough,butyou shouldreadittobeawareofwhatispossible.Forthemostpar t,whenIneedtousethis materiallaterinthetext,Iwillexplainitagainbriery,or Iwillreferyoubacktoit.Inthis section,we'lllookattwovariables, this and super ,thatareautomaticallydenedinany instancemethod.5.6.1TheSpecialVariablethisAstaticmemberofaclasshasasimplename,whichcanonlybeu sedinsidetheclassdenition.Foruseoutsidetheclass,ithasafullnameofthefor m h class-name i h simple-name i Forexample,\ System.out "isastaticmembervariablewithsimplename\ out "intheclass \ System ".It'salwayslegaltousethefullnameofastaticmember,ev enwithintheclass whereit'sdened.Sometimesit'sevennecessary,aswhenth esimplenameofastaticmember variableishiddenbyalocalvariableofthesamename. Instancevariablesandinstancemethodsalsohavesimplena mes.Thesimplenameofsuch aninstancemembercanbeusedininstancemethodsintheclas swheretheinstancemember isdened.Instancemembersalsohavefullnames,butrememb erthatinstancevariablesand methodsareactuallycontainedinobjects,notclasses.The fullnameofaninstancemember hastocontainareferencetotheobjectthatcontainstheins tancemember.Togetatan instancevariableormethodfromoutsidetheclassdenitio n,youneedavariablethatrefersto theobject.Thenthefullnameisoftheform h variable-name i h simple-name i .Butsupposeyou arewritingthedenitionofaninstancemethodinsomeclass .Howcanyougetareferenceto theobjectthatcontainsthatinstancemethod?Youmightnee dsuchareference,forexample, ifyouwanttousethefullnameofaninstancevariable,becau sethesimplenameoftheinstance variableishiddenbyalocalvariableorparameter. Javaprovidesaspecial,predenedvariablenamed\ this "thatyoucanuseforsuchpurposes.Thevariable, this ,isusedinthesourcecodeofaninstancemethodtorefertoth e

PAGE 218

CHAPTER5.OBJECTSANDCLASSES 204 objectthatcontainsthemethod.Thisintentofthename, this ,istoreferto\thisobject,"the onerightherethatthisverymethodisin.If x isaninstancevariableinthesameobject,then this.x canbeusedasafullnameforthatvariable.If otherMethod() isaninstancemethod inthesameobject,then this.otherMethod() couldbeusedtocallthatmethod.Whenever thecomputerexecutesaninstancemethod,itautomatically setsthevariable, this ,toreferto theobjectthatcontainsthemethod. Onecommonuseof this isinconstructors.Forexample: publicclassStudent{ privateStringname;//Nameofthestudent.publicStudent(Stringname){ //Constructor.Createastudentwithspecifiedname. this.name=name; } ..//Morevariablesandmethods.. } Intheconstructor,theinstancevariablecalled name ishiddenbyaformalparameter.However,theinstancevariablecanstillbereferredtobyitsfu llname, this.name .Intheassignmentstatement,thevalueoftheformalparameter, name ,isassignedtotheinstancevariable, this.name .Thisisconsideredtobeacceptablestyle:Thereisnoneedt odreamupcutenew namesforformalparametersthatarejustusedtoinitialize instancevariables.Youcanusethe samenamefortheparameterasfortheinstancevariable. Thereareotherusesfor this .Sometimes,whenyouarewritinganinstancemethod,you needtopasstheobjectthatcontainsthemethodtoasubrouti ne,asanactualparameter.In thatcase,youcanuse this astheactualparameter.Forexample,ifyouwantedtoprinto ut astringrepresentationoftheobject,youcouldsay\ System.out.println(this); ".Oryou couldassignthevalueof this toanothervariableinanassignmentstatement.Infact,you can doanythingwith this thatyoucoulddowithanyothervariable,exceptchangeitsv alue. 5.6.2TheSpecialVariablesuperJavaalsodenesanotherspecialvariable,named\ super ",foruseinthedenitionsofinstance methods.Thevariable super isforuseinasubclass.Like this super referstotheobject thatcontainsthemethod.Butit'sforgetful.Itforgetstha ttheobjectbelongstotheclassyou arewriting,anditremembersonlythatitbelongstothesupe rclassofthatclass.Thepointis thattheclasscancontainadditionsandmodicationstothe superclass. super doesn'tknow aboutanyofthoseadditionsandmodications;itcanonlybe usedtorefertomethodsand variablesinthesuperclass. Let'ssaythattheclassthatyouarewritingcontainsaninst ancemethodnamed doSomething() .Considerthesubroutinecallstatement super.doSomething() .Now, super doesn'tknowanythingaboutthe doSomething() methodinthesubclass.Itonlyknows aboutthingsinthesuperclass,soittriestoexecuteametho dnamed doSomething() from thesuperclass.Ifthereisnone|ifthe doSomething() methodwasanadditionratherthana modication|you'llgetasyntaxerror. Thereason super existsissoyoucangetaccesstothingsinthesuperclasstha tare hidden bythingsinthesubclass.Forexample, super.x alwaysreferstoaninstancevariablenamed

PAGE 219

CHAPTER5.OBJECTSANDCLASSES 205 x inthesuperclass.Thiscanbeusefulforthefollowingreaso n:Ifaclasscontainsaninstance variablewiththesamenameasaninstancevariableinitssup erclass,thenanobjectofthat classwillactuallycontaintwovariableswiththesamename :onedenedaspartoftheclass itselfandonedenedaspartofthesuperclass.Thevariable inthesubclassdoesnot replace thevariableofthesamenameinthesuperclass;itmerely hides it.Thevariablefromthe superclasscanstillbeaccessed,using super Whenyouwriteamethodinasubclassthathasthesamesignatu reasamethodinits superclass,themethodfromthesuperclassishiddeninthes ameway.Wesaythatthemethod inthesubclass overrides themethodfromthesuperclass.Again,however, super canbeused toaccessthemethodfromthesuperclass. Themajoruseof super istooverrideamethodwithanewmethodthat extends the behavioroftheinheritedmethod,insteadof replacing thatbehaviorentirely.Thenewmethod canuse super tocallthemethodfromthesuperclass,andthenitcanaddadd itionalcodeto provideadditionalbehavior.Asanexample,supposeyouhav ea PairOfDice classthatincludes a roll() method.Supposethatyouwantasubclass, GraphicalDice ,torepresentapairof dicedrawnonthecomputerscreen.The roll() methodinthe GraphicalDice classshoulddo everythingthatthe roll() methodinthe PairOfDice classdoes.Wecanexpressthiswitha callto super.roll() ,whichcallsthemethodinthesuperclass.Butinadditionto that,the roll() methodfora GraphicalDice objecthastoredrawthedicetoshowthenewvalues.The GraphicalDice classmightlooksomethinglikethis: publicclassGraphicalDiceextendsPairOfDice{ publicvoidroll(){ //Rollthedice,andredrawthem. super.roll();//CalltherollmethodfromPairOfDice.redraw();//Callamethodtodrawthedice. } ..//Morestuff,includingdefinitionofredraw().. } Notethatthisallowsyoutoextendthebehaviorofthe roll() methodevenifyoudon'tknow howthemethodisimplementedinthesuperclass! Hereisamorecompleteexample.Theappletattheendof Section4.7 intheon-line versionofthisbookshowsadisturbancethatmovesaroundin amosaicoflittlesquares.Asit moves,eachsquareitvisitsbecomeabrightershadeofred.T heresultlooksinteresting,butI thinkitwouldbeprettierifthepatternweresymmetric.Asy mmetricversionoftheappletis shownatthebottomofthe Section5.7 (intheon-lineversion).Thesymmetricappletcanbe programmedasaneasyextensionoftheoriginalapplet. Inthesymmetricversion,eachtimeasquareisbrightened,t hesquaresthatcanbeobtained fromthatonebyhorizontalandverticalrerectionthrought hecenterofthemosaicarealso brightened.Thispicturemightmakethesymmetryideaclear er:

PAGE 220

CHAPTER5.OBJECTSANDCLASSES 206 Thefourredsquaresinthepicture,forexample,formasetof suchsymmetricallyplaced squares,asdothepurplesquaresandthegreensquares.(The bluesquareisatthecenterof themosaic,sorerectingitdoesn'tproduceanyothersquare s;it'sitsownrerection.) Theoriginalappletisdenedbytheclass RandomBrighten .Inthatclass,theactualtask ofbrighteningasquareisdonebyamethodcalled brighten() .If row and col aretherow andcolumnnumbersofasquare,then\ brighten(row,col); "increasesthebrightnessofthat square.Allweneedisasubclassof RandomBrighten withamodied brighten() routine. Insteadofjustbrighteningonesquare,themodiedroutine willalsobrightenthehorizontal andverticalrerectionsofthatsquare.Buthowwillitbrigh teneachofthefourindividual squares?Bycallingthe brighten() methodfromtheoriginalclass.Itcandothisbycalling super.brighten() Thereisstilltheproblemofcomputingtherowandcolumnnum bersofthehorizontal andverticalrerections.Todothis,youneedtoknowthenumb erofrowsandthenumber ofcolumns.The RandomBrighten classhasinstancevariablesnamed ROWS and COLUMNS to representthesequantities.Usingthesevariables,it'spo ssibletocomeupwithformulasforthe rerections,asshowninthedenitionofthe brighten() methodbelow. Here'sthecompletedenitionofthenewclass: publicclassSymmetricBrightenextendsRandomBrighten{ voidbrighten(introw,intcol){ //Brightenthespecifiedsquareanditshorizontal//andverticalreflections.Thisoverridesthebrighten//methodfromtheRandomBrightenclass,whichjust//brightensonesquare. super.brighten(row,col);super.brighten(ROWS-1-row,col);super.brighten(row,COLUMNS-1-col);super.brighten(ROWS-1-row,COLUMNS-1-col); } }//endclassSymmetricBrighten Thisistheentiresourcecodefortheapplet!5.6.3ConstructorsinSubclassesConstructorsarenotinherited.Thatis,ifyouextendanexi stingclasstomakeasubclass,the constructorsinthesuperclassdo not becomepartofthesubclass.Ifyouwantconstructorsin thesubclass,youhavetodenenewonesfromscratch.Ifyoud on'tdeneanyconstructors inthesubclass,thenthecomputerwillmakeupadefaultcons tructor,withnoparameters,for you.

PAGE 221

CHAPTER5.OBJECTSANDCLASSES 207 Thiscouldbeaproblem,ifthereisaconstructorinthesuper classthatdoesalotof necessarywork.Itlookslikeyoumighthavetorepeatalltha tworkinthesubclass!Thiscould bea real problemifyoudon'thavethesourcecodetothesuperclass,a nddon'tknowhow itworks,oriftheconstructorinthesuperclassinitialize s private membervariablesthatyou don'tevenhaveaccesstointhesubclass! Obviously,therehastobesomexforthis,andthereis.Itin volvesthespecialvariable, super .Astheveryrststatementinaconstructor,youcanuse super tocallaconstructor fromthesuperclass.Thenotationforthisisabituglyandmi sleading,anditcanonlybeused inthisoneparticularcircumstance:Itlookslikeyouareca lling super asasubroutine(even though super isnotasubroutineandyoucan'tcallconstructorsthesamew ayyoucallother subroutinesanyway).Asanexample,assumethatthe PairOfDice classhasaconstructorthat takestwointegersasparameters.Considerasubclass: publicclassGraphicalDiceextendsPairOfDice{ publicGraphicalDice(){//Constructorforthisclass. super(3,4);//Calltheconstructorfromthe //PairOfDiceclass,withparameters3,4. initializeGraphics();//Dosomeinitializationspecific //totheGraphicalDiceclass. } ..//Moreconstructors,methods,variables.... } Thestatement\ super(3,4); "callstheconstructorfromthesuperclass.Thiscallmust betherstlineoftheconstructorinthesubclass.Notethat ifyoudon'texplicitlycalla constructorfromthesuperclassinthisway,thenthedefaul tconstructorfromthesuperclass, theonewithnoparameters,willbecalledautomatically. Thismightseemrathertechnical,butunfortunatelyitisso metimesnecessary.Bytheway, youcanusethespecialvariable this inexactlythesamewaytocallanotherconstructorinthe sameclass.Thiscanbeusefulsinceitcansaveyoufromrepea tingthesamecodeinseveral constructors.5.7Interfaces,NestedClasses,andOtherDetailsT HISSECTIONsimplypullstogetherafewmoremiscellaneousf eaturesofobjectoriented programminginJava.Readitnow,orjustlookthroughitandr eferbacktoitlaterwhenyou needthismaterial.(Youwillneedtoknowaboutthersttopi c,interfaces,almostassoonas webeginGUIprogramming.)5.7.1InterfacesSomeobject-orientedprogramminglanguages,suchasC++,a llowaclasstoextendtwoor moresuperclasses.Thisiscalled multipleinheritance .Intheillustrationbelow,forexample, classEisshownashavingbothclassAandclassBasdirectsup erclasses,whileclassFhas threedirectsuperclasses.

PAGE 222

CHAPTER5.OBJECTSANDCLASSES 208 Suchmultipleinheritanceis not allowedinJava.ThedesignersofJavawantedtokeepthe languagereasonablysimple,andfeltthatthebenetsofmul tipleinheritancewerenotworththe costinincreasedcomplexity.However,Javadoeshaveafeat urethatcanbeusedtoaccomplish manyofthesamegoalsasmultipleinheritance: interfaces We'veencounteredtheterm\interface"before,inconnecti onwithblackboxesingeneraland subroutinesinparticular.Theinterfaceofasubroutineco nsistsofthenameofthesubroutine, itsreturntype,andthenumberandtypesofitsparameters.T hisistheinformationyouneed toknowifyouwanttocallthesubroutine.Asubroutinealsoh asanimplementation:theblock ofcodewhichdenesitandwhichisexecutedwhenthesubrout ineiscalled. InJava, interface isareservedwordwithanadditional,technicalmeaning.An \ interface "inthissenseconsistsofasetofinstancemethodinterface s,withoutanyassociatedimplementations.(Actually,aJavainterfacecan containotherthingsaswell,butwe won'tdiscussthemhere.)Aclasscan implement an interface byprovidinganimplementationforeachofthemethodsspeciedbytheinterface.Her eisanexampleofaverysimple Java interface : publicinterfaceDrawable{ publicvoiddraw(Graphicsg); } Thislooksmuchlikeaclassdenition,exceptthattheimple mentationofthe draw() methodis omitted.Aclassthatimplementsthe interface Drawable mustprovideanimplementationfor thismethod.Ofcourse,theclasscanalsoincludeothermeth odsandvariables.Forexample, publicclassLineimplementsDrawable{ publicvoiddraw(Graphicsg){ ...//dosomething---presumably,drawaline }...//othermethodsandvariables } Notethattoimplementaninterface,aclassmustdomorethan simplyprovideanimplementationforeachmethodintheinterface;itmustalso state thatitimplementstheinterface,using thereservedword implements asinthisexample:\publicclassLine implements Drawable". Anyclassthatimplementsthe Drawable interfacedenesa draw() instancemethod.Anyobjectcreatedfromsuchaclassincludesa draw() method.Wesaythatan object implements

PAGE 223

CHAPTER5.OBJECTSANDCLASSES 209 an interface ifitbelongstoaclassthatimplementstheinterface.Forex ample,anyobject oftype Line implementsthe Drawable interface. Whileaclasscan extend onlyoneotherclass,itcan implement anynumberofinterfaces. Infact,aclasscanbothextendoneotherclassandimplement oneormoreinterfaces.So,we canhavethingslike classFilledCircleextendsCircle implementsDrawable,Fillable{ ... } Thepointofallthisisthat,althoughinterfacesarenotcla sses,theyaresomethingvery similar.Aninterfaceisverymuchlikeanabstractclass,th atis,aclassthatcanneverbeused forconstructingobjects,butcanbeusedasabasisformakin gsubclasses.Thesubroutines inaninterfaceareabstractmethods,whichmustbeimplemen tedinanyconcreteclassthat implementstheinterface.Andaswithabstractclasses,eve nthoughyoucan'tconstructan objectfromaninterface,youcandeclareavariablewhosety peisgivenbytheinterface.For example,if Drawable isaninterface,andif Line and FilledCircle areclassesthatimplement Drawable ,thenyoucouldsay: Drawablefigure;//DeclareavariableoftypeDrawable.Itc an //refertoanyobjectthatimplementsthe//Drawableinterface. figure=newLine();//figurenowreferstoanobjectofclass Line figure.draw(g);//callsdraw()methodfromclassLinefigure=newFilledCircle();//Now,figurereferstoanobje ct //ofclassFilledCircle. figure.draw(g);//callsdraw()methodfromclassFilledCi rcle Avariableoftype Drawable canrefertoanyobjectofanyclassthatimplementsthe Drawable interface.Astatementlike figure.draw(g) ,above,islegalbecause figure isoftype Drawable and any Drawable objecthasa draw() method.So,whateverobject figure refersto,that objectmusthavea draw() method. Notethata type issomethingthatcanbeusedtodeclarevariables.Atypecan alsobe usedtospecifythetypeofaparameterinasubroutine,orthe returntypeofafunction.In Java,atypecanbeeitheraclass,aninterface,oroneofthee ightbuilt-inprimitivetypes. Thesearetheonlypossibilities.Ofthese,however,onlycl assescanbeusedtoconstructnew objects. Youarenotlikelytoneedtowriteyourowninterfacesuntily ougettothepointofwriting fairlycomplexprograms.However,thereareafewinterface sthatareusedinimportantways inJava'sstandardpackages.You'lllearnaboutsomeofthes estandardinterfacesinthenext fewchapters.5.7.2NestedClassesAclassseemslikeitshouldbeaprettyimportantthing.Acla ssisahigh-levelbuildingblock ofaprogram,representingapotentiallycomplexideaandit sassociateddataandbehaviors. I'vealwaysfeltabitsillywritingtinylittleclassesthat existonlytogroupafewscrapsofdata together.However,suchtrivialclassesareoftenusefulan devenessential.Fortunately,inJava, Icaneasetheembarrassment,becauseoneclasscanbenested insideanotherclass.Mytrivial

PAGE 224

CHAPTER5.OBJECTSANDCLASSES 210 littleclassdoesn'thavetostandonitsown.Itbecomespart ofalargermorerespectableclass. Thisisparticularlyusefulwhenyouwanttocreatealittlec lassspecicallytosupportthework ofalargerclass.And,moreseriously,thereareothergoodr easonsfornestingthedenitionof oneclassinsideanotherclass. InJava,a nestedclass isanyclasswhosedenitionisinsidethedenitionofanoth er class.Nestedclassescanbeeither named or anonymous .Iwillcomebacktothetopicof anonymousclasseslaterinthissection.Anamednestedclas s,likemostotherthingsthatoccur inclasses,canbeeitherstaticornon-static. Thedenitionofastaticnestedclasslooksjustlikethede nitionofanyotherclass,except thatitisnestedinsideanotherclassandithasthemodier static aspartofitsdeclaration. Astaticnestedclassispartofthestaticstructureoftheco ntainingclass.Itcanbeusedinside thatclasstocreateobjectsintheusualway.Ifithasnotbee ndeclaredprivate,thenitcan alsobeusedoutsidethecontainingclass,butwhenitisused outsidetheclass,itsnamemust indicateitsmembershipinthecontainingclass.Thisissim ilartootherstaticcomponentsof aclass:Astaticnestedclassispartoftheclassitselfinth esamewaythatstaticmember variablesarepartsoftheclassitself. Forexample,supposeaclassnamed WireFrameModel representsasetoflinesinthreedimensionalspace.(Suchmodelsareusedtorepresentthree -dimensionalobjectsingraphics programs.)Supposethatthe WireFrameModel classcontainsastaticnestedclass, Line ,that representsasingleline.Then,outsideoftheclass WireFrameModel ,the Line classwouldbe referredtoas WireFrameModel.Line .Ofcourse,thisjustfollowsthenormalnamingconvention forstaticmembersofaclass.Thedenitionofthe WireFrameModel classwithitsnested Line classwouldlook,inoutline,likethis: publicclassWireFrameModel{ ...//othermembersoftheWireFrameModelclassstaticpublicclassLine{ //Representsalinefromthepoint(x1,y1,z1)//tothepoint(x2,y2,z2)in3-dimensionalspace. doublex1,y1,z1;doublex2,y2,z2; }//endclassLine...//othermembersoftheWireFrameModelclass }//endWireFrameModel Insidethe WireFrameModel class,a Line objectwouldbecreatedwiththeconstructor\ new Line() ".Outsidetheclass,\ newWireFrameModel.Line() "wouldbeused. Astaticnestedclasshasfullaccesstothestaticmembersof thecontainingclass,eventothe privatemembers.Similarly,thecontainingclasshasfulla ccesstothemembersofthenested class.Thiscanbeanothermotivationfordeclaringanested class,sinceitletsyougiveone classaccesstotheprivatemembersofanotherclasswithout makingthosemembersgenerally availabletootherclasses. Whenyoucompiletheaboveclassdenition,twoclassleswi llbecreated.Eventhough thedenitionof Line isnestedinside WireFrameModel ,thecompiled Line classisstoredina separatele.Thenameoftheclasslefor Line willbe WireFrameModel$Line.class

PAGE 225

CHAPTER5.OBJECTSANDCLASSES 211 Non-staticnestedclassesarereferredtoas innerclasses .Innerclassesarenot,inpractice, verydierentfromstaticnestedclasses,butanon-staticn estedclassisactuallyassociatedwith anobjectratherthantotheclassinwhichitisnested.Thisc antakesomegettingusedto. Anynon-staticmemberofaclassisnotreallypartoftheclas sitself(althoughitssource codeiscontainedintheclassdenition).Thisistrueforin nerclasses,justasitisforanyother non-staticpartofaclass.Thenon-staticmembersofaclass specifywhatwillbecontainedin objectsthatarecreatedfromthatclass.Thesameistrue|at leastlogically|forinnerclasses. It'sasifeachobjectthatbelongstothecontainingclassha sits owncopy ofthenestedclass. Thiscopyhasaccesstoalltheinstancemethodsandinstance variablesoftheobject,evento thosethataredeclared private .Thetwocopiesoftheinnerclassintwodierentobjectsdi er becausetheinstancevariablesandmethodstheyrefertoare indierentobjects.Infact,the rulefordecidingwhetheranestedclassshouldbestaticorn on-staticissimple:Ifthenested classneedstouseanyinstancevariableorinstancemethodf romthecontainingclass,makethe nestedclassnon-static.Otherwise,itmightaswellbestat ic. Fromoutsidethecontainingclass,anon-staticnestedclas shastobereferredtousinga nameoftheform h variableName i h NestedClassName i ,where h variableName i isavariablethat referstotheobjectthatcontainstheclass.Thisisactuall yratherrare,however.Anon-static nestedclassisgenerallyusedonlyinsidetheclassinwhich itisnested,andthereitcanbe referredtobyitssimplename. Inordertocreateanobjectthatbelongstoaninnerclass,yo umustrsthaveanobject thatbelongstothecontainingclass.(Whenworkinginsidet heclass,theobject\ this "isused implicitly.)Theinnerclassobjectispermanentlyassocia tedwiththecontainingclassobject, andithascompleteaccesstothemembersofthecontainingcl assobject.Lookingatanexample willhelp,andwillhopefullyconvinceyouthatinnerclasse sarereallyverynatural.Consider aclassthatrepresentspokergames.Thisclassmightinclud eanestedclasstorepresentthe playersofthegame.Thisstructureofthe PokerGame classcouldbe: publicclassPokerGame{//Representsagameofpoker. privateclassPlayer{//Representsoneoftheplayersinthi s game. ... }//endclassPlayerprivateDeckdeck;//Adeckofcardsforplayingthegame.privateintpot;//Theamountofmoneythathasbeenbet.... }//endclassPokerGame If game isavariableoftype PokerGame ,then,conceptually, game containsitsowncopyof the Player class.Inananinstancemethodofa PokerGame object,anew Player objectwould becreatedbysaying\ newPlayer() ",justasforanyotherclass.(A Player objectcouldbe createdoutsidethe PokerGame classwithanexpressionsuchas\ game.newPlayer() ".Again, however,thisisveryrare.)The Player objectwillhaveaccesstothe deck and pot instance variablesinthe PokerGame object.Each PokerGame objecthasitsown deck and pot and Players .Playersofthatpokergameusethedeckandpotforthatgame; playersofanother pokergameusetheothergame'sdeckandpot.That'stheeect ofmakingthe Player class

PAGE 226

CHAPTER5.OBJECTSANDCLASSES 212 non-static.Thisisthemostnaturalwayforplayerstobehav e.A Player objectrepresentsa playerofoneparticularpokergame.If Player werea static nestedclass,ontheotherhand,it wouldrepresentthegeneralideaofapokerplayer,independ entofaparticularpokergame. 5.7.3AnonymousInnerClassesInsomecases,youmightndyourselfwritinganinnerclassa ndthenusingthatclassinjusta singlelineofyourprogram.Isitworthcreatingsuchaclass ?Indeed,itcanbe,butforcases likethisyouhavetheoptionofusingan anonymousinnerclass .Ananonymousclassis createdwithavariationofthe new operatorthathastheform new h superclass-or-interface i ( h parameter-list i ){ h methods-and-variables i } Thisconstructordenesanewclass,withoutgivingitaname ,anditsimultaneouslycreates anobjectthatbelongstothatclass.Thisformofthe new operatorcanbeusedinanystatement wherearegular\ new "couldbeused.Theintentionofthisexpressionistocreate :\anewobject belongingtoaclassthatisthesameas h superclass-or-interface i butwiththese h methods-andvariables i added."Theeectistocreateauniquelycustomizedobject, justatthepointin theprogramwhereyouneedit.Notethatitispossibletobase ananonymousclassonan interface,ratherthanaclass.Inthiscase,theanonymousc lassmustimplementtheinterface bydeningallthemethodsthataredeclaredintheinterface .Ifaninterfaceisusedasabase, the h parameter-list i mustbeempty.Otherwise,itcancontainparametersforacon structorin the h superclass i Anonymousclassesareoftenusedforhandlingeventsingrap hicaluserinterfaces,andwe willencounterthemseveraltimesinthechaptersonGUIprog ramming.Fornow,wewilllook atonenot-very-plausibleexample.Considerthe Drawable interface,whichisdenedearlierin thissection.Supposethatwewanta Drawable objectthatdrawsalled,red,100-pixelsquare. Ratherthandeninganew,separateclassandthenusingthat classtocreatetheobject,we canuseananonymousclasstocreatetheobjectinonestateme nt: DrawableredSquare=newDrawable(){ voiddraw(Graphicsg){ g.setColor(Color.red);g.fillRect(10,10,100,100); } }; Thesemicolonattheendofthisstatementisnotpartofthecl assdenition.It'sthesemicolon thatisrequiredattheendofeverydeclarationstatement. WhenaJavaclassiscompiled,eachanonymousnestedclasswi llproduceaseparate classle.Ifthenameofthemainclassis MainClass ,forexample,thenthenamesofthe classlesfortheanonymousnestedclasseswillbe MainClass$1.class MainClass$2.class MainClass$3.class ,andsoon. 5.7.4MixingStaticandNon-staticClasses,asI'vesaid,havetwoverydistinctpurposes.Acla sscanbeusedtogrouptogethera setofstaticmembervariablesandstaticmembersubroutine s.Oritcanbeusedasafactory formakingobjects.Thenon-staticvariablesandsubroutin esintheclassdenitionspecifythe

PAGE 227

CHAPTER5.OBJECTSANDCLASSES 213 instancevariablesandmethodsoftheobjects.Inmostcases ,aclassperformsoneortheother oftheseroles,notboth. Sometimes,however,staticandnon-staticmembersaremixe dinasingleclass.Inthiscase, theclassplaysadualrole.Sometimes,theserolesarecompl etelyseparate.Itisalsopossible forthestaticandnon-staticpartsofaclasstointeract.Th ishappenswheninstancemethods usestaticmembervariablesorcallstaticmembersubroutin es.Aninstancemethodbelongsto anobject,nottotheclassitself,andtherecanbemanyobjec tswiththeirownversionsofthe instancemethod.Butthereisonlyonecopyofastaticmember variable.So,eectively,we havemanyobjectssharingthatonevariable. Suppose,forexample,thatwewanttowritea PairOfDice classthatusesthe Random class mentionedin Section5.3 forrollingthedice.Todothis,a PairOfDice objectneedsaccessto anobjectoftype Random .Butthereisnoneedforeach PairOfDice objecttohaveaseparate Random object.(Infact,itwouldnotevenbeagoodidea:Becauseoft hewayrandomnumber generatorswork,aprogramshould,ingeneral,useonlyones ourceofrandomnumbers.)A nicesolutionistohaveasingle Random variableasa static memberofthe PairOfDice class, sothatitcanbesharedbyall PairOfDice objects.Forexample: importjava.util.Random;publicclassPairOfDice{ privatestaticRandomrandGen=newRandom();publicintdie1;//Numbershowingonthefirstdie.publicintdie2;//Numbershowingontheseconddie.publicPairOfDice(){ //Constructor.Createsapairofdicethat//initiallyshowsrandomvalues. roll(); }publicvoidroll(){ //Rollthedicebysettingeachofthedicetobe//arandomnumberbetween1and6. die1=randGen.nextInt(6)+1;die2=randGen.nextInt(6)+1; } }//endclassPairOfDice Asanotherexample,let'srewritethe Student classthatwasusedin Section5.2 .I'veadded an ID foreachstudentanda static membercalled nextUniqueID .Althoughthereisan ID variableineachstudentobject,thereisonlyone nextUniqueID variable. publicclassStudent{ privateStringname;//Student'sname.privateintID;//UniqueIDnumberforthisstudent.publicdoubletest1,test2,test3;//Gradesonthreetests.privatestaticintnextUniqueID=0; //keeptrackofnextavailableuniqueIDnumber Student(StringtheName){ //ConstructorforStudentobjects;providesanamefortheS tudent,

PAGE 228

CHAPTER5.OBJECTSANDCLASSES 214 //andassignsthestudentauniqueIDnumber. name=theName;nextUniqueID++;ID=nextUniqueID; }publicStringgetName(){ //Accessormethodforreadingvalueofprivate//instancevariable,name. returnname; }publicintgetID(){ //AccessormethodforreadingvalueofID. returnID; }publicdoublegetAverage(){ //Computeaveragetestgrade. return(test1+test2+test3)/3; } }//endofclassStudent Theinitialization\ nextUniqueID=0 "isdoneonlyonce,whentheclassisrstloaded. Whenevera Student objectisconstructedandtheconstructorsays\ nextUniqueID++; ",it's alwaysthesamestaticmembervariablethatisbeingincreme nted.Whentheveryrst Student objectiscreated, nextUniqueID becomes1.Whenthesecondobjectiscreated, nextUniqueID becomes2.Afterthethirdobject,itbecomes3.Andsoon.The constructorstoresthenew valueof nextUniqueID inthe ID variableoftheobjectthatisbeingcreated.Ofcourse, ID isan instancevariable,soeveryobjecthasitsownindividual ID variable.Theclassisconstructed sothateachstudentwillautomaticallygetadierentvalue forits ID variable.Furthermore, the ID variableis private ,sothereisnowayforthisvariabletobetamperedwithafter the objecthasbeencreated.Youareguaranteed,justbythewayt heclassisdesigned,thatevery studentobjectwillhaveitsownpermanent,uniqueidentic ationnumber.Whichiskindof coolifyouthinkaboutit.5.7.5StaticImportThe import directivemakesitpossibletorefertoaclasssuchas java.awt.Color usingits simplename, Color .Allyouhavetodoissay importjava.awt.Color or importjava.awt.* Butyoustillhavetousecompoundnamestorefertostaticmem bervariablessuchas System.out andtostaticmethodssuchas Math.sqrt Java5.0introducedanewformofthe import directivethatcanbeusedtoimport static membersofaclassinthesamewaythattheordinary import directiveimportsclassesfroma package.Thenewformofthedirectiveiscalleda staticimport ,andithassyntax importstatic h package-name i h class-name i h static-member-name i ; toimportonestaticmembernamefromaclass,or importstatic h package-name i h class-name i .*; toimportallthepublicstaticmembersfromaclass.Forexam ple,ifyouprefaceaclass denitionwith

PAGE 229

CHAPTER5.OBJECTSANDCLASSES 215 importstaticjava.lang.System.out; thenyoucanusethesimplename out insteadofthecompoundname System.out .Thismeans youcanuse out.println insteadof System.out.println .Ifyouaregoingtoworkextensively withthe Math class,youcanprefaceyourclassdenitionwith importstaticjava.lang.Math.*; Thiswouldallowyoutosay sqrt insteadof Math.sqrt log insteadof Math.log PI instead of Math.PI ,andsoon. Notethatthestaticimportdirectiverequiresa h package-name i ,evenforclassesinthe standardpackage java.lang .Oneconsequenceofthisisthatyoucan'tdoastaticimportf rom aclassinthedefaultpackage.Inparticular,itisnotpossi bletodoastaticimportfrommy TextIO class|ifyouwantedtodothat,youwouldhavetomove TextIO intoapackage. 5.7.6EnumsasClassesEnumeratedtypeswereintroducedin Subsection2.3.3 .Nowthatwehavecoveredmorematerial onclassesandobjects,wecanrevisitthetopic(althoughst illnotcoveringenumeratedtypes intheirfullcomplexity). Enumeratedtypesareactuallyclasses,andeachenumerated typeconstantisa public final static membervariableinthatclass(eventhoughtheyarenotdecla redwiththese modiers).Thevalueofthevariableisanobjectbelongingt otheenumeratedtypeclass.There isonesuchobjectforeachenumeratedtypeconstant,andthe searetheonlyobjectsofthe classthatcaneverbecreated.Itisreallytheseobjectstha trepresentthepossiblevaluesof theenumeratedtype.Theenumeratedtypeconstantsareactu allyvariablesthatrefertothese objects. Whenanenumeratedtypeisdenedinsideanotherclass,itis anestedclassinsidethe enclosingclass.Infact,itisastaticnestedclass,whethe ryoudeclareittobe static ornot. Butitcanalsobedeclaredasanon-nestedclass,inaleofit sown.Forexample,wecould denethefollowingenumeratedtypeinalenamed Suit.java : publicenumSuit{ SPADES,HEARTS,DIAMONDS,CLUBS } Thisenumeratedtyperepresentsthefourpossiblesuitsfor aplayingcard,anditcouldhave beenusedintheexample Card.java from Subsection5.4.2 Furthermore,inadditiontoitslistofvalues,anenumerate dtypecancontainsomeof theotherthingsthataregularclasscancontain,including methodsandadditionalmember variables.Justaddasemicolon(;)attheendofthelistofva lues,andthenadddenitions ofthemethodsandvariablesintheusualway.Forexample,we mightmakeanenumerated typetorepresentthepossiblevaluesofaplayingcard.Itmi ghtbeusefultohaveamethod thatreturnsthecorrespondingvalueinthegameofBlackjac k.Asanotherexample,suppose thatwhenweprintoutoneofthevalues,we'dliketoseesomet hingdierentfromthedefault stringrepresentation(theidentierthatnamestheconsta nt).Inthatcase,wecanoverridethe toString() methodintheclasstoprintoutadierentstringrepresenta tion.Thiswouldgives somethinglike: publicenumCardValue{

PAGE 230

CHAPTER5.OBJECTSANDCLASSES 216 ACE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT, NINE,TEN,JACK,QUEEN,KING; /** *ReturnthevalueofthisCardValueinthegameofBlackjack.*Notethatthevaluereturnedforanaceis1.*/ publicintblackJackValue(){ if(this==JACK||this==QUEEN||this==KING) return10; else return1+ordinal(); }/** *ReturnaStringrepresentationofthisCardValue,usingnu mbers *forthenumericalcardsandnamesfortheaceandfacecards.*/ publicStringtoString(){ switch(this){//"this"isoneoftheenumeratedtypevaluescaseACE://ordinalnumberofACE return"Ace"; caseJACK://ordinalnumberofJACK return"Jack"; caseQUEEN://ordinalnumberofQUEEN return"Queen"; caseKING://ordinalnumberofKING return"King"; default://it'sanumericcardvalue intnumericValue=1+ordinal();return""+numericValue; } }//endCardValue Themethods blackjackValue() and toString() areinstancemethodsin CardValue .Since CardValue.JACK isanobjectbelongingtothatclass,youcancall CardValue.JACK.blackjackValue() .Supposethat cardVal isdeclaredtobeavariable oftype CardValue ,sothatitcanrefertoanyofthevaluesintheenumeratedtyp e.We cancall cardVal.blackjackValue() tondtheBlackjackvalueofthe CardValue objectto which cardVal refers,and System.out.println(cardVal) willimplicitlycallthemethod cardVal.toString() toobtaintheprintrepresentationofthat CardValue .(Oneotherthingto keepinmindisthatsince CardValue isaclass,thevalueof cardVal canbe null ,whichmeans itdoesnotrefertoanyobject.) Rememberthat ACE TWO ,..., KING aretheonlypossibleobjectsoftype CardValue ,soinan instancemethodinthatclass, this willrefertooneofthosevalues.Recallthattheinstance method ordinal() isdenedinanyenumeratedtypeandgivesthepositionofthe enumerated typevalueinthelistofpossiblevalues,withcountingstar tingfromzero. (Ifyounditannoyingtousetheclassnameaspartofthename ofeveryenumerated typeconstant,youcanusestaticimporttomakethesimplena mesoftheconstantsdirectly available|butonlyifyouputtheenumeratedtypeintoapack age.Forexample,iftheenumeratedtype CardValue isdenedinapackagenamed cardgames ,thenyoucouldplace importstaticcardgames.CardValue.*;

PAGE 231

CHAPTER5.OBJECTSANDCLASSES 217 atthebeginningofasourcecodele.Thiswouldallowyou,fo rexample,tousethename JACK inthatleinsteadof CardValue.JACK .)

PAGE 232

Exercises 218 ExercisesforChapter5 1. Inallversionsofthe PairOfDice classin Section5.2 ,theinstancevariables die1 and die2 (solution) aredeclaredtobe public .Theyreallyshouldbeprivate,sothattheyareprotectedfr om beingchangedfromoutsidetheclass.Writeanotherversion ofthe PairOfDice classin whichtheinstancevariables die1 and die2 are private .Yourclasswillneed\getter" methodsthatcanbeusedtondoutthevaluesof die1 and die2 .(Theideaistoprotect theirvaluesfrombeingchangedfromoutsidetheclass,buts tilltoallowthevaluestobe read.)Includeotherimprovementsintheclass,ifyoucanth inkofany.Testyourclass withashortprogramthatcountshowmanytimesapairofdicei srolled,beforethetotal ofthetwodiceisequaltotwo. 2. Acommonprogrammingtaskiscomputingstatisticsofasetof numbers.(Astatisticis (solution) anumberthatsummarizessomepropertyofasetofdata.)Comm onstatisticsinclude themean(alsoknownastheaverage)andthestandarddeviati on(whichtellshowspread outthedataarefromthemean).Ihavewrittenalittleclassc alled StatCalc thatcan beusedtocomputethesestatistics,aswellasthesumofthei temsinthedatasetand thenumberofitemsinthedataset.Youcanreadthesourcecod eforthisclassinthe le StatCalc.java .If calc isavariableoftype StatCalc ,thenthefollowingmethodsare dened: calc.enter(item); where item isanumber,addstheitemtothedataset. calc.getCount() isafunctionthatreturnsthenumberofitemsthathavebeen addedtothedataset. calc.getSum() isafunctionthatreturnsthesumofalltheitemsthathavebe en addedtothedataset. calc.getMean() isafunctionthatreturnstheaverageofalltheitems. calc.getStandardDeviation() isafunctionthatreturnsthestandarddeviation oftheitems. Typically,allthedataareaddedoneaftertheotherbycalli ngthe enter() method overandover,asthedatabecomeavailable.Afterallthedat ahavebeenentered,any oftheothermethodscanbecalledtogetstatisticalinforma tionaboutthedata.The methods getMean() and getStandardDeviation() shouldonlybecalledifthenumber ofitemsisgreaterthanzero. Modifythecurrentsourcecode, StatCalc.java ,toaddinstancemethods getMax() and getMin() .The getMax() methodshouldreturnthelargestofalltheitemsthathavebe en addedtothedataset,and getMin() shouldreturnthesmallest.Youwillneedtoaddtwo newinstancevariablestokeeptrackofthelargestandsmall estitemsthathavebeenseen sofar. Testyournewclassbyusingitinaprogramtocomputestatist icsforasetofnon-zero numbersenteredbytheuser.Startbycreatinganobjectofty pe StatCalc : StatCalccalc;//Objecttobeusedtoprocessthedata.calc=newStatCalc(); Readnumbersfromtheuserandaddthemtothedataset.Use0as asentinelvalue (thatis,stopreadingnumberswhentheuserenters0).After alltheuser'snon-zero

PAGE 233

Exercises 219 numbershavebeenentered,printouteachofthesixstatisti csthatareavailablefrom calc 3. Thisproblemusesthe PairOfDice classfromExercise5.1andthe StatCalc classfrom (solution) Exercise5.2. TheprograminExercise4.4performstheexperimentofcount inghowmanytimesa pairofdiceisrolledbeforeagiventotalcomesup.Itrepeat sthisexperiment10000times andthenreportstheaveragenumberofrolls.Itdoesthiswho leprocessforeachpossible total(2,3,...,12). Redothatexercise.Butinsteadofjustreportingtheaverag enumberofrolls,you shouldalsoreportthestandarddeviationandthemaximumnu mberofrolls.Usea PairOfDice objecttorepresentthedice.Usea StatCalc objecttocomputethestatistics. (You'llneedanew StatCalc objectforeachpossibletotal,2,3,...,12.Youcanusea newpairofdiceifyouwant,butit'snotnecessary.) 4. The BlackjackHand classfrom Subsection5.5.1 isanextensionofthe Hand classfrom Sec(solution) tion5.4 .Theinstancemethodsinthe Hand classarediscussedinthatsection.Inaddition tothosemethods, BlackjackHand includesaninstancemethod, getBlackjackValue() thatreturnsthevalueofthehandforthegameofBlackjack.F orthisexercise,youwill alsoneedthe Deck and Card classesfrom Section5.4 ABlackjackhandtypicallycontainsfromtwotosixcards.Wr iteaprogramtotestthe BlackjackHand class.Youshouldcreatea BlackjackHand objectanda Deck object.Pick arandomnumberbetween2and6.Dealthatmanycardsfromthed eckandaddthemto thehand.Printoutallthecardsinthehand,andthenprintou tthevaluecomputedfor thehandby getBlackjackValue() .Repeatthisaslongastheuserwantstocontinue. Inadditionto TextIO.java ,yourprogramwilldependon Card.java Deck.java Hand.java ,and BlackjackHand.java 5. WriteaprogramthatletstheuserplayBlackjack.Thegamewi llbeasimpliedversion (solution) ofBlackjackasitisplayedinacasino.Thecomputerwillact asthedealer.Asin thepreviousexercise,yourprogramwillneedtheclassesde nedin Card.java Deck.java Hand.java ,and BlackjackHand.java .(Thisisthelongestandmostcomplexprogramthat hascomeupsofarintheexercises.) Youshouldrstwriteasubroutineinwhichtheuserplaysone game.Thesubroutine shouldreturna boolean valuetoindicatewhethertheuserwinsthegameornot.Retur n true iftheuserwins, false ifthedealerwins.Theprogramneedsanobjectofclass Deck andtwoobjectsoftype BlackjackHand ,oneforthedealerandonefortheuser. ThegeneralobjectinBlackjackistogetahandofcardswhose valueisascloseto21as possible,withoutgoingover.Thegamegoeslikethis. First,twocardsaredealtintoeachplayer'shand.Ifthedea ler'shandhasavalueof 21atthispoint,thenthedealerwins.Otherwise,iftheuser has21,thentheuser wins.(Thisiscalleda\Blackjack".)Notethatthedealerwi nsonatie,soifboth playershaveBlackjack,thenthedealerwins. Now,ifthegamehasnotended,theusergetsachancetoaddsom ecardstoher hand.Inthisphase,theuserseesherowncardsandsees one ofthedealer'stwo cards.(Inacasino,thedealerdealshimselfonecardfaceup andonecardfacedown. Alltheuser'scardsaredealtfaceup.)Theusermakesadecis ionwhetherto\Hit",

PAGE 234

Exercises 220 whichmeanstoaddanothercardtoherhand,orto\Stand",whi chmeanstostop takingcards. IftheuserHits,thereisapossibilitythattheuserwillgoo ver21.Inthatcase,the gameisoverandtheuserloses.Ifnot,thentheprocessconti nues.Theusergetsto decideagainwhethertoHitorStand. IftheuserStands,thegamewillend,butrstthedealergets achancetodrawcards. Thedealeronlyfollowsrules,withoutanychoice.Therulei sthataslongasthe valueofthedealer'shandislessthanorequalto16,thedeal erHits(thatis,takes anothercard).Theusershouldseeallthedealer'scardsatt hispoint.Now,the winnercanbedetermined:Ifthedealerhasgoneover21,theu serwins.Otherwise, ifthedealer'stotalisgreaterthanorequaltotheuser'sto tal,thenthedealerwins. Otherwise,theuserwins. Twonotesonprogramming:Atanypointinthesubroutine,ass oonasyouknowwho thewinneris,youcansay\ returntrue ;"or\ returnfalse ;"toendthesubroutine andreturntothemainprogram.Toavoidhavinganoverabunda nceofvariablesinyour subroutine,rememberthatafunctioncallsuchas userHand.getBlackjackValue() can beusedanywherethatanumbercouldbeused,includinginano utputstatementorin theconditionofan if statement. WriteamainprogramthatletstheuserplayseveralgamesofB lackjack.Tomake thingsinteresting,givetheuser100dollars,andlettheus ermakebetsonthegame.If theuserloses,subtractthebetfromtheuser'smoney.Ifthe userwins,addanamount equaltothebettotheuser'smoney.Endtheprogramwhentheu serwantstoquitor whensherunsoutofmoney. Anappletversionofthisprogramcanbefoundintheon-linev ersionofthisexercise. Youmightwanttotryitoutbeforeyouworkontheprogram. 6. Subsection5.7.6 discussesthepossibilityofrepresentingthesuitsandval uesofplaying (solution) cardsasenumeratedtypes.Rewritethe Card classfrom Subsection5.4.2 tousethese enumeratedtypes.Testyourclasswithaprogramthatprints outthe52possibleplaying cards.Suggestions:Youcanmodifythesourcecodele Card.java ,butyoushouldleave outsupportforJokers.Inyourmainprogram,usenested for loopstogeneratedcardsof allpossiblesuitsandvalues;the for loopswillbe\for-each"loopsofthetypediscussed in Subsection3.4.4 .Itwouldbenicetoadda toString() methodtothe Suit classfrom Subsection5.7.6 ,sothatasuitprintsoutas\Spades"or\Hearts"insteadof\ SPADES" or\HEARTS".

PAGE 235

Quiz 221 QuizonChapter5 (answers) 1. Object-orientedprogramminguses classes and objects .Whatareclassesandwhatare objects?Whatistherelationshipbetweenclassesandobjec ts? 2. Explaincarefullywhat null meansinJava,andwhythisspecialvalueisnecessary. 3. Whatisa constructor? Whatisthepurposeofaconstructorinaclass? 4. Supposethat Kumquat isthenameofaclassandthat fruit isavariableoftype Kumquat. Whatisthemeaningofthestatement\ fruit=newKumquat(); "?Thatis,whatdoes thecomputerdowhenitexecutesthisstatement?(Trytogive acompleteanswer.The computerdoesseveralthings.) 5. Whatismeantbytheterms instancevariable and instancemethod ? 6. Explainwhatismeantbytheterms subclass and superclass. 7. Modifythefollowingclasssothatthetwoinstancevariable sare private andthereisa gettermethodandasettermethodforeachinstancevariable : publicclassPlayer{ Stringname;intscore; } 8. Explainwhytheclass Player thatisdenedinthepreviousquestionhasaninstance methodnamed toString() ,eventhoughnodenitionofthismethodappearsinthe denitionoftheclass. 9. Explaintheterm polymorphism. 10. Javauses\garbagecollection"formemorymanagement.Expl ainwhatismeanthereby garbagecollection.Whatisthealternativetogarbagecoll ection? 11. Forthisproblem,youshouldwriteaverysimplebutcomplete class.Theclassrepresents acounterthatcounts0,1,2,3,4,....Thenameoftheclasssh ouldbe Counter .Ithas one private instancevariablerepresentingthevalueofthecounter.It hastwoinstance methods: increment() addsonetothecountervalue,and getValue() returnsthecurrent countervalue.Writeacompletedenitionfortheclass, Counter 12. Thisproblemusesthe Counter classfromthepreviousquestion.Thefollowingprogram segmentismeanttosimulatetossingacoin100times.Itshou ldusetwo Counter objects, headCount and tailCount ,tocountthenumberofheadsandthenumberoftails.Fillin theblankssothatitwilldoso:

PAGE 236

Quiz 222 CounterheadCount,tailCount;tailCount=newCounter();headCount=newCounter();for(intflip=0;flip<100;flip++){ if(Math.random()<0.5)//There'sa50/50chancethatthisi strue. ;//Counta"head". else ;//Counta"tail". }System.out.println("Therewere"+ +"heads."); System.out.println("Therewere"+ +"tails.");

PAGE 237

Chapter6IntroductiontoGUIProgrammingC omputeruserstodayexpect tointeractwiththeircomputersusingagraphicaluser interface(GUI).JavacanbeusedtowriteGUIprogramsrangi ngfromsimpleappletswhich runonaWebpagetosophisticatedstand-aloneapplications GUIprogramsdierfromtraditional\straight-through"pr ogramsthatyouhaveencounteredintherstfewchaptersofthisbook.Onebigdierence isthatGUIprogramsare event-driven .Thatis,useractionssuchasclickingonabuttonorpressin gakeyonthe keyboardgenerateevents,andtheprogrammustrespondtoth eseeventsastheyoccur.Eventdrivenprogrammingbuildsonalltheskillsyouhavelearned intherstvechaptersofthis text.Youneedtobeabletowritethesubroutinesthatrespon dtoevents.Insidethesesubroutines,youaredoingthekindofprogramming-in-the-smallt hatwascoveredin Chapter2 and Chapter3 Andofcourse,objectsareeverywhereinGUIprogramming.Ev entsareobjects.Colors andfontsareobjects.GUIcomponentssuchasbuttonsandmen usareobjects.Eventsare handledbyinstancemethodscontainedinobjects.InJava,G UIprogrammingisobject-oriented programming. ThischaptercoversthebasicsofGUIprogramming.Thediscu ssionwillcontinuein Chapter12 withmoredetailsandwithmoreadvancedtechniques. 6.1TheBasicGUIApplicationT herearetwobasictypes ofGUIprograminJava: stand-aloneapplications and (online) applets .AnappletisaprogramthatrunsinarectangularareaonaWeb page.Appletsare generallysmallprograms,meanttodofairlysimplethings, althoughthereisnothingtostop themfrombeingverycomplex.Appletswereresponsiblefora lotoftheinitialexcitementabout Javawhenitwasintroduced,sincetheycoulddothingsthatc ouldnototherwisebedoneon Webpages.However,therearenoweasierwaystodomanyofthe morebasicthingsthatcan bedonewithapplets,andtheyarenolongerthemainfocusofi nterestinJava.Nevertheless, therearestillsomethingsthatcanbedonebestwithapplets ,andtheyarestillfairlycommon ontheWeb.Wewilllookatappletsinthenextsection. Astand-aloneapplicationisaprogramthatrunsonitsown,w ithoutdependingona Webbrowser.You'vebeenwritingstand-aloneapplications allalong.Anyclassthathasa main() routinedenesastand-aloneapplication;runningtheprog ramjustmeansexecuting this main() routine.However,theprogramsthatyou'veseenuptillnowh avebeen\commandline"programs,wheretheuserandcomputerinteractbytypi ngthingsbackandforthtoeach 223

PAGE 238

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 224 other.AGUIprogramoersamuchrichertypeofuserinterfac e,wheretheuserusesamouse andkeyboardtointeractwithGUIcomponentssuchaswindows ,menus,buttons,checkboxes, textinputboxes,scrollbars,andsoon.Themainroutineofa GUIprogramcreatesoneor moresuchcomponentsanddisplaysthemonthecomputerscree n.Veryoften,that'sallitdoes. OnceaGUIcomponenthasbeencreated,itfollowsits own programming|programmingthat tellsithowtodrawitselfonthescreenandhowtorespondtoe ventssuchasbeingclickedon bytheuser. AGUIprogramdoesn'thavetobeimmenselycomplex.Wecan,fo rexample,writeavery simpleGUI\HelloWorld"programthatsays\Hello"totheuse r,butdoesitbyopeninga windowwherethethegreetingisdisplayed: importjavax.swing.JOptionPane;publicclassHelloWorldGUI1{ publicstaticvoidmain(String[]args){ JOptionPane.showMessageDialog(null,"HelloWorld!"); } } Whenthisprogramisrun,awindowappearsonthescreenthatc ontainsthemessage \HelloWorld!".Thewindowalsocontainsan\OK"buttonfort heusertoclickafterreading themessage.Whentheuserclicksthisbutton,thewindowclo sesandtheprogramends.By theway,thisprogramcanbeplacedinalenamed HelloWorldGUI1.java ,compiled,andrun justlikeanyotherJavaprogram. Now,thisprogramisalreadydoingsomeprettyfancystu.It createsawindow,itdraws thecontentsofthatwindow,andithandlestheeventthatisg eneratedwhentheuserclicks thebutton.Thereasontheprogramwassoeasytowriteisthat alltheworkisdoneby showMessageDialog() ,a static methodinthebuilt-inclass JOptionPane .(Notethatthe sourcecode\imports"theclass javax.swing.JOptionPane tomakeitpossibletorefertothe JOptionPane classusingitssimplename.See Subsection4.5.3 forinformationaboutimporting classesfromJava'sstandardpackages.) IfyouwanttodisplayamessagetotheuserinaGUIprogram,th isisagoodwaytodoit: Justuseastandardclassthatalreadyknowshowtodothework !Andinfact, JOptionPane is regularlyusedforjustthispurpose(butaspartofalargerp rogram,usually).Ofcourse,ifyou wanttodoanythingseriousinaGUIprogram,thereisalotmor etolearn.Togiveyouanidea ofthetypesofthingsthatareinvolved,we'lllookatashort GUIprogramthatdoesthesame thingsasthepreviousprogram|openawindowcontainingame ssageandanOKbutton,and respondtoaclickonthebuttonbyendingtheprogram|butdoe sitallbyhandinsteadofby usingthebuilt-in JOptionPane class.Mindyou,thisis not agoodwaytowritetheprogram, butitwillillustratesomeimportantaspectsofGUIprogram minginJava. Hereisthesourcecodefortheprogram.Youarenotexpectedt ounderstandityet.I willexplainhowitworksbelow,butitwilltaketherestofth echapterbeforeyouwillreally understandcompletely.Inthissection,youwilljustgetab riefoverviewofGUIprogramming. importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassHelloWorldGUI2{ privatestaticclassHelloWorldDisplayextendsJPanel{

PAGE 239

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 225 publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);g.drawString("HelloWorld!",20,30); } }privatestaticclassButtonHandlerimplementsActionList ener{ publicvoidactionPerformed(ActionEvente){ System.exit(0); } }publicstaticvoidmain(String[]args){ HelloWorldDisplaydisplayPanel=newHelloWorldDisplay( ); JButtonokButton=newJButton("OK");ButtonHandlerlistener=newButtonHandler();okButton.addActionListener(listener);JPanelcontent=newJPanel();content.setLayout(newBorderLayout());content.add(displayPanel,BorderLayout.CENTER);content.add(okButton,BorderLayout.SOUTH);JFramewindow=newJFrame("GUITest");window.setContentPane(content);window.setSize(250,100);window.setLocation(100,100);window.setVisible(true); } } 6.1.1JFrameandJPanelInaJavaGUIprogram,eachGUIcomponentintheinterfaceisr epresentedbyanobjectin theprogram.Oneofthemostfundamentaltypesofcomponenti sthe window .Windowshave manybehaviors.Theycanbeopenedandclosed.Theycanberes ized.Theyhave\titles"that aredisplayedinthetitlebarabovethewindow.Andmostimpo rtant,theycancontainother GUIcomponentssuchasbuttonsandmenus. Java,ofcourse,hasabuilt-inclasstorepresentwindows.T hereareactuallyseveraldierent typesofwindow,butthemostcommontypeisrepresentedbyth e JFrame class(whichis includedinthepackage javax.swing ).A JFrame isanindependentwindowthatcan,for example,actasthemainwindowofanapplication.Oneofthem ostimportantthingsto understandisthata JFrame objectcomeswithmanyofthebehaviorsofwindowsalready programmedin.Inparticular,itcomeswiththebasicproper tiessharedbyallwindows,such asatitlebarandtheabilitytobeopenedandclosed.Sincea JFrame comeswiththesebehaviors, youdon'thavetoprogramthemyourself!Thisis,ofcourse,o neofthecentralideasofobjectorientedprogramming.Whata JFrame doesn'tcomewith,ofcourse,is content ,thestuthat iscontainedinthewindow.Ifyoudon'taddanyothercontent toa JFrame ,itwilljustdisplay alargeblankarea.Youcanaddcontenteitherbycreatinga JFrame objectandthenadding thecontenttoitorbycreatingasubclassof JFrame andaddingthecontentintheconstructor ofthatsubclass.

PAGE 240

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 226 Themainprogramabovedeclaresavariable, window ,oftype JFrame andsetsittoreferto anewwindowobjectwiththestatement: JFramewindow=newJFrame("GUITest"); Theparameterintheconstructor,\GUITest",speciesthet itlethatwillbedisplayedinthe titlebarofthewindow.Thislinecreatesthewindowobject, butthewindowitselfisnotyet visibleonthescreen.Beforemakingthewindowvisible,som eofitspropertiesaresetwith thesestatements: window.setContentPane(content);window.setSize(250,100);window.setLocation(100,100); Therstlineheresetsthecontentofthewindow.(Theconten titselfwascreatedearlierinthe mainprogram.)Thesecondlinesaysthatthewindowwillbe25 0pixelswideand100pixels high.Thethirdlinesaysthattheupperleftcornerofthewin dowwillbe100pixelsoverfrom theleftedgeofthescreenand100pixelsdownfromthetop.On ceallthishasbeensetup,the windowisactuallymadevisibleonthescreenwiththecomman d: window.setVisible(true); Itmightlookasiftheprogramendsatthatpoint,and,infact ,the main() routinedoesend. However,thethewindowisstillonthescreenandtheprogram asawholedoesnotenduntil theuserclickstheOKbutton. Thecontentthatisdisplayedina JFrame iscalledits contentpane .(Inadditiontoits contentpane,a JFrame canalsohaveamenubar,whichisaseparatethingthatIwillt alk aboutlater.)Abasic JFrame alreadyhasablankcontentpane;youcaneitheraddthings tothatpaneoryoucanreplacethebasiccontentpaneentirel y.Inmysampleprogram, theline window.setContentPane(content) replacestheoriginalblankcontentpanewitha dierentcomponent.(Rememberthata\component"isjustav isualelementofagraphical userinterface).Inthiscase,thenewcontentisacomponent oftype JPanel JPanel isanotherofthefundamentalclassesinSwing.Thebasic JPanel is,again,just ablankrectangle.Therearetwowaystomakeauseful JPanel :Therstisto addother components tothepanel;thesecondisto drawsomething inthepanel.Bothofthese techniquesareillustratedinthesampleprogram.Infact,y ouwillndtwo JPanel sinthe program: content ,whichisusedtocontainothercomponents,and displayPanel ,whichis usedasadrawingsurface. Let'slookmorecloselyat displayPanel .Thisvariableisoftype HelloWorldDisplay ,which isanestedstaticclassinsidethe HelloWorldGUI2 class.(Nestedclasseswereintroducedin Subsection5.7.2 .)Thisclassdenesjustoneinstancemethod, paintComponent() ,which overridesamethodofthesamenameinthe JPanel class: privatestaticclassHelloWorldDisplayextendsJPanel{ publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);g.drawString("HelloWorld!",20,30); } } The paintComponent() methodiscalledbythesystemwhenacomponentneedstobepai nted onthescreen.Inthe JPanel class,the paintComponent methodsimplyllsthepanelwiththe

PAGE 241

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 227 panel'sbackgroundcolor.The paintComponent() methodin HelloWorldDisplay beginsbycalling super.paintComponent(g) .Thiscallstheversionof paintComponent() thatisdenedin thesuperclass, JPanel ;thatis,itllsthepanelwiththebackgroundcolor.(See Subsection5.6.2 foradiscussionofthespecialvariable super .)Thenitcalls g.drawString() topaintthestring \HelloWorld!"ontothepanel.Thenetresultisthatwheneve ra HelloWorldDisplay isshown onthescreen,itdisplaysthestring\HelloWorld!". Wewilloftenuse JPanel sinthisway,asdrawingsurfaces.Usually,whenwedothis,w ewill deneanestedclassthatisasubclassof JPanel andwewillwritea paintComponent method inthatclasstodrawthedesiredcontentinthepanel.6.1.2ComponentsandLayoutAnotherwayofusinga JPanel isasa container toholdothercomponents.Javahasmany classesthatdeneGUIcomponents.Beforethesecomponents canappearonthescreen,they mustbe added toacontainer.Inthisprogram,thevariablenamed content referstoa JPanel thatisusedasacontainer,andtwoothercomponentsareadde dtothatcontainer.Thisis doneinthestatements: content.add(displayPanel,BorderLayout.CENTER);content.add(okButton,BorderLayout.SOUTH); Here, content referstoanobjectoftype JPanel ;laterintheprogram,thispanelbecomesthe contentpaneofthewindow.Therstcomponentthatisaddedt o content is displayPanel which,asdiscussedabove,displaysthemessage,\HelloWor ld!".Thesecondis okButton which representsthebuttonthattheuserclickstoclosethewindo w.Thevariable okButton isof type JButton ,theJavaclassthatrepresentspushbuttons. The\BorderLayout"stuinthesestatementshastodowithho wthetwocomponentsare arrangedinthecontainer.Whencomponentsareaddedtoacon tainer,therehastobesomeway ofdecidinghowthosecomponentsarearrangedinsidethecon tainer.Thisiscalled\layingout" thecomponentsinthecontainer,andthemostcommontechniq ueforlayingoutcomponents istousea layoutmanager .Alayoutmanagerisanobjectthatimplementssomepolicyfo r howtoarrangethecomponentsinacontainer;dierenttypes oflayoutmanagerimplement dierentpolicies.Onetypeoflayoutmanagerisdenedbyth e BorderLayout class.Inthe program,thestatement content.setLayout(newBorderLayout()); createsanew BorderLayout objectandtellsthe content paneltousethenewobjectasitslayout manager.Essentially,thislinedetermineshowcomponents thatareaddedtothecontentpanel willbearrangedinsidethepanel.Wewillcoverlayoutmanag ersinmuchmoredetaillater,but fornowallyouneedtoknowisthatadding okButton inthe BorderLayout.SOUTH positionputs thebuttonatthebottomofthepanel,andputting displayPanel inthe BorderLayout.CENTER positionmakesitllanyspacethatisnottakenupbythebutt on. ThisexampleshowsageneraltechniqueforsettingupaGUI:C reateacontainerandassign alayoutmanagertoit,createcomponentsandaddthemtothec ontainer,andusethecontainer asthecontentpaneofawindoworapplet.Acontainerisitsel facomponent,soitispossible thatsomeofthecomponentsthatareaddedtothetop-levelco ntainerarethemselvescontainers, withtheirownlayoutmanagersandcomponents.Thismakesit possibletobuildupcomplex userinterfacesinahierarchicalfashion,withcontainers insidecontainersinsidecontainers...

PAGE 242

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 228 6.1.3EventsandListenersThestructureofcontainersandcomponentssetsupthephysi calappearanceofaGUI,but itdoesn'tsayanythingabouthowtheGUI behaves .Thatis,whatcantheuserdotothe GUIandhowwillitrespond?GUIsarelargely event-driven ;thatis,theprogramwaits foreventsthataregeneratedbytheuser'sactions(orbysom eothercause).Whenanevent occurs,theprogramrespondsbyexecutingan event-handlingmethod .Inordertoprogram thebehaviorofaGUI,youhavetowriteevent-handlingmetho dstorespondtotheeventsthat youareinterestedin. ThemostcommontechniqueforhandlingeventsinJavaistous e eventlisteners .A listenerisanobjectthatincludesoneormoreevent-handli ngmethods.Whenaneventis detectedbyanotherobject,suchasabuttonormenu,thelist enerobjectisnotiedandit respondsbyrunningtheappropriateevent-handlingmethod .Aneventisdetectedorgenerated byanobject.Anotherobject,thelistener,hastheresponsi bilityofrespondingtotheevent. Theeventitselfisactuallyrepresentedbyathirdobject,w hichcarriesinformationaboutthe typeofevent,whenitoccurred,andsoon.Thisdivisionofre sponsibilitiesmakesiteasierto organizelargeprograms. Asanexample,considertheOKbuttoninthesampleprogram.W hentheuserclicksthe button,aneventisgenerated.Thiseventisrepresentedbya nobjectbelongingtotheclass ActionEvent .Theeventthatisgeneratedisassociatedwiththebutton;w esaythatthebutton isthe source oftheevent.Thelistenerobjectinthiscaseisanobjectbel ongingtotheclass ButtonHandler ,whichisdenedasanestedclassinside HelloWorldGUI2 : privatestaticclassButtonHandlerimplementsActionList ener{ publicvoidactionPerformed(ActionEvente){ System.exit(0); } } Thisclassimplementsthe ActionListener interface|arequirementforlistenerobjectsthat handleeventsfrombuttons.(Interfaceswereintroducedin Subsection5.7.1 .)Theeventhandlingmethodisnamed actionPerformed ,asspeciedbythe ActionListener interface.This methodcontainsthecodethatisexecutedwhentheuserclick sthebutton;inthiscase,the codeisacallto System.exit() ,whichwillterminatetheprogram. Thereisonemoreingredientthatisnecessarytogettheeven tfromthebuttontothe listenerobject:Thelistenerobjectmust register itselfwiththebuttonasaneventlistener. Thisisdonewiththestatement: okButton.addActionListener(listener); Thisstatementtells okButton thatwhentheuserclicksthebutton,theActionEventthatis generatedshouldbesentto listener .Withoutthisstatement,thebuttonhasnowayof knowingthatsomeotherobjectwouldliketolistenforevent sfromthebutton. Thisexampleshowsageneraltechniqueforprogrammingtheb ehaviorofaGUI:Write classesthatincludeevent-handlingmethods.Createobjec tsthatbelongtotheseclassesand registerthemaslistenerswiththeobjectsthatwillactual lydetectorgeneratetheevents.When aneventoccurs,thelistenerisnotied,andthecodethatyo uwroteinoneofitsevent-handling methodsisexecuted.Atrst,thismightseemlikeaveryroun daboutandcomplicatedwayto getthingsdone,butasyougainexperiencewithit,youwill ndthatitisveryrexibleand thatitgoestogetherverywellwithobjectorientedprogram ming.(Wewillreturntoevents

PAGE 243

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 229 andlistenersinmuchmoredetailin Section6.3 andlatersections,andIdonotexpectyouto completelyunderstandthematthistime.)6.2AppletsandHTMLA lthoughstand-aloneapplications areprobablymoreimportantthanappletsatthis (online) pointinthehistoryofJava,appletsarestillwidelyused.T heycandothingsonWebpages thatcan'teasilybedonewithothertechnologies.Itiseasy todistributeappletstousers:The userjusthastoopenaWebpage,andtheappletisthere,withn ospecialinstallationrequired (althoughtheusermusthaveanappropriateversionofJavai nstalledontheircomputer).And ofcourse,appletsarefun;nowthattheWebhasbecomesuchac ommonpartoflife,it'snice tobeabletoseeyourworkrunningonawebpage. Thegoodnewsisthatwritingappletsisnotmuchdierentfro mwritingstand-aloneapplications.Thestructureofanappletisessentiallythesamea sthestructureofthe JFrame sthat wereintroducedintheprevioussection,andeventsarehand ledinthesamewayinbothtypes ofprogram.So,mostofwhatyoulearnaboutapplicationsapp liestoapplets,and viceversa Ofcourse,onedierenceisthatanappletisdependentonaWe bpage,sotouseapplets eectively,youhavetolearnatleastalittleaboutcreatin gWebpages.Webpagesarewritten usingalanguagecalled HTML (HyperTextMarkupLanguage).In Subsection6.2.3 ,below, you'lllearnhowtouseHTMLtocreateWebpagesthatdisplaya pplets. 6.2.1JAppletThe JApplet class(inpackage javax.swing )canbeusedasabasisforwritingappletsinthe samewaythat JFrame isusedforwritingstand-aloneapplications.Thebasic JApplet class representsablankrectangulararea.Sinceanappletisnota stand-aloneapplication,thisarea mustappearonaWebpage,orinsomeotherenvironmentthatkn owshowtodisplayanapplet. Likea JFrame ,a JApplet containsacontentpane(andcancontainamenubar).Youcana dd contenttoanappleteitherbyaddingcontenttoitscontentp aneorbyreplacingthecontent panewithanothercomponent.Inmyexamples,Iwillgenerall ycreatea JPanel anduseitasa replacementfortheapplet'scontentpane. Tocreateanapplet,youwillwriteasubclassof JApplet .The JApplet classdenesseveral instancemethodsthatareuniquetoapplets.Thesemethodsa recalledbytheapplet'senvironmentatcertainpointsduringtheapplet's\lifecycle."Int he JApplet classitself,thesemethods donothing;youcanoverridethesemethodsinasubclass.The mostimportantofthesespecial appletmethodsis publicvoidinit() Anapplet's init() methodiscalledwhentheappletiscreated.Youcanusethe init() method asaplacewhereyoucansetupthephysicalstructureoftheap pletandtheeventhandling thatwilldetermineitsbehavior.(Youcanalsodosomeiniti alizationintheconstructorfor yourclass,buttherearecertainaspectsoftheapplet'senv ironmentthataresetupafterits constructoriscalledbutbeforethe init() methodiscalled,sothereareafewoperations thatwillworkinthe init() methodbutwillnotworkintheconstructor.)Theotherapple t life-cyclemethodsare start() stop() ,and destroy() .Iwillnotusethesemethodsforthe timebeingandwillnotdiscussthemhereexcepttomentionth at destroy() iscalledatthe endoftheapplet'slifetimeandcanbeusedasaplacetodoany necessarycleanup,suchas closinganywindowsthatwereopenedbytheapplet.

PAGE 244

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 230 Withthisinmind,wecanlookatourrstexampleofa JApplet .Itis,ofcourse,anapplet thatsays\HelloWorld!".Tomakeitalittlemoreinterestin g,Ihaveaddedabuttonthat changesthetextofthemessage,andastatevariable, currentMessage ,thatholdsthetextofthe currentmessage.Thisexampleisverysimilartothestand-a loneapplication HelloWorldGUI2 fromtheprevioussection.Itusesanevent-handlingclasst orespondwhentheuserclicksthe button,apaneltodisplaythemessage,andanotherpaneltha tservesasacontainerforthe messagepanelandthebutton.Thesecondpanelbecomestheco ntentpaneoftheapplet.Here isthesourcecodefortheapplet;again,youarenotexpected tounderstandallthedetailsat thistime: importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;/** *Asimpleappletthatcandisplaythemessages"HelloWorld"*and"GoodbyeWorld".Theappletcontainsabutton,andit*switchesfromonemessagetotheotherwhenthebuttonis*clicked.*/ publicclassHelloWorldAppletextendsJApplet{ privateStringcurrentMessage="HelloWorld!";//Current lydisplayedmessage. privateMessageDisplaydisplayPanel;//Thepanelwhereth emessageisdisplayed. privateclassMessageDisplayextendsJPanel{//Definesth edisplaypanel. publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);g.drawString(currentMessage,20,30); } }privateclassButtonHandlerimplementsActionListener{/ /Theeventlistener. publicvoidactionPerformed(ActionEvente){ if(currentMessage.equals("HelloWorld!")) currentMessage="GoodbyeWorld!"; else currentMessage="HelloWorld!"; displayPanel.repaint();//Paintdisplaypanelwithnewme ssage. } }/** *Theapplet'sinit()methodcreatesthebuttonanddisplayp aneland *addsthemtotheapplet,anditsetsupalistenertorespondt o *clicksonthebutton.*/ publicvoidinit(){ displayPanel=newMessageDisplay();JButtonchangeMessageButton=newJButton("ChangeMessag e"); ButtonHandlerlistener=newButtonHandler();changeMessageButton.addActionListener(listener);JPanelcontent=newJPanel();content.setLayout(newBorderLayout());

PAGE 245

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 231 content.add(displayPanel,BorderLayout.CENTER);content.add(changeMessageButton,BorderLayout.SOUTH) ; setContentPane(content); } } Youshouldcomparethisclasswith HelloWorldGUI2.java fromtheprevioussection.One subtledierencethatyouwillnoticeisthatthemembervari ablesandnestedclassesinthis examplearenon-static.Rememberthatanappletisanobject .Asingleclasscanbeusedto makeseveralapplets,andeachofthoseappletswillneedits owncopyoftheappletdata,so themembervariablesinwhichthedataisstoredmustbenon-s taticinstancevariables.Since thevariablesarenon-static,thetwonestedclasses,which usethosevariables,mustalsobe non-static.(Staticnestedclassescannotaccessnon-stat icmembervariablesinthecontaining class;see Subsection5.7.2 .)Rememberthebasicrulefordecidingwhethertomakeanest ed classstatic:Ifitneedsaccesstoanyinstancevariableori nstancemethodinthecontaining class,thenestedclassmustbenon-static;otherwise,itca nbedeclaredtobe static 6.2.2ReusingYourJPanelsBothappletsandframescanbeprogrammedinthesameway:Des igna JPanel ,anduseitto replacethedefaultcontentpaneintheappletorframe.This makesitveryeasytowritetwo versionsofaprogram,onewhichrunsasanappletandonewhic hrunsasaframe.Theideais tocreateasubclassof JPanel thatrepresentsthecontentpaneforyourprogram;alltheha rd programmingworkisdoneinthispanelclass.Anobjectofthi sclasscanthenbeusedasthe contentpaneeitherinaframeorinanapplet.Onlyaverysimp le main() programisneeded toshowyourpanelinaframe,andonlyaverysimpleappletcla ssisneededtoshowyourpanel inanapplet,soit'seasytomakebothversions. Asanexample,wecanrewrite HelloWorldApplet bywritingasubclassof JPanel .Thatclass canthenbereusedtomakeaframeinastandaloneapplication .Thisclassisverysimilarto HelloWorldApplet ,butnowtheinitializationisdoneinaconstructorinstead ofinan init() method: importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassHelloWorldPanelextendsJPanel{ privateStringcurrentMessage="HelloWorld!";//Current lydisplayedmessage. privateMessageDisplaydisplayPanel;//Thepanelwhereth emessageisdisplayed. privateclassMessageDisplayextendsJPanel{//Definesth edisplaypanel. publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);g.drawString(currentMessage,20,30); } }privateclassButtonHandlerimplementsActionListener{/ /Theeventlistener. publicvoidactionPerformed(ActionEvente){ if(currentMessage.equals("HelloWorld!")) currentMessage="GoodbyeWorld!";

PAGE 246

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 232 else currentMessage="HelloWorld!"; displayPanel.repaint();//Paintdisplaypanelwithnewme ssage. } }/** *Theconstructorcreatesthecomponentsthatwillbecontai nedinsidethis *panel,andthenaddsthosecomponentstothispanel.*/ publicHelloWorldPanel(){ displayPanel=newMessageDisplay();//Createthedisplay subpanel. JButtonchangeMessageButton=newJButton("ChangeMessag e");//Thebutton. ButtonHandlerlistener=newButtonHandler();changeMessageButton.addActionListener(listener);setLayout(newBorderLayout());//Setthelayoutmanagerf orthispanel. add(displayPanel,BorderLayout.CENTER);//Addthedispl aypanel. add(changeMessageButton,BorderLayout.SOUTH);//Addth ebutton. } } Oncethisclassexists,itcanbeusedinanapplet.Theapplet classonlyhastocreateanobject oftype HelloWorldPanel andusethatobjectasitscontentpane: importjavax.swing.JApplet;publicclassHelloWorldApplet2extendsJApplet{ publicvoidinit(){ HelloWorldPanelcontent=newHelloWorldPanel();setContentPane(content); } } Similarly,itseasytomakeaframethatusesanobjectoftype HelloWorldPanel asitscontent pane: importjavax.swing.JFrame;publicclassHelloWorldGUI3{ publicstaticvoidmain(String[]args){ JFramewindow=newJFrame("GUITest");HelloWorldPanelcontent=newHelloWorldPanel();window.setContentPane(content);window.setSize(250,100);window.setLocation(100,100);window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE); window.setVisible(true); } } Onenewfeatureofthisexampleistheline window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE);

PAGE 247

CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 233 Thissaysthatwhentheuserclosesthewindowbyclickingthe closeboxinthetitlebarofthe window,theprogramshouldbeterminated.Thisisnecessary becausenootherwayisprovided toendtheprogram.Withoutthisline,thedefaultcloseoper ationofthewindowwouldsimply hidethewindowwhentheuserclickstheclosebox,leavingth eprogramrunning.Thisbrings uponeofthedicultiesofreusingthesamepanelclassbothi nanappletandinaframe:There aresomethingsthatastand-aloneapplicationcandothatan appletcan'tdo.Terminating theprogramisoneofthosethings.Ifanappletcalls System.exit() ,ithasnoeectexceptto generateanerror. Nevertheless,inspiteofoccasionalminordiculties,man yoftheGUIexamplesinthis bookwillbewrittenassubclassesof JPanel thatcanbeusedeitherinanappletorinaframe. 6.2.3BasicHTMLBeforeyoucanactuallyuseanappletthatyouhavewritten,y ouneedtocreateaWebpage onwhichtoplacetheapplet.Suchpagesarethemselveswritt eninalanguagecalled HTML (HyperTextMarkupLanguage).AnHTMLdocumentdescribesth econtentsofapage.AWeb browserinterpretstheHTMLcodetodeterminewhattodispla yonthepage.TheHTMLcode doesn'tlookmuchliketheresultingpagethatappearsinthe browser.TheHTMLdocument doescontainallthetextthatappearsonthepage,butthatte xtis\markedup"withcommands thatdeterminethestructureandappearanceofthetextandd eterminewhatwillappearon thepageinadditiontothetext. HTMLhasbecomearathercomplicatedlanguage.Inthissecti on,Iwillcoverjustthe mostbasicaspectsofthelanguage.Youcaneasilyndmorein formationontheWeb,ifyou wanttolearnmore.AlthoughtherearemanyWeb-authoringpr ogramsthatmakeitpossible tocreateWebpageswithouteverlookingattheunderlyingHT MLcode,itispossibletowrite anHTMLpageusinganordinarytexteditor,typinginallthem ark-upcommandsbyhand, anditisworthwhiletolearnhowtocreateatleastsimplepag esinthisway. ThereisastrictsyntaxforHTMLdocuments(althoughinprac ticeWebbrowserswilldo theirbesttodisplayapageevenifitdoesnotfollowthesynt axstrictly).Leavingoutoptional features,anHTMLdocumenthastheform: h document-title i h document-content i The h document-title i istextthatwillappearinthetitlebaroftheWebbrowserwin dowwhen thepageisdisplayed.The h document-content i iswhatisdisplayedonthepageitself.Therest ofthissectiondescribessomeofthethingsthatcangointot he h document-content i sectionof anHTMLdocument Themark-upcommandsusedbyHTMLarecalled tags .Examplesinclude and inthedocumentoutlinegivenabove.AnHTMLtagtakesthefor m < h tag-name ih optional-modifiers i > <br /> <br /> PAGE 248<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 234 wherethe h tag-name i isawordthatspeciesthecommand,andthe h optional-modiers i ,if present,areusedtoprovideadditionalinformationforthe command(muchlikeparametersin subroutines).Amodiertakestheform h modifier-name i = h value i Usually,the h value i isenclosedinquotes,anditmustbeifitismorethanoneword longorif itcontainscertainspecialcharacters.Thereareafewmodi erswhichhavenovalue,inwhich caseonlythenameofthemodierispresent.HTMLiscaseinse nsitive,whichmeansthat youcanuseuppercaseandlowercaselettersinterchangeabl yintagsandmodiers.(However, lowercaseisgenerallyusedbecauseXHTML,asuccessorlang uagetoHTML,requireslower case.) Asimpleexampleofatagis <hr> ,whichdrawsaline|alsocalleda\horizontalrule"| acrossthepage.The hr tagcantakeseveralpossiblemodierssuchas width and align .For example,ahorizontallinethatextendshalfwayacrossthep agecouldbegeneratedwiththe tag: <hrwidth="50%"> The width hereisspeciedas 50% oftheavailablespace,meaningalinethatextendshalfway acrossthepage.Thewidthcouldalsobegivenasaxednumber ofpixels. Manytagsrequirematchingclosingtags,whichtaketheform </ h tag-name i > Forexample,the <html> tagatthebeginningofanHTMLdocumentmustbematched byaclosing </html> tagattheendofthedocument.Asanotherexample,thetag <pre> mustalwayshaveamatchingclosingtag </pre> laterinthedocument.Anopening/closing tagpairappliestoeverythingthatcomesbetweentheopenin gtagandtheclosingtag.The <pre> tagtellsaWebbrowsertodisplayeverythingbetweenthe <pre> andthe </pre> justas itisformattedintheoriginalHTMLsourcecode,includinga llthespacesandcarriagereturns. (Buttagsbetween <pre> and </pre> arestillinterpretedbythebrowser.)\Pre"standsfor preformattedtext.Allofthesampleprogramsintheon-line versionofthisbookareformatted usingthe <pre> command. Itisimportantforyoutounderstandthatwhenyoudon'tuse <pre> ,thecomputerwill completelyignoretheformattingofthetextintheHTMLsour cecode.Theonlythingitpays attentiontoisthetags.Fiveblanklinesinthesourcecodeh avenomoreeectthanoneblank lineorevenasingleblankspace.Outsideof <pre> ,ifyouwanttoforceanewlineonthe Webpage,youcanusethetag <br> ,whichstandsfor\break".Forexample,Imightgivemy addressas: DavidEck<br>DepartmentofMathematicsandComputerScience<br>HobartandWilliamSmithColleges<br>Geneva,NY14456<br> Ifyouwantextraverticalspaceinyourwebpage,youcanuses everal <br> 'sinarow. Similarly,youneedatagtoindicatehowthetextshouldbebr okenupintoparagraphs. Thisisdonewiththe <p> tag,whichshouldbeplacedatthebeginningofeveryparagra ph. The <p> taghasamatching </p> ,whichshouldbeplacedattheendofeachparagraph.The closing </p> istechnicallyoptional,butitisconsideredgoodformtous eit.Ifyouwantallthe linesoftheparagraphtobeshovedovertotheright,youcanu se <palign=right> insteadof <br /> <br /> PAGE 249<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 235 <p> .(Thisismostlyusefulwhenusedwithoneshortline,orwhen usedwith <br> tomake severalshortlines.)Youcanalsouse <palign=center> forcenteredlines. Bytheway,iftagslike <p> and <hr> havespecialmeaningsinHTML,youmightwonder howonecangetthemtoappearliterallyonawebpage.Togetce rtainspecialcharactersto appearonthepage,youhavetousean entityname intheHTMLsourcecode.Theentity namefor < is < ,andtheentitynamefor > is > .Entitynamesbeginwith & andendwith asemicolon.Thecharacter & isitselfaspecialcharacterwhoseentitynameis & .There arealsoentitynamesfornonstandardcharacterssuchasana ccented\e",whichhastheentity name é Thereareseveralusefultagsthatchangetheappearanceoft ext.Forexample,togetitalic text,enclosethetextbetween <i> and </i> .Forexample, <i>IntroductiontoProgrammingusingJava</i> inanHTMLdocumentgives IntroductiontoProgrammingusingJava initalicswhenthe documentisdisplayedasaWebpage.Similarly,thetags <b> <u> ,and <tt> canbeused for bold ,underlined ,and typewriter-style (\monospace")text. Aheadline,withverylargetext,canbemadebyplacingtheth etextbetween <h1> and </h1> .Headlineswithsmallertextcanbemadeusing <h2> or <h3> insteadof <h1> .Note thattheseheadlinetagsstandontheirown;theyarenotused insideparagraphs.Youcanadd themodier align=center tocentertheheadline,andyoucanincludebreaktags( <br> )ina headlinetobreakitupintomultiplelines.Forexample,the followingHTMLcodewillproduce amedium{sized,centered,two-lineheadline: <h2align=center>Chapter6:<br>IntroductiontoGUIProgr amming</h2> ThemostdistinctivefeatureofHTMListhatdocumentscanco ntain links tootherdocuments.Theusercanfollowlinksfrompagetopageandinthepr ocessvisitpagesfromallover theInternet. The <a> tagisusedtocreatealink.Thetextbetweenthe <a> anditsmatching </a> appearsonthepageasthetextofthelink;theusercanfollow thelinkbyclickingonthis text.The <a> tagusesthemodier href tosaywhichdocumentthelinkshouldconnectto. Thevaluefor href mustbea URL (UniformResourceLocator).AURLisacodedsetof instructionsforndingadocumentontheInternet.Forexam ple,theURLformyown\home page"is http://math.hws.edu/eck/ Tomakealinktothispage,IwouldusetheHTMLsourcecode <ahref="http://math.hws.edu/eck/">David'sHomePage</ a> ThebestplacetondURLsisonexistingWebpages.Webbrowse rsdisplaytheURLforthe pageyouarecurrentlyviewing,andtheycandisplaytheURLo falinkifyoupointtothelink withthemouse. IfyouarewritinganHTMLdocumentandyouwanttomakealinkt oanotherdocument thatisinthesamedirectory,youcanusea relativeURL .TherelativeURLconsistsofjustthe nameofthele.Forexample,tocreatealinktoalenamed\s1 .html"inthesamedirectory astheHTMLdocumentthatyouarewriting,youcoulduse <ahref="s1.html">Section1</a> <br /> <br /> PAGE 250<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 236 TherearealsorelativeURLsforlinkingtolesthatareinot herdirectories.Usingrelative URLsisagoodidea,sinceifyouusethem,youcanmoveawholec ollectionofleswithout changinganyofthelinksbetweenthem(aslongasyoudon'tch angetherelativelocationsof theles). WhenyoutypeaURLintoaWebbrowser,youcanomitthe\http:/ /"atthebeginningof theURL.However,inan <a> taginanHTMLdocument,the\http://"canonlybeomittedif theURLisarelativeURL.ForanormalURL,itisrequired. YoucanaddimagestoaWebpagewiththe <img> tag.(Thisisatagthathasnomatching closingtag.)Theactualimagemustbestoredinaseparatel efromtheHTMLdocument. The <img> taghasarequiredmodier,named src ,tospecifytheURLoftheimagele.For mostbrowsers,theimageshouldbeinoneoftheformatsPNG(w ithalenameendingin \.png"),JPEG(withalenameendingin\.jpeg"or\.jpg"),o rGIF(withalenameending in\.gif").Usually,theimageisstoredinthesameplaceast heHTMLdocument,andarelative URL|thatis,justthenameoftheimagele|isusedtospecify theimagele. The <img> tagalsohasseveraloptionalmodiers.It'sagoodideatoal waysincludethe height and width modiers,whichspecifythesizeoftheimageinpixels.Some browsers handleimagesbetteriftheyknowinadvancehowbigtheyare. The align modiercanbe usedtoaecttheplacementoftheimage:\align=right"will shovetheimagetotherightedge ofthepage,andthetextonthepagewillrowaroundtheimage; \align=left"workssimilarly. (Unfortunately,\align=center"doesn'thavethemeaningy ouwouldexpect.Browserstreat imagesasiftheyarejustbigcharacters.Imagescanoccurin sideparagraphs,links,and headings,forexample.Alignmentvaluesof center top ,and bottom areusedtospecifyhow theimageshouldlineupwithothercharactersinalineoftex t:Shouldthebaselineofthetext beatthecenter,thetop,orthebottomoftheimage?Alignmen tvaluesof right and left wereaddedtoHTMLlater,buttheyarethemostusefulvalues. Ifyouwantanimagecentered onthepage,putitinsidea <palign=center> tag.) Forexample,hereisHTMLcodethatwillplaceanimagefroma lenamedgure1.pngon thepage. <imgsrc="figure1.png"align=rightheight=150width=100 > Theimageis100pixelswideand150pixelshigh,anditwillap pearontherightedgeofthe page.6.2.4AppletsonWebPagesThemainpointofthiswholediscussionofHTMListolearnhow touseappletsontheWeb. The <applet> tagcanbeusedtoaddaJavaapplettoaWebpage.Thistagmusth avea matching </applet> .Arequiredmodiernamed code givesthenameofthecompiledclass lethatcontainstheappletclass.Themodiers height and width arerequiredtospecifythe sizeoftheapplet,inpixels.Ifyouwanttheapplettobecent eredonthepage,youcanput theappletinaparagraphwith center alignmentSo,anapplettagtodisplayanappletnamed HelloWorldApplet centeredonaWebpagewouldlooklikethis: <palign=center><appletcode="HelloWorldApplet.class"height=100width =250> </applet></p> <br /> <br /> PAGE 251<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 237 Thisassumesthatthele HelloWorldApplet.class islocatedinthesamedirectorywith theHTMLdocument.Ifthisisnotthecase,youcanuseanother modier, codebase ,togive theURLofthedirectorythatcontainstheclassle.Thevalu eof code itselfisalwaysjusta class,notaURL. Iftheappletusesotherclassesinadditiontotheappletcla ssitself,thenthoseclassles mustbeinthesamedirectoryastheappletclass(alwaysassu mingthatyourclassesareallin the\defaultpackage";see Subsection2.6.4 ).Ifanappletrequiresmorethanoneortwoclass les,it'sagoodideatocollectalltheclasslesintoasing lejarle.Jarlesare\archiveles" whichholdanumberofsmallerles.Ifyourclasslesareina jararchive,thenyouhaveto specifythenameofthejarleinan archive modierinthe <applet> tag,asin <appletcode="HelloWorldApplet.class"archive="HelloW orld.jar"height=50... Iwillhavemoretosayaboutcreatingandusingjarlesatthe endofthischapter. Appletscanuse appletparameters tocustomizetheirbehavior.Appletparametersare speciedbyusing <param> tags,whichcanonlyoccurbetweenan <applet> tagandtheclosing </applet> .The param taghasrequiredmodiersnamed name and value ,andittakesthe form <paramname=" h param-name i "value=" h param-value i "> Theparametersareavailabletotheappletwhenitruns.Anap pletcanusethepredened method getParameter() tocheckforparametersspeciedin param tags.The getParameter() methodhasthefollowinginterface: StringgetParameter(StringparamName) Theparameter paramName correspondstothe h param-name i ina param tag.Ifthespecied paramName actuallyoccursinoneofthe param tags,then getParameter(paramName) returns theassociated h param-value i .Ifthespecied paramName doesnotoccurinany param tag,then getParameter(paramName) returnsthevalue null .Parameternamesarecase-sensitive,soyou cannotuse\size"inthe param tagandaskfor\Size"in getParameter .The getParameter() methodisoftencalledintheapplet's init() method.Itwillnotworkcorrectlyintheapplet's constructor,sinceitdependsoninformationabouttheappl et'senvironmentthatisnotavailable whentheconstructoriscalled. Hereisanexampleofan applet tagwithseveral params : <appletcode="ShowMessage.class"width=200height=50> <paramname="message"value="GoodbyeWorld!"><paramname="font"value="Serif"><paramname="size"value="36"> </applet> The ShowMessage appletwouldpresumablyreadtheseparametersinits init() method, whichcouldgosomethinglikethis: Stringmessage;//Instancevariable:messagetobedisplay ed. StringfontName;//Instancevariable:fonttousefordispl ay. intfontSize;//Instancevariable:sizeofthedisplayfont publicvoidinit(){ Stringvalue;value=getParameter("message");//Getmessageparam,ifa ny. if(value==null) <br /> <br /> PAGE 252<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 238 message="HelloWorld!";//Defaultvalue,ifnoparamispre sent. else message=value;//ValuefromPARAMtag. value=getParameter("font");if(value==null) fontName="SansSerif";//Defaultvalue,ifnoparamispres ent. else fontName=value; value=getParameter("size");try{ fontSize=Integer.parseInt(value);//Convertstrington umber. }catch(NumberFormatExceptione){ fontSize=20;//Defaultvalue,ifnoparamispresent,orif }//theparametervalueisnotalegalinteger. ... Elsewhereintheapplet,theinstancevariables message fontName ,and fontSize wouldbe usedtodeterminethemessagedisplayedbytheappletandthe appearanceofthatmessage. Notethatthevaluereturnedby getParameter() isalwaysa String .Ifthe param represents anumericalvalue,thestringmustbeconvertedintoanumber ,asisdonehereforthe size parameter.6.3GraphicsandPaintingE verthingyouseeonacomputerscreen hastobedrawnthere,eventhetext.The (online) JavaAPIincludesarangeofclassesandmethodsthataredevo tedtodrawing.Inthissection, I'lllookatsomeofthemostbasicofthese. ThephysicalstructureofaGUIisbuiltofcomponents.Thete rm component referstoa visualelementinaGUI,includingbuttons,menus,text-inp utboxes,scrollbars,checkboxes, andsoon.InJava,GUIcomponentsarerepresentedbyobjects belongingtosubclassesofthe class java.awt.Component .MostcomponentsintheSwingGUI|althoughnottop-levelco mponentslikeJAppletandJFrame|belongtosubclassesofthe class javax.swing.JComponent whichisitselfasubclassof java.awt.Component .Everycomponentisresponsiblefordrawing itself.Ifyouwanttouseastandardcomponent,youonlyhave toaddittoyourappletorframe. Youdon'thavetoworryaboutpaintingitonthescreen.Thatw illhappenautomatically,since italreadyknowshowtodrawitself. Sometimes,however,youdowanttodrawonacomponent.Youwi llhavetodothis wheneveryouwanttodisplaysomethingthatisnotincludeda mongthestandard,pre-dened componentclasses.Whenyouwanttodothis,youhavetodene yourowncomponentclass andprovideamethodinthatclassfordrawingthecomponent. Iwillalwaysuseasubclass of JPanel whenIneedadrawingsurfaceofthiskind,asIdidforthe MessageDisplay classin theexample HelloWorldApplet.java intheprevioussection.AJPanel,likeanyJComponent, drawsitscontentinthemethod publicvoidpaintComponent(Graphicsg) Tocreateadrawingsurface,youshoulddeneasubclassof JPanel andprovideacustom paintComponent() method.Createanobjectbelongingtothisclassanduseitin yourapplet <br /> <br /> PAGE 253<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 239 orframe.Whenthetimecomesforyourcomponenttobedrawnon thescreen,thesystem willcallits paintComponent() todothedrawing.Thatis,thecodethatyouputintothe paintComponent() methodwillbeexecutedwheneverthepanelneedstobedrawno nthe screen;bywritingthismethod,youdeterminethepictureth atwillbedisplayedinthepanel. Notethatthe paintComponent() methodhasaparameteroftype Graphics .The Graphics objectwillbeprovidedbythesystemwhenitcallsyourmetho d.Youneedthisobjectto dotheactualdrawing.TodoanydrawingatallinJava,younee da graphicscontext .A graphicscontextisanobjectbelongingtotheclass java.awt.Graphics .Instancemethods areprovidedinthisclassfordrawingshapes,text,andimag es.Anygiven Graphics object candrawtoonlyonelocation.Inthischapter,thatlocation willalwaysbeaGUIcomponent belongingtosomesubclassof JPanel .The Graphics classisanabstractclass,whichmeans thatitisimpossibletocreateagraphicscontextdirectly, withaconstructor.Thereareactually twowaystogetagraphicscontextfordrawingonacomponent: Firstofall,ofcourse,when the paintComponent() methodofacomponentiscalledbythesystem,theparametert othat methodisagraphicscontextfordrawingonthecomponent.Se cond,everycomponenthas aninstancemethodcalled getGraphics() .Thismethodisafunctionthatreturnsagraphics contextthatcanbeusedfordrawingonthecomponentoutside its paintComponent() method. Theociallineisthatyoushould not dothis,andIwillavoiditforthemostpart.ButIhave founditconvenienttouse getGraphics() inafewcases. The paintComponent() methodinthe JPanel classsimplyllsthepanelwiththepanel's backgroundcolor.Whendeningasubclassof JPanel foruseasadrawingsurface,youwill almostalwayswanttollthepanelwiththebackgroundcolor beforedrawingothercontent ontothepanel(althoughitisnotnecessarytodothisifthed rawingcommandsinthemethod coverthebackgroundofthecomponentcompletely.)Thisist raditionallydonewithacallto super.paintComponent(g) ,somost paintComponent() methodsthatyouwritewillhavethe form: publicvoidpaintComponent(g){ super.paintComponent(g);...//Drawthecontentofthecomponent. } Mostcomponentsdo,infact,doalldrawingoperationsinthe ir paintComponent() methods. Whathappensif,inthemiddleofsomeothermethod,youreali zethatthecontentofthe componentneedstobechanged?Youshould not call paintComponent() directlytomakethe change;thismethodismeanttobecalledonlybythesystem.I nstead,youhavetoinform thesystemthatthecomponentneedstoberedrawn,andletthe systemdoitsjobbycalling paintComponent() .Youdothisbycallingthecomponent's repaint() method.Themethod publicvoidrepaint(); isdenedinthe Component class,andsocanbeusedwithanycomponent.Youshouldcall repaint() toinformthesystemthatthecomponentneedstoberedrawn.T he repaint() methodreturnsimmediately,withoutdoinganypaintingits elf.Thesystemwillcallthecomponent's paintComponent() method later ,assoonasitgetsachancetodoso,afterprocessing otherpendingeventsifthereareany. Notethatthesystemcanalsocall paintComponent() forotherreasons.Itiscalledwhen thecomponentrstappearsonthescreen.Itwillalsobecall edifthecomponentisresizedorif itiscoveredupbyanotherwindowandthenuncovered.Thesys temdoesnotsaveacopyofthe <br /> <br /> PAGE 254<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 240 component'scontentswhenitiscovered.Whenitisuncovere d,thecomponentisresponsible forredrawingitself.(Asyouwillsee,someofourearlyexam pleswillnotbeabletodothis correctly.) Thismeansthat,toworkproperly,the paintComponent() methodmustbesmartenough tocorrectlyredrawthecomponentatanytime.Tomakethispo ssible,aprogramshouldstore dataaboutthestateofthecomponentinitsinstancevariabl es.Thesevariablesshouldcontain alltheinformationnecessarytoredrawthecomponentcompl etely.The paintComponent() methodshouldusethedatainthesevariablestodecidewhatt odraw.Whentheprogram wantstochangethecontentofthecomponent,itshouldnotsi mplydrawthenewcontent. Itshouldchangethevaluesoftherelevantvariablesandcal l repaint() .Whenthesystem calls paintComponent() ,thatmethodwillusethenewvaluesofthevariablesandwill draw thecomponentwiththedesiredmodications.Thismightsee maroundaboutwayofdoing things.Whynotjustdrawthemodicationsdirectly?Therea reatleasttworeasons.First ofall,itreallydoesturnouttobeeasiertogetthingsright ifalldrawingisdoneinone method.Second,evenifyoudidmakemodicationsdirectly, youwouldstillhavetomakethe paintComponent() methodawareoftheminsomewaysothatitwillbeableto redraw the componentcorrectlyondemand. Youwillseehowallthisworksinpracticeasweworkthroughe xamplesintherestofthis chapter.Fornow,wewillspendtherestofthissectionlooki ngathowtogetsomeactual drawingdone.6.3.1CoordinatesThescreenofacomputerisagridoflittlesquarescalled pixels .Thecolorofeachpixelcanbe setindividually,anddrawingonthescreenjustmeanssetti ngthecolorsofindividualpixels. Agraphicscontextdrawsinarectanglemadeupofpixels.Apo sitionintherectangle isspeciedbyapairofintegercoordinates, (x,y) .Theupperleftcornerhascoordinates (0,0) .The x coordinateincreasesfromlefttoright,andthe y coordinateincreasesfromtop tobottom.Theillustrationshowsa16-by-10pixelcomponen t(withverylargepixels).Asmall line,rectangle,andovalareshownastheywouldbedrawnbyc oloringindividualpixels.(Note that,properlyspeaking,thecoordinatesdon'tbelongtoth epixelsbuttothegridlinesbetween them.) Foranycomponent,youcanndoutthesizeoftherectangleth atitoccupiesbycalling theinstancemethods getWidth() and getHeight() ,whichreturnthenumberofpixelsinthe horizontalandverticaldirections,respectively.Ingene ral,it'snotagoodideatoassumethat youknowthesizeofacomponent,sincethesizeisoftensetby alayoutmanagerandcan <br /> <br /> PAGE 255<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 241 evenchangeifthecomponentisinawindowandthatwindowisr esizedbytheuser.This meansthatit'sgoodformtocheckthesizeofacomponentbefo redoinganydrawingonthat component.Forexample,youcanusea paintComponent() methodthatlookslike: publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);intwidth=getWidth();//Findoutthewidthofthiscomponen t. intheight=getHeight();//Findoutitsheight....//Drawthecontentofthecomponent. } Ofcourse,yourdrawingcommandswillhavetotakethesizein toaccount.Thatis,they willhavetouse (x,y) coordinatesthatarecalculatedbasedontheactualheighta ndwidthof thecomponent.6.3.2ColorsYouwillprobablywanttousesomecolorwhenyoudraw.Javais designedtoworkwith the RGBcolorsystem .AnRGBcolorisspeciedbythreenumbersthatgivethelevel ofred,green,andblue,respectively,inthecolor.Acolori nJavaisanobjectoftheclass, java.awt.Color .Youcanconstructanewcolorbyspecifyingitsred,blue,an dgreencomponents.Forexample, ColormyColor=newColor(r,g,b); Therearetwoconstructorsthatyoucancallinthisway.Inth eonethatIalmostalwaysuse, r g ,and b areintegersintherange0to255.Intheother,theyarenumbersoftype roat intherange0.0Fto1.0F.(Recallthataliteraloftype roat iswritten withan\F"todistinguishitfroma double number.)Often,youcanavoidconstructing newcolorsaltogether,sincethe Color classdenesseveralnamedconstantsrepresentingcommoncolors: Color.WHITE Color.BLACK Color.RED Color.GREEN Color.BLUE Color.CYAN Color.MAGENTA Color.YELLOW Color.PINK Color.ORANGE Color.LIGHT GRAY Color.GRAY and Color.DARK GRAY .(Thereareolder,alternativenamesfortheseconstantsth atuselower caseratherthanuppercaseconstants,suchas Color.red insteadof Color.RED ,buttheupper caseversionsarepreferredbecausetheyfollowtheconvent ionthatconstantnamesshouldbe uppercase.) AnalternativetoRGBisthe HSBcolorsystem .IntheHSBsystem,acolorisspeciedby threenumberscalledthe hue ,the saturation ,andthe brightness .Thehueisthebasiccolor, rangingfromredthroughorangethroughalltheothercolors oftherainbow.Thebrightnessis prettymuchwhatitsoundslike.Afullysaturatedcolorisap urecolortone.Decreasingthe saturationislikemixingwhiteorgraypaintintothepureco lor.InJava,thehue,saturation andbrightnessarealwaysspeciedbyvaluesoftype roat intherangefrom0.0Fto1.0F.The Color classhasa static memberfunctionnamed getHSBColor forcreatingHSBcolors.To createthecolorwithHSBvaluesgivenby h s ,and b ,youcansay: ColormyColor=Color.getHSBColor(h,s,b); Forexample,tomakeacolorwitharandomhuethatisasbright andassaturatedaspossible, youcoulduse: ColorrandomColor=Color.getHSBColor((float)Math.rand om(),1.0F,1.0F); <br /> <br /> PAGE 256<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 242 Thetypecastisnecessarybecausethevaluereturnedby Math.random() isoftype double and Color.getHSBColor() requiresvaluesoftype roat .(Bytheway,youmightaskwhy RGBcolorsarecreatedusingaconstructorwhileHSBcolorsa recreatedusingastaticmember function.Theproblemisthatwewouldneedtwodierentcons tructors,bothofthemwith threeparametersoftype roat .Unfortunately,thisisimpossible.Youcanhavetwoconstr uctors onlyifthenumberofparametersortheparametertypesdier .) TheRGBsystemandtheHSBsystemarejustdierentwaysofdes cribingthesamesetof colors.Itispossibletotranslatebetweenonesystemandth eother.Thebestwaytounderstand thecolorsystemsistoexperimentwiththem.Intheon-linev ersionofthissection,youwill ndanappletthatyoucanusetoexperimentwithRGBandHSBco lors. Oneofthepropertiesofa Graphics objectisthecurrentdrawingcolor,whichisusedfor alldrawingofshapesandtext.If g isagraphicscontext,youcanchangethecurrentdrawing colorfor g usingthemethod g.setColor(c) ,where c isa Color .Forexample,ifyouwant todrawingreen,youwouldjustsay g.setColor(Color.GREEN) beforedoingthedrawing. Thegraphicscontextcontinuestousethecoloruntilyouexp licitlychangeitwithanother setColor() command.Ifyouwanttoknowwhatthecurrentdrawingcoloris ,youcancallthe function g.getColor() ,whichreturnsanobjectoftype Color .Thiscanbeusefulifyouwant tochangetoanotherdrawingcolortemporarilyandthenrest orethepreviousdrawingcolor. Everycomponenthasanassociated foregroundcolor and backgroundcolor .Generally, thecomponentislledwiththebackgroundcolorbeforeanyt hingelseisdrawn(althoughsome componentsare\transparent,"meaningthatthebackground colorisignored).Whenanew graphicscontextiscreatedforacomponent,thecurrentdra wingcolorissettotheforeground color.Notethattheforegroundcolorandbackgroundcolora repropertiesofthecomponent, notofagraphicscontext. Theforegroundandbackgroundcolorscanbesetbyinstancem ethods setForeground(c) and setBackground(c) ,whicharedenedinthe Component classandthereforeareavailable forusewithanycomponent.Thiscanbeusefulevenforstanda rdcomponents,ifyouwant themtousecolorsthataredierentfromthedefaults.6.3.3FontsA font representsaparticularsizeandstyleoftext.Thesamechar acterwillappeardierent indierentfonts.InJava,afontischaracterizedbyafontn ame,astyle,andasize.The availablefontnamesaresystemdependent,butyoucanalway susethefollowingfourstringsas fontnames:\Serif",\SansSerif",\Monospaced",and\Dial og".(A\serif"isalittledecoration onacharacter,suchasashorthorizontallineatthebottomo ftheletteri.\SansSerif"means \withoutserifs."\Monospaced"meansthatallthecharacte rsinthefonthavethesamewidth. The\Dialog"fontistheonethatistypicallyusedindialogb oxes.) Thestyleofafontisspeciedusingnamedconstantsthatare denedinthe Font class. Youcanspecifythestyleasoneofthefourvalues: Font.PLAIN Font.ITALIC Font.BOLD ,or Font.BOLD+Font.ITALIC Thesizeofafontisaninteger.Sizetypicallyrangesfromab out10to36,althoughlarger sizescanalsobeused.Thesizeofafontisusuallyaboutequa ltotheheightofthelargest charactersinthefont,inpixels,butthisisnotanexactrul e.Thesizeofthedefaultfontis12. <br /> <br /> PAGE 257<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 243 Javausestheclassnamed java.awt.Font forrepresentingfonts.Youcanconstructanew fontbyspecifyingitsfontname,style,andsizeinaconstru ctor: FontplainFont=newFont("Serif",Font.PLAIN,12);FontbigBoldFont=newFont("SansSerif",Font.BOLD,24); Everygraphicscontexthasacurrentfont,whichisusedford rawingtext.Youcanchange thecurrentfontwiththe setFont() method.Forexample,if g isagraphicscontextand bigBoldFont isafont,thenthecommand g.setFont(bigBoldFont) willsetthecurrentfont of g to bigBoldFont .Thenewfontwillbeusedforanytextthatisdrawn after the setFont() commandisgiven.Youcanndoutthecurrentfontof g bycallingthemethod g.getFont() whichreturnsanobjectoftype Font Everycomponenthasanassociatedfont.Itcanbesetwiththe instancemethod setFont(font) ,whichisdenedinthe Component class.Whenagraphicscontextiscreatedfordrawingonacomponent,thegraphiccontext'scurre ntfontissetequaltothefontof thecomponent.6.3.4ShapesThe Graphics classincludesalargenumberofinstancemethodsfordrawin gvariousshapes, suchaslines,rectangles,andovals.Theshapesarespecie dusingthe (x,y) coordinatesystem describedabove.Theyaredrawninthecurrentdrawingcolor ofthegraphicscontext.The currentdrawingcolorissettotheforegroundcoloroftheco mponentwhenthegraphicscontext iscreated,butitcanbechangedatanytimeusingthe setColor() method. Hereisalistofsomeofthemostimportantdrawingmethods.W ithallthesecommands, anydrawingthatisdoneoutsidetheboundariesofthecompon entisignored.Notethatall thesemethodsareinthe Graphics class,sotheyallmustbecalledthroughanobjectoftype Graphics drawString(Stringstr,intx,inty) |Drawsthetextgivenbythestring str Thestringisdrawnusingthecurrentcolorandfontofthegra phicscontext. x species thepositionoftheleftendofthestring. y isthey-coordinateofthebaselineofthe string.Thebaselineisahorizontallineonwhichthecharac tersrest.Somepartsofthe characters,suchasthetailonayorg,extendbelowthebasel ine. drawLine(intx1,inty1,intx2,inty2) |Drawsalinefromthepoint (x1,y1) tothepoint (x2,y2) .Thelineisdrawnasifwithapenthathangsonepixeltothe rightandonepixeldownfromthe (x,y) pointwherethepenislocated.Forexample,if g referstoanobjectoftype Graphics ,thenthecommand g.drawLine(x,y,x,y) ,which correspondstoputtingthependownatapoint,colorsthesin glepixelwithupperleft corneratthepoint (x,y) drawRect(intx,inty,intwidth,intheight) |Drawstheoutlineofarectangle. Theupperleftcornerisat (x,y) ,andthewidthandheightoftherectangleareas specied.If width equals height ,thentherectangleisasquare.Ifthe width orthe height isnegative,thennothingisdrawn.Therectangleisdrawnwi ththesamepen thatisusedfor drawLine() .Thismeansthattheactualwidthoftherectangleasdrawn is width+1 ,andsimilarlyfortheheight.Thereisanextrapixelalongt herightedgeand thebottomedge.Forexample,ifyouwanttodrawarectanglea roundtheedgesofthe component,youcansay\ g.drawRect(0,0,getWidth()-1,getHeight()-1); ",where g isagraphicscontextforthecomponent.Ifyouuse\ g.drawRect(0,0,getWidth(), <br /> <br /> PAGE 258<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 244 getHeight()); ",thentherightandbottomedgesoftherectanglewillbedra wn outside thecomponent. drawOval(intx,inty,intwidth,intheight) |Drawstheoutlineofanoval. Theovalisonethatjusttsinsidetherectanglespeciedby x y width ,and height .If width equals height ,theovalisacircle. drawRoundRect(intx,inty,intwidth,intheight,intxdiam ,intydiam) | Drawstheoutlineofarectanglewithroundedcorners.Theba sicrectangleisspeciedby x y width ,and height ,butthecornersarerounded.Thedegreeofroundingisgiven by xdiam and ydiam .Thecornersarearcsofanellipsewithhorizontaldiameter xdiam and verticaldiameter ydiam .Atypicalvaluefor xdiam and ydiam is16,butthevalueused shouldreallydependonhowbigtherectangleis. draw3DRect(intx,inty,intwidth,intheight,booleanrais ed) |Drawsthe outlineofarectanglethatissupposedtohaveathree-dimen sionaleect,asifitisraised fromthescreenorpushedintothescreen.Thebasicrectangl eisspeciedby x y width and height .The raised parametertellswhethertherectangleseemstoberaisedfro mthe screenorpushedintoit.The3Deectisachievedbyusingbri ghteranddarkerversions ofthedrawingcolorfordierentedgesoftherectangle.The documentationrecommends settingthedrawingcolorequaltothebackgroundcolorbefo reusingthismethod.The eectwon'tworkwellforsomecolors. drawArc(intx,inty,intwidth,intheight,intstartAngle, intarcAngle) | Drawspartoftheovalthatjusttsinsidetherectanglespec iedby x y width ,and height .Thepartdrawnisanarcthatextends arcAngle degreesfromastartingangle at startAngle degrees.Anglesaremeasuredwith0degreesatthe3o'clockp osition(the positivedirectionofthehorizontalaxis).Positiveangle saremeasuredcounterclockwise fromzero,andnegativeanglesaremeasuredclockwise.Toge tanarcofacircle,make surethat width isequalto height fillRect(intx,inty,intwidth,intheight) |Drawsalled-inrectangle.This llsintheinterioroftherectanglethatwouldbedrawnby drawRect(x,y,width,height) Theextrapixelalongthebottomandrightedgesisnotinclud ed.The width and height parametersgivetheexactwidthandheightoftherectangle. Forexample,ifyou wantedtollintheentirecomponent,youcouldsay\ g.fillRect(0,0,getWidth(), getHeight()); fillOval(intx,inty,intwidth,intheight) |Drawsalled-inoval. fillRoundRect(intx,inty,intwidth,intheight,intxdiam ,intydiam) | Drawsalled-inroundedrectangle. fill3DRect(intx,inty,intwidth,intheight,booleanrais ed) |Drawsa lled-inthree-dimensionalrectangle. fillArc(intx,inty,intwidth,intheight,intstartAngle, intarcAngle) | Drawalled-inarc.Thislookslikeawedgeofpie,whosecrus tisthearcthatwouldbe drawnbythe drawArc method. 6.3.5Graphics2DAlldrawinginJavaisdonethroughanobjectoftype Graphics .The Graphics classprovides basiccommandsforsuchthingsasdrawingshapesandtextand forselectingadrawingcolor. <br /> <br /> PAGE 259<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 245 Thesecommandsareadequateinmanycases,buttheyfallfars hortofwhat'sneededina seriouscomputergraphicsprogram.Javahasanotherclass, Graphics2D ,thatprovidesalarger setofdrawingoperations. Graphics2D isasub-classof Graphics ,soallthemethodsfromthe Graphics classarealsoavailableina Graphics2D The paintComponent() methodofa JComponent givesyouagraphicscontextoftype Graphics thatyoucanusefordrawingonthecomponent.Infact,thegra phicscontextactually belongstothesub-class Graphics2D (inJavaversion1.2andlater),andcanbetype-castto gainaccesstotheadvanced Graphics2D drawingmethods: publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);Graphics2Dg2;g2=(Graphics2D)g; ..//Drawonthecomponentusingg2.. } Drawingin Graphics2D isbasedonshapes,whichareobjectsthatimplementaninter face named Shape .Shapeclassesinclude Line2D Rectangle2D Ellipse2D Arc2D ,and CubicCurve2D amongothers;alltheseclassesaredenedinthepackage java.awt.geom CubicCurve2D can beusedtodrawBezierCurves,whichareusedinmanygraphics programs. Graphics2D has methods draw(Shape) and fill(Shape) fordrawingtheoutlineofashapeandforllingits interior.Advancedcapabilitiesinclude:linesthataremo rethanonepixelthick,dottedand dashedlines,llingashapewithatexture(thisis,withare peatedimage),llingashapewith agradient,anddrawingtranslucentobjectsthatwillblend withtheirbackground. Inthe Graphics class,coordinatesarespeciedasintegersandarebasedon pixels.The shapesthatareusedwith Graphics2D userealnumbersforcoordinates,andtheyarenotnecessarilyboundtopixels.Infact,youcanchangethecoordinat esystemanduseanycoordinates thatareconvenienttoyourapplication.Incomputergraphi csterms,youcanapplya\transformation"tothecoordinatesystem.Thetransformationcanbe anycombinationoftranslation, scaling,androtation. Imention Graphics2D hereforcompleteness.Iwillnotuseanyoftheadvancedcapa bilities of Graphics2D inthischapter,butIwillcoverafewofthemin Section12.2 6.3.6AnExampleLet'susesomeofthematerialcoveredinthissectiontowrit easubclassof JPanel foruseas adrawingsurface.Thepanelcanthenbeusedineitheranappl etoraframe,asdiscussedin Subsection6.2.2 .Allthedrawingwillbedoneinthe paintComponent() methodofthepanel class.Thepanelwilldrawmultiplecopiesofamessageonabl ackbackground.Eachcopyof themessageisinarandomcolor.Fivedierentfontsareused ,withdierentsizesandstyles. Themessagecanbespeciedintheconstructor;ifthedefaul tconstructorisused,themessage isthestring\Java!".ThepanelworksOKnomatterwhatitssi ze.Hereiswhatthepanel lookslike: <br /> <br /> PAGE 260<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 246 Thereisoneproblemwiththewaythisclassworks.Whenthepa nel's paintComponent() methodiscalled,itchoosesrandomcolors,fonts,andlocat ionsforthemessages.Theinformationaboutwhichcolors,fonts,andlocationsareusedisnot storedanywhere.Thenexttime paintComponent() iscalled,itwillmakedierentrandomchoicesandwilldraw adierent picture.Forthisparticularapplet,theproblemonlyreall yappearswhenthepanelis partially coveredandthenuncovered(andeventhentheproblemdoesno tshowupinallenvironments). Itispossiblethatonlythepartthatwascoveredwillberedr awn,andinthepartthat'snot redrawn,theoldpicturewillremain.Theusermightseepart ialmessages,cutobythedividinglinebetweenthenewpictureandtheold.Abetterappr oachwouldbetocomputethe contentsofthepictureelsewhere,outsidethe paintComponent() method.Informationabout thepictureshouldbestoredininstancevariables,andthe paintComponent() methodshould usethatinformationtodrawthepicture.If paintComponent() iscalledtwice,itshoulddraw thesamepicturetwice,unlessthedatahaschangedinthemea ntime.Unfortunately,tostore thedataforthepictureinthisapplet,wewouldneedtouseei therarrays,whichwillnotbe covereduntil Chapter7 ,oro-screenimages,whichwillnotbecovereduntil Chapter12 .Other examplesinthischapterwillsuerfromthesameproblem. Thesourceforthepanelclassisshownbelow.Iuseaninstanc evariablecalled message to holdthemessagethatthepanelwilldisplay.Therearevein stancevariablesoftype Font that representdierentsizesandstylesoftext.Thesevariable sareinitializedintheconstructorand areusedinthe paintComponent() method. The paintComponent() methodforthepanelsimplydraws25copiesofthemessage.Fo r eachcopy,itchoosesoneofthevefontsatrandom,anditcal ls g.setFont() toselectthat fontfordrawingthetext.ItcreatesarandomHSBcolorandus es g.setColor() toselectthat colorfordrawing.Itthenchoosesrandom (x,y) coordinatesforthelocationofthemessage. The x coordinategivesthehorizontalpositionoftheleftendoft hestring.Theformulaused forthe x coordinate,\ -50+(int)(Math.random()*(width+40)) "givesarandominteger intherangefrom -50 to width-10 .Thismakesitpossibleforthestringtoextendbeyondthe leftedgeortherightedgeofthepanel.Similarly,theformu lafor y allowsthestringtoextend beyondthetopandbottomoftheapplet. Hereisthecompletesourcecodeforthe RandomStringsPanel importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics;importjavax.swing.JPanel;/** *Thispaneldisplays25copiesofamessage.Thecolorand*positionofeachmessageisselectedatrandom.Thefont <br /> <br /> PAGE 261<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 247 *ofeachmessageisrandomlychosenfromamongfivepossible*fonts.Themessagesaredisplayedonablackbackground.*<p>Note:Thestyleofdrawingusedhereisbad,becauseever y *timethepaintComponent()methodiscalled,newrandomval uesare *used.Thismeansthatadifferentpicturewillbedrawneach*time.Thisisparticularlybadifonlypartofthepanel*needstoberedrawn,sincethenthepanelwillcontain*cut-offpiecesofmessages.*<p>Thispanelismeanttobeusedasthecontentpanein*eitheranappletoraframe.*/ publicclassRandomStringsPanelextendsJPanel{ privateStringmessage;//Themessagetobedisplayed.This canbesetin //theconstructor.Ifnovalueisprovidedinthe//constructor,thenthestring"Java!"isused. privateFontfont1,font2,font3,font4,font5;//Thefivef onts. /** *Defaultconstructorcreatesapanelthatdisplaysthemess age"Java!". **/ publicRandomStringsPanel(){ this(null);//Calltheotherconstructor,withparametern ull. }/** *Constructorcreatesapaneltodisplay25copiesofaspecif iedmessage. *@parammessageStringThemessagetobedisplayed.Ifthisi snull, *thenthedefaultmessage"Java!"isdisplayed.*/ publicRandomStringsPanel(StringmessageString){ message=messageString;if(message==null) message="Java!"; font1=newFont("Serif",Font.BOLD,14);font2=newFont("SansSerif",Font.BOLD+Font.ITALIC,24) ; font3=newFont("Monospaced",Font.PLAIN,30);font4=newFont("Dialog",Font.PLAIN,36);font5=newFont("Serif",Font.ITALIC,48);setBackground(Color.BLACK); }/** *ThepaintComponentmethodisresponsiblefordrawingthec ontentofthepanel. *Itdraws25copiesofthemessagestring,usingarandomcolo r,font,and *positionforeachstring.*/ publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);//CallthepaintComponentmeth odfromthe //superclass,JPanel.Thissimplyfillsthe//entirepanelwiththebackgroundcolor,black. <br /> <br /> PAGE 262<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 248 intwidth=getWidth();intheight=getHeight();for(inti=0;i<25;i++){ //Drawonestring.First,setthefonttobeoneofthefive//availablefonts,atrandom.intfontNum=(int)(5*Math.random())+1;switch(fontNum){ case1: g.setFont(font1);break; case2: g.setFont(font2);break; case3: g.setFont(font3);break; case4: g.setFont(font4);break; case5: g.setFont(font5);break; }//endswitch//Setthecolortoabright,saturatedcolor,withrandomhue floathue=(float)Math.random();g.setColor(Color.getHSBColor(hue,1.0F,1.0F));//Selectthepositionofthestring,atrandom.intx,y;x=-50+(int)(Math.random()*(width+40));y=(int)(Math.random()*(height+20));//Drawthemessage.g.drawString(message,x,y); }//endfor }//endpaintComponent() }//endclassRandomStringsPanel Thisclassdenesapanel,whichisnotsomethingthatcansta ndonitsown.Toseeitonthe screen,wehavetouseitinanappletoraframe.Hereisasimpl eappletclassthatusesa RandomStringsPanel asitscontentpane: importjavax.swing.JApplet;/** *ARandomStringsAppletdisplays25copiesofastring,usin grandomcolors, *fonts,andpositionsforthecopies.Themessagecanbespec ifiedasthe *valueofanappletparamwithname"message."Ifnoparamwit hname *"message"ispresent,thenthedefaultmessage"Java!"isd isplayed. <br /> <br /> PAGE 263<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 249 *TheactualcontentoftheappletisanobjectoftypeRandomS tringsPanel. */ publicclassRandomStringsAppletextendsJApplet{ publicvoidinit(){ Stringmessage=getParameter("message");RandomStringsPanelcontent=newRandomStringsPanel(mes sage); setContentPane(content); } } Notethatthemessagetobedisplayedintheappletcanbesetu singanappletparameterwhen theappletisaddedtoanHTMLdocument.UsingappletsonWebp ageswasdiscussedin Subsection6.2.4 .RememberthattousetheappletonaWebpage,youmustinclud eboththepanel classle, RandomStringsPanel.class ,andtheappletclassle, RandomStringsApplet.class inthesamedirectoryastheHTMLdocument(or,alternativel y,bundlethetwoclasslesinto ajarle,andputthejarleinthedocumentdirectory). Insteadofwritinganapplet,ofcourse,wecouldusethepane linthewindowofastandaloneapplication.Youcanndthesourcecodeforamainprog ramthatdoesthisinthele RandomStringsApp.java 6.4MouseEventsE ventsarecentral toprogrammingforagraphicaluserinterface.AGUIprogram doesn't (online) havea main() routinethatoutlineswhatwillhappenwhentheprogramisru n,inastep-by-step processfrombeginningtoend.Instead,theprogrammustbep reparedtorespondtovarious kindsofeventsthatcanhappenatunpredictabletimesandin anorderthattheprogramdoesn't control.Themostbasickindsofeventsaregeneratedbythem ouseandkeyboard.Theuser canpressanykeyonthekeyboard,movethemouse,orpressabu ttononthemouse.Theuser candoanyofthesethingsatanytime,andthecomputerhastor espondappropriately. InJava,eventsarerepresentedbyobjects.Whenaneventocc urs,thesystemcollectsallthe informationrelevanttotheeventandconstructsanobjectt ocontainthatinformation.Dierent typesofeventsarerepresentedbyobjectsbelongingtodie rentclasses.Forexample,whenthe userpressesoneofthebuttonsonamouse,anobjectbelongin gtoaclasscalled MouseEvent isconstructed.Theobjectcontainsinformationsuchasthe sourceoftheevent(thatis,the componentonwhichtheuserclicked),the (x,y) coordinatesofthepointinthecomponent wheretheclickoccurred,andwhichbuttononthemousewaspr essed.Whentheuserpressesa keyonthekeyboard,a KeyEvent iscreated.Aftertheeventobjectisconstructed,itispass ed asaparametertoadesignatedsubroutine.Bywritingthatsu broutine,theprogrammersays whatshouldhappenwhentheeventoccurs. AsaJavaprogrammer,yougetafairlyhigh-levelviewofeven ts.Thereisalotofprocessing thatgoesonbetweenthetimethattheuserpressesakeyormov esthemouseandthetimethat asubroutineinyourprogramiscalledtorespondtotheevent .Fortunately,youdon'tneedto knowmuchaboutthatprocessing.Butyoushouldunderstandt hismuch:Eventhoughyour GUIprogramdoesn'thavea main() routine,thereisasortofmainroutinerunningsomewhere thatexecutesaloopoftheform whiletheprogramisstillrunning: WaitforthenexteventtooccurCallasubroutinetohandletheevent <br /> <br /> PAGE 264<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 250 Thisloopiscalledan eventloop .EveryGUIprogramhasaneventloop.InJava,you don'thavetowritetheloop.It'spartof\thesystem."Ifyou writeaGUIprograminsome otherlanguage,youmighthavetoprovideamainroutinethat runsaneventloop. Inthissection,we'lllookathandlingmouseeventsinJava, andwe'llcovertheframework forhandlingeventsingeneral.Thenextsectionwillcoverk eyboard-relatedeventsandtimer events.Javaalsohasothertypesofevents,whichareproduc edbyGUIcomponents.These willbeintroducedin Section6.6 6.4.1EventHandlingForaneventtohaveanyeect,aprogrammustdetecttheevent andreacttoit.Inorderto detectanevent,theprogrammust\listen"forit.Listening foreventsissomethingthatisdone byanobjectcalledan eventlistener .Aneventlistenerobjectmustcontaininstancemethods forhandlingtheeventsforwhichitlistens.Forexample,if anobjectistoserveasalistenerfor eventsoftype MouseEvent ,thenitmustcontainthefollowingmethod(amongseveralot hers): publicvoidmousePressed(MouseEventevt){...} Thebodyofthemethoddeneshowtheobjectrespondswheniti snotiedthatamousebutton hasbeenpressed.Theparameter, evt ,containsinformationabouttheevent.Thisinformation canbeusedbythelistenerobjecttodetermineitsresponse. Themethodsthatarerequiredinamouseeventlisteneraresp eciedinan interface named MouseListener .Tobeusedasalistenerformouseevents,anobjectmustimpl ement this MouseListener interface.Java interfaces werecoveredin Subsection5.7.1 .(Toreview briery:An interface inJavaisjustalistofinstancemethods.Aclasscan\implem ent"an interfacebydoingtwothings.First,theclassmustbedecla redtoimplementtheinterface,as in\ classMyListenerimplementsMouseListener "or\ classMyAppletextendsJApplet implementsMouseListener ".Second,theclassmustincludeadenitionforeachinstan ce methodspeciedintheinterface.An interface canbeusedasthetypeforavariableor formalparameter.Wesaythatanobjectimplementsthe MouseListener interfaceifitbelongs toaclassthatimplementsthe MouseListener interface.Notethatitisnotenoughfortheobject toincludethespeciedmethods.Itmustalsobelongtoaclas sthatisspecicallydeclaredto implementtheinterface.) ManyeventsinJavaareassociatedwithGUIcomponents.Fore xample,whentheuser pressesabuttononthemouse,theassociatedcomponentisth eonethattheuserclicked on.Beforealistenerobjectcan\hear"eventsassociatedwi thagivencomponent,thelistenerobjectmustberegisteredwiththecomponent.Ifa MouseListener object, mListener needstohearmouseeventsassociatedwitha Component object, comp ,thelistenermustbe registered withthecomponentbycalling\ comp.addMouseListener(mListener); ".The addMouseListener() methodisaninstancemethodinclass Component ,andsocanbeused withanyGUIcomponentobject.Inourrstfewexamples,wewi lllistenforeventsonaJPanel thatisbeingusedasadrawingsurface. Theeventclasses,suchas MouseEvent ,andthelistenerinterfaces,suchas MouseListener ,are denedinthepackage java.awt.event .Thismeansthatifyouwanttoworkwithevents,you shouldeitherincludetheline\ importjava.awt.event.*; "atthebeginningofyoursource codeleorimporttheindividualclassesandinterfaces. Admittedly,thereisalargenumberofdetailstotendtowhen youwanttouseevents.To summarize,youmust <br /> <br /> PAGE 265<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 251 1. Puttheimportspecication\ importjava.awt.event.*; "(orindividualimports)at thebeginningofyoursourcecode; 2. Declarethatsomeclassimplementstheappropriatelistene rinterface,suchas MouseListener ; 3. Providedenitionsinthatclassforthesubroutinesfromth einterface; 4. Registerthelistenerobjectwiththecomponentthatwillge neratetheeventsbycalling amethodsuchas addMouseListener() inthecomponent. Anyobjectcanactasaneventlistener,providedthatitimpl ementstheappropriateinterface.Acomponentcanlistenfortheeventsthatititself generates.Apanelcanlistenfor eventsfromcomponentsthatarecontainedinthepanel.Aspe cialclasscanbecreatedjust forthepurposeofdeningalisteningobject.Manypeopleco nsiderittobegoodformtouse anonymousinnerclassestodenelisteningobjects(see Subsection5.7.3 ).Youwillseeallof thesepatternsinexamplesinthistextbook.6.4.2MouseEventandMouseListenerThe MouseListener interfacespeciesvedierentinstancemethods: publicvoidmousePressed(MouseEventevt);publicvoidmouseReleased(MouseEventevt);publicvoidmouseClicked(MouseEventevt);publicvoidmouseEntered(MouseEventevt);publicvoidmouseExited(MouseEventevt); The mousePressed methodiscalledassoonastheuserpressesdownononeofthem ouse buttons,and mouseReleased iscalledwhentheuserreleasesabutton.Thesearethetwo methodsthataremostcommonlyused,butanymouselistenero bjectmustdeneallve methods;youcanleavethebodyofamethodemptyifyoudon'tw anttodenearesponse.The mouseClicked methodiscallediftheuserpressesamousebuttonandthenre leasesitquickly, withoutmovingthemouse.(Whentheuserdoesthis,allthree routines| mousePressed mouseReleased ,and mouseClicked |willbecalledinthatorder.)Inmostcases,youshould dene mousePressed insteadof mouseClicked .The mouseEntered and mouseExited methods arecalledwhenthemousecursorentersorleavesthecompone nt.Forexample,ifyouwantthe componenttochangeappearancewhenevertheusermovesthem ouseoverthecomponent,you coulddenethesetwomethods. Asanexample,wewilllookatasmalladditiontothe RandomStringsPanel examplefrom theprevioussection.Inthenewversion,thepanelwillrepa intitselfwhentheuserclicksonit. Inorderforthistohappen,amouselistenershouldlistenfo rmouseeventsonthepanel,and whenthelistenerdetectsa mousePressed event,itshouldrespondbycallingthe repaint() methodofthepanel. Forthenewversionoftheprogram,weneedanobjectthatimpl ementsthe MouseListener interface.Onewaytocreatetheobjectistodeneaseparate class,suchas: importjava.awt.Component;importjava.awt.event.*;/** *AnobjectoftypeRepaintOnClickisaMouseListenerthat*willrespondtoamousePressedeventbycallingtherepaint () *methodofthesourceoftheevent.Thatis,aRepaintOnClick <br /> <br /> PAGE 266<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 252 *objectcanbeaddedasamouselistenertoanyComponent;*whentheuserclicksthatcomponent,thecomponentwillbe*repainted.*/ publicclassRepaintOnClickimplementsMouseListener{ publicvoidmousePressed(MouseEventevt){ Componentsource=(Component)evt.getSource();source.repaint();//Callrepaint()ontheComponentthatw asclicked. }publicvoidmouseClicked(MouseEventevt){}publicvoidmouseReleased(MouseEventevt){}publicvoidmouseEntered(MouseEventevt){}publicvoidmouseExited(MouseEventevt){} } Thisclassdoesthreeofthefourthingsthatweneedtodoinor dertohandlemouseevents: First,itimports java.awt.event.* foreasyaccesstoevent-relatedclasses.Second,itis declaredthattheclass\ implementsMouseListener ".Andthird,itprovidesdenitionsfor thevemethodsthatarespeciedinthe MouseListener interface.(Notethatfouroftheve event-handlingmethodshaveemptydentions.Wereallyonl ywanttodenearesponseto mousePressed events,butinordertoimplementthe MouseListener interface,aclass must deneallvemethods.) Wemustdoonemorethingtosetuptheeventhandlingforthise xample:Wemustregister anevent-handlingobjectasalistenerwiththecomponentth atwillgeneratetheevents.In thiscase,themouseeventsthatweareinterestedinwillbeg eneratedbyanobjectoftype RandomStringsPanel .If panel isavariablethatreferstothepanelobject,wecancreatea mouselistenerobjectandregisteritwiththepanelwiththe statements: RepaintOnClicklistener=newRepaintOnClick();//Create MouseListenerobject. panel.addMouseListener(listener);//RegisterMouseLis tenerwiththepanel. Oncethisisdone,the listener objectwillbenotiedofmouseeventsonthepanel.Whena mousePressed eventoccurs,the mousePressed() methodinthe listener willbecalled.The codeinthismethodcallsthe repaint() methodinthecomponentthatisthesourceofthe event,thatis,inthepanel.Theresultisthatthe RandomStringsPanel isrepaintedwithits stringsinnewrandomcolors,fonts,andpositions. Althoughwehavewrittenthe RepaintOnClick classforusewithour RandomStringsPanel example,theevent-handlingclasscontainsnoreferenceat alltothe RandomStringsPanel class. Howcanthisbe?The mousePressed() methodinclass RepaintOnClick looksatthesource oftheevent,andcallsits repaint() method.Ifwehaveregisteredthe RepaintOnClick object asalistenerona RandomStringsPanel ,thenitisthatpanelthatisrepainted.Butthelistener objectcouldbeusedwithanytypeofcomponent,anditwouldw orkinthesameway. Similarly,the RandomStringsPanel classcontainsnoreferencetothe RepaintOnClick class| infact, RandomStringsPanel waswrittenbeforeweevenknewanythingaboutmouseevents! Thepanelwillsendmouseeventstoanyobjectthathasregist eredwithitasamouselistener. Itdoesnotneedtoknowanythingaboutthatobjectexcepttha titiscapableofreceivingmouse events. Therelationshipbetweenanobjectthatgeneratesaneventa ndanobjectthatresponds tothateventisratherloose.Therelationshipissetupbyre gisteringoneobjecttolistenfor <br /> <br /> PAGE 267<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 253 eventsfromtheotherobject.Thisissomethingthatcanpote ntiallybedonefromoutside bothobjects.Eachobjectcanbedevelopedindependently,w ithnoknowledgeoftheinternal operationoftheotherobject.Thisistheessenceof modulardesign :Buildacomplexsystem outofmodulesthatinteractonlyinstraightforward,easyt ounderstandways.Theneach moduleisaseparatedesignproblemthatcanbetackledindep endently. Tomakethisclearer,considertheapplicationversionofth e ClickableRandomStrings program.Ihaveincluded RepaintOnClick asanestedclass,althoughitcouldjustaseasilybe aseparateclass.Themainpointisthatthisprogramusesthe same RandomStringsPanel class thatwasusedintheoriginalprogram,whichdidnotrespondt omouseclicks.Themouse handlinghasbeen\boltedon"toanexistingclass,withouth avingtomakeanychangesatall tothatclass: importjava.awt.Component;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjavax.swing.JFrame;/** *Displaysawindowthatshows25copiesofthestring"Java!" in *randomcolors,fonts,andpositions.Thecontentofthewin dow *isanobjectoftypeRandomStringsPanel.Whentheuserclic ks *thewindow,thecontentofthewindowisrepainted,withthe*stringsinnewlyselectedrandomcolors,fonts,andpositi ons. */ publicclassClickableRandomStringsApp{ publicstaticvoidmain(String[]args){ JFramewindow=newJFrame("RandomStrings");RandomStringsPanelcontent=newRandomStringsPanel();content.addMouseListener(newRepaintOnClick()); //Registermouselistener. window.setContentPane(content);window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE); window.setLocation(100,75);window.setSize(300,240);window.setVisible(true); }privatestaticclassRepaintOnClickimplementsMouseList ener{ publicvoidmousePressed(MouseEventevt){ Componentsource=(Component)evt.getSource();source.repaint(); }publicvoidmouseClicked(MouseEventevt){}publicvoidmouseReleased(MouseEventevt){}publicvoidmouseEntered(MouseEventevt){}publicvoidmouseExited(MouseEventevt){} } } <br /> <br /> PAGE 268<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 254 6.4.3MouseCoordinatesOften,whenamouseeventoccurs,youwanttoknowthelocatio nofthemousecursor.This informationisavailablefromthe MouseEvent parametertotheevent-handlingmethod,which containsinstancemethodsthatreturninformationaboutth eevent.If evt istheparameter,thenyoucanndoutthecoordinatesofthemousecursorb ycalling evt.getX() and evt.getY() .Thesemethodsreturnintegerswhichgivethe x and y coordinateswherethe mousecursorwaspositionedatthetimewhentheeventoccurr ed.Thecoordinatesareexpressedinthecoordinatesystemofthecomponentthatgener atedtheevent,wherethetopleft cornerofthecomponentis(0,0). Theusercanholddowncertain modierkeys whileusingthemouse.Thepossiblemodierkeysinclude:theShiftkey,theControlkey,theALTkey (calledtheOptionkeyonthe Macintosh),andtheMetakey(calledtheCommandorApplekey ontheMacintosh).You mightwanttorespondtoamouseeventdierentlywhentheuse risholdingdownamodierkey.Theboolean-valuedinstancemethods evt.isShiftDown() evt.isControlDown() evt.isAltDown() ,and evt.isMetaDown() canbecalledtotestwhetherthemodierkeysare pressed. Youmightalsowanttohavedierentresponsesdependingonw hethertheuserpresses theleftmousebutton,themiddlemousebutton,ortherightm ousebutton.Now,notevery mousehasamiddlebuttonandarightbutton,soJavahandlest heinformationinapeculiar way.Ittreatspressingtherightbuttonasequivalenttohol dingdowntheMetakeywhile pressingtheleftmousebutton.Thatis,iftherightbuttoni spressed,thentheinstance method evt.isMetaDown() willreturn true (eveniftheMetakeyisnotpressed).Similarly, pressingthemiddlemousebuttonisequivalenttoholdingdo wntheALTkey.Inpractice, whatthisreallymeansisthatpressingtherightmousebutto nunderWindowsisequivalentto holdingdowntheCommandkeywhilepressingthemousebutton onMacintosh.Aprogram testsforeitherofthesebycalling evt.isMetaDown() Asanexample,considera JPanel thatdoesthefollowing:Clickingonthepanelwiththeleft mousebuttonwillplacearedrectangleonthepanelatthepoi ntwherethemousewasclicked. Clickingwiththerightmousebutton(orholdingdowntheCom mandkeywhileclickingona Macintosh)willplaceablueovalontheapplet.Holdingdown theShiftkeywhileclickingwill clearthepanelbyremovingalltheshapesthathavebeenplac ed. Thereareseveralwaystowritethisexample.Icouldwriteas eparateclasstohandle mouseevents,asIdidinthepreviousexample.However,inth iscase,Idecidedtoletthe panelrespondtomouseeventsitself.Anyobjectcanbeamous elistener,aslongasitimplementsthe MouseListener interface.Inthiscase,thepanelclassimplementsthe MouseListener interface,soanyobjectbelongingtothatclasscanactasam ouselistener.Theconstructor forthepanelclassregistersthepanelwith itself asamouselistener.Itdoesthiswiththe statement\ addMouseListener(this) ".Sincethiscommandisinamethodinthepanelclass, the addMouseListener() methodinthepanelobjectisbeingcalled,andalistenerisb eing registeredwiththatpanel.Theparameter\ this "alsoreferstothepanelobject,soitisthe samepanelobjectthatislisteningforevents.Thus,thepan elobjectplaysadualrolehere.(If youndthistooconfusing,rememberthatyoucanalwayswrit easeparateclasstodenethe listeningobject.) Thesourcecodeforthepanelclassisshownbelow.Youshould checkhowtheinstance methodsinthe MouseEvent objectareused.YoucanalsocheckfortheFourStepsofEvent Handling(\ importjava.awt.event.* ",\ implementsMouseListener ",denitionsforthe event-handlingmethods,and\ addMouseListener "): <br /> <br /> PAGE 269<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 255 importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;/** *AsimpledemonstrationofMouseEvents.Shapesaredrawn*onablackbackgroundwhentheuserclicksthepanelIf*theuserShift-clicks,theappletiscleared.Iftheuser*right-clickstheapplet,ablueovalisdrawn.Otherwise,*whentheuserclicks,aredrectangleisdrawn.Thecontents of *thepanelarenotpersistent.Forexample,theymightdisap pear *ifthepaneliscoveredanduncovered.*/ publicclassSimpleStamperPanelextendsJPanelimplement sMouseListener{ /** *Thisconstructorsimplysetsthebackgroundcolorofthepa neltobeblack *andsetsthepaneltolistenformouseeventsonitself.*/ publicSimpleStamperPanel(){ setBackground(Color.BLACK);addMouseListener(this); }/** *Sincethispanelhasbeensettolistenformouseeventsonit self, *thismethodwillbecalledwhentheuserclicksthemouseont hepanel. *ThismethodispartoftheMouseListenerinterface.*/ publicvoidmousePressed(MouseEventevt){ if(evt.isShiftDown()){ //TheuserwasholdingdowntheShiftkey.Justrepaintthepa nel. //SincethisclassdoesnotdefineapaintComponent()metho d,the //methodfromthesuperclass,JPanel,iscalled.Thatmetho dsimply //fillsthepanelwithitsbackgroundcolor,whichisblack. The //effectistoclearthepanel. repaint();return; }intx=evt.getX();//x-coordinatewhereuserclicked.inty=evt.getY();//y-coordinatewhereuserclicked.Graphicsg=getGraphics();//Graphicscontextfordrawing directly. //NOTE:Thisisconsideredtobebadstyle! if(evt.isMetaDown()){ //Userright-clickedatthepoint(x,y).Drawablueovalcen tered //atthepoint(x,y).(Ablackoutlinearoundtheovalwillma keit //moredistinctwhenovalsandrectsoverlap.) g.setColor(Color.BLUE);//Blueinterior.g.fillOval(x-30,y-15,60,30);g.setColor(Color.BLACK);//Blackoutline.g.drawOval(x-30,y-15,60,30); } <br /> <br /> PAGE 270<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 256 else{ //Userleft-clicked(ormiddle-clicked)at(x,y).//Drawaredrectanglecenteredat(x,y). g.setColor(Color.RED);//Redinterior.g.fillRect(x-30,y-15,60,30);g.setColor(Color.BLACK);//Blackoutline.g.drawRect(x-30,y-15,60,30); }g.dispose();//Wearefinishedwiththegraphicscontext,s odisposeofit. }//endmousePressed();//ThenextfouremptyroutinesarerequiredbytheMouseList enerinterface. //Sincetheydon'tdoanythinginthisclass,sotheirdefini tionsareempty. publicvoidmouseEntered(MouseEventevt){}publicvoidmouseExited(MouseEventevt){}publicvoidmouseClicked(MouseEventevt){}publicvoidmouseReleased(MouseEventevt){} }//endclassSimpleStamperPanel Note,bytheway,thatthisclassviolatestherulethatalldr awingshouldbedone ina paintComponent() method.Therectanglesandovalsaredrawndirectlyinthe mousePressed() routine.Tomakethispossible,Ineedtoobtainagraphicsco ntextbysaying \ g=getGraphics() ".Afterusing g fordrawing,Icall g.dispose() toinformtheoperating systemthatIwillnolongerbeusing g fordrawing.Itisagoodideatodothistofreethe systemresourcesthatareusedbythegraphicscontext.Idon otadvisedoingthistypeofdirect drawingifitcanbeavoided,butyoucanseethatitdoesworki nthiscase,andatthispoint wereallyhavenootherwaytowritethisexample.6.4.4MouseMotionListenersandDraggingWheneverthemouseismoved,itgeneratesevents.Theoperat ingsystemofthecomputer detectstheseeventsandusesthemtomovethemousecursoron thescreen.Itisalsopossible foraprogramtolistenforthese\mousemotion"eventsandre spondtothem.Themost commonreasontodosoistoimplement dragging .Draggingoccurswhentheusermovesthe mousewhileholdingdownamousebutton. Themethodsforrespondingtomousemotioneventsaredened inaninterfacenamed MouseMotionListener .Thisinterfacespeciestwoevent-handlingmethods: publicvoidmouseDragged(MouseEventevt);publicvoidmouseMoved(MouseEventevt); The mouseDragged methodiscalledifthemouseismovedwhileabuttononthemou se ispressed.Ifthemouseismovedwhilenomousebuttonisdown ,then mouseMoved iscalled instead.Theparameter, evt ,isanobjectoftype MouseEvent .Itcontainsthe x and y coordinatesofthemouse'slocation.Aslongastheusercontinuest omovethemouse,oneofthese methodswillbecalledoverandover.(Somanyeventsaregene ratedthatitwouldbeinecient foraprogramtohearthemall,ifitdoesn'twanttodoanythin ginresponse.Thisiswhythe mousemotionevent-handlersaredenedinaseparateinterf acefromtheothermouseevents: Youcanlistenforthemouseeventsdenedin MouseListener withoutautomaticallyhearingall mousemotioneventsaswell.) <br /> <br /> PAGE 271<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 257 Ifyouwantyourprogramtorespondtomousemotionevents,yo umustcreateanobjectthat implementsthe MouseMotionListener interface,andyoumustregisterthatobjecttolistenfor events.Theregistrationisdonebycallingacomponent's addMouseMotionListener method. Theobjectwillthenlistenfor mouseDragged and mouseMoved eventsassociatedwiththat component.Inmostcases,thelistenerobjectwillalsoimpl ementthe MouseListener interface sothatitcanrespondtotheothermouseeventsaswell. Togetabetterideaofhowmouseeventswork,youshouldtryth e SimpleTrackMouseApplet intheon-lineversionofthissection.Theappletisprogram medtorespondtoanyoftheseven dierentkindsofmouseeventsbydisplayingthecoordinate softhemouse,thetypeofevent,and alistofthemodierkeysthataredown(Shift,Control,Meta ,andAlt).Youcanexperiment withtheapplettoseewhathappenswhenyouusethemouseonth eapplet.(Alternatively, youcouldrunthestand-aloneapplicationversionofthepro gram, SimpleTrackMouse.java .) Thesourcecodefortheappletcanbefoundin SimpleTrackMousePanel.java ,whichdenes thepanelthatisusedasthecontentpaneoftheapplet,andin SimpleTrackMouseApplet.java whichdenestheappletclass.Thepanelclassincludesanes tedclass, MouseHandler ,that denesthemouse-handlingobject.Iencourageyoutoreadth esourcecode.Youshouldnow befamiliarwithallthetechniquesthatituses. Itisinterestingtolookatwhataprogramneedstodoinorder torespondtodraggingoperations.Ingeneral,theresponseinvolvesthreemethods: mousePressed() mouseDragged() and mouseReleased() .Thedragginggesturestartswhentheuserpressesamousebu tton, itcontinueswhilethemouseisdragged,anditendswhentheu serreleasesthebutton.This meansthattheprogrammingfortheresponsetoonedraggingg esturemustbespreadoutover thethreemethods!Furthermore,the mouseDragged() methodcanbecalledmanytimesas themousemoves.Tokeeptrackofwhatisgoingonbetweenonem ethodcallandthenext, youneedtosetupsomeinstancevariables.Inmanyapplicati ons,forexample,inorderto processa mouseDragged event,youneedtorememberthepreviouscoordinatesofthem ouse. Youcanstorethisinformationintwoinstancevariables prevX and prevY oftype int .Itcan alsobeusefultosavethestartingcoordinates,wherethe mousePressed eventoccurred,in instancevariables.Ialsosuggesthavinga boolean variable, dragging ,whichissetto true whileadragginggestureisbeingprocessed.Thisisnecessa rybecausenotevery mousePressed eventstartsadraggingoperationtowhichyouwanttorespon d.The mouseDragged and mouseReleased methodscanusethevalueof dragging tocheckwhetheradragoperationis actuallyinprogress.Youmightneedotherinstancevariabl esaswell,butingeneraloutline,a classthathandlesmousedragginglookslikethis: importjava.awt.event.*;publicclassMouseDragHandlerimplementsMouseListener, MouseMotionListener{ privateintstartX,startY;//Pointwheremouseispressed.privateintprevX,prevY;//Mostrecentlyprocessedmousec oords. privatebooleandragging;//Settotruewhendraggingisinp rocess. ...//otherinstancevariablesforuseindraggingpublicvoidmousePressed(MouseEventevt){ if(we-want-to-start-dragging){ dragging=true;startX=evt.getX();//Rememberstartingposition.startY=evt.getY();prevX=startX;//Remembermostrecentcoords.prevY=startY; <br /> <br /> PAGE 272<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 258 ..//Otherprocessing.. } }publicvoidmouseDragged(MouseEventevt){ if(dragging==false)//First,checkifweare return;//processingadragginggesture. intx=evt.getX();//CurrentpositionofMouse.inty=evt.getY(); ..//Processamousemovementfrom(prevX,prevY)to(x,y).. prevX=x;//Rememberthecurrentpositionforthenextcall.prevY=y; }publicvoidmouseReleased(MouseEventevt){ if(dragging==false)//First,checkifweare return;//processingadragginggesture. dragging=false;//Wearedonedragging. ..//Otherprocessingandclean-up.. } } Asanexample,let'slookatatypicaluseofdragging:allowi ngtheusertosketchacurveby draggingthemouse.Thisexamplealsoshowsmanyotherfeatu resofgraphicsandmouseprocessing.Intheprogram,youcandrawacurvebydraggingthem ouseonalargewhitedrawing area,andyoucanselectacolorfordrawingbyclickingonone ofseveralcoloredrectangles totherightofthedrawingarea.Thecompletesourcecodecan befoundin SimplePaint.java whichcanberunasastand-aloneapplication,andyoucannd anappletversionintheon-line versionofthissection.Hereisapictureoftheprogram: <br /> <br /> PAGE 273<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 259 Iwilldiscussafewaspectsofthesourcecodehere,butIenco urageyoutoreaditcarefully initsentirety.Therearelotsofinformativecommentsinth esourcecode.(Thesourcecode usesoneunusualtechnique:Itdenesasubclassof JApplet ,butitalsoincludesa main() routine.The main() routinehasnothingtodowiththeclass'suseasanapplet,bu titmakesit possibletoruntheclassasastand-aloneapplication.When thisisdone,theapplicationopens awindowthatshowsthesamepanelthatwouldbeshownintheap pletversion.Thisexample thusshowshowtowriteasinglelethatcanbeusedeitherasa stand-aloneapplicationoras anapplet.) Thepanelclassforthisexampleisdesignedtoworkforanyre asonablesize,thatis,unless thepanelistoosmall.Thismeansthatcoordinatesarecompu tedintermsoftheactual widthandheightofthepanel.(Thewidthandheightareobtai nedbycalling getWidth() and getHeight() .)Thismakesthingsquiteabitharderthantheywouldbeifwe assumedsome particularxedsizeforthepanel.Let'slookatsomeofthes ecomputationsindetail.For example,thelargewhitedrawingareaextendsfrom y=3 to y=height-3 verticallyand from x=3 to x=width-56 horizontally.Thesenumbersareneededinordertointerpre t themeaningofamouseclick.Theytakeintoaccountagraybor deraroundthepaneland thecolorpalettealongtherightedgeofthepanel.Theborde ris3pixelswide.Thecolored rectanglesare50pixelswide.Togetherwiththe3-pixelbor deraroundthepanelanda3-pixel dividerbetweenthedrawingareaandthecoloredrectangles ,thisaddsuptoputtherightedge ofthedrawingarea56pixelsfromtherightedgeofthepanel. Awhitesquarelabeled\ CLEAR "occupiesa50-by-50pixelregionbeneaththecoloredrectanglesontherightedgeofthepanel.Allowingforthissquar e,wecangureouthowmuch verticalspaceisavailableforthesevencoloredrectangle s,andthendividethatspaceby7to gettheverticalspaceavailableforeachrectangle.Thisqu antityisrepresentedbyavariable, colorSpace .Outofthisspace,3pixelsareusedasspacingbetweenthere ctangles,sotheheight ofeachrectangleis colorSpace-3 .Thetopofthe N -threctangleislocated (N*colorSpace +3) pixelsdownfromthetopofthepanel,assumingthatwecountt herectanglesstarting withzero.Thisisbecausethereare N rectanglesabovethe N -threctangle,eachofwhichuses colorSpace pixels.Theextra3isfortheborderatthetopofthepanel.Af terallthat,wecan writedownthecommandfordrawingthe N -threctangle: g.fillRect(width-53,N*colorSpace+3,50,colorSpace-3) ; Thatwasnoteasy!Butitshowsthekindofcarefulthinkingan dprecisiongraphicsthatare sometimesnecessarytogetgoodresults. Themouseinthispanelisusedtodothreedierentthings:Se lectacolor,clearthedrawing, anddrawacurve.Onlythethirdoftheseinvolvesdragging,s onoteverymouseclickwillstart adraggingoperation.The mousePressed routinehastolookatthe (x,y) coordinateswhere themousewasclickedanddecidehowtorespond.Iftheusercl ickedonthe CLEAR rectangle, thedrawingareaisclearedbycalling repaint() .Iftheuserclickedsomewhereinthestrip ofcoloredrectangles,theselectedcolorischanged.Thisi nvolvescomputingwhichcolorthe userclickedon,whichisdonebydividingthe y coordinateby colorSpace .Finally,iftheuser clickedonthedrawingarea,adragoperationisinitiated.A booleanvariable, dragging ,is setto true sothatthe mouseDragged and mouseReleased methodswillknowthatacurveis beingdrawn.Thecodeforthisfollowsthegeneralformgiven above.Theactualdrawingof thecurveisdoneinthe mouseDragged method,whichdrawsalinefromthepreviouslocation ofthemousetoitscurrentlocation.Someeortisrequiredt omakesurethatthelinedoes notextendbeyondthewhitedrawingareaofthepanel.Thisis notautomatic,sinceasfaras thecomputerisconcerned,theborderandthecolorbararepa rtofthedrawingsurface.Ifthe <br /> <br /> PAGE 274<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 260 userdragsthemouseoutsidethedrawingareawhiledrawinga line,the mouseDragged routine changesthe x and y coordinatestomakethemliewithinthedrawingarea. 6.4.5AnonymousEventHandlersAsImentionedabove,itisafairlycommonpracticetouseano nymousnestedclassestodene listenerobjects.Asdiscussedin Subsection5.7.3 ,aspecialformofthe new operatorisusedto createanobjectthatbelongstoananonymousclass.Forexam ple,amouselistenerobjectcan becreatedwithanexpressionoftheform: newMouseListener(){ publicvoidmousePressed(MouseEventevt){...}publicvoidmouseReleased(MouseEventevt){...}publicvoidmouseClicked(MouseEventevt){...}publicvoidmouseEntered(MouseEventevt){...}publicvoidmouseExited(MouseEventevt){...} } Thisisalljustonelongexpressionthatbothdenesanun-na medclassandcreatesanobject thatbelongstothatclass.Tousetheobjectasamouselisten er,itshouldbepassedasthe parametertosomecomponent's addMouseListener() methodinacommandoftheform: component.addMouseListener( newMouseListener(){ publicvoidmousePressed(MouseEventevt){...}publicvoidmouseReleased(MouseEventevt){...}publicvoidmouseClicked(MouseEventevt){...}publicvoidmouseEntered(MouseEventevt){...}publicvoidmouseExited(MouseEventevt){...} } ); Now,inatypicalapplication,mostofthemethoddenitions inthisclasswillbeempty. Aclassthatimplementsan interface mustprovidedenitionsforallthemethodsinthat interface,evenifthedenitionsareempty.Toavoidtheted iumofwritingemptymethod denitionsincaseslikethis,Javaprovides adapterclasses .Anadapterclassimplements alistenerinterfacebyprovidingemptydenitionsforallt hemethodsintheinterface.An adapterclassisusefulonlyasabasisformakingsubclasses .Inthesubclass,youcandenejust thosemethodsthatyouactuallywanttouse.Fortheremainin gmethods,theemptydenitions thatareprovidedbytheadapterclasswillbeused.Theadapt erclassforthe MouseListener interfaceisnamed MouseAdapter .Forexample,ifyouwantamouselistenerthatonlyresponds tomouse-pressedevents,youcanuseacommandoftheform: component.addMouseListener(new MouseAdapter() { publicvoidmousePressed(MouseEventevt){...} }); Toseehowthisworksinarealexample,let'swriteanotherve rsionofthe ClickableRandomStringsApp applicationfrom Subsection6.4.2 .Thisversionusesananonymousclassbasedon MouseAdapter tohandlemouseevents: importjava.awt.Component;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjavax.swing.JFrame;publicclassClickableRandomStringsApp{ <br /> <br /> PAGE 275<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 261 publicstaticvoidmain(String[]args){ JFramewindow=newJFrame("RandomStrings");RandomStringsPanelcontent=newRandomStringsPanel();content.addMouseListener(newMouseAdapter() { //Registeramouselistenerthatisdefinedbyananonymouss ubclass //ofMouseAdapter.ThisreplacestheRepaintOnClickclass thatwas //usedintheoriginalversion. publicvoidmousePressed(MouseEventevt) { Componentsource=(Component)evt.getSource();source.repaint(); } } ); window.setContentPane(content);window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE); window.setLocation(100,75);window.setSize(300,240);window.setVisible(true); } } Anonymousinnerclassescanbeusedforotherpurposesbesid eseventhandling.Forexample,supposethatyouwanttodeneasubclassof JPanel torepresentadrawingsurface. Thesubclasswillonlybeusedonce.Itwillredenethe paintComponent() method,butwill makenootherchangesto JPanel .Itmightmakesensetodenethesubclassasananonymousnestedclass.Asanexample,Ipresent HelloWorldGUI4.java .Thisversionisavariation of HelloWorldGUI2.java thatusesanonymousnestedclasseswheretheoriginalprogr amuses ordinary,namednestedclasses: importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;/** *AsimpleGUIprogramthatcreatesandopensaJFramecontain ing *themessage"HelloWorld"andan"OK"button.Whentheuserc licks *theOKbutton,theprogramends.Thisversionusesanonymou s *classestodefinethemessagedisplaypanelandtheactionl istener *object.ComparetoHelloWorldGUI2,whichusesnestedclas ses. */ publicclassHelloWorldGUI4{ /** *ThemainprogramcreatesawindowcontainingaHelloWorldD isplay *andabuttonthatwillendtheprogramwhentheuserclicksit */ publicstaticvoidmain(String[]args){ JPaneldisplayPanel=newJPanel() { //AnanonymoussubclassofJPanelthatdisplays"HelloWorl d!". publicvoidpaintComponent(Graphicsg) { super.paintComponent(g);g.drawString("HelloWorld!",20,30); } <br /> <br /> PAGE 276<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 262 } ; JButtonokButton=newJButton("OK");okButton.addActionListener(newActionListener() { //Ananonymousclassthatdefinesthelistenerobject. publicvoidactionPerformed(ActionEvente) { System.exit(0); } } ); JPanelcontent=newJPanel();content.setLayout(newBorderLayout());content.add(displayPanel,BorderLayout.CENTER);content.add(okButton,BorderLayout.SOUTH);JFramewindow=newJFrame("GUITest");window.setContentPane(content);window.setSize(250,100);window.setLocation(100,100);window.setVisible(true); } } 6.5TimerandKeyboardEventsN oteveryevent isgeneratedbyanactiononthepartoftheuser.Eventscanal sobe (online) generatedbyobjectsaspartoftheirregularprogramming,a ndtheseeventscanbemonitored byotherobjectssothattheycantakeappropriateactionswh entheeventsoccur.Oneexample ofthisistheclass javax.swing.Timer .A Timer generateseventsatregularintervals.These eventscanbeusedtodriveananimationortoperformsomeoth ertaskatregularintervals. Wewillbeginthissectionwithalookattimereventsandanim ation.Wewillthenlookat anothertypeofbasicuser-generatedevent:the KeyEvent sthataregeneratedwhentheuser typesonthekeyboard.Theexampleattheendofthesectionus esbothatimerandkeyboard eventstoimplementasimplegame.6.5.1TimersandAnimationAnobjectbelongingtotheclass javax.swing.Timer existsonlytogenerateevents.A Timer bydefault,generatesasequenceofeventswithaxeddelayb etweeneacheventandthenext. (Itisalsopossibletoseta Timer toemitasingleeventafteraspeciedtimedelay;inthatcas e, thetimerisbeingusedasan\alarm.")Eacheventbelongstot heclass ActionEvent .Anobject thatistolistenfortheeventsmustimplementtheinterface ActionListener ,whichdenesjust onemethod: publicvoidactionPerformed(ActionEventevt) Tousea Timer ,youmustcreateanobjectthatimplementsthe ActionListener interface.That is,theobjectmustbelongtoaclassthatisdeclaredto\ implementActionListener ",and thatclassmustdenethe actionPerformed method.Then,iftheobjectissettolistenfor <br /> <br /> PAGE 277<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 263 eventsfromthetimer,thecodeinthelistener's actionPerformed methodwillbeexecuted everytimethetimergeneratesanevent. Sincethereisnopointtohavingatimerwithouthavingalist enertorespondtoitsevents, theactionlistenerforatimerisspeciedasaparameterint hetimer'sconstructor.Thetime delaybetweentimereventsisalsospeciedintheconstruct or.If timer isavariableoftype Timer ,thenthestatement timer=newTimer(millisDelay,listener); createsatimerwithadelayof millisDelay millisecondsbetweenevents(where1000millisecondsequalonesecond).Eventsfromthetimeraresentt othe listener .( millisDelay mustbeoftype int ,and listener mustbeoftype ActionListener .)Notethatatimerisnot guaranteedtodelivereventsatpreciselyregularinterval s.Ifthecomputerisbusywithsome othertask,aneventmightbedelayedorevendroppedaltoget her. Atimerdoesnotautomaticallystartgeneratingeventswhen thetimerobjectiscreated. The start() methodinthetimermustbecalledtotellthetimertostartge neratingevents. Thetimer's stop() methodcanbeusedtoturnthestreamofeventso|itcanberes tarted bycalling start() again. Oneapplicationoftimersiscomputeranimation.Acomputer animationisjustasequence ofstillimages,presentedtotheuseroneaftertheother.If thetimebetweenimagesisshort, andifthechangefromoneimagetoanotherisnottoogreat,th entheuserperceivescontinuous motion.TheeasiestwaytodoanimationinJavaistousea Timer todrivetheanimation.Each timethetimergeneratesanevent,thenextframeoftheanima tioniscomputedanddrawnon thescreen|thecodethatimplementsthisgoesinthe actionPerformed methodofanobject thatlistensforeventsfromthetimer. Ourrstexampleofusingatimerisnotexactlyananimation, butitdoesdisplayanew imageforeachtimerevent.Theprogramshowsrandomlygener atedimagesthatvaguely resembleworksofabstractart.Infact,theprogramdrawsan ewrandomimageeverytime its paintComponent() methodiscalled,andtheresponsetoatimereventissimplyt ocall repaint() ,whichinturntriggersacallto paintComponent .Theworkoftheprogramisdone inasubclassof JPanel ,whichstartslikethis: importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassRandomArtPanelextendsJPanel{ /** *ARepaintActionobjectcallstherepaintmethodofthispan eleach *timeitsactionPerformed()methodiscalled.Anobjectoft his *typeisusedasanactionlistenerforaTimerthatgenerates an *ActionEventeveryfourseconds.Theresultisthatthepane lis *redrawneveryfourseconds.*/ privateclassRepaintActionimplementsActionListener{ publicvoidactionPerformed(ActionEventevt){ repaint();//Calltherepaint()methodinthepanelclass. } } <br /> <br /> PAGE 278<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 264 /** *Theconstructorcreatesatimerwithadelaytimeoffoursec onds *(4000milliseconds),andwithaRepaintActionobjectasit s *ActionListener.Italsostartsthetimerrunning.*/ publicRandomArtPanel(){ RepaintActionaction=newRepaintAction();Timertimer=newTimer(4000,action);timer.start(); }/** *ThepaintComponent()methodfillsthepanelwitharandoms hadeof *grayandthendrawsoneofthreetypesofrandom"art".Thety pe *ofarttobedrawnischosenatrandom.*/ publicvoidpaintComponent(Graphicsg){ ..//Therestoftheclassisomitted. Youcanndthefullsourcecodeforthisclassinthele RandomArtPanel.java ;Anapplication versionoftheprogramis RandomArt.java ,whiletheappletversionis RandomArtApplet.java Youcanseetheappletversionintheon-lineversionofthiss ection. Laterinthissection,wewilluseatimertodrivetheanimati oninasimplecomputergame. 6.5.2KeyboardEventsInJava,useractionsbecomeeventsinaprogram.Theseevent sareassociatedwithGUI components.Whentheuserpressesabuttononthemouse,thee ventthatisgeneratedis associatedwiththecomponentthatcontainsthemousecurso r.Whataboutkeyboardevents? Whentheuserpressesakey,whatcomponentisassociatedwit hthekeyeventthatisgenerated? AGUIusestheideaof inputfocus todeterminethecomponentassociatedwithkeyboard events.Atanygiventime,exactlyoneinterfaceelementont hescreenhastheinputfocus, andthatiswhereallkeyboardeventsaredirected.Iftheint erfaceelementhappenstobea Javacomponent,thentheinformationaboutthekeyboardeve ntbecomesaJavaobjectoftype KeyEvent ,anditisdeliveredtoanylistenerobjectsthatarelisteni ngfor KeyEvents associated withthatcomponent.Thenecessityofmanaginginputfocusa ddsanextratwisttoworking withkeyboardevents. It'sagoodideatogivetheusersomevisualfeedbackaboutwh ichcomponenthastheinput focus.Forexample,ifthecomponentisthetypingareaofawo rd-processor,thefeedbackis usuallyintheformofablinkingtextcursor.Anothercommon visualclueistodrawabrightly coloredborderaroundtheedgeofacomponentwhenithasthei nputfocus,asIdointhe examplesgivenlaterinthissection. Acomponentthatwantstohavetheinputfocuscancallthemet hod requestFocus() whichisdenedinthe Component class.Callingthismethoddoesnotabsolutelyguarantee thatthecomponentwillactuallygettheinputfocus.Severa lcomponentsmightrequestthe focus;onlyonewillgetit.Thismethodshouldonlybeusedin certaincircumstancesinany case,sinceitcanbearudesurprisetotheusertohavethefoc ussuddenlypulledawayfrom acomponentthattheuserisworkingwith.Inatypicaluserin terface,theusercanchooseto <br /> <br /> PAGE 279<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 265 givethefocustoacomponentbyclickingonthatcomponentwi ththemouse.Andpressing thetabkeywilloftenmovethefocusfromonecomponenttoano ther. Somecomponentsdonotautomaticallyrequesttheinputfocu swhentheuserclickson them.Tosolvethisproblem,aprogramhastoregisteramouse listenerwiththecomponenttodetectuserclicks.Inresponsetoauserclick,the mousePressed() methodshould call requestFocus() forthecomponent.Thisistrue,inparticular,forthecompo nentsthat areusedasdrawingsurfacesintheexamplesinthischapter. Thesecomponentsaredened assubclassesof JPanel ,and JPanel objectsdonotreceivetheinputfocusautomatically.If youwanttobeabletousethekeyboardtointeractwitha JPanel named drawingSurface youhavetoregisteralistenertolistenformouseeventsont he drawingSurface andcall drawingSurface.requestFocus() inthe mousePressed() methodofthelistenerobject. Asourrstexampleofprocessingkeyevents,welookatasimp leprograminwhichthe usermovesasquareup,down,left,andrightbypressingarro wkeys.Whentheuserhitsthe 'R','G','B',or'K'key,thecolorofthesquareissettored, green,blue,orblack,respectively. Ofcourse,noneofthesekeyeventsaredeliveredtotheprogr amunlessithastheinputfocus. Thepanelintheprogramchangesitsappearancewhenithasth einputfocus:Whenitdoes, acyan-coloredborderisdrawnaroundthepanel;whenitdoes not,agray-coloredborderis drawn.Also,thepaneldisplaysadierentmessageineachca se.Ifthepaneldoesnothave theinputfocus,theusercangivetheinputfocustothepanel byclickingonit.Thecomplete sourcecodeforthisexamplecanbefoundinthele KeyboardAndFocusDemo.java .Iwill discusssomeaspectsofitbelow.Afterreadingthissection ,youshouldbeabletounderstand thesourcecodeinitsentirety.Hereiswhattheprogramlook slikeinitsfocussedstate: InJava,keyboardeventobjectsbelongtoaclasscalled KeyEvent .Anobjectthatneedsto listenfor KeyEvent smustimplementtheinterfacenamed KeyListener .Furthermore,theobject mustberegisteredwithacomponentbycallingthecomponent 's addKeyListener() method. Theregistrationisdonewiththecommand\ component.addKeyListener(listener); "where listener istheobjectthatistolistenforkeyevents,and component istheobjectthatwill generatethekeyevents(whenithastheinputfocus).Itispo ssiblefor component and listener tobethesameobject.Allthisis,ofcourse,directlyanalog oustowhatyoulearnedaboutmouse eventsintheprevioussection.The KeyListener interfacedenesthefollowingmethods,which mustbeincludedinanyclassthatimplements KeyListener : publicvoidkeyPressed(KeyEventevt);publicvoidkeyReleased(KeyEventevt);publicvoidkeyTyped(KeyEventevt); Javamakesacarefuldistinctionbetween thekeysthatyoupress and thecharactersthat youtype .Therearelotsofkeysonakeyboard:letterkeys,numberkey s,modierkeyssuch asControlandShift,arrowkeys,pageupandpagedownkeys,k eypadkeys,functionkeys.In <br /> <br /> PAGE 280<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 266 manycases,pressingakeydoesnottypeacharacter.Ontheot herhand,typingacharacter sometimesinvolvespressingseveralkeys.Forexample,tot ypeanuppercase'A',youhaveto presstheShiftkeyandthenpresstheAkeybeforereleasingt heShiftkey.OnmyMacintosh computer,Icantypeanaccentede,byholdingdowntheOption key,pressingtheEkey, releasingtheOptionkey,andpressingEagain.Onlyonechar acterwastyped,butIhadto performthreekey-pressesandIhadtoreleaseakeyattherig httime.InJava,thereare threetypesof KeyEvent .Thetypescorrespondtopressingakey,releasingakey,and typing acharacter.The keyPressed methodiscalledwhentheuserpressesakey,the keyReleased methodiscalledwhentheuserreleasesakey,andthe keyTyped methodiscalledwhentheuser typesacharacter.Notethatoneuseraction,suchaspressin gtheEkey,canberesponsiblefor twoevents,a keyPressed eventanda keyTyped event.Typinganuppercase'A'cangenerate two keyPressed ,two keyReleased ,andone keyTyped event. Usually,itisbettertothinkintermsoftwoseparatestream sofevents,oneconsistingof keyPressed and keyReleased eventsandtheotherconsistingof keyTyped events.Forsome applications,youwanttomonitortherststream;forother applications,youwanttomonitor thesecondone.Ofcourse,theinformationinthe keyTyped streamcouldbeextractedfrom the keyPressed/keyReleased stream,butitwouldbedicult(andalsosystem-dependent tosomeextent).Someuseractions,suchaspressingtheShif tkey,canonlybedetectedas keyPressed events.Ihaveasolitairegameonmycomputerthathilitesev erycardthatcanbe moved,whenIholddowntheShiftkey.Youcoulddosomethingl ikethatinJavabyhiliting thecardswhentheShiftkeyispressedandremovingthehilit ewhentheShiftkeyisreleased. Thereisonemorecomplication.Usually,whenyouholddowna keyonthekeyboard,that keywill auto-repeat .Thismeansthatitwillgeneratemultiple keyPressed events,aslong asitishelddown.Itcanalsogeneratemultiple keyTyped events.Forthemostpart,thiswill notaectyourprogramming,butyoushouldnotexpectevery keyPressed eventtohavea corresponding keyReleased event. Everykeyonthekeyboardhasanintegercodenumber.(Actual ly,thisisonlytrue forkeysthatJavaknowsabout.Manykeyboardshaveextrakey sthatcan'tbeusedwith Java.)Whenthe keyPressed or keyReleased methodiscalled,theparameter, evt ,contains thecodeofthekeythatwaspressedorreleased.Thecodecanb eobtainedbycallingthe function evt.getKeyCode() .Ratherthanaskingyoutomemorizeatableofcodenumbers, Javaprovidesanamedconstantforeachkey.Theseconstants aredenedinthe KeyEvent class.Forexampletheconstantfortheshiftkeyis KeyEvent.VK SHIFT .Ifyouwanttotest whetherthekeythattheuserpressedistheShiftkey,youcou ldsay\ if(evt.getKeyCode() ==KeyEvent.VK SHIFT) ".Thekeycodesforthefourarrowkeysare KeyEvent.VK LEFT KeyEvent.VK RIGHT KeyEvent.VK UP ,and KeyEvent.VK DOWN .Otherkeyshavesimilarcodes. (The\VK"standsfor\VirtualKeyboard".Inreality,diere ntkeyboardsusedierentkey codes,butJavatranslatestheactualcodesfromthekeyboar dintoitsown\virtual"codes. Yourprogramonlyseesthesevirtualkeycodes,soitwillwor kwithvariouskeyboardson variousplatformswithoutmodication.) Inthecaseofa keyTyped event,youwanttoknowwhichcharacterwastyped.This informationcanbeobtainedfromtheparameter, evt ,inthe keyTyped methodbycalling thefunction evt.getKeyChar() .Thisfunctionreturnsavalueoftype char representingthe characterthatwastyped. Inthe KeyboardAndFocusDemo program,Iusethe keyPressed routinetorespondwhenthe userpressesoneofthearrowkeys.Theappletincludesinsta ncevariables, squareLeft and squareTop ,thatgivethepositionoftheupperleftcornerofthemovabl esquare.Whenthe <br /> <br /> PAGE 281<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 267 userpressesoneofthearrowkeys,the keyPressed routinemodiestheappropriateinstance variableandcalls repaint() toredrawthepanelwiththesquareinitsnewposition.Note thatthevaluesof squareLeft and squareTop arerestrictedsothatthesquarenevermoves outsidethewhiteareaofthepanel: /** *Thisiscalledeachtimetheuserpressesakeywhilethepane lhas *theinputfocus.Ifthekeypressedwasoneofthearrowkeys,*thesquareismoved(exceptthatitisnotallowedtomoveoff the *edgeofthepanel,allowingfora3-pixelborder).*/ publicvoidkeyPressed(KeyEventevt){ intkey=evt.getKeyCode();//keyboardcodeforthepressed key if(key==KeyEvent.VK LEFT){//movethesquareleft squareLeft-=8;if(squareLeft<3) squareLeft=3; repaint(); }elseif(key==KeyEvent.VK RIGHT){//movethesquareright squareLeft+=8;if(squareLeft>getWidth()-3-SQUARE SIZE) squareLeft=getWidth()-3-SQUARE SIZE; repaint(); }elseif(key==KeyEvent.VK UP){//movethesqureup squareTop-=8;if(squareTop<3) squareTop=3; repaint(); }elseif(key==KeyEvent.VK DOWN){//movethesquaredown squareTop+=8;if(squareTop>getHeight()-3-SQUARE SIZE) squareTop=getHeight()-3-SQUARE SIZE; repaint(); } }//endkeyPressed() Colorchanges|whichhappenwhentheusertypesthecharacte rs'R','G','B',and'K',or thelowercaseequivalents|arehandledinthe keyTyped method.Iwon'tincludeithere,since itissosimilartothe keyPressed method.Finally,tocompletethe KeyListener interface,the keyReleased methodmustbedened.Inthesampleprogram,thebodyofthis methodis emptysincetheappletdoesnothinginresponseto keyReleased events. 6.5.3FocusEventsIfacomponentistochangeitsappearancewhenithastheinpu tfocus,itneedssomewayto knowwhenithasthefocus.InJava,objectsarenotiedabout changesofinputfocusbyevents oftype FocusEvent .Anobjectthatwantstobenotiedofchangesinfocuscanimp lementthe FocusListener interface.Thisinterfacedeclarestwomethods: <br /> <br /> PAGE 282<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 268 publicvoidfocusGained(FocusEventevt);publicvoidfocusLost(FocusEventevt); Furthermore,the addFocusListener() methodmustbeusedtosetupalistenerforthe focusevents.Whenacomponentgetstheinputfocus,itcalls the focusGained() methodof anyobjectthathasbeenregisteredwiththatcomponentasa FocusListener .Whenitlosesthe focus,itcallsthelistener's focusLost() method.Sometimes,itisthecomponentitselfthat listensforfocusevents. Inthesample KeyboardAndFocusDemo program,theresponsetoafocuseventissimply toredrawthepanel.The paintComponent() methodcheckswhetherthepanelhastheinput focusbycallingthe boolean -valuedfunction hasFocus() ,whichisdenedinthe Component class,anditdrawsadierentpicturedependingonwhethero rnotthepanelhastheinput focus.Thenetresultisthattheappearanceofthepanelchan geswhenthepanelgainsorloses focus.Themethodsfromthe FocusListener interfacearedenedsimplyas: publicvoidfocusGained(FocusEventevt){ //Thepanelnowhastheinputfocus. repaint();//willredrawwithanewmessageandacyanborder }publicvoidfocusLost(FocusEventevt){ //Thepanelhasnowlosttheinputfocus. repaint();//willredrawwithanewmessageandagrayborder } Theotheraspectofhandlingfocusistomakesurethatthe panel getsthefocuswhenthe userclicksonit.Todothis,thepanelimplementsthe MouseListener interfaceandlistensfor mouseeventsonitself.Itdenesa mousePressed routinethatasksthattheinputfocusbe giventothepanel: publicvoidmousePressed(MouseEventevt){ requestFocus(); } Theotherfourmethodsofthe mouseListener interfacearedenedtobeempty.Notethatthe panelimplementsthreedierentlistenerinterfaces, KeyListener FocusListener ,and MouseListener ,andtheconstructorinthepanelclassregistersitselftol istenforallthreetypesofevents withthestatements: addKeyListener(this);addFocusListener(this);addMouseListener(this); Thereare,ofcourse,otherwaystoorganizethisexample.It wouldbepossible,forexample,to useanestedclasstodenethelisteningobject.Oranonymou sclassescouldbeusedtodene separatelisteningobjectsforeachtypeofevent.Inmynext example,Iwilltakethelatter approach.6.5.4StateMachinesTheinformationstoredinanobject'sinstancevariablesis saidtorepresentthe state ofthat object.Whenoneoftheobject'smethodsiscalled,theactio ntakenbytheobjectcandepend onitsstate.(Or,intheterminologywehavebeenusing,thed enitionofthemethodcanlook attheinstancevariablestodecidewhattodo.)Furthermore ,thestatecanchange.(That <br /> <br /> PAGE 283<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 269 is,thedenitionofthemethodcanassignnewvaluestothein stancevariables.)Incomputer science,thereistheideaofa statemachine ,whichisjustsomethingthathasastateand canchangestateinresponsetoeventsorinputs.Therespons eofastatemachinetoanevent orinputdependsonwhatstateit'sin.Anobjectisakindofst atemachine.Sometimes,this pointofviewcanbeveryusefulindesigningclasses. Thestatemachinepointofviewcanbeespeciallyusefulinth etypeofevent-oriented programmingthatisrequiredbygraphicaluserinterfaces. WhendesigningaGUIprogram, youcanaskyourself:WhatinformationaboutstatedoIneedt okeeptrackof?Whatevents canchangethestateoftheprogram?Howwillmyresponsetoag iveneventdependonthe currentstate?ShouldtheappearanceoftheGUIbechangedto rerectachangeinstate?How shouldthe paintComponent() methodtakethestateintoaccount?Allthisisanalternativ eto thetop-down,step-wise-renementstyleofprogramdesign ,whichdoesnotapplytotheoverall designofanevent-orientedprogram. Inthe KeyboardAndFocusDemo program,shownabove,thestateoftheprogramisrecorded intheinstancevariables squareColor squareLeft ,and squareTop .Thesestatevariablesare usedinthe paintComponent() methodtodecidehowtodrawthepanel.Theyarechangedin thetwokey-event-handlingmethods. Intherestofthissection,we'lllookatanotherexample,wh erethestateplaysaneven biggerrole.Inthisexample,theuserplaysasimplearcadestylegamebypressingthearrow keys.Themainpaneloftheprogramisdenedinthesoucecode le SubKillerPanel.java Anappletthatusesthispanelcanbefoundin SubKillerApplet.java ,whilethestand-alone applicationversionis SubKiller.java .Youcantryouttheappletintheon-lineversionofthis section.Hereiswhatitlookslike: Youhavetoclickonthepaneltogiveittheinputfocus.Thepr ogramshowsablack \submarine"nearthebottomofthepanel.Whenthepanelhast heinputfocus,thissubmarine movesbackandfortherraticallynearthebottom.Neartheto p,thereisablue\boat".You canmovethisboatbackandforthbypressingtheleftandrigh tarrowkeys.Attachedtothe boatisared\bomb"(or\depthcharge").Youcandropthebomb byhittingthedownarrow key.Theobjectiveistoblowupthesubmarinebyhittingitwi ththebomb.Ifthebombfalls othebottomofthescreen,yougetanewone.Ifthesubmarine explodes,anewsubiscreated andyougetanewbomb.Tryit!Makesuretohitthesubatleasto nce,soyoucanseethe explosion. Let'sthinkabouthowthisprogramcanbeprogrammed.Firsto fall,sincewearedoing object-orientedprogramming,Idecidedtorepresentthebo at,thedepthcharge,andthesubmarineasobjects.Eachoftheseobjectsisdenedbyasepara tenestedclassinsidethemain panelclass,andeachobjecthasitsownstatewhichisrepres entedbytheinstancevariablesin <br /> <br /> PAGE 284<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 270 thecorrespondingclass.Iusevariables boat bomb ,and sub inthepanelclasstorefertothe boat,bomb,andsubmarineobjects. Now,whatconstitutesthe\state"oftheprogram?Thatis,wh atthingschangefromtime totimeandaecttheappearanceorbehavioroftheprogram?O fcourse,thestateincludes thepositionsoftheboat,submarine,andbomb,soIneedvari ablestostorethepositions. Anythingelse,possiblylessobvious?Well,sometimestheb ombisfalling,andsometimesit's not.Thatisadierenceinstate.Sincetherearetwopossibi lities,Irepresentthisaspectofthe statewithabooleanvariableinthe bomb object, bomb.isFalling .Sometimesthesubmarineis movingleftandsometimesitismovingright.Thedierencei srepresentedbyanotherboolean variable, sub.isMovingLeft .Sometimes,thesubisexploding.Thisisalsopartofthesta te, anditisrepresentedbyabooleanvariable, sub.isExploding .However,theexplosionsrequire alittlemorethought.Anexplosionissomethingthattakesp laceoveraseriesofframes.While anexplosionisinprogress,thesublooksdierentineachfr ame,asthesizeoftheexplosion increases.Also,Ineedtoknowwhentheexplosionisoversot hatIcangobacktomovingand drawingthesubasusual.So,Iuseanintegervariable, sub.explosionFrameNumber torecord howmanyframeshavebeendrawnsincetheexplosionstarted; thevalueofthisvariableisused onlywhenanexplosionisinprogress. Howandwhendothevaluesofthesestatevariableschange?So meofthemseemtochange ontheirown:Forexample,asthesubmovesleftandright,the statevariablesthethatspecify itspositionarechanging.Ofcourse,thesevariablesarech angingbecauseofananimation,and thatanimationisdrivenbyatimer.Eachtimeaneventisgene ratedbythetimer,someofthe statevariableshavetochangetogetreadyforthenextframe oftheanimation.Thechanges aremadebytheactionlistenerthatlistensforeventsfromt hetimer.The boat bomb ,and sub objectseachcontainan updateForNextFrame() methodthatupdatesthestatevariables oftheobjecttogetreadyforthenextframeoftheanimation. Theactionlistenerforthetimer callsthesemethodswiththestatements boat.updateForNewFrame();bomb.updateForNewFrame();sub.updateForNewFrame(); Theactionlisteneralsocalls repaint() ,sothatthepanelwillberedrawntorerectitsnew state.Thereareseveralstatevariablesthatchangeinthes eupdatemethods,inadditionto thepositionofthesub:Ifthebombisfalling,thenitsy-coo rdinateincreasesfromoneframe tothenext.Ifthebombhitsthesub,thenthe isExploding variableofthesubchangesto true,andthe isFalling variableofthebombbecomes false .The isFalling variablealso becomesfalsewhenthebombfallsothebottomofthescreen. Ifthesubisexploding,then its explosionFrameNumber increasesfromoneframetothenext,andwhenitreachesacer tain value,theexplosionendsand isExploding isresettofalse.Atrandomtimes,thesubswitches betweenmovingtotheleftandmovingtotheright.Itsdirect ionofmotionisrecordedinthe thesub's isMovingLeft variable.Thesub's updateForNewFrame() methodincludesthelines if(Math.random()<0.04) isMovingLeft=!isMovingLeft; Thereisa1in25chancethat Math.random() willbelessthan0.04,sothestatement \ isMovingLeft=!isMovingLeft "isexecutedinoneineverytwenty-veframes,onthe average.Theeectofthisstatementistoreversethevalueo f isMovingLeft ,fromfalsetotrue orfromtruetofalse.Thatis,thedirectionofmotionofthes ubisreversed. Inaddtiontochangesinstatethattakeplacefromoneframet othenext,afewstate variableschangewhentheuserpressescertainkeys.Inthep rogram,thisischeckedina <br /> <br /> PAGE 285<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 271 methodthatrespondstouserkeystrokes.Iftheuserpresses theleftorrightarrowkey,the positionoftheboatischanged.Iftheuserpressesthedowna rrowkey,thebombchanges fromnot-fallingtofalling.Thisiscodedinthe keyPressed() methodofa KeyListener thatis registeredtolistenforkeyeventsonthepanel;thatmethod readsasfollows: publicvoidkeyPressed(KeyEventevt){ intcode=evt.getKeyCode();//whichkeywaspressed.if(code==KeyEvent.VK LEFT){ //Movetheboatleft.(Ifthismovestheboatoutoftheframe, its //positionwillbeadjustedintheboat.updateForNewFrame ()method.) boat.centerX-=15; }elseif(code==KeyEvent.VK RIGHT){ //Movetheboatright.(Ifthismovesboatoutoftheframe,it s //positionwillbeadjustedintheboat.updateForNewFrame ()method.) boat.centerX+=15; }elseif(code==KeyEvent.VK DOWN){ //Startthebombfalling,itisisnotalreadyfalling. if(bomb.isFalling==false) bomb.isFalling=true; } } Notethatit'snotnecessarytocall repaint() whenthestatechanges,sincethispanelshows ananimationthatisconstantlybeingredrawnanyway.Anych angesinthestatewillbecome visibletotheuserassoonasthenextframeisdrawn.Atsomep ointintheprogram,Ihave tomakesurethattheuserdoesnotmovetheboatothescreen. Icouldhavedonethisin keyPressed() ,butIchoosetocheckforthisinanotherroutine,intheboat object. Iencourageyoutoreadthesourcecodein SubKillerPanel.java .Althoughafewpointsare tricky,youshouldwithsomeeortbeabletoreadandunderst andtheentireprogram.Tryto understandtheprogramintermsofstatemachines.Notehowt hestateofeachofthethree objectsintheprogramchangesinresponsetoeventsfromthe timerandfromtheuser. Youshouldalsonotethattheprogramusesfourlisteners,to respondtoactioneventsfrom thetimer,keyeventsfromtheuser,focusevents,andmousee vents.(Themouseisusedonlyto requesttheinputfocuswhentheuserclicksthepanel.)Thet imerrunsonlywhenthepanelhas theinputfocus;thisisprogrammedbyhavingthefocusliste nerstartthetimerwhenthepanel gainstheinputfocusandstopthetimerwhenthepanellosest heinputfocus.Allfourlisteners arecreatedintheconstructorofthe SubKillerPanel classusinganonymousinnerclasses.(See Subsection6.4.5 .) Whileit'snotatallsophisticatedasarcadegamesgo,theSu bKillergamedoesusesome interestingprogramming.Anditnicelyillustrateshowtoa pplystate-machinethinkingin event-orientedprogramming.6.6BasicComponentsI nprecedingsections ,you'veseenhowtouseagraphicscontexttodrawonthescree n (online) andhowtohandlemouseeventsandkeyboardevents.Inonesen se,that'sallthereisto GUIprogramming.Ifyou'rewillingtoprogramallthedrawin gandhandleallthemouseand keyboardevents,youhavenothingmoretolearn.However,yo uwouldeitherbedoingalot <br /> <br /> PAGE 286<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 272 moreworkthanyouneedtodo,oryouwouldbelimitingyoursel ftoverysimpleuserinterfaces. AtypicaluserinterfaceusesstandardGUIcomponentssucha sbuttons,scrollbars,text-input boxes,andmenus.Thesecomponentshavealreadybeenwritte nforyou,soyoudon'thaveto duplicatetheworkinvolvedindevelopingthem.Theyknowho wtodrawthemselves,andthey canhandlethedetailsofprocessingthemouseandkeyboarde ventsthatconcernthem. Consideroneofthesimplestuserinterfacecomponents,apu shbutton.Thebuttonhasa border,anditdisplayssometext.Thistextcanbechanged.S ometimesthebuttonisdisabled, sothatclickingonitdoesn'thaveanyeect.Whenitisdisab led,itsappearancechanges.When theuserclicksonthepushbutton,thebuttonchangesappear ancewhilethemousebuttonis pressedandchangesbackwhenthemousebuttonisreleased.I nfact,it'smorecomplicated thanthat.Iftheusermovesthemouseoutsidethepushbutton beforereleasingthemouse button,thebuttonchangestoitsregularappearance.Toimp lementthis,itisnecessaryto respondtomouseexitormousedragevents.Furthermore,onm anyplatforms,abuttoncan receivetheinputfocus.Thebuttonchangesappearancewhen ithasthefocus.Ifthebutton hasthefocusandtheuserpressesthespacebar,thebuttonis triggered.Thismeansthatthe buttonmustrespondtokeyboardandfocuseventsaswell. Fortunately,youdon'thavetoprogram any ofthis,providedyouuseanobjectbelonging tothestandardclass javax.swing.JButton .A JButton objectdrawsitselfandprocesses mouse,keyboard,andfocuseventsonitsown.Youonlyhearfr omthe Button whenthe usertriggersitbyclickingonitorpressingthespacebarwh ilethebuttonhastheinput focus.Whenthishappens,the JButton objectcreatesaneventobjectbelongingtotheclass java.awt.event.ActionEvent .Theeventobjectissenttoanyregisteredlistenerstotell them thatthebuttonhasbeenpushed.Yourprogramgetsonlythein formationitneeds|thefact thatabuttonwaspushed. ThestandardcomponentsthataredenedaspartoftheSwingg raphicaluserinterface APIaredenedbysubclassesoftheclass JComponent ,whichisitselfasubclassof Component (Notethatthisincludesthe JPanel classthatwehavealreadybeenworkingwithextensively.) Manyusefulmethodsaredenedinthe Component and JComponent classesandsocanbeused withanySwingcomponent.Webeginbylookingatafewofthese methods.Supposethat comp isavariablethatreferstosome JComponent .Thenthefollowingmethodscanbeused: comp.getWidth() and comp.getHeight() arefunctionsthatgivethecurrentsizeofthe component,inpixels.Onewarning:Whenacomponentisrstc reated,itssizeiszero. Thesizewillbesetlater,probablybyalayoutmanager.Acom monmistakeistocheck thesizeofacomponentbeforethatsizehasbeenset,suchasi naconstructor. comp.setEnabled(true) and comp.setEnabled(false) canbeusedtoenableanddisable thecomponent.Whenacomponentisdisabled,itsappearance mightchange,andtheuser cannotdoanythingwithit.Thereisaboolean-valuedfuncti on, comp.isEnabled() that youcancalltodiscoverwhetherthecomponentisenabled. comp.setVisible(true) and comp.setVisible(false) canbecalledtohideorshowthe component. comp.setFont(font) setsthefontthatisusedfortextdisplayedonthecomponent .See Subsection6.3.3 foradiscussionoffonts. comp.setBackground(color) and comp.setForeground(color) setthebackgroundand foregroundcolorsforthecomponent.See Subsection6.3.2 <br /> <br /> PAGE 287<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 273 comp.setOpaque(true) tellsthecomponentthattheareaoccupiedbythecomponent shouldbelledwiththecomponent'sbackgroundcolorbefor ethecontentofthecomponentispainted.Bydefault,only JLabels arenon-opaque.Anon-opaque,or\transparent",componentignoresitsbackgroundcolorandsimply paintsitscontentoverthe contentofitscontainer.Thisusuallymeansthatitinherit sthebackgroundcolorfromits container. comp.setToolTipText(string) setsthespeciedstringasa\tooltip"forthecomponent. Thetooltipisdisplayedifthemousecursorisinthecompone ntandthemouseisnot movedforafewseconds.Thetooltipshouldgivesomeinforma tionaboutthemeaning ofthecomponentorhowtouseit. comp.setPreferredSize(size) setsthesizeatwhichthecomponentshouldbedisplayed, ifpossible.Theparameterisoftype java.awt.Dimension ,whereanobjectoftype Dimension hastwopublicinteger-valuedinstancevariables, width and height .Acalltothis methodusuallylookssomethinglike\ setPreferredSize(newDimension(100,50)) ". Thepreferredsizeisusedasahintbylayoutmanagers,butwi llnotberespectedinall cases.Standardcomponentsgenerallycomputeacorrectpre ferredsizeautomatically,but itcanbeusefultosetitinsomecases.Forexample,ifyouuse a JPanel asadrawing surface,itmightbeagoodideatosetapreferredsizeforit. Notethatusinganycomponentisamulti-stepprocess.Theco mponentobjectmustbe createdwithaconstructor.Itmustbeaddedtoacontainer.I nmanycases,alistenermust beregisteredtorespondtoeventsfromthecomponent.Andin somecases,areferencetothe componentmustbesavedinaninstancevariablesothattheco mponentcanbemanipulatedby theprogramafterithasbeencreated.Inthissection,wewil llookatafewofthebasicstandard componentsthatareavailableinSwing.Inthenextsectionw ewillconsidertheproblemof layingoutcomponentsincontainers.6.6.1JButtonAnobjectofclass JButton isapushbuttonthattheusercanclicktotriggersomeaction You'vealreadyseenbuttonsusedin Section6.1 and Section6.2 ,butweconsiderthemin muchmoredetailhere.Touseanycomponenteectively,ther eareseveralaspectsofthe correspondingclassthatyoushouldbefamiliarwith.For JButton ,asanexample,Ilistthese aspectsexplicitely: Constructors :The JButton classhasaconstructorthattakesastringasaparameter. Thisstringbecomesthetextdisplayedonthebutton.Forexa mple: stopGoButton= newJButton("Go") .Thiscreatesabuttonobjectthatwilldisplaythetext,\Go "(but rememberthatthebuttonmuststillbeaddedtoacontainerbe foreitcanappearonthe screen). Events :Whentheuserclicksonabutton,thebuttongeneratesaneve ntoftype ActionEvent .Thiseventissenttoanylistenerthathasbeenregisteredw iththebuttonasan ActionListener Listeners :Anobjectthatwantstohandleeventsgeneratedbybuttonsm ustimplementthe ActionListener interface.Thisinterfacedenesjustonemethod,\ publicvoid actionPerformed(ActionEventevt) ",whichiscalledtonotifytheobjectofanaction event. <br /> <br /> PAGE 288<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 274 RegistrationofListeners :Inordertoactuallyreceivenoticationofaneventfroma button,an ActionListener mustberegisteredwiththebutton.Thisisdonewiththebutton's addActionListener() method.Forexample: stopGoButton.addActionListener( buttonHandler); Eventmethods :When actionPerformed(evt) iscalledbythebutton,theparameter, evt ,containsinformationabouttheevent.Thisinformationca nberetrievedbycalling methodsinthe ActionEvent class.Inparticular, evt.getActionCommand() returnsa String givingthecommandassociatedwiththebutton.Bydefault,t hiscommandisthe textthatisdisplayedonthebutton,butitispossibletoset ittosomeotherstring.The method evt.getSource() returnsareferencetothe Object thatproducedtheevent, thatis,tothe JButton thatwaspressed.Thereturnvalueisoftype Object ,not JButton becauseothertypesofcomponentscanalsoproduce ActionEvent s. Componentmethods :Severalusefulmethodsaredenedinthe JButton class.For example, stopGoButton.setText("Stop") changesthetextdisplayedonthebuttonto \Stop".And stopGoButton.setActionCommand("sgb") changestheactioncommand associatedtothisbuttonforactionevents. Ofcourse, JButtons alsohaveallthegeneral Component methods,suchas setEnabled() and setFont() .The setEnabled() and setText() methodsofabuttonareparticularlyuseful forgivingtheuserinformationaboutwhatisgoingoninthep rogram.Adisabledbuttonis betterthanabuttonthatgivesanobnoxiouserrormessagesu chas\Sorry,youcan'tclickon menow!"6.6.2JLabelJLabel iscertainlythesimplesttypeofcomponent.Anobjectoftyp e JLabel existsjustto displayalineoftext.Thetextcannotbeeditedbytheuser,a lthoughitcanbechangedby yourprogram.Theconstructorfora JLabel speciesthetexttobedisplayed: JLabelmessage=newJLabel("HelloWorld!"); Thereisanotherconstructorthatspecieswhereinthelabe lthetextislocated,ifthereis extraspace.Thepossiblealignmentsaregivenbytheconsta nts JLabel.LEFT JLabel.CENTER and JLabel.RIGHT .Forexample, JLabelmessage=newJLabel("HelloWorld!",JLabel.CENTER ); createsalabelwhosetextiscenteredintheavailablespace .Youcanchangethetextdisplayed inalabelbycallingthelabel's setText() method: message.setText("GoodbyWorld!"); Sincethe JLabel classisasubclassof JComponent ,youcanusemethodssuchas setForeground() withlabels.Ifyouwantthebackgroundcolortohaveanyeec t,youshould call setOpaque(true) onthelabel,sinceotherwisethe JLabel mightnotllinitsbackground. Forexample: JLabelmessage=newJLabel("HelloWorld!",JLabel.CENTER ); message.setForeground(Color.RED);//Displayredtext.. message.setBackground(Color.BLACK);//onablackbackgr ound... message.setFont(newFont("Serif",Font.BOLD,18));//in abigboldfont. message.setOpaque(true);//Makesurebackgroundisfille din. <br /> <br /> PAGE 289<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 275 6.6.3JCheckBoxA JCheckBox isacomponentthathastwostates:selectedorunselected.T heusercanchange thestateofacheckboxbyclickingonit.Thestateofacheckb oxisrepresentedbya boolean valuethatis true iftheboxisselectedand false iftheboxisunselected.Acheckboxhasa label,whichisspeciedwhentheboxisconstructed: JCheckBoxshowTime=newJCheckBox("ShowCurrentTime"); Usually,it'stheuserwhosetsthestateofa JCheckBox ,butyoucanalsosetthestate inyourprogram.Thecurrentstateofacheckboxissetusingi ts setSelected(boolean) method.Forexample,ifyouwantthecheckbox showTime tobechecked,youwouldsay \ showTime.setSelected(true)" .Touncheckthebox,say\ showTime.setSelected(false)" Youcandeterminethecurrentstateofacheckboxbycallingi ts isSelected() method,which returnsabooleanvalue. Inmanycases,youdon'tneedtoworryabouteventsfromcheck boxes.Yourprogramcan justcheckthestatewheneveritneedstoknowitbycallingth e isSelected() method.However, acheckboxdoesgenerateaneventwhenitsstateischangedby theuser,andyoucandetectthis eventandrespondtoitifyouwantsomethingtohappenatthem omentthestatechanges.When thestateofacheckboxischangedbytheuser,itgeneratesan eventoftype ActionEvent .Ifyou wantsomethingtohappenwhentheuserchangesthestate,you mustregisteran ActionListener withthecheckboxbycallingits addActionListener() method.(Notethatifyouchange thestatebycallingthe setSelected() method,no ActionEvent isgenerated.However,there isanothermethodinthe JCheckBox class, doClick() ,whichsimulatesauserclickonthe checkboxanddoesgeneratean ActionEvent .) Whenhandlingan ActionEvent ,youcancall evt.getSource() inthe actionPerformed() methodtondoutwhichobjectgeneratedtheevent.(Ofcours e,ifyouareonlylisteningfor eventsfromonecomponent,youdon'tevenhavetodothis.)Th ereturnedvalueisoftype Object ,butyoucantype-castittoanothertypeifyouwant.Onceyou knowtheobject thatgeneratedtheevent,youcanasktheobjecttotellyouit scurrentstate.Forexample, ifyouknowthattheeventhadtocomefromoneoftwocheckboxe s, cb1 or cb2 ,thenyour actionPerformed() methodmightlooklikethis: publicvoidactionPerformed(ActionEventevt){ Objectsource=evt.getSource();if(source==cb1){ booleannewState=cb1.isSelected();...//respondtothechangeofstate }elseif(source==cb2){ booleannewState=cb2.isSelected();...//respondtothechangeofstate } } Alternatively,youcanuse evt.getActionCommand() toretrievetheactioncommandassociatedwiththesource.Fora JCheckBox ,theactioncommandis,bydefault,thelabelofthe checkbox. <br /> <br /> PAGE 290<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 276 6.6.4JTextFieldandJTextAreaThe JTextField and JTextArea classesrepresentcomponentsthatcontaintextthatcanbee dited bytheuser.A JTextField holdsasinglelineoftext,whilea JTextArea canholdmultiplelines. Itisalsopossibletoseta JTextField or JTextArea toberead-onlysothattheusercanreadthe textthatitcontainsbutcannoteditthetext.Bothclassesa resubclassesofanabstractclass, JTextComponent ,whichdenestheircommonproperties. JTextField and JTextArea havemanymethodsincommon.Theinstancemethod setText() whichtakesaparameteroftype String ,canbeusedtochangethetextthatisdisplayedinan inputcomponent.Thecontentsofthecomponentcanberetrie vedbycallingits getText() instancemethod,whichreturnsavalueoftype String .Ifyouwanttostoptheuserfrom modifyingthetext,youcancall setEditable(false) .Callthesamemethodwithaparameter of true tomaketheinputcomponentuser-editableagain. Theusercanonlytypeintoatextcomponentwhenithastheinp utfocus.Theusercan givetheinputfocustoatextcomponentbyclickingitwithth emouse,butsometimesitis usefultogivetheinputfocustoatexteldprogrammaticall y.Youcandothisbycallingits requestFocus() method.Forexample,whenIdiscoveranerrorintheuser'sin put,Iusually call requestFocus() onthetexteldthatcontainstheerror.Thishelpstheusers eewhere theerroroccurredandletstheuserstarttypingthecorrect ionimmediately. Bydefault,thereisnospacebetweenthetextinatextcompon entandtheedgeofthe component,whichusuallydoesn'tlookverygood.Youcanuse the setMargin() methodof thecomponenttoaddsomeblankspacebetweentheedgeofthec omponentandthetext. Thismethodtakesaparameteroftype java.awt.Insets whichcontainsfourintegerinstance variablesthatspecifythemarginsonthetop,left,bottom, andrightedgeofthecomponent. Forexample, textComponent.setMargin(newInsets(5,5,5,5)); addsave-pixelmarginbetweenthetextin textComponent andeachedgeofthecomponent. The JTextField classhasaconstructor publicJTextField(intcolumns) where columns isanintegerthatspeciesthenumberofcharactersthatsho uldbevisibleinthe texteld.Thisisusedtodeterminethepreferredwidthofth etexteld.(Becausecharacters canbeofdierentsizesandbecausethepreferredwidthisno talwaysrespected,theactual numberofcharactersvisibleinthetexteldmightnotbeequ alto columns .)Youdon'thave tospecifythenumberofcolumns;forexample,youmightuset hetexteldinacontextwhere itwillexpandtollwhateverspaceisavailable.Inthatcas e,youcanusetheconstructor JTextField() ,withnoparameters.Youcanalsousethefollowingconstruc tors,whichspecify theinitialcontentsofthetexteld: publicJTextField(Stringcontents);publicJTextField(Stringcontents,intcolumns); Theconstructorsfora JTextArea are publicJTextArea()publicJTextArea(introws,intcolumns)publicJTextArea(Stringcontents)publicJTextArea(Stringcontents,introws,intcolumns) <br /> <br /> PAGE 291<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 277 Theparameter rows specieshowmanylinesoftextshouldbevisibleinthetexta rea.This determinesthepreferredheightofthetextarea,justas columns determinesthepreferredwidth. However,thetextareacanactuallycontainanynumberoflin es;thetextareacanbescrolled toreveallinesthatarenotcurrentlyvisible.Itiscommont ousea JTextArea asthe CENTER componentofaBorderLayout.Inthatcase,itislessusefult ospecifythenumberoflinesand columns,sincetheTextAreawillexpandtollallthespacea vailableinthecenterareaofthe container. The JTextArea classaddsafewusefulmethodstothoseinheritedfrom JTextComponent Forexample,theinstancemethod append(moreText) ,where moreText isoftype String ,adds thespeciedtextattheendofthecurrentcontentofthetext area.(Whenusing append() or setText() toaddtexttoa JTextArea ,linebreakscanbeinsertedinthetextbyusingthe newlinecharacter, '\n' .)And setLineWrap(wrap) ,where wrap isoftype boolean ,tellswhat shouldhappenwhenalineoftextistoolongtobedisplayedin thetextarea.If wrap istrue, thenanylinethatistoolongwillbe\wrapped"ontothenextl ine;if wrap isfalse,thelinewill simplyextendoutsidethetextarea,andtheuserwillhaveto scrollthetextareahorizontally toseetheentireline.Thedefaultvalueof wrap isfalse. Sinceitmightbenecessarytoscrollatextareatoseeallthe textthatitcontains,youmight expectatextareatocomewithscrollbars.Unfortunately,t hisdoesnothappenautomatically. Togetscrollbarsforatextarea,youhavetoputthe JTextArea insideanothercomponent, calleda JScrollPane .Thiscanbedoneasfollows: JTextAreainputArea=newJTextArea();JScrollPanescroller=newJScrollPane(inputArea); Thescrollpaneprovidesscrollbarsthatcanbeusedtoscrol lthetextinthetextarea.The scrollbarswillappearonlywhenneeded,thatiswhenthesiz eofthetextexceedsthesizeof thetextarea.Notethatwhenyouwanttoputthetextareainto acontainer,youshouldadd thescrollpane,notthetextareaitself,tothecontainer. Whentheuseristypingina JTextField andpressesreturn,an ActionEvent isgenerated. Ifyouwanttorespondtosuchevents,youcanregisteran ActionListener withthetexteld, usingthetexteld's addActionListener() method.(Sincea JTextArea cancontainmultiple linesoftext,pressingreturninatextareadoesnotgenerat eanevent;issimplybeginsanew lineoftext.) JTextField hasasubclass, JPasswordField ,whichisidenticalexceptthatitdoesnotreveal thetextthatitcontains.Thecharactersina JPasswordField arealldisplayedasasterisks(or someotherxedcharacter).Apasswordeldis,obviously,d esignedtolettheuserentera passwordwithoutshowingthatpasswordonthescreen. Textcomponentsareactuallyquitecomplex,andIhavecover edonlytheirmostbasic propertieshere.Iwillreturntothetopicoftextcomponent sin Subsection12.4.4 6.6.5JComboBoxThe JComboBox classprovidesawaytolettheuserselectoneoptionfromali stofoptions. Theoptionsarepresentedasakindofpop-upmenu,andonlyth ecurrentlyselectedoptionis visibleonthescreen. Whena JComboBox objectisrstconstructed,itinitiallycontainsnoitems. Anitemis addedtothebottomofthemenubycallingthecombobox'sinst ancemethod, addItem(str) where str isthestringthatwillbedisplayedinthemenu. <br /> <br /> PAGE 292<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 278 Forexample,thefollowingcodewillcreateanobjectoftype JComboBox thatcontainsthe optionsRed,Blue,Green,andBlack: JComboBoxcolorChoice=newJComboBox();colorChoice.addItem("Red");colorChoice.addItem("Blue");colorChoice.addItem("Green");colorChoice.addItem("Black"); Youcancallthe getSelectedIndex() methodofa JComboBox tondoutwhichitem iscurrentlyselected.Thismethodreturnsanintegerthatg ivesthepositionoftheselected iteminthelist,wheretheitemsarenumberedstartingfromz ero.Alternatively,youcancall getSelectedItem() togettheselecteditemitself.(Thismethodreturnsavalue oftype Object sincea JComboBox canactuallyholdothertypesofobjectsbesidesstrings.)Y oucanchange theselectionbycallingthemethod setSelectedIndex(n) ,where n isanintegergivingthe positionoftheitemthatyouwanttoselect. Themostcommonwaytousea JComboBox istocallits getSelectedIndex() methodwhen youhaveaneedtoknowwhichitemiscurrentlyselected.Howe ver,likeothercomponentsthat wehaveseen, JComboBox componentsgenerate ActionEvent swhentheuserselectsanitem. Youcanregisteran ActionListener withthe JComboBox ifyouwanttorespondtosuchevents astheyoccur. JComboBoxes haveaniftyfeature,whichisprobablynotallthatusefulin practice.Youcan makea JComboBox \editable"bycallingitsmethod setEditable(true) .Ifyoudothis,the usercanedittheselectionbyclickingonthe JComboBox andtyping.Thisallowstheuserto makeaselectionthatisnotinthepre-conguredlistthatyo uprovide.(The\Combo"inthe name\JComboBox"referstothefactthatit'sakindofcombin ationofmenuandtext-input box.)Iftheuserhaseditedtheselectioninthisway,thenth e getSelectedIndex() method willreturnthevalue -1 ,and getSelectedItem() willreturnthestringthattheusertyped. An ActionEvent istriggerediftheuserpressesreturnwhiletypinginthe JComboBox 6.6.6JSliderA JSlider providesawayfortheusertoselectanintegervaluefromara ngeofpossiblevalues. Theuserdoesthisbydragginga\knob"alongabar.Asliderca n,optionally,bedecorated withtickmarksandwithlabels.Thispictureshowsthreesli derswithdierentdecorationsand withdierentrangesofvalues: Here,thesecondsliderisdecoratedwithticks,andthethir doneisdecoratedwithlabels.It's possibleforasingleslidertohavebothtypesofdecoration s. Themostcommonlyusedconstructorfor JSliders speciesthestartandendoftherange ofvaluesfortheslideranditsinitialvaluewhenitrstapp earsonthescreen: publicJSlider(intminimum,intmaximum,intvalue) <br /> <br /> PAGE 293<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 279 Iftheparametersareomitted,thevalues0,100,and50areus ed.Bydefault,asliderishorizontal,butyoucanmakeitverticalbycallingitsmethod setOrientation(JSlider.VERTICAL) Thecurrentvalueofa JSlider canbereadatanytimewithits getValue() method,which returnsavalueoftype int .Ifyouwanttochangethevalue,youcandosowiththemethod setValue(n) ,whichtakesaparameteroftype int Ifyouwanttorespondimmediatelywhentheuserchangesthev alueofaslider,youcan registeralistenerwiththeslider. JSliders ,unlikeothercomponentswehaveseen,donot generate ActionEvents .Instead,theygenerateeventsoftype ChangeEvent ChangeEvent and relatedclassesaredenedinthepackage javax.swing.event ratherthan java.awt.event ,so ifyouwanttouse ChangeEvents ,youshould importjavax.swing.event.* atthebeginning ofyourprogram.Youmustalsodenesomeobjecttoimplement the ChangeListener interface, andyoumustregisterthechangelistenerwiththesliderbyc allingits addChangeListener() method.A ChangeListener mustprovideadenitionforthemethod: publicvoidstateChanged(ChangeEventevt) Thismethodwillbecalledwheneverthevalueofthesliderch anges.(Notethatitwillalso becalledwhenyouchangethevaluewiththe setValue() method,aswellaswhentheuser changesthevalue.)Inthe stateChanged() method,youcancall evt.getSource() tondout whichobjectgeneratedtheevent. Usingtickmarksonasliderisatwo-stepprocess:Specifyth eintervalbetweenthetick marks,andtellthesliderthatthetickmarksshouldbedispl ayed.Thereareactuallytwo typesoftickmarks,\major"tickmarksand\minor"tickmark s.Youcanhaveoneor theotherorboth.Majortickmarksareabitlongerthanminor tickmarks.Themethod setMinorTickSpacing(i) indicatesthatthereshouldbeaminortickmarkevery i unitsalong theslider.Theparameterisaninteger.(Thespacingisinte rmsofvaluesontheslider,not pixels.)Forthemajortickmarks,thereisasimilarcommand setMajorTickSpacing(i) Callingthesemethodsisnotenoughtomakethetickmarksapp ear.Youalsohavetocall setPaintTicks(true) .Forexample,thesecondsliderintheabovepicturewascrea tedand conguredusingthecommands: slider2=newJSlider();//(Usesdefaultmin,max,andvalue .) slider2.addChangeListener(this);slider2.setMajorTickSpacing(25);slider2.setMinorTickSpacing(5);slider2.setPaintTicks(true); Labelsonasliderarehandledsimilarly.Youhavetospecify thelabelsandtellthesliderto paintthem.Specifyinglabelsisatrickybusiness,butthe JSlider classhasamethodtosimplify it.Youcancreateasetoflabelsandaddthemtoaslidernamed sldr withthecommand: sldr.setLabelTable(sldr.createStandardLabels(i)); where i isanintegergivingthespacingbetweenthelabels.Toarran geforthelabelstobe displayed,call setPaintLabels(true) .Forexample,thethirdsliderintheabovepicturewas createdandconguredwiththecommands: slider3=newJSlider(2000,2100,2006);slider3.addChangeListener(this);slider3.setLabelTable(slider3.createStandardLabels( 50)); slider3.setPaintLabels(true); <br /> <br /> PAGE 294<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 280 6.7BasicLayoutC omponents arethefundamentalbuildingblocksofagraphicaluserinte rface.Butyouhave (online) todomorewithcomponentsbesidescreatethem.Anotheraspe ctofGUIprogrammingis layingout componentsonthescreen,thatis,decidingwheretheyaredr awnandhowbig theyare.Youhaveprobablynoticedthatcomputingcoordina tescanbeadicultproblem, especiallyifyoudon'tassumeaxedsizeforthedrawingare a.Javahasasolutionforthis,as well. ComponentsarethevisibleobjectsthatmakeupaGUI.Someco mponentsare containers whichcanholdothercomponents.ContainersinJavaareobje ctsthatbelongtosomesubclassof java.awt.Container .Thecontentpaneofa JApplet or JFrame isanexampleofacontainer. Thestandardclass JPanel ,whichwehavemostlyusedasadrawingsurfaceuptillnow,is anotherexampleofacontainer. Becausea JPanel objectisacontainer,itcanholdothercomponents.Because a JPanel is itselfacomponent,youcanadda JPanel toanother JPanel .Thismakescomplexnestingof componentspossible. JPanels canbeusedtoorganizecomplicateduserinterfaces,asshow nin thisillustration: Thecomponentsinacontainermustbe\laidout,"whichmeans settingtheirsizesand positions.It'spossibletoprogramthelayoutyourself,bu tordinarilylayoutisdonebya layoutmanager .Alayoutmanagerisanobjectassociatedwithacontainerth atimplements somepolicyforlayingoutthecomponentsinthatcontainer. Dierenttypesoflayoutmanager implementdierentpolicies.Inthissection,wewillcover thethreemostcommontypesof layoutmanager,andthenwewilllookatseveralprogramming examplesthatusecomponents andlayout. Everycontainerhasaninstancemethod, setLayout() ,thattakesaparameteroftype LayoutManager andthatisusedtospecifythelayoutmanagerthatwillberes ponsibleforlaying outanycomponentsthatareaddedtothecontainer.Componen tsareaddedtoacontainerby callinganinstancemethodnamed add() inthecontainerobject.Thereareactuallyseveral versionsofthe add() method,withdierentparameterlists.Dierentversionso f add() are appropriatefordierentlayoutmanagers,aswewillseebel ow. <br /> <br /> PAGE 295<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 281 6.7.1BasicLayoutManagersJavahasavarietyofstandardlayoutmanagersthatcanbeuse dasparametersinthe setLayout() method.Theyaredenedbyclassesinthepackage java.awt .Here,wewill lookatjustthreeoftheselayoutmanagerclasses: FlowLayout BorderLayout ,and GridLayout A FlowLayout simplylinesupcomponentsinarowacrossthecontainer.The sizeofeach componentisequaltothatcomponent's\preferredsize."Af terlayingoutasmanyitemsaswill tinarowacrossthecontainer,thelayoutmanagerwillmove ontothenextrow.Thedefault layoutfora JPanel isa FlowLayout ;thatis,a JPanel usesa FlowLayout unlessyouspecifya dierentlayoutmanagerbycallingthepanel's setLayout() method. Thecomponentsinagivenrowcanbeeitherleft-aligned,rig ht-aligned,orcenteredwithin thatrow,andtherecanbehorizontalandverticalgapsbetwe encomponents.Ifthedefault constructor,\ newFlowLayout() ",isused,thenthecomponentsoneachrowwillbecentered andboththehorizontalandtheverticalgapswillbevepixe ls.Theconstructor publicFlowLayout(intalign,inthgap,intvgap) canbeusedtospecifyalternativealignmentandgaps.Thepo ssiblevaluesof align are FlowLayout.LEFT FlowLayout.RIGHT ,and FlowLayout.CENTER Supposethat cntr isacontainerobjectthatisusinga FlowLayout asitslayoutmanager. Then,acomponent, comp ,canbeaddedtothecontainerwiththestatement cntr.add(comp); The FlowLayout willlineupallthecomponentsthathavebeenaddedtothecon tainerinthis way.Theywillbelinedupintheorderinwhichtheywereadded .Forexample,thispicture showsvebuttonsinapanelthatusesa FlowLayout : Notethatsincethevebuttonswillnottinasinglerowacro ssthepanel,theyarearranged intworows.Ineachrow,thebuttonsaregroupedtogetherand arecenteredintherow.The buttonswereaddedtothepanelusingthestatements: panel.add(button1);panel.add(button2);panel.add(button3);panel.add(button4);panel.add(button5); Whenacontainerusesalayoutmanager,thelayoutmanageris ordinarilyresponsiblefor computingthepreferredsizeofthecontainer(althoughadi erentpreferredsizecouldbe setbycallingthecontainer's setPreferredSize method).A FlowLayout preferstoputits componentsinasinglerow,sothepreferredwidthisthetota lofthepreferredwidthsofall thecomponents,plusthehorizontalgapsbetweenthecompon ents.Thepreferredheightisthe maximumpreferredheightofallthecomponents. <br /> <br /> PAGE 296<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 282 A BorderLayout layoutmanagerisdesignedtodisplayonelarge,centralcom ponent,withup tofoursmallercomponentsarrangedalongtheedgesofthece ntralcomponent.Ifacontainer, cntr ,isusinga BorderLayout ,thenacomponent, comp ,shouldbeaddedtothecontainerusing astatementoftheform cntr.add(comp,borderLayoutPosition); where borderLayoutPosition specieswhatpositionthecomponentshouldoccupyinthe layoutandisgivenasoneoftheconstants BorderLayout.CENTER BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.EAST ,or BorderLayout.WEST .Themeaningoftheve positionsisshowninthisdiagram: Notethataborderlayoutcancontainfewerthanvecompompo ntnts,sothatnotallveof thepossiblepositionsneedtobelled. A BorderLayout selectsthesizesofitscomponentsasfollows:The NORTH and SOUTH components(ifpresent)areshownattheirpreferredheights,b uttheirwidthissetequaltothefull widthofthecontainer.The EAST and WEST componentsareshownattheirpreferredwidths, buttheirheightissettotheheightofthecontainer,minust hespaceoccupiedbythe NORTH and SOUTH components.Finally,the CENTER componenttakesupanyremainingspace;the preferredsizeofthe CENTER componentiscompletelyignored.Youshouldmakesurethat thecomponentsthatyouputintoa BorderLayout aresuitableforthepositionsthattheywill occupy.Ahorizontalsliderortexteld,forexample,would workwellinthe NORTH or SOUTH position,butwouldn'tmakemuchsenseinthe EAST or WEST position. Thedefaultconstructor, newBorderLayout() ,leavesnospacebetweencomponents.Ifyou wouldliketoleavesomespace,youcanspecifyhorizontalan dverticalgapsintheconstructor ofthe BorderLayout object.Forexample,ifyousay panel.setLayout(newBorderLayout(5,7)); thenthelayoutmanagerwillinserthorizontalgapsof5pixe lsbetweencomponentsandvertical gapsof7pixelsbetweencomponents.Thebackgroundcolorof thecontainerwillshowthrough inthesegaps.Thedefaultlayoutfortheoriginalcontentpa nethatcomeswitha JFrame or JApplet isa BorderLayout withnohorizontalorverticalgap. Finally,weconsiderthe GridLayout layoutmanager.Agridlayoutlaysoutcomponentsina gridofequalsizedrectangles.Thisillustrationshowshow thecomponentswouldbearranged inagridlayoutwith3rowsand2columns: <br /> <br /> PAGE 297<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 283 Ifacontainerusesa GridLayout ,theappropriate add methodforthecontainertakesasingle parameteroftype Component (forexample: cntr.add(comp) ).Componentsareaddedtothe gridintheordershown;thatis,eachrowislledfromleftto rightbeforegoingonthenext row. Theconstructorfora GridLayout takestheform\ newGridLayout(R,C) ",where R isthe numberofrowsand C isthenumberofcolumns.Ifyouwanttoleavehorizontalgaps of H pixels betweencolumnsandverticalgapsof V pixelsbetweenrows,use\ newGridLayout(R,C,H,V) instead. Whenyouusea GridLayout ,it'sprobablygoodformtoaddjustenoughcomponentstoll thegrid.However,thisisnotrequired.Infact,aslongasyo uspecifyanon-zerovalueforthe numberofrows,thenthenumberofcolumnsisessentiallyign ored.Thesystemwillusejustas manycolumnsasarenecessarytoholdallthecomponentsthat youaddtothecontainer.Ifyou wanttodependonthisbehavior,youshouldprobablyspecify zeroasthenumberofcolumns. Youcanalsospecifythenumberofrowsaszero.Inthatcase,y oumustgiveanon-zeronumber ofcolumns.Thesystemwillusethespeciednumberofcolumn s,withjustasmanyrowsas necessarytoholdthecomponentsthatareaddedtothecontai ner. Horizontalgrids,withasinglerow,andverticalgrids,wit hasinglecolumn,areverycommon.Forexample,supposethat button1 button2 ,and button3 arebuttonsandthatyou'd liketodisplaytheminahorizontalrowinapanel.Ifyouusea horizontalgridforthepanel, thenthebuttonswillcompletelyllthatpanelandwillallb ethesamesize.Thepanelcanbe createdasfollows: JPanelbuttonBar=newJPanel();buttonBar.setLayout(newGridLayout(1,3)); //(Note:The"3"hereisprettymuchignored,and//youcouldalsosay"newGridLayout(1,0)".//Toleavegapsbetweenthebuttons,youcoulduse//"newGridLayout(1,0,5,5)".) buttonBar.add(button1);buttonBar.add(button2);buttonBar.add(button3); Youmightndthisbuttonbartobemoreattractivethantheon ethatusesthedefault FlowLayout layoutmanager. 6.7.2BordersWehaveseenhowtoleavegapsbetweenthecomponentsinacont ainer,butwhatifyouwould liketoleaveaborderaroundtheoutsideofthecontainer?Th isproblemisnothandledby layoutmanagers.Instead,bordersinSwingarerepresented byobjects.A Border objectcanbe addedtoany JComponent ,notjusttocontainers.Borderscanbemorethanjustemptys pace. Theclass javax.swing.BorderFactory containsalargenumberofstaticmethodsforcreating borderobjects.Forexample,thefunction <br /> <br /> PAGE 298<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 284 BorderFactory.createLineBorder(Color.BLACK) returnsanobjectthatrepresentsaone-pixelwideblacklin earoundtheoutsideofacomponent. If comp isa JComponent ,abordercanbeaddedto comp usingits setBorder() method.For example: comp.setBorder(BorderFactory.createLineBorder(Color .BLACK)); Whenaborderhasbeensetfora JComponent ,theborderisdrawnautomatically,without anyfurthereortonthepartoftheprogrammer.Theborderis drawnalongtheedgesofthe component,justinsideitsboundary.Thelayoutmanagerofa JPanel orothercontainerwill takethespaceoccupiedbytheborderintoaccount.Thecompo nentsthatareaddedtothe containerwillbedisplayedintheareainsidetheborder.Id on'trecommendusingaborderon a JPanel thatisbeingusedasadrawingsurface.However,ifyoudothi s,youshouldtakethe borderintoaccount.Ifyoudrawintheareaoccupiedbythebo rder,thatpartofyourdrawing willbecoveredbytheborder. Herearesomeofthestaticmethodsthatcanbeusedtocreateb orders: BorderFactory.createEmptyBorder(top,left,bottom,rig ht) |leavesanemptyborderaroundtheedgesofacomponent.Nothingisdrawninthiss pace,sothebackground colorofthecomponentwillappearintheareaoccupiedbythe border.Theparameters areintegersthatgivethewidthoftheborderalongthetop,l eft,bottom,andrightedges ofthecomponent.Thisisactuallyveryusefulwhenusedona JPanel thatcontainsother components.Itputssomespacebetweenthecomponentsandth eedgeofthepanel.It canalsobeusefulona JLabel ,whichotherwisewouldnothaveanyspacebetweenthe textandtheedgeofthelabel. BorderFactory.createLineBorder(color,thickness) |drawsalinearoundallfour edgesofacomponent.Therstparameterisoftype Color andspeciesthecolorofthe line.Thesecondparameterisanintegerthatspeciestheth icknessoftheborder.Ifthe secondparameterisomitted,alineofthickness1isdrawn. BorderFactory.createMatteBorder(top,left,bottom,rig ht,color) |issimilarto createLineBorder ,exceptthatyoucanspecifyindividualthicknessesforthe top,left, bottom,andrightedgesofthecomponent. BorderFactory.createEtchedBorder() |createsaborderthatlookslikeagroove etchedaroundtheboundaryofthecomponent.Theeectisach ievedusinglighterand darkershadesofthecomponent'sbackgroundcolor,anditdo esnotworkwellwithevery backgroundcolor. BorderFactory.createLoweredBevelBorder() |givesacomponentathree-dimensional eectthatmakesitlooklikeitisloweredintothecomputers creen.AswithanEtchedBorder,thisonlyworkswellforcertainbackgroundcolors. BorderFactory.createRaisedBevelBorder() |similartoaLoweredBevelBorder,but thecomponentlookslikeitisraisedabovethecomputerscre en. BorderFactory.createTitledBorder(title) |createsaborderwithatitle.Thetitleis a String ,whichisdisplayedintheupperleftcorneroftheborder. Therearemanyothermethodsinthe BorderFactory class,mostofthemprovidingvariationsofthebasicborderstylesgivenhere.Thefollowingi llustrationshowssixcomponents withsixdierentborderstyles.Thetextineachcomponenti sthecommandthatcreatedthe borderforthatcomponent: <br /> <br /> PAGE 299<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 285 (Thesourcecodefortheappletthatproducedthispictureca nbefoundin BorderDemo.java .) 6.7.3SliderAndComboBoxDemoNowthatwehavelookedatcomponentsandlayouts,it'stimet oputthemtogetherintosome completeprograms.Westartwithasimpledemothatusesa JLabel ,a JComboBox ,anda coupleof JSlider s,alllaidoutina GridLayout ,asshowninthispicture: Theslidersinthisappletcontroltheforegroundandbackgr oundcolorofthelabel,andthe comboboxcontrolsitsfontstyle.Writingthisprogramisam atterofcreatingthecomponents, layingthemout,andprogramminglistenerstorespondtoeve ntsfromtheslidersandcombo box.Inmyprogram,Ideneasubclassof JPanel whichwillbeusedfortheapplet'scontent pane.Thisclassimplements ChangeListener and ActionListener ,sothepanelitselfcanactas thelistenerforchangeeventsfromtheslidersandactionev entsfromthecombobox.Inthe constructor,thefourcomponentsarecreatedandcongured ,a GridLayout isinstalledasthe layoutmanagerforthepanel,andthecomponentsareaddedto thepanel: /*Createthesliders,andsetupthispaneltolistenfor ChangeEventsthataregeneratedbythesliders.*/ bgColorSlider=newJSlider(0,255,100);bgColorSlider.addChangeListener(this);fgColorSlider=newJSlider(0,255,200);fgColorSlider.addChangeListener(this); <br /> <br /> PAGE 300<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 286 /*Createthecombobox,andaddfouritemstoit,listing differentfontstyles.SetupthepaneltolistenforActionEventsfromthecombobox.*/ fontStyleSelect=newJComboBox();fontStyleSelect.addItem("PlainFont");fontStyleSelect.addItem("ItalicFont");fontStyleSelect.addItem("BoldFont");fontStyleSelect.addItem("BoldItalicFont");fontStyleSelect.setSelectedIndex(2);fontStyleSelect.addActionListener(this);/*Createthedisplaylabel,withpropertiestomatchthe valuesoftheslidersandthesettingofthecombobox.*/ displayLabel=newJLabel("HelloWorld!",JLabel.CENTER) ; displayLabel.setOpaque(true);displayLabel.setBackground(newColor(100,100,100));displayLabel.setForeground(newColor(255,200,200));displayLabel.setFont(newFont("Serif",Font.BOLD,30)) ; /*Setthelayoutforthepanel,andaddthefourcomponents. UseaGridLayoutwith4rowsand1column.*/ setLayout(newGridLayout(4,1));add(displayLabel);add(bgColorSlider);add(fgColorSlider);add(fontStyleSelect); Theclassalsodenesthemethodsrequiredbythe ActionListener and ChangeListener interfaces.The actionPerformed() methodiscalledwhentheuserselectsaniteminthecombo box.Thismethodchangesthefontinthe JLable ,wherethefontdependsonwhichitemis currentlyselectedinthecombobox, fontStyleSelect : publicvoidactionPerformed(ActionEventevt){ switch(fontStyleSelect.getSelectedIndex()){case0: displayLabel.setFont(newFont("Serif",Font.PLAIN,30) ); break; case1: displayLabel.setFont(newFont("Serif",Font.ITALIC,30 )); break; case2: displayLabel.setFont(newFont("Serif",Font.BOLD,30)) ; break; case3: displayLabel.setFont(newFont("Serif",Font.BOLD+Font .ITALIC,30)); break; } } Andthe stateChanged() method,whichiscalledwhentheusermanipulatesoneofthes liders, usesthevalueontheslidertocomputeanewforegroundorbac kgroundcolorforthelabel. Themethodchecks evt.getSource() todeterminewhichsliderwaschanged: <br /> <br /> PAGE 301<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 287 publicvoidstateChanged(ChangeEventevt){ if(evt.getSource()==bgColorSlider){ intbgVal=bgColorSlider.getValue();displayLabel.setBackground(newColor(bgVal,bgVal,bgV al)); //NOTE:Thebackgroundcolorisashadeofgray,//determinedbythesettingontheslider. }else{ intfgVal=fgColorSlider.getValue();displayLabel.setForeground(newColor(255,fgVal,fgVal )); //Note:Theforegroundcolorrangesfrompureredtopure//whiteastheslidervalueincreasesfrom0to255. } } (Thecompletesourcecodeisinthele SliderAndComboBoxDemo.java .) 6.7.4ASimpleCalculatorAsournextexample,welookbrieryatanexamplethatusesnes tedsubpanelstobuildamore complexuserinterface.Theprogramhastwo JTextField swheretheusercanentertwonumbers, four JButtons thattheusercanclicktoadd,subtract,multiply,ordivide thetwonumbers,and a JLabel thatdisplaystheresultoftheoperation: Likethepreviousexample,thisexampleusesamainpanelwit ha GridLayout thathasfourrows andonecolumn.Inthiscase,thelayoutiscreatedwiththest atement: setLayout(newGridLayout(4,1,3,3)); whichallowsa3-pixelgapbetweentherowswherethegraybac kgroundcolorofthepanelis visible.Thegrayborderaroundtheedgesofthepanelisadde dwiththestatement setBorder(BorderFactory.createEmptyBorder(5,5,5,5)) ; Therstrowofthegridlayoutactuallycontainstwocompone nts,a JLabel displayingthe text\ x= "anda JTextField .Agridlayoutcanonlyonlyhaveonecomponentineachpositi on. Inthiscase,thatcomponentisa JPanel ,asubpanelthatisnestedinsidethemainpanel.This subpanelinturncontainsthelabelandtexteld.Thiscanbe programmedasfollows: xInput=newJTextField("0",10);//Createatextfieldsize dtohold10chars. JPanelxPanel=newJPanel();//Createthesubpanel.xPanel.add(newJLabel("x="));//Addalabeltothesubpane l. xPanel.add(xInput);//AddthetextfieldtothesubpanelmainPanel.add(xPanel);//Addthesubpaneltothemainpane l. <br /> <br /> PAGE 302<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 288 Thesubpanelusesthedefault FlowLayout layoutmanager,sothelabelandtexteldaresimply placednexttoeachotherinthesubpanelattheirpreferreds ize,andarecenteredinthe subpanel. Similarly,thethirdrowofthegridlayoutisasubpanelthat containsfourbuttons.Inthis case,thesubpanelusesa GridLayout withonerowandfourcolumns,sothatthebuttonsare allthesamesizeandcompletelyllthesubpanel. Oneotherpointofinterestinthisexampleisthe actionPerformed() methodthatresponds whentheuserclicksoneofthebuttons.Thismethodmustretr ievetheuser'snumbersfromthe texteld,performtheappropriatearithmeticoperationon them(dependingonwhichbutton wasclicked),andsetthetextofthelabeltorepresentthere sult.However,thecontentsofthe texteldscanonlyberetrievedasstrings,andthesestring smustbeconvertedintonumbers. Iftheconversionfails,thelabelissettodisplayanerrorm essage: publicvoidactionPerformed(ActionEventevt){ doublex,y;//Thenumbersfromtheinputboxes.try{ StringxStr=xInput.getText();x=Double.parseDouble(xStr); }catch(NumberFormatExceptione){ //ThestringxStrisnotalegalnumber. answer.setText("Illegaldataforx.");xInput.requestFocus();return; }try{ StringyStr=yInput.getText();y=Double.parseDouble(yStr); }catch(NumberFormatExceptione){ //ThestringyStrisnotalegalnumber. answer.setText("Illegaldatafory.");yInput.requestFocus();return; }/*Perfromtheoperationbasedontheactioncommandfromthe button.Theactioncommandisthetextdisplayedonthebutto n. Notethatdivisionbyzeroproducesanerrormessage.*/ Stringop=evt.getActionCommand();if(op.equals("+")) answer.setText("x+y="+(x+y)); elseif(op.equals("-")) answer.setText("x-y="+(x-y)); elseif(op.equals("*")) answer.setText("x*y="+(x*y)); elseif(op.equals("/")){ if(y==0) answer.setText("Can'tdividebyzero!"); else answer.setText("x/y="+(x/y)); <br /> <br /> PAGE 303<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 289 } }//endactionPerformed() (Thecompletesourcecodeforthisexamplecanbefoundin SimpleCalc.java .) 6.7.5UsinganullLayoutAsmentionedabove,itispossibletodowithoutalayoutmana geraltogether.Foroutnext example,we'lllookatapanelthatdoesnotusealayoutmanag er.Ifyousetthelayoutmanager ofacontainertobe null ,bycalling container.setLayout(null) ,thenyouassumecomplete responsibilityforpositioningandsizingthecomponentsi nthatcontainer. If comp isanycomponent,thenthestatement comp.setBounds(x,y,width,height); putsthetopleftcornerofthecomponentatthepoint (x,y) ,measuredinthecoordinatesystem ofthecontainerthatcontainsthecomponent,anditsetsthe widthandheightofthecomponent tothespeciedvalues.Youshouldonlysettheboundsofacom ponentifthecontainerthat containsithasanulllayoutmanager.Inacontainerthathas anon-nulllayoutmanager,the layoutmanagerisresponsibleforsettingthebounds,andyo ushouldnotinterferewithitsjob. Assumingthatyouhavesetthelayoutmanagerto null ,youcancallthe setBounds() methodanytimeyoulike.(Youcanevenmakeacomponentthatm ovesorchangessizewhile theuseriswatching.)Ifyouarewritingapanelthathasakno wn,xedsize,thenyoucan settheboundsofeachcomponentinthepanel'sconstructor. Notethatyoumustalsoaddthe componentstothepanel,usingthepanel's add(component) instancemethod;otherwise,the componentwillnotappearonthescreen. Ourexamplecontainsfourcomponents:twobuttons,alabel, andapanelthatdisplaysa checkerboardpattern: Thisisjustanexampleofusinganulllayout;itdoesn'tdoan ything,exceptthatclickingthe buttonschangesthetextofthelabel.(Wewillusethisexamp lein Section7.5 asastarting pointforacheckersgame.) Foritscontentpane,thisexampleusesamainpanelthatisde nedbyaclassnamed NullLayoutPanel .Thefourcomponentsarecreatedandaddedtothepanelinthe constructor ofthe NullLayoutPanel class.Thenthe setBounds() methodofeachcomponentiscalledtoset thesizeandpositionofthecomponent: <br /> <br /> PAGE 304<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 290 publicNullLayoutPanel(){ setLayout(null);//Iwilldothelayoutmyself!setBackground(newColor(0,150,0));//Adarkgreenbackgr ound. setBorder(BorderFactory.createEtchedBorder());setPreferredSize(newDimension(350,240)); //Iassumethatthesizeofthepanelis,infact,350-by-240. /*Createthecomponentsandaddthemtothecontentpane.Ify ou don'taddthemtotheacontainer,theywon'tappear,evenifyousettheirbounds!*/ board=newCheckerboard(); //(CheckerboradisasubclassofJPanel,definedelsewhere .) add(board);newGameButton=newJButton("NewGame");newGameButton.addActionListener(this);add(newGameButton);resignButton=newJButton("Resign");resignButton.addActionListener(this);add(resignButton);message=newJLabel("Click\"NewGame\"tobeginagame.");message.setForeground(newColor(100,255,100));//Ligh tgreen. message.setFont(newFont("Serif",Font.BOLD,14));add(message);/*Setthepositionandsizeofeachcomponentbycalling itssetBounds()method.*/ board.setBounds(20,20,164,164);newGameButton.setBounds(210,60,120,30);resignButton.setBounds(210,120,120,30);message.setBounds(20,200,330,30); }//endconstructor It'sreasonablyeasy,inthiscase,togetanattractivelayo ut.It'smuchmoredicult todoyourownlayoutifyouwanttoallowforchangesofsize.I nthatcase,youhaveto respondtochangesinthecontainer'ssizebyrecomputingth esizesandpositionsofallthe componentsthatitcontains.Ifyouwanttorespondtochange sinacontainer'ssize,youcan registeranappropriatelistenerwiththecontainer.Anyco mponentgeneratesaneventoftype ComponentEvent whenitssizechanges(andalsowhenitismoved,hidden,orsh own).You canregistera ComponentListener withthecontainerandrespondtosizechangeeventsby recomputingthesizesandpositionsofallthecomponentsin thecontainer.ConsultaJava referenceformoreinformationabout ComponentEvents .However,myrealadviceisthatifyou wanttoallowforchangesinthecontainer'ssize,trytonda layoutmanagertodothework foryou. (Thecompletesourcecodeforthisexampleisin NullLayoutDemo.java .) <br /> <br /> PAGE 305<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 291 6.7.6ALittleCardGameForanalexample,let'slookatsomethingalittlemoreinte restingasaprogram.Theexample isasimplecardgameinwhichyoulookataplayingcardandtry topredictwhetherthenext cardwillbehigherorlowerinvalue.(Aceshavethelowestva lueinthisgame.)You'veseena text-orientedversionofthesamegamein Subsection5.4.3 Section5.4 alsointroduced Deck Hand ,and Card classesthatareusedinthegameprogram.InthisGUIversion ofthegame, youclickonabuttontomakeyourprediction.Ifyoupredictw rong,youlose.Ifyoumake threecorrectpredictions,youwin.Aftercompletingonega me,youcanclickthe\NewGame" buttontostartanewgame.Hereiswhatthegamelookslike: Thecompletesourcecodeforthisexampleisinthele HighLowGUI.java .Youcantryout thegameintheon-lineversionofthissection,orbyrunning theprogramasastand-alone application. Theoverallstructureofthemainpanelinthisexampleshoul dbeclear:Ithasthreebuttons inasubpanelatthebottomofthemainpanelandalargedrawin gsurfacethatdisplaysthe cardsandamessage.Themainpanelusesa BorderLayout .Thedrawingsurfaceoccupiesthe CENTER positionoftheborderlayout.Thesubpanelthatcontainsth ebuttonsoccupiesthe SOUTH positionoftheborderlayout,andtheotherthreepositions ofthelayoutareempty. Thedrawingsurfaceisdenedbyanestedclassnamed CardPanel ,whichisasubclassof JPanel .Ihavechosentoletthedrawingsurfaceobjectdomostofthe workofthegame: Itlistensforeventsfromthethreebuttonsandrespondsbyt akingtheappropriateactions. Themainpanelisdenedby HighLowGUI itself,whichisanothersubclassof JPanel .The constructorofthe HighLowGUI classcreatesalltheothercomponents,setsupeventhandli ng, andlaysoutthecomponents: publicHighLowGUI(){//Theconstructor. setBackground(newColor(130,50,40));setLayout(newBorderLayout(3,3));//BorderLayoutwith3 -pixelgaps. CardPanelboard=newCardPanel();//Wherethecardsaredra wn. add(board,BorderLayout.CENTER);JPanelbuttonPanel=newJPanel();//Thesubpanelthathold sthebuttons. buttonPanel.setBackground(newColor(220,200,180));add(buttonPanel,BorderLayout.SOUTH);JButtonhigher=newJButton("Higher"); <br /> <br /> PAGE 306<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 292 higher.addActionListener(board);//TheCardPanelliste nsforevents. buttonPanel.add(higher);JButtonlower=newJButton("Lower");lower.addActionListener(board);buttonPanel.add(lower);JButtonnewGame=newJButton("NewGame");newGame.addActionListener(board);buttonPanel.add(newGame);setBorder(BorderFactory.createLineBorder(newColor(1 30,50,40),3)); }//endconstructor Theprogrammingofthedrawingsurfaceclass, CardPanel ,isaniceexampleofthinking intermsofastatemachine.(See Subsection6.5.4 .)Itisimportanttothinkintermsofthe statesthatthegamecanbein,howthestatecanchange,andho wtheresponsetoevents candependonthestate.Theapproachthatproducedtheorigi nal,text-orientedgamein Subsection5.4.3 isnotappropriatehere.Tryingtothinkaboutthegameinter msofaprocess thatgoesstep-by-stepfrombeginningtoendismorelikelyt oconfuseyouthantohelpyou. Thestateofthegameincludesthecardsandthemessage.Thec ardsarestoredinan objectoftype Hand .Themessageisa String .Thesevaluesarestoredininstancevariables. Thereisalsoanother,lessobviousaspectofthestate:Some timesagameisinprogress,and theuserissupposedtomakeapredictionaboutthenextcard. Sometimeswearebetween games,andtheuserissupposedtoclickthe\NewGame"button .It'sagoodideatokeep trackofthisbasicdierenceinstate.The CardPanel classusesabooleaninstancevariable named gameInProgress forthispurpose. Thestateofthegamecanchangewhenevertheuserclicksonab utton.The CardPanel classimplementsthe ActionListener interfaceanddenesan actionPerformed() methodto respondtotheuser'sclicks.Thismethodsimplycallsoneof threeothermethods, doHigher() doLower() ,or newGame() ,dependingonwhichbuttonwaspressed.It'sinthesethreee venthandlingmethodsthattheactionofthegametakesplace. Wedon'twanttolettheuserstartanewgameifagameiscurren tlyinprogress.Thatwould becheating.So,theresponseinthe newGame() methodisdierentdependingonwhetherthe statevariable gameInProgress istrueorfalse.Ifagameisinprogress,the message instance variableshouldbesettoshowanerrormessage.Ifagameisno tinprogress,thenallthestate variablesshouldbesettoappropriatevaluesforthebeginn ingofanewgame.Inanycase,the boardmustberepaintedsothattheusercanseethatthestate haschanged.Thecomplete newGame() methodisasfollows: /** *CalledbytheCardPanelconstructor,andcalledbyactionP erformed()if *theuserclicksthe"NewGame"button.Startanewgame.*/ voiddoNewGame(){ if(gameInProgress){ //Ifthecurrentgameisnotover,itisanerrortotry//tostartanewgame. message="Youstillhavetofinishthisgame!";repaint();return; } <br /> <br /> PAGE 307<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 293 deck=newDeck();//Createthedeckandhandtouseforthisga me. hand=newHand();deck.shuffle();hand.addCard(deck.dealCard());//Dealthefirstcardint othehand. message="Isthenextcardhigherorlower?";gameInProgress=true;repaint(); }//enddoNewGame() The doHigher() and doLower() methodsarealmostidenticaltoeachother(andcould probablyhavebeencombinedintoonemethodwithaparameter ,ifIweremoreclever).Let's lookatthe doHigher() routine.Thisiscalledwhentheuserclicksthe\Higher"but ton.This onlymakessenseifagameisinprogress,sotherstthing doHigher() shoulddoischeckthe valueofthestatevariable gameInProgress .Ifthevalueis false ,then doHigher() shouldjust setupanerrormessage.Ifagameisinprogress,anewcardsho uldbeaddedtothehandand theuser'spredictionshouldbetested.Theusermightwinor loseatthistime.Ifso,thevalue ofthestatevariable gameInProgress mustbesetto false becausethegameisover.Inany case,theboardisrepaintedtoshowthenewstate.Hereisthe doHigher() method: /** *CalledbyactionPerformmed()whenuserclicks"Higher"bu tton. *Checktheuser'sprediction.Gameendsifuserguessed*wrongoriftheuserhasmadethreecorrectpredictions.*/ voiddoHigher(){ if(gameInProgress==false){ //Ifthegamehasended,itwasanerrortoclick"Higher",//Sosetupanerrormessageandabortprocessing. message="Click\"NewGame\"tostartanewgame!";repaint();return; }hand.addCard(deck.dealCard());//Dealacardtothehand.intcardCt=hand.getCardCount();CardthisCard=hand.getCard(cardCt-1);//Cardjustdealt CardprevCard=hand.getCard(cardCt-2);//Thepreviousca rd. if(thisCard.getValue()<prevCard.getValue()){ gameInProgress=false;message="Toobad!Youlose."; }elseif(thisCard.getValue()==prevCard.getValue()){ gameInProgress=false;message="Toobad!Youloseonties."; }elseif(cardCt==4){ gameInProgress=false;message="Youwin!Youmadethreecorrectguesses."; }else{ message="Gotitright!Tryfor"+cardCt+"."; }repaint(); }//enddoHigher() <br /> <br /> PAGE 308<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 294 The paintComponent() methodofthe CardPanel classusesthevaluesinthestatevariables todecidewhattoshow.Itdisplaysthestringstoredinthe message variable.Itdrawseach ofthecardsinthe hand .Thereisonelittletrickybit:Ifagameisinprogress,itdr awsan extraface-downcard,whichisnotinthehand,torepresentt henextcardinthedeck.Drawing thecardsrequiressomecareandcomputation.Iwroteametho d,\ voiddrawCard(Graphics g,Cardcard,intx,inty) ",whichdrawsacardwithitsupperleftcorneratthepoint (x,y) .The paintComponent() routinedecideswheretodraweachcardandcallsthisroutin e todothedrawing.Youcancheckoutallthedetailsinthesour cecode, HighLowGUI.java Onefurthernoteontheprogrammingofthisexample:Thesour cecodedenes HighLowGUI asasubclassof JPanel .Theclasscontainsa main() routinesothatitcanberunasastand-alone application;the main() routinesimplyopensawindowthatusesapaneloftype HighLowGUI asitscontentpane.Inaddition,Idecidedtowriteanapplet versionoftheprogramasa staticnestedclassnamed Applet insidethe HighLowGUI class.Sincethisisanestedclass,its fullnameis HighLowGUI.Applet andtheclasslethatisproducedwhenthesourcecodeis compiledisnamed HighLowGUI$Applet.class .Thisclassisusedfortheappletversionofthe programintheon-lineversionofthebook.The < applet > tagliststheclasslefortheapplet as code="HighLowGUI$Applet.class" .Thisisadmittedlyanunusualwaytoorganizethe program,anditisprobablymorenaturaltohavethepanel,ap plet,andstand-aloneprogram denedinseparateclasses.However,writingtheprogramin thiswaydoesshowtherexibility ofJavaclasses.(Nestedclasseswerediscussedin Subsection5.7.2 .) 6.8MenusandDialogsW ehavealreadyencountered manyofthebasicaspectsofGUIprogramming,but (online) professionalprogramsusemanyadditionalfeatures.Wewil lcoversomeoftheadvancedfeatures ofJavaGUIprogrammingin Chapter12 ,butinthissectionwelookbrieryatafewmorebasic featuresthatareessentialforwritingGUIprograms.Iwill discussthesefeaturesinthecontext ofa\MosaicDraw"programthatisshowninthispicture: <br /> <br /> PAGE 309<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 295 Astheuserclicks-and-dragsthemouseinthelargedrawinga reaofthisprogram,itleavesa trailoflittlecoloredsquares.Thereissomerandomvariat ioninthecolorofthesquares.(This ismeanttomakethepicturelookalittlemorelikearealmosa ic,whichisapicturemadeoutof smallcoloredstonesinwhichtherewouldbesomenaturalcol orvariation.)Thereisamenubar abovethedrawingarea.The\Control"menucontainscommand sforllingandclearingthe drawingarea,alongwithafewoptionsthataecttheappeara nceofthepicture.The\Color" menuletstheuserselectthecolorthatwillbeusedwhentheu serdraws.The\Tools"menu aectsthebehaviorofthemouse.Usingthedefault\Draw"to ol,themouseleavesatrailof singlesquares.Usingthe\Draw3x3"tool,themouseleavesa swathofcoloredsquaresthatis threesquareswide.Therearealso\Erase"tools,whichlett heusersetsquaresbacktotheir defaultblackcolor. Thedrawingareaoftheprogramisapanelthatbelongstothe MosaicPanel class,asubclass of JPanel thatisdenedin MosaicPanel.java MosaicPanel isahighlyreusableclassforrepresentingmosaicsofcoloredrectangles.Itdoesnotdirectly supportdrawingonthemosaic,but itdoessupportsettingthecolorofeachindividualsquare. TheMosaicDrawprograminstallsa mouselisteneronthepanel;themouselistenerrespondstom ousePressedandmouseDragged eventsonthepanelbysettingthecolorofthesquarethatcon tainsthemouse.Thisisanice exampleofapplyingalistenertoanobjecttodosomethingth atwasnotprogrammedintothe objectitself. MostoftheprogrammingforMosaicDrawcanbefoundin MosaicDrawController.java .(It couldhavegoneintothe MosaicPanel class,ifIhadnotdecidedtousethatpre-existingclass inunmodiedform.)Itisthe MosaicDrawController classthatcreatesa MosaicPanel object andaddsamouselistenertoit.Italsocreatesthemenubarth atisshownatthetopof theprogramandimplementsallthecommandsinthemenubar.I thasaninstancemethod getMosaicPanel() thatreturnsareferencetothemosaicpanelthatithascreat ed,andit hasanotherinstancemethod getMenuBar() thatreturnsamenubarfortheprogram.These methodsareusedtoobtainthepanelandmenubarsothattheyc anbeaddedtoanappletor aframe. Togetaworkingprogram,anobjectoftype JApplet or JFrame isneeded.Theles MosaicDrawApplet.java and MosaicDrawFrame.java denetheappletandframeversionsof theprogram.Thesearerathersimpleclasses;theysimplycr eatea MosaicDrawController objectanduseitsmosaicpanelandmenubar.Iurgeyoutostud ytheseles,alongwith MosaicDrawController.java .Iwillnotbediscussingallaspectsofthecodehere,butyou shouldbeabletounderstanditallafterreadingthissectio n.Asfor MosaicPanel.java ,ituses sometechniquesthatyouwouldnotunderstandatthispoint, butIencourageyoutoatleast readthecommentsinthisletolearnabouttheAPIformosaic panels. 6.8.1MenusandMenubarsMosaicDrawistherstexamplethatwehaveseenthatusesame nubar.Fortunately,menus areveryeasytouseinJava.Theitemsinamenuarerepresente dbytheclass JMenuItem (this classandothermenu-relatedclassesareinpackage javax.swing ).Menuitemsareusedin almostexactlythesamewayasbuttons.Infact, JMenuItem and JButton arebothsubclasses ofaclass, AbstractButton ,thatdenestheircommonbehavior.Inparticular,a JMenuItem is createdusingaconstructorthatspeciesthetextofthemen uitem,suchas: JMenuItemfillCommand=newJMenuItem("Fill"); Youcanaddan ActionListener toa JMenuItem bycallingthemenuitem's addActionListener() <br /> <br /> PAGE 310<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 296 method.The actionPerformed() methodoftheactionlisteneriscalledwhentheuserselects theitemfromthemenu.Youcanchangethetextoftheitembyca llingits setText(String) method,andyoucanenableitanddisableitusingthe setEnabled(boolean) method.Allthis worksinexactlythesamewayasfora JButton Themaindierencebetweenamenuitemandabutton,ofcourse ,isthatamenuitem ismeanttoappearinamenuratherthaninapanel.AmenuinJav aisrepresentedby theclass JMenu .A JMenu hasaname,whichisspeciedintheconstructor,andithasan add(JMenuItem) methodthatcanbeusedtoadda JMenuItem tothemenu.So,the\Tools" menuintheMosaicDrawprogramcouldbecreatedasfollows,w here listener isavariableof type ActionListener : JMenutoolsMenu=newJMenu("Tools");//Createamenuwithn ame"Tools" JMenuItemdrawCommand=newJMenuItem("Draw");//Createa menuitem. drawCommand.addActionListener(listener);//Addlisten ertomenuitem. toolsMenu.add(drawCommand);//Addmenuitemtomenu.JMenuItemeraseCommand=newJMenuItem("Erase");//Creat eamenuitem. eraseCommand.addActionListener(listener);//Addliste nertomenuitem. toolsMenu.add(eraseCommand);//Addmenuitemtomenu. ..//Createandaddothermenuitems.. Onceamenuhasbeencreated,itmustbeaddedtoamenubar.Ame nubarisrepresented bytheclass JMenuBar .Amenubarisjustacontainerformenus.Itdoesnothaveanam e, anditsconstructordoesnothaveanyparameters.Ithasan add(JMenu) methodthatcanbe usedtoaddmenustothemenubar.Forexample,theMosaicDraw programusesthreemenus, controlMenu colorMenu ,and toolsMenu .Wecouldcreateamenubarandaddthemenusto itwiththestatements: JMenuBarmenuBar=newJMenuBar();menuBar.add(controlMenu);menuBar.add(colorMenu);menuBar.add(toolsMenu); Thenalstepinusingmenusistousethemenubarina JApplet or JFrame .Wehavealready seenthatanappletorframehasa\contentpane."Themenubar isanothercomponentofthe appletorframe,notcontainedinsidethecontentpane.Both the JApplet andthe JFrame classesincludeaninstancemethod setMenuBar(JMenuBar) thatcanbeusedtosetthemenu bar.(Therecanonlybeone,sothisisa\set"methodratherth anan\add"method.)Inthe MosaicDrawprogram,themenubariscreatedbya MosaicDrawController objectandcanbe obtainedbycallingthatobject's getMenuBar() method.Hereisthebasiccodethatisused(in somewhatmodiedform)tosetuptheinterfacebothintheapp letandintheframeversionof theprogram: MosaicDrawControllercontroller=newMosaicDrawControl ler(); MoasicPanelcontent=controller.getMosaicPanel();setContentPane(content);//Usepanelfromcontrollerasc ontentpane. JMenuBarmenuBar=controller.getMenuBar();setJMenuBar(menuBar);//Usethemenubarfromthecontroll er. <br /> <br /> PAGE 311<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 297 Usingmenusalwaysfollowsthesamegeneralpattern:Create amenubar.Createmenus andaddthemtothemenubar.Createmenuitemsandaddthemtot hemenus(andsetup listeningtohandleactioneventsfromthemenuitems).Uset hemenubarina JApplet or JFrame bycallingthe setJMenuBar() methodoftheappletorframe. Thereareotherkindsofmenuitems,denedbysubclassesof JMenuItem ,thatcanbeadded tomenus.Oneoftheseis JCheckBoxMenuItem ,whichrepresentsmenuitemsthatcanbeinone oftwostates,selectedornotselected.A JCheckBoxMenuItem hasthesamefunctionalityandis usedinthesamewayasa JCheckBox (see Subsection6.6.3 ).Three JCheckBoxMenuItems are usedinthe\Control"menuoftheMosaicDrawprogram.Onecan beusedtoturntherandom colorvariationofthesquaresonando.Anotherturnsasymm etryfeatureonando;when symmetryisturnedon,theuser'sdrawingisrerectedhorizo ntallyandverticallytoproducea symmetricpattern.Andthethirdcheckboxmenuitemshowsan dhidesthe\grouting"inthe mosaic;thegroutingisthegraylinesthataredrawnarounde achofthelittlesquaresinthe mosaic.Themenuitemthatcorrespondstothe\UseRandomnes s"optioninthe\Control" menucouldbesetupwiththestatements: JMenuItemuseRandomnessToggle=newJCheckBoxMenuItem(" UseRandomness"); useRandomnessToggle.addActionListener(listener);//S etupalistener. useRandomnessToggle.setSelected(true);//Randomnessi sinitiallyturnedon. controlMenu.add(useRandomnessToggle);//Addthemenuit emtothemenu. The\UseRandomness" JCheckBoxMenuItem correspondstoaboolean-valuedinstancevariablenamed useRandomness inthe MosaicDrawController class.Thisvariableispartofthestate ofthecontrollerobject.Itsvalueistestedwhenevertheus erdrawsoneofthesquares,todecide whetherornottoaddarandomvariationtothecolorofthesqu are.Whentheuserselects the\UseRandomness"commandfromthemenu,thestateofthe JCheckBoxMenuItem isreversed,fromselectedtonot-selectedorfromnot-selected toselected.The ActionListener for themenuitemcheckswhetherthemenuitemisselectedornot, anditchangesthevalueof useRandomness tomatch.Notethatselectingthemenucommanddoesnothavea nyimmediate eectonthepicturethatisshowninthewindow.Itjustchang esthestateoftheprogramso thatfuturedrawingoperationsonthepartoftheuserwillha veadierenteect.The\Use Symmetry"optioninthe\Control"menuworksinmuchthesame way.The\ShowGrouting" optionisalittledierent.Selectingthe\ShowGrouting"o ptiondoeshaveanimmediateeect: Thepictureisredrawnwithorwithoutthegrouting,dependi ngonthestateofthemenuitem. Myprogramusesasingle ActionListener torespondtoallofthemenuitemsinallthe menus.Thisisnotaparticularlygooddesign,butitiseasyt oimplementforasmallprogram likethisone.The actionPerformed() methodofthelistenerobjectusesthestatement Stringcommand=evt.getActionCommand(); togettheactioncommandofthesourceoftheevent;thiswill bethetextofthemenuitem. Thelistenerteststhevalueof command todeterminewhichmenuitemwasselectedbythe user.Ifthemenuitemisa JCheckBoxMenuItem ,thelistenermustcheckthestateofthemenu item.Thenmenuitemisthesourceoftheeventthatisbeingpr ocessed.Thelistenercan getitshandsonthemenuitemobjectbycalling evt.getSource() .Sincethereturnvalueof getSource() is Object ,thethereturnvaluemustbetype-casttothecorrecttype.H ere,for example,isthecodethathandlesthe\UseRandomness"comma nd: if(command.equals("UseRandomness")){ //SetthevalueofuseRandomnessdependingonthemenuitem' sstate. <br /> <br /> PAGE 312<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 298 JCheckBoxMenuItemtoggle=(JCheckBoxMenuItem)evt.getS ource(); useRandomness=toggle.isSelected(); } Inadditiontomenuitems,amenucancontainlinesthatsepar atethemenuitemsinto groups.IntheMosaicDrawprogram,the\Control"menuconta insaseparator.A JMenu has aninstancemethod addSeparator() thatcanbeusedtoaddaseparatortothemenu.For example,theseparatorinthe\Control"menuwascreatedwit hthestatement: controlMenu.addSeparator(); Amenucanalsocontainasubmenu.Thenameofthesubmenuappe arsasaniteminthe mainmenu.Whentheusermovesthemouseoverthesubmenuname ,thesubmenupopsup. (ThereisnoexampleofthisintheMosaicDrawprogram.)Itis veryeasytodothisinJava: Youcanaddone JMenu toanother JMenu usingastatementsuchas mainMenu.add(submenu) 6.8.2DialogsOneofthecommandsinthe\Color"menuoftheMosaicDrawprog ramis\CustomColor...". Whentheuserselectsthiscommand,anewwindowappearswher etheusercanselectacolor. Thiswindowisanexampleofa dialog or dialogbox .Adialogisatypeofwindowthatis generallyusedforshort,singlepurposeinteractionswith theuser.Forexample,adialogbox canbeusedtodisplayamessagetotheuser,toasktheuseraqu estion,tolettheuserselecta letobeopened,ortolettheuserselectacolor.InSwing,ad ialogboxisrepresentedbyan objectbelongingtotheclass JDialog ortoasubclass. The JDialog classisverysimilarto JFrame andisusedinmuchthesameway.Likea frame,adialogboxisaseparatewindow.Unlikeaframe,howe ver,adialogisnotcompletely independent.Everydialogisassociatedwithaframe(orano therdialog),whichiscalled its parentwindow .Thedialogboxisdependentonitsparent.Forexample,ifth eparentis closed,thedialogboxwillalsobeclosed.Itispossibletoc reateadialogboxwithoutspecifying aparent,butinthatcaseaaninvisibleframeiscreatedbyth esystemtoserveastheparent. Dialogboxescanbeeither modal or modeless .Whenamodaldialogiscreated,itsparent frameisblocked.Thatis,theuserwillnotbeabletointerac twiththeparentuntilthedialog boxisclosed.Modelessdialogboxesdonotblocktheirparen tsinthesameway,sotheyseem alotmorelikeindependentwindows.Inpractice,modaldial ogboxesareeasiertouseandare muchmorecommonthanmodelessdialogs.Alltheexampleswew illlookataremodal. Asidefromhavingaparent,a JDialog canbecreatedandusedinthesamewayasa JFrame However,Iwillnotgiveanyexampleshereofusing JDialog directly.Swinghasmanyconvenient methodsforcreatingmanycommontypesofdialogboxes.Fore xample,thecolorchoicedialog thatappearswhentheuserselectsthe\CustomColor"comman dintheMosaicDrawprogram belongstotheclass JColorChooser ,whichisasubclassof JDialog .The JColorChooser classhas astaticmethodstaticmethodthatmakescolorchoicedialog sveryeasytouse: ColorJColorChooser.showDialog(ComponentparentComp, Stringtitle,ColorinitialColor) Whenyoucallthismethod,adialogboxappearsthatallowsth eusertoselectacolor.The rstparameterspeciestheparentofthedialog;theparent windowofthedialogwillbethe window(ifany)thatcontains parentComp ;thisparametercanbe null anditcanitselfbea frameordialogobject.Thesecondparameterisastringthat appearsinthetitlebarofthe <br /> <br /> PAGE 313<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 299 dialogbox.Andthethirdparameter, initialColor ,speciesthecolorthatisselectedwhen thecolorchoicedialogrstappears.Thedialoghasasophis ticatedinterfacethatallowsthe usertochangetheselectedcolor.Whentheuserpressesan\O K"button,thedialogboxcloses andtheselectedcolorisreturnedasthevalueofthemethod. Theusercanalsoclicka\Cancel" buttonorclosethedialogboxinsomeotherway;inthatcase, null isreturnedasthevalue ofthemethod.Byusingthispredenedcolorchooserdialog, youcanwriteonelineofcode thatwilllettheuserselectanarbitrarycolor.Swingalsoh asa JFileChooser classthatmakes italmostaseasytoshowadialogboxthatletstheuserselect aletobeopenedorsaved. The JOptionPane classincludesavarietyofmethodsformakingsimpledialog boxesthat arevariationsonthreebasictypes:a\message"dialog,a\c onrm"dialog,andan\input" dialog.(Thevariationsallowyoutoprovideatitleforthed ialogbox,tospecifytheiconthat appearsinthedialog,andtoaddothercomponentstothedial ogbox.Iwillonlycoverthe mostbasicformshere.)Theon-lineversionofthissectioni ncludesanappletthatdemonstrates JOptionPane aswellas JColorChooser Amessagedialogsimplydisplaysamessagestringtotheuser .Theuser(hopefully)reads themessageanddismissesthedialogbyclickingthe\OK"but ton.Amessagedialogcanbe shownbycallingthestaticmethod: voidJOptionPane.showMessageDialog(ComponentparentCo mp,Stringmessage) Themessagecanbemorethanonelinelong.Linesinthemessag eshouldbeseparatedby newlinecharacters, \n .Newlineswillnotbeinsertedautomatically,eveniftheme ssageisvery long. Aninputdialogdisplaysaquestionorrequestandletstheus ertypeinastringasaresponse. Youcanshowaninputdialogbycalling: StringJOptionPane.showInputDialog(ComponentparentCo mp,Stringquestion) Again,thequestioncanincludenewlinecharacters.Thedia logboxwillcontainaninputbox, an\OK"button,anda\Cancel"button.Iftheuserclicks\Can cel",orclosesthedialogbox insomeotherway,thenthereturnvalueofthemethodis null .Iftheuserclicks\OK",then thereturnvalueisthestringthatwasenteredbytheuser.No tethatthereturnvaluecanbe anemptystring(whichisnotthesameasa null value),iftheuserclicks\OK"withouttyping anythingintheinputbox.Ifyouwanttouseaninputdialogto getanumericalvaluefrom theuser,youwillhavetoconvertthereturnvalueintoanumb er;see Subsection3.7.2 Finally,aconrmdialogpresentsaquestionandthreerespo nsebuttons:\Yes",\No",and \Cancel".Aconrmdialogcanbeshownbycalling: intJOptionPane.showConfirmDialog(ComponentparentCom p,Stringquestion) Thereturnvaluetellsyoutheuser'sresponse.Itisoneofth efollowingconstants: JOptionPane.YES OPTION |theuserclickedthe\Yes"button JOptionPane.NO OPTION |theuserclickedthe\No"button JOptionPane.CANCEL OPTION |theuserclickedthe\Cancel"button JOptionPane.CLOSE OPTION |thedialogwasclosedinsomeotherway. Bytheway,itispossibletoomittheCancelbuttonfromacon rmdialogbycallingoneof theothermethodsinthe JOptionPane class.Justcall: JOptionPane.showConfirmDialog( parent,question,title,JOptionPane.YES NO OPTION) <br /> <br /> PAGE 314<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 300 Thenalparameterisaconstantwhichspeciesthatonlya\Y es"buttonanda\No"button shouldbeused.Thethirdparameterisastringthatwillbedi splayedasthetitleofthedialog boxwindow. Ifyouwouldliketoseehowdialogsarecreatedandusedinthe sampleapplet,youcannd thesourcecodeinthele SimpleDialogDemo.java 6.8.3FinePointsofFramesInprevioussections,wheneverIusedaframe,Icreateda JFrame objectina main() routine andinstalledapanelasthecontentpaneofthatframe.Thisw orksne,butamoreobjectorientedapproachistodeneasubclassof JFrame andtosetupthecontentsoftheframe intheconstructorofthatclass.ThisiswhatIdidinthecase oftheMosaicDrawprogram. MosaicDrawFrame isdenedasasubclassof JFrame .Thedenitionofthisclassisveryshort, butitillustratesseveralnewfeaturesofframesthatIwant todiscuss: publicclassMosaicDrawFrameextendsJFrame{ publicstaticvoidmain(String[]args){ JFramewindow=newMosaicDrawFrame();window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE); window.setVisible(true); }publicMosaicDrawFrame(){ super("MosaicDraw");MosaicDrawControllercontroller=newMosaicDrawControl ler(); setContentPane(controller.getMosaicPanel());setJMenuBar(controller.getMenuBar());pack();Dimensionscreensize=Toolkit.getDefaultToolkit().get ScreenSize(); setLocation((screensize.width-getWidth())/2, (screensize.height-getHeight())/2); } } Theconstructorinthisclassbeginswiththestatement super("MosaicDraw") ,whichcalls theconstructorinthesuperclass, JFrame .Theparameterspeciesatitlethatwillappearin thetitlebarofthewindow.Thenextthreelinesoftheconstr uctorsetupthecontentsofthe window;a MosaicDrawController iscreated,andthecontentpaneandmenubarofthewindow areobtainedfromthecontroller.Thenextlineissomething new.If window isavariableof type JFrame (or JDialog ),thenthestatement window.pack() willresizethewindowsothatits sizematchesthepreferredsizeofitscontents.(Inthiscas e,ofcourse,\ pack() "isequivalent to\ this.pack() ";thatis,itreferstothewindowthatisbeingcreatedbythe constructor.) The pack() methodisusuallythebestwaytosetthesizeofawindow.Note thatitwillonly workcorrectlyifeverycomponentinthewindowhasacorrect preferredsize.Thisisonlya problemintwocases:whenapanelisusedasadrawingsurface andwhenapanelisusedas acontainerwitha null layoutmanager.Inboththesecasesthereisnowayforthesys temto determinethecorrectpreferredsizeautomatically,andyo ushouldsetapreferredsizebyhand. Forexample: panel.setPreferredSize(newDimension(400,250)); <br /> <br /> PAGE 315<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 301 Thelasttwolinesintheconstructorpositionthewindowsot hatitisexactlycenteredon thescreen.Theline Dimensionscreensize=Toolkit.getDefaultToolkit().get ScreenSize(); determinesthesizeofthescreen.Thesizeofthescreenis screensize.width pixelsinthehorizontaldirectionand screensize.height pixelsintheverticaldirection.The setLocation() methodoftheframesetsthepositionoftheupperleftcorner oftheframeonthescreen.The expression\ screensize.width-getWidth() "istheamountofhorizontalspaceleftonthe screenaftersubtractingthewidthofthewindow.Thisisdiv idedby2sothathalfoftheempty spacewillbetotheleftofthewindow,leavingtheotherhalf ofthespacetotherightofthe window.Similarly,halfoftheextraverticalspaceisabove thewindow,andhalfisbelow. Notethattheconstructorhascreatedthewindowandsetitss izeandposition,butthat attheendoftheconstructor,thewindowisnotyetvisibleon thescreen.(Moreexactly,the constructorhascreatedthewindow object ,butthevisualrepresentationofthatobjectonthe screenhasnotyetbeencreated.)Toshowthewindowonthescr een,itwillbenecessaryto callitsinstancemethod, window.setVisible(true) Inadditiontotheconstructor,the MosaicDrawFrame classincludesa main() routine.This makesitpossibletorun MosaicDrawFrame asastand-aloneapplication.(The main() routine,as a static method,hasnothingtodowiththefunctionofa MosaicDrawFrame object,anditcould (andperhapsshould)beinaseparateclass.)The main() routinecreatesa MosaicDrawFrame andmakesitvisibleonthescreen.Italsocalls window.setDefaultCloseOperation(JFrame.EXIT ON CLOSE); whichmeansthattheprogramwillendwhentheuserclosesthe window.Notethatthisisnot doneintheconstructorbecausedoingittherewouldmake MosaicDrawFrame lessrexible.It wouldbepossible,forexample,towriteaprogramthatletst heuseropenmultipleMosaicDraw windows.Inthatcase,wedon'twanttoendtheprogramjustbe causetheuserhasclosed one ofthewindows.Furthermore,itispossibleforanapplettoc reateaframe,whichwillopenas aseparatewindowonthescreen.Anappletisnotallowedto\t erminatetheprogram"(and it'snotevenclearwhatthatshouldmeaninthecaseofanappl et),andattemptingtodoso willproduceanexception.Thereareotherpossiblevaluesf orthedefaultcloseoperationofa window: JFrame.DO NOTHING ON CLOSE |theuser'sattemptstoclosethewindowbyclickingits closeboxwillbeignored. JFrame.HIDE ON CLOSE |whentheuserclicksitsclosebox,thewindowwillbehidden justasif window.setVisible(false) werecalled.Thewindowcanbemadevisibleagain bycalling window.setVisible(true) .Thisisthevaluethatisusedifyoudonotspecify anothervaluebycalling setDefaultCloseOperation JFrame.DISPOSE ON CLOSE |thewindowisclosedandanyoperatingsystemresources usedbythewindowarereleased.Itisnotpossibletomakethe windowvisibleagain. (Thisistheproperwaytopermanentlygetridofawindowwith outendingtheprogram. Youcanaccomplishthesamethingbycallingtheinstancemet hod window.dispose() .) I'vewrittenanappletversionoftheMosaicDrawprogramtha tappearsonaWebpageasa singlebutton.Whentheuserclicksthebutton,theappletop ensa MosaicDrawFrame .Inthis case,theappletsetsthedefaultcloseoperationofthewind owto JFrame.DISPOSE ON CLOSE Youcantrytheappletintheon-lineversionofthissection. <br /> <br /> PAGE 316<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 302 Thele MosaicDrawLauncherApplet.java containsthesourcecodefortheapplet.One interestingpointintheappletisthatthetextofthebutton changesdependingonwhethera windowisopenornot.Ifthereisnowindow,thetextreads\La unchMosaicDraw".When thewindowisopen,itchangesto\CloseMosaicDraw",andcli ckingthebuttonwillclosethe window.Thechangeisimplementedbyattachinga WindowListener tothewindow.Thelistener respondsto WindowEvent sthataregeneratedwhenthewindowopensandcloses.Althou ghI willnotdiscusswindoweventsfurtherhere,youcanlookatt hesourcecodeforanexampleof howtheycanbeused.6.8.4CreatingJarFilesAsthenaltopicforthischapter,welookagainatjarles.R ecallthatajarleisa\java archive"thatcancontainanumberofclassles.Whencreati ngaprogramthatusesmorethan oneclass,it'susuallyagoodideatoplacealltheclassesth atarerequiredbytheprograminto ajarle,sincethenauserwillonlyneedthatoneletorunth eprogram. Subsection6.2.4 discusseshowajarlecanbeusedforanapplet.Jarlescana lsobeusedforstand-alone applications.Infact,itispossibletomakeaso-called executablejarle .Ausercanrunan executablejarleinmuchthesamewayasanyotherapplicati on,usuallybydouble-clicking theiconofthejarle.(Theuser'scomputermusthaveacorre ctversionofJavainstalled,and thecomputermustbeconguredcorrectlyforthistowork.Th econgurationisusuallydone automaticallywhenJavaisinstalled,atleastonWindowsan dMacOS.) Thequestion,then,ishowtocreateajarle.Theanswerdepe ndsonwhatprogramming environmentyouareusing.Thetwobasictypesofprogrammin genvironment|commandline andIDE|werediscussedin Section2.6 .AnyIDE(IntegratedProgrammingEnvironment) forJavashouldhaveacommandforcreatingjarles.IntheEc lipseIDE,forexample,it's doneasfollows:InthePackageExplorerpane,selectthepro grammingproject(orjustallthe individualsourcecodelesthatyouneed).Right-clickont heselection,andchoose\Export" fromthemenuthatpopsup.Inthewindowthatappears,select \JARle"andclick\Next". Inthewindowthatappearsnext,enteranameforthejarlein theboxlabeled\JARle". (Clickthe\Browse"buttonnexttothisboxtoselectthelen ameusingaledialogbox.)The nameoftheleshouldendwith\.jar".Ifyouarecreatingare gularjarle,notanexecutable one,youcanhit\Finish"atthispoint,andthejarlewillbe created.Youcoulddothis,for example,ifthejarlecontainsanappletbutnomainprogram .Tocreateanexecutablele, hitthe\Next"button twice togettothe\JarManifestSpecication"screen.Atthebott om ofthisscreenisaninputboxlabeled\Mainclass".Youhavet oenterthenameoftheclass thatcontainsthe main() routinethatwillberunwhenthejarleisexecuted.Ifyouhi tthe \Browse"buttonnexttothe\Mainclass"box,youcanselectt heclassfromalistofclasses thatcontain main() routines.Onceyou'veselectedthemainclass,youcanclick the\Finish" buttontocreatetheexecutablejarle. Itisalsopossibletocreatejarlesonthecommandline.The JavaDevelopmentKit includesacommand-lineprogramnamed jar thatcanbeusedtocreatejarles.Ifallyour classesareinthedefaultpackage(liketheexamplesinthis book),thenthe jar commandis easytouse.Tocreateanon-executablejarleonthecommand line,changetothedirectory thatcontainstheclasslesthatyouwanttoincludeintheja r.Thengivethecommand jarcfJarFileName.jar*.class where JarFileName canbeanynamethatyouwanttouseforthejarle.The\ "in\ *.class isawildcardthatmakes *.class matcheveryclassleinthecurrentdirectory.Thismeans <br /> <br /> PAGE 317<br /> <br /> CHAPTER6.INTRODUCTIONTOGUIPROGRAMMING 303 thatalltheclasslesinthedirectorywillbeincludedinth ejarle.Ifyouwanttoinclude onlycertainclassles,youcannamethemindividually,sep aratedbyspaces.(Thingsgetmore complicatedifyourclassesarenotinthedefaultpackage.I nthatcase,theclasslesmustbe insubdirectoriesofthedirectoryinwhichyouissuethejar le.See Subsection2.6.4 .) Makinganexecutablejarleonthecommandlineisalittlemo recomplicated.Therehas tobesomewayofspecifyingwhichclasscontainsthe main() routine.Thisisdonebycreating a manifestle .Themanifestlecanbeaplaintextlecontainingasinglel ineoftheform Main-Class:ClassName where ClassName shouldbereplacedbythenameoftheclassthatcontainsthe main() routine. Forexample,ifthe main() routineisintheclass MosaicDrawFrame ,thenthemanifestleshould read\ Main-Class:MosaicDrawFrame ".Youcangivethemanifestleanynameyoulike. Putitinthesamedirectorywhereyouwillissuethe jar command,anduseacommandofthe form jarcmfManifestFileNameJarFileName.jar*.class tocreatethejarle.(The jar commandiscapableofperformingavarietyofdierentopera tions.Therstparametertothecommand,suchas\ cf "or\ cmf ",tellsitwhichoperationto perform.) Bytheway,ifyouhavesuccessfullycreatedanexecutableja rle,youcanrunitonthe commandlineusingthecommand\ java-jar ".Forexample: java-jarJarFileName.jar <br /> <br /> PAGE 318<br /> <br /> Exercises 304 ExercisesforChapter6 1. Inthe SimpleStamperPanel examplefrom Subsection6.4.2 ,arectangleorovalisdrawnon (solution) thepanelwhentheuserclicksthemouse,exceptthatwhenthe usershift-clicks,thepanel isclearedinstead.Modifythisclasssothatthemodiedver sionwillcontinuetodraw guresastheuserdragsthemouse.Thatis,themousewilllea veatrailofguresasthe userdragsthemouse.However,iftheusershift-clicks,the panelshouldsimplybecleared andnoguresshouldbedrawneveniftheuserdragsthemousea ftershift-clicking.Use yourpaneleitherinanappletorinastand-aloneapplicatio n(orboth).Hereisapicture ofmysolution: Thesourcecodefortheoriginalpanelclassis SimpleStamperPanel.java .Anapplet thatusesthisclasscanbefoundin SimpleStamperApplet.java ,andamainprogramthat usesthepanelinaframeisin SimpleStamper.java .Seethediscussionofdraggingin Subsection6.4.4 .(Notethatintheoriginalversion,Idrewablackoutlinear oundeach shape.Inthemodiedversion,Idecidedthatitwouldlookbe ttertodrawagrayoutline instead.) 2. Writeapanelthatshowsasmallredsquareandasmallbluesqu are.Theusershouldbe (solution) abletodrageithersquarewiththemouse.(You'llneedanins tancevariabletoremember whichsquaretheuserisdragging.)Theusercandragthesqua reotheappletifshe wants;ifshedoesthis,it'sgone.Useyourpanelineitheran appletorastand-alone application. 3. Writeapanelthatshowsapairofdice.Whentheuserclickson thepanel,thediceshould (solution) berolled(thatis,thediceshouldbeassignednewlycompute drandomvalues).Eachdie shouldbedrawnasasquareshowingfrom1to6dots.Sinceyouh avetodrawtwodice, itsagoodideatowriteasubroutine,\ voiddrawDie(Graphicsg,intval,intx, inty) ",todrawadieatthespecied (x,y) coordinates.Thesecondparameter, val speciesthevaluethatisshowingonthedie.Assumethatthe sizeofthepanelis100 by100pixels.Alsowriteanappletthatusesyourpanelasits contentpane.Hereisa pictureoftheapplet: <br /> <br /> PAGE 319<br /> <br /> Exercises 305 4. InExercise6.3,youwroteapair-of-dicepanelwherethedic earerolledwhentheuser (solution) clicksonthepanelNowmakeapair-of-diceprograminwhicht heuserrollsthediceby clickingabutton.Thebuttonshouldappearunderthepanelt hatshowsthedice.Also makethefollowingchange:Whenthedicearerolled,instead ofjustshowingthenew value,showashortanimationduringwhichthevaluesonthed icearechangedinevery frame.Theanimationissupposedtomakethedicelookmoreli ketheyareactuallyrolling. Writeyourprogramasastand-aloneapplication. 5. InExercise3.6,youdrewacheckerboard.Forthisexercise, writeacheckerboardapplet (solution) wheretheusercanselectasquarebyclickingonit.Hiliteth eselectedsquarebydrawing acoloredborderaroundit.Whentheappletisrstcreated,n osquareisselected.When theuserclicksonasquarethatisnotcurrentlyselected,it becomesselected.Iftheuser clicksthesquarethatisselected,itbecomesunselected.A ssumethatthesizeoftheapplet isexactly160by160pixels,sothateachsquareonthechecke rboardis20by20pixels. 6. Forthisexercise,youshouldmodifytheSubKillergamefrom Subsection6.5.4 .Youcan (solution) startwiththeexistingsourcecode,fromthele SubKillerPanel.java .Modifythegame soitkeepstrackofthenumberofhitsandmissesanddisplays thesequantities.That is,everytimethedepthchargeblowsupthesub,thenumberof hitsgoesupbyone. Everytimethedepthchargefallsothebottomofthescreenw ithouthittingthesub,the numberofmissesgoesupbyone.Thereisroomatthetopofthep aneltodisplaythese numbers.Todothisexercise,youonlyhavetoaddahalf-doze nlinestothesourcecode. Butyouhavetogureoutwhattheyareandwheretoaddthem.To dothis,you'llhave toreadthesourcecodecloselyenoughtounderstandhowitwo rks. 7. Exercise5.2involvedaclass, StatCalc.java ,thatcouldcomputesomestatisticsofasetof (solution) numbers.Writeaprogramthatusesthe StatCalc classtocomputeanddisplaystatistics ofnumbersenteredbytheuser.Thepanelwillhaveaninstanc evariableoftype StatCalc thatdoesthecomputations.Thepanelshouldincludea JTextField wheretheuserenters anumber.Itshouldhavefourlabelsthatdisplayfourstatis ticsforthenumbersthathave beenentered:thenumberofnumbers,thesum,themean,andth estandarddeviation. Everytimetheuserentersanewnumber,thestatisticsdispl ayedonthelabelsshould change.Theuserentersanumberbytypingitintothe JTextField andpressingreturn. Thereshouldbea\Clear"buttonthatclearsoutallthedata. Thismeanscreatinganew StatCalc objectandresettingthedisplaysonthelabels.Mypanelals ohasan\Enter" buttonthatdoesthesamethingaspressingthereturnkeyint he JTextField .(Recallthat a JTextField generatesan ActionEvent whentheuserpressesreturn,soyourpanelshould registeritselftolistenfor ActionEvents fromthe JTextField .)Writeyourprogramasa stand-aloneapplication.Hereisapictureofmysolutionto thisproblem: <br /> <br /> PAGE 320<br /> <br /> Exercises 306 8. Writeapanelwitha JTextArea wheretheusercanentersometext.Thepanelshould (solution) haveabutton.Whentheuserclicksonthebutton,thepanelsh ouldcountthenumber oflinesintheuser'sinput,thenumberofwordsintheuser's input,andthenumberof charactersintheuser'sinput.Thisinformationshouldbed isplayedonthreelabelsin thepanel.Recallthatif textInput isa JTextArea ,thenyoucangetthecontentsofthe JTextArea bycallingthefunction textInput.getText() .Thisfunctionreturnsa String containingallthetextfromthetextarea.Thenumberofchar actersisjustthelength ofthis String .Linesinthe String areseparatedbythenewlinecharacter, '\n' ,sothe numberoflinesisjustthenumberofnewlinecharactersinth e String ,plusone.Words arealittlehardertocount.Exercise3.4hassomeadviceabo utndingthewordsina String .Essentially,youwanttocountthenumberofcharacterstha tarerstcharacters inwords.Don'tforgettoputyour JTextArea ina JScrollPane ,andaddthescrollpaneto thecontainer,notthetextarea.Scrollbarsshouldappearw hentheusertypesmoretext thanwilltintheavailablearea.Hereisapictureofmysolu tion: 9. WriteaBlackjackprogramthatletstheuserplayagameofBla ckjack,withthecomputer (solution) asthedealer.Theappletshoulddrawtheuser'scardsandthe dealer'scards,justaswas doneforthegraphicalHighLowcardgamein Subsection6.7.6 .Youcanusethesource codeforthatgame, HighLowGUI.java ,forsomeideasabouthowtowriteyourBlackjack game.ThestructuresoftheHighLowpanelandtheBlackjackp anelareverysimilar.You willcertainlywanttousethe drawCard() methodfromtheHighLowprogram. <br /> <br /> PAGE 321<br /> <br /> Exercises 307 YoucanndadescriptionofthegameofBlackjackinExercise 5.5.Addthefollowing ruletothatdescription:Ifaplayertakesvecardswithout goingover21,thatplayerwins immediately.Thisruleisusedinsomecasinos.Foryourprog ram,itmeansthatyouonly havetoallowroomforvecards.Youshouldassumethatthepa nelisjustwideenough toshowvecards,andthatitistallenoughshowtheuser'sha ndandthedealer'shand. NotethatthedesignofaGUIBlackjackgameisverydierentf romthedesignofthe text-orientedprogramthatyouwroteforExercise5.5.Theu sershouldplaythegameby clickingon\Hit"and\Stand"buttons.Thereshouldbea\New Game"buttonthatcan beusedtostartanothergameafteronegameends.Youhavetod ecidewhathappens wheneachofthesebuttonsispressed.Youdon'thavemuchcha nceofgettingthisright unlessyouthinkintermsofthestatesthatthegamecanbeina ndhowthestatecan change. Yourprogramwillneedtheclassesdenedin Card.java Hand.java Deck.java ,and BlackjackHand.java 10. IntheBlackjackgamefromExercise6.9,theusercanclickon the\Hit",\Stand",and (solution) \NewGame"buttonsevenwhenitdoesn'tmakesensetodoso.It wouldbebetterifthe buttonsweredisabledattheappropriatetimes.The\NewGam e"buttonshouldbedisabledwhenthereisagameinprogress.The\Hit"and\Stand"b uttonsshouldbedisabled whenthereisnotagameinprogress.Theinstancevariable gameInProgress tellswhether ornotagameisinprogress,soyoujusthavetomakesurethatt hebuttonsareproperly enabledanddisabledwheneverthisvariablechangesvalue. Istronglyadvisewritingasubroutinethatcanbecalledwheneveritisnecessarytosetthe valueofthe gameInProgress variable.Thenthesubroutinecantakeresponsibilityfore nablinganddisablingthebuttons.Recallthatif bttn isavariableoftype JButton ,then bttn.setEnabled(false) disablesthebuttonand bttn.setEnabled(true) enablesthebutton. Asasecond(andmoredicult)improvement,makeitpossible fortheusertoplace betsontheBlackjackgame.Whentheappletstarts,givetheu ser$100.Adda JTextField tothestripofcontrolsalongthebottomoftheapplet.Theus ercanenterthebetin this JTextField .Whenthegamebegins,checktheamountofthebet.Youshould dothis whenthegamebegins,notwhenitends,becauseseveralerror scanoccur:Thecontents ofthe JTextField mightnotbealegalnumber.Thebetthattheuserplacesmight be moremoneythantheuserhas,oritmightbe < =0.Youshoulddetecttheseerrorsand showanerrormessageinsteadofstartingthegame.Theuser' sbetshouldbeanintegral numberofdollars. Itwouldbeagoodideatomakethe JTextField uneditablewhilethegameisinprogress. If betInput isthe JTextField ,youcanmakeiteditableanduneditablebytheuserwith thecommands betInput.setEditable(true) and betInput.setEditable(false) Inthe paintComponent() method,youshouldincludecommandstodisplaythe amountofmoneythattheuserhasleft. Thereisoneotherthingtothinkabout:Ideally,theapplets houldnotstartanew gamewhenitisrstcreated.Theusershouldhaveachancetos etabetamountbefore thegamestarts.So,intheconstructorforthedrawingsurfa ceclass,youshouldnotcall doNewGame() .Youmightwanttodisplayamessagesuchas\WelcometoBlack jack" beforetherstgamestarts. Hereisapictureofmyprogram: <br /> <br /> PAGE 322<br /> <br /> Exercises 308 <br /> <br /> PAGE 323<br /> <br /> Quiz 309 QuizonChapter6 (answers) 1. Programswrittenforagraphicaluserinterfacehavetodeal with\events."Explainwhat ismeantbytheterm event. Giveatleasttwodierentexamplesofevents,anddiscuss howaprogrammightrespondtothoseevents. 2. Explaincarefullywhatthe repaint() methoddoes. 3. WhatisHTML? 4. Javahasastandardclasscalled JPanel .Discuss two waysinwhichJPanelscanbeused. 5. Drawthepicturethatwillbeproducedbythefollowing paintComponent() method: publicstaticvoidpaintComponent(Graphicsg){ super.paintComponent(g);for(inti=10;i<=210;i=i+50) for(intj=10;j<=210;j=j+50) g.drawLine(i,10,j,60); } 6. Supposeyouwouldlikeapanelthatdisplaysagreensquarein sidearedcircle,asillustrated.Writea paintComponent() methodforthepanelclassthatwilldrawtheimage. 7. Javahasastandardclasscalled MouseEvent .Whatisthepurposeofthisclass?What doesanobjectoftype MouseEvent do? 8. OneofthemainclassesinSwingisthe JComponent class.Whatismeantbyacomponent? Whataresomeexamples? 9. Whatisthefunctionofa LayoutManager inJava? 10. Whattypeoflayoutmanagerisbeingusedforeachofthethree panelsinthefollowing illustrationfrom Section6.7 ? <br /> <br /> PAGE 324<br /> <br /> Quiz 310 Ž   ‘ ‘ ’ “ ” ‘ • – — –  ™ ” š ” › •  — › ” œ “ š ” š ”  – š œ  ‘  › Ÿ ’ ” ‘ ” œ – — –  ™ ” š ”   “   ¡ 11. Explainhow Timers areusedtodoanimation. 12. Whatisa JCheckBox andhowisitused? <br /> <br /> PAGE 325<br /> <br /> Chapter7ArraysC omputersgetalotoftheirpower fromworkingwith datastructures .Adata structureisanorganizedcollectionofrelateddata.Anobj ectisadatastructure,butthis typeofdatastructure|consistingofafairlysmallnumbero fnamedinstancevariables|isjust thebeginning.Inmanycases,programmersbuildcomplicate ddatastructuresbyhand,by linkingobjectstogether.We'lllookatthesecustom-built datastructuresin Chapter9 .But thereisonetypeofdatastructurethatissoimportantandso basicthatitisbuiltintoevery programminglanguage:thearray. An array isadatastructureconsistingofanumberedlistofitems,wh erealltheitemsare ofthesametype.InJava,theitemsinanarrayarealwaysnumb eredfromzerouptosome maximumvalue,whichissetwhenthearrayiscreated.Forexa mple,anarraymightcontain 100integers,numberedfromzeroto99.Theitemsinanarrayc anbelongtooneofJava's primitivetypes.Theycanalsobereferencestoobjects,sot hatyoucould,forexample,make anarraycontainingallthebuttonsinaGUIprogram. ThischapterdiscusseshowarraysarecreatedandusedinJav a.Italsocoversthestandard class java.util.ArrayList .Anobjectoftype ArrayList isverysimilartoanarrayof Objects butitcangrowtoholdanynumberofitems.7.1CreatingandUsingArraysW henanumberofdataitems arechunkedtogetherintoaunit,theresultisa data (online) structure .Datastructurescanbeverycomplex,butinmanyapplicatio ns,theappropriate datastructureconsistssimplyofasequenceofdataitems.D atastructuresofthissimplevariety canbeeither arrays or records Theterm\record"isnotusedinJava.Arecordisessentially thesameasaJavaobject thathasinstancevariablesonly,butnoinstancemethods.S omeotherlanguages,whichdonot supportobjectsingeneral,neverthelessdosupportrecord s.TheCprogramminglanguage,for example,isnotobject-oriented,butithasrecords,whichi nCgobythename\struct."The dataitemsinarecord|inJava,anobject'sinstancevariabl es|arecalledthe elds ofthe record.Eachitemisreferredtousinga eldname .InJava,eldnamesarejustthenames oftheinstancevariables.Thedistinguishingcharacteris ticsofarecordarethatthedataitems intherecordarereferredtobynameandthatdierenteldsi narecordareallowedtobeof dierenttypes.Forexample,iftheclass Person isdenedas: classPerson{ Stringname; 311 <br /> <br /> PAGE 326<br /> <br /> CHAPTER7.ARRAYS 312 intid number; Datebirthday;intage; } thenanobjectofclass Person couldbeconsideredtobearecordwithfourelds.Theeld namesare name id number birthday ,and age .Notethattheeldsareofvarioustypes: String int ,and Date Becauserecordsarejustaspecialtypeofobject,Iwillnotd iscussthemfurther. 7.1.1ArraysLikearecord,anarrayisasequenceofitems.However,where itemsinarecordarereferred toby name ,theitemsinanarrayarenumbered,andindividualitemsare referredtobytheir positionnumber .Furthermore,alltheitemsinanarraymustbeofthesametyp e.The denitionofanarrayis:anumberedsequenceofitems,which areallofthesametype.The numberofitemsinanarrayiscalledthe length ofthearray.Thepositionnumberofanitem inanarrayiscalledthe index ofthatitem.Thetypeoftheindividualitemsinanarrayis calledthe basetype ofthearray. ThebasetypeofanarraycanbeanyJavatype,thatis,oneofth eprimitivetypes,oraclass name,oraninterfacename.Ifthebasetypeofanarrayis int ,itisreferredtoasan\arrayof ints ."Anarraywithbasetype String isreferredtoasan\arrayof Strings ."However,anarray isnot,properlyspeaking,alistofintegersorstringsorot her values .Itisbetterthoughtofas alistof variables oftype int ,oroftype String ,orofsomeothertype.Asalways,thereissome potentialforconfusionbetweenthetwousesofavariable:a sanameforamemorylocation andasanameforthevaluestoredinthatmemorylocation.Eac hpositioninanarrayactsas avariable.Eachpositioncanholdavalueofaspeciedtype( thebasetypeofthearray).The valuecanbechangedatanytime.Valuesarestored in anarray.Thearray is thecontainer, notthevalues. Theitemsinanarray|really,theindividualvariablesthat makeupthearray|aremore oftenreferredtoasthe elements ofthearray.InJava,theelementsinanarrayarealways numberedstartingfromzero.Thatis,theindexoftherstel ementinthearrayiszero.Ifthe lengthofthearrayis N ,thentheindexofthelastelementinthearrayis N-1 .Onceanarray hasbeencreated,itslengthcannotbechanged. Javaarraysare objects .Thishasseveralconsequences.Arraysarecreatedusingaf ormof the new operator.Novariablecanever hold anarray;avariablecanonly refer toanarray. Anyvariablethatcanrefertoanarraycanalsoholdthevalue null ,meaningthatitdoesn't atthemomentrefertoanything.Likeanyobject,anarraybel ongstoaclass,whichlikeall classesisasubclassoftheclass Object .Theelementsofthearrayare,essentially,instance variablesinthearrayobject,exceptthattheyarereferred tobynumberratherthanbyname. Nevertheless,eventhougharraysareobjects,therearedi erencesbetweenarraysandother kindsofobjects,andthereareanumberofspeciallanguagef eaturesinJavaforcreatingand usingarrays.7.1.2UsingArraysSupposethat A isavariablethatreferstoanarray.Thentheelementatinde x k in A isreferred toas A[k] .Therstelementis A[0] ,thesecondis A[1] ,andsoforth.\ A[k] "isreallya variable,anditcanbeusedjustlikeanyothervariable.You canassignvaluestoit,youcan <br /> <br /> PAGE 327<br /> <br /> CHAPTER7.ARRAYS 313 useitinexpressions,andyoucanpassitasaparametertoasu broutine.Allofthiswillbe discussedinmoredetailbelow.Fornow,justkeepinmindthe syntax h array-variable i [ h integer-expression i ] forreferringtoanelementofanarray. Althougheveryarray,asanobject,belongstosomeclass,ar rayclassesneverhavetobe dened.Onceatypeexists,thecorrespondingarrayclassex istsautomatically.Ifthename ofthetypeis BaseType ,thenthenameoftheassociatedarrayclassis BaseType[] .Thatis tosay,anobjectbelongingtotheclass BaseType[] isanarrayofitems,whereeachitemisa variableoftype BaseType .Thebrackets,\ [] ",aremeanttorecallthesyntaxforreferringto theindividualitemsinthearray.\ BaseType[] "isreadas\arrayofBaseType"or\BaseType array."Itmightbeworthmentioningherethatif ClassA isasubclassof ClassB ,thentheclass ClassA[] isautomaticallyasubclassof ClassB[] ThebasetypeofanarraycanbeanylegalJavatype.Fromthepr imitivetype int ,the arraytype int[] isderived.Eachelementinanarrayoftype int[] isavariableoftype int ,which holdsavalueoftype int .Fromaclassnamed Shape ,thearraytype Shape[] isderived.Each iteminanarrayoftype Shape[] isavariableoftype Shape ,whichholdsavalueoftype Shape Thisvaluecanbeeither null orareferencetoanobjectbelongingtotheclass Shape .(This includesobjectsbelongingtosubclassesof Shape .) Let'strytogetalittlemoreconcreteaboutallthis,usinga rraysofintegersasourrst example.Since int[] isaclass,itcanbeusedtodeclarevariables.Forexample, int[]list; createsavariablenamed list oftype int[] .Thisvariableis capable ofreferringtoanarray of ints ,butinitiallyitsvalueis null (if list isamembervariableinaclass)orundened(if list isalocalvariableinamethod).The new operatorisusedtocreateanewarrayobject, whichcanthenbeassignedto list .Thesyntaxforusing new witharraysisdierentfromthe syntaxyoulearnedpreviously.Asanexample, list=newint[5]; createsanarrayofveintegers.Moregenerally,theconstr uctor\ newBaseType[N] "isusedto createanarraybelongingtotheclass BaseType[] .Thevalue N inbracketsspeciesthelength ofthearray,thatis,thenumberofelementsthatitcontains .Notethatthearray\knows" howlongitis.Thelengthofthearrayisaninstancevariable inthearrayobject.Infact,the lengthofanarray, list ,canbereferredtoas list.length .(However,youarenotallowedto changethevalueof list.length ,soit'sreallya\ final "instancevariable,thatis,onewhose valuecannotbechangedafterithasbeeninitialized.) Thesituationproducedbythestatement\ list=newint[5]; "canbepicturedlikethis: ¢ £ ¤ ¦ § ¨ ¢ £ ¤ ¢ ¢ £ ¤ ¢ £ ¤ ¢ £ ¤ ¢ £ ¤ ¢ £ ¤ <br /> <br /> PAGE 328<br /> <br /> CHAPTER7.ARRAYS 314 Notethatthenewlycreatedarrayofintegersisautomatical lylledwithzeros.InJava,a newlycreatedarrayis always lledwithaknown,defaultvalue:zerofornumbers, false for boolean ,thecharacterwithUnicodenumberzerofor char ,and null forobjects. Theelementsinthearray, list ,arereferredtoas list[0] list[1] list[2] list[3] and list[4] .(Noteagainthattheindexforthelastitemisonelessthan list.length .) However,arrayreferencescanbemuchmoregeneralthanthis .Thebracketsinanarray referencecancontainanyexpressionwhosevalueisaninteg er.Forexampleif indx isa variableoftype int ,then list[indx] and list[2*indx+7] aresyntacticallycorrectreferences toelementsofthearray list .Thus,thefollowingloopwouldprintalltheintegersinthe array, list ,tostandardoutput: for(inti=0;i<list.length;i++){ System.out.println(list[i]); } Thersttimethroughtheloop, i is0,and list[i] refersto list[0] .So,itisthevalue storedinthevariable list[0] thatisprinted.Thesecondtimethroughtheloop, i is1,and thevaluestoredin list[1] isprinted.Theloopendsafterprintingthevalueof list[4] when i becomesequalto5andthecontinuationcondition\ i<list.length "isnolonger true.Thisisatypicalexampleofusingalooptoprocessanar ray.I'lldiscussmoreexamples ofarrayprocessingthroughoutthischapter. Everyuseofavariableinaprogramspeciesamemorylocatio n.Thinkforamoment aboutwhatthecomputerdoeswhenitencountersareferencet oanarrayelement, list[k] whileitisexecutingaprogram.Thecomputermustdetermine whichmemorylocationisbeing referredto.Tothecomputer, list[k] meanssomethinglikethis:\Getthepointerthatis storedinthevariable, list .Followthispointertondanarrayobject.Getthevalueof k Gotothe k -thpositioninthearray,andthat'sthememorylocationyou want."Therearetwo thingsthatcangowronghere.Supposethatthevalueof list is null .Ifthatisthecase, then list doesn'tevenrefertoanarray.Theattempttorefertoanelem entofanarraythat doesn'texistisanerrorthatwillcauseanexceptionoftype NullPointerException tobethrown. Thesecondpossibleerroroccursif list doesrefertoanarray,butthevalueof k isoutsidethe legalrangeofindicesforthatarray.Thiswillhappenif k<0 orif k>=list.length .This iscalledan\arrayindexoutofbounds"error.Whenanerroro fthistypeoccurs,anexception oftype ArrayIndexOutOfBoundsException isthrown.Whenyouusearraysinaprogram,you shouldbemindfulthatbothtypesoferrorsarepossible.How ever,arrayindexoutofbounds errorsarebyfarthemostcommonerrorwhenworkingwitharra ys. 7.1.3ArrayInitializationForanarrayvariable,justasforanyvariable,youcandecla rethevariableandinitializeitin asinglestep.Forexample, int[]list=newint[5]; If list isalocalvariableinasubroutine,thenthisisexactlyequi valenttothetwostatements: int[]list;list=newint[5]; (If list isaninstancevariable,thenofcourseyoucan'tsimplyrepl ace\ int[]list=new int[5]; "with\ int[]list;list=newint[5]; "sincetheassignmentstatement\ list= newint[5]; "isonlylegalinsideasubroutine.) <br /> <br /> PAGE 329<br /> <br /> CHAPTER7.ARRAYS 315 Thenewarrayislledwiththedefaultvalueappropriatefor thebasetypeofthearray|zero for int and null forclasstypes,forexample.However,Javaalsoprovidesaw aytoinitializean arrayvariablewithanewarraylledwithaspeciedlistofv alues.Inadeclarationstatement thatcreatesanewarray,thisisdonewithan arrayinitializer .Forexample, int[]list={1,4,9,16,25,36,49}; createsanewarraycontainingthesevenvalues1,4,9,16,25 ,36,and49,andsets list to refertothatnewarray.Thevalueof list[0] willbe1,thevalueof list[1] willbe4,andso forth.Thelengthof list isseven,sincesevenvaluesareprovidedintheinitializer Anarrayinitializertakestheformofalistofvalues,separ atedbycommasandenclosed betweenbraces.Thelengthofthearraydoesnothavetobespe cied,becauseitisimplicitin thelistofvalues.Theitemsinanarrayinitializerdon'tha vetobeconstants.Theycanbe variablesorarbitraryexpressions,providedthattheirva luesareoftheappropriatetype.For example,thefollowingdeclarationcreatesanarrayofeigh t Colors .Someofthecolorsaregiven byexpressionsoftheform\ newColor(r,g,b) "insteadofbyconstants: Color[]palette={ Color.BLACK,Color.RED,Color.PINK,newColor(0,180,0),//darkgreenColor.GREEN,Color.BLUE,newColor(180,180,255),//lightblueColor.WHITE }; Alistinitializerofthisformcanbeused only inadeclarationstatement,togivean initialvaluetoanewlydeclaredarrayvariable.Itcannotb eusedinanassignmentstatement toassignavaluetoavariablethathasbeenpreviouslydecla red.However,thereisanother, similarnotationforcreatinganewarraythatcanbeusedina nassignmentstatementorpassed asaparametertoasubroutine.Thenotationusesanotherfor mofthe new operatortoboth createandinitializeanewarrayobjectatthesametime.(Th eratheroddsyntaxissimilarto thesyntaxforanonymousclasses,whichwerediscussedin Subsection5.7.3 .)Forexampleto assignanewvaluetoanarrayvariable, list ,thatwasdeclaredpreviously,youcoulduse: list=newint[]{1,8,27,64,125,216,343}; Thegeneralsyntaxforthisformofthe new operatoris new h base-type i []{ h list-of-values i } Thisisactuallyanexpressionwhosevalueisareferencetoa newlycreatedarrayobject.This meansthatitcanbeusedinanycontextwhereanobjectoftype h base-type i [] isexpected. Forexample,if makeButtons isamethodthattakesanarrayof Strings asaparameter,you couldsay: makeButtons(newString[]{"Stop","Go","Next","Previou s"}); Beingabletocreateanduseanarray\inplace"inthiswaycan beveryconvenient,inthe samewaythatanonymousnestedclassesareconvenient. Bytheway,itisperfectlylegaltousethe\ newBaseType[]{...} "syntaxinsteadof thearrayinitializersyntaxinthedeclarationofanarrayv ariable.Forexample,insteadof saying: <br /> <br /> PAGE 330<br /> <br /> CHAPTER7.ARRAYS 316 int[]primes={2,3,5,7,11,13,17,19}; youcansay,equivalently, int[]primes=newint[]{2,3,5,7,11,17,19}; Infact,ratherthanuseaspecialnotationthatworksonlyin thecontextofdeclarationstatements,Iprefertousethesecondform. Onenalnote:Forhistoricalreasons,anarraydeclaration suchas int[]list; canalsobewrittenas intlist[]; whichisasyntaxusedinthelanguagesCandC++.However,thi salternativesyntaxdoesnot reallymakemuchsenseinthecontextofJava,anditisprobab lybestavoided.Afterall,the intentistodeclareavariableofacertaintype,andthename ofthattypeis\ int[] ".Itmakes sensetofollowthe\ h type-name ih variable-name i ;"syntaxforsuchdeclarations. 7.2ProgrammingWithArraysA rraysarethemostbasic andthemostimportanttypeofdatastructure,andtech(online) niquesforprocessingarraysareamongthemostimportantpr ogrammingtechniquesyoucan learn.Twofundamentalarrayprocessingtechniques|searc hingandsorting|willbecovered in Section7.4 .Thissectionintroducessomeofthebasicideasofarraypro cessingingeneral. 7.2.1ArraysandforLoopsInmanycases,processinganarraymeansapplyingthesameop erationtoeachiteminthe array.Thisiscommonlydonewitha for loop.Aloopforprocessingalltheelementsofan array A hastheform: //doanynecessaryinitializationfor(inti=0;i<A.length;i++){ ...//processA[i] } Suppose,forexample,that A isanarrayoftype double[] .Supposethatthegoalistoadd upallthenumbersinthearray.Aninformalalgorithmfordoi ngthiswouldbe: Startwith0;AddA[0];(processthefirstiteminA)AddA[1];(processtheseconditeminA) ... AddA[A.length-1];(processthelastiteminA) Puttingtheobviousrepetitionintoaloopandgivinganamet othesum,thisbecomes: <br /> <br /> PAGE 331<br /> <br /> CHAPTER7.ARRAYS 317 doublesum;//ThesumofthenumbersinA.sum=0;//Startwith0.for(inti=0;i<A.length;i++) sum+=A[i];//addA[i]tothesum,for //i=0,1,...,A.length-1 Notethatthecontinuationcondition,\ i<A.length ",impliesthatthelastvalueof i that isactuallyprocessedis A.length-1 ,whichistheindexofthenaliteminthearray.It's importanttouse\ < "here,not\ <= ",since\ <= "wouldgiveanarrayindexoutofboundserror. Thereisnoelementatposition A.length in A Eventually,youshouldjustaboutbeabletowriteloopssimi lartothisoneinyoursleep. Iwillgiveafewmoresimpleexamples.Hereisaloopthatwill countthenumberofitemsin thearray A whicharelessthanzero: intcount;//Forcountingtheitems.count=0;//Startwith0itemscounted.for(inti=0;i<A.length;i++){ if(A[i]<0.0)//ifthisitemislessthanzero... count++;//...thencountit }//Atthispoint,thevalueofcountisthenumber//ofitemsthathavepassedthetestofbeing<0 Replacethetest\ A[i]<0.0 ",ifyouwanttocountthenumberofitemsinanarraythat satisfysomeotherproperty.Hereisavariationonthesamet heme.Supposeyouwanttocount thenumberoftimesthataniteminthearray A isequaltotheitemthatfollowsit.Theitem thatfollows A[i] inthearrayis A[i+1] ,sothetestinthiscaseis\ if(A[i]==A[i+1]) ". Butthereisacatch:Thistestcannotbeappliedwhen A[i] isthelastiteminthearray,since thenthereisnosuchitemas A[i+1] .Theresultoftryingtoapplythetestinthiscasewould bean ArrayIndexOutOfBoundsException .Thisjustmeansthatwehavetostoponeitemshort ofthenalitem: intcount=0;for(inti=0;i< A.length-1 ;i++){ if(A[i]==A[i+1]) count++; } Anothertypicalproblemistondthelargestnumberin A .Thestrategyistogothrough thearray,keepingtrackofthelargestnumberfoundsofar.W e'llstorethelargestnumber foundsofarinavariablecalled max .Aswelookthroughthearray,wheneverwendanumber largerthanthecurrentvalueof max ,wechangethevalueof max tothatlargervalue.Afterthe wholearrayhasbeenprocessed, max isthelargestiteminthearrayoverall.Theonlyquestion is,whatshouldtheoriginalvalueof max be?Onepossibilityistostartwith max equalto A[0] andthentolookthroughtherestofthearray,startingfrom A[1] ,forlargeritems: doublemax=A[0];for( inti=1 ;i<A.length;i++){ if(A[i]>max) max=A[i]; }//atthispoint,maxisthelargestiteminA <br /> <br /> PAGE 332<br /> <br /> CHAPTER7.ARRAYS 318 (Thereisonesubtleproblemhere.It'spossibleinJavafora narraytohavelengthzero.In thatcase, A[0] doesn'texist,andthereferenceto A[0] intherstlinegivesanarrayindexout ofboundserror.However,zero-lengtharraysarenormallys omethingthatyouwanttoavoid inrealproblems.Anyway,whatwoulditmeantoaskforthelar gestiteminanarraythat containsnoitemsatall?) Asanalexampleofbasicarrayoperations,considerthepro blemofcopyinganarray.To makeacopyofoursamplearray A ,itis not sucienttosay double[]B=A; sincethisdoesnotcreateanewarrayobject.Allitdoesisde clareanewarrayvariableand makeitrefertothesameobjecttowhich A refers.(Sothat,forexample,achangeto A[i] will automaticallychange B[i] aswell.)Tomakeanewarraythatisacopyof A ,itisnecessaryto makeanewarrayobjectandtocopyeachoftheindividualitem sfrom A intothenewarray: double[]B=newdouble[A.length];//Makeanewarrayobject //thesamesizeasA. for(inti=0;i<A.length;i++) B[i]=A[i];//CopyeachitemfromAtoB. Copyingvaluesfromonearraytoanotherissuchacommonoper ationthatJavahasa predenedsubroutinetodoit.Thesubroutine, System.arraycopy() ,isastaticmember subroutineinthestandard System class.Itsdeclarationhastheform publicstaticvoidarraycopy(ObjectsourceArray,intsour ceStartIndex, ObjectdestArray,intdestStartIndex,intcount) where sourceArray and destArray canbearrayswithanybasetype.Valuesarecopiedfrom sourceArray to destArray .The count tellshowmanyelementstocopy.Valuesaretakenfrom sourceArray startingatposition sourceStartIndex andarestoredin destArray startingat position destStartIndex .Forexample,tomakeacopyofthearray, A ,usingthissubroutine, youwouldsay: doubleB=newdouble[A.length];System.arraycopy(A,0,B,0,A.length); 7.2.2Arraysandfor-eachLoopsJava5.0introducedanewformofthe for loop,the\for-eachloop"thatwasintroducedin Subsection3.4.4 .Thefor-eachloopismeantspecicallyforprocessingallt hevaluesinadata structure.Whenusedtoprocessanarray,afor-eachloopcan beusedtoperformthesame operationoneachvaluethatisstoredinthearray.If anArray isanarrayoftype BaseType[] thenafor-eachloopfor anArray hastheform: for(BaseTypeitem:anArray){ ..//processtheitem. } Inthisloop, item istheloopcontrolvariable.Itisbeingdeclaredasavariab leoftype BaseType where BaseType isthebasetypeofthearray.(Inafor-eachloop,theloopcon trolvariable must bedeclaredintheloop.)Whenthisloopisexecuted,eachval uefromthearrayisassigned to item inturnandthebodyoftheloopisexecutedforeachvalue.Thu s,theaboveloopis exactlyequivalentto: <br /> <br /> PAGE 333<br /> <br /> CHAPTER7.ARRAYS 319 for(intindex=0;index<anArray.length;index++){ BaseTypeitem;item=anArray[index];//Getoneofthevaluesfromthearray ..//processtheitem. } Forexample,if A isanarrayoftype int[] ,thenwecouldprintallthevaluesfrom A with thefor-eachloop: for(intitem:A) System.out.println(item); andwecouldaddupallthepositiveintegersin A with: intsum=0;//Thiswillbethesumofallthepositivenumbersi nA for(intitem:A){ if(item>0) sum=sum+item; } Thefor-eachloopisnotalwaysappropriate.Forexample,th ereisnosimplewaytouseit toprocesstheitemsinjustapartofanarray.However,itdoe smakeitalittleeasiertoprocess allthevaluesinanarray,sinceiteliminatesanyneedtouse arrayindices. It'simportanttonotethatafor-eachloopprocessesthe values inthearray,notthe elements (whereanelementmeanstheactualmemorylocationthatispa rtofthearray).For example,considerthefollowingincorrectattempttollan arrayofintegerswith17's: int[]intList=newint[10];for(intitem:intList){ //INCORRECT!DOESNOTMODIFYTHEARRAY! item=17; } Theassignmentstatement item=17 assignsthevalue17totheloopcontrolvariable, item However,thishasnothingtodowiththearray.Whenthebodyo ftheloopisexecuted,the valuefromoneoftheelementsofthearrayiscopiedinto item .Thestatement item=17 replacesthatcopiedvaluebuthasnoeectonthearrayeleme ntfromwhichitwascopied;the valueinthearrayisnotchanged.7.2.3ArrayTypesinSubroutinesAnyarraytype,suchas double[] ,isafull-redgedJavatype,soitcanbeusedinalltheways thatanyotherJavatypecanbeused.Inparticular,itcanbeu sedasthetypeofaformal parameterinasubroutine.Itcanevenbethereturntypeofaf unction.Forexample,itmight beusefultohaveafunctionthatmakesacopyofanarrayof double : /** *Createanewarrayofdoublesthatisacopyofagivenarray.*@paramsourcethearraythatistobecopied;thevaluecanbe null *@returnacopyofsource;ifsourceisnull,thenthereturnv alueisalsonull */ publicstaticdouble[]copy(double[]source){ if(source==null) <br /> <br /> PAGE 334<br /> <br /> CHAPTER7.ARRAYS 320 returnnull; double[]cpy;//Acopyofthesourcearray.cpy=newdouble[source.length];System.arraycopy(source,0,cpy,0,source.length);returncpy; } The main() routineofaprogramhasaparameteroftype String[] .You'veseenthisused sinceallthewaybackin Section2.1 ,butIhaven'treallybeenabletoexplainituntilnow. Theparametertothe main() routineisanarrayof String s.Whenthesystemcallsthe main() routine,thestringsinthisarrayarethe command-linearguments fromthecommandthat wasusedtoruntheprogram.Whenusingacommand-lineinterf ace,theusertypesacommand totellthesystemtoexecuteaprogram.Theusercanincludee xtrainputinthiscommand, beyondthenameoftheprogram.Thisextrainputbecomesthec ommand-linearguments.For example,ifthenameoftheclassthatcontainsthe main() routineis myProg ,thentheuser cantype\ javamyProg "toexecutetheprogram.Inthiscase,therearenocommand-l ine arguments.Butiftheusertypesthecommand javamyProgonetwothree thenthecommand-lineargumentsarethestrings\one",\two ",and\three".Thesystemputs thesestringsintoanarrayof String sandpassesthatarrayasaparametertothe main() routine.Here,forexample,isashortprogramthatsimplypr intsoutanycommandline argumentsenteredbytheuser: publicclassCLDemo{ publicstaticvoidmain(String[]args){ System.out.println("Youentered"+args.length +"command-linearguments"); if(args.length>0){ System.out.println("Theywere:");for(inti=0;i<args.length;i++) System.out.println(""+args[i]); } }//endmain() }//endclassCLDemo Notethattheparameter, args ,isnever null when main() iscalledbythesystem,butitmight beanarrayoflengthzero. Inpractice,command-lineargumentsareoftenthenamesof lestobeprocessedbythe program.Iwillgivesomeexamplesofthisin Chapter11 ,whenIdiscussleprocessing. 7.2.4RandomAccessSofar,allmyexamplesofarrayprocessinghaveused sequentialaccess .Thatis,theelements ofthearraywereprocessedoneaftertheotherinthesequenc einwhichtheyoccurinthearray. Butoneofthebigadvantagesofarraysisthattheyallow randomaccess .Thatis,every elementofthearrayisequallyaccessibleatanygiventime. Asanexample,let'slookatawell-knownproblemcalledtheb irthdayproblem:Suppose thatthereare N peopleinaroom.What'sthechancethattherearetwopeoplei ntheroom whohavethesamebirthday?(Thatis,theywerebornonthesam edayinthesamemonth, butnotnecessarilyinthesameyear.)Mostpeopleseverelyu nderestimatetheprobability.We <br /> <br /> PAGE 335<br /> <br /> CHAPTER7.ARRAYS 321 willactuallylookatadierentversionofthequestion:Sup poseyouchoosepeopleatrandom andchecktheirbirthdays.Howmanypeoplewillyoucheckbef oreyoundonewhohasthe samebirthdayassomeoneyou'vealreadychecked?Ofcourse, theanswerinaparticularcase dependsonrandomfactors,butwecansimulatetheexperimen twithacomputerprogramand runtheprogramseveraltimestogetanideaofhowmanypeople needtobecheckedonaverage. Tosimulatetheexperiment,weneedtokeeptrackofeachbirt hdaythatwend.Thereare 365dierentpossiblebirthdays.(We'llignoreleapyears. )Foreachpossiblebirthday,weneed tokeeptrackofwhetherornotwehavealreadyfoundapersonw hohasthatbirthday.The answertothisquestionisabooleanvalue,trueorfalse.Toh oldthedataforall365possible birthdays,wecanuseanarrayof365booleanvalues: boolean[]used;used=newboolean[365]; Thedaysoftheyeararenumberedfrom0to364.Thevalueof used[i] istrueifsomeone hasbeenselectedwhosebirthdayisdaynumber i .Initially,allthevaluesinthearray, used arefalse.Whenweselectsomeonewhosebirthdayisdaynumbe r i ,werstcheckwhether used[i] istrue.Ifso,thenthisisthesecondpersonwiththatbirthd ay.Wearedone.If used[i] isfalse,weset used[i] tobetruetorecordthefactthatwe'veencounteredsomeone withthatbirthday,andwegoontothenextperson.Hereisasu broutinethatcarriesout thesimulatedexperiment(ofcourse,inthesubroutine,the rearenosimulatedpeople,only simulatedbirthdays): /** *Simulatechoosingpeopleatrandomandcheckingthedayoft heyearthey *werebornon.Ifthebirthdayisthesameasonethatwasseenp reviously, *stop,andoutputthenumberofpeoplewhowerechecked.*/ privatestaticvoidbirthdayProblem(){ boolean[]used;//Forrecordingthepossiblebirthdays //thathavebeenseensofar.Avalue//oftrueinused[i]meansthataperson//whosebirthdayisthei-thdayofthe//yearhasbeenfound. intcount;//Thenumberofpeoplewhohavebeenchecked.used=newboolean[365];//Initially,allentriesarefalse count=0;while(true){ //Selectabirthdayatrandom,from0to364.//Ifthebirthdayhasalreadybeenused,quit.//Otherwise,recordthebirthdayasused. intbirthday;//Theselectedbirthday.birthday=(int)(Math.random()*365);count++;if(used[birthday])//Thisdaywasfoundbefore;It'sadupl icate. break; used[birthday]=true; }System.out.println("Aduplicatebirthdaywasfoundafter <br /> <br /> PAGE 336<br /> <br /> CHAPTER7.ARRAYS 322 +count+"tries."); }//endbirthdayProblem() Thissubroutinemakesessentialuseofthefactthateveryel ementinanewlycreatedarrayof boolean issettobe false .Ifwewantedtoreusethesamearrayinasecondsimulation,w e wouldhavetoresetalltheelementsinittobe false witha for loop: for(inti=0;i<365;i++) used[i]=false; Theprogramthatusesthissubroutineis BirthdayProblemDemo.java .Anappletversionof theprogramcanbefoundintheonlineversionofthissection 7.2.5ArraysofObjectsOneoftheexamplesin Subsection6.4.2 wasanappletthatshowsmultiplecopiesofamessage inrandompositions,colors,andfonts.Whentheuserclicks ontheapplet,thepositions,colors, andfontsarechangedtonewrandomvalues.Likeseveralothe rexamplesfromthatchapter, theapplethadaraw:Itdidn'thaveanywayofstoringthedata thatwouldbenecessaryto redrawitself.Arraysprovideuswithonepossiblesolution tothisproblem.Wecanwriteanew versionoftheRandomStringsappletthatusesanarraytosto retheposition,font,andcolorof eachstring.Whenthecontentpaneoftheappletispainted,t hisinformationisusedtodraw thestrings,sotheappletwillpaintitselfcorrectlywhene verithastoberedrawn.Whenthe userclicksontheapplet,thearrayislledwithnewrandomv aluesandtheappletisrepainted usingthenewdata.So,theonlytimethatthepicturewillcha ngeisinresponsetoamouse click. Inthisapplet,thenumberofcopiesofthemessageisgivenby anamedconstant, MESSAGE COUNT .Onewaytostoretheposition,color,andfontof MESSAGE COUNT stringswould betousefourarrays: int[]x=newint[MESSAGE COUNT]; int[]y=newint[MESSAGE COUNT]; Color[]color=newColor[MESSAGE COUNT]; Font[]font=newFont[MESSAGE COUNT]; Thesearrayswouldbelledwithrandomvalues.Inthe paintComponent() method,the i -th copyofthestringwouldbedrawnatthepoint (x[i],y[i]) .Itscolorwouldbegivenby color[i] .Anditwouldbedrawninthefont font[i] .Thiswouldbeaccomplishedbythe paintComponent() method publicvoidpaintComponent(Graphicsg){ super.paintComponent();//(Fillwithbackgroundcolor.)for(inti=0;i<MESSAGE COUNT;i++){ g.setColor(color[i]);g.setFont(font[i]);g.drawString(message,x[i],y[i]); } } Thisapproachissaidtouse parallelarrays .Thedataforagivencopyofthemessageis spreadoutacrossseveralarrays.Ifyouthinkofthearraysa slaidoutinparallelcolumns| array x intherstcolumn,array y inthesecond,array color inthethird,andarray font inthefourth|thenthedataforthe i -thstringcanbefoundalongthethe i -throw.There <br /> <br /> PAGE 337<br /> <br /> CHAPTER7.ARRAYS 323 isnothingwrongwithusingparallelarraysinthissimpleex ample,butitdoesgoagainstthe object-orientedphilosophyofkeepingrelateddatainoneo bject.Ifwefollowthisrule,thenwe don'thaveto imagine therelationshipamongthedata,becauseallthedataforone copyof themessageisphysicallyinoneplace.So,whenIwrotetheap plet,Imadeasimpleclassto representallthedatathatisneededforonecopyofthemessa ge: /** *Anobjectofthistypeholdstheposition,color,andfont*ofonecopyofthestring.*/ privatestaticclassStringData{ intx,y;//Thecoordinatesoftheleftendofbaselineofstri ng. Colorcolor;//Thecolorinwhichthestringisdrawn.Fontfont;//Thefontthatisusedtodrawthestring. } (Thisclassisactuallydenedasastaticnestedclassinthe mainappletclass.)Tostorethedata formultiplecopiesofthemessage,Iuseanarrayoftype StringData[] .Thearrayisdeclared asaninstancevariable,withthename stringData : StringData[]stringData; Ofcourse,thevalueof stringData is null untilanactualarrayiscreatedandassignedtoit. Thisisdoneinthe init() methodoftheappletwiththestatement stringData=newStringData[MESSAGE COUNT]; Thebasetypeofthisarrayis StringData ,whichisaclass.Wesaythat stringData isan array ofobjects .Thismeansthattheelementsofthearrayarevariablesofty pe StringData .Like anyobjectvariable,eachelementofthearraycaneitherbe null orcanholdareferencetoan object.(Notethattheterm\arrayofobjects"isalittlemis leading,sincetheobjectsarenot inthearray;thearraycanonlycontainreferencestoobject s).Whenthe stringData arrayis rstcreated,thevalueofeachelementinthearrayis null ThedataneededbytheRandomStringsprogramwillbestoredi nobjectsoftype StringData butnosuchobjectsexistyet.Allwehavesofarisanarrayofv ariablesthatarecapableof referringtosuchobjects.Idecidedtocreatethe StringData objectsintheapplet's init method. (Itcouldbedoneinotherplaces|justsolongasweavoidtryi ngtouseanobjectthatdoesn't exist.Thisisimportant:Rememberthatanewlycreatedarra ywhosebasetypeisanobject typeisalwayslledwith null elements.Thereare no objectsinthearrayuntilyouputthem there.)Theobjectsarecreatedwiththe for loop for(inti=0;i<MESSAGE COUNT;i++) stringData[i]=newStringData(); FortheRandomStringsapplet,theideaistostoredataforth e i -thcopyofthe messageinthevariables stringData[i].x stringData[i].y stringData[i].color ,and stringData[i].font .Makesurethatyouunderstandthenotationhere: stringData[i] referstoanobject.Thatobjectcontainsinstancevariable s.Thenotation stringData[i].x tellsthecomputer:\Findyourwaytotheobjectthatisrefer redtoby stringData[i] .Then gototheinstancevariablenamed x inthatobject."Variablenamescangetevenmorecomplicatedthanthis,soitisimportanttolearnhowtoreadthe m.Usingthearray, stringData the paintComponent() methodfortheappletcouldbewritten <br /> <br /> PAGE 338<br /> <br /> CHAPTER7.ARRAYS 324 publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);//(Fillwithbackgroundcolor. ) for(inti=0;i<MESSAGE COUNT;i++){ g.setColor( stringData[i]. color); g.setFont( stringData[i]. font); g.drawString(message, stringData[i]. x, stringData[i]. y); } } However,sincethe for loopisprocessingeveryvalueinthearray,analternativew ouldbeto useafor-eachloop: publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);for(StringDatadata:stringData){ //Drawacopyofthemessageintheposition,color,//andfontstoredindata. g.setColor(data.color);g.setFont(data.font);g.drawString(message,data.x,data.y); } } Intheloop,theloopcontrolvariable, data ,holdsacopyofoneofthevaluesfromthearray. Thatvalueisareferencetoanobjectoftype StringData ,whichhasinstancevariablesnamed color font x ,and y .Onceagain,theuseofafor-eachloophaseliminatedthenee dtowork witharrayindices. Thereisstillthematterofllingthearray, data ,withrandomvalues.Ifyouareinterested, youcanlookatthesourcecodefortheapplet, RandomStringsWithArray.java TheRandomStringsappletusesoneotherarrayofobjects.Th efontforagivencopyof themessageischosenatrandomfromasetofvepossiblefont s.Intheoriginalversionofthe applet,therewerevevariablesoftype Font torepresentthefonts.Thevariableswerenamed font1 font2 font3 font4 ,and font5 .Toselectoneofthesefontsatrandom,a switch statementcouldbeused: FontrandomFont;//Oneofthe5fonts,chosenatrandom.intrand;//Arandomintegerintherange0to4.rand=(int)(Math.random()*5);switch(rand){ case0: randomFont=font1;break; case1: randomFont=font2;break; case2: randomFont=font3;break; case3: randomFont=font4;break; case4: <br /> <br /> PAGE 339<br /> <br /> CHAPTER7.ARRAYS 325 randomFont=font5;break; } Inthenewversionoftheapplet,thevefontsarestoredinan array,whichisnamed fonts Thisarrayisdeclaredasaninstancevariableoftype Font[] Font[]fonts; Thearrayiscreatedinthe init() methodoftheapplet,andeachelementofthearrayisset torefertoanew Font object: fonts=newFont[5];//Createthearraytoholdthefivefonts fonts[0]=newFont("Serif",Font.BOLD,14);fonts[1]=newFont("SansSerif",Font.BOLD+Font.ITALIC, 24); fonts[2]=newFont("Monospaced",Font.PLAIN,20);fonts[3]=newFont("Dialog",Font.PLAIN,30);fonts[4]=newFont("Serif",Font.ITALIC,36); Thismakesitmucheasiertoselectoneofthefontsatrandom. Itcanbedonewiththe statements FontrandomFont;//Oneofthe5fonts,chosenatrandom.intfontIndex;//Arandomnumberintherange0to4.fontIndex=(int)(Math.random()*5);randomFont=fonts[fontIndex]; The switch statementhasbeenreplacedbyasinglelineofcode.Infact, theprecedingfour linescouldbereplacedbythesingleline: FontrandomFont=fonts[(int)(Math.random()*5)]; Thisisaverytypicalapplicationofarrays.Notethatthise xampleusestherandomaccess propertyofarrays:Wecanpickanarrayindexatrandomandgo directlytothearrayelement atthatindex. Hereisanotherexampleofthesamesortofthing.Monthsareo ftenstoredasnumbers1,2, 3,...,12.Sometimes,however,thesenumbershavetobetran slatedintothenamesJanuary, February,...,December.Thetranslationcanbedonewithan array.Thearraycanbedeclared andinitializedas staticString[]monthName={"January","February","Marc h", "April","May","June","July","August","September","October","November","December"}; If mnth isavariablethatholdsoneoftheintegers1through12,then monthName[mnth-1] isthe nameofthecorrespondingmonth.Weneedthe\ -1 "becausemonthsarenumberedstarting from1,whilearrayelementsarenumberedstartingfrom0.Si mplearrayindexingdoesthe translationforus!7.2.6VariableArityMethodsArraysareusedintheimplementationofoneofthenewfeatur esinJava5.0.Beforeversion5.0, everymethodinJavahadaxedarity.(The arity ofasubroutineisdenedasthenumberof parametersinacalltothemethod.)Inaxedaritymethod,th enumberofparametersmust bethesameineverycalltothemethod.Java5.0introduced variablearitymethods .Ina <br /> <br /> PAGE 340<br /> <br /> CHAPTER7.ARRAYS 326 variablearitymethod,dierentcallstothemethodcanhave dierentnumbersofparameters. Forexample,theformattedoutputmethod System.out.printf ,whichwasintroducedin Subsection2.4.4 ,isavariablearitymethod.Therstparameterof System.out.printf mustbe a String ,butitcanhaveanynumberofadditionalparameters,ofanyt ypes. Callingavariablearitymethodisnodierentfromcallinga nyothersortofmethod,but writingonerequiressomenewsyntax.Asanexample,conside ramethodthatcancompute theaverageofanynumberofvaluesoftype double .Thedenitionofsuchamethodcould beginwith: publicstaticdoubleaverage(double...numbers){ Here,the ... afterthetypename, double ,indicatesthatanynumberofvaluesoftype double canbeprovidedwhenthesubroutineiscalled,sothatforexa mple average(1,2,3) average(3.14,2.17) average(0.375) ,andeven average() arealllegalcallstothismethod. Notethatactualparametersoftype int canbepassedto average .Theintegerswill,asusual, beautomaticallyconvertedtorealnumbers. Whenthemethodiscalled,thevaluesofalltheactualparame tersthatcorrespondtothe variablearityparameterareplacedintoanarray,anditist hisarraythatisactuallypassedto themethod.Thatis,inthebodyofamethod,avariablearityp arameteroftype T actually lookslikeanordinaryparameteroftype T[] .Thelengthofthearraytellsyouhowmany actualparameterswereprovidedinthemethodcall.Inthe average example,thebodyofthe methodwouldseeanarraynamed numbers oftype double[] .Thenumberofactualparameters inthemethodcallwouldbe numbers.length ,andthevaluesoftheactualparameterswould be numbers[0] numbers[1] ,andsoon.Acompletedenitionofthemethodwouldbe: publicstaticdoubleaverage(double...numbers){ doublesum;//Thesumofalltheactualparameters.doubleaverage;//Theaverageofalltheactualparameters.sum=0;for(inti=0;i<numbers.length;i++){ sum=sum+numbers[i];//Addoneoftheactualparameterstot hesum. }average=sum/numbers.length;returnaverage; } Notethatthe\ ... "canbeappliedonlytothe last formalparameterinamethoddenition. Notealsothatitispossibletopassanactualarraytothemet hod,insteadofalistofindividual values.Forexample,if salesData isavariableoftype double[] ,thenitwouldbelegaltocall average(salesData) ,andthiswouldcomputetheaverageofallthenumbersinthea rray. Asanotherexample,consideramethodthatcandrawapolygon throughanynumberof points.Thepointsaregivenasvaluesoftype Point ,whereanobjectoftype Point hastwo instancevariables, x and y ,oftype int .Inthiscase,themethodhasoneordinaryparameter| thegraphicscontextthatwillbeusedtodrawthepolygon|in additiontothevariablearity parameter: publicstaticvoiddrawPolygon(Graphicsg,Point...point s){ if(points.length>1){//(Needatleast2pointstodrawanyt hing.) for(inti=0;i<points.length-1;i++){ //Drawalinefromi-thpointto(i+1)-thpointg.drawline(points[i].x,points[i].y,points[i+1].x,po ints[i+1].y); } <br /> <br /> PAGE 341<br /> <br /> CHAPTER7.ARRAYS 327 //Now,drawalinebacktothestartingpoint.g.drawLine(points[points.length-1].x,points[points. length-1].y, points[0].x,points[0].y); } } Becauseofautomatictypeconversion,avariablearitypara meteroftype\ Object... "can takeactualparametersofanytypewhatsoever.Evenprimiti vetypevaluesareallowed,because ofautoboxing.(Aprimitivetypevaluebelongingtoatypesu chas int isconvertedtoanobject belongingtoa\wrapper"classsuchas Integer .See Subsection5.3.2 .)Forexample,themethod denitionfor System.out.printf couldbegin: publicvoidprintf(Stringformat,Object...values){ Thisallowsthe printf methodtooutputvaluesofanytype.Similarly,wecouldwrit eamethod thatstringstogetherthestringrepresentationsofallits parametersintoonelongstring: publicstaticStringconcat(Object...values){ Stringstr="";//Startwithanemptystring.for(Objectobj:values){//A"foreach"loopforprocessing thevalues. if(obj==null) str=str+"null";//Representnullvaluesby"null". else str=str+obj.toString(); } } 7.3DynamicArraysandArrayListsT hesizeofanarray isxedwhenitiscreated.Inmanycases,however,thenumber ofdata (online) itemsthatareactuallystoredinthearrayvarieswithtime. Considerthefollowingexamples: Anarraythatstoresthelinesoftextinaword-processingpr ogram.Anarraythatholdsthelist ofcomputersthatarecurrentlydownloadingapagefromaWeb site.Anarraythatcontains theshapesthathavebeenaddedtothescreenbytheuserofadr awingprogram.Clearly,we needsomewaytodealwithcaseswherethenumberofdataitems inanarrayisnotxed. 7.3.1PartiallyFullArraysConsideranapplicationwherethenumberofitemsthatwewan ttostoreinanarraychanges astheprogramruns.Sincethesizeofthearraycan'tactuall ybechanged,aseparatecounter variablemustbeusedtokeeptrackofhowmanyspacesinthear rayareinuse.(Ofcourse, everyspaceinthearrayhastocontainsomething;thequesti onis,howmanyspacescontain usefulorvaliditems?) Consider,forexample,aprogramthatreadspositiveintege rsenteredbytheuserandstores themforlaterprocessing.Theprogramstopsreadingwhenth euserinputsanumberthatis lessthanorequaltozero.Theinputnumberscanbekeptinana rray, numbers ,oftype int[] Let'ssaythatnomorethan100numberswillbeinput.Thenthe sizeofthearraycanbexed at100.Buttheprogrammustkeeptrackofhowmanynumbershav eactuallybeenreadand storedinthearray.Forthis,itcanuseanintegervariable, numCount .Eachtimeanumber isstoredinthearray, numCount mustbeincrementedbyone.Asarathersillyexample,let's writeaprogramthatwillreadthenumbersinputbytheuseran dthenprinttheminreverse <br /> <br /> PAGE 342<br /> <br /> CHAPTER7.ARRAYS 328 order.(Thisis,atleast,aprocessingtaskthatrequiresth atthenumbersbesavedinanarray. Rememberthatmanytypesofprocessing,suchasndingthesu moraverageormaximumof thenumbers,canbedonewithoutsavingtheindividualnumbe rs.) publicclassReverseInputNumbers{ publicstaticvoidmain(String[]args){ int[]numbers;//Anarrayforstoringtheinputvalues.intnumCount;//Thenumberofnumberssavedinthearray.intnum;//Oneofthenumbersinputbytheuser.numbers=newint[100];//Spacefor100ints.numCount=0;//Nonumbershavebeensavedyet.TextIO.putln("Enterupto100positiveintegers;enter0to end."); while(true){//Getthenumbersandputtheminthearray. TextIO.put("?");num=TextIO.getlnInt();if(num<=0) break; numbers[numCount]=num;numCount++; }TextIO.putln("\nYournumbersinreverseorderare:\n");for(inti=numCount-1;i>=0;i--){ TextIO.putln(numbers[i]); } }//endmain(); }//endclassReverseInputNumbers Itisespeciallyimportanttonotethatthevariable numCount playsadualrole.Itisthe numberofitemsthathavebeenenteredintothearray.Butiti salsotheindexofthenext availablespotinthearray.Forexample,if4numbershavebe enstoredinthearray,theyoccupy locationsnumber0,1,2,and3.Thenextavailablespotisloc ation4.Whenthetimecomesto printoutthenumbersinthearray,thelastoccupiedspotint hearrayislocation numCount1 ,sothe for loopprintsoutvaluesstartingfromlocation numCount-1 andgoingdownto0. Let'slookatanother,morerealisticexample.Supposethat youwriteagameprogram,and thatplayerscanjointhegameandleavethegameasitprogres ses.Asagoodobject-oriented programmer,youprobablyhaveaclassnamed Player torepresenttheindividualplayersin thegame.Alistofallplayerswhoarecurrentlyinthegameco uldbestoredinanarray, playerList ,oftype Player[] .Sincethenumberofplayerscanchange,youwillalsoneeda variable, playerCt ,torecordthenumberofplayerscurrentlyinthegame.Assum ingthatthere willneverbemorethan10playersinthegame,youcoulddecla rethevariablesas: Player[]playerList=newPlayer[10];//Upto10players.intplayerCt=0;//Atthestart,therearenoplayers. Aftersomeplayershavejoinedthegame, playerCt willbegreaterthan0,and theplayerobjectsrepresentingtheplayerswillbestoredi nthearrayelements playerList[0] playerList[1] ,..., playerList[playerCt-1] .Notethatthearrayelement <br /> <br /> PAGE 343<br /> <br /> CHAPTER7.ARRAYS 329 playerList[playerCt] is not inuse.Theprocedureforaddinganewplayer, newPlayer ,to thegameissimple: playerList[playerCt]=newPlayer;//Putnewplayerinnext //availablespot. playerCt++;//AndincrementplayerCttocountthenewplaye r. Deletingaplayerfromthegameisalittleharder,sinceyoud on'twanttoleavea\hole" inthearray.Supposeyouwanttodeletetheplayeratindex k in playerList .Ifyouarenot worriedaboutkeepingtheplayersinanyparticularorder,t henonewaytodothisistomove theplayerfromthelastoccupiedpositioninthearrayintop osition k andthentodecrement thevalueof playerCt : playerList[k]=playerList[playerCt-1];playerCt--; Theplayerpreviouslyinposition k isnolongerinthearray.Theplayerpreviouslyinposition playerCt-1 isnowinthearraytwice.Butit'sonlyintheoccupiedorvali dpartofthearray once,since playerCt hasdecreasedbyone.Rememberthateveryelementofthearra yhasto holdsomevalue,butonlythevaluesinpositions0through playerCt-1 willbelookedator processedinanyway.(Bytheway,youshouldthinkaboutwhat happensiftheplayerthat isbeingdeletedisinthelastpositioninthelist.Thecoded oesstillworkinthiscase.What exactlyhappens?) Supposethatwhendeletingtheplayerinposition k ,you'dliketokeeptheremainingplayers inthesameorder.(Maybebecausetheytaketurnsintheorder inwhichtheyarestoredinthe array.)Todothis,alltheplayersinpositions k+1 andabovemustmovedownonepositionin thearray.Player k+1 replacesplayer k ,whoisoutofthegame.Player k+2 llsthespotleft openwhenplayer k+1 ismoved.Andsoon.Thecodeforthisis for(inti=k+1;i<playerCt;i++){ playerList[i-1]=playerList[i]; }playerCt--; It'sworthemphasizingthatthe Player exampledealswithanarraywhosebasetypeisa class.Aniteminthearrayiseither null orisareferencetoanobjectbelongingtotheclass, Player .The Player objectsthemselvesarenotreallystoredinthearray,onlyr eferencesto them.NotethatbecauseoftherulesforassignmentinJava,t heobjectscanactuallybelongto subclassesof Player .Thustherecouldbedierentclassesofplayerssuchascomp uterplayers, regularhumanplayers,playerswhoarewizards,...,allrep resentedbydierentsubclassesof Player Asanotherexample,supposethataclass Shape representsthegeneralideaofashape drawnonascreen,andthatithassubclassestorepresentspe cictypesofshapessuchas lines,rectangles,roundedrectangles,ovals,lled-inov als,andsoforth.( Shape itselfwouldbe anabstractclass,asdiscussedin Subsection5.5.5 .)Thenanarrayoftype Shape[] canhold referencestoobjectsbelongingtothesubclassesof Shape .Forexample,thesituationcreated bythestatements Shape[]shapes=newShape[100];//Arraytoholdupto100sha pes. shapes[0]=newRect();//Putsomeobjectsinthearray.shapes[1]=newLine();shapes[2]=newFilledOval();intshapeCt=3;//Keeptrackofnumberofobjectsinarray. <br /> <br /> PAGE 344<br /> <br /> CHAPTER7.ARRAYS 330 couldbeillustratedas: Suchanarraywouldbeusefulinadrawingprogram.Thearrayc ouldbeusedtoholdalist ofshapestobedisplayed.Ifthe Shape classincludesamethod,\ voidredraw(Graphicsg) ", fordrawingtheshapeinagraphicscontext g ,thenalltheshapesinthearraycouldberedrawn withasimpleforloop: for(inti=0;i<shapeCt;i++) shapes[i].redraw(g); Thestatement\ shapes[i].redraw(g); "callsthe redraw() methodbelongingtotheparticularshapeatindex i inthearray.Eachobjectknowshowtoredrawitself,sothatr epeated executionsofthestatementcanproduceavarietyofdieren tshapesonthescreen.Thisisnice examplebothofpolymorphismandofarrayprocessing.7.3.2DynamicArraysIneachoftheaboveexamples,anarbitrarylimitwassetonth enumberofitems|100 ints ,10 Players ,100 Shapes .Sincethesizeofanarrayisxed,agivenarraycanonlyhold acertain maximumnumberofitems.Inmanycases,suchanarbitrarylim itisundesirable.Whyshould aprogramworkfor100datavalues,butnotfor101?Theobviou salternativeofmakingan arraythat'ssobigthatitwillworkinanypracticalcaseisn otusuallyagoodsolutiontothe problem.Itmeansthatinmostcases,alotofcomputermemory willbewastedonunusedspace inthearray.Thatmemorymightbebetterusedforsomethinge lse.Andwhatifsomeoneis usingacomputerthatcouldhandleasmanydatavaluesastheu seractuallywantstoprocess, butdoesn'thaveenoughmemorytoaccommodatealltheextras pacethatyou'veallocatedfor yourhugearray? Clearly,itwouldbeniceifwecouldincreasethesizeofanar rayatwill.Thisisnotpossible, butwhat is possibleisalmostasgood.Rememberthatanarrayvariabled oesnotactually holdanarray.Itjustholdsareferencetoanarrayobject.We can'tmakethearraybigger, butwecanmakeanew,biggerarrayobjectandchangethevalue ofthearrayvariablesothat itreferstothebiggerarray.Ofcourse,wealsohavetocopyt hecontentsoftheoldarrayinto thenewarray.Thearrayvariablethenreferstoanarrayobje ctthatcontainsallthedataof theoldarray,withroomforadditionaldata.Theoldarraywi llbegarbagecollected,sinceit isnolongerinuse. Let'slookbackatthegameexample,inwhich playerList isanarrayoftype Player[] and playerCt isthenumberofspacesthathavebeenusedinthearray.Suppo sethatwedon't wanttoputapre-setlimitonthenumberofplayers.Ifanewpl ayerjoinsthegameandthe <br /> <br /> PAGE 345<br /> <br /> CHAPTER7.ARRAYS 331 currentarrayisfull,wejustmakeanew,biggerone.Thesame variable, playerList ,willrefer tothenewarray.Notethatafterthisisdone, playerList[0] willrefertoadierentmemory location,butthevaluestoredin playerList[0] willstillbethesameasitwasbefore.Hereis somecodethatwilldothis: //Addanewplayer,evenifthecurrentarrayisfull.if(playerCt==playerList.length){ //Arrayisfull.Makeanew,biggerarray,//copythecontentsoftheoldarrayintoit,//andsetplayerListtorefertothenewarray. intnewSize=2*playerList.length;//Sizeofnewarray.Player[]temp=newPlayer[newSize];//Thenewarray.System.arraycopy(playerList,0,temp,0,playerList.len gth); playerList=temp;//SetplayerListtorefertonewarray. }//Atthispoint,weKNOWthereisroominthearray.playerList[playerCt]=newPlayer;//Addthenewplayer...playerCt++;//...andcountit. Ifwearegoingtobedoingthingslikethisregularly,itwoul dbenicetodeneareusable classtohandlethedetails.Anarray-likeobjectthatchang essizetoaccommodatetheamount ofdatathatitactuallycontainsiscalleda dynamicarray .Adynamicarraysupportsthe sameoperationsasanarray:puttingavalueatagivenpositi onandgettingthevaluethatis storedatagivenposition.Butthereisnoupperlimitonthep ositionsthatcanbeused(except thoseimposedbythesizeofthecomputer'smemory).Inadyna micarrayclass,the put and get operationsmustbeimplementedasinstancemethods.Here,f orexample,isaclassthat implementsadynamicarrayof ints : /** *AnobjectoftypeDynamicArrayOfIntactslikeanarrayofin t *ofunlimitedsize.ThenotationA.get(i)mustbeusedinste ad *ofA[i],andA.set(i,v)mustbeusedinsteadofA[i]=v.*/ publicclassDynamicArrayOfInt{ privateint[]data;//Anarraytoholdthedata./** *Constructorcreatesanarraywithaninitialsizeof1,*butthearraysizewillbeincreasedwheneverareference*ismadetoanarraypositionthatdoesnotyetexist.*/ publicDynamicArrayOfInt(){ data=newint[1]; }/** *Getthevaluefromthespecifiedpositioninthearray.*Sinceallarrayelementsareinitializedtozero,whenthe*specifiedpositionliesoutsidetheactualphysicalsize*ofthedataarray,avalueof0isreturned.Notethat*anegativevalueofpositionwillstillproducean*ArrayIndexOutOfBoundsException. <br /> <br /> PAGE 346<br /> <br /> CHAPTER7.ARRAYS 332 */ publicintget(intposition){ if(position>=data.length) return0; else returndata[position]; }/** *Storethevalueinthespecifiedpositioninthearray.*Thedataarraywillincreaseinsizetoincludethis*position,ifnecessary.*/ publicvoidput(intposition,intvalue){ if(position>=data.length){ //Thespecifiedpositionisoutsidetheactualsizeof//thedataarray.Doublethesize,orifthatstilldoes//notincludethespecifiedposition,setthenewsize//to2*position. intnewSize=2*data.length;if(position>=newSize) newSize=2*position; int[]newData=newint[newSize];System.arraycopy(data,0,newData,0,data.length);data=newData; //Thefollowinglineisfordemonstrationpurposesonly!! System.out.println("Sizeofdynamicarrayincreasedto"+ newSize); }data[position]=value; } }//endclassDynamicArrayOfInt Thedataina DynamicArrayOfInt objectisactuallystoredinaregulararray,butthatarray isdiscardedandreplacedbyabiggerarraywhenevernecessa ry.If numbers isavariableof type DynamicArrayOfInt ,thenthecommand numbers.put(pos,val) storesthevalue val at positionnumber pos inthedynamicarray.Thefunction numbers.get(pos) returnsthevalue storedatpositionnumber pos Therstexampleinthissectionusedanarraytostorepositi veintegersinputbythe user.Wecanrewritethatexampletousea DynamicArrayOfInt .Areferenceto numbers[i] isreplacedby numbers.get(i) .Thestatement\ numbers[numCount]=num ;"isreplacedby \ numbers.put(numCount,num); ".Here'stheprogram: publicclassReverseWithDynamicArray{ publicstaticvoidmain(String[]args){ DynamicArrayOfInt numbers;//Toholdtheinputnumbers. intnumCount;//Thenumberofnumbersstoredinthearray.intnum;//Oneofthenumbersinputbytheuser.numbers=newDynamicArrayOfInt();numCount=0;TextIO.putln("Entersomepositiveintegers;Enter0toend "); while(true){//Getnumbersandputtheminthedynamicarray <br /> <br /> PAGE 347<br /> <br /> CHAPTER7.ARRAYS 333 TextIO.put("?");num=TextIO.getlnInt();if(num<=0) break; numbers.put(numCount,num); //Storenuminthedynamicarray. numCount++; }TextIO.putln("\nYournumbersinreverseorderare:\n");for(inti=numCount-1;i>=0;i--){ TextIO.putln( numbers.get(i) );//Printthei-thnumber. } }//endmain(); }//endclassReverseWithDynamicArray 7.3.3ArrrayListsThe DynamicArrayOfInt classcouldbeusedinanysituationwhereanarrayof int withnopreset limitonthesizeisneeded.However,ifwewanttostore Shapes insteadof ints ,wewouldhave todeneanewclasstodoit.Thatclass,probablynamed\ DynamicArrayOfShape ",wouldlook exactlythesameasthe DynamicArrayOfInt classexceptthateverywherethetype\ int "appears, itwouldbereplacedbythetype\ Shape ".Similarly,wecoulddenea DynamicArrayOfDouble class,a DynamicArrayOfPlayer class,andsoon.Butthereissomethingalittlesillyaboutt his, sincealltheseclassesareclosetobeingidentical.Itwoul dbenicetobeabletowritesome kindofsourcecode,onceandforall,thatcouldbeusedtogen erateanyoftheseclasseson demand,giventhetypeofvaluethatwewanttostore.Thiswou ldbeanexampleof generic programming .Someprogramminglanguages,includingC++,havehadsuppo rtforgeneric programmingforsometime.Withversion5.0,Javaintroduce dtruegenericprogramming, butevenbeforethatithadsomethingthatwasverysimilar:O necancomeclosetogeneric programminginJavabyworkingwithdatastructuresthatcon tainelementsoftype Object Wewillrstconsiderthealmost-genericprogrammingthath asbeenavailableinJavafrom thebeginning,andthenwewilllookatthechangethatwasint roducedinJava5.0.Afull discussionofgenericprogrammingwillbegivenin Chapter10 InJava,everyclassisasubclassoftheclassnamed Object .Thismeansthateveryobjectcan beassignedtoavariableoftype Object .Anyobjectcanbeputintoanarrayoftype Object[] Ifwedeneda DynamicArrayOfObject class,thenwecouldstoreobjectsofanytype.Thisisnot truegenericprogramming,anditdoesn'tapplytotheprimit ivetypessuchas int and double Butitdoescomeclose.Infact,thereisnoneedforustodene a DynamicArrayOfObject class. Javaalreadyhasastandardclassnamed ArrayList thatservesmuchthesamepurpose.The ArrayList classisinthepackage java.util ,soifyouwanttouseitinaprogram,youshould putthedirective\ importjava.util.ArrayList; "atthebeginningofyoursourcecodele. The ArrayList classdiersfrommy DynamicArrayOfInt classinthatan ArrayList object alwayshasadenitesize,anditisillegaltorefertoaposit ioninthe ArrayList thatliesoutside itssize.Inthis,an ArrayList ismorelikearegulararray.However,thesizeofan ArrayList can beincreasedatwill.The ArrayList classdenesmanyinstancemethods.I'lldescribesomeof themostuseful.Supposethat list isavariableoftype ArrayList .Thenwehave: <br /> <br /> PAGE 348<br /> <br /> CHAPTER7.ARRAYS 334 list.size() |Thisfunctionreturnsthecurrentsizeofthe ArrayList .Theonlyvalid positionsinthelistarenumbersintherange 0 to list.size()-1 .Notethatthesizecan bezero.Acalltothedefaultconstructor newArrayList() createsan ArrayList ofsize zero. list.add(obj) |Addsanobjectontotheendofthelist,increasingthesizeb y1.The parameter, obj ,canrefertoanobjectofanytype,oritcanbe null list.get(N) |Thisfunctionreturnsthevaluestoredatposition N inthe ArrayList N mustbeanintegerintherange 0 to list.size()-1 .If N isoutsidethisrange,anerror oftype IndexOutOfBoundsException occurs.Callingthisfunctionissimilartoreferring to A[N] foranarray, A ,exceptthatyoucan'tuse list.get(N) ontheleftsideofan assignmentstatement. list.set(N,obj) |Assignstheobject, obj ,toposition N inthe ArrayList ,replacing theitempreviouslystoredatposition N .Theinteger N mustbeintherangefrom 0 to list.size()-1 .Acalltothisfunctionisequivalenttothecommand A[N]=obj foran array A list.remove(obj) |Ifthespeciedobjectoccurssomewhereinthe ArrayList ,itis removedfromthelist.Anyitemsinthelistthatcomeafterth eremoveditemaremoved downoneposition.Thesizeofthe ArrayList decreasesby1.If obj occursmorethanonce inthelist,onlytherstcopyisremoved. list.remove(N) |Foraninteger, N ,thisremovesthe N-th iteminthe ArrayList N must beintherange 0 to list.size()-1 .Anyitemsinthelistthatcomeaftertheremoved itemaremoveddownoneposition.Thesizeofthe ArrayList decreasesby1. list.indexOf(obj) |Afunctionthatsearchesfortheobject, obj ,inthe ArrayList .If theobjectisfoundinthelist,thenthepositionnumberwher eitisfoundisreturned.If theobjectisnotfound,then -1 isreturned. Forexample,supposeagainthatplayersinagamearereprese ntedbyobjectsoftype Player Theplayerscurrentlyinthegamecouldbestoredinan ArrayList named players .Thisvariable wouldbedeclaredas ArrayListplayers; andinitializedtorefertoanew,empty ArrayList objectwith players=newArrayList(); If newPlayer isavariablethatreferstoa Player object,thenewplayerwouldbeaddedtothe ArrayList andtothegamebysaying players.add(newPlayer); andifplayernumber i leavesthegame,itisonlynecessarytosay players.remove(i); Or,if player isavariablethatreferstothe Player thatistoberemoved,youcouldsay players.remove(player); Allthisworksverynicely.Theonlyslightdicultyarisesw henyouusethefunction players.get(i) togetthevaluestoredatposition i inthe ArrayList .Thereturntypeof thisfunctionis Object .Inthiscasetheobjectthatisreturnedbythefunctionisac tuallyof type Player .Inordertodoanythingusefulwiththereturnedvalue,it's usuallynecessaryto type-castittotype Player : <br /> <br /> PAGE 349<br /> <br /> CHAPTER7.ARRAYS 335 Playerplr=(Player)players.get(i); Forexample,ifthe Player classincludesaninstancemethod makeMove() thatiscalledtoallow aplayertomakeamoveinthegame,thenthecodeforlettingev eryplayermakeamoveis for(inti=0;i<players.size();i++){ Playerplr=(Player)players.get(i);plr.makeMove(); } Thetwolinesinsidethe for loopcanbecombinedtoasingleline: ((Player)players.get(i)).makeMove(); Thisgetsanitemfromthelist,type-castsit,andthencalls the makeMove() methodonthe resulting Player .Theparenthesesaround\ (Player)players.get(i) "arerequiredbecause ofJava'sprecedencerules.Theparenthesesforcethetypecasttobeperformedbeforethe makeMove() methodiscalled. For-eachloopsworkfor ArrayLists justastheydoforarrays.Butnotethatsincetheitems inan ArrayList areonlyknowntobe Objects ,thetypeoftheloopcontrolvariablemustbe Object .Forexample,the for loopusedabovetoleteach Player makeamovecouldbewritten asthefor-eachloop for(ObjectplrObj:players){ Playerplr=(Player)plrObj;plr.makeMove(); } Inthebodyoftheloop,thevalueoftheloopcontrolvariable plrObj ,isoneoftheobjects fromthelist, players .Thisobjectmustbetype-casttotype Player beforeitcanbeused. In Subsection5.5.5 ,Idiscussedaprogram, ShapeDraw ,thatuses ArrayLists .Hereisanother versionofthesameidea,simpliedtomakeiteasiertoseeho w ArrayList isbeingused.The programsupportsthefollowingoperations:Clickthelarge whitedrawingareatoaddacolored rectangle.(Thecoloroftherectangleisgivenbya\rainbow palette"alongthebottomofthe applet;clickthepalettetoselectanewcolor.)Dragrectan glesusingtherightmousebutton. HolddowntheAltkeyandclickonarectangletodeleteit.Shi ft-clickarectangletomoveit outinfrontofalltheotherrectangles.Youcantryanapplet versionoftheprograminthe on-lineversionofthissection. Sourcecodeforthemainpanelforthisprogramcanbefoundin SimpleDrawRects.java Youshouldbeabletofollowthesourcecodeinitsentirety.( Youcanalsotakealookatthe le RainbowPalette.java ,whichdenesthecolorpaletteshownatthebottomoftheapp let,if youlike.)Here,Ijustwanttolookatthepartsoftheprogram thatusean ArrayList Theappletusesavariablenamed rects ,oftype ArrayList ,toholdinformationaboutthe rectanglesthathavebeenaddedtothedrawingarea.Theobje ctsthatarestoredinthelist belongtoastaticnestedclass, ColoredRect ,thatisdenedas /** *AnobjectoftypeColoredRectholdsthedataforonecolored rectangle. */ privatestaticclassColoredRect{ intx,y;//Upperleftcorneroftherectangle.intwidth,height;//Sizeoftherectangle.Colorcolor;//Coloroftherectangle. } <br /> <br /> PAGE 350<br /> <br /> CHAPTER7.ARRAYS 336 If g isavariableoftype Graphics ,thenthefollowingcodedrawsalltherectanglesthat arestoredinthelist rects (withablackoutlinearoundeachrectangle): for(inti=0;i<rects.size();i++){ ColoredRectrect=(ColoredRect)rects.get(i);g.setColor(rect.color);g.fillRect(rect.x,rect.y,rect.width,rect.height);g.setColor(Color.BLACK);g.drawRect(rect.x,rect.y,rect.width-1,rect.height-1 ); } The i -threctangleinthelistisobtainedbycalling rects.get(i) .Sincethismethodreturns avalueoftype Object ,thereturnvaluemustbetypecasttoitsactualtype, ColoredRect ,toget accesstothedatathatitcontains. Toimplementthemouseoperations,itmustbepossibletond therectangle,ifany,that containsthepointwheretheuserclickedthemouse.Todothi s,Iwrotethefunction /** *Findthetopmostrectthatcontainsthepoint(x,y).Return null *ifnorectcontainsthatpoint.TherectsintheArrayListar e *consideredinreverseordersothatifoneliesontopofanot her, *theoneontopisseenfirstandisreturned.*/ ColoredRectfindRect(intx,inty){ for(inti=rects.size()-1;i>=0;i--){ ColoredRectrect=(ColoredRect)rects.get(i);if(x>=rect.x&&x<rect.x+rect.width &&y>=rect.y&&y<rect.y+rect.height) returnrect;//(x,y)isinsidethisrect. }returnnull;//Norectcontaining(x,y)wasfound. } Thecodeforremovinga ColoredRect rect ,fromthedrawingareaissimply rects.remove(rect) (followedbya repaint() ).Bringingagivenrectangleoutinfrontof alltheotherrectanglesisjustalittleharder.Sincethere ctanglesaredrawnintheorderin whichtheyoccurinthe ArrayList ,therectanglethatisinthelastpositioninthelistisinfr ont ofalltheotherrectanglesonthescreen.Soweneedtomoveth eselectedrectangletothe lastpositioninthelist.Thiscanmosteasilybedoneinasli ghtlytrickywayusingbuilt-in ArrayList operations:Therectangleissimplyremovedfromitscurren tpositioninthelistand thenaddingbackattheendofthelist: voidbringToFront(ColoredRectrect){ if(rect!=null){ rects.remove(rect);//Removerectfromthelist.rects.add(rect);//Additback;itwillbeplacedinthelast position. repaint(); } } Thisshouldbeenoughtogiveyouthebasicidea.Youcanlooki nthesourcecodeformore details. <br /> <br /> PAGE 351<br /> <br /> CHAPTER7.ARRAYS 337 7.3.4ParameterizedTypesThemaindierencebetweentruegenericprogrammingandthe ArrayList examplesinthe previoussubsectionistheuseofthetype Object asthebasictypeforobjectsthatarestored inalist.Thishasatleasttwounfortunateconsequences:Fi rst,itmakesitnecessarytouse type-castinginalmosteverycasewhenanelementisretriev edfromthatlist.Second,since anytypeofobjectcanlegallybeaddedtothelist,thereisno wayforthecompilertodetect anattempttoaddthewrongtypeofobjecttothelist;theerro rwillbedetectedonlyatrun timewhentheobjectisretrievedfromthelistandtheattemp ttotype-casttheobjectfails. Comparethistoarrays.Anarrayoftype BaseType[] can only holdobjectsoftype BaseType Anattempttostoreanobjectofthewrongtypeinthearraywil lbedetectedbythecompiler, andthereisnoneedtotype-castitemsthatareretrievedfro mthearraybacktotype BaseType Toaddressthisproblem,Java5.0introduced parameterizedtypes ArrayList isanexample:Insteadofusingtheplain\ArrayList"type,itispos sibletouse ArrayList < BaseType > where BaseType isanyobjecttype,thatis,thenameofaclassorofaninterfa ce.( BaseType cannot beoneoftheprimitivetypes.) ArrayList < BaseType > canbeusedtocreateliststhat canholdonlyobjectsoftype BaseType .Forexample, ArrayList<ColoredRect>rects; declaresavariablenamed rects oftype ArrayList < ColoredRect > ,and rects=newArrayList<ColoredRect>(); sets rects torefertoanewlycreatedlistthatcanonlyholdobjectsbel ongingtotheclass ColoredRect (ortoasubclass).Thefunny-lookingname\ArrayList < ColoredRect > "isbeing usedhereinexactlythesamewayasanordinaryclassname|do n'tletthe\ < ColoredRect > confuseyou;it'sjustpartofthenameofthetype.Whenastat ementsuchas rects.add(x); occursintheprogram,thecompilercancheckwhether x isinfactoftype ColoredRect .Ifnot, thecompilerwillreportasyntaxerror.Whenanobjectisret rievefromthelist,thecompiler knowsthattheobjectmustbeoftype ColoredRect ,sonotype-castisnecessary.Youcansay simply: ColoredRectrect=rects.get(i) Youcanevenreferdirectlytoaninstancevariableintheobj ect,suchas rects.get(i).color Thismakesusing ArrayList < ColoredRect > verysimilartousing ColoredRect[] withtheadded advantagethatthelistcangrowtoanysize.Notethatifafor -eachloopisusedtoprocessthe itemsin rects ,thetypeoftheloopcontrolvariablecanbe ColoredRect ,andnotype-castis necessary.Forexample,whenusing ArrayList < ColoredRect > asthetypeforthelist rects ,the codefordrawingalltherectanglesinthelistcouldberewri ttenas: for(ColoredRectrect:rects){ g.setColor(rect.color);g.fillRect(rect.x,rect.y,rect.width,rect.height);g.setColor(Color.BLACK);g.drawRect(rect.x,rect.y,rect.width-1,rect.height-1 ); } Youcanuse ArrayList < ColoredRect > anyplacewhereyoucoulduseanormaltype:todeclare variables,asthetypeofaformalparameterinasubroutine, orasthereturntypeofasubroutine. Youcanevencreateasubclassof ArrayList < ColoredRect > !(Nevertheless,technicallyspeaking, ArrayList < ColoredRect > isnotconsideredtobeaseparateclassfrom ArrayList .Anobjectof <br /> <br /> PAGE 352<br /> <br /> CHAPTER7.ARRAYS 338 type ArrayList < ColoredRect > actuallybelongstotheclass ArrayList ,butthecompilerrestricts thetypeofobjectsthatcanbeaddedtothelist.) Theonlydrawbacktousingparameterizedtypesisthattheba setypecannotbeaprimitive type.Forexample,thereisnosuchthingas\ ArrayList<int> ".However,thisisnotsucha bigdrawbackasitmightseematrst,becauseofthe\wrapper types"and\autoboxing"that wereintroducedin Subsection5.3.2 .Awrappertypesuchas Double or Integer canbeusedas abasetypeforaparameterizedtype.Anobjectoftype ArrayList < Double > canholdobjectsof type Double .Sinceeachobjectoftype Double holdsavalueoftype double ,it'salmostlike havingalistof doubles .If numlist isdeclaredtobeoftype ArrayList < Double > andif x isof type double ,thenthevalueof x canbeaddedtothelistbysaying: numlist.add(newDouble(x)); Furthermore,becauseofautoboxing,thecompilerwillauto maticallydo double -toDouble and Double -todouble typeconversionswhennecessary.Thismeansthatthecompil erwilltreat \ numlist.add(x) "asbeginequivalentto\ numlist.add(newDouble(x)) ".So,behindthe scenes,\ numlist.add(x) "isactuallyaddinganobjecttothelist,butitlooksalotas ifyou areworkingwithalistof doubles Thesampleprogram SimplePaint2.java demonstratestheuseofparameterizedtypes.In thisprogram,theusercansketchcurvesinadrawingareabyc lickinganddraggingwiththe mouse.Thecurvescanbeofanycolor,andtheusercanselectt hedrawingcolorusingamenu. Thebackgroundcolorofthedrawingareacanalsobeselected usingamenu.Andthereisa \Control"menuthatcontainsseveralcommands:An\Undo"co mmand,whichremovesthe mostrecentlydrawncurvefromthescreen,a\Clear"command thatremovesallthecurves, anda\UseSymmetry"commandthatturnsasymmetryfeatureon ando.Curvesthatare drawnbytheuserwhenthesymmetryoptionisonarererectedh orizontallyandvertically toproduceasymmetricpattern.Youcantryanappletversion oftheprogramintheon-line versionofthissection. UnliketheoriginalSimplePaintprogramin Subsection6.4.4 ,thisnewversionusesadata structuretostoreinformationaboutthepicturethathasbe endrawnbytheuser.Thisdata isusedinthe paintComponent() methodtoredrawthepicturewhenevernecessary.Thus,the picturedoesn'tdisappearwhen,forexample,thepictureis coveredandthenuncovered.The datastructureisimplementedusing ArrayLists Themaindataforacurveconsistsofalistofthepointsonthe curve.Thisdatacanbestored inanobjectoftype ArrayList < Point > ,where java.awt.Point isoneofJava'sstandardclasses. (A Point objectcontainstwopublicintegervariables x and y thatrepresentthecoordinatesof apoint.)However,toredrawthecurve,wealsoneedtoknowit scolor,andweneedtoknow whetherthesymmetryoptionshouldbeappliedtothecurve.A llthedatathatisneededto redrawthecurvecanbegroupedintoanobjectoftype CurveData thatisdenedas privatestaticclassCurveData{ Colorcolor;//Thecolorofthecurve.booleansymmetric;//Arehorizontalandverticalreflecti onsalsodrawn? ArrayList<Point>points;//Thepointsonthecurve. } However,apicturecancontainmanycurves,notjustone,sot ostoreallthedatanecessaryto redrawtheentirepicture,weneeda list ofobjectsoftype CurveData .Forthislist,wecanuse avariable curves declaredas <br /> <br /> PAGE 353<br /> <br /> CHAPTER7.ARRAYS 339 ArrayList<CurveData>curves=newArrayList<CurveData>( ); Herewehavealistofobjects,whereeachobjectcontainsali stofpointsaspartofitsdata! Let'slookatafewexamplesofprocessingthisdatastructur e.Whentheuserclicksthemouse onthedrawingsurface,it'sthestartofanewcurve,andanew CurveData objectmustbe createdandaddedtothelistofcurves.Theinstancevariabl esinthenew CurveData object mustalsobeinitialized.Hereisthecodefromthe mousePressed() routinethatdoesthis: currentCurve=newCurveData();//CreateanewCurveDataob ject. currentCurve.color=currentColor;//Thecolorofthecurv eistakenfroman //instancevariablethatrepresentsthe//currentlyselecteddrawingcolor. currentCurve.symmetric=useSymmetry;//The"symmetric" propertyofthecurve //isalsocopiedfromthecurrentvalue//ofaninstancevariable,useSymmetry. currentCurve.points=newArrayList<Point>();//Createa newpointlistobject. currentCurve.points.add(newPoint(evt.getX(),evt.get Y())); //Thepointwheretheuserpressedthemouseisthefirstpoin ton //thecurve.AnewPointobjectiscreatedtoholdthecoordin ates //ofthatpointandisaddedtothelistofpointsforthecurve curves.add(currentCurve);//AddtheCurveDataobjecttot helistofcurves. Astheuserdragsthemouse,newpointsareaddedto currentCurve ,and repaint() iscalled. Whenthepictureisredrawn,thenewpointwillbepartofthep icture. The paintComponent() methodhastousethedatain curves todrawallthecurves.The basicstructureisafor-eachloopthatprocessesthedatafo reachindividualcurveinturn.This hastheform: for(CurveDatacurve:curves){ ..//Drawthecurverepresentedbytheobject,curve,oftypeC urveData. } Inthebodyofthisloop, curve.points isavariableoftype ArrayList < Point > thatholdsthe listofpointsonthecurve.The i-th pointonthecurvecanbeobtainedbycallingthe get() methodofthislist: curve.points.get(i) .Thisreturnsavalueoftype Point whichcontains instancevariablesnamed x and y .Wecanreferdirectlytothex-coordinateofthe i-th point as: curve.points.get(i).x Thismightseemrathercomplicated,butit'saniceexampleo facomplexnamethatspecies apathtoadesiredpieceofdata:Gototheobject, curve .Inside curve ,goto points .Inside points ,getthe i-th item.Andfromthatitem,gettheinstancevariablenamed x .Hereisthe completedenitionofthe paintCompontent() method: publicvoidpaintComponent(Graphicsg){ super.paintComponent(g);for(CurveDatacurve:curves){ g.setColor(curve.color);for(inti=1;i<curve.points.size();i++){ <br /> <br /> PAGE 354<br /> <br /> CHAPTER7.ARRAYS 340 //Drawalinesegmentfrompointnumberi-1topointnumberi. intx1=curve.points.get(i-1).x;inty1=curve.points.get(i-1).y;intx2=curve.points.get(i).x;inty2=curve.points.get(i).y;g.drawLine(x1,y1,x2,y2);if(curve.symmetric){ //Alsodrawthehorizontalandverticalreflections//ofthelinesegment. intw=getWidth();inth=getHeight();g.drawLine(w-x1,y1,w-x2,y2);g.drawLine(x1,h-y1,x2,h-y2);g.drawLine(w-x1,h-y1,w-x2,h-y2); } } } }//endpaintComponent() Iencourageyoutoreadthefullsourcecode, SimplePaint2.java .Inadditiontoservingasan exampleofusingparameterizedtypes,italsoservesananot herexampleofcreatingandusing menus.7.3.5VectorsThe ArrayList classwasintroducedinJavaversion1.2,asoneofagroupofc lassesdesigned forworkingwithcollectionsofobjects.We'lllookatthese \collectionclasses"in Chapter10 EarlyversionsofJavadidnotinclude ArrayList ,buttheydidhaveaverysimilarclassnamed java.util.Vector .Youcanstillsee Vectors usedinoldercodeandinmanyofJava'sstandard classes,soit'sworthknowingaboutthem.Usinga Vector issimilartousingan ArrayList ,except thatdierentnamesareusedforsomecommonlyusedinstance methods,andsomeinstance methodsinoneclassdon'tcorrespondtoanyinstancemethod intheotherclass. Likean ArrayList ,a Vector issimilartoanarrayof Objects thatcangrowtobeaslargeas necessary.Thedefaultconstructor, newVector() ,createsavectorwithnoelements.Suppose that vec isa Vector .Thenwehave: vec.size() |afunctionthatreturnsthenumberofelementscurrentlyin thevector. vec.elementAt(N) |returnsthe N-th elementofthevector,foraninteger N N mustbe intherange0to vec.size()-1 .Thisisthesameas get(N) foran ArrayList vec.setElementAt(obj,N) |setsthe N-th elementinthevectortobe obj N mustbe intherange0to vec.size()-1 .Thisisthesameas set(N,obj) foran ArrayList vec.addElement(obj) |addsthe Object obj ,totheendofthevector.Thisisthesame asthe add() methodofan ArrayList vec.removeElement(obj) |removes obj fromthevector,ifitoccurs.Onlytherst occurrenceisremoved.Thisisthesameas remove(obj) foran ArrayList vec.removeElementAt(N) |removesthe N-th element,foraninteger N N mustbein therange0to vec.size()-1 .Thisisthesameas remove(N) foran ArrayList vec.setSize(N) |setsthesizeofthevectorto N .Ifthereweremorethan N elementsin vec ,theextraelementsareremoved.Iftherewerefewerthan N elements,extraspacesare lledwith null .The ArrayList class,unfortunately,doesnothavea setSize() method. <br /> <br /> PAGE 355<br /> <br /> CHAPTER7.ARRAYS 341 The Vector classincludesmanymoremethods,buttheseareprobablythe mostcommonly used.NotethatinJava5.0, Vector canbeusedasaparamaterizedtypeinexactlythesame wayas ArrayList .Thatis,if BaseType isanyclassorinterfacename,then Vector < BaseType > representsvectorsthatcanholdonlyobjectsoftype BaseType 7.4SearchingandSortingT woarrayprocessingtechniques thatareparticularlycommonare searching and sort(online) ing .Searchingherereferstondinganiteminthearraythatmee tssomespeciedcriterion. Sortingreferstorearrangingalltheitemsinthearrayinto increasingordecreasingorder(where themeaningofincreasinganddecreasingcandependontheco ntext). Sortingandsearchingareoftendiscussed,inatheoretical sortofway,usinganarrayof numbersasanexample.Inpracticalsituations,though,mor einterestingtypesofdataare usuallyinvolved.Forexample,thearraymightbeamailingl ist,andeachelementofthearray mightbeanobjectcontaininganameandaddress.Giventhena meofaperson,youmight wanttolookupthatperson'saddress.Thisisanexampleofse arching,sinceyouwanttond theobjectinthearraythatcontainsthegivenname.Itwould alsobeusefultobeabletosort thearrayaccordingtovariouscriteria.Oneexampleofsort ingwouldbeorderingtheelements ofthearraysothatthenamesareinalphabeticalorder.Anot herexamplewouldbetoorder theelementsofthearrayaccordingtozipcodebeforeprinti ngasetofmailinglabels.(This kindofsortingcangetyouacheaperpostagerateonalargema iling.) Thisexamplecanbegeneralizedtoamoreabstractsituation inwhichwehaveanarray thatcontainsobjects,andwewanttosearchorsortthearray basedonthevalueofoneofthe instancevariablesinthatarray.Wecanusesometerminolog yherethatoriginatedinwork with\databases,"whicharejustlarge,organizedcollecti onsofdata.Werefertoeachofthe objectsinthearrayasa record .Theinstancevariablesinanobjectarethencalled elds of therecord.Inthemailinglistexample,eachrecordwouldco ntainanameandaddress.The eldsoftherecordmightbetherstname,lastname,streeta ddress,state,cityandzipcode. Forthepurposeofsearchingorsorting,oneoftheeldsisde signatedtobethe key eld. Searchingthenmeansndingarecordinthearraythathasasp eciedvalueinitskeyeld. Sortingmeansmovingtherecordsaroundinthearraysothatt hekeyeldsoftherecordare inincreasing(ordecreasing)order. Inthissection,mostofmyexamplesfollowthetraditionofu singarraysofnumbers.But I'llalsogiveafewexamplesusingrecordsandkeys,toremin dyouofthemorepractical applications.7.4.1SearchingThereisanobviousalgorithmforsearchingforaparticular iteminanarray:Lookateach iteminthearrayinturn,andcheckwhetherthatitemistheon eyouarelookingfor.Ifso, thesearchisnished.Ifyoulookateveryitemwithoutndin gtheoneyouwant,thenyou canbesurethattheitemisnotinthearray.It'seasytowrite asubroutinetoimplementthis algorithm.Let'ssaythearraythatyouwanttosearchisanar rayof ints .Hereisamethod thatwillsearchthearrayforaspeciedinteger.Iftheinte gerisfound,themethodreturns theindexofthelocationinthearraywhereitisfound.Ifthe integerisnotinthearray,the methodreturnsthevalue -1 asasignalthattheintegercouldnotbefound: /** <br /> <br /> PAGE 356<br /> <br /> CHAPTER7.ARRAYS 342 *SearchesthearrayAfortheintegerN.IfNisnotinthearray *then-1isreturned.IfNisinthearray,thenreturnvalueis*thefirstintegerithatsatisfiesA[i]==N.*/ staticintfind(int[]A,intN){ for(intindex=0;index<A.length;index++){ if(A[index]==N) returnindex;//Nhasbeenfoundatthisindex! }//Ifwegetthisfar,thenNhasnotbeenfound//anywhereinthearray.Returnavalueof-1.return-1; } Thismethodofsearchinganarraybylookingateachitemintu rniscalled linearsearch Ifnothingisknownabouttheorderoftheitemsinthearray,t henthereisreallynobetter alternativealgorithm.Butiftheelementsinthearrayarek nowntobeinincreasingordecreasingorder,thenamuchfastersearchalgorithmcanbeused.An arrayinwhichtheelementsare inorderissaidtobe sorted .Ofcourse,ittakessomeworktosortanarray,butifthearra y istobesearchedmanytimes,thentheworkdoneinsortingitc anreallypayo. Binarysearch isamethodforsearchingforagivenitemina sorted array.Although theimplementationisnottrivial,thebasicideaissimple: Ifyouaresearchingforanitemin asortedlist,thenitispossibletoeliminatehalfoftheite msinthelistbyinspectingasingle item.Forexample,supposethatyouarelookingforthenumbe r42inasortedarrayof1000 integers.Let'sassumethatthearrayissortedintoincreas ingorder.Supposeyoucheckitem number500inthearray,andndthattheitemis93.Since42is lessthan93,andsincethe elementsinthearrayareinincreasingorder,wecanconclud ethatif42occursinthearray atall,thenitmustoccursomewherebeforelocation500.All thelocationsnumbered500or abovecontainvaluesthataregreaterthanorequalto93.The selocationscanbeeliminated aspossiblelocationsofthenumber42. Thenextobviousstepistochecklocation250.Ifthenumbera tthatlocationis,say,-21, thenyoucaneliminatelocationsbefore250andlimitfurthe rsearchtolocationsbetween251 and499.Thenexttestwilllimitthesearchtoabout125locat ions,andtheoneafterthatto about62.Afterjust10steps,thereisonlyonelocationleft .Thisisawholelotbetterthan lookingthrougheveryelementinthearray.Iftherewereami llionitems,itwouldstilltake only20stepsforbinarysearchtosearchthearray!(Mathema tically,thenumberofstepsis approximatelyequaltothelogarithm,inthebase2,ofthenu mberofitemsinthearray.) InordertomakebinarysearchintoaJavasubroutinethatsea rchesanarrayAforanitem N ,wejusthavetokeeptrackoftherangeoflocationsthatcoul dpossiblycontain N .Ateach step,asweeliminatepossibilities,wereducethesizeofth isrange.Thebasicoperationisto lookattheiteminthemiddleoftherange.Ifthisitemisgrea terthan N ,thenthesecond halfoftherangecanbeeliminated.Ifitislessthan N ,thenthersthalfoftherangecan beeliminated.Ifthenumberinthemiddlejusthappenstobe N exactly,thenthesearchis nished.Ifthesizeoftherangedecreasestozero,thenthen umber N doesnotoccurinthe array.Hereisasubroutinethatreturnsthelocationof N inasortedarray A .If N cannotbe foundinthearray,thenavalueof-1isreturnedinstead: /** <br /> <br /> PAGE 357<br /> <br /> CHAPTER7.ARRAYS 343 *SearchesthearrayAfortheintegerN.*Precondition:Amustbesortedintoincreasingorder.*Postcondition:IfNisinthearray,thenthereturnvalue,i *satisfiesA[i]==N.IfNisnotinthearray,thenthe*returnvalueis-1.*/ staticintbinarySearch(int[]A,intN){ intlowestPossibleLoc=0;inthighestPossibleLoc=A.length-1;while(highestPossibleLoc>=lowestPossibleLoc){ intmiddle=(lowestPossibleLoc+highestPossibleLoc)/2;if(A[middle]==N){ //Nhasbeenfoundatthisindex! returnmiddle; }elseif(A[middle]>N){ //eliminatelocations>=middle highestPossibleLoc=middle-1; }else{ //eliminatelocations<=middle lowestPossibleLoc=middle+1; } }//Atthispoint,highestPossibleLoc<LowestPossibleLoc,//whichmeansthatNisknowntobenotinthearray.Return//a-1toindicatethatNcouldnotbefoundinthearray.return-1; } 7.4.2AssociationListsOneparticularlycommonapplicationofsearchingiswith associationlists .Thestandard exampleofanassociationlistisadictionary.Adictionary associatesdenitionswithwords. Givenaword,youcanusethedictionarytolookupitsdeniti on.Wecanthinkofthedictionary asbeingalistof pairs oftheform (w,d) ,where w isawordand d isitsdenition.Ageneral associationlistisalistofpairs (k,v) ,where k issome\key"value,and v isavalueassociated tothatkey.Ingeneral,wewanttoassumethatnotwopairsint helisthavethesamekey. Therearetwobasicoperationsonassociationlists:Givena key, k ,ndthevalue v associated with k ,ifany.Andgivenakey, k ,andavalue v ,addthepair (k,v) totheassociationlist (replacingthepair,ifany,thathadthesamekeyvalue).The twooperationsareusuallycalled get and put Associationlistsareverywidelyusedincomputerscience. Forexample,acompilerhas tokeeptrackofthelocationinmemoryassociatedwitheachv ariable.Itcandothiswithan associationlistinwhicheachkeyisavariablenameandthea ssociatedvalueistheaddressof thatvariableinmemory.Anotherexamplewouldbeamailingl ist,ifwethinkofitasassociating anaddresstoeachnameonthelist.Asarelatedexample,cons ideraphonedirectorythat <br /> <br /> PAGE 358<br /> <br /> CHAPTER7.ARRAYS 344 associatesaphonenumbertoeachname.Theitemsinthelistc ouldbeobjectsbelongingto theclass: classPhoneEntry{ Stringname;StringphoneNum; } Thedataforaphonedirectoryconsistsofanarrayoftype PhoneEntry[] andaninteger variabletokeeptrackofhowmanyentriesareactuallystore dinthedirectory.Thetechnique of\dynamicarrays"( Subsection7.3.2 )canbeusedinordertoavoidputtinganarbitrarylimit onthenumberofentriesthatthephonedirectorycanhold.Us ingan ArrayList wouldbeanother possibility.A PhoneDirectory classshouldincludeinstancemethodsthatimplementthe\g et" and\put"operations.Hereisonepossiblesimpledenition oftheclass: /** *APhoneDirectoryholdsalistofnameswithaphonenumberfo r *eachname.Itispossibletofindthenumberassociatedwith*agivenname,andtospecifythephonenumberforagivenname */ publicclassPhoneDirectory{ /** *AnobjectoftypePhoneEntryholdsonename/numberpair.*/ privatestaticclassPhoneEntry{ Stringname;//Thename.Stringnumber;//Theassociatedphonenumber. }privatePhoneEntry[]data;//Arraythatholdsthename/num berpairs. privateintdataCount;//Thenumberofpairsstoredinthear ray. /** *Constructorcreatesaninitiallyemptydirectory.*/ publicPhoneDirectory(){ data=newPhoneEntry[1];dataCount=0; }/** *Looksforaname/numberpairwithagivenname.Iffound,the index *ofthepairinthedataarrayisreturned.Ifnopaircontains the *givenname,thenthereturnvalueis-1.*/ privateintfind(Stringname){ for(inti=0;i<dataCount;i++){ if(data[i].name.equals(name)) returni;//Thenamehasbeenfoundinpositioni. }return-1;//Thenamedoesnotexistinthearray. }/** *Findsthephonenumber,ifany,foragivenname. <br /> <br /> PAGE 359<br /> <br /> CHAPTER7.ARRAYS 345 *@returnThephonenumberassociatedwiththename;ifthena medoes *notoccurinthephonedirectory,thenthereturnvalueisnu ll. */ publicStringgetNumber(Stringname){ intposition=find(name);if(position==-1) returnnull;//Thereisnophoneentryforthegivenname. else returndata[position].number; }/** *Associatesagivennamewithagivenphonenumber.Ifthenam e *alreadyexistsinthephonedirectory,thenthenewnumberr eplaces *theoldone.Otherwise,anewname/numberpairisadded.The*nameandnumbershouldbothbenon-null.AnIllegalArgumen tException *isthrownifthisisnotthecase.*/ publicvoidputNumber(Stringname,Stringnumber){ if(name==null||number==null) thrownewIllegalArgumentException("nameandnumbercann otbenull"); inti=find(name);if(i>=0){ //Thenamealreadyexists,inpositioniinthearray.//Justreplacetheoldnumberatthatpositionwiththenew. data[i].number=number; }else{ //Addanewname/numberpairtothearray.Ifthearrayis//alreadyfull,firstcreateanew,largerarray. if(dataCount==data.length){ PhoneEntry[]newData=newPhoneEntry[2*data.length];System.arraycopy(newData,0,data,0,dataCount);data=newData; }PhoneEntrynewEntry=newPhoneEntry();//Createanewpair newEntry.name=name;newEntry.number=number;data[dataCount]=newEntry;//Addthenewpairtothearray.dataCount++; } } }//endclassPhoneDirectory Theclassdenesaprivateinstancemethod, find() ,thatuseslinearsearchtondthe positionofagivennameinthearrayofname/numberpairs.Th e find() methodisused bothinthe getNumber() methodandinthe putNumber() method.Noteinparticularthat putNumber(name,number) hastocheckwhetherthenameisinthephonedirectory.Ifso, it justchangesthenumberintheexistingentry;ifnot,ithast ocreateanewphoneentryand addittothearray. Thisclasscouldusealotofimprovement.Foronething,itwo uldbenicetousebinary searchinsteadofsimplelinearsearchinthe getNumber method.However,wecouldonlydo thatifthelistofPhoneEntriesweresortedintoalphabetic alorderaccordingtoname.Infact, <br /> <br /> PAGE 360<br /> <br /> CHAPTER7.ARRAYS 346 it'sreallynotallthathardtokeepthelistofentriesinsor tedorder,asyou'llseeinthenext subsection.7.4.3InsertionSortWe'veseenthattherearegoodreasonsforsortingarrays.Th erearemanyalgorithmsavailable fordoingso.Oneoftheeasiesttounderstandisthe insertionsort algorithm.Thismethod isalsoapplicabletotheproblemof keeping alistinsortedorderasyouaddnewitemstothe list.Let'sconsiderthatcaserst: Supposeyouhaveasortedlistandyouwanttoaddanitemtotha tlist.Ifyouwantto makesurethatthemodiedlistisstillsorted,thentheitem mustbeinsertedintotheright location,withallthesmalleritemscomingbeforeitandall thebiggeritemsafterit.Thiswill meanmovingeachofthebiggeritemsuponespacetomakeroomf orthenewitem. /* *Precondition:itemsInArrayisthenumberofitemsthatare*storedinA.Theseitemsmustbeinincreasingorder*(A[0]<=A[1]<=...<=A[itemsInArray-1]).*ThearraysizeisatleastonegreaterthanitemsInArray.*Postcondition:Thenumberofitemshasincreasedbyone,*newItemhasbeenaddedtothearray,andalltheitems*inthearrayarestillinincreasingorder.*Note:Tocompletetheprocessofinsertinganiteminthe*array,thevariablethatcountsthenumberofitems*inthearraymustbeincremented,aftercallingthis*subroutine.*/ staticvoidinsert(int[]A,intitemsInArray,intnewItem) { intloc=itemsInArray-1;//Startattheendofthearray./*MoveitemsbiggerthannewItemuponespace; Stopwhenasmalleritemisencounteredorwhenthebeginningofthearray(loc==0)isreached.*/ while(loc>=0&&A[loc]>newItem){ A[loc+1]=A[loc];//BumpitemfromA[loc]uptoloc+1.loc=loc-1;//Goontonextlocation. }A[loc+1]=newItem;//PutnewIteminlastvacatedspace. } Conceptually,thiscouldbeextendedtoasortingmethodifw eweretotakealltheitems outofanunsortedarray,andtheninsertthembackintothear rayone-by-one,keepingthelist insortedorderaswedoso.Eachinsertioncanbedoneusingth e insert routinegivenabove. Intheactualalgorithm,wedon'treallytakealltheitemsfr omthearray;wejustremember whatpartofthearrayhasbeensorted: staticvoidinsertionSort(int[]A){ //SortthearrayAintoincreasingorder. intitemsSorted;//Numberofitemsthathavebeensortedsof ar. for(itemsSorted=1;itemsSorted<A.length;itemsSorted+ +){ <br /> <br /> PAGE 361<br /> <br /> CHAPTER7.ARRAYS 347 //AssumethatitemsA[0],A[1],...A[itemsSorted-1]//havealreadybeensorted.InsertA[itemsSorted]//intothesortedpartofthelist. inttemp=A[itemsSorted];//Theitemtobeinserted.intloc=itemsSorted-1;//Startatendoflist.while(loc>=0&&A[loc]>temp){ A[loc+1]=A[loc];//BumpitemfromA[loc]uptoloc+1.loc=loc-1;//Goontonextlocation. }A[loc+1]=temp;//Puttempinlastvacatedspace. } } Thefollowingisanillustrationofonestageininsertionso rt.Itshowswhathappensduring oneexecutionofthe for loopintheabovemethod,when itemsSorted is5: n n r r r r r r r r r 7.4.4SelectionSortAnothertypicalsortingmethodusestheideaofndingthebi ggestiteminthelistandmoving ittotheend|whichiswhereitbelongsifthelististobeinin creasingorder.Oncethebiggest itemisinitscorrectlocation,youcanthenapplythesameid eatotheremainingitems.Thatis, ndthenext-biggestitem,andmoveitintothenext-to-last space,andsoforth.Thisalgorithm iscalled selectionsort .It'seasytowrite: <br /> <br /> PAGE 362<br /> <br /> CHAPTER7.ARRAYS 348 staticvoidselectionSort(int[]A){ //SortAintoincreasingorder,usingselectionsort for(intlastPlace=A.length-1;lastPlace>0;lastPlace-){ //FindthelargestitemamongA[0],A[1],...,//A[lastPlace],andmoveitintopositionlastPlace//byswappingitwiththenumberthatiscurrently//inpositionlastPlace. intmaxLoc=0;//Locationoflargestitemseensofar.for(intj=1;j<=lastPlace;j++){ if(A[j]>A[maxLoc]){ //SinceA[j]isbiggerthanthemaximumwe'veseen//sofar,jisthenewlocationofthemaximumvalue//we'veseensofar. maxLoc=j; } }inttemp=A[maxLoc];//SwaplargestitemwithA[lastPlace] A[maxLoc]=A[lastPlace];A[lastPlace]=temp; }//endofforloop } Insertionsortandselectionsortaresuitableforsortingf airlysmallarrays(uptoafewhundredelements,say).Therearemorecomplicatedsortingalg orithmsthataremuchfasterthan insertionsortandselectionsortforlargearrays.I'lldis cussonesuchalgorithmin Chapter9 Avariationofselectionsortisusedinthe Hand classthatwasintroducedin Subsection5.4.1 (Bytheway,youarenallyinapositiontofullyunderstandt hesourcecodeforboththe Hand classandthe Deck classfromthatsection.Seethesourceles Deck.java and Hand.java .) Inthe Hand class,ahandofplayingcardsisrepresentedbya Vector .Thisisoldercode, whichused Vector insteadof ArrayList ,andIhavechosennottomodifyitsothatyouwould seeatleastoneexampleofusing Vectors .See Subsection7.3.5 foradiscussionof Vectors Theobjectsstoredinthe Vector areoftype Card .A Card objectcontainsinstancemethods getSuit() and getValue() thatcanbeusedtodeterminethesuitandvalueofthecard.In mysortingmethod,Iactuallycreateanewvectorandmovethe cardsone-by-onefromtheold vectortothenewvector.Thecardsareselectedfromtheoldv ectorinincreasingorder.Inthe end,thenewvectorbecomesthehandandtheoldvectorisdisc arded.Thisiscertainlynot themostecientprocedure!Buthandsofcardsaresosmallth attheineciencyisnegligible. Hereisthecodeforsortingcardsbysuit: /** *Sortsthecardsinthehandsothatcardsofthesamesuitare*groupedtogether,andwithinasuitthecardsaresortedbyv alue. *Notethatacesareconsideredtohavethelowestvalue,1.*/ publicvoidsortBySuit(){ VectornewHand=newVector();while(hand.size()>0){ <br /> <br /> PAGE 363<br /> <br /> CHAPTER7.ARRAYS 349 intpos=0;//Positionofminimalcardfoundsofar.Cardc=(Card)hand.elementAt(0);//Theminimalcard.for(inti=1;i<hand.size();i++){ Cardc1=(Card)hand.elementAt(i);if(c1.getSuit()<c.getSuit()|| (c1.getSuit()==c.getSuit()&&c1.getValue()<c.getValu e())){ pos=i;c=c1; } }hand.removeElementAt(pos);newHand.addElement(c); }hand=newHand; } Thisexampleillustratesthefactthatcomparingitemsinal istisnotusuallyassimpleas usingtheoperator\ < ".Inthiscase,weconsideronecardtobelessthananotherif thesuit oftherstcardislessthanthesuitofthesecond,andalsoif thesuitsarethesameandthe valueofthesecondcardislessthanthevalueoftherst.The secondpartofthistestensures thatcardswiththesamesuitwillendupsortedbyvalue. Sortingalistof Strings raisesasimilarproblem:the\ < "operatorisnotdenedforstrings. However,the String classdoesdenea compareTo method.If str1 and str2 areoftype String then str1.compareTo(str2) returnsan int thatis0when str1 isequalto str2 ,islessthan0when str1 preceeds str2 andisgreaterthan0when str1 follows str2 .Thedenitionof\succeeds"and\follows"for stringsuseswhatiscalled lexicographicordering ,whichisbasedontheUnicodevaluesof thecharactersinthestrings.Lexicographicorderingisno tthesameasalphabeticalordering, evenforstringsthatconsistentirelyofletters(becausei nlexicographicordering,alltheupper caseletterscomebeforeallthelowercaseletters).Howeve r,forwordsconsistingstrictlyof the26lowercaselettersintheEnglishalphabet,lexicogra phicandalphabeticorderingarethe same.Thus,if str1 and str2 arestringscontainingonlylettersfromtheEnglishalphab et, thenthetest str1.toLowerCase().compareTo(str2.toLowerCase())<0 istrueifandonlyif str1 comesbefore str2 inalphabeticalorder. 7.4.5UnsortingIcan'tresistendingthissectiononsortingwitharelatedp roblemthatismuchlesscommon, butisabitmorefun.Thatistheproblemofputtingtheelemen tsofanarrayintoarandom order.Thetypicalcaseofthisproblemisshuingadeckofca rds.Agoodalgorithmfor shuingissimilartoselectionsort,exceptthatinsteadof movingthebiggestitemtotheend ofthelist,anitemisselectedatrandomandmovedtotheendo fthelist.Hereisasubroutine toshueanarrayof ints : /** *Postcondition:TheitemsinAhavebeenrearrangedintoara ndomorder. */ staticvoidshuffle(int[]A){ <br /> <br /> PAGE 364<br /> <br /> CHAPTER7.ARRAYS 350 for(intlastPlace=A.length-1;lastPlace>0;lastPlace-){ //Choosearandomlocationfromamong0,1,...,lastPlace. intrandLoc=(int)(Math.random()*(lastPlace+1)); //SwapitemsinlocationsrandLocandlastPlace. inttemp=A[randLoc];A[randLoc]=A[lastPlace];A[lastPlace]=temp; } } 7.5Multi-dimensionalArraysA nytypecanbeused asthebasetypeofanarray.Youcanhaveanarrayof ints ,an (online) arrayof Strings ,anarrayof Objects ,andsoon.Inparticular,sinceanarraytypeisarst-class Javatype,youcanhaveanarrayofarrays.Forexample,anarr ayof ints hastype int[] .This meansthatthereisautomaticallyanothertype, int[][] ,whichrepresentsan\arrayofarraysof ints ".Suchanarrayissaidtobea two-dimensionalarray .Ofcourseonceyouhavethe type int[][] ,thereisnothingtostopyoufromformingthetype int[][][] ,whichrepresentsa three-dimensionalarray |andsoon.Thereisnolimitonthenumberofdimensionsthata n arraytypecanhave.However,arraysofdimensionthreeorhi gherarefairlyuncommon,and Iconcentrateheremainlyontwo-dimensionalarrays.Thety pe BaseType[][] isusuallyread \two-dimensionalarrayof BaseType "or\ BaseType arrayarray". 7.5.1CreatingTwo-dimensionalArraysThedeclarationstatement\ int[][]A; "declaresavariablenamed A oftype int[][] .This variablecanholdareferencetoanobjectoftype int[][] .Theassignmentstatement\ A=new int[3][4]; "createsanewtwo-dimensionalarrayobjectandsets A topointtothenewlycreatedobject.Asusual,thedeclarationandassignmentcould becombinedinasingledeclaration statement\ int[][]A=newint[3][4]; ".Thenewlycreatedobjectisanarrayofarraysofints .Thenotation int[3][4] indicatesthatthereare3arrays-ofints inthearray A ,and thatthereare4 ints ineacharray-ofints .However,tryingtothinkinsuchtermscangetabit confusing|asyoumighthavealreadynoticed.Soitiscustom arytothinkofatwo-dimensional arrayofitemsasarectangular grid or matrix ofitems.Thenotation\ newint[3][4] "can thenbetakentodescribeagridof ints with3rowsand4columns.Thefollowingpicture mighthelp: <br /> <br /> PAGE 365<br /> <br /> CHAPTER7.ARRAYS 351 # $ $ % Forthemostpart,youcanignoretherealityandkeepthepict ureofagridinmind. Sometimes,though,youwillneedtorememberthateachrowin thegridisreallyanarrayin itself.Thesearrayscanbereferredtoas A[0] A[1] ,and A[2] .Eachrowisinfactavalueof type int[] .Itcould,forexample,bepassedtoasubroutinethatasksfo raparameteroftype int[] Thenotation A[1] referstooneoftherowsofthearray A .Since A[1] isitselfanarrayof ints ,youcanuseanothersubscripttorefertooneoftheposition sinthatrow.Forexample, A[1][3] referstoitemnumber3inrownumber1.Keepinmind,ofcourse ,thatbothrows andcolumnsarenumberedstartingfromzero.So,intheabove example, A[1][3] is5.More generally, A[i][j] referstothegridpositioninrownumber i andcolumnnumber j .The12 itemsin A arenamedasfollows: A[0][0]A[0][1]A[0][2]A[0][3]A[1][0]A[1][1]A[1][2]A[1][3]A[2][0]A[2][1]A[2][2]A[2][3] A[i][j] isactuallyavariableoftype int .Youcanassignintegervaluestoitoruseitinany othercontextwhereanintegervariableisallowed. Itmightbeworthnotingthat A.length givesthenumberofrowsof A .Togetthenumber ofcolumnsin A ,youhavetoaskhowmany ints thereareinarow;thisnumberwouldbe givenby A[0].length ,orequivalentlyby A[1].length or A[2].length .(Thereisactually norulethatsaysthatalltherowsofanarraymusthavethesam elength,andsomeadvanced applicationsofarraysusevarying-sizedrows.Butifyouus ethe new operatortocreateanarray inthemannerdescribedabove,you'llalwaysgetanarraywit hequal-sizedrows.) Three-dimensionalarraysaretreatedsimilarly.Forexamp le,athree-dimensionalarrayof ints couldbecreatedwiththedeclarationstatement\ int[][][]B=newint[7][5][11]; ". It'spossibletovisualizethevalueof B asasolid7-by-5-by-11blockofcells.Eachcellholdsan int andrepresentsonepositioninthethree-dimensionalarray .Individualpositionsinthearray canbereferredtowithvariablenamesoftheform B[i][j][k] .Higher-dimensionalarrays <br /> <br /> PAGE 366<br /> <br /> CHAPTER7.ARRAYS 352 followthesamepattern,althoughfordimensionsgreaterth anthree,thereisnoeasywayto visualizethestructureofthearray. It'spossibletollamulti-dimensionalarraywithspecie ditemsatthetimeitisdeclared. Recallthatwhenanordinaryone-dimensionalarrayvariabl eisdeclared,itcanbeassigned an\arrayinitializer,"whichisjustalistofvaluesenclos edbetweenbraces, { and } .Array initializerscanalsobeusedwhenamulti-dimensionalarra yisdeclared.Aninitializerfora two-dimensionalarrayconsistsofalistofone-dimensiona larrayinitializers,oneforeachrow inthetwo-dimensionalarray.Forexample,thearray A showninthepictureabovecouldbe createdwith: int[][]A={{1,0,12,-1}, {7,-3,2,5},{-5,-2,2,-9} }; Ifnoinitializerisprovidedforanarray,thenwhenthearra yiscreateditisautomaticallylled withtheappropriatevalue:zerofornumbers, false forboolean,and null forobjects. 7.5.2UsingTwo-dimensionalArraysJustasinthecaseofone-dimensionalarrays,two-dimensio nalarraysareoftenprocessedusing for statements.Toprocessalltheitemsinatwo-dimensionalar ray,youhavetouseone for statementnestedinsideanother.Ifthearray A isdeclaredas int[][]A=newint[3][4]; thenyoucouldstoreazerointoeachlocationin A with: for(introw=0;row<3;row++){ for(intcolumn=0;column<4;column++){ A[row][column]=0; } } Thersttimetheouter for loopexecutes(with row =0),theinnerforloopllsinthefour valuesintherstrowofA,namely A[0][0]=0 A[0][1]=0 A[0][2]=0 ,and A[0][3] =0 .Thenextexecutionoftheouter for loopllsinthesecondrowof A .Andthethirdand nalexecutionoftheouterloopllsinthenalrowof A Similarly,youcouldaddupalltheitemsin A with: intsum=0;for(inti=0;i<3;i++) for(intj=0;j<4;j++) sum=sum+A[i][j]; Thiscouldevenbedonewithnestedfor-eachloops.Keepinmi ndthattheelementsin A are objectsoftype int[] ,whiletheelementsineachrowof A areoftype int : intsum=0;for(int[]row:A){//ForeachrowinA... for(intitem:row)//Foreachiteminthatrow... sum=sum+item;//Additemtothesum. } <br /> <br /> PAGE 367<br /> <br /> CHAPTER7.ARRAYS 353 Toprocessathree-dimensionalarray,youwould,ofcourse, usetriplynested for loops. Atwo-dimensionalarraycanbeusedwheneverthedatathatis beingrepresentedcanbe arrangedintorowsandcolumnsinanaturalway.Often,thegr idisbuiltintotheproblem. Forexample,achessboardisagridwith8rowsand8columns.I faclassnamed ChessPiece isavailabletorepresentindividualchesspieces,thenthe contentsofachessboardcouldbe representedbyatwo-dimensionalarray: ChessPiece[][]board=newChessPiece[8][8]; Orconsiderthe\mosaic"ofcoloredrectanglesusedinanexa mplein Subsection4.6.2 .The mosaicisimplementedbyaclassnamed MosaicCanvas.java .Thedataaboutthecolorofeach oftherectanglesinthemosaicisstoredinaninstancevaria blenamed grid oftype Color[][] Eachpositioninthisgridisoccupiedbyavalueoftype Color .Thereisonepositioninthegrid foreachcoloredrectangleinthemosaic.Theactualtwo-dim ensionalarrayiscreatedbythe statement: grid=newColor[ROWS][COLUMNS]; where ROWS isthenumberofrowsofrectanglesinthemosaicand COLUMNS isthenumberof columns.Thevalueofthe Color variable grid[i][j] isthecoloroftherectangleinrownumber i andcolumnnumber j .Whenthecolorofthatrectangleischangedtosomecolor, c ,thevalue storedin grid[i][j] ischangedwithastatementoftheform\ grid[i][j]=c; ".Whenthe mosaicisredrawn,thevaluesstoredinthetwo-dimensional arrayareusedtodecidewhatcolor tomakeeachrectangle.Hereisasimpliedversionofthecod efromthe MosaicCanvas class thatdrawsallthecoloredrectanglesinthegrid.Youcansee howitusesthearray: introwHeight=getHeight()/ROWS;intcolWidth=getWidth()/COLUMNS;for(introw=0;row<ROWS;row++){ for(intcol=0;col<COLUMNS;col++){ g.setColor(grid[row][col]);//Getcolorfromarray.g.fillRect(col*colWidth,row*rowHeight, colWidth,rowHeight); } } Sometimestwo-dimensionalarraysareusedinproblemsinwh ichthegridisnotsovisually obvious.Consideracompanythatowns25stores.Supposetha tthecompanyhasdataabout theprotearnedateachstoreforeachmonthintheyear2006. Ifthestoresarenumbered from0to24,andifthetwelvemonthsfromJanuary'06through December'06arenumbered from0to11,thentheprotdatacouldbestoredinanarray, profit ,constructedasfollows: double[][]profit=newdouble[25][12]; profit[3][2] wouldbetheamountofprotearnedatstorenumber3inMarch, and moregenerally, profit[storeNum][monthNum] wouldbetheamountofprotearnedinstore number storeNum inmonthnumber monthNum .Inthisexample,theone-dimensionalarray profit[storeNum] hasaveryusefulmeaning:Itisjusttheprotdataforonepar ticularstore forthewholeyear. Let'sassumethatthe profit arrayhasalreadybeenlledwithdata.Thisdatacanbe processedinalotofinterestingways.Forexample,thetota lprotforthecompany|forthe wholeyearfromallitsstores|canbecalculatedbyaddingup alltheentriesinthearray: <br /> <br /> PAGE 368<br /> <br /> CHAPTER7.ARRAYS 354 doubletotalProfit;//Company'stotalprofitin2006.totalProfit=0;for(intstore=0;store<25;store++){ for(intmonth=0;month<12;month++) totalProfit+=profit[store][month]; } Sometimesitisnecessarytoprocessasingleroworasinglec olumnofanarray,notthe entirearray.Forexample,tocomputethetotalprotearned bythecompanyinDecember, thatis,inmonthnumber11,youcouldusetheloop: doubledecemberProfit=0.0;for(storeNum=0;storeNum<25;storeNum++) decemberProfit+=profit[storeNum][11]; Let'sextendthisideatocreateaone-dimensionalarraytha tcontainsthetotalprotforeach monthoftheyear: double[]monthlyProfit;//Holdsprofitforeachmonth.monthlyProfit=newdouble[12];for(intmonth=0;month<12;month++){ //computethetotalprofitfromallstoresinthismonth.monthlyProfit[month]=0.0;for(intstore=0;store<25;store++){ //Addtheprofitfromthisstoreinthismonth//intothetotalprofitfigureforthemonth. monthlyProfit[month]+=profit[store][month]; } } Asanalexampleofprocessingtheprotarray,supposethat wewantedtoknowwhich storegeneratedthemostprotoverthecourseoftheyear.To dothis,wehavetoaddupthe monthlyprotsforeachstore.Inarrayterms,thismeanstha twewanttondthesumofeach rowinthearray.Aswedothis,weneedtokeeptrackofwhichro wproducesthelargesttotal. doublemaxProfit;//Maximumprofitearnedbyastore.intbestStore;//Thenumberofthestorewiththe //maximumprofit. doubletotal=0.0;//Totalprofitforonestore.//Firstcomputetheprofitfromstorenumber0.for(intmonth=0;month<12;month++) total+=profit[0][month]; bestStore=0;//StartbyassumingthatthebestmaxProfit=total;//storeisstorenumber0.//Now,gothroughtheotherstores,andwheneverwe//findonewithabiggerprofitthanmaxProfit,revise//theassumptionsaboutbestStoreandmaxProfit.for(store=1;store<25;store++){ //Computethisstore'sprofitfortheyear.total=0.0; <br /> <br /> PAGE 369<br /> <br /> CHAPTER7.ARRAYS 355 for(month=0;month<12;month++) total+=profit[store][month]; //Comparethisstore'sprofitswiththehighest//profitwehaveseenamongtheprecedingstores.if(total>maxProfit){ maxProfit=total;//Bestprofitseensofar!bestStore=store;//Itcamefromthisstore. } }//endfor//Atthispoint,maxProfitisthebestprofitofany//ofthe25stores,andbestStoreisastorethat//generatedthatprofit.(Notethattherecouldalsobe//otherstoresthatgeneratedexactlythesameprofit.) 7.5.3Example:CheckersFortherestofthissection,we'lllookatamoresubstantial example.Welookataprogramthat letstwousersplaycheckersagainsteachother.Aplayermov esbyclickingonthepiecetobe movedandthenontheemptysquaretowhichitistobemoved.Th esquaresthatthecurrent playercanlegallyclickarehilited.Thesquarecontaining apiecethathasbeenselectedtobe movedissurroundedbyawhiteborder.Otherpiecesthatcanl egallybemovedaresurrounded byacyan-coloredborder.Ifapiecehasbeenselected,eache mptysquarethatitcanlegally movetoishilitedwithagreenborder.Thegameenforcesther ulethatifthecurrentplayercan jumponeoftheopponent'spieces,thentheplayermustjump. Whenaplayer'spiecebecomes aking,byreachingtheoppositeendoftheboard,abigwhite\ K"isdrawnonthepiece.You cantryanappletversionoftheprogramintheon-lineversio nofthissection.Hereiswhatit lookslike: Iwillonlycoverapartoftheprogrammingofthisapplet.Ien courageyoutoreadthe completesourcecode, Checkers.java .Atover750lines,thisisamoresubstantialexample thananythingyou'veseenbeforeinthiscourse,butit'sane xcellentexampleofstate-based, event-drivenprogramming. Thedataaboutthepiecesontheboardarestoredinatwo-dime nsionalarray.Becauseof thecomplexityoftheprogram,Iwantedtodivideitintoseve ralclasses.Inadditiontothe <br /> <br /> PAGE 370<br /> <br /> CHAPTER7.ARRAYS 356 mainclass,thereareseveralnestedclasses.Oneofthesecl assesis CheckersData ,whichhandles thedatafortheboard.ItismainlythisclassthatIwanttota lkabout. The CheckersData classhasaninstancevariablenamed board oftype int[][] .Thevalue ofboardissetto\ newint[8][8] ",an8-by-8gridofintegers.Thevaluesstoredinthegrid aredenedasconstantsrepresentingthepossiblecontents ofasquareonacheckerboard: staticfinalint EMPTY=0,//Valuerepresentinganemptysquare.RED=1,//Aregularredpiece.RED KING=2,//Aredking. BLACK=3,//Aregularblackpiece.BLACK KING=4;//Ablackking. Theconstants RED and BLACK arealsousedinmyprogram(or,perhaps,misused)toreprese nt thetwoplayersinthegame.Whenagameisstarted,thevalues inthevariable, board ,areset torepresenttheinitialstateoftheboard.Thegridofvalue slookslike & ( ) + / & ( ) + / & ( ) + / & ( ) + / 0 & ( ) + / & ( ) + / & ( ) + / & ( ) + / 1 & ( ) + / & ( ) + / & ( ) + / & ( ) + / 2 + / + / + / + / 3 + / + / + / + / + / + / + / + / 4 + / + / + / + / 5 6 + 7 8 6 + 7 + / + / + / + / 9 6 + 7 6 + 7 6 + 7 + / + / + / + / 6 + 7 6 + 7 6 + 7 0 1 2 3 4 5 8 9 6 + 7 + / + / + / + / 6 + 7 6 + 7 6 + 7 Ablackpiececanonlymove\down"thegrid.Thatis,therownu mberofthesquareit movestomustbegreaterthantherownumberofthesquareitco mesfrom.Aredpiececan onlymoveupthegrid.Kingsofeithercolor,ofcourse,canmo veinbothdirections. Onefunctionofthe CheckersData classistotakecareofallthedetailsofmakingmoves ontheboard.Aninstancemethodnamed makeMove() isprovidedtodothis.Whenaplayer movesapiecefromonesquaretoanother,thevaluesstoredat twopositionsinthearrayare changed.Butthat'snotall.Ifthemoveisajump,thenthepie cethatwasjumpedisremoved fromtheboard.(Themethodcheckswhetherthemoveisajumpb ycheckingifthesquareto whichthepieceismovingistworowsawayfromthesquarewher eitstarts.)Furthermore,a RED piecethatmovestorow0ora BLACK piecethatmovestorow7becomesaking.Thisis goodprogramming:therestoftheprogramdoesn'thavetowor ryaboutanyofthesedetails. Itjustcallsthis makeMove() method: /** *Makethemovefrom(fromRow,fromCol)to(toRow,toCol).It is *ASSUMEDthatthismoveislegal!Ifthemoveisajump,the*jumpedpieceisremovedfromtheboard.Ifapiecemoves*tothelastrowontheopponent'ssideoftheboard,the*piecebecomesaking.*/ voidmakeMove(intfromRow,intfromCol,inttoRow,inttoCo l){ <br /> <br /> PAGE 371<br /> <br /> CHAPTER7.ARRAYS 357 board[toRow][toCol]=board[fromRow][fromCol];//Movet hepiece. board[fromRow][fromCol]=EMPTY;if(fromRow-toRow==2||fromRow-toRow==-2){ //Themoveisajump.Removethejumpedpiecefromtheboard. intjumpRow=(fromRow+toRow)/2;//Rowofthejumpedpiece.intjumpCol=(fromCol+toCol)/2;//Columnofthejumpedpie ce. board[jumpRow][jumpCol]=EMPTY; }if(toRow==0&&board[toRow][toCol]==RED) board[toRow][toCol]=RED KING;//Redpiecebecomesaking. if(toRow==7&&board[toRow][toCol]==BLACK) board[toRow][toCol]=BLACK KING;//Blackpiecebecomesaking. }//endmakeMove() Anevenmoreimportantfunctionofthe CheckersData classistondlegalmovesonthe board.Inmyprogram,amoveinaCheckersgameisrepresented byanobjectbelongingto thefollowingclass: /** *ACheckersMoveobjectrepresentsamoveinthegameof*Checkers.Itholdstherowandcolumnofthepiecethatis*tobemovedandtherowandcolumnofthesquaretowhich*itistobemoved.(Thisclassmakesnoguaranteethat*themoveislegal.)*/ privatestaticclassCheckersMove{ intfromRow,fromCol;//Positionofpiecetobemoved.inttoRow,toCol;//Squareitistomoveto.CheckersMove(intr1,intc1,intr2,intc2){ //Constructor.Setthevaluesoftheinstancevariables. fromRow=r1;fromCol=c1;toRow=r2;toCol=c2; }booleanisJump(){ //Testwhetherthismoveisajump.Itisassumedthat//themoveislegal.Inajump,thepiecemovestwo//rows.(Inaregularmove,itonlymovesonerow.) return(fromRow-toRow==2||fromRow-toRow==-2); } }//endclassCheckersMove. The CheckersData classhasaninstancemethodwhichndsallthelegalmovesth atare currentlyavailableforaspeciedplayer.Thismethodisaf unctionthatreturnsanarray oftype CheckersMove[] .Thearraycontainsallthelegalmoves,representedas CheckersMove objects.Thespecicationforthismethodreads <br /> <br /> PAGE 372<br /> <br /> CHAPTER7.ARRAYS 358 /** *ReturnanarraycontainingallthelegalCheckersMoves*forthespecifiedplayeronthecurrentboard.Iftheplayer*hasnolegalmoves,nullisreturned.Thevalueofplayer*shouldbeoneoftheconstantsREDorBLACK;ifnot,null*isreturned.Ifthereturnedvalueisnon-null,itconsists*entirelyofjumpmovesorentirelyofregularmoves,since*iftheplayercanjump,onlyjumpsarelegalmoves.*/ CheckersMove[]getLegalMoves(intplayer) Abriefpseudocodealgorithmforthemethodis StartwithanemptylistofmovesFindanylegaljumpsandaddthemtothelistiftherearenojumps: Findanyotherlegalmovesandaddthemtothelist ifthelistisempty: returnnull else: returnthelist Now,whatisthis\list"?Wehavetoreturnthelegalmovesina narray.Butsinceanarrayhas axedsize,wecan'tcreatethearrayuntilweknowhowmanymo vesthereare,andwedon't knowthatuntilneartheendofthemethod,afterwe'vealread ymadethelist!Aneatsolution istousean ArrayList insteadofanarraytoholdthemovesaswendthem.Infact,Iu sean objectdenedbytheparameterizedtype ArrayList < CheckersMove > sothatthelistisrestricted toholdingobjectsoftype CheckersMove .Asweaddmovestothelist,itwillgrowjustaslarge asnecessary.Attheendofthemethod,wecancreatethearray thatwereallywantandcopy thedataintoit: Let"moves"beanemptyArrayList<CheckerMove>Findanylegaljumpsandaddthemtomovesifmoves.size()is0: Findanyotherlegalmovesandaddthemtomoves ifmoves.size()is0: returnnull else: LetmoveArraybeanarrayofCheckersMovesoflengthmoves.s ize() CopythecontentsofmovesintomoveArrayreturnmoveArray Now,howdowendthelegaljumpsorthelegalmoves?Theinfor mationweneedisinthe board array,butittakessomeworktoextractit.Wehavetolookthr oughallthepositions inthearrayandndthepiecesthatbelongtothecurrentplay er.Foreachpiece,wehaveto checkeachsquarethatitcouldconceivablymoveto,andchec kwhetherthatwouldbealegal move.Therearefoursquarestoconsider.Forajump,wewantt olookatsquaresthataretwo rowsandtwocolumnsawayfromthepiece.Thus,thelineinthe algorithmthatsays\Find anylegaljumpsandaddthemtomoves"expandsto: Foreachrowoftheboard: Foreachcolumnoftheboard: ifoneoftheplayer'spiecesisatthislocation: ifitislegaltojumptorow+2,column+2 addthismovetomoves <br /> <br /> PAGE 373<br /> <br /> CHAPTER7.ARRAYS 359 ifitislegaltojumptorow-2,column+2 addthismovetomoves ifitislegaltojumptorow+2,column-2 addthismovetomoves ifitislegaltojumptorow-2,column-2 addthismovetomoves Thelinethatsays\Findanyotherlegalmovesandaddthemtom oves"expandstosomethingsimilar,exceptthatwehavetolookatthefoursquares thatareonecolumnandone rowawayfromthepiece.Testingwhetheraplayercanlegally movefromonegivensquareto anothergivensquareisitselfnon-trivial.Thesquarethep layerismovingtomustactuallybe ontheboard,anditmustbeempty.Furthermore,regularreda ndblackpiecescanonlymove inonedirection.Iwrotethefollowingutilitymethodtoche ckwhetheraplayercanmakea givennon-jumpmove: /** *ThisiscalledbythegetLegalMoves()methodtodetermine*whethertheplayercanlegallymovefrom(r1,c1)to(r2,c2) *ItisASSUMEDthat(r1,c1)containsoneoftheplayer's*piecesandthat(r2,c2)isaneighboringsquare.*/ privatebooleancanMove(intplayer,intr1,intc1,intr2,i ntc2){ if(r2<0||r2>=8||c2<0||c2>=8) returnfalse;//(r2,c2)isofftheboard. if(board[r2][c2]!=EMPTY) returnfalse;//(r2,c2)alreadycontainsapiece. if(player==RED){ if(board[r1][c1]==RED&&r2>r1) returnfalse;//Regularredpiececanonlymovedown. returntrue;//Themoveislegal. }else{ if(board[r1][c1]==BLACK&&r2<r1) returnfalse;//Regularblackpiececanonlymoveup. returntrue;//Themoveislegal. } }//endcanMove() Thismethodiscalledbymy getLegalMoves() methodtocheckwhetheroneofthepossible movesthatithasfoundisactuallylegal.Ihaveasimilarmet hodthatiscalledtocheckwhether ajumpislegal.Inthiscase,Ipasstothemethodthesquareco ntainingtheplayer'spiece, thesquarethattheplayermightmoveto,andthesquarebetwe enthosetwo,whichtheplayer wouldbejumpingover.Thesquarethatisbeingjumpedmustco ntainoneoftheopponent's pieces.Thismethodhasthespecication: /** *Thisiscalledbyothermethodstocheckwhether*theplayercanlegallyjumpfrom(r1,c1)to(r3,c3).*Itisassumedthattheplayerhasapieceat(r1,c1),that*(r3,c3)isapositionthatis2rowsand2columnsdistant*from(r1,c1)andthat(r2,c2)isthesquarebetween(r1,c1)*and(r3,c3). <br /> <br /> PAGE 374<br /> <br /> CHAPTER7.ARRAYS 360 */ privatebooleancanJump(intplayer,intr1,intc1, intr2,intc2,intr3,intc3){... Givenallthis,youshouldbeinapositiontounderstandthec omplete getLegalMoves() method.It'sanicewaytonishothischapter,sinceitcomb inesseveraltopicsthatwe've lookedat:one-dimensionalarrays, ArrayLists ,andtwo-dimensionalarrays: CheckersMove[]getLegalMoves(intplayer){ if(player!=RED&&player!=BLACK) returnnull; intplayerKing;//TheconstantforaKingbelongingtothepl ayer. if(player==RED) playerKing=RED KING; else playerKing=BLACK KING; ArrayList<ChecherMove>moves=newArrayList<CheckerMov e>(); //Moveswillbestoredinthislist. /*First,checkforanypossiblejumps.Lookateachsquareon theboard.Ifthatsquarecontainsoneoftheplayer'spieces lookatapossiblejumpineachofthefourdirectionsfromtha t square.Ifthereisalegaljumpinthatdirection,putitinthemovesArrayList. */for(introw=0;row<8;row++){ for(intcol=0;col<8;col++){ if(board[row][col]==player||board[row][col]==player King){ if(canJump(player,row,col,row+1,col+1,row+2,col+2)) moves.add(newCheckersMove(row,col,row+2,col+2)); if(canJump(player,row,col,row-1,col+1,row-2,col+2)) moves.add(newCheckersMove(row,col,row-2,col+2)); if(canJump(player,row,col,row+1,col-1,row+2,col-2)) moves.add(newCheckersMove(row,col,row+2,col-2)); if(canJump(player,row,col,row-1,col-1,row-2,col-2)) moves.add(newCheckersMove(row,col,row-2,col-2)); } } }/*Ifanyjumpmoveswerefound,thentheusermustjump,sowe don'taddanyregularmoves.However,ifnojumpswerefound,checkforanylegalregularmoves.Lookateachsquareontheboard.Ifthatsquarecontainsoneoftheplayer'spieces lookatapossiblemoveineachofthefourdirectionsfromthatsquare.Ifthereisalegalmoveinthatdirection,putitinthemovesArrayList. */if(moves.size()==0){ for(introw=0;row<8;row++){ for(intcol=0;col<8;col++){ if(board[row][col]==player||board[row][col]==player King){ <br /> <br /> PAGE 375<br /> <br /> CHAPTER7.ARRAYS 361 if(canMove(player,row,col,row+1,col+1)) moves.add(newCheckersMove(row,col,row+1,col+1)); if(canMove(player,row,col,row-1,col+1)) moves.add(newCheckersMove(row,col,row-1,col+1)); if(canMove(player,row,col,row+1,col-1)) moves.add(newCheckersMove(row,col,row+1,col-1)); if(canMove(player,row,col,row-1,col-1)) moves.add(newCheckersMove(row,col,row-1,col-1)); } } } }/*Ifnolegalmoveshavebeenfound,returnnull.Otherwise, create anarrayjustbigenoughtoholdallthelegalmoves,copythelegalmovesfromtheArrayListintothearray,andreturnthe array. */if(moves.size()==0) returnnull; else{ CheckersMove[]moveArray=newCheckersMove[moves.size( )]; for(inti=0;i<moves.size();i++) moveArray[i]=moves.get(i); returnmoveArray; } }//endgetLegalMoves <br /> <br /> PAGE 376<br /> <br /> Exercises 362 ExercisesforChapter7 1. Anexamplein Subsection7.2.4 triedtoanswerthequestion,Howmanyrandompeopledo (solution) youhavetoselectbeforeyoundaduplicatebirthday?Theso urcecodeforthatprogram canbefoundinthele BirthdayProblemDemo.java .Herearesomerelatedquestions: Howmanyrandompeopledoyouhavetoselectbeforeyound three peoplewho sharethesamebirthday?(Thatis,allthreepeoplewereborn onthesamedayin thesamemonth,butnotnecessarilyinthesameyear.) Supposeyouchoose365peopleatrandom.Howmanydierentbi rthdayswillthey have?(Thenumbercouldtheoreticallybeanywherefrom1to3 65). Howmanydierentpeopledoyouhavetocheckbeforeyou'vefo undatleastone personwithabirthdayoneachofthe365daysoftheyear? Write three programstoanswerthesequestions.Eachofyourprogramssh ouldsimulatechoosingpeopleatrandomandcheckingtheirbirthday s.(Ineachcase,ignorethe possibilityofleapyears.) 2. Writeaprogramthatwillreadasequenceofpositiverealnum bersenteredbytheuser (solution) andwillprintthesamenumbersinsortedorderfromsmallest tolargest.Theuserwill inputazerotomarktheendoftheinput.Assumethatatmost10 0positivenumberswill beentered. 3. A polygon isageometricguremadeupofasequenceofconnectedlinese gments.The (solution) pointswherethelinesegmentsmeetarecalledthe vertices ofthepolygon.The Graphics classincludescommandsfordrawingandllingpolygons.Fo rthesecommands,the coordinatesoftheverticesofthepolygonarestoredinarra ys.If g isavariableoftype Graphics then g.drawPolygon(xCoords,yCoords,pointCt) willdrawtheoutlineofthepolygon withverticesatthepoints (xCoords[0],yCoords[0]) (xCoords[1],yCoords[1]) ..., (xCoords[pointCt-1],yCoords[pointCt-1]) .Thethirdparameter, pointCt isan int thatspeciesthenumberofverticesofthepolygon.Itsvalu e shouldbe3orgreater.Thersttwoparametersarearraysoft ype int[] .Notethatthepolygonautomaticallyincludesalinefromth elast point, (xCoords[pointCt-1],yCoords[pointCt-1]) ,backtothestartingpoint (xCoords[0],yCoords[0]) g.fillPolygon(xCoords,yCoords,pointCt) llstheinteriorofthepolygonwith thecurrentdrawingcolor.Theparametershavethesamemean ingasinthe drawPolygon() method.NotethatitisOKforthesidesofthepolygontocross eachother,buttheinteriorofapolygonwithself-intersec tionsmightnotbeexactly whatyouexpect. Writeapanelclassthatletstheuserdrawpolygons,andusey ourpanelasthecontent paneinanapplet(orstandaloneapplication).Astheusercl icksasequenceofpoints, countthemandstoretheirx-andy-coordinatesintwoarrays .Thesepointswillbethe verticesofthepolygon.Also,drawalinebetweeneachconse cutivepairofpointstogive theusersomevisualfeedback.Whentheuserclicksnearthes tartingpoint,drawthe <br /> <br /> PAGE 377<br /> <br /> Exercises 363 completepolygon.Drawitwitharedinteriorandablackbord er.Theusershouldthen beabletostartdrawinganewpolygon.Whentheusershift-cl icksontheapplet,clearit. Forthisexercise,thereisnoneedtostoreinformationabou tthecontentsoftheapplet. Dothedrawingdirectlyinthe mouseDragged() routine,andusethe getGraphics() methodtogeta Graphics objectthatyoucanusetodrawtheline.(Remember,though, thatthisisconsideredtobebadstyle.)Youwillnotneeda paintComponent() method, sincethedefaultactionofllingthepanelwithitsbackgro undcolorisgoodenough. Hereisapictureofmysolutionaftertheuserhasdrawnafewp olygons: 4. Forthisproblem,youwillneedtouseanarrayofobjects.The objectsbelongtotheclass (solution) MovingBall ,whichIhavealreadywritten.Youcanndthesourcecodefor thisclassin thele MovingBall.java .A MovingBall representsacirclethathasanassociatedcolor, radius,direction,andspeed.Itisrestrictedtomovingina rectangleinthe (x,y) plane. Itwill\bounceback"whenithitsoneofthesidesofthisrect angle.A MovingBall doesnot actuallymovebyitself.It'sjustacollectionofdata.Youh avetocallinstancemethodsto tellittoupdateitspositionandtodrawitself.Theconstru ctorforthe MovingBall class takestheform newMovingBall(xmin,xmax,ymin,ymax) wheretheparametersareintegersthatspecifythelimitson the x and y coordinatesof theball.Inthisexercise,youwillwantballstobounceoth esidesoftheapplet,soyou willcreatethemwiththeconstructorcall newMovingBall(0,getWidth(),0,getHeight()) Theconstructorcreatesaballthatinitiallyiscoloredred ,hasaradiusof5pixels,is locatedatthecenterofitsrange,hasarandomspeedbetween 4and12,andisheadedin arandomdirection.Thereisone problem here:Youcan'tusethisconstructoruntilthe widthandheightofthecomponentareknown.ItwouldbeOKtou seitinthe init() methodofanapplet,butnotintheconstructorofanappletor panelclass.Ifyouareusing apanelclasstodisplaytheball,oneslightlymessysolutio nistocreatethe MovingBall objectsinthepanel's paintComponent() methodthersttimethatmethodiscalled.You canbesurethatthesizeofthepanelhasbeendeterminedbefo re paintComponent() is called.ThisiswhatIdidinmyownsolutiontothisexercise. <br /> <br /> PAGE 378<br /> <br /> Exercises 364 If ball isavariableoftype MovingBall ,thenthefollowingmethodsareavailable: ball.draw(g) |drawtheballinagraphicscontext.Theparameter, g ,mustbeof type Graphics .(Thedrawingcolorin g willbechangedtothecoloroftheball.) ball.travel() |changethe (x,y)coordinatesoftheballbyanamountequalto itsspeed.Theballhasacertaindirectionofmotion,andthe ballismovedinthat direction.Ordinarily,youwillcallthisonceforeachfram eofananimation,sothe speedisgivenintermsof\pixelsperframe".Callingthisro utinedoesnotmove theballonthescreen.Itjustchangesthevaluesofsomeinst ancevariablesinthe object.Thenexttimetheobject's draw() methodiscalled,theballwillbedrawn inthenewposition. ball.headTowards(x,y) |changethedirectionofmotionoftheballsothatitis headedtowardsthepoint (x,y) .Thisdoesnotaectthespeed. Thesearethemethodsthatyouwillneedforthisexercise.Th erearealsomethodsfor settingvariouspropertiesoftheball,suchas ball.setColor(color) forchangingthe colorand ball.setRadius(radius) forchangingitssize.Seethesourcecodeformore information. Forthisexercise,youshouldcreateanappletthatshowsana nimationofballsbouncing aroundonablackbackground.Usea Timer todrivetheanimation.(See Subsection6.5.1 .) Useanarrayoftype MovingBall[] toholdthedatafortheballs.Inaddition,your programshouldlistenformouseandmousemotionevents.Whe ntheuserpressesthe mouseordragsthemouse,calleachoftheball's headTowards() methodstomakethe ballsheadtowardsthemouse'slocation.Mysolutionuses50 ballsandatimedelayof50 millisecondsforthetimer. 5. Thesampleprogram RandomArtPanel.java from Subsection6.5.1 showsadierentran(solution) dom\artwork"everyfourseconds.Therearethreetypesof\a rt",onemadefromlines, onefromcircles,andonefromlledsquares.However,thepr ogramdoesnotsavethedata forthepicturethatisshownonthescreen.Asaresult,thepi cturecannotberedrawn whennecessary.Infact,everytime paintComponent() iscalled,anewpictureisdrawn. Writeanewversionof RandomArtPanel.java thatsavesthedataneededtoredrawits pictures.The paintComponent() methodshouldsimplyusethedatatodrawthepicture. Newdatashouldberecomputedonlyeveryfourseconds,inres ponsetoaneventfromthe timerthatdrivestheprogram. Tomakethisinteresting,writeaseparateclassforeachoft hethreedierenttypesof art.Alsowriteanabstractclasstoserveasthecommonbasec lassforthethreeclasses. Sinceallthreetypesofartusearandomgraybackground,the backgroundcolorcanbe denedintheirsuperclass.Thesuperclassalsocontainsa draw() methodthatdrawsthe picture;thisisanabstractmethodbecauseitsimplementat iondependsontheparticular typeofartthatisbeingdrawn.Theabstractclasscanbeden edas: privateabstractclassArtData{ ColorbackgroundColor;//Thebackgroundcolorfortheart.ArtData(){//Constructorsetsbackgroundcolortobearand omgray. intx=(int)(256*Math.random());backgroundColor=newColor(x,x,x,); }abstractvoiddraw(Graphicsg);//Drawsthisartwork. } <br /> <br /> PAGE 379<br /> <br /> Exercises 365 Eachofthethreesubclassesof ArtData mustdeneitsown draw() method.Itmust alsodeneinstancevariablestoholdthedatanecessarytod rawthepicture.Isuggest thatyoushouldcreaterandomdataforthepictureinthecons tructoroftheclass,sothat constructingtheobjectwillautomaticallycreatethedata forarandomartwork.(One problemwiththisisthatyoucan'tcreatethedatauntilyouk nowthesizeofthepanel, soyoucan'tcreateanartdataobjectintheconstructorofth epanel.Onesolutionisto createanartdataobjectatthebeginningofthe paintComponent() method,iftheobject hasnotalreadybeencreated.)Inallthreesubclasses,youw illneedtouseseveralarrays tostorethedata. Thele RandomArtPanel.java onlydenesapanelclass.Amainprogramthatuses thispanelcanbefoundin RandomArt.java ,andanappletthatusesitcanbefoundin RandomArtApplet.java 6. Writeaprogramthatwillreadatextleselectedbytheuser, andwillmakeanalphabetical (solution) listofallthedierentwordsinthatle.Allwordsshouldbe convertedtolowercase,and duplicatesshouldbeeliminatedfromthelist.Thelistshou ldbewrittentoanoutputle selectedbytheuser.Asdiscussedin Subsection2.4.5 ,youcanuse TextIO toreadandwrite les.Useavariableoftype ArrayList < String > tostorethewords.(See Subsection7.3.4 .) Itisnoteasytoseparatealeintowordsasyouarereadingit .Youcanusethefollowing method: /** *ReadthenextwordfromTextIO,ifthereisone.First,skipp ast *anynon-lettersintheinput.Ifanend-of-fileisencounte redbefore *awordisfound,returnnull.Otherwise,readandreturnthe word. *Awordisdefinedasasequenceofletters.Also,awordcanin clude *anapostropheiftheapostropheissurroundedbyletterson eachside. *@returnthenextwordfromTextIO,ornullifanend-of-file is *encountered*/ privatestaticStringreadNextWord(){ charch=TextIO.peek();//Lookatnextcharacterininput.while(ch!=TextIO.EOF&&!Character.isLetter(ch)){ TextIO.getAnyChar();//Readthecharacter.ch=TextIO.peek();//Lookatthenextcharacter. }if(ch==TextIO.EOF)//Encounteredend-of-file returnnull; //Atthispoint,weknowthenextcharacterisaletter,sorea daword. Stringword="";//Thiswillbethewordthatisread.while(true){ word+=TextIO.getAnyChar();//Appendtheletterontoword ch=TextIO.peek();//Lookatnextcharacter.if(ch=='\''){ //Thenextcharacterisanapostrophe.Readit,and//ifthefollowingcharacterisaletter,addboththe//apostropheandtheletterontothewordandcontinue//readingtheword.Ifthecharacteraftertheapostrophe//isnotaletter,thewordisdone,sobreakoutoftheloop. TextIO.getAnyChar();//Readtheapostrophe.ch=TextIO.peek();//Lookatcharthatfollowsapostrophe.if(Character.isLetter(ch)){ <br /> <br /> PAGE 380<br /> <br /> Exercises 366 word+="\'"+TextIO.getAnyChar();ch=TextIO.peek();//Lookatnextchar. }else break; }if(!Character.isLetter(ch)){ //Ifthenextcharacterisnotaletter,thewordis//finished,sobreakoutoftheloop. break; }//Ifwehaven'tbrokenoutoftheloop,nextcharisaletter. }returnword;//Returnthewordthathasbeenread. } Notethatthismethodwillreturn null whenthelehasbeenentirelyread.Youcanuse thisasasignaltostopprocessingtheinputle. 7. ThegameofGoMoku(alsoknownasPenteorFiveStones)issimi lartoTic-Tac-Toe, (solution) exceptthatitplayedonamuchlargerboardandtheobjectist ogetvesquaresinarow ratherthanthree.Playerstaketurnsplacingpiecesonaboa rd.Apiececanbeplaced inanyemptysquare.Therstplayertogetvepiecesinarow| horizontally,vertically, ordiagonally|wins.Ifallsquaresarelledbeforeeitherp layerwins,thenthegameisa draw.WriteaprogramthatletstwoplayersplayGoMokuagain steachother. Yourprogramwillbesimplerthanthe Checkers programfrom Subsection7.5.3 .Play alternatesstrictlybetweenthetwoplayers,andthereisno needtohilitethelegalmoves. Youwillonlyneedtwoclasses,ashortpanelclasstosetupth einterfaceanda Board classtodrawtheboardanddoalltheworkofthegame.Neverth eless,youwillprobably wanttolookatthesourcecodeforthecheckersprogram, Checkers.java ,forideasabout thegeneraloutlineoftheprogram. Thehardestpartoftheprogramischeckingwhetherthemovet hataplayermakesis awinningmove.Todothis,youhavetolookineachofthefourp ossibledirectionsfrom thesquarewheretheuserhasplacedapiece.Youhavetocount howmanypiecesthat playerhasinarowinthatdirection.Ifthenumberisveormo reinanydirection,then thatplayerwins.Asahint,hereispartofthecodefrommyapp let.Thiscodecounts thenumberofpiecesthattheuserhasinarowinaspecieddir ection.Thedirectionis speciedbytwointegers, dirX and dirY .Thevaluesofthesevariablesare0,1,or-1,and atleastoneofthemisnon-zero.Forexample,tolookintheho rizontaldirection, dirX is 1and dirY is0. intct=1;//Numberofpiecesinarowbelongingtotheplayer.intr,c;//Arowandcolumntobeexaminedr=row+dirX;//Lookatsquareinspecifieddirection.c=col+dirY;while(r>=0&&r<13&&c>=0&&c<13 &&board[r][c]==player){ //Squareisontheboard,andit//containsoneoftheplayers'spieces. ct++; <br /> <br /> PAGE 381<br /> <br /> Exercises 367 r+=dirX;//Goontonextsquareinthisdirection.c+=dirY; }r=row-dirX;//Now,lookintheoppositedirection.c=col-dirY;while(r>=0&&r<13&&c>=0&&c<13 &&board[r][c]==player){ ct++;r-=dirX;//Goontonextsquareinthisdirection.c-=dirY; } HereisapictureofmyprogramItusesa13-by-13board.Youca ndothesameoruse anormal8-by-8checkerboard. <br /> <br /> PAGE 382<br /> <br /> Quiz 368 QuizonChapter7 (answers) 1. Whatdoesthecomputerdowhenitexecutesthefollowingstat ement?Trytogiveas completeanansweraspossible. Color[]palette=newColor[12]; 2. Whatismeantbythe basetype ofanarray? 3. Whatdoesitmeantosortanarray? 4. Whatisthemainadvantageofbinarysearchoverlinearsearc h?Whatisthemain disadvantage? 5. Whatismeantbya dynamicarray? Whatistheadvantageofadynamicarrayovera regulararray? 6. Supposethatavariable strlst hasbeendeclaredas ArrayList<String>strlst=newArrayList<String>(); Assumethatthelistisnotemptyandthatalltheitemsinthel istarenon-null.Writea codesegmentthatwillndandprintthestringinthelisttha tcomesrstinlexicographic order.Howwouldyouranswerchangeif strlst weredeclaredtobeoftype ArrayList insteadof ArrayList < String > ? 7. Whatisthepurposeofthefollowingsubroutine?Whatisthem eaningofthevaluethat itreturns,intermsofthevalueofitsparameter? staticStringconcat(String[]str){ if(str==null) return""; Stringans="";for(inti=0;i<str.length;i++){ ans=ans+str[i]; returnans; } 8. Showtheexactoutputproducedbythefollowingcodesegment char[][]pic=newchar[6][6];for(inti=0;i<6;i++) for(intj=0;j<6;j++){ if(i==j||i==0||i==5) pic[i][j]='*'; else pic[i][j]='.'; } for(inti=0;i<6;i++){ for(intj=0;j<6;j++) System.out.print(pic[i][j]); System.out.println(); } <br /> <br /> PAGE 383<br /> <br /> Quiz 369 9. Writeacompletesubroutinethatndsthelargestvalueinan arrayof ints .Thesubroutineshouldhaveoneparameter,whichisanarrayoftype int[] .Thelargestnumberin thearrayshouldbereturnedasthevalueofthesubroutine. 10. Supposethattemperaturemeasurementsweremadeoneachday of1999ineachof100 cities.Themeasurementshavebeenstoredinanarray int[][]temps=newint[100][365]; where temps[c][d] holdsthemeasurementforcitynumber c onthe d th dayoftheyear. Writeacodesegmentthatwillprintouttheaveragetemperat ure,overthecourseofthe wholeyear,foreachcity.Theaveragetemperatureforacity canbeobtainedbyadding upall365measurementsforthatcityanddividingtheanswer by365.0. 11. Supposethataclass, Employee, isdenedasfollows: classEmployee{ StringlastName;StringfirstName;doublehourlyWage;intyearsWithCompany; } Supposethatdataabout100employeesis already storedinanarray: Employee[]employeeData=newEmployee[100]; Writeacodesegmentthatwilloutputtherstname,lastname ,andhourlywageofeach employeewhohasbeenwiththecompanyfor20yearsormore. 12. Supposethat A hasbeendeclaredandinitializedwiththestatement double[]A=newdouble[20]; andsupposethat A has already beenlledwith20values.Writeaprogramsegmentthat willndtheaverageofallthe non-zero numbersinthearray.(Theaverageisthesum ofthenumbers,dividedbythenumberofnumbers.Notethatyo uwillhavetocountthe numberofnon-zeroentriesinthearray.)Declareanyvariab lesthatyouuse. <br /> <br /> PAGE 384<br /> <br /> Chapter8CorrectnessandRobustnessI npreviouschapters ,wehavecoveredthefundamentalsofprogramming.Thechapt ers thatfollowwillcovermoreadvancedaspectsofprogramming .Theideasthatarepresented willbealittlemorecomplexandtheprogramsthatusethemal ittlemorecomplicated.This chapterisakindofturningpointinwhichwelookattheprobl emofgettingsuchcomplex programs right Computerprogramsthatfailaremuchtoocommon.Programsar efragile.Atinyerror cancauseaprogramtomisbehaveorcrash.Mostofusarefamil iarwiththisfromourown experiencewithcomputers.Andwe'veallheardstoriesabou tsoftwareglitchesthatcause spacecrafttocrash,telephoneservicetofail,and,inafew cases,peopletodie. Programsdon'thavetobeasbadastheyare.Itmightwellbeim possibletoguarantee thatprogramsareproblem-free,butcarefulprogrammingan dwell-designedprogrammingtools canhelpkeeptheproblemstoaminimum.Thischapterwillloo katissuesofcorrectnessand robustnessofprograms.Italsolooksmorecloselyatexcept ionsandthe try..catch statement, anditintroduces assertions ,anotherofthetoolsthatJavaprovidesasanaidinwritingc orrect programs. Thischapteralsoincludessectionsontwotopicsthatareon lyindirectlyrelatedtocorrectnessandrobustness. Section8.5 willintroduce threads while Section8.6 looksbrieryatthe AnalysisofAlgorithms .Bothofthesetopicsdotintothischapterinitsroleasatu rning point,sincetheyarepartofthefoundationformoreadvance dprogramming. 8.1IntroductiontoCorrectnessandRobustnessA program is correct ifitaccomplishesthetaskthatitwasdesignedtoperform.I tis robust (online) ifitcanhandleillegalinputsandotherunexpectedsituati onsinareasonableway.Forexample, consideraprogramthatisdesignedtoreadsomenumbersfrom theuserandthenprintthe samenumbersinsortedorder.Theprogramiscorrectifitwor ksforanysetofinputnumbers. Itisrobustifitcanalsodealwithnon-numericinputby,for example,printinganerrormessage andignoringthebadinput.Anon-robustprogrammightcrash orgivenonsensicaloutputin thesamecircumstance. Everyprogramshouldbecorrect.(Asortingprogramthatdoe sn'tsortcorrectlyispretty useless.)It'snotthecasethateveryprogramneedstobecom pletelyrobust.Itdependson whowilluseitandhowitwillbeused.Forexample,asmalluti lityprogramthatyouwrite foryourownusedoesn'thavetobeparticularlyrobust. Thequestionofcorrectnessisactuallymoresubtlethanitm ightappear.Aprogrammer 370 <br /> <br /> PAGE 385<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 371 worksfromaspecicationofwhattheprogramissupposedtod o.Theprogrammer'sworkis correctiftheprogrammeetsitsspecication.Butdoesthat meanthattheprogramitselfis correct?Whatifthespecicationisincorrectorincomplet e?Acorrectprogramshouldbea correctimplementationofacompleteandcorrectspecicat ion.Thequestioniswhetherthe specicationcorrectlyexpressestheintentionanddesire softhepeopleforwhomtheprogram isbeingwritten.Thisisaquestionthatlieslargelyoutsid ethedomainofcomputerscience. 8.1.1HorrorStoriesMostcomputerusershavepersonalexperiencewithprograms thatdon'tworkorthatcrash.In manycases,suchproblemsarejustannoyances,butevenonap ersonalcomputertherecanbe moreseriousconsequences,suchaslostworkorlostmoney.W hencomputersaregivenmore importanttasks,theconsequencesoffailurecanbeproport ionatelymoreserious. Justafewyearsago,thefailureoftwomulti-millionspacem issionstoMarswasprominent inthenews.Bothfailureswereprobablyduetosoftwareprob lems,butinbothcasesthe problemwasnotwithanincorrectprogramassuch.InSeptemb er1999,theMarsClimate OrbiterburnedupintheMartianatmospherebecausedatatha twasexpressedinEnglishunits ofmeasurement(suchasfeetandpounds)wasenteredintoaco mputerprogramthatwas designedtousemetricunits(suchascentimetersandgrams) .Afewmonthslater,theMars PolarLanderprobablycrashedbecauseitssoftwareturnedo itslandingenginestoosoon. Theprogramwassupposedtodetectthebumpwhenthespacecra ftlandedandturnothe enginesthen.Ithasbeendeterminedthatdeploymentofthel andinggearmighthavejarred thespacecraftenoughtoactivatetheprogram,causingitto turnotheengineswhenthe spacecraftwasstillintheair.Theunpoweredspacecraftwo uldthenhavefallentotheMartian surface.Amorerobustsystemwouldhavecheckedthealtitud ebeforeturningotheengines! Therearemanyequallydramaticstoriesofproblemscausedb yincorrectorpoorlywritten software.Let'slookatafewincidentsrecountedinthebook ComputerEthics byTomForester andPerryMorrison.(Thisbookcoversvariousethicalissue sincomputing.It,orsomething likeit,isessentialreadingforanystudentofcomputersci ence.) In1985and1986,onepersonwaskilledandseveralwereinjur edbyexcessradiation,while undergoingradiationtreatmentsbyamis-programmedcompu terizedradiationmachine.In anothercase,overaten-yearperiodendingin1992,almost1 ,000cancerpatientsreceived radiationdosagesthatwere30%lessthanprescribedbecaus eofaprogrammingerror. In1985,acomputerattheBankofNewYorkstarteddestroying recordsofon-goingsecurity transactionsbecauseofanerrorinaprogram.Ittooklessth an24hourstoxtheprogram, butbythattime,thebankwasout$5,000,000inovernightint erestpaymentsonfundsthatit hadtoborrowtocovertheproblem. TheprogrammingoftheinertialguidancesystemoftheF-16 ghterplanewouldhaveturned theplaneupside-downwhenitcrossedtheequator,ifthepro blemhadnotbeendiscoveredin simulation.TheMariner18spaceprobewaslostbecauseofan errorinonelineofaprogram. TheGeminiVspacecapsulemisseditsscheduledlandingtarg etbyahundredmiles,because aprogrammerforgottotakeintoaccounttherotationoftheE arth. In1990,AT&T'slong-distancetelephoneservicewasdisrup tedthroughouttheUnitedStates whenanewlyloadedcomputerprogramprovedtocontainabug. Thesearejustafewexamples.Softwareproblemsarealltooc ommon.Asprogrammers, weneedtounderstandwhythatistrueandwhatcanbedoneabou tit. <br /> <br /> PAGE 386<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 372 8.1.2JavatotheRescuePartoftheproblem,accordingtotheinventorsofJava,canb etracedtoprogramminglanguages themselves.Javawasdesignedtoprovidesomeprotectionag ainstcertaintypesoferrors.How canalanguagefeaturehelppreventerrors?Let'slookatafe wexamples. Earlyprogramminglanguagesdidnotrequirevariablestobe declared.Insuchlanguages, whenavariablenameisusedinaprogram,thevariableiscrea tedautomatically.Youmight considerthismoreconvenientthanhavingtodeclareeveryv ariableexplicitly.Butthereisan unfortunateconsequence:Aninadvertentspellingerrormi ghtintroduceanextravariablethat youhadnointentionofcreating.Thistypeoferrorwasrespo nsible,accordingtoonefamous story,foryetanotherlostspacecraft.Inthe FORTRAN programminglanguage,thecommand\ DO 20I=1,5 "istherststatementofacountingloop.Now,spacesareins ignicantin FORTRAN sothisisequivalentto\ DO20I=1,5 ".Ontheotherhand,thecommand\ DO20I=1.5 ",witha periodinsteadofacomma,isanassignmentstatementthatas signsthevalue 1.5 tothevariable DO20I .Supposedly,theinadvertentsubstitutionofaperiodfora commainastatementofthis typecausedarockettoblowupontake-o.Because FORTRAN doesn'trequirevariablestobe declared,thecompilerwouldbehappytoacceptthestatemen t\ DO20I=1.5 ."Itwouldjust createanewvariablenamed DO20I .If FORTRAN requiredvariablestobedeclared,thecompiler wouldhavecomplainedthatthevariable DO20I wasundeclared. Whilemostprogramminglanguagestodaydorequirevariable stobedeclared,thereare otherfeaturesincommonprogramminglanguagesthatcancau seproblems.Javahaseliminated someofthesefeatures.Somepeoplecomplainthatthismakes Javalessecientandless powerful.Whilethereissomejusticeinthiscriticism,the increaseinsecurityandrobustnessis probablyworththecostinmostcircumstances.Thebestdefe nseagainstsometypesoferrors istodesignaprogramminglanguageinwhichtheerrorsareim possible.Inothercases,where theerrorcan'tbecompletelyeliminated,thelanguagecanb edesignedsothatwhentheerror doesoccur,itwillautomaticallybedetected.Thiswillatl eastpreventtheerrorfromcausing furtherharm,anditwillalerttheprogrammerthatthereisa bugthatneedsxing.Let'slook atafewcaseswherethedesignersofJavahavetakentheseapp roaches. Anarrayiscreatedwithacertainnumberoflocations,numbe redfromzerouptosome speciedmaximumindex.Itisanerrortotrytouseanarraylo cationthatisoutsideofthe speciedrange.InJava,anyattempttodosoisdetectedauto maticallybythesystem.Insome otherlanguages,suchasCandC++,it'suptotheprogrammert omakesurethattheindex iswithinthelegalrange.Supposethatanarray, A ,hasthreelocations, A[0] A[1] ,and A[2] Then A[3] A[4] ,andsoonrefertomemorylocationsbeyondtheendofthearra y.InJava, anattempttostoredatain A[3] willbedetected.Theprogramwillbeterminated(unlessthe erroris\caught",asdiscussedin Section3.7 ).InCorC++,thecomputerwilljustgoahead andstorethedatainmemorythatisnotpartofthearray.Sinc ethereisnotellingwhatthat memorylocationisbeingusedfor,theresultwillbeunpredi ctable.Theconsequencescould bemuchmoreseriousthanaterminatedprogram.(See,forexa mple,thediscussionofbuer overrowerrorslaterinthissection.) Pointersareanotorioussourceofprogrammingerrors.InJa va,avariableofobjecttype holdseitherapointertoanobjectorthespecialvalue null .Anyattempttousea null valueas ifitwereapointertoanactualobjectwillbedetectedbythe system.Insomeotherlanguages, again,it'suptotheprogrammertoavoidsuchnullpointerer rors.InmyoldMacintosh computer,a null pointerwasactuallyimplementedasifitwereapointertome morylocation zero.Aprogramcoulduseanullpointertochangevaluesstor edinmemorynearlocationzero. Unfortunately,theMacintoshstoredimportantsystemdata inthoselocations.Changingthat <br /> <br /> PAGE 387<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 373 datacouldcausethewholesystemtocrash,aconsequencemor eseverethanasinglefailed program. Anothertypeofpointererroroccurswhenapointervalueisp ointingtoanobjectofthe wrongtypeortoasegmentofmemorythatdoesnotevenholdava lidobjectatall.These typesoferrorsareimpossibleinJava,whichdoesnotallowp rogrammerstomanipulatepointers directly.Inotherlanguages,itispossibletosetapointer topoint,essentially,toanylocation inmemory.Ifthisisdoneincorrectly,thenusingthepointe rcanhaveunpredictableresults. AnothertypeoferrorthatcannotoccurinJavaisamemorylea k.InJava,oncethereare nolongeranypointersthatrefertoanobject,thatobjectis \garbagecollected"sothatthe memorythatitoccupiedcanbereused.Inotherlanguages,it istheprogrammer'sresponsibility toreturnunusedmemorytothesystem.Iftheprogrammerfail stodothis,unusedmemory canbuildup,leavinglessmemoryforprogramsanddata.Ther eisastorythatmanycommon programsforolderWindowscomputershadsomanymemoryleak sthatthecomputerwould runoutofmemoryafterafewdaysofuseandwouldhavetoberes tarted. Manyprogramshavebeenfoundtosuerfrom bueroverrowerrors .Bueroverrow errorsoftenmakethenewsbecausetheyareresponsibleform anynetworksecurityproblems. Whenonecomputerreceivesdatafromanothercomputerovera network,thatdataisstoredin abuer.Thebuerisjustasegmentofmemorythathasbeenall ocatedbyaprogramtohold datathatitexpectstoreceive.Abueroverrowoccurswhenm oredataisreceivedthanwill tinthebuer.Thequestionis,whathappensthen?Iftheerr orisdetectedbytheprogram orbythenetworkingsoftware,thentheonlythingthathasha ppenedisafailednetwork datatransmission.Therealproblemoccurswhenthesoftwar edoesnotproperlydetectbuer overrows.Inthatcase,thesoftwarecontinuestostoredata inmemoryevenafterthebueris lled,andtheextradatagoesintosomepartofmemorythatwa snotallocatedbytheprogram aspartofthebuer.Thatmemorymightbeinuseforsomeother purpose.Itmightcontain importantdata.Itmightevencontainpartoftheprogramits elf.Thisiswheretherealsecurity issuescomein.Supposethatabueroverrowcausespartofap rogramtobereplacedwith extradatareceivedoveranetwork.Whenthecomputergoesto executethepartoftheprogram thatwasreplaced,it'sactuallyexecutingdatathatwasrec eivedfromanothercomputer.That datacouldbeanything.Itcouldbeaprogramthatcrashesthe computerortakesitover.A maliciousprogrammerwhondsaconvenientbueroverrower rorinnetworkingsoftwarecan trytoexploitthaterrortotrickothercomputersintoexecu tinghisprograms. ForsoftwarewrittencompletelyinJava,bueroverrowerro rsareimpossible.Thelanguage simplydoesnotprovideanywaytostoredataintomemorythat hasnotbeenproperlyallocated. Todothat,youwouldneedapointerthatpointstounallocate dmemoryoryouwouldhave torefertoanarraylocationthatliesoutsidetherangeallo catedforthearray.Asexplained above,neitheroftheseispossibleinJava.(However,there couldconceivablystillbeerrorsin Java'sstandardclasses,sincesomeofthemethodsinthesec lassesareactuallywritteninthe CprogramminglanguageratherthaninJava.) It'sclearthatlanguagedesigncanhelppreventerrorsorde tectthemwhentheyoccur. Doingsoinvolvesrestrictingwhataprogrammerisallowedt odo.Oritrequirestests,suchas checkingwhetherapointeris null ,thattakesomeextraprocessingtime.Someprogrammers feelthatthesacriceofpowerandeciencyistoohighapric etopayfortheextrasecurity.In someapplications,thisistrue.However,therearemanysit uationswheresafetyandsecurity areprimaryconsiderations.Javaisdesignedforsuchsitua tions. <br /> <br /> PAGE 388<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 374 8.1.3ProblemsRemaininJavaThereisoneareawherethedesignersofJavachosenottodete cterrorsautomatically:numerical computations.InJava,avalueoftype int isrepresentedasa32-bitbinarynumber.With32 bits,it'spossibletorepresentalittleoverfourbilliond ierentvalues.Thevaluesoftype int rangefrom-2147483648to2147483647.Whathappenswhenthe resultofacomputationlies outsidethisrange?Forexample,whatis 2147483647+1 ?Andwhatis 2000000000*2 ?The mathematicallycorrectresultineachcasecannotberepres entedasavalueoftype int .These areexamplesof integeroverrow .Inmostcases,integeroverrowshouldbeconsideredan error.However,Javadoesnotautomaticallydetectsucherr ors.Forexample,itwillcompute thevalueof 2147483647+1 tobethenegativenumber, -2147483648 .(Whathappensis thatanyextrabitsbeyondthe32-ndbitinthecorrectanswer arediscarded.Valuesgreater than2147483647will\wraparound"tonegativevalues.Math ematicallyspeaking,theresult isalways\correctmodulo2 32 ".) Forexample,considerthe3N+1program,whichwasdiscussed in Subsection3.2.2 .Starting fromapositiveinteger N ,theprogramcomputesacertainsequenceofintegers: while(N!=1){ if(N%2==0)//IfNiseven... N=N/2; else N=3*N+1; System.out.println(N); } Butthereisaproblemhere:If N istoolarge,thenthevalueof 3*N+1 willnotbemathematically correctbecauseofintegeroverrow.Theproblemariseswhen ever 3*N+1>2147483647 ,thatis when N>2147483646/3 .Foracompletelycorrectprogram,weshouldcheckforthisp ossibility before computing 3*N+1 : while(N!=1){ if(N%2==0)//IfNiseven... N=N/2; else{ if(N>2147483646/3){ System.out.println("Sorry,butthevalueofNhasbecome") ; System.out.println("toolargeforyourcomputer!");break; }N=3*N+1; }System.out.println(N); } Theproblemhereisnotthattheoriginalalgorithmforcompu ting 3N+1 sequenceswas wrong.Theproblemisthatitjustcan'tbecorrectlyimpleme ntedusing32-bitintegers.Many programsignorethistypeofproblem.Butintegeroverrower rorshavebeenresponsiblefortheir shareofseriouscomputerfailures,andacompletelyrobust programshouldtakethepossibility ofintegeroverrowintoaccount.(Theinfamous\Y2K"bugwas ,infact,justthissortoferror.) Fornumbersoftype double ,thereareevenmoreproblems.Therearestilloverrowerrors,whichoccurwhentheresultofacomputationisoutside therangeofvaluesthatcanbe representedasavalueoftype double .Thisrangeextendsuptoabout1.7times10tothe <br /> <br /> PAGE 389<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 375 power308.Numbersbeyondthisrangedonot\wraparound"ton egativevalues.Instead,they arerepresentedbyspecialvaluesthathavenorealnumerica lequivalent.Thespecialvalues Double.POSITIVE INFINITY and Double.NEGATIVE INFINITY representnumbersoutsidethe rangeoflegalvalues.Forexample, 20*1e308 iscomputedtobe Double.POSITIVE INFINITY Anotherspecialvalueoftype double Double.NaN ,representsanillegalorundenedresult. (\NaN"standsfor\NotaNumber".)Forexample,theresultof dividingbyzeroortaking thesquarerootofanegativenumberis Double.NaN .Youcantestwhetheranumber x isthis specialnon-a-numbervaluebycallingthe boolean -valuedfunction Double.isNaN(x) Forrealnumbers,thereistheaddedcomplicationthatmostr ealnumberscanonlybe representedapproximatelyonacomputer.Arealnumbercanh aveaninnitenumberofdigits afterthedecimalpoint.Avalueoftype double isonlyaccuratetoabout15digits.Thereal number1/3,forexample,istherepeatingdecimal 0.333333333333... ,andthereisnowayto representitexactlyusinganitenumberofdigits.Computa tionswithrealnumbersgenerally involvealossofaccuracy.Infact,ifcareisnotexercised, theresultofalargenumberofsuch computationsmightbecompletelywrong!Thereisawholeel dofcomputerscience,knownas numericalanalysis ,whichisdevotedtostudyingalgorithmsthatmanipulatere alnumbers. Soyouseethatnotallpossibleerrorsareavoidedordetecte dautomaticallyinJava.Furthermore,evenwhenanerrorisdetectedautomatically,the system'sdefaultresponseisto reporttheerrorandterminatetheprogram.Thisishardlyro bustbehavior!So,aJavaprogrammerstillneedstolearntechniquesforavoidinganddea lingwitherrors.Thesearethe maintopicsoftherestofthischapter.8.2WritingCorrectProgramsC orrectprogramsdon't justhappen.Ittakesplanningandattentiontodetailtoavo id (online) errorsinprograms.Therearesometechniquesthatprogramm erscanusetoincreasethe likelihoodthattheirprogramsarecorrect.8.2.1ProvablyCorrectProgramsInsomecases,itispossibleto prove thataprogramiscorrect.Thatis,itispossibleto demonstratemathematicallythatthesequenceofcomputati onsrepresentedbytheprogram willalwaysproducethecorrectresult.Rigorousproofisdi cultenoughthatinpracticeitcan onlybeappliedtofairlysmallprograms.Furthermore,itde pendsonthefactthatthe\correct result"hasbeenspeciedcorrectlyandcompletely.AsI've alreadypointedout,aprogram thatcorrectlymeetsitsspecicationisnotusefulifitssp ecicationwaswrong.Nevertheless, evenineverydayprogramming,wecanapplysomeoftheideasa ndtechniquesthatareused inprovingthatprogramsarecorrect. Thefundamentalideasare process and state .Astateconsistsofalltheinformation relevanttotheexecutionofaprogramatagivenmomentdurin gitsexecution.Thestate includes,forexample,thevaluesofallthevariablesinthe program,theoutputthathasbeen produced,anyinputthatiswaitingtoberead,andarecordof thepositionintheprogram wherethecomputerisworking.Aprocessisthesequenceofst atesthatthecomputergoes throughasitexecutestheprogram.Fromthispointofview,t hemeaningofastatementina programcanbeexpressedintermsoftheeectthattheexecut ionofthatstatementhasonthe computer'sstate.Asasimpleexample,themeaningoftheass ignmentstatement\ x=7; "is thatafterthisstatementisexecuted,thevalueofthevaria ble x willbe7.Wecanbeabsolutely <br /> <br /> PAGE 390<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 376 sureofthisfact,soitissomethinguponwhichwecanbuildpa rtofamathematicalproof. Infact,itisoftenpossibletolookataprogramanddeduceth atsomefactmustbetrueat agivenpointduringtheexecutionofaprogram.Forexample, considerthe do loop: do{ TextIO.put("Enterapositiveinteger:");N=TextIO.getlnInt(); }while(N<=0); Afterthisloopends,wecanbeabsolutelysurethatthevalue ofthevariable N isgreaterthan zero.Theloopcannotenduntilthisconditionissatised.T hisfactispartofthemeaningof the while loop.Moregenerally,ifa while loopusesthetest\ while( h condition i ) ",then aftertheloopends,wecanbesurethatthe h condition i isfalse.Wecanthenusethisfactto drawfurtherdeductionsaboutwhathappensastheexecution oftheprogramcontinues.(With aloop,bytheway,wealsohavetoworryaboutthequestionofw hethertheloopwilleverend. Thisissomethingthathastobeveriedseparately.) Afactthatcanbeproventobetrueafteragivenprogramsegme nthasbeenexecuted iscalleda postcondition ofthatprogramsegment.Postconditionsareknownfactsupo n whichwecanbuildfurtherdeductionsaboutthebehavioroft heprogram.Apostcondition ofaprogramasawholeissimplyafactthatcanbeproventobet rueaftertheprogramhas nishedexecuting.Aprogramcanbeproventobecorrectbysh owingthatthepostconditions oftheprogrammeettheprogram'sspecication. Considerthefollowingprogramsegment,whereallthevaria blesareoftype double : disc=B*B-4*A*C;x=(-B+Math.sqrt(disc))/(2*A); Thequadraticformula(fromhigh-schoolmathematics)assu resusthatthevalueassignedto x isasolutionoftheequation A*x 2 +B*x+C=0 ,providedthatthevalueof disc isgreater thanorequaltozeroandthevalueof A isnotzero. If wecanassumeorguaranteethat B*B-4*A*C>=0 andthat A!=0 ,thenthefactthat x isasolutionoftheequationbecomes apostconditionoftheprogramsegment.Wesaythatthecondi tion, B*B-4*A*C>=0 isa precondition oftheprogramsegment.Theconditionthat A!=0 isanotherprecondition.A preconditionisdenedtobeconditionthatmustbetrueatag ivenpointintheexecutionofa programinorderfortheprogramtocontinuecorrectly.Apre conditionissomethingthatyou wanttobetrue.It'ssomethingthatyouhavetocheckorforce tobetrue,ifyouwantyour programtobecorrect. We'veencounteredpreconditionsandpostconditionsonceb efore,in Subsection4.6.1 .That sectionintroducedpreconditionsandpostconditionsasaw ayofspecifyingthecontractof asubroutine.Asthetermsarebeingusedhere,apreconditio nofasubroutineisjusta preconditionofthecodethatmakesupthedenitionofthesu broutine,andthepostcondition ofasubroutineisapostconditionofthesamecode.Inthisse ction,wehavegeneralizedthese termstomakethemmoreusefulintalkingaboutprogramcorre ctness. Let'sseehowthisworksbyconsideringalongerprogramsegm ent: do{ TextIO.putln("EnterA,B,andC.B*B-4*A*Cmustbe>=0.");TextIO.put("A=");A=TextIO.getlnDouble();TextIO.put("B=");B=TextIO.getlnDouble();TextIO.put("C="); <br /> <br /> PAGE 391<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 377 C=TextIO.getlnDouble();if(A==0||B*B-4*A*C<0) TextIO.putln("Yourinputisillegal.Tryagain."); }while(A==0||B*B-4*A*C<0);disc=B*B-4*A*C;x=(-B+Math.sqrt(disc))/(2*A); Aftertheloopends,wecanbesurethat B*B-4*A*C>=0 andthat A!=0 .Thepreconditions forthelasttwolinesarefullled,sothepostconditiontha t x isasolutionoftheequation A*x 2 +B*x+C=0 isalsovalid.Thisprogramsegmentcorrectlyandprovablyc omputesasolution totheequation.(Actually,becauseofproblemswithrepres entingnumbersoncomputers,this isnot100%true.The algorithm iscorrect,butthe program isnotaperfectimplementation ofthealgorithm.Seethediscussionin Subsection8.1.3 .) Hereisanothervariation,inwhichthepreconditionischec kedbyan if statement.Inthe rstpartofthe if statement,whereasolutioniscomputedandprinted,weknow thatthe preconditionsarefullled.Intheotherparts,weknowthat oneofthepreconditionsfailsto hold.Inanycase,theprogramiscorrect. TextIO.putln("EnteryourvaluesforA,B,andC.");TextIO.put("A=");A=TextIO.getlnDouble();TextIO.put("B=");B=TextIO.getlnDouble();TextIO.put("C=");C=TextIO.getlnDouble();if(A!=0&&B*B-4*A*C>=0){ disc=B*B-4*A*C;x=(-B+Math.sqrt(disc))/(2*A);TextIO.putln("AsolutionofA*X*X+B*X+C=0is"+x); }elseif(A==0){ TextIO.putln("ThevalueofAcannotbezero."); }else{ TextIO.putln("SinceB*B-4*A*Cislessthanzero,the");TextIO.putln("equationA*X*X+B*X+C=0hasnosolution.") ; } Wheneveryouwriteaprogram,it'sagoodideatowatchoutfor preconditionsandthink abouthowyourprogramhandlesthem.Often,apreconditionc anoeraclueabouthowto writetheprogram. Forexample,everyarrayreference,suchas A[i] ,hasaprecondition:Theindexmust bewithintherangeoflegalindicesforthearray.For A[i] ,thepreconditionisthat 0<=i <A.length .Thecomputerwillcheckthisconditionwhenitevaluates A[i] ,andifthecondition isnotsatised,theprogramwillbeterminated.Inordertoa voidthis,youneedtomakesure thattheindexhasalegalvalue.(Thereisactuallyanotherp recondition,namelythat A isnot null ,butlet'sleavethatasideforthemoment.)Considerthefol lowingcode,whichsearches forthenumber x inthearray A andsetsthevalueof i tobetheindexofthearrayelement thatcontains x : <br /> <br /> PAGE 392<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 378 i=0;while(A[i]!=x){ i++; } Asthisprogramsegmentstands,ithasaprecondition,namel ythat x isactuallyinthearray. Ifthispreconditionissatised,thentheloopwillendwhen A[i]==x .Thatis,thevalueof i whentheloopendswillbethepositionof x inthearray.However,if x isnotinthearray, thenthevalueof i willjustkeepincreasinguntilitisequalto A.length .Atthattime,the referenceto A[i] isillegalandtheprogramwillbeterminated.Toavoidthis, wecanadda testtomakesurethatthepreconditionforreferringto A[i] issatised: i=0;while( i < A.length &&A[i]!=x){ i++; } Now,theloopwilldenitelyend.Afteritends, i willsatisfy either i==A.length or A[i]==x .An if statementcanbeusedafterthelooptotestwhichofthesecon ditions causedthelooptoend: i=0;while(i<A.length&&A[i]!=x){ i++; }if(i==A.length) System.out.println("xisnotinthearray"); else System.out.println("xisinposition"+i); 8.2.2RobustHandlingofInputOneplacewherecorrectnessandrobustnessareimportant|a ndespeciallydicult|isinthe processingofinputdata,whetherthatdataistypedinbythe user,readfromale,orreceived overanetwork.Filesandnetworkingwillbecoveredin Chapter11 ,whichwillmakeessential useofmaterialthatwillbecoveredinthenexttwosectionso fthischapter.Fornow,let'slook atanexampleofprocessinguserinput. Examplesinthistextbookusemy TextIO classforreadinginputfromtheuser.Thisclass hasbuilt-inerrorhandling.Forexample,thefunction TextIO.getDouble() isguaranteedto returnalegalvalueoftype double .Iftheusertypesanillegalvalue,then TextIO willask theusertore-entertheirresponse;yourprogramneversees theillegalvalue.However,this approachcanbeclumsyandunsatisfactory,especiallywhen theuserisenteringcomplexdata. Inthefollowingexample,I'lldomyownerror-checking. Sometimes,it'susefultobeabletolookaheadatwhat'scomi ngupintheinputwithout actuallyreadingit.Forexample,aprogrammightneedtokno wwhetherthenextitemin theinputisanumberoraword.Forthispurpose,the TextIO classincludesthefunction TextIO.peek() .Thisfunctionreturnsa char whichisthenextcharacterintheuser'sinput, butitdoesnotactuallyreadthatcharacter.Ifthenextthin gintheinputisanend-of-line, then TextIO.peek() returnsthenew-linecharacter, '\n' Often,whatwereallyneedtoknowisthenext non-blank characterintheuser'sinput. Beforewecantestthis,weneedtoskippastanyspaces(andta bs).Hereisafunctionthatdoes <br /> <br /> PAGE 393<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 379 this.Ituses TextIO.peek() tolookahead,anditreadscharactersuntilthenextcharact erinthe inputiseitheranend-of-lineorsomenon-blankcharacter. (Thefunction TextIO.getAnyChar() readsandreturnsthenextcharacterintheuser'sinput,eve nifthatcharacterisaspace.By contrast,themorecommon TextIO.getChar() wouldskipanyblanksandthenreadandreturn thenextnon-blankcharacter.Wecan'tuse TextIO.getChar() heresincetheobjectistoskip theblanks without readingthenextnon-blankcharacter.) /** *Readspastanyblanksandtabsintheinput.*Postcondition:Thenextcharacterintheinputisan*end-of-lineoranon-blankcharacter.*/ staticvoidskipBlanks(){ charch;ch=TextIO.peek();while(ch==''||ch=='\t'){ //Nextcharacterisaspaceortab;readit//andlookatthecharacterthatfollowsit. ch=TextIO.getAnyChar();ch=TextIO.peek(); } }//endskipBlanks() (Infact,thisoperationissocommonthatitisbuiltintothe mostrecentversionof TextIO .The method TextIO.skipBlanks() doesessentiallythesamethingasthe skipBlanks() method presentedhere.) Anexamplein Subsection3.5.3 allowedtheusertoenterlengthmeasurementssuchas\3 miles"or\1foot".Itwouldthenconvertthemeasurementint oinches,feet,yards,andmiles. Butpeoplecommonlyusecombinedmeasurementssuchas\3fee t7inches".Let'simprovethe programsothatitallowsinputsofthisform. Morespecically,theuserwillinputlinescontainingoneo rmoremeasurementssuchas\1 foot"or\3miles20yards2feet".Thelegalunitsofmeasurea reinch,foot,yard,andmile. Theprogramwillalsorecognizeplurals(inches,feet,yard s,miles)andabbreviations(in,ft, yd,mi).Let'swriteasubroutinethatwillreadonelineofin putofthisformandcompute theequivalentnumberofinches.Themainprogramusesthenu mberofinchestocomputethe equivalentnumberoffeet,yards,andmiles.Ifthereisanye rrorintheinput,thesubroutine willprintanerrormessageandreturnthevalue -1 .Thesubroutineassumesthattheinput lineisnotempty.Themainprogramtestsforthisbeforecall ingthesubroutineandusesan emptylineasasignalforendingtheprogram. Ignoringthepossibilityofillegalinputs,apseudocodeal gorithmforthesubroutineis inches=0//Thiswillbethetotalnumberofincheswhilethereismoreinputontheline: readthenumericalmeasurementreadtheunitsofmeasureaddthemeasurementtoinches returninches Wecantestwhetherthereismoreinputonthelinebychecking whetherthenextnon-blank characteristheend-of-linecharacter.Butthistesthasap recondition:Beforewecantestthe nextnon-blankcharacter,wehavetoskipoveranyblanks.So ,thealgorithmbecomes <br /> <br /> PAGE 394<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 380 inches=0skipBlanks()whileTextIO.peek()isnot'\n': readthenumericalmeasurementreadtheunitofmeasureaddthemeasurementtoinchesskipBlanks() returninches Notethecallto skipBlanks() attheendofthe while loop.Thissubroutinemustbeexecuted beforethecomputerreturnstothetestatthebeginningofth eloop.Moregenerally,ifthetest ina while loophasaprecondition,thenyouhavetomakesurethatthisp reconditionholdsat the end ofthewhileloop,beforethecomputerjumpsbacktore-evalu atethetest. Whatabouterrorchecking?Beforereadingthenumericalmea surement,wehavetomake surethatthereisreallyanumbertheretoread.Beforereadi ngtheunitofmeasure,wehaveto testthatthereissomethingtheretoread.(Thenumbermight havebeenthelastthingonthe line.Aninputsuchas\3",withoutaunitofmeasure,isilleg al.)Also,wehavetocheckthat theunitofmeasureisoneofthevalidunits:inches,feet,ya rds,ormiles.Hereisanalgorithm thatincludeserror-checking: inches=0skipBlanks()whileTextIO.peek()isnot'\n': ifthenextcharacterisnotadigit: reportanerrorandreturn-1 Letmeasurement=TextIO.getDouble();skipBlanks()//Preconditionforthenexttest!!ifthenextcharacterisend-of-line: reportanerrorandreturn-1 Letunits=TextIO.getWord()iftheunitsareinches: addmeasurementtoinches elseiftheunitsarefeet: add12*measurementtoinches elseiftheunitsareyards: add36*measurementtoinches elseiftheunitsaremiles: add12*5280*measurementtoinches else reportanerrorandreturn-1 skipBlanks() returninches Asyoucansee,error-testingaddssignicantlytothecompl exityofthealgorithm.Yet thisisstillafairlysimpleexample,anditdoesn'tevenhan dleallthepossibleerrors.For example,iftheuserentersanumericalmeasurementsuchas 1e400 thatisoutsidethelegal rangeofvaluesoftype double ,thentheprogramwillfallbackonthedefaulterror-handli ng in TextIO .Somethingevenmoreinterestinghappensifthemeasuremen tis\1e308miles".The number 1e308 islegal,butthecorrespondingnumberofinchesisoutsidet helegalrangeof <br /> <br /> PAGE 395<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 381 valuesfortype double .Asmentionedintheprevioussection,thecomputerwillget thevalue Double.POSITIVE INFINITY whenitdoesthecomputation. HereisthesubroutinewrittenoutinJava: /** *Readstheuser'sinputmeasurementfromonelineofinput.*Precondition:Theinputlineisnotempty.*Postcondition:Iftheuser'sinputislegal,themeasureme nt *isconvertedtoinchesandreturned.Ifthe*inputisnotlegal,thevalue-1isreturned.*Theend-of-lineisNOTreadbythisroutine.*/ staticdoublereadMeasurement(){ doubleinches;//Totalnumberofinchesinuser'smeasureme nt. doublemeasurement;//Onemeasurement, //suchasthe12in"12miles" Stringunits;//Theunitsspecifiedforthemeasurement, //suchas"miles" charch;//Usedtopeekatnextcharacterintheuser'sinput.inches=0;//Noincheshaveyetbeenread.skipBlanks();ch=TextIO.peek();/*Aslongasthereismoreinputontheline,readameasuremen tand addtheequivalentnumberofinchestothevariable,inches. Ifan errorisdetectedduringtheloop,endthesubroutineimmedi ately byreturning-1.*/ while(ch!='\n'){ /*Getthenextmeasurementandtheunits.Beforereading anything,makesurethatalegalvalueistheretoread.*/ if(!Character.isDigit(ch)){ TextIO.putln( "Error:Expectedtofindanumber,butfound"+ch); return-1; }measurement=TextIO.getDouble();skipBlanks();if(TextIO.peek()=='\n'){ TextIO.putln( "Error:Missingunitofmeasureatendofline."); return-1; }units=TextIO.getWord();units=units.toLowerCase();/*Convertthemeasurementtoinchesandaddittothetotal.* / if(units.equals("inch") ||units.equals("inches")||units.equals("in")){ inches+=measurement; <br /> <br /> PAGE 396<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 382 }elseif(units.equals("foot") ||units.equals("feet")||units.equals("ft")){ inches+=measurement*12; }elseif(units.equals("yard") ||units.equals("yards")||units.equals("yd")){ inches+=measurement*36; }elseif(units.equals("mile") ||units.equals("miles")||units.equals("mi")){ inches+=measurement*12*5280; }else{ TextIO.putln("Error:\""+units +"\"isnotalegalunitofmeasure."); return-1; }/*Lookaheadtoseewhetherthenextthingonthelineis theend-of-line.*/ skipBlanks();ch=TextIO.peek(); }//endwhilereturninches; }//endreadMeasurement() Thesourcecodeforthecompleteprogramcanbefoundinthel e LengthConverter2.java 8.3Exceptionsandtry..catchG ettingaprogramtowork underidealcircumstancesisusuallyaloteasierthanmakin g (online) theprogram robust .Arobustprogramcansurviveunusualor\exceptional"circ umstances withoutcrashing.Oneapproachtowritingrobustprogramsi stoanticipatetheproblemsthat mightariseandtoincludetestsintheprogramforeachpossi bleproblem.Forexample,a programwillcrashifittriestouseanarrayelement A[i] ,when i isnotwithinthedeclared rangeofindicesforthearray A .Arobustprogrammustanticipatethepossibilityofabadin dex andguardagainstit.Onewaytodothisistowritetheprogram inawaythatensuresthat theindexisinthelegalrange.Anotherwayistotestwhether theindexvalueislegalbefore usingitinthearray.Thiscouldbedonewithan if statement: if(i<0||i>=A.length){ ...//Dosomethingtohandletheout-of-rangeindex,i }else{ ...//Processthearrayelement,A[i] } <br /> <br /> PAGE 397<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 383 Therearesomeproblemswiththisapproach.Itisdicultand sometimesimpossibletoanticipateallthepossiblethingsthatmightgowrong.It'sno talwaysclearwhattodowhenan errorisdetected.Furthermore,tryingtoanticipateallth epossibleproblemscanturnwhat wouldotherwisebeastraightforwardprogramintoamessyta ngleof if statements. 8.3.1ExceptionsandExceptionClassesWehavealreadyseenthatJava(likeitscousin,C++)provide saneater,morestructured alternativemethodfordealingwitherrorsthatcanoccurwh ileaprogramisrunning.The methodisreferredtoas exceptionhandling .Theword\exception"ismeanttobemore generalthan\error."Itincludesanycircumstancethatari sesastheprogramisexecutedwhich ismeanttobetreatedasanexceptiontothenormalrowofcont roloftheprogram.An exceptionmightbeanerror,oritmightjustbeaspecialcase thatyouwouldrathernothave clutterupyourelegantalgorithm. Whenanexceptionoccursduringtheexecutionofaprogram,w esaythattheexception is thrown .Whenthishappens,thenormalrowoftheprogramisthrowno -track,andthe programisindangerofcrashing.However,thecrashcanbeav oidediftheexceptionis caught andhandledinsomeway.Anexceptioncanbethrowninonepart ofaprogramandcaught inadierentpart.Anexceptionthatisnotcaughtwillgener allycausetheprogramtocrash. (Moreexactly,thethreadthatthrowstheexceptionwillcra sh.Inamultithreadedprogram, itispossibleforotherthreadstocontinueevenafteronecr ashes.Wewillcoverthreadsin Section8.5 .Inparticular,GUIprogramsaremultithreaded,andpartso ftheprogrammight continuetofunctionevenwhileotherpartsarenon-functio nalbecauseofexceptions.) Bytheway,sinceJavaprogramsareexecutedbyaJavainterpr eter,havingaprogram crashsimplymeansthatitterminatesabnormallyandpremat urely.Itdoesn'tmeanthat theJavainterpreterwillcrash.Ineect,theinterpreterc atchesanyexceptionsthatarenot caughtbytheprogram.Theinterpreterrespondsbyterminat ingtheprogram.Inmanyother programminglanguages,acrashedprogramwillsometimescr ashtheentiresystemandfreeze thecomputeruntilitisrestarted.WithJava,suchsystemcr ashesshouldbeimpossible|which meansthatwhentheyhappen,youhavethesatisfactionofbla mingthesystemratherthan yourownprogram. Exceptionswereintroducedin Section3.7 ,alongwiththe try..catch statement,whichis usedtocatchandhandleexceptions.However,thatsectiond idnotcoverthecompletesyntax of try..catch orthefullcomplexityofexceptions.Inthissection,wecov erthesetopicsinfull detail. Whenanexceptionoccurs,thethingthatisactually\thrown "isanobject.Thisobject cancarryinformation(initsinstancevariables)fromthep ointwheretheexceptionoccursto thepointwhereitiscaughtandhandled.Thisinformational waysincludesthe subroutine callstack ,whichisalistofthesubroutinesthatwerebeingexecutedw hentheexceptionwas thrown.(Sinceonesubroutinecancallanother,severalsub routinescanbeactiveatthesame time.)Typically,anexceptionobjectalsoincludesanerro rmessagedescribingwhathappened tocausetheexception,anditcancontainotherdataaswell. Allexceptionobjectsmustbelong toasubclassofthestandardclass java.lang.Throwable .Ingeneral,eachdierenttypeof exceptionisrepresentedbyitsownsubclassof Throwable ,andthesesubclassesarearrangedin afairlycomplexclasshierarchythatshowstherelationshi pamongvarioustypesofexception. Throwable hastwodirectsubclasses, Error and Exception .Thesetwosubclassesinturnhave <br /> <br /> PAGE 398<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 384 manyotherpredenedsubclasses.Inaddition,aprogrammer cancreatenewexceptionclasses torepresentnewtypesofexception. Mostofthesubclassesoftheclass Error representseriouserrorswithintheJavavirtual machinethatshouldordinarilycauseprogramterminationb ecausethereisnoreasonableway tohandlethem.Ingeneral,youshouldnottrytocatchandhan dlesucherrors.Anexampleis a ClassFormatError ,whichoccurswhentheJavavirtualmachinendssomekindof illegaldata inalethatissupposedtocontainacompiledJavaclass.Ift hatclasswasbeingloadedas partoftheprogram,thenthereisreallynowayfortheprogra mtoproceed. Ontheotherhand,subclassesoftheclass Exception representexceptionsthataremeant tobecaught.Inmanycases,theseareexceptionsthatmightn aturallybecalled\errors,"but theyareerrorsintheprogramorininputdatathataprogramm ercananticipateandpossibly respondtoinsomereasonableway.(However,youshouldavoi dthetemptationofsaying,\Well, I'lljustputathingheretocatchalltheerrorsthatmightoc cur,somyprogramwon'tcrash." Ifyoudon'thaveareasonablewaytorespondtotheerror,it' sbestjusttolettheprogram crash,becausetryingtogoonwillprobablyonlyleadtowors ethingsdowntheroad|inthe worstcase,aprogramthatgivesanincorrectanswerwithout givingyouanyindicationthat theanswermightbewrong!) Theclass Exception hasitsownsubclass, RuntimeException .Thisclassgroupstogether manycommonexceptions,includingallthosethathavebeenc overedinprevioussections.For example, IllegalArgumentException and NullPointerException aresubclassesof RuntimeException A RuntimeException generallyindicatesabugintheprogram,whichtheprogramm ershould x. RuntimeExceptions and Errors sharethepropertythataprogramcansimplyignorethe possibilitythattheymightoccur.(\Ignoring"heremeanst hatyouarecontenttoletyour programcrashiftheexceptionoccurs.)Forexample,aprogr amdoesthiseverytimeituses anarrayreferencelike A[i] withoutmakingarrangementstocatchapossible ArrayIndexOutOfBoundsException .Forallotherexceptionclassesbesides Error RuntimeException ,andtheir subclasses,exception-handlingis\mandatory"inasenset hatI'lldiscussbelow. Thefollowingdiagramisaclasshierarchyshowingtheclass Throwable andjustafewof itssubclasses.Classesthatrequiremandatoryexceptionhandlingareshowninitalic: : ; < = > ? @ A B C D E F G H I J K L M C D E F G H I J K L K H F N N O G H F P C D E F G H I J K Q J E R F H C D E F G H I J K C M S C D E F G H I J K T < < = < U V W X Y Z B T [ \ B ] X Y = W ^ < < ? ` W a B [ b V X b c d = V W a e T [ \ B ] X Y = W ` A A B f ? A ^ < f V Z B W X T [ \ B ] X Y = W g V Z @ B < c h = < Z ? X T [ \ B ] X Y = W i j k l m n o o p i j q r s n t m k p n u v o r w k r x y z o o { t l m n o o k o | Theclass Throwable includesseveralinstancemethodsthatcanbeusedwithanye xception object.If e isoftype Throwable (oroneofitssubclasses),then e.getMessage() isafunction <br /> <br /> PAGE 399<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 385 thatreturnsa String thatdescribestheexception.Thefunction e.toString() ,whichisused bythesystemwheneveritneedsastringrepresentationofth eobject,returnsa String that containsthenameoftheclasstowhichtheexceptionbelongs aswellasthesamestringthat wouldbereturnedby e.getMessage() .And e.printStackTrace() writesastacktraceto standardoutputthattellswhichsubroutineswereactivewh entheexceptionoccurred.Astack tracecanbeveryusefulwhenyouaretryingtodeterminethec auseoftheproblem.(Notethat ifanexceptionis not caughtbytheprogram,thenthesystemautomaticallyprints thestack tracetostandardoutput.)8.3.2ThetryStatementTocatchexceptionsinaJavaprogram,youneeda try statement.Wehavebeenusingsuch statementssince Section3.7 ,butthefullsyntaxofthe try statementismorecomplicatedthan whatwaspresentedthere.The try statementsthatwehaveusedsofarhadasyntaxsimilar tothefollowingexample: try{ doubledeterminant=M[0][0]*M[1][1]-M[0][1]*M[1][0];System.out.println("ThedeterminantofMis"+determinan t); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.println("Misthewrongsizetohaveadetermina nt."); e.printStackTrace(); } Here,thecomputertriestoexecutetheblockofstatementsf ollowingtheword\ try ".Ifno exceptionoccursduringtheexecutionofthisblock,thenth e\ catch "partofthestatement issimplyignored.However,ifanexceptionoftype ArrayIndexOutOfBoundsException occurs, thenthecomputerjumpsimmediatelytothe catch clauseofthe try statement.Thisblock ofstatementsissaidtobean exceptionhandler for ArrayIndexOutOfBoundsException .By handlingtheexceptioninthisway,youpreventitfromcrash ingtheprogram.Beforethebody ofthe catch clauseisexecuted,theobjectthatrepresentstheexceptio nisassignedtothe variable e ,whichisusedinthisexampletoprintastacktrace. However,thefullsyntaxofthe try statementallowsmorethanone catch clause.This makesitpossibletocatchseveraldierenttypesofexcepti onwithone try statement.Inthe aboveexample,inadditiontothepossible ArrayIndexOutOfBoundsException ,thereisapossible NullPointerException whichwilloccurifthevalueof M is null .Wecanhandlebothpossible exceptionsbyaddingasecond catch clausetothe try statement: try{ doubledeterminant=M[0][0]*M[1][1]-M[0][1]*M[1][0];System.out.println("ThedeterminantofMis"+determinan t); }catch(ArrayIndexOutOfBoundsExceptione){ System.out.println("Misthewrongsizetohaveadetermina nt."); }catch(NullPointerExceptione){ System.out.print("Programmingerror!Mdoesn'texist."+ ); } Here,thecomputertriestoexecutethestatementsinthe try clause.Ifnoerroroccurs,both ofthe catch clausesareskipped.Ifan ArrayIndexOutOfBoundsException occurs,thecomputer <br /> <br /> PAGE 400<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 386 executesthebodyoftherst catch clauseandskipsthesecondone.Ifa NullPointerException occurs,itjumpstothesecond catch clauseandexecutesthat. Notethatboth ArrayIndexOutOfBoundsException and NullPointerException aresubclassesof RuntimeException .It'spossibletocatchall RuntimeExceptions withasingle catch clause.For example: try{ doubledeterminant=M[0][0]*M[1][1]-M[0][1]*M[1][0];System.out.println("ThedeterminantofMis"+determinan t); }catch(RuntimeExceptionerr){ System.out.println("Sorry,anerrorhasoccurred.");System.out.println("Theerrorwas:"+err); } The catch clauseinthis try statementwillcatchanyexceptionbelongingtoclass RuntimeException ortoanyofitssubclasses.Thisshowswhyexceptionclasses areorganizedintoaclass hierarchy.Itallowsyoutheoptionofcastingyournetnarro wlytocatchonlyaspecictype ofexception.Oryoucancastyournetwidelytocatchawidecl assofexceptions.Because ofsubclassing,whentherearemultiple catch clausesina try statement,itispossiblethata givenexceptionmightmatchseveralofthose catch clauses.Forexample,anexceptionoftype NullPointerException wouldmatch catch clausesfor NullPointerException RuntimeException Exception ,or Throwable .Inthiscase,onlythe rst catch clausethatmatchestheexception isexecuted. TheexampleI'vegivenhereisnotparticularlyrealistic.Y ouarenotverylikelytouse exception-handlingtoguardagainstnullpointersandbada rrayindices.Thisisacasewhere carefulprogrammingisbetterthanexceptionhandling:Jus tbesurethatyourprogramassigns areasonable,nonnull valuetothearray M .Youwouldcertainlyresentitifthedesignersof Javaforcedyoutosetupa try..catch statementeverytimeyouwantedtouseanarray! Thisiswhyhandlingofpotential RuntimeExceptions isnotmandatory.Therearejusttoo manythingsthatmightgowrong!(Thisalsoshowsthatexcept ion-handlingdoesnotsolve theproblemofprogramrobustness.Itjustgivesyouatoolth atwillinmanycasesletyou approachtheprobleminamoreorganizedway.) Ihavestillnotcompletelyspeciedthesyntaxofthe try statement.Thereisoneadditional element:thepossibilityofa nallyclause attheendofa try statement.Thecompletesyntax ofthe try statementcanbedescribedas: try{ h statements i }h optional-catch-clauses i h optional-finally-clause i Notethatthe catch clausesarealsolistedasoptional.The try statementcanincludezeroor more catch clausesand,optionally,a finally clause.The try statement must includeone ortheother.Thatis,a try statementcanhaveeithera finally clause,oroneormore catch clauses,orboth.Thesyntaxfora catch clauseis catch( h exception-class-name ih variable-name i ){ h statements i } <br /> <br /> PAGE 401<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 387 andthesyntaxfora finally clauseis finally{ h statements i } Thesemanticsofthe finally clauseisthattheblockofstatementsinthe finally clauseis guaranteedtobeexecutedasthelaststepintheexecutionof thetrystatement,whetherornot anyexceptionoccursandwhetherornotanyexceptionthatdo esoccuriscaughtandhandled. The finally clauseismeantfordoingessentialcleanupthatundernocir cumstancesshould beomitted.Oneexampleofthistypeofcleanupisclosingane tworkconnection.Although youdon'tyetknowenoughaboutnetworkingtolookattheactu alprogramminginthiscase, wecanconsidersomepseudocode: try{ openanetworkconnection }catch(IOExceptione){ reporttheerrorreturn//Don'tcontinueifconnectioncan'tbeopened! }//Atthispoint,weKNOWthattheconnectionisopen.try{ communicateovertheconnection }catch(IOExceptione){ handletheerror }finally{ closetheconnection } The finally clauseinthesecond try statementensuresthatthenetworkconnectionwill denitelybeclosed,whetherornotanerroroccursduringth ecommunication.Therst try statementistheretomakesurethatwedon'teventrytocommu nicateoverthenetworkunless wehavesuccessfullyopenedaconnection.Thepseudocodein thisexamplefollowsageneral patternthatcanbeusedtorobustlyobtainaresource,useth eresource,andthenreleasethe resource.8.3.3ThrowingExceptionsTherearetimeswhenitmakessenseforaprogramtodeliberat elythrowanexception.This isthecasewhentheprogramdiscoverssomesortofexception alorerrorcondition,butthere isnoreasonablewaytohandletheerroratthepointwherethe problemisdiscovered.The programcanthrowanexceptioninthehopethatsomeotherpar toftheprogramwillcatch andhandletheexception.Thiscanbedonewitha throwstatement .Youhavealreadyseen anexampleofthisin Subsection4.3.5 .Inthissection,wecoverthe throw statementmore fully.Thesyntaxofthe throw statementis: throw h exception-object i ; <br /> <br /> PAGE 402<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 388 The h exception-object i mustbeanobjectbelongingtooneofthesubclassesof Throwable Usually,itwillinfactbelongtooneofthesubclassesof Exception .Inmostcases,itwillbea newlyconstructedobjectcreatedwiththe new operator.Forexample: thrownewArithmeticException("Divisionbyzero"); Theparameterintheconstructorbecomestheerrormessagei ntheexceptionobject;if e referstotheobject,theerrormessagecanberetrievedbyca lling e.getMessage() .(You mightndthisexampleabitodd,becauseyoumightexpectthe systemitselftothrowan ArithmeticException whenanattemptismadetodividebyzero.Sowhyshouldaprogr ammer bothertothrowtheexception?Recallthatifthenumberstha tarebeingdividedareoftype int ,thendivisionbyzerowillindeedthrowan ArithmeticException .However,noarithmetic operationswithroating-pointnumberswilleverproducean exception.Instead,thespecial value Double.NaN isusedtorepresenttheresultofanillegaloperation.Inso mesituations,you mightprefertothrowan ArithmeticException whenarealnumberisdividedbyzero.) Anexceptioncanbethrowneitherbythesystemorbya throw statement.Theexception isprocessedinexactlythesamewayineithercase.Supposet hattheexceptionisthrown insidea try statement.Ifthat try statementhasa catch clausethathandlesthattypeof exception,thenthecomputerjumpstothe catch clauseandexecutesit.Theexceptionhas been handled .Afterhandlingtheexception,thecomputerexecutesthe finally clauseof the try statement,ifthereisone.Itthencontinuesnormallywitht herestoftheprogram, whichfollowsthe try statement.Iftheexceptionisnotimmediatelycaughtandha ndled,the processingoftheexceptionwillcontinue. Whenanexceptionisthrownduringtheexecutionofasubrout ineandtheexceptionis nothandledinthesamesubroutine,thenthatsubroutineist erminated(aftertheexecution ofanypending finally clauses).Thentheroutinethatcalledthatsubroutinegets achance tohandletheexception.Thatis,ifthesubroutinewascalle dinsidea try statementthathas anappropriate catch clause,then that catch clausewillbeexecutedandtheprogramwill continueonnormallyfromthere.Again,ifthesecondroutin edoesnothandletheexception, thenitalsoisterminatedandtheroutinethatcalled it (ifany)getsthenextshotatthe exception.Theexceptionwillcrashtheprogramonlyifitpa ssesupthroughtheentirechainof subroutinecallswithoutbeinghandled.(Infact,eventhis isnotquitetrue:Inamultithreaded program,onlythethreadinwhichtheexceptionoccurredist erminated.) Asubroutinethatmightgenerateanexceptioncanannouncet hisfactbyaddingaclause \ throws h exception-class-name i "totheheaderoftheroutine.Forexample: /** *Returnsthelargerofthetworootsofthequadraticequatio n *A*x*x+B*x+C=0,providedithasanyroots.IfA==0or*ifthediscriminant,B*B-4*A*C,isnegative,thenanexcep tion *oftypeIllegalArgumentExceptionisthrown.*/ staticpublicdoubleroot(doubleA,doubleB,doubleC) throwsIllegalArgumentException { if(A==0){ thrownewIllegalArgumentException("Acan'tbezero."); }else{ doubledisc=B*B-4*A*C;if(disc<0) thrownewIllegalArgumentException("Discriminant<zero ."); <br /> <br /> PAGE 403<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 389 return(-B+Math.sqrt(disc))/(2*A); } } Asdiscussedintheprevioussection,thecomputationinthi ssubroutinehasthepreconditionsthat A!=0 and B*B-4*A*C>=0 .Thesubroutinethrowsanexceptionoftype IllegalArgumentException wheneitherofthesepreconditionsisviolated.Whenanille galcondition isfoundinasubroutine,throwinganexceptionisoftenarea sonableresponse.Iftheprogram thatcalledthesubroutineknowssomegoodwaytohandlethee rror,itcancatchtheexception. Ifnot,theprogramwillcrash|andtheprogrammerwillknowt hattheprogramneedstobe xed. A throws clauseinasubroutineheadingcandeclareseveraldierent typesofexception, separatedbycommas.Forexample: voidprocessArray(int[]A)throwsNullPointerException, ArrayIndexOutOfBoundsException{... 8.3.4MandatoryExceptionHandlingIntheprecedingexample,declaringthatthesubroutine root() canthrowan IllegalArgumentException isjustacourtesytopotentialreadersofthisroutine.This isbecausehandlingof IllegalArgumentExceptions isnot\mandatory."Aroutinecanthrowan IllegalArgumentException withoutannouncingthepossibility.Andaprogramthatcall sthatroutineisfreeeithertocatch ortoignoretheexception,justasaprogrammercanchooseei thertocatchortoignorean exceptionoftype NullPointerException Forthoseexceptionclassesthatrequiremandatoryhandlin g,thesituationisdierent.Ifa subroutinecanthrowsuchanexception,thatfact must beannouncedina throws clausein theroutinedenition.Failingtodosoisasyntaxerrorthat willbereportedbythecompiler. Ontheotherhand,supposethatsomestatementinthebodyofa subroutinecangenerate anexceptionofatypethatrequiresmandatoryhandling.The statementcouldbea throw statement,whichthrowstheexceptiondirectly,oritcould beacalltoasubroutinethatcan throwtheexception.Ineithercase,theexception must behandled.Thiscanbedoneinone oftwoways:Therstwayistoplacethestatementina try statementthathasa catch clause thathandlestheexception;inthiscase,theexceptionisha ndledwithinthesubroutine,sothat anycallerofthesubroutinewillneverseetheexception.Th esecondwayistodeclarethatthe subroutinecanthrowtheexception.Thisisdonebyaddinga\ throws "clausetothesubroutine heading,whichalertsanycallerstothepossibilitythatan exceptionmightbegeneratedwhen thesubroutineisexecuted.Thecallerwill,inturn,beforc edeithertohandletheexceptionin a try statementortodeclaretheexceptionina throws clauseinitsownheader. Exception-handlingismandatoryforanyexceptionclassth atisnotasubclassofeither Error or RuntimeException .Exceptionsthatrequiremandatoryhandlinggenerallyrep resent conditionsthatareoutsidethecontroloftheprogrammer.F orexample,theymightrepresent badinputoranillegalactiontakenbytheuser.Thereisnowa yto avoid sucherrors,soa robustprogramhastobepreparedtohandlethem.Thedesigno fJavamakesitimpossiblefor programmerstoignorethepossibilityofsucherrors. Amongtheexceptionsthatrequiremandatoryhandlingarese veralthatcanoccurwhen usingJava'sinput/outputroutines.Thismeansthatyoucan 'tevenusetheseroutinesunless youunderstandsomethingaboutexception-handling. Chapter11 dealswithinput/outputand usesmandatoryexception-handlingextensively. <br /> <br /> PAGE 404<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 390 8.3.5ProgrammingwithExceptionsExceptionscanbeusedtohelpwriterobustprograms.Theypr ovideanorganizedandstructuredapproachtorobustness.Withoutexceptions,aprogra mcanbecomeclutteredwith if statementsthattestforvariouspossibleerrorconditions .Withexceptions,itbecomespossible towriteacleanimplementationofanalgorithmthatwillhan dleallthenormalcases.The exceptionalcasescanbehandledelsewhere,ina catch clauseofa try statement. Whenaprogramencountersanexceptionalconditionandhasn owayofhandlingitimmediately,theprogramcanthrowanexception.Insomecases ,itmakessensetothrowan exceptionbelongingtooneofJava'spredenedclasses,suc has IllegalArgumentException or IOException .However,ifthereisnostandardclassthatadequatelyrepr esentstheexceptional condition,theprogrammercandeneanewexceptionclass.T henewclassmustextendthe standardclass Throwable oroneofitssubclasses.Ingeneral,iftheprogrammerdoes not want torequiremandatoryexceptionhandling,thenewclasswill extend RuntimeException (orone ofitssubclasses).Tocreateanewexceptionclassthat does requiremandatoryhandling,the programmercanextendoneoftheothersubclassesof Exception orcanextend Exception itself. Here,forexample,isaclassthatextends Exception ,andthereforerequiresmandatory exceptionhandlingwhenitisused: publicclassParseErrorextendsException{ publicParseError(Stringmessage){ //CreateaParseErrorobjectcontaining//thegivenmessageasitserrormessage. super(message); } } Theclasscontainsonlyaconstructorthatmakesitpossible tocreatea ParseError object containingagivenerrormessage.(Thestatement\ super(message) "callsaconstructorinthe superclass, Exception .See Subsection5.6.3 .)Ofcoursetheclassinheritsthe getMessage() and printStackTrace() routinesfromitssuperclass.If e referstoanobjectoftype ParseError thenthefunctioncall e.getMessage() willretrievetheerrormessagethatwasspeciedinthe constructor.Butthemainpointofthe ParseError classissimplytoexist.Whenanobjectof type ParseError isthrown,itindicatesthatacertaintypeoferrorhasoccur red.( Parsing ,by theway,referstoguringoutthesyntaxofastring.A ParseError wouldindicate,presumably, thatsomestringthatisbeingprocessedbytheprogramdoesn othavetheexpectedform.) A throw statementcanbeusedinaprogramtothrowanerroroftype ParseError .The constructorforthe ParseError objectmustspecifyanerrormessage.Forexample: thrownewParseError("Encounteredanillegalnegativenum ber."); or thrownewParseError("Theword'"+word +"'isnotavalidfilename."); Ifthe throw statementdoesnotoccurina try statementthatcatchestheerror,thenthe subroutinethatcontainsthe throw statementmustdeclarethatitcanthrowa ParseError by addingtheclause\ throwsParseError "tothesubroutineheading.Forexample, voidgetUserData()throwsParseError{ ... } <br /> <br /> PAGE 405<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 391 Thiswouldnotberequiredif ParseError weredenedasasubclassof RuntimeException instead of Exception ,sinceinthatcaseexceptionhandlingfor ParseErrors wouldnotbemandatory. Aroutinethatwantstohandle ParseErrors canusea try statementwitha catch clause thatcatches ParseErrors .Forexample: try{ getUserData();processUserData(); }catch(ParseErrorpe){ ...//Handletheerror } Notethatsince ParseError isasubclassof Exception ,a catch clauseoftheform\ catch (Exceptione) "wouldalsocatch ParseErrors ,alongwithanyotherobjectoftype Exception Sometimes,it'susefultostoreextradatainanexceptionob ject.Forexample, classShipDestroyedextendsRuntimeException{ Shipship;//Whichshipwasdestroyed.intwhere x,where y;//Locationwhereshipwasdestroyed. ShipDestroyed(Stringmessage,Ships,intx,inty){ //ConstructorcreatesaShipDestroyedobject//carryinganerrormessageplustheinformation//thattheshipswasdestroyedatlocation(x,y)//onthescreen. super(message);ship=s;where x=x; where y=y; } } Here,a ShipDestroyed objectcontainsanerrormessageandsomeinformationabout ashipthat wasdestroyed.Thiscouldbeused,forexample,inastatemen t: if(userShip.isHit()) thrownewShipDestroyed("You'vebeenhit!",userShip,xPo s,yPos); Notethattheconditionrepresentedbya ShipDestroyed objectmightnotevenbeconsidered anerror.Itcouldbejustanexpectedinterruptiontothenor malrowofagame.Exceptions cansometimesbeusedtohandlesuchinterruptionsneatly. Theabilitytothrowexceptionsisparticularlyusefulinwr itinggeneral-purposesubroutines andclassesthataremeanttobeusedinmorethanoneprogram. Inthiscase,thepersonwriting thesubroutineorclassoftenhasnoreasonablewayofhandli ngtheerror,sincethatpersonhas nowayofknowingexactlyhowthesubroutineorclasswillbeu sed.Insuchcircumstances, anoviceprogrammerisoftentemptedtoprintanerrormessag eandforgeahead,butthisis almostneversatisfactorysinceitcanleadtounpredictabl eresultsdowntheline.Printingan errormessageandterminatingtheprogramisalmostasbad,s inceitgivestheprogramno chancetohandletheerror. Theprogramthatcallsthesubroutineorusestheclassneeds toknowthattheerrorhas occurred.Inlanguagesthatdonotsupportexceptions,theo nlyalternativeistoreturnsome specialvalueortosetthevalueofsomevariabletoindicate thatanerrorhasoccurred.For <br /> <br /> PAGE 406<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 392 example,the readMeasurement() functionin Subsection8.2.2 returnsthevalue -1 iftheuser's inputisillegal.However,thisonlydoesanygoodifthemain programbotherstotestthe returnvalue.Itisveryeasytobelazyaboutcheckingforspe cialreturnvalueseverytimea subroutineiscalled.Andinthiscase,using -1 asasignalthatanerrorhasoccurredmakesit impossibletoallownegativemeasurements.Exceptionsare acleanerwayforasubroutineto reactwhenitencountersanerror. Itiseasytomodifythe readMeasurement() subroutinetouseexceptionsinsteadofa specialreturnvaluetosignalanerror.Mymodiedsubrouti nethrowsa ParseError whenthe user'sinputisillegal,where ParseError isthesubclassof Exception thatwasdenedabove. (Arguably,itmightbereasonabletoavoiddeninganewclas sbyusingthestandardexception class IllegalArgumentException instead.)Thechangesfromtheoriginalversionareshownin italic: /** *Readstheuser'sinputmeasurementfromonelineofinput.*Precondition:Theinputlineisnotempty.*Postcondition:Iftheuser'sinputislegal,themeasureme nt *isconvertedtoinchesandreturned.*@throwsParseErroriftheuser'sinputisnotlegal.*/ staticdoublereadMeasurement() throwsParseError { doubleinches;//Totalnumberofinchesinuser'smeasureme nt. doublemeasurement;//Onemeasurement, //suchasthe12in"12miles." Stringunits;//Theunitsspecifiedforthemeasurement, //suchas"miles." charch;//Usedtopeekatnextcharacterintheuser'sinput.inches=0;//Noincheshaveyetbeenread.skipBlanks();ch=TextIO.peek();/*Aslongasthereismoreinputontheline,readameasuremen tand addtheequivalentnumberofinchestothevariable,inches. Ifan errorisdetectedduringtheloop,endthesubroutineimmedi ately by throwingaParseError. */ while(ch!='\n'){ /*Getthenextmeasurementandtheunits.Beforereading anything,makesurethatalegalvalueistheretoread.*/ if(!Character.isDigit(ch)){ thrownewParseError("Expectedtofindanumber,butfound" +ch); }measurement=TextIO.getDouble();skipBlanks();if(TextIO.peek()=='\n'){ thrownewParseError("Missingunitofmeasureatendofline ."); }units=TextIO.getWord();units=units.toLowerCase(); <br /> <br /> PAGE 407<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 393 /*Convertthemeasurementtoinchesandaddittothetotal.* / if(units.equals("inch") ||units.equals("inches")||units.equals("in")){ inches+=measurement; }elseif(units.equals("foot") ||units.equals("feet")||units.equals("ft")){ inches+=measurement*12; }elseif(units.equals("yard") ||units.equals("yards")||units.equals("yd")){ inches+=measurement*36; }elseif(units.equals("mile") ||units.equals("miles")||units.equals("mi")){ inches+=measurement*12*5280; }else{ thrownewParseError("\""+units +"\"isnotalegalunitofmeasure."); }/*Lookaheadtoseewhetherthenextthingonthelineis theend-of-line.*/ skipBlanks();ch=TextIO.peek(); }//endwhilereturninches; }//endreadMeasurement() Inthemainprogram,thissubroutineiscalledina try statementoftheform try{ inches=readMeasurement(); }catch(ParseErrore){ ...//Handletheerror. } Thecompleteprogramcanbefoundinthele LengthConverter3.java .Fromtheuser's pointofview,thisprogramhasexactlythesamebehaviorast heprogram LengthConverter2 fromtheprevioussection.Internally,however,theprogra msaresignicantlydierent,since LengthConverter3usesexception-handling.8.4AssertionsI nthisshortsection ,welookat assertions ,anotherfeatureoftheJavaprogramming (online) languagethatcanbeusedtoaidinthedevelopmentofcorrect androbustprograms. Recallthatapreconditionisaconditionthatmustbetrueat acertainpointinaprogram, fortheexecutionoftheprogramtocontinuecorrectlyfromt hatpoint.Inthecasewhere <br /> <br /> PAGE 408<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 394 thereisachancethatthepreconditionmightnotbesatised |forexample,ifitdependson inputfromtheuser|thenit'sagoodideatoinsertan if statementtotestit.Butthenthe questionarises,Whatshouldbedoneifthepreconditiondoe snothold?Oneoptionistothrow anexception.Thiswillterminatetheprogram,unlesstheex ceptioniscaughtandhandled elsewhereintheprogram. Inmanycases,ofcourse,insteadofusingan if statementto test whetheraprecondition holds,aprogrammertriestowritetheprograminawaythatwi ll guarantee thatthepreconditionholds.Inthatcase,thetestshouldnotbenecessary,an dthe if statementcanbeavoided. Theproblemisthatprogrammersarenotperfect.Inspiteoft heprogrammer'sintention,the programmightcontainabugthatscrewsuptheprecondition. Somaybeit'sagoodideato checktheprecondition|atleastduringthedebuggingphase ofprogramdevelopment. Similarly,apostconditionisaconditionthatistrueatace rtainpointintheprogramas aconsequenceofthecodethathasbeenexecutedbeforethatp oint.Assumingthatthecode iscorrectlywritten,apostconditionisguaranteedtobetr ue,buthereagaintestingwhethera desiredpostconditionis actually trueisawayofcheckingforabugthatmighthavescrewed upthepostcondition.Thisissomthingthatmightbedesirab leduringdebugging. TheprogramminglanguagesCandC++havealwayshadafacilit yforaddingwhatare called assertions toaprogram.Theseassertionstaketheform\ assert( h condition i ) ",where h condition i isa boolean -valuedexpression.Thisconditionexpressesapreconditi onorpostconditionthatshouldholdatthatpointintheprogram.When thecomputerencountersan assertionduringtheexecutionoftheprogram,itevaluates thecondition.Iftheconditionis false,theprogramisterminated.Otherwise,theprogramco ntinuesnormally.Thisallowsthe programmer'sbeliefthattheconditionistruetobetested; ififitnottrue,thatindicatesthat thepartoftheprogramthatprecededtheassertioncontaine dabug.OnenicethingaboutassertionsinCandC++isthattheycanbe\turnedo"atcompile time.Thatis,iftheprogram iscompiledinoneway,thentheassertionsareincludedinth ecompiledcode.Iftheprogram iscompiledinanotherway,theassertionsarenotincluded. Duringdebugging,thersttypeof compilationisused.Thereleaseversionoftheprogramisco mpiledwithassertionsturnedo. Thereleaseversionwillbemoreecient,becausethecomput erwon'thavetoevaluateallthe assertions. AlthoughearlyversionsofJavadidnothaveassertions,ana ssertionfacilitysimilartothe oneinC/C++hasbeenavailableinJavasinceversion1.4.Asw iththeC/C++version,Java assertionscanbeturnedonduringdebuggingandturnedodu ringnormalexecution.InJava, however,assertionsareturnedonandoatruntimeratherth anatcompiletime.Anassertion intheJavasourcecodeisalwaysincludedinthecompiledcla ssle.Whentheprogramis runinthenormalway,theseassertionsareignored;sinceth econditionintheassertionisnot evaluatedinthiscase,thereislittleornoperformancepen altyforhavingtheassertionsin theprogram.Whentheprogramisbeingdebugged,itcanberun withassertionsenabled,as discussedbelow,andthentheassertionscanbeagreathelpi nlocatingandidentifyingbugs. An assertionstatement inJavatakesoneofthefollowingtwoforms: assert h condition i ; or assert h condition i : h error-message i ; where h condition i isa boolean -valuedexpressionand h error-message i isastringoranexpressionoftype String .Theword\ assert "isareservedwordinJava,whichcannotbeusedasan <br /> <br /> PAGE 409<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 395 identier.AnassertionstatementcanbeusedanyplaceinJa vawhereastatementislegal. Ifaprogramisrunwithassertionsdisabled,anassertionst atementisequivalenttoan emptystatementandhasnoeect.Whenassertionsareenable dandanassertionstatementis encounteredintheprogram,the h condition i intheassertionisevaluated.Ifthevalueis true theprogramproceedsnormally.Ifthevalueofthecondition is false ,thenanexceptionof type java.lang.AssertionError isthrown,andtheprogramwillcrash(unlesstheerroris caughtbya try statement).Ifthe assert statementincludesan h error-message i ,thenthe errormessagestringbecomesthemessageinthe AssertionError So,thestatement\ assert h condition i : h error-message i ;" issimilarto if( h condition i ==false) thrownewAssertionError( h error-message i ); exceptthatthe if statementisexecutedwhenevertheprogramisrun,andthe assert statementisexecutedonlywhentheprogramisrunwithassertions enabled. Thequestionis,whentouseassertionsinsteadofexception s?Thegeneralruleistouse assertionstotestconditionsthatshoulddenitelybetrue ,iftheprogramiswrittencorrectly. Assertionsareusefulfortestingaprogramtoseewhetheror notitiscorrectandfornding theerrorsinanincorrectprogram.Aftertestinganddebugg ing,whentheprogramisusedin thenormalway,theassertionsintheprogramwillbeignored .However,ifaproblemturns uplater,theassertionsarestillthereintheprogramtobeu sedtohelplocatetheerror.If someonewritestoyoutosaythatyourprogramdoesn'tworkwh enhedoessuch-and-such,you canruntheprogramwithassertionsenabled,dosuch-and-su ch,andhopethattheassertions intheprogramwillhelpyoulocatethepointintheprogramwh ereitgoeswrong. Consider,forexample,the root() methodfrom Subsection8.3.3 thatcalculatesarootof aquadraticequation.Ifyoubelievethatyourprogramwilla lwayscallthismethodwithlegal arguments,thenitwouldmakesensetowritethemethodusing assertionsinsteadofexceptions: /** *Returnsthelargerofthetworootsofthequadraticequatio n *A*x*x+B*x+C=0,providedithasanyroots.*Precondition:A!=0andB*B-4*A*C>=0.*/ staticpublicdoubleroot(doubleA,doubleB,doubleC){ assertA!=0:"Leadingcoefficientofquadraticequationca nnotbezero."; doubledisc=B*B-4*A*C;assertdisc>=0:"Discriminantofquadraticequationcanno tbenegative."; return(-B+Math.sqrt(disc))/(2*A); } Theassertionsarenotcheckedwhentheprogramisruninthen ormalway.Ifyouarecorrectin yourbeliefthatthemethodisnevercalledwithillegalargu ments,thencheckingtheconditions intheassertionswouldbeunnecessary.Ifyourbeliefisnot correct,theproblemshouldturn upduringtestingordebugging,whentheprogramisrunwitht heassertionsenabled. Ifthe root() methodispartofasoftwarelibrarythatyouexpectotherpeo pletouse,then thesituationislessclear.Sun'sJavadocumentationadvis esthatassertionsshould not beused forcheckingthecontractofpublicmethods:Ifthecallerof amethodviolatesthecontractby passingillegalparameters,thenanexceptionshouldbethr own.Thiswillenforcethecontract whetherornotassertionsareenabled.(However,whileit's truethatJavaprogrammers expect thecontractofamethodtobeenforcedwithexceptions,ther earereasonableargumentsfor usingassertionsinstead,insomecases.) <br /> <br /> PAGE 410<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 396 Ontheotherhand,itneverhurtstouseanassertiontochecka postconditionofamethod. Apostconditionissomethingthatissupposedtobetrueafte rthemethodhasexecuted,andit canbetestedwithan assert statementattheendofthemethod.Ifthepostcoditionisfal se, thereisabuginthemethoditself,andthatissomethingthat needstobefoundduringthe developmentofthemethod. Tohaveanyeect,assertionsmustbe enabled whentheprogramisrun.Howtodothis dependsonwhatprogrammingenvironmentyouareusing.(See Section2.6 foradiscussionof programmingenvironments.)Intheusualcommandlineenvir onment,assertionsareenabledby addingtheoption -enableassertions tothe java commandthatisusedtoruntheprogram. Forexample,iftheclassthatcontainsthemainprogramis RootFinder ,thenthecommand java-enableassertionsRootFinder willruntheprogramwithassertionsenabled.The -enableassertions optioncanbeabbreviatedto -ea ,sothecommandcanalternativelybewrittenas java-eaRootFinder Infact,itispossibletoenableassertionsinjustpartofap rogram.Anoptionoftheform \ -ea: h class-name i "enablesonlytheassertionsinthespeciedclass.Notetha tthereareno spacesbetweenthe -ea ,the\:",andthenameoftheclass.Toenablealltheassertio nsina packageandinitssub-packages,youcanuseanoptionofthef orm\ -ea: h package-name i ... ". Toenableassertionsinthe\defaultpackage"(thatis,clas sesthatarenotspeciedtobelongto apackage,likealmostalltheclassesinthisbook),use\ -ea:... ".Forexample,torunaJava programnamed\MegaPaint"withassertionsenabledforever yclassinthepackagesnamed \paintutils"and\drawing",youwouldusethecommand: java-ea:paintutils...-ea:drawing...MegaPaint IfyouareusingtheEclipseintegrateddevelopmentenviron ment,youcanspecifythe -ea optionbycreatinga runconguration .Right-clickthenameofthemainprogramclassinthe PackageExplorerpane,andselect\RunAs"fromthepop-upme nuandthen\Run..."from thesubmenu.Thiswillopenadialogboxwhereyoucanmanager uncongurations.Thename oftheprojectandofthemainclasswillbealreadybelledin .Clickthe\Arguments"tab,and enter -ea intheboxunder\VMArguments".Thecontentsofthisboxarea ddedtothe java commandthatisusedtoruntheprogram.Youcanenterotherop tionsinthisbox,including morecomplicated enableassertions optionssuchas -ea:paintutils... .Whenyouclickthe \Run"button,theoptionswillbeapplied.Furthermore,the ywillbeappliedwheneveryourun theprogram,unlessyouchangetheruncongurationoraddan ewconguration.Notethatit ispossibletomaketworuncongurationsforthesameclass, onewithassertionsenabledand onewithassertionsdisabled.8.5IntroductiontoThreadsL ikepeople,computers can multitask .Thatis,theycanbeworkingonseveraldierent (online) tasksatthesametime.Acomputerthathasjustasinglecentr alprocessingunitcan'tliterally dotwothingsatthesametime,anymorethanapersoncan,buti tcanstillswitchitsattention backandforthamongseveraltasks.Furthermore,itisincre asinglycommonforcomputersto havemorethanoneprocessingunit,andsuchcomputerscanli terallyworkonseveraltasks simultaneously.Itislikelythatfromnowon,mostoftheinc reaseincomputingpowerwill <br /> <br /> PAGE 411<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 397 comefromaddingadditionalprocessorstocomputersrather thanfromincreasingthespeedof individualprocessors.Tousethefullpowerofthesemultip rocessingcomputers,aprogrammer mustdo parallelprogramming ,whichmeanswritingaprogramasasetofseveraltasksthat canbeexecutedsimultaneously.Evenonasingle-processor computer,parallelprogramming techniquescanbeuseful,sincesomeproblemscanbetackled mostnaturallybybreakingthe solutionintoasetofsimultaneoustasksthatcooperatetos olvetheproblem. InJava,asingletaskiscalleda thread .Theterm\thread"referstoa\threadofcontrol"or \threadofexecution,"meaningasequenceofinstructionst hatareexecutedoneafteranother| thethreadextendsthroughtime,connectingeachinstructi ontothenext.Inamultithreaded program,therecanbemanythreadsofcontrol,weavingthrou ghtimeinparallelandforming thecompletefabricoftheprogram.(Ok,enoughwiththemeta phor,already!)EveryJava programhasatleastonethread;whentheJavavirtualmachin erunsyourprogram,itcreatesa threadthatisresponsibleforexecutingthe main routineoftheprogram.Thismainthreadcan inturncreateotherthreadsthatcancontinueevenafterthe mainthreadhasterminated.Ina GUIprogram,thereisatleastoneadditionalthread,whichi sresponsibleforhandlingevents anddrawingcomponentsonthescreen.ThisGUIthreadiscrea tedwhentherstwindowis opened.Soinfact,youhavealreadydoneparallelprogrammi ng!Whena main routineopensa window,boththemainthreadandtheGUIthreadcancontinuet oruninparallel.Ofcourse, parallelprogrammingcanbeusedinmuchmoreinterestingwa ys. Unfortunately,parallelprogrammingisevenmoredicultt hanordinary,single-threaded programming.Whenseveralthreadsareworkingtogetherona problem,awholenewcategory oferrorsispossible.Thisjustmeansthattechniquesforwr itingcorrectandrobustprogramsare evenmoreimportantforparallelprogrammingthantheyaref ornormalprogramming.(That's oneexcuseforhavingthissectioninthischapter|anotheri sthatwewillneedthreadsatseveral pointsinfuturechapters,andIdidn'thaveanotherplacein thebookwherethetopictsmore naturally.)Sincethreadsareadiculttopic,youwillprob ablynotfullyunderstandeverything inthissectionthersttimethroughthematerial.Yourunde rstandingshouldimproveasyou encountermoreexamplesofthreadsinfuturesections.8.5.1CreatingandRunningThreadsInJava,athreadisrepresentedbyanobjectbelongingtothe class java.lang.Thread (orto asubclassofthisclass).Thepurposeofa Thread objectistoexecuteasinglemethod.The methodisexecutedinitsownthreadofcontrol,whichcanrun inparallelwithotherthreads. Whentheexecutionofthemethodisnished,eitherbecauset hemethodterminatesnormally orbecauseofanuncaughtexception,thethreadstopsrunnin g.Oncethishappens,thereisno waytorestartthethreadortousethesame Thread objecttostartanotherthread. Therearetwowaystoprogramathread.Oneistocreateasubcl assof Thread andtodene themethod publicvoidrun() inthesubclass.This run() methoddenesthetaskthatwill beperformedbythethread;thatis,whenthethreadisstarte d,itisthe run() methodthat willbeexecutedinthethread.Forexample,hereisasimple, andratheruseless,classthat denesathreadthatdoesnothingbutprintamessageonstand ardoutput: publicclassNamedThreadextendsThread{ privateStringname;//Thenameofthisthread.publicNamedThread(Stringname){//Constructorgivesnam etothread. this.name=name; }publicvoidrun(){//Therunmethodprintsamessagetostand ardoutput. <br /> <br /> PAGE 412<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 398 System.out.println("Greetingsfromthread'"+name+"'!" ); } } Tousea NamedThread ,youmustofcoursecreateanobjectbelongingtothisclass. For example, NamedThreadgreetings=newNamedThread("Fred"); However,creatingtheobjectdoesnotautomaticallystartt hethreadrunning.Todothat,you mustcallthe start() methodinthethreadobject.Fortheexample,thiswouldbedo newith thestatement greetings.start(); Thepurposeofthe start() methodistocreateanewthreadofcontrolthatwillexecutet he Thread object's run() method.Thenewthreadrunsinparallelwiththethreadinwhi chthe start() methodwascalled,alongwithanyotherthreadsthatalready existed.Thismeans thatthecodeinthe run() methodwillexecuteatthesametimeasthestatementsthatfo llow thecallto greetings.start() .Considerthiscodesegment: NamedThreadgreetings=newNamedThread("Fred");greetings.start();System.out.println("Threadhasbeenstarted."); After greetings.start() isexecuted,therearetwothreads.Oneofthemwillprint\Th read hasbeenstarted."whiletheotheronewantstoprint\Greeti ngsfromthread'Fred'!".Itis importanttonotethat thesemessagescanbeprintedineitherorder .Thetwothreadsrun simultaneouslyandwillcompeteforaccesstostandardoutp ut,sothattheycanprinttheir messages.Whicheverthreadhappenstobethersttogetacce sswillbethersttoprintits message.Inanormal,single-threadedprogram,thingshapp eninadenite,predictableorder frombeginningtoend.Inamulti-threadedprogram,thereis afundamentalindeterminancy. Youcan'tbesurewhatorderthingswillhappenin.Thisindet erminacyiswhatmakesparallel programmingsodicult! Notethatcalling greetings.start() is very dierentfromcalling greetings.run() Calling greetings.run() willexecutethe run() methodinthesamethread,ratherthan creatinganewthread.Thismeansthatalltheworkofthe run() willbedonebeforethe computermovesontothestatementthatfollowsthecallto greetings.run() intheprogram. Thereisnoparallelismandnoindeterminacy. Imentionedthattherearetwowaystoprogramathread.Ther stwaywastodeneasubclassof Thread .Thesecondistodeneaclassthatimplementstheinterface java.lang.Runnable .The Runnable interfacedenesasinglemethod, publicvoidrun() Anobjectthatimplementsthe Runnable interfacecanbepassedasaparametertotheconstructorofanobjectoftype Thread .Whenthatthread's start methodiscalled,thethread willexecutethe run() methodinthe Runnable object.Forexample,asanalternativetothe NamedThread class,wecoulddenetheclass: publicclassNamedRunnableimplementsRunnable{ privateStringname;//Thenameofthisthread.publicNamedRunnable(Stringname){//Constructorgivesn ametoobject. this.name=name; } <br /> <br /> PAGE 413<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 399 publicvoidrun(){//Therunmethodprintsamessagetostand ardoutput. System.out.println("Greetingsfromthread'"+name+"'!" ); } } Tousethisversionoftheclass,wewouldcreatea NamedRunnable objectandusethatobject tocreateanobjectoftype Thread : NamedRunnablegreetings=newNamedRunnable("Fred");ThreadgreetingsThread=newThread(greetings);greetingsThread.start(); Finally,I'llnotethatitissometimesconvenienttodenea threadusingananonymous innerclass( Subsection5.7.3 ).Forexample: ThreadgreetingsFromFred=newThread(){ publicvoidrun(){ System.out.println("GreetingsfromFred!"); } };greetingsFromFred.start(); Tohelpyouunderstandhowmultiplethreadsareexecutedinp arallel,weconsiderthesample program ThreadTest1.java .Thisprogramcreatesseveralthreads.Eachthreadperform sexactly thesametask.Thetaskistocountthenumberofintegersless than1000000thatareprime. (Theparticulartaskthatisdoneisnotimportantforourpur poseshere.)Onmycomputer, thistasktakesalittlemorethanonesecondofprocessingti me.Thethreadsthatperformthis taskaredenedbythefollowingstaticnestedclass: /** *Whenathreadbelongingtothisclassisrunitwillcountthe*numberofprimesbetween2and1000000.Itwillprinttheres ult *tostandardoutput,alongwithitsIDnumberandtheelapsed*timebetweenthestartandtheendofthecomputation.*/ privatestaticclassCountPrimesThreadextendsThread{ intid;//Anidnumberforthisthread;specifiedintheconst ructor. publicCountPrimesThread(intid){ this.id=id; }publicvoidrun(){ longstartTime=System.currentTimeMillis();intcount=countPrimes(2,1000000);//Countstheprimes.longelapsedTime=System.currentTimeMillis()-startTim e; System.out.println("Thread"+id+"counted"+ count+"primesin"+(elapsedTime/1000.0)+"seconds."); } } Themainprogramaskstheuserhowmanythreadstorun,andthe ncreatesandstartsthe speciednumberofthreads: <br /> <br /> PAGE 414<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 400 publicstaticvoidmain(String[]args){ intnumberOfThreads=0;while(numberOfThreads<1||numberOfThreads>25){ System.out.print("Howmanythreadsdoyouwanttouse(1to2 5)?"); numberOfThreads=TextIO.getlnInt();if(numberOfThreads<1||numberOfThreads>25) System.out.println("Pleaseenteranumberbetween1and25 !"); }System.out.println("\nCreating"+numberOfThreads +"primecountingthreads..."); CountPrimesThread[]worker=newCountPrimesThread[numb erOfThreads]; for(inti=0;i<numberOfThreads;i++) worker[i]=newCountPrimesThread(i); for(inti=0;i<numberOfThreads;i++) worker[i].start(); System.out.println("Threadshavebeencreatedandstarte d."); } Itwouldbeagoodideaforyoutocompileandruntheprogramor totrytheappletversion, whichcanbefoundintheon-lineversionofthissection. WhenIrantheprogramwithonethread,ittook1.18secondsfo rmycomputertodothe computation.WhenIranitusingsixthreads,theoutputwas: Creating6primecountingthreads...Threadshavebeencreatedandstarted.Thread1counted78498primesin6.706seconds.Thread4counted78498primesin6.693seconds.Thread0counted78498primesin6.838seconds.Thread2counted78498primesin6.825seconds.Thread3counted78498primesin6.893seconds.Thread5counted78498primesin6.859seconds. Thesecondlinewasprintedimmediatelyaftertherst.Atth ispoint,themainprogram hasendedbutthesixthreadscontinuetorun.Afterapauseof aboutsevenseconds,allsix threadscompletedataboutthesametime.Theorderinwhicht hethreadscompleteisnotthe sameastheorderinwhichtheywerestarted,andtheorderisi ndeterminate.Thatis,ifthe programisrunagain,theorderinwhichthethreadscomplete willprobablybedierent. Onmycomputer,sixthreadstakeaboutsixtimeslongerthano nethread.Thisisbecause mycomputerhasonlyoneprocessor.Sixthreads,alldoingth esametask,takesixtimesas muchprocessingasonethread.Withonlyoneprocessortodot hework,thetotalelapsedtime forsixthreadsisaboutsixtimeslongerthanthetimeforone thread.Onacomputerwith twoprocessors,thecomputercanworkontwotasksatthesame time,andsixthreadsmight completeinaslittleasthreetimesthetimeittakesforonet hread.Onacomputerwithsixor moreprocessors,sixthreadsmighttakenomoretimethanasi nglethread.Becauseofoverhead andotherreasons,theactualspeedupwillprobablybesmall erthanthisanalysisindicates,but onamultiprocessormachine,youshouldseeadenitespeedu p.Whathappenswhenyourun theprogramonyourowncomputer?Howmanyprocessorsdoyouh ave? Whenevertherearemorethreadstoberunthanthereareproce ssorstorunthem,the computerdividesitsattentionamongalltherunnablethrea dsbyswitchingrapidlyfromone threadtoanother.Thatis,eachprocessorrunsonethreadfo rawhilethenswitchestoanother threadandrunsthatoneforawhile,andsoon.Typically,the se\contextswitches"occur about100timesormorepersecond.Theresultisthatthecomp utermakesprogressonall <br /> <br /> PAGE 415<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 401 thetasks,anditlookstotheuserasifallthetasksarebeing executedsimultaneously.This iswhyinthesampleprogram,inwhicheachthreadhasthesame amountofworktodo,all thethreadscompleteataboutthesametime:Overanytimeper iodlongerthanafractionof asecond,thecomputer'stimeisdividedapproximatelyequa llyamongallthethreads. Whenyoudoparallelprogramminginordertospreadtheworka mongseveralprocessors, youmightwanttotakeintoaccountthenumberofavailablepr ocessors.Youmight,forexample, wanttocreateonethreadforeachprocessor.InJava,youcan ndoutthenumberofprocessors bycallingthefunction Runtime.getRuntime().availableProcessors() whichreturnsan int givingthenumberofprocessorsthatareavailabletotheJav aVirtual Machine.Insomecases,thismightbelessthantheactualnum berofprocessorsinthecomputer. 8.5.2OperationsonThreadsThe Thread classincludesseveralusefulmethodsinadditiontothe start() methodthatwas discussedabove.Iwillmentionjustafewofthem. If thrd isanobjectoftype Thread ,thenthe boolean -valuedfunction thrd.isAlive() can beusedtotestwhetherornotthethreadisalive.Athreadis\ alive"betweenthetimeit isstartedandthetimewhenitterminates.Afterthethreadh asterminateditissaidtobe \dead".(Therathergruesomemetaphorisalsousedwhenwere ferto\killing"or\aborting" athread.) Thestaticmethod Thread.sleep(milliseconds) causesthethreadthatexecutesthis methodto\sleep"forthespeciednumberofmilliseconds.A sleepingthreadisstillalive, butitisnotrunning.Whileathreadissleeping,thecompute rwillworkonanyotherrunnable threads(oronotherprograms). Thread.sleep() canbeusedtoinsertapauseintheexecution ofathread.The sleep methodcanthrowanexceptionoftype InterruptedException ,which isanexceptionclassthatrequiresmandatoryexceptionhan dling(see Subsection8.3.4 ).In practice,thismeansthatthe sleep methodisusuallyusedina try..catch statementthat catchesthepotential InterruptedException : try{ Thread.sleep(lengthOfPause); }catch(InterruptedExceptione){} Onethreadcaninterruptanotherthreadtowakeitupwheniti ssleepingorpausedforsome otherreason.A Thread thrd ,canbeinterruptedbycallingitsmethod thrd.interrupt() butyouarenotlikelytodothisuntilyoustartwritingrathe radvancedapplications,andyou arenotlikelytoneedtodoanythinginresponsetoan InterruptedException (exceptto catch it).It'sunfortunatethatyouhavetoworryaboutitatall,b utthat'sthewaythatmandatory exceptionhandlingworks. Sometimes,it'snecessaryforonethreadtowaitforanthert hreadtodie.Thisisdone withthe join() methodfromthe Thread class.Supposethat thrd isa Thread .Then, ifanotherthreadcalls thrd.join() ,thatotherthreadwillgotosleepuntil thrd terminates.If thrd isalreadydeadwhen thrd.join() iscalled,thenitsimplyhasnoeect| thethreadthatcalled thrd.join() proceedsimmediately.Themethod join() canthrowan InterruptedException ,whichmustbehandled.Asanexample,thefollowingcodesta rts severalthreads,waitsforthemalltoterminate,andthenou tputstheelapsedtime: <br /> <br /> PAGE 416<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 402 CountPrimesThread[]worker=newCountPrimesThread[numb erOfThreads]; longstartTime=System.currentTimeMillis();for(inti=0;i<numberOfThreads;i++){ worker[i]=newCountPrimesThread();worker[i].start(); }for(inti=0;i<numberOfThreads;i++){ try{ worker[i].join();//Sleepuntilworker[i]hasterminated }catch(InterruptedExceptione){} }//Atthispoint,alltheworkerthreadshaveterminated.longelapsedTime=System.currentTimeMillis()-startTim e; System.out.println("Elapsedtime:"+(elapsedTime/1000 .0)+"seconds."); Anobservantreaderwillnotethatthiscodeassumesthatno InterruptedException willoccur. Tobeabsolutelysurethatthethread worker[i] hasterminatedinanenvironmentwhere InterruptedExceptions arepossible,youwouldhavetodosomethinglike: while(worker[i].isAlive()){ try{ worker[i].join(); }catch(InterruptedExceptione){} } 8.5.3MutualExclusionwith\synchronized"Programmingseveralthreadstocarryoutindependenttasks iseasy.Therealdicultyarises whenthreadshavetointeractinsomeway.Onewaythatthread sinteractisbysharing resources.Whentwothreadsneedaccesstothesameresource ,suchasavariableorawindow onthescreen,somecaremustbetakenthattheydon'ttrytous ethesameresourceatthesame time.Otherwise,thesituationcouldbesomethinglikethis :Imagineseveralcookssharingthe useofjustonemeasuringcup,andimaginethatCookAllsthe measuringcupwithmilk,only tohaveCookBgrabthecupbeforeCookAhasachancetoemptyth emilkintohisbowl. TherehastobesomewayforCookAtoclaimexclusiverightsto thecupwhileheperforms thetwooperations:Add-Milk-To-CupandEmpty-Cup-Into-B owl. Somethingsimilarhappenswiththreads,evenwithsomethin gassimpleasaddingonetoa counter.Thestatement count=count+1; isactuallyasequenceofthreeoperations: Step1.GetthevalueofcountStep2.Add1tothevalue.Step3.Storethenewvalueincount <br /> <br /> PAGE 417<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 403 Supposethatseveralthreadsperformthesethreesteps.Rem emberthatit'spossiblefortwo threadstorunatthesametime,andevenifthereisonlyonepr ocessor,it'spossibleforthat processortoswitchfromonethreadtoanotheratanypoint.S upposethatwhileonethreadis betweenStep2andStep3,anotherthreadstartsexecutingth esamesequenceofsteps.Since therstthreadhasnotyetstoredthenewvaluein count ,thesecondthreadreadsthe old value of count andaddsonetothatoldvalue.Afterboththreadshaveexecut edStep3,thevalueof count hasgoneuponlyby1insteadofby2!Thistypeofproblemiscal leda racecondition Thisoccurswhenonethreadisinthemiddleofamulti-stepop eration,andanotherthread changessomevalueorconditionthattherstthreadisdepen dingupon.(Therstthreadis\in arace"tocompleteallthestepsbeforeitisinterruptedbya notherthread.)Anotherexample ofaraceconditioncanoccurinan if statement.Supposethefollowingstatement,whichis meanttoavoidadivision-by-zeroerrorisexecutedbyathre ad: if(A!=0) B=C/A; Ifthevariable A issharedbyseveralthreads,andifnothingisdonetoguarda gainsttherace condition,thenitispossiblethatasecondthreadwillchan gethevalueof A tozerobetweenthe timethattherstthreadchecksthecondition A!=0 andthetimethatitdoesthedivision. Thismeansthatthethreadendsupdividingbyzero,eventhou ghitjustcheckedthat A was notzero! Toxtheproblemofraceconditions,therehastobesomewayf orathreadtoget exclusive access toasharedresource.Thisisnotatrivialthingtoimplement ,butJavaprovidesahigh levelandrelativelyeasy-to-useapproachtoexclusiveacc ess.It'sdonewith synchronized methods andwiththe synchronizedstatement .Theseareusedtoprotectsharedresources bymakingsurethatonlyonethreadatatimewilltrytoaccess theresource.Synchronizationin Javaactuallyprovidesonly mutualexclusion ,whichmeansthatexclusiveaccesstoaresource isonlyguaranteedif every threadthatneedsaccesstothatresourceusessynchronizat ion. Synchronizationislikeacookleavinganotethatsays,\I'm usingthemeasuringcup."This willgetthecookexclusiveaccesstothecup|butonlyifallt hecooksagreetocheckthenote beforetryingtograbthecup. Becausethisisadiculttopic,Iwillstartwithasimpleexa mple.Supposethatwewant toavoidtheraceconditionthatoccurswhenseveralthreads allwanttoadd1toacounter. Wecandothisbydeningaclasstorepresentthecounterandb yusingsynchronizedmethods inthatclass: publicclassThreadSafeCounter{ privateintcount=0;//Thevalueofthecounter.synchronizedpublicvoidincrement(){ count=count+1; }synchronizedpublicintgetValue(){ returncount; } } If tsc isoftype ThreadSafeCounter ,thenanythreadcancall tsc.increment() toadd1to thecounterinacompletelysafeway.Thefactthat tsc.increment() is synchronized means thatonlyonethreadcanbeinthismethodatatime;onceathre adstartsexecutingthis <br /> <br /> PAGE 418<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 404 method,itisguaranteedthatitwillnishexecutingitwith outhavinganotherthreadchange thevalueof tsc.count inthemeantime.Thereisnopossibilityofaracecondition. Notethat theguaranteedependsonthefactthat count isa private variable.Thisforcesallaccessto tsc.count tooccurinthe synchronized methodsthatareprovidedbytheclass.If count were public ,itwouldbepossibleforathreadtobypassthesynchronizat ionby,forexample,saying tsc.count++ .Thiscouldchangethevalueof count whileanotherthreadisinthemiddleof the tsc.increment() .Synchronizationdoes not guaranteeexclusiveaccess;itonlyguarantees mutualexclusion amongallthethreadsthatareproperlysynchronized. The ThreadSafeCounter classdoesnotpreventallpossibleraceconditionsthatmig htarise whenusingacounter.Considerthe if statement: if(tsc.getValue()==0) doSomething(); where doSomething() issomemethodthatrequiresthevalueofthecountertobezer o.There isstillaraceconditionhere,whichoccursifasecondthrea dincrementsthecounterbetween thetimetherstthreadtests tsc.getValue()==0 andthetimeitexecutes doSomething() Therstthreadneedsexclusiveaccesstothecounterduring theexecutionofthewhole if statement.(Thesynchronizationinthe ThreadSafeCounter classonlygivesitexclusiveaccess duringthetimeitisevaluating tsc.getValue() .)Wecansolvetheraceconditionbyputting the if statementina synchronized statement: synchronized(tsc){ if(tsc.getValue()==0) doSomething(); } Notethatthe synchronized statementtakesanobject| tsc inthiscase|asakindofparameter.Thesyntaxofthe synchronized statementis: synchronized( h object i ){ h statements i } InJava,mutualexclusionisalwaysassociatedwithanobjec t;wesaythatthesynchronizationis\on"thatobject.Forexample,the if statementaboveis\synchronizedon tsc ."A synchronizedinstancemethod,suchasthoseintheclass ThreadSafeCounter ,issynchronized ontheobjectthatcontainstheinstancemethod.Infact,add ingthe synchronized modier tothedenitionofaninstancemethodisprettymuchequival enttoputtingthebodyofthe methodina synchronized statement, synchronized(this){...} .Itisalsopossibletohave synchronizedstaticmethods;asynchronizedstaticmethod issynchronizedonaspecialclass objectthatrepresentstheclassthatcontainsthestaticme thod. TherealruleofsynchronizationinJavais: Twothreadscannotbesynchronizedon thesameobjectatthesametime ;thatis,theycannotsimultaneouslybeexecutingcode segmentsthataresynchronizedonthatobject.Ifonethread issynchronizedonanobject,and asecondthreadtriestosynchronizeonthesameobject,thes econdthreadisforcedtowait untiltherstthreadhasnishedwiththeobject.Thisisimp lementedusingsomethingcalled a lock .Everyobjecthasalock,andthatlockcanbe\held"byonlyon ethreadatatime.To enterasynchronizedstatementorsynchronizedmethod,ath readmustobtaintheassociated object'slock.Ifthelockisavailable,thenthethreadobta insthelockandimmediatelybegins executingthesynchronizedcode.Itreleasesthelockafter itnishesexecutingthesynchronized code.IfThreadAtriestoobtainalockthatisalreadyheldby ThreadB,thenThreadAhas <br /> <br /> PAGE 419<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 405 towaituntilThreadBreleasesthelock.Infact,ThreadAwil lgotosleep,andwillnotbe awokenuntilthelockbecomesavailable. Asasimpleexampleofsharedresources,wereturntotheprim e-countingproblem.Suppose thatwewanttocountalltheprimesinagivenrangeofinteger s,andsupposethatwewant todividetheworkupamongseveralthreads.Eachthreadwill beassignedpartoftherange ofintegersandwillcounttheprimesinitsassignedrange.A ttheendofitscomputation,the threadhastoadditscounttotheoveralltotalnumberofprim esfound.Thevariablethat representsthetotalissharedbyallthethreads.Ifeachthr eadjustsays total=total+count; thenthereisa(small)chancethattwothreadswilltrytodot hisatthesametimeandthatthe naltotalwillbewrong.Topreventthisracecondition,acc essto total hastobesynchronized. Myprogramusesasynchronizedmethodtoaddthecountstothe total: synchronizedprivatestaticvoidaddToTotal(intx){ total=total+x;System.out.println(total+"primesfoundsofar."); } Thesourcecodefortheprogramcanbefoundin ThreadTest2.java .Thisprogramcounts theprimesintherange3000001to6000000.(Thenumbersarer atherarbitrary.)The main() routineinthisprogramcreatesbetween1and5threadsandas signspartofthejobtoeach thread.Itthenwaitsforallthethreadstonish,usingthe join() methodasdescribedabove, andreportsthetotalelapsedtime.Ifyouruntheprogramona multiprocessorcomputer,it shouldtakelesstimefortheprogramtorunwhenyouusemoret hanonethread.Youcan compileandruntheprogramortrytheequivalentappletinth eon-lineversionofthissection. Synchronizationcanhelptopreventraceconditions,butit introducesthepossibilityof anothertypeoferror, deadlock .Adeadlockoccurswhenathreadwaitsforeverforaresource thatitwillneverget.Inthekitchen,adeadlockmightoccur iftwoverysimple-mindedcooks bothwanttomeasureacupofmilkatthesametime.Therstcoo kgrabsthemeasuringcup, whilethesecondcookgrabsthemilk.Therstcookneedsthem ilk,butcan'tnditbecause thesecondcookhasit.Thesecondcookneedsthemeasuringcu p,butcan'tnditbecause therstcookhasit.Neithercookcancontinueandnothingmo regetsdone.Thisisdeadlock. Exactlythesamethingcanhappeninaprogram,forexampleif therearetwothreads(likethe twocooks)bothofwhichneedtoobtainlocksonthesametwoob jects(likethemilkandthe measuringcup)beforetheycanproceed.Deadlockscaneasil yoccur,unlessgreatcareistaken toavoidthem.Fortunately,wewon'tbelookingatanyexampl esthatrequirelocksonmore thanoneobject,sowewillavoidthatsourceofdeadlock.8.5.4WaitandNotifyThreadscaninteractwitheachotherinotherwaysbesidessh aringresources.Forexample, onethreadmightproducesomesortofresultthatisneededby anotherthread.Thisimposes somerestrictionontheorderinwhichthethreadscandothei rcomputations.Ifthesecond threadgetstothepointwhereitneedstheresultfromthers tthread,itmighthavetostop andwaitfortheresulttobeproduced.Sincethesecondthrea dcan'tcontinue,itmightaswell gotosleep.Butthentherehastobesomewaytonotifytheseco ndthreadwhentheresultis <br /> <br /> PAGE 420<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 406 ready,sothatitcanwakeupandcontinueitscomputation.Ja va,ofcourse,hasawaytodo thiskindofwaitingandnotication:Ithas wait() and notify() methodsthataredenedas instancemethodsinclass Object andsocanbeusedwithanyobject.Thereasonwhy wait() and notify() shouldbeassociatedwithobjectsisnotobvious,sodon'two rryaboutitatthis point.Itdoes,atleast,makeitpossibletodirectdierent noticationstoadierentrecipients, dependingonwhichobject's notify() methodiscalled. Thegeneralideaisthatwhenathreadcallsa wait() methodinsomeobject,thatthread goestosleepuntilthe notify() methodinthesameobjectiscalled.Itwillhavetobecalled, obviously,byanotherthread,sincethethreadthatcalled wait() issleeping.Atypicalpattern isthatThreadAcalls wait() whenitneedsaresultfromThreadB,butthatresultisnotyet available.WhenThreadBhastheresultready,itcalls notify() ,whichwillwakeThreadA upsothatitcanusetheresult.Itisnotanerrortocall notify() whennooneiswaiting; itjusthasnoeect.Toimplementthis,ThreadAwillexecute codesimlartothefollowing, where obj issomeobject: if(resultIsAvailable()==false) obj.wait();//waitfornoificationthattheresultisavail able useTheResult(); whileThreadBdoessomethinglike: generateTheResult();obj.notify();//sendoutanotificationthattheresultisa vailable Now,thereisareallynastyraceconditioninthiscode.Thet wothreadsmightexecute theircodeinthefollowingorder: 1.ThreadAchecksresultIsAvailable()andfindsthatthere sultisnotready, soitdecidestoexecutetheobj.wait()statement,butbefor eitdoes, 2.ThreadBfinishesgeneratingtheresultandcallsobj.not ify() 3.ThreadAcallsobj.wait()towaitfornotificationthatth eresultisready. InStep3,ThreadAiswaitingforanoticationthatwillneve rcome,because notify() hasalreadybeencalled.Thisisakindofdeadlockthatcanle aveThreadAwaitingforever. Obviously,weneedsomekindofsynchronization.Thesoluti onistoenclosebothThreadA's codeandThreadB'scodein synchronized statements,anditisverynaturaltosynchronize onthesameobject, obj ,thatisusedforthecallsto wait() and notify() .Infact,since synchronizationisalmostalwaysneededwhen wait() and notify() areused,Javamakesit anabsoluterequirement.InJava,athreadcanlegallycall obj.wait() or obj.notify() only ifthatthreadholdsthesynchronizationlockassociatedwi ththeobject obj .Ifitdoesnothold thatlock,thenanexceptionisthrown.(Theexceptionisoft ype IllegalMonitorStateException whichdoesnotrequiremandatoryhandlingandwhichistypic allynotcaught.)Onefurther complicationisthatthe wait() methodcanthrowan InterruptedException andsoshouldbe calledina try statementthathandlestheexception. Tomakethingsmoredenite,letsconsidera producer/consumer problemwhereone threadproducesaresultthatisconsumedbyanotherthread. Assumethatthereisashared variablenamed sharedResult thatisusedtotransfertheresultfromtheproducertothe consumer.Whentheresultisready,theproducersetsthevar iabletoanon-nullvalue.The producercancheckwhethertheresultisreadybytestingwhe therthevalueof sharedResult isnull.Wewilluseavariablenamed lock forsynchronization.Thethecodefortheproducer threadcouldhavetheform: <br /> <br /> PAGE 421<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 407 makeResult=generateTheResult();//Notsynchronized!synchronized(lock){ sharedResult=makeResult;lock.notify(); } whiletheconsumerwouldexecutecodesuchas: synchronized(lock){ while(sharedResult==null){ try{ lock.wait(); }catch(InterruptedExceptione){} }useResult=sharedResult; }useTheResult(useResult);//Notsynchronized! Thecallsto generateTheResult() and useTheResult() arenotsynchronized,whichallowsthemtoruninparallelwithotherthreadsthatmightals osynchronizeon lock .Since sharedResult isasharedvariable,allreferencesto sharedResult shouldbesynchronized,so thereferencesto sharedResult mustbeinsidethe synchronized statements.Thegoalisto doaslittleaspossible(butnotless)insynchronizedcodes egments. Ifyouareuncommonlyalert,youmightnoticesomethingfunn y: lock.wait() does notnishuntil lock.notify() isexecuted,butsincebothofthesemethodsarecalledin synchronized statementsthatsynchronizeonthesameobject,shouldn'ti tbeimpossiblefor bothmethodstoberunningatthesametime?Infact, lock.wait() isaspecialcase:Whenthe consumerthreadcalls lock.wait() ,itgivesupthelockthatitholdsonthesynchronization object, lock .Thisgivestheproducerthreadachancetoexecutethe synchronized(lock) blockthatcontainsthe lock.notify() statement.Aftertheproducerthreadexitsfromthis block,thelockisreturnedtotheconsumerthreadsothatitc ancontinue. Theproducer/consumerpatterncanbegeneralizedandmadem oreusefulwithoutmakingitanymorecomplex.Inthegeneralcase,multipleresult sareproducedbyoneormore producerthreadsandareconsumedbyoneormoreconsumerthr eads.Insteadofhavingjust one sharedResult object,wekeepalistofobjectsthathavebeenproducedbutn otyetconsumed.Producerthreadsaddobjectstothislist.Consumert hreadsremoveobjectsfromthis list.Theonlytimewhenathreadisblockedfromrunningiswh enaconsumerthreadtries togetaresultfromthelist,andnoresultsareavailable.It iseasytoencapsulatethewhole producer/consumerpatterninaclass(whereIassumethatth ereisaclass ResultType that representstheresultobjects): /** *AnobjectoftypeProducerConsumerrepresentsalistofres ults *thatareavailableforprocessing.Resultsareaddedtothe list *bycallingtheproducemethodandareremovebycallingcons ume. *Ifnoresultisavailablewhenconsumeiscalled,themethod will *notreturnuntilaresultbecomesavailable.*/ privatestaticclassProducerConsumer{ privateArrayList<ResultType>items=newArrayList<Resu ltType>(); <br /> <br /> PAGE 422<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 408 //ThisArrayListholdsresultsthathavebeenproducedanda rewaiting //tobeconsumed.See Subsection7.3.3 forinformationonArrayList. publicvoidproduce(ResultTypeitem){ synchronized(items){ items.add(item);//Additemtothelistofresults.items.notify();//Notifyanythreadwaitinginconsume()m ethod. } }publicResultTypeconsume(){ ResultTypeitem;synchronized(items){ //Ifnoresultsareavailable,waitfornotificationfrompr oduce(). while(items.size()==0){ try{ items.wait(); }catch(InterruptedExceptione){} }//Atthispoint,weknowthatatleastoneresultisavailable item=items.remove(0); }returnitem; } } Foranexampleofaprogramthatusesa ProducerConsumer class,see ThreadTest3.java Thisprogramperformsthesametaskas ThreadTest2.java ,butthethreadscommunicateusing theproducer/consumerpatterninsteadofwithasharedvari able. Goingbacktoourkitchenanalogyforamoment,considerares taurantwithseveralwaiters andseveralcooks.Ifwelookattherowofcustomerordersint othekitchen,thewaiters \produce"theordersandleavetheminapile.Theordersare\ consumed"bythecooks; wheneveracookneedsanewordertoworkon,shepicksoneupfr omthepile.Thepileof orders,orcourse,playstheroleofthelistofresultobject sintheproducer/consumerpattern. Notethattheonlytimethatacookhastowaitiswhensheneeds anewordertoworkon,and therearenoordersinthepile.Thecookmustwaituntiloneof thewaitersplacesanorderin thepile.Wecancompletetheanalogybyimaginingthatthewa iterringsabellwhenheplaces theorderinthepile|ringingthebellislikecallingthe notify() methodtonotifythecooks thatanorderisavailable. Analnoteon notify :Itispossibleforseveralthreadstobewaitingfornotica tion.Acall to obj.notify() willwakeonlyoneofthethreadsthatiswaitingon obj .Ifyouwanttowake allthreadsthatarewaitingon obj ,youcancall obj.notifyAll() .Andanalnoteon wait : Thereisananotherversionof wait() thattakesanumberofmillisecondsasaparameter. Athreadthatcalls obj.wait(milliseconds) willwaitonlyuptothespeciednumberof millisecondsforanotication.Ifanoticationdoesn'toc curduringthatperiod,thethread willwakeupandcontinuewithoutthenotication.Inpracti ce,thisfeatureismostoftenused toletawaitingthreadwakeperiodicallywhileitiswaiting inordertoperformsomeperiodic task,suchascausingamessage\Waitingforcomputationto nish"toblink. <br /> <br /> PAGE 423<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 409 8.5.5VolatileVariablesAndanalnoteoncommunicationamongthreads:Ingeneral,t hreadscommunicatebysharing variablesandaccessingthosevariablesinsynchronizedme thodsorsynchronizedstatements. However,synchronizationisfairlyexpensivecomputation ally,andexcessiveuseofitshouldbe avoided.Soinsomecases,itcanmakesenseforthreadstoref ertosharedvariableswithout synchronizingtheiraccesstothosevariables. However,asubtleproblemariseswhenthevalueofasharedva riableissetisonethread andusedinanother.Becauseofthewaythatthreadsareimple mentedinJava,thesecond threadmightnotseethechangedvalueofthevariableimmedi ately.Thatis,itispossiblethat athreadwillcontinuetoseethe old valueofthesharedvariableforsometimeafterthevalue ofthevariablehasbeenchangedbyanotherthread.Thisisbe causethreadsareallowedto cache shareddata.Thatis,eachthreadcankeepitsownlocalcopyo ftheshareddata.When onethreadchangesthevalueofasharedvariable,thelocalc opiesinthecachesofotherthreads arenotimmediatelychanged,sotheotherthreadscontinuet oseetheoldvalue. Whenasynchronizedmethodorstatementisentered,threads areforcedtoupdatetheir cachestothemostcurrentvaluesofthevariablesinthecach e.So,usingsharedvariablesin synchronizedcodeisalwayssafe. Itisstillpossibletouseasharedvariable outside ofsynchronizedcode,butinthatcase, thevariablemustbedeclaredtobe volatile .The volatile keywordisamodierthatcanbe addedtoavariabledeclaration,asin privatevolatileintcount; Ifavariableisdeclaredtobe volatile ,nothreadwillkeepalocalcopyofthatvariableinits cache.Instead,thethreadwillalwaysusetheocial,mainc opyofthevariable.Thismeans thatanychangemadetothevariablewillimmediatelybeavai labletoallthreads.Thismakes itsafeforthreadstoreferto volatile sharedvariablesevenoutsideofsynchronizedcode. (Remember,though,thatsynchronizationisstilltheonlyw aytopreventraceconditions.) Whenthe volatile modierisappliedtoanobjectvariable,onlythevariablei tselfis declaredtobevolatile,notthecontentsoftheobjectthatt hevariablepointsto.Forthis reason, volatile isgenerallyonlyusedforvariablesofsimpletypessuchasp rimitivetypes andenumeratedtypes. Atypicalexampleofusingvolatilevariablesistosendasig nalfromonethreadtoanother thattellsthesecondthreadtoterminate.Thetwothreadswo uldshareavariable volatilebooleanterminate=false; Therunmethodofthesecondthreadwouldcheckthevalueof terminate frequentlyandend whenthevalueof terminate becomestrue: publicvoidrun(){ while(true){ if(terminate) return; ..//Dosomework. } } Thisthreadwillrununtilsomeotherthreadsetsthevalueof terminate totrue.Something likethisisreallytheonlycleanwayforonethreadtocausea notherthreadtodie. <br /> <br /> PAGE 424<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 410 (Bytheway,youmightbewonderingwhythreadsshoulduseloc aldatacachesintherst place,sinceitseemstocomplicatethingsunnecessarily.C achingisallowedbecauseofthe structureofmultiprocessingcomputers.Inmanymultiproc essingcomputers,eachprocessor hassomelocalmemorythatisdirectlyconnectedtotheproce ssor.Athread'scacheisstored inthelocalmemoryoftheprocessoronwhichthethreadisrun ning.Accesstothislocal memoryismuchfasterthanaccesstoothermemory,soitismor eecientforathreadtouse alocalcopyofasharedvariableratherthansome\mastercop y"thatisstoredinnon-local memory.)8.6AnalysisofAlgorithmsT hischapterhasconcentrated mostlyoncorrectnessofprograms.Inpractice,another (online) issueisalsoimportant: eciency .Whenanalyzingaprogramintermsofeciency,we wanttolookatquestionssuchas,\Howlongdoesittakeforth eprogramtorun?"and\Is thereanotherapproachthatwillgettheanswermorequickly ?"Eciencywillalwaysbeless importantthancorrectness;ifyoudon'tcarewhetheraprog ramworkscorrectly,youcanmake itrunveryquicklyindeed,butnoonewillthinkit'smuchofa nachievement!Ontheother hand,aprogramthatgivesacorrectansweraftertenthousan dyearsisn'tveryusefuleither, soeciencyisoftenanimportantissue. Theterm\eciency"canrefertoecientuseofalmostanyres ource,includingtime, computermemory,diskspace,ornetworkbandwidth.Inthiss ection,however,wewilldeal exclusivelywithtimeeciency,andthemajorquestionthat wewanttoaskaboutaprogram is,howlongdoesittaketoperformitstask? Itreallymakeslittlesensetoclassifyanindividualprogr amasbeing\ecient"or\inecient."Itmakesmoresensetocomparetwo(correct)program sthatperformthesametaskand askwhichoneofthetwois\moreecient,"thatis,whichonep erformsthetaskmorequickly. However,evenheretherearediculties.Therunningtimeof aprogramisnotwell-dened. Theruntimecanbedierentdependingonthenumberandspeed oftheprocessorsinthe computeronwhichitisrunand,inthecaseofJava,onthedesi gnoftheJavaVirtualMachine whichisusedtointerprettheprogram.Itcandependondetai lsofthecompilerwhichisused totranslatetheprogramfromhigh-levellanguagetomachin elanguage.Furthermore,therun timeofaprogramdependsonthesizeoftheproblemwhichthep rogramhastosolve.Ittakes asortingprogramlongertosort10000itemsthanittakesitt osort100items.Whentherun timesoftwoprogramsarecompared,itoftenhappensthatPro gramAsolvessmallproblems fasterthanProgramB,whileProgramBsolveslargeproblems fasterthanProgramA,sothat itissimplynotthecasethatoneprogramisfasterthantheot herinallcases. Inspiteofthesediculties,thereisaeldofcomputerscie ncededicatedtoanalyzing theeciencyofprograms.Theeldisknownas AnalysisofAlgorithms .Thefocusis onalgorithms,ratherthanonprogramsassuch,toavoidhavi ngtodealwithmultipleimplementationsofthesamealgorithmwrittenindierentlan guages,compiledwithdierent compilers,andrunningondierentcomputers.AnalysisofA lgorithmsisamathematicaleld thatabstractsawayfromthesedown-and-dirtydetails.Sti ll,eventhoughitisatheoretical eld,everyworkingprogrammershouldbeawareofsomeofits techniquesandresults.This sectionisaverybriefintroductiontosomeofthosetechniq uesandresults.Becausethisisnot amathematicsbook,thetreatmentwillberatherinformal. Oneofthemaintechniquesofanalysisofalgorithmsis asymptoticanalysis .Theterm \asymptotic"heremeansbasically\thetendencyinthelong run."Anasymptoticanalysisof <br /> <br /> PAGE 425<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 411 analgorithm'sruntimelooksatthequestionofhowtherunti medependsonthesizeofthe problem.Theanalysisisasymptoticbecauseitonlyconside rswhathappenstotheruntime asthesizeoftheproblemincreaseswithoutlimit;itisnotc oncernedwithwhathappensfor problemsofsmallsizeor,infact,forproblemsofanyxedn itesize.Onlywhathappensinthe longrun,astheproblemsizeincreaseswithoutlimit,isimp ortant.ShowingthatAlgorithmA isasymptoticallyfasterthanAlgorithmBdoesn'tnecessar ilymeanthatAlgorithmAwillrun fasterthanAlgorithmBforproblemsofsize10orsize1000or evensize1000000|itonly meansthatifyoukeepincreasingtheproblemsize,youwille ventuallycometoapointwhere AlgorithmAisfasterthanAlgorithmB.Anasymptoticanalys isisonlyarstapproximation, butinpracticeitoftengivesimportantandusefulinformat ion. Centraltoasymptoticanalysisis Big-Ohnotation .Usingthisnotation,wemightsay, forexample,thatanalgorithmhasarunningtimethatis O (n 2 )or O (n)or O (log(n)).These notationsareread\Big-Ohofnsquared,"\Big-Ohofn,"and\ Big-Ohoflogn"(wherelogisa logarithmfunction).Moregenerally,wecanreferto O (f(n))(\Big-Ohoffofn"),wheref(n)is somefunctionthatassignsapositiverealnumbertoeverypo sitiveintegern.The\n"inthis notationreferstothesizeoftheproblem.Beforeyoucaneve nbeginanasymptoticanalysis, youneedsomewaytomeasureproblemsize.Usually,thisisno tabigissue.Forexample,if theproblemistosortalistofitems,thentheproblemsizeca nbetakentobethenumberof itemsinthelist.Whentheinputtoanalgorithmisaninteger ,asinthecaseofalgorithmthat checkswhetheragivenpositiveintegerisprime,theusualm easureofthesizeofaproblem isthenumberofbitsintheinputintegerratherthantheinte geritself.Moregenerally,the numberofbitsintheinputtoaproblemisoftenagoodmeasure ofthesizeoftheproblem. Tosaythattherunningtimeofanalgorithmis O (f(n))meansthatforlargevaluesof theproblemsize,n,therunningtimeofthealgorithmisnobi ggerthansomeconstanttimes f(n).(Morerigorously,thereisanumberCandapositiveint egerMsuchthatwhenevern isgreaterthanM,theruntimeislessthanorequaltoC*f(n). )Theconstanttakesinto accountdetailssuchasthespeedofthecomputeronwhichthe algorithmisrun;ifyouuse aslowercomputer,youmighthavetouseabiggerconstantint heformula,butchangingthe constantwon'tchangethebasicfactthattheruntimeis O (f(n)).Theconstantalsomakes itunnecessarytosaywhetherwearemeasuringtimeinsecond s,years,CPUcycles,orany otherunitofmeasure;achangefromoneunitofmeasuretoano therisjustmultiplicationby aconstant.Notealsothat O (f(n))doesn'tdependatallonwhathappensforsmallproble m sizes,onlyonwhathappensinthelongrunastheproblemsize increaseswithoutlimit. Tolookatasimpleexample,considertheproblemofaddingup allthenumbersinanarray. Theproblemsize,n,isthelengthofthearray.Using A asthenameofthearray,thealgorithm canbeexpressedinJavaas: total=0;for(inti=0;i<n;i++) total=total+A[i]; Thisalgorithmperformsthesameoperation, total=total+A[i] ,ntimes.Thetotal timespentonthisoperationisa*n,whereaisthetimeittake stoperformtheoperationonce. Now,thisisnottheonlythingthatisdoneinthealgorithm.T hevalueof i isincremented andiscomparedtoneachtimethroughtheloop.Thisaddsanad ditionaltimeofb*ntothe runtime,forsomeconstantb.Furthermore, i and total bothhavetobeinitializedtozero; thisaddssomeconstantamountctotherunningtime.Theexac trunningtimewouldthenbe (a+b)*n+c,wheretheconstantsa,b,andcdependonfactorss uchashowthecodeiscompiled <br /> <br /> PAGE 426<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 412 andwhatcomputeritisrunon.Usingthefactthatcislesstha norequaltoc*nforany positiveintegern,wecansaythattheruntimeislessthanor equalto(a+b+c)*n.Thatis, theruntimeislessthanorequaltoaconstanttimesn.Byden ition,thismeansthattherun timeforthisalgorithmis O (n). Ifthisexplanationistoomathematicalforyou,wecanjustn otethatforlargevaluesof n,thecintheformula(a+b)*n+cisinsignicantcomparedto theotherterm,(a+b)*n.We saythatcisa\lowerorderterm."Whendoingasymptoticanal ysis,lowerordertermscan bediscarded.Arough,butcorrect,asymptoticanalysisoft healgorithmwouldgosomething likethis:Eachiterationofthe for looptakesacertainconstantamountoftime.Thereare niterationsoftheloop,sothetotalruntimeisaconstantti mesn,pluslowerorderterms (toaccountfortheinitialization).Disregardingloweror derterms,weseethattheruntimeis O (n). Notethattosaythatanalgorithmhasruntime O (f(n))istosaythatitsruntimeisno biggerthansomeconstanttimesn(forlargevaluesofn). O (f(n))putsan upperlimit onthe runtime.However,theruntimecouldbesmaller,evenmuchsm aller.Forexample,iftherun timeis O (n),itwouldalsobecorrecttosaythattheruntimeis O (n 2 )oreven O (n 10 ).Ifthe runtimeislessthanaconstanttimesn,thenitiscertainlyl essthanthesameconstanttimes n 2 orn 10 Ofcourse,sometimesit'susefultohavea lowerlimit ontheruntime.Thatis,wewantto beabletosaythattheruntimeisgreaterthanorequaltosome constanttimesf(n)(forlarge valuesofn).Thenotationforthisisn(f(n)),read\Omegaof fofn."\Omega"isthenameof aletterintheGreekalphabet,andnistheuppercaseversion ofthatletter.(Tobetechnical, sayingthattheruntimeofanalgorithmisn(f(n))meansthat thereisapositivenumberC andapositiveintegerMsuchthatwhenevernisgreaterthanM ,theruntimeisgreaterthan orequaltoC*f(n).) O (f(n))tellsyousomethingaboutthemaximumamountoftimet hatyou mighthavetowaitforanalgorithmtonish;n(f(n))tellsyo usomethingabouttheminimum time. Thealgorithmforaddingupthenumbersinanarrayhasarunti methatisn(n)aswellas O (n).Whenanalgorithmhasaruntimethatisbothn(f(n))and O (f(n)),itsruntimeissaid tobe(f(n)),read\Thetaoffofn."(Thetaisanotherletter fromtheGreekalphabet.)To saythattheruntimeofanalgorithmis(f(n))meansthatfor largevaluesofn,theruntime isbetweena*f(n)andb*f(n),whereaandbareconstants(wit hbgreaterthana,andboth greaterthan0). Let'slookatanotherexample.Considerthealgorithmthatc anbeexpressedinJavainthe followingmethod: /** *SortsthenarrayelementsA[0],A[1],...,A[n-1]intoincr easingorder. */ publicstaticsimpleBubbleSort(int[]A,intn){ for(inti=0;i<n;i++){ //Donpassesthroughthearray... for(intj=0;j<n-1;j++){ if(A[j]>A[j+1]){ //A[j]andA[j+1]areoutoforder,soswapthem inttemp=A[j];A[j]=A[j+1];A[j+1]=temp; <br /> <br /> PAGE 427<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 413 } } } } Here,theparameternrepresentstheproblemsize.Theouter for loopinthemethodisexecuted ntimes.Eachtimetheouter for loopisexecuted,theinner for loopisexectuedn-1times,so the if statementisexecutedn*(n-1)times.Thisisn 2 -n,butsincelowerordertermsarenot signicantinanasymptoticanalysis,it'sgoodenoughtosa ythatthe if statementisexecuted aboutn 2 times.Inparticular,thetest A[j]>A[j+1] isexecutedaboutn 2 times,andthisfact byitselfisenoughtosaythattheruntimeofthealgorithmis n(n 2 ),thatis,theruntimeis atleastsomeconstanttimesn 2 .Furthermore,ifwelookatotheroperations|theassignmen t statements,incrementing i and j ,etc.|noneofthemareexecutedmorethann 2 times,sothe runtimeisalso O (n 2 ),thatis,theruntimeisnomorethansomeconstanttimesn 2 .Sinceit isbothn(n 2 )and O (n 2 ),theruntimeofthesimpleBubbleSortalgorithmis(n 2 ). Youshouldbeawarethatsomepeopleusethenotation O (f(n))asifitmeant(f(n)).That is,whentheysaythattheruntimeofanalgorithmis O (f(n)),theymeantosaythattherun timeisabout equal toaconstanttimesf(n).Forthat,theyshoulduse(f(n)).P roperly speaking, O (f(n))meansthattheruntimeislessthanaconstanttimesf( n),possiblymuch less. Sofar,myanalysishasignoredanimportantdetail.Wehavel ookedathowruntime dependsontheproblemsize,butinfacttheruntimeusuallyd ependsnotjustonthesizeof theproblembutonthespecicdatathathastobeprocessed.F orexample,theruntimeofa sortingalgorithmcandependontheinitialorderoftheitem sthataretobesorted,andnot justonthenumberofitems. Toaccountforthisdependency,wecanconsidereitherthe worstcase runtimeanalysis orthe averagecase runtimeanalysisofanalgorithm.Foraworstcaseruntimean alysis,we considerallpossibleproblemsofsizenandlookatthe longest possibleruntimeforallsuch problems.Foranaveragecaseanalysis,weconsiderallposs ibleproblemsofsizenandlookat the average oftheruntimesforallsuchproblems.Usually,theaveragec aseanalysisassumes thatallproblemsofsizenareequallylikelytobeencounter ed,althoughthisisnotalways realistic|orevenpossibleinthecasewherethereisaninn itenumberofdierentproblemsof agivensize. Inmanycases,theaverageandtheworstcaseruntimesarethe sametowithinaconstant multiple.Thismeansthatasfarasasymptoticanalysisisco ncerned,theyarethesame.That is,iftheaveragecaseruntimeis O (f(n))or(f(n)),thensoistheworstcase.However,lateri n thebook,wewillencounterafewcaseswheretheaverageandw orstcaseasymptoticanalyses dier. So,whatdoyoureallyhavetoknowaboutanalysisofalgorith mstoreadtherestofthis book?Wewillnotdoanyrigorousmathematicalanalysis,but youshouldbeabletofollow informaldiscussionofsimplecasessuchastheexamplestha twehavelookedatinthissection. Mostimportant,though,youshouldhaveafeelingforexactl ywhatitmeanstosaythatthe runningtimeofanalgorithmis O (f(n))or(f(n))forsomecommonfunctionsf(n).Themain pointisthatthesenotationsdonottellyouanythingaboutt heactualnumericalvalueofthe runningtimeofthealgorithmforanyparticularcase.Theyd onottellyouanythingatall <br /> <br /> PAGE 428<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 414 abouttherunningtimeforsmallvaluesofn.Whattheydotell youissomethingaboutthe rateofgrowth oftherunningtimeasthesizeoftheproblemincreases. Supposeyoucomparetwoalgorithmthatsolvethesameproble m.Theruntimeofone algorithmis(n 2 ),whiletheruntimeofthesecondalgorithmis(n 3 ).Whatdoesthistell you?Ifyouwanttoknowwhichalgorithmwillbefasterforsom eparticularproblemofsize, say,100,nothingiscertain.Asfarasyoucantelljustfromt heasymptoticanalysis,either algorithmcouldbefasterforthatparticularcase|orin any particularcase.Butwhatyoucan sayforsureisthatifyoulookatlargerandlargerproblems, youwillcometoapointwherethe (n 2 )algorithmisfasterthanthe(n 3 )algorithm.Furthermore,asyoucontinuetoincrease theproblemsize,therelativeadvantageofthe(n 2 )algorithmwillcontinuetogrow.There willbevaluesofnforwhichthe(n 2 )algorithmisathousandtimesfaster,amilliontimes faster,abilliontimesfaster,andsoon.Thisisbecausefor anypositiveconstantsaandb,the functiona*n 3 growsfaster thanthefunctionb*n 2 asngetslarger.(Mathematically,thelimit oftheratioofa*n 3 tob*n 2 isinniteasnapproachesinnity.) Thismeansthatfor\large"problems,a(n 2 )algorithmwilldenitelybefasterthana (n 3 )algorithm.Youjustdon'tknow|basedontheasymptoticana lysisalone|exactlyhow large\large"hastobe.Inpractice,infact,itislikelytha tthe(n 2 )algorithmwillbefaster evenforfairlysmallvaluesofn,andabsentotherinformati onyouwouldgenerallyprefera (n 2 )algorithmtoa(n 3 )algorithm. So,tounderstandandapplyasymptoticanalysis,itisessen tialtohavesomeideaofthe ratesofgrowthofsomecommonfunctions.Forthepowerfunct ionsn,n 2 ,n 3 ,n 4 ,...,thelarger theexponent,thegreatertherateofgrowthofthefunction. Exponentialfunctionssuchas2 n and10 n ,wherethenisintheexponent,haveagrowthratethatisfast erthanthatofanypower function.Infact,exponentialfunctionsgrowsoquicklyth atanalgorithmwhoseruntimegrows exponentiallyisalmostcertainlyimpracticalevenforrel ativelymodestvaluesofn,becausethe runningtimeisjusttoolong.Anotherfunctionthatoftentu rnsupinasymptoticanalysisis thelogarithmfunction,log(n).Thereareactuallymanydi erentlogarithmfunctions,butthe onethatisusuallyusedincomputerscienceistheso-called logarithmtothebasetwo,whichis denedbythefactthatlog(2 x )=xforanynumberx.(Usually,thisfunctioniswrittenlog 2 (n), butIwillleaveoutthesubscript2,sinceIwillonlyusetheb ase-twologarithminthisbook.) Thelogarithmfunctiongrowsveryslowly.Thegrowthrateof log(n)ismuchsmallerthanthe growthrateofn.Thegrowthrateofn*log(n)isalittlelarge rthanthegrowthrateofn,but muchsmallerthanthegrowthrateofn 2 .Thefollowingtableshouldhelpyouunderstandthe dierencesamongtheratesofgrowsofvariousfunctions: } ~ ~ €  ~ } ‚ € } ‚ ‚ ‚ ‚ ‚ ‚ } ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ~ ƒ } ‚ € ‚ „ ‚ ~ „ ƒ € ‚ ƒ } ‚ € ‚ } … … „ }  ~ ƒ € … ƒ … † „  € ƒ  €  ~ ‚ … ~ ~   „ ~ } ‚ ƒ  † ~ } ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ } ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‚ ‡ ‚ } ‚ ‡ † „ € ‡ ‚ } ‚ € ‡  ‚ } † „ ‡ } „ „ † † † † ‡ „ ˆ ‰ Š ‹ Œ ˆ  ˆ Ž ‰ Š ‹ Œ ˆ  ˆ ˆ  ‰ Š ‹ Œ ˆ   Thereasonthatlog(n)showsupsooftenisbecauseofitsasso ciationwithmultiplyingand dividingbytwo:Supposeyoustartwiththenumbernanddivid eitby2,thendivideby2 again,andsoon,untilyougetanumberthatislessthanorequ alto1.Thenthenumberof divisionsisequal(tothenearestinteger)tolog(n). <br /> <br /> PAGE 429<br /> <br /> CHAPTER8.CORRECTNESSANDROBUSTNESS 415 Asanexample,considerthebinarysearchalgorithmfrom Subsection7.4.1 .Thisalgorithm searchesforaniteminasortedarray.Theproblemsize,n,ca nbetakentobethelengthof thearray.Eachstepinthebinarysearchalgorithmdividest henumberofitemsstillunder considerationby2,andthealgorithmstopswhenthenumbero fitemsunderconsiderationis lessthanorequalto1(orsooner).Itfollowsthatthenumber ofstepsforanarrayoflengthn isatmostlog(n).Thismeansthattheworst-caseruntimefor binarysearchis(log(n)).(The averagecaseruntimeisalso(log(n)).)Bycomparison,the linearsearchalgorithm,which wasalsopresentedin Subsection7.4.1 hasaruntimethatis(n).Thenotationgivesus aquantitativewaytoexpressandtounderstandthefactthat binarysearchis\muchfaster" thanlinearsearch. Inbinarysearch,eachstepofthealgorithmdividestheprob lemsizeby2.Itoftenhappens thatsomeoperationinanalgorithm(notnecessarilyasingl estep)dividestheproblemsize by2.Wheneverthathappens,thelogarithmfunctionislikel ytoshowupinanasymptotic analysisoftheruntimeofthealgorithm. AnalysisofAlgorithmsisalarge,fascinatingeld.Wewill onlyuseafewofthemostbasic ideasfromthiseld,buteventhosecanbeveryhelpfulforun derstandingthedierencesamong algorithms. <br /> <br /> PAGE 430<br /> <br /> Exercises 416 ExercisesforChapter8 1. Writeaprogramthatusesthefollowingsubroutine,from Subsection8.3.3 ,tosolveequa(solution) tionsspeciedbytheuser. /** *Returnsthelargerofthetworootsofthequadraticequatio n *A*x*x+B*x+C=0,providedithasanyroots.IfA==0or*ifthediscriminant,B*B-4*A*C,isnegative,thenanexcep tion *oftypeIllegalArgumentExceptionisthrown.*/ staticpublicdoubleroot(doubleA,doubleB,doubleC) throwsIllegalArgumentException{ if(A==0){ thrownewIllegalArgumentException("Acan'tbezero."); }else{ doubledisc=B*B-4*A*C;if(disc<0) thrownewIllegalArgumentException("Discriminant<zero ."); return(-B+Math.sqrt(disc))/(2*A); } } Yourprogramshouldallowtheusertospecifyvaluesfor A B ,and C .Itshouldcallthe subroutinetocomputeasolutionoftheequation.Ifnoerror occurs,itshouldprintthe root.However,ifanerroroccurs,yourprogramshouldcatch thaterrorandprintanerror message.Afterprocessingoneequation,theprogramshould askwhethertheuserwants toenteranotherequation.Theprogramshouldcontinueunti ltheuseranswersno. 2. Asdiscussedin Section8.1 ,valuesoftype int arelimitedto32bits.Integersthatare (solution) toolargetoberepresentedin32bitscannotbestoredinan int variable.Javahasa standardclass, java.math.BigInteger ,thataddressesthisproblem.Anobjectoftype BigInteger isanintegerthatcanbearbitrarilylarge.(Themaximumsiz eislimitedonly bytheamountofmemoryonyourcomputer.)Since BigIntegers areobjects,theymust bemanipulatedusinginstancemethodsfromthe BigInteger class.Forexample,youcan't addtwo BigIntegers withthe + operator.Instead,if N and M arevariablesthatreferto BigIntegers ,youcancomputethesumof N and M withthefunctioncall N.add(M) .The valuereturnedbythisfunctionisanew BigInteger objectthatisequaltothesumof N and M The BigInteger classhasaconstructor newBigInteger(str) ,where str isastring. Thestringmustrepresentaninteger,suchas\3"or\3984982 3783783283733".Ifthestring doesnotrepresentalegalinteger,thentheconstructorthr owsa NumberFormatException Therearemanyinstancemethodsinthe BigInteger class.Hereareafewthatyouwill ndusefulforthisexercise.Assumethat N and M arevariablesoftype BigInteger N.add(M) |afunctionthatreturnsa BigInteger representingthesumof N and M N.multiply(M) |afunctionthatreturnsa BigInteger representingtheresultof multiplying N times M <br /> <br /> PAGE 431<br /> <br /> Exercises 417 N.divide(M) |afunctionthatreturnsa BigInteger representingtheresultofdividing N by M ,discardingtheremainder. N.signum() |afunctionthatreturnsanordinary int .Thereturnedvaluerepresents thesignoftheinteger N .Thereturnedvalueis1if N isgreaterthanzero.Itis-1if N islessthanzero.Anditis0if N iszero. N.equals(M) |afunctionthatreturnsa boolean valuethatis true if N and M have thesameintegervalue. N.toString() |afunctionthatreturnsa String representingthevalueof N N.testBit(k) |afunctionthatreturnsa boolean value.Theparameter k isaninteger.Thereturnvalueis true ifthe k -thbitin N is1,anditis false ifthe k -thbitis0. Bitsarenumberedfromrighttoleft,startingwith0.Testin g\ if(N.testBit(0)) isaneasywaytocheckwhether N isevenorodd. N.testBit(0) is true ifandonly if N isanoddnumber. Forthisexercise,youshouldwriteaprogramthatprints 3N+1 sequenceswithstarting valuesspeciedbytheuser.Inthisversionoftheprogram,y oushoulduse BigIntegers torepresentthetermsinthesequence.Youcanreadtheuser' sinputintoa String with the TextIO.getln() function.Usetheinputvaluetocreatethe BigInteger objectthat representsthestartingpointofthe 3N+1 sequence.Don'tforgettocatchandhandlethe NumberFormatException thatwilloccuriftheuser'sinputisnotalegalinteger!You shouldalsocheckthattheinputnumberisgreaterthanzero. Iftheuser'sinputisle