с,,.,* * ш Ш :?mmFHOW T O P R O G R A MEIGHTH EDITIONPearson International EditionPaul DeitelDeitel & Associates, Inc.Harvey DeitelDeitel & Associates, Inc.ТЖГГШ!Upper Saddle River, New Jersey 07458

ContentsPrefaceBefore You BeginxxvxxxixIntroduction to Computers, the Internet andthe Hardware and SoftwareComputer OrganizationEarly Operating SystemsPersonal, Distributed and Client/Server ComputingThe Internet and the World Wide WebMachine Languages, Assembly Languages and High-Level LanguagesHistory of С and C History of JavaJava Class LibrariesFortran, C O B O L , Pascal and AdaBASIC, Visual Basic, Visual C , C# and .NETTypical Java Development EnvironmentNotes about Java and Java How to Program, Eighth EditionTest-Driving a Java ApplicationSoftware Engineering Case Study: Introduction to Object Technologyand the U M LWeb 2.0Software TechnologiesWrap-UpWeb Resources2Introduction to Java Applications2. u r First Program in Java: Printing a Line of TextModifying Our First Java ProgramDisplaying Text with pri ntfAnother Application: Adding Integers234566788910111114152024252626373838444647

xContents2. ConceptsArithmeticDecision Making: Equality and Relational OperatorsWrap-Up3Introduction to Classes and Classes, Objects, Methods and Instance VariablesDeclaring a Class with a Method and Instantiating an Object of a ClassDeclaring a Method with a ParameterInstance Variables, set Methods and get MethodsPrimitive Types vs. Reference TypesInitializing Objects with ConstructorsFloating-Point Numbers and Type double(Optional) GUI and Graphics Case Study: Using Dialog BoxesWrap-Up4Control Statements: Part 15IntroductionAlgorithmsPseudocodeControl Structuresi f Single-Selection Statementi f. .el se Double-Selection Statementwhi l e Repetition StatementFormulating Algorithms: Counter-Controlled RepetitionFormulating Algorithms: Sentinel-Controlled RepetitionFormulating Algorithms: Nested Control StatementsCompound Assignment OperatorsIncrement and Decrement OperatorsPrimitive Types(Optional) GUI and Graphics Case Study: Creating Simple DrawingsWrap-Up5Control Statements: Part of Counter-Controlled Repetitionfor Repetition StatementExamples Using the for Statementdo.while Repetition Statementswitch Multiple-Selection Statementbreak and continue StatementsLogical OperatorsStructured Programming 176178184

Contentsxi5.105.11(Optional) GUI and Graphics Case Study: Drawing Rectangles and OvalsWrap-Up1891926Methods: A Deeper Look6. Modules in Javas t a t i с Methods, s t a t i с Fields and Class MathDeclaring Methods with Multiple ParametersNotes on Declaring and Using MethodsMethod-Call Stack and Activation RecordsArgument Promotion and CastingJava API PackagesCase Study: Random-Number Generation6.9.1Generalized Scaling and Shifting of Random Numbers6.9.2Random-Number Repeatability for Testing and DebuggingCase Study: A Game of Chance; Introducing EnumerationsScope of DeclarationsMethod Overloading(Optional) GUI and Graphics Case Study: Colors and Filled ShapesWrap-Up6. and Ar r a y L i s t 157.16IntroductionArraysDeclaring and Creating ArraysExamples Using ArraysCase Study: Card Shuffling and Dealing SimulationEnhanced for StatementPassing Arrays to MethodsCase Study: Class GradeBook Using an Array to Store GradesMultidimensional ArraysCase Study: Class GradeBook Using a Two-Dimensional ArrayVariable-Length Argument ListsUsing Command-Line ArgumentsClass ArraysIntroduction to Collections and Class ArrayLi s t(Optional) GUI and Graphics Case Study: Drawing ArcsWrap-Up8Classes and Objects: A Deeper Look8. me Class Case StudyControlling Access to MembersReferring to the Current Object's Members with the t h i s 87289292295316317317321322

8.168.17Time Class Case Study: Overloaded ConstructorsDefault and No-Argument ConstructorsNotes on Set and Get MethodsCompositionEnumerationsGarbage Collection and Method fi nal i zes t a t i c Class Memberss t a t i c Importfi nal Instance VariablesTime Class Case Study: Creating PackagesPackage Access(Optional) GUI and Graphics Case Study: Using Objects with GraphicsWrap-Up9Object-Oriented Programming: Inheritance9. and Subclassesp r o t e c t e d MembersRelationship between Superclasses and Subclasses9.4.1Creating and Using a Commi ssi onEmpl oyee Class9.4.2Creating and Using a BasePlusCommi ssi onEmpl oyee Class9.4.3Creating a Commi s s i onEmpl oyee—BasePlusCommi ssi onEmpl oyeeInheritance Hierarchy9.4.4Commi ssi onEmpl oyee-BasePl usCommi ssi onEmpl oyee InheritanceHierarchy Using p r o t e c t e d Instance Variables9.4.5Commi ssi onEmpl oyee-BasePl usCommi ssi onEmpl oyee InheritanceHierarchy Using pri vate Instance VariablesConstructors in SubclassesSoftware Engineering with InheritanceObject Class(Optional) G U I and Graphics Case Study: Displaying Text andImages Using LabelsWrap-Up9. Object-Oriented Programming: rphism ExamplesDemonstrating Polymorphic BehaviorAbstract Classes and MethodsCase Study: Payroll System Using Polymorphism10.5.1 Abstract Superclass Employee10.5.2 Concrete Subclass Sal ariedEmpl oyee10.5.3 Concrete Subclass Hour!yEmployee10.5-4 Concrete Subclass Commi ssi onEmpl oyee10.5.5 Indirect Concrete Subclass BasePlusCommi ssi onEmpl 406408409412414415417

Contents10.5.610.5.710.610.710.810.9Polymorphie Processing, Operator i nstanceof and DowncastingSummary of the Allowed Assignments Between Superclass andSubclass Variablesfi nal Methods and ClassesCase Study: Creating and Using Interfaces10.7.1 Developing a Payabl e Hierarchy10.7.2 Interface Payabl e10.7.3 Class Invoice10.7.4 Modifying Class Employee to Implement Interface Payable10.7.5 Modifying Class Sal ari edEmpl oyee for Use in the Payabl eHierarchy10.7.6 Using Interface Payable to Process Invoices and EmployeesPolymorphically10.7.7 Common Interfaces of the Java API(Optional) GUI and Graphics Case Study: Drawing with PolymorphismWrap-Up1 1 Exception 1.1111.1211.1311.14IntroductionError-Handling OverviewExample: Divide by Zero without Exception HandlingExample: Handling Ari thmeti cExcepti ons andInputMismatchExceptionsWhen to Use Exception HandlingJava Exception Hierarchyf i n a l l y BlockStack UnwindingprintStackTrace, getStackTrace and getMessageChained ExceptionsDeclaring New Exception TypesPreconditions and PostconditionsAssertionsWrap-Up12 ATM Case Study, Part 1: Object-OrientedDesign with the UML12.112.212.312.412.512.612.712.8Case Study IntroductionExamining the Requirements DocumentIdentifying the Classes in a Requirements DocumentIdentifying Class AttributesIdentifying Objects'States and ActivitiesIdentifying Class OperationsIndicating Collaboration Among 70476477477485491496500506513

xivContentsI 3 ATM Case Study Part 2: implementing anObject-Oriented Design13.113.213.313.4IntroductionStarting to Program the Classes of the ATM SystemIncorporating Inheritance and Polymorphism into the ATM System13.3.1 Implementing the ATM System Design (Incorporating Inheritance)ATM Case Study Implementation13.4.1 Class ATM13.4.2 Class Screen13.4.3 Class Keypad13.4.413.5Class CashDispenser13.4.5 Class DepositSlot13.4.6 Class Account13.4.7 Class BankDatabase13.4.8 Class Transaction13.4.9 Class Balancelnqui ry13.4.10 Class Withdrawal13.4.11 Class Deposit13.4.12 Class 3853954154354554655055355314 GUI Components: Part 1214.1314.1414.1514.1614.1714.18IntroductionJava's New Nimbus Look-and-FeelSimple GUI-Based Input/Output with JOptionPaneOverview of Swing ComponentsDisplaying Text and Images in a WindowText Fields and an Introduction to Event Handling with Nested ClassesCommon GUI Event Types and Listener InterfacesHow Event Handling WorksJButtonButtons That Maintain State14.10.1 JCheckBox14.10.2 DRadioButtonJComboBox and Using an Anonymous Inner Class for Event HandlingJListMultiple-Selection ListsMouse Event HandlingAdapter Classes3 Panel Subclass for Drawing with the MouseKey Event HandlingIntroduction to Layout Managers14.18.1 FlowLayout14.18.2 BorderLayout14.18.3 91593596600604607610612615618

Contents14.19 Using Panels to Manage More Complex Layouts14.20 JTextArea14.21 Wrap-Up15 Graphics and Java 2D aphics Contexts and Graphics ObjectsColor ControlManipulating FontsDrawing Lines, Rectangles and OvalsDrawing ArcsDrawing Polygons and PolylinesJava 2 D APIWrap-Up16 Strings, Characters and Regular ctionFundamentals of Characters and StringsClass S t r i n g16.3.1 S t r i n g Constructors16.3.2 S t r i n g Methods length, charAt and getChars16.3.3 Comparing Strings16.3.4 Locating Characters and Substrings in Strings16.3.5 Extracting Substrings from Strings16.3.6 Concatenating Strings16.3.7 Miscellaneous S t r i n g Methods16.3.8 S t r i n g Method valueOfClass S t r i n g B u i l d e r16.4.1 S t r i n g B u i l d e r Constructors16.4.2 S t r i n g B u i l d e r Methods length, capacity, setLength andensureCapacity16.4.3 S t r i n g B u i l d e r Methods charAt, setCharAt, getChars andreverse16.4.4 S t r i n g B u i l d e r append Methods16.4.5 S t r i n g B u i l d e r Insertion and Deletion MethodsClass CharacterTokenizing StringsRegular Expressions, Class P a t t e r n and Class 698700701703707708717S 7 Files, Streams and Object Serialization72817.117.2729730IntroductionData Hierarchy

xvi17.317.417.5Contents17.8Files and StreamsClass FileSequential-Access Text Files17.5.1 Creating a Sequential-Access Text File17.5.2 Reading Data from a Sequential-Access Text File17.5.3 Case Study: A Credit-Inquiry Program17.5.4 Updating Sequential-Access FilesObject Serialization17.6.1 Creating a Sequential-Access File Using Object Serialization17.6.2 Reading and Deserializing Data from a Sequential-Access FileAdditional j ava. i о Classes17.7.1 Interfaces and Classes for Byte-Based Input and Output17.7.2 Interfaces and Classes for Character-Based Input and OutputOpening Files with 3 Fi .518.618.718.818.918.10IntroductionRecursion ConceptsExample Using Recursion: FactorialsExample Using Recursion: Fibonacci SeriesRecursion and the Method-Call StackRecursion vs. IterationTowers of HanoiFractalsRecursive BacktrackingWrap-Up19Searching, Sorting and Big О19.119.2IntroductionSearching Algorithms19.2.1 Linear Search19.2.2 Binary SearchSorting Algorithms19.3.1 Selection Sort19.3.2 Insertion Sort19.3.3 Merge SortWrap-Up17.617.719.319.42 0 Generic Collections20.120.220.3IntroductionCollections OverviewType-Wrapper Classes for Primitive 2822826830836841842842843

1320.1420.1520.16Autoboxing and Auto-UnboxingInterface Col 1 ecti on and Class Col 1 ecti onsLists20.6.1 ArrayList and Iterator84484484584620.6.2848LinkedListCollections Methods20.7.1 Methodsort20.7.2 Method shuffle20.7.3 Methods reverse, f i l l , copy, max and min20.7.4 Method binarySearch20.7.5 Methods addAll, frequency and disjointStack Class of Package Java, utilClass PriorityQueue and Interface QueueSetsMapsProperties ClassSynchronized CollectionsUnmodifiable CollectionsAbstract ImplementationsWrap-Up2 S Generic Classes and Methods21.121.221.321.4IntroductionMotivation for Generic MethodsGeneric Methods: Implementation and Compile-Time TranslationAdditional Compile-Time Translation Issues: Methods That Use a TypeParameter as the Return Type21.5 Overloading Generic Methods21.6 Generic Classes21.7 Raw Types21.8 Wildcards in Methods That Accept Type Parameters21.9 Generics and Inheritance: Notes21.10 Wrap-Up2 2 Custom Generic Data oductionSelf-Referential ClassesDynamic Memory AllocationLinked 8912913917918918919920930934937943

xvüiContents2 3 Applets and Java Web ample Applets Provided with the J D KSimple Java Applet: Drawing a String23.3.1 Executing WeicomeApplet in the appletviewer23.3.2 Executing an Applet in a Web BrowserApplet Life-Cycle MethodsInitializing an Instance Variable with Method i ni tSandbox Security ModelJava W e b Start and the Java Network Launch Protocol (JNLP)23.7.1 Packaging the DrawTest Applet for Use with Java Web Start23.7.2 JNLP Document for the DrawTest 742 4 Multimedia: Applets and uctionLoading, Displaying and Scaling ImagesAnimating a Series of ImagesImage MapsLoading and Playing Audio ClipsPlaying Video and Other Media with Java Media FrameworkWrap-UpWeb Resources2 5 GUI Component