Share E-Book

Java How to Program, Late Objects, Global Edition (Harvey Deitel, Paul J. Deitel) (z-library.sk, 1lib.sk, z-lib.sk)

Author Harvey Deitel, Paul J. Deitel

java
Language English

Unparalleled breadth and depth of object-oriented programming conceptsThe Deitels’ groundbreaking How to Program series offers unparalleled breadth and depth of programming fundamentals, object-oriented programming concepts and intermediate-level topics for further study. Java How to Program, Late Objects, 11th Edition, presents leading-edge computing technologies using the Deitel signature live-code approach, which demonstrates concepts in hundreds of complete working programs. The 11th Edition presents updated coverage of Java SE 8 and new Java SE 9 capabilities, including JShell, the Java Module System, and other key Java 9 topics. [Java How to Program, Early Objects, 11th Edition also is available.

Format PDF
Size 8.4 MB
1
Views
0
Downloads
0.00
Total Donations
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
DIGITAL RESOURCES FOR STUDENTS Use the login name and password you created during registration to start using the digital resources that accompany your textbook. IMPORTANT This prepaid subscription does not include access to MyProgrammingLab, which is available at www.myprogramminglab.com for purchase. This access code can only be used once. This subscription is valid for 12 months upon activation and is not transferable. For technical support go to https://support.pearson.com/getsupport Your new textbook provides 12-month access to digital resources that may include VideoNotes (step-by-step video tutorials on programming concepts), source code, web chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of resources. Follow the instructions below to register for the Companion Website for Paul Deitel and Harvey Deitel’s Java™ How to Program, Late Objects, Eleventh Edition, Global Edition. 1 Gotowww.pearsonglobaleditions.com/deitel. 2 Enterthetitleofyourtextbookorbrowsebyauthorname. 3 ClickCompanionWebsite. 4 ClickRegisterandfollowtheon-screeninstructionstocreatealoginnameandpassword. ISSLDO-WHIFF-SAURY-LAMBS-DOLBY-LIKES
Page 3
(This page has no text content)
Page 4
(This page has no text content)
Page 5
Paul Deitel Deitel & Associates, Inc. Harvey Deitel Deitel & Associates, Inc.
Page 6
Senior Vice President Courseware Portfolio Management: Marcia J. Horton Director, Portfolio Management: Engineering, Computer Science & Global Editions: Julian Partridge Higher Ed Portfolio Management: Tracy Johnson (Dunkelberger) Portfolio Management Assistant: Kristy Alaura Acquisitions Editor, Global Edition: Aditee Agarwal Managing Content Producer: Scott Disanno Content Producer: Robert Engelhardt Senior Project Editor, Global Edition: K.K. Neelakantan Web Developer: Steve Wright Rights and Permissions Manager: Ben Ferrini Manufacturing Buyer, Higher Ed, Lake Side Communications Inc (LSC): Maura Zaldivar-Garcia Senior Manufacturing Controller, Global Edition: Kay Holman Inventory Manager: Ann Lam Product Marketing Manager: Yvonne Vannatta Field Marketing Manager: Demetrius Hall Marketing Assistant: Jon Bryant Manager, Media Production, Global Edition: Vikram Kumar Cover Designer: Lumina Datamatics, Inc. Cover Art: ©MchlSkhrv/Shutterstock Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on page 6. Java™ and Netbeans™ screenshots ©2017 by Oracle Corporation, all rights reserved. Reprinted with permission. Pearson Education Limited KAO Two KAO Park Harlow CM17 9SR United Kingdom and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2020 The rights of Paul Deitel and Harvey Deitel to be identified as the authors of this work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988. Authorized adaptation from the United States edition, entitled Java How to Program, Late Objects, 11thEdition, ISBN 978-0-13-479140-1 by Paul Deitel and Harvey Deitel published by Pearson Education © 2020. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions department, please visit www.pearsoned.com/permissions. This eBook is a standalone product and may or may not include all assets that were part of the print version. It also does not provide access to other Pearson digital products like MyLab and Mastering. The publisher reserves the right to remove any material in this eBook at any time. British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library ISBN 10: 1-292-27373-9 ISBN 13: 978-1-292-27373-0 eBook ISBN 13: 978-1-292-27374-7 eBook formatted by GEX Inc.
Page 7
In memory of Dr. Henry Heimlich: Barbara Deitel used your Heimlich maneuver to save Abbey Deitel’s life. Our family is forever grateful to you. Harvey, Barbara, Paul and Abbey Deitel
Page 8
Trademarks DEITEL and the double-thumbs-up bug are registered trademarks of Deitel and Associates, Inc. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/ or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective sup- pliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typograph- ical errors. Changes are periodically added to the information herein. Microsoft and/or its respective sup- pliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. UNIX is a registered trademark of The Open Group. Apache is a trademark of The Apache Software Foundation. CSS and XML are registered trademarks of the World Wide Web Consortium. Firefox is a registered trademark of the Mozilla Foundation. Google is a trademark of Google, Inc. Mac and macOS are trademarks of Apple Inc., registered in the U.S. and other countries. Linux is a registered trademark of Linus Torvalds. All trademarks are property of their respective owners. Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Page 9
The online chapters and appendices listed at the end of this Table of Contents are located on the book’s Companion Website (http://www.pearsonglobaleditions.com)—see the inside front cover of your book for details. Foreword 25 Preface 27 Before You Begin 47 1 Introduction to Computers, the Internet and Java 53 1.1 Introduction 54 1.2 Hardware and Software 56 1.2.1 Moore’s Law 56 1.2.2 Computer Organization 57 1.3 Data Hierarchy 59 1.4 Machine Languages, Assembly Languages and High-Level Languages 61 1.5 Basic Introduction to Object Terminology 62 1.5.1 Automobile as an Object 63 1.5.2 Methods and Classes 63 1.5.3 Instantiation 63 1.5.4 Reuse 63 1.5.5 Messages and Method Calls 64 1.5.6 Attributes and Instance Variables 64 1.5.7 Encapsulation and Information Hiding 64 1.5.8 Inheritance 64 1.5.9 Interfaces 65 1.5.10 Object-Oriented Analysis and Design (OOAD) 65 1.5.11 The UML (Unified Modeling Language) 65 1.6 Operating Systems 66 1.6.1 Windows—A Proprietary Operating System 66 1.6.2 Linux—An Open-Source Operating System 66 1.6.3 Apple’s macOS and Apple’s iOS for iPhone®, iPad® and iPod Touch® Devices 67 1.6.4 Google’s Android 67 Contents
Page 10
8 Contents 1.7 Programming Languages 68 1.8 Java 70 1.9 A Typical Java Development Environment 71 1.10 Test-Driving a Java Application 74 1.11 Internet and World Wide Web 78 1.11.1 Internet: A Network of Networks 79 1.11.2 World Wide Web: Making the Internet User-Friendly 79 1.11.3 Web Services and Mashups 79 1.11.4 Internet of Things 80 1.12 Software Technologies 81 1.13 Getting Your Questions Answered 83 2 Introduction to Java Applications; Input/Output and Operators 87 2.1 Introduction 88 2.2 Your First Program in Java: Printing a Line of Text 88 2.2.1 Compiling the Application 92 2.2.2 Executing the Application 93 2.3 Modifying Your First Java Program 94 2.4 Displaying Text with printf 96 2.5 Another Application: Adding Integers 97 2.5.1 import Declarations 98 2.5.2 Declaring and Creating a Scanner to Obtain User Input from the Keyboard 98 2.5.3 Prompting the User for Input 99 2.5.4 Declaring a Variable to Store an Integer and Obtaining an Integer from the Keyboard 99 2.5.5 Obtaining a Second Integer 100 2.5.6 Using Variables in a Calculation 100 2.5.7 Displaying the Calculation Result 100 2.5.8 Java API Documentation 101 2.5.9 Declaring and Initializing Variables in Separate Statements 101 2.6 Memory Concepts 101 2.7 Arithmetic 102 2.8 Decision Making: Equality and Relational Operators 106 2.9 Wrap-Up 109 3 Control Statements: Part 1; Assignment, ++ and -- Operators 120 3.1 Introduction 121 3.2 Algorithms 121 3.3 Pseudocode 122 3.4 Control Structures 122 3.4.1 Sequence Structure in Java 123
Page 11
Contents 9 3.4.2 Selection Statements in Java 124 3.4.3 Iteration Statements in Java 124 3.4.4 Summary of Control Statements in Java 124 3.5 if Single-Selection Statement 125 3.6 if…else Double-Selection Statement 126 3.6.1 Nested if…else Statements 127 3.6.2 Dangling-else Problem 128 3.6.3 Blocks 128 3.6.4 Conditional Operator (?:) 129 3.7 while Iteration Statement 129 3.8 Formulating Algorithms: Counter-Controlled Iteration 131 3.9 Formulating Algorithms: Sentinel-Controlled Iteration 135 3.10 Formulating Algorithms: Nested Control Statements 142 3.11 Compound Assignment Operators 146 3.12 Increment and Decrement Operators 147 3.13 Primitive Types 150 3.14 Wrap-Up 150 4 Control Statements: Part 2; Logical Operators 164 4.1 Introduction 165 4.2 Essentials of Counter-Controlled Iteration 165 4.3 for Iteration Statement 166 4.4 Examples Using the for Statement 170 4.4.1 Application: Summing the Even Integers from 2 to 20 171 4.4.2 Application: Compound-Interest Calculations 172 4.5 do…while Iteration Statement 175 4.6 switch Multiple-Selection Statement 176 4.7 break and continue Statements 182 4.7.1 break Statement 182 4.7.2 continue Statement 182 4.8 Logical Operators 183 4.8.1 Conditional AND (&&) Operator 184 4.8.2 Conditional OR (||) Operator 184 4.8.3 Short-Circuit Evaluation of Complex Conditions 185 4.8.4 Boolean Logical AND (&) and Boolean Logical Inclusive OR (|) Operators 185 4.8.5 Boolean Logical Exclusive OR (^) 186 4.8.6 Logical Negation (!) Operator 186 4.8.7 Logical Operators Example 187 4.9 Structured-Programming Summary 189 4.10 Wrap-Up 194 5 Methods 204 5.1 Introduction 205
Page 12
10 Contents 5.2 Program Units in Java 205 5.3 static Methods, static Variables and Class Math 207 5.4 Declaring Methods 209 5.5 Notes on Declaring and Using Methods 213 5.6 Method-Call Stack and Activation Records 214 5.6.1 Method-Call Stack 214 5.6.2 Stack Frames 214 5.6.3 Local Variables and Stack Frames 215 5.6.4 Stack Overflow 215 5.7 Argument Promotion and Casting 215 5.8 Java API Packages 216 5.9 Case Study: Secure Random-Number Generation 218 5.10 Case Study: A Game of Chance; Introducing enums 223 5.11 Scope of Declarations 227 5.12 Method Overloading 230 5.12.1 Declaring Overloaded Methods 230 5.12.2 Distinguishing Between Overloaded Methods 231 5.12.3 Return Types of Overloaded Methods 231 5.13 Wrap-Up 232 6 Arrays and ArrayLists 245 6.1 Introduction 246 6.2 Primitive Types vs. Reference Types 247 6.3 Arrays 247 6.4 Declaring and Creating Arrays 249 6.5 Examples Using Arrays 250 6.5.1 Creating and Initializing an Array 250 6.5.2 Using an Array Initializer 251 6.5.3 Calculating the Values to Store in an Array 252 6.5.4 Summing the Elements of an Array 253 6.5.5 Using Bar Charts to Display Array Data Graphically 254 6.5.6 Using the Elements of an Array as Counters 256 6.5.7 Using Arrays to Analyze Survey Results 257 6.6 Exception Handling: Processing the Incorrect Response 259 6.6.1 The try Statement 259 6.6.2 Executing the catch Block 259 6.6.3 toString Method of the Exception Parameter 260 6.7 Enhanced for Statement 260 6.8 Passing Arrays to Methods 261 6.9 Pass-By-Value vs. Pass-By-Reference 264 6.10 Multidimensional Arrays 264 6.10.1 Arrays of One-Dimensional Arrays 265 6.10.2 Two-Dimensional Arrays with Rows of Different Lengths 265 6.10.3 Creating Two-Dimensional Arrays with Array-Creation Expressions 266
Page 13
Contents 11 6.10.4 Two-Dimensional Array Example: Displaying Element Values 266 6.10.5 Common Multidimensional-Array Manipulations Performed with for Statements 267 6.11 Variable-Length Argument Lists 268 6.12 Using Command-Line Arguments 269 6.13 Class Arrays 271 6.14 Introduction to Collections and Class ArrayList 274 6.15 Wrap-Up 278 7 Introduction to Classes and Objects 298 7.1 Introduction 299 7.2 Instance Variables, set Methods and get Methods 300 7.2.1 Account Class with an Instance Variable, and set and get Methods 300 7.2.2 AccountTest Class That Creates and Uses an Object of Class Account 302 7.2.3 Compiling and Executing an App with Multiple Classes 305 7.2.4 Account UML Class Diagram 305 7.2.5 Additional Notes on Class AccountTest 306 7.2.6 Software Engineering with private Instance Variables and public set and get Methods 307 7.3 Default and Explicit Initialization for Instance Variables 308 7.4 Account Class: Initializing Objects with Constructors 309 7.4.1 Declaring an Account Constructor for Custom Object Initialization 309 7.4.2 Class AccountTest: Initializing Account Objects When They’re Created 310 7.5 Account Class with a Balance 312 7.5.1 Account Class with a balance Instance Variable of Type double 312 7.5.2 AccountTest Class to Use Class Account 313 7.6 Case Study: Card Shuffling and Dealing Simulation 316 7.7 Case Study: Class GradeBook Using an Array to Store Grades 320 7.8 Case Study: Class GradeBook Using a Two-Dimensional Array 326 7.9 Wrap-Up 331 8 Classes and Objects: A Deeper Look 339 8.1 Introduction 340 8.2 Time Class Case Study 340 8.3 Controlling Access to Members 345 8.4 Referring to the Current Object’s Members with the this Reference 346 8.5 Time Class Case Study: Overloaded Constructors 348 8.6 Default and No-Argument Constructors 353 8.7 Notes on Set and Get Methods 354 8.8 Composition 355 8.9 enum Types 358
Page 14
12 Contents 8.10 Garbage Collection 361 8.11 static Class Members 361 8.12 static Import 365 8.13 final Instance Variables 366 8.14 Package Access 367 8.15 Using BigDecimal for Precise Monetary Calculations 368 8.16 (Optional) GUI and Graphics Case Study: Using Objects with Graphics 371 8.17 Wrap-Up 375 9 Object-Oriented Programming: Inheritance 383 9.1 Introduction 384 9.2 Superclasses and Subclasses 385 9.3 protected Members 387 9.4 Relationship Between Superclasses and Subclasses 388 9.4.1 Creating and Using a CommissionEmployee Class 388 9.4.2 Creating and Using a BasePlusCommissionEmployee Class 393 9.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy 398 9.4.4 CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables 401 9.4.5 CommissionEmployee–BasePlusCommissionEmployee Inheritance Hierarchy Using private Instance Variables 404 9.5 Constructors in Subclasses 408 9.6 Class Object 409 9.7 Designing with Composition vs. Inheritance 410 9.8 Wrap-Up 412 10 Object-Oriented Programming: Polymorphism and Interfaces 417 10.1 Introduction 418 10.2 Polymorphism Examples 420 10.3 Demonstrating Polymorphic Behavior 421 10.4 Abstract Classes and Methods 423 10.5 Case Study: Payroll System Using Polymorphism 426 10.5.1 Abstract Superclass Employee 427 10.5.2 Concrete Subclass SalariedEmployee 429 10.5.3 Concrete Subclass HourlyEmployee 431 10.5.4 Concrete Subclass CommissionEmployee 432 10.5.5 Indirect Concrete Subclass BasePlusCommissionEmployee 434 10.5.6 Polymorphic Processing, Operator instanceof and Downcasting 435 10.6 Allowed Assignments Between Superclass and Subclass Variables 440 10.7 final Methods and Classes 440 10.8 A Deeper Explanation of Issues with Calling Methods from Constructors 441 10.9 Creating and Using Interfaces 442 10.9.1 Developing a Payable Hierarchy 444
Page 15
Contents 13 10.9.2 Interface Payable 445 10.9.3 Class Invoice 445 10.9.4 Modifying Class Employee to Implement Interface Payable 447 10.9.5 Using Interface Payable to Process Invoices and Employees Polymorphically 449 10.9.6 Some Common Interfaces of the Java API 450 10.10 Java SE 8 Interface Enhancements 451 10.10.1 default Interface Methods 451 10.10.2 static Interface Methods 452 10.10.3 Functional Interfaces 452 10.11 Java SE 9 private Interface Methods 453 10.12 private Constructors 453 10.13 Program to an Interface, Not an Implementation 454 10.13.1 Implementation Inheritance Is Best for Small Numbers of Tightly Coupled Classes 454 10.13.2 Interface Inheritance Is Best for Flexibility 454 10.13.3 Rethinking the Employee Hierarchy 455 10.14 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 456 10.15 Wrap-Up 458 11 Exception Handling: A Deeper Look 465 11.1 Introduction 466 11.2 Example: Divide by Zero without Exception Handling 467 11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 469 11.4 When to Use Exception Handling 475 11.5 Java Exception Hierarchy 475 11.6 finally Block 479 11.7 Stack Unwinding and Obtaining Information from an Exception 483 11.8 Chained Exceptions 486 11.9 Declaring New Exception Types 488 11.10 Preconditions and Postconditions 489 11.11 Assertions 489 11.12 try-with-Resources: Automatic Resource Deallocation 491 11.13 Wrap-Up 492 12 JavaFX Graphical User Interfaces: Part 1 498 12.1 Introduction 499 12.2 JavaFX Scene Builder 500 12.3 JavaFX App Window Structure 501 12.4 Welcome App—Displaying Text and an Image 502 12.4.1 Opening Scene Builder and Creating the File Welcome.fxml 502 12.4.2 Adding an Image to the Folder Containing Welcome.fxml 503 12.4.3 Creating a VBox Layout Container 503 12.4.4 Configuring the VBox Layout Container 504 12.4.5 Adding and Configuring a Label 504
Page 16
14 Contents 12.4.6 Adding and Configuring an ImageView 505 12.4.7 Previewing the Welcome GUI 507 12.5 Tip Calculator App—Introduction to Event Handling 507 12.5.1 Test-Driving the Tip Calculator App 508 12.5.2 Technologies Overview 509 12.5.3 Building the App’s GUI 511 12.5.4 TipCalculator Class 518 12.5.5 TipCalculatorController Class 520 12.6 Features Covered in the Other JavaFX Chapters 525 12.7 Wrap-Up 525 13 JavaFX GUI: Part 2 533 13.1 Introduction 534 13.2 Laying Out Nodes in a Scene Graph 534 13.3 Painter App: RadioButtons, Mouse Events and Shapes 536 13.3.1 Technologies Overview 536 13.3.2 Creating the Painter.fxml File 538 13.3.3 Building the GUI 538 13.3.4 Painter Subclass of Application 541 13.3.5 PainterController Class 542 13.4 Color Chooser App: Property Bindings and Property Listeners 546 13.4.1 Technologies Overview 546 13.4.2 Building the GUI 547 13.4.3 ColorChooser Subclass of Application 549 13.4.4 ColorChooserController Class 550 13.5 Cover Viewer App: Data-Driven GUIs with JavaFX Collections 552 13.5.1 Technologies Overview 553 13.5.2 Adding Images to the App’s Folder 553 13.5.3 Building the GUI 553 13.5.4 CoverViewer Subclass of Application 555 13.5.5 CoverViewerController Class 555 13.6 Cover Viewer App: Customizing ListView Cells 557 13.6.1 Technologies Overview 558 13.6.2 Copying the CoverViewer App 558 13.6.3 ImageTextCell Custom Cell Factory Class 559 13.6.4 CoverViewerController Class 560 13.7 Additional JavaFX Capabilities 561 13.8 JavaFX 9: Java SE 9 JavaFX Updates 563 13.9 Wrap-Up 565 14 Strings, Characters and Regular Expressions 574 14.1 Introduction 575 14.2 Fundamentals of Characters and Strings 575 14.3 Class String 576 14.3.1 String Constructors 576
Page 17
Contents 15 14.3.2 String Methods length, charAt and getChars 577 14.3.3 Comparing Strings 579 14.3.4 Locating Characters and Substrings in Strings 583 14.3.5 Extracting Substrings from Strings 585 14.3.6 Concatenating Strings 586 14.3.7 Miscellaneous String Methods 587 14.3.8 String Method valueOf 588 14.4 Class StringBuilder 589 14.4.1 StringBuilder Constructors 590 14.4.2 StringBuilder Methods length, capacity, setLength and ensureCapacity 591 14.4.3 StringBuilder Methods charAt, setCharAt, getChars and reverse 592 14.4.4 StringBuilder append Methods 593 14.4.5 StringBuilder Insertion and Deletion Methods 595 14.5 Class Character 596 14.6 Tokenizing Strings 601 14.7 Regular Expressions, Class Pattern and Class Matcher 602 14.7.1 Replacing Substrings and Splitting Strings 607 14.7.2 Classes Pattern and Matcher 609 14.8 Wrap-Up 611 15 Files, Input/Output Streams, NIO and XML Serialization 622 15.1 Introduction 623 15.2 Files and Streams 623 15.3 Using NIO Classes and Interfaces to Get File and Directory Information 625 15.4 Sequential Text Files 629 15.4.1 Creating a Sequential Text File 629 15.4.2 Reading Data from a Sequential Text File 632 15.4.3 Case Study: A Credit-Inquiry Program 633 15.4.4 Updating Sequential Files 638 15.5 XML Serialization 638 15.5.1 Creating a Sequential File Using XML Serialization 638 15.5.2 Reading and Deserializing Data from a Sequential File 644 15.6 FileChooser and DirectoryChooser Dialogs 645 15.7 (Optional) Additional java.io Classes 651 15.7.1 Interfaces and Classes for Byte-Based Input and Output 651 15.7.2 Interfaces and Classes for Character-Based Input and Output 653 15.8 Wrap-Up 654 16 Generic Collections 662 16.1 Introduction 663 16.2 Collections Overview 663
Page 18
16 Contents 16.3 Type-Wrapper Classes 665 16.4 Autoboxing and Auto-Unboxing 665 16.5 Interface Collection and Class Collections 665 16.6 Lists 666 16.6.1 ArrayList and Iterator 667 16.6.2 LinkedList 669 16.7 Collections Methods 674 16.7.1 Method sort 674 16.7.2 Method shuffle 678 16.7.3 Methods reverse, fill, copy, max and min 680 16.7.4 Method binarySearch 682 16.7.5 Methods addAll, frequency and disjoint 683 16.8 Class PriorityQueue and Interface Queue 685 16.9 Sets 686 16.10 Maps 689 16.11 Synchronized Collections 693 16.12 Unmodifiable Collections 693 16.13 Abstract Implementations 694 16.14 Java SE 9: Convenience Factory Methods for Immutable Collections 694 16.15 Wrap-Up 698 17 Lambdas and Streams 704 17.1 Introduction 705 17.2 Streams and Reduction 707 17.2.1 Summing the Integers from 1 through 10 with a for Loop 707 17.2.2 External Iteration with for Is Error Prone 708 17.2.3 Summing with a Stream and Reduction 708 17.2.4 Internal Iteration 709 17.3 Mapping and Lambdas 710 17.3.1 Lambda Expressions 711 17.3.2 Lambda Syntax 712 17.3.3 Intermediate and Terminal Operations 713 17.4 Filtering 714 17.5 How Elements Move Through Stream Pipelines 716 17.6 Method References 717 17.6.1 Creating an IntStream of Random Values 718 17.6.2 Performing a Task on Each Stream Element with forEach and a Method Reference 718 17.6.3 Mapping Integers to String Objects with mapToObj 719 17.6.4 Concatenating Strings with collect 719 17.7 IntStream Operations 720 17.7.1 Creating an IntStream and Displaying Its Values 721 17.7.2 Terminal Operations count, min, max, sum and average 721 17.7.3 Terminal Operation reduce 722 17.7.4 Sorting IntStream Values 724
Page 19
Contents 17 17.8 Functional Interfaces 725 17.9 Lambdas: A Deeper Look 726 17.10 Stream<Integer> Manipulations 727 17.10.1 Creating a Stream<Integer> 728 17.10.2 Sorting a Stream and Collecting the Results 729 17.10.3 Filtering a Stream and Storing the Results for Later Use 729 17.10.4 Filtering and Sorting a Stream and Collecting the Results 730 17.10.5 Sorting Previously Collected Results 730 17.11 Stream<String> Manipulations 730 17.11.1 Mapping Strings to Uppercase 731 17.11.2 Filtering Strings Then Sorting Them in Case-Insensitive Ascending Order 732 17.11.3 Filtering Strings Then Sorting Them in Case-Insensitive Descending Order 732 17.12 Stream<Employee> Manipulations 733 17.12.1 Creating and Displaying a List<Employee> 734 17.12.2 Filtering Employees with Salaries in a Specified Range 735 17.12.3 Sorting Employees By Multiple Fields 738 17.12.4 Mapping Employees to Unique-Last-Name Strings 740 17.12.5 Grouping Employees By Department 741 17.12.6 Counting the Number of Employees in Each Department 742 17.12.7 Summing and Averaging Employee Salaries 743 17.13 Creating a Stream<String> from a File 744 17.14 Streams of Random Values 747 17.15 Infinite Streams 749 17.16 Lambda Event Handlers 751 17.17 Additional Notes on Java SE 8 Interfaces 751 17.18 Wrap-Up 752 18 Recursion 766 18.1 Introduction 767 18.2 Recursion Concepts 768 18.3 Example Using Recursion: Factorials 769 18.4 Reimplementing Class FactorialCalculator Using BigInteger 771 18.5 Example Using Recursion: Fibonacci Series 773 18.6 Recursion and the Method-Call Stack 776 18.7 Recursion vs. Iteration 777 18.8 Towers of Hanoi 779 18.9 Fractals 781 18.9.1 Koch Curve Fractal 782 18.9.2 (Optional) Case Study: Lo Feather Fractal 783 18.9.3 (Optional) Fractal App GUI 785 18.9.4 (Optional) FractalController Class 787 18.10 Recursive Backtracking 792 18.11 Wrap-Up 792
Page 20
18 Contents 19 Searching, Sorting and Big O 801 19.1 Introduction 802 19.2 Linear Search 803 19.3 Big O Notation 806 19.3.1 O(1) Algorithms 806 19.3.2 O(n) Algorithms 806 19.3.3 O(n2) Algorithms 806 19.3.4 Big O of the Linear Search 807 19.4 Binary Search 807 19.4.1 Binary Search Implementation 808 19.4.2 Efficiency of the Binary Search 811 19.5 Sorting Algorithms 812 19.6 Selection Sort 812 19.6.1 Selection Sort Implementation 813 19.6.2 Efficiency of the Selection Sort 815 19.7 Insertion Sort 815 19.7.1 Insertion Sort Implementation 816 19.7.2 Efficiency of the Insertion Sort 818 19.8 Merge Sort 819 19.8.1 Merge Sort Implementation 819 19.8.2 Efficiency of the Merge Sort 824 19.9 Big O Summary for This Chapter’s Searching and Sorting Algorithms 824 19.10 Massive Parallelism and Parallel Algorithms 825 19.11 Wrap-Up 825 20 Generic Classes and Methods: A Deeper Look 831 20.1 Introduction 832 20.2 Motivation for Generic Methods 832 20.3 Generic Methods: Implementation and Compile-Time Translation 834 20.4 Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type 837 20.5 Overloading Generic Methods 840 20.6 Generic Classes 841 20.7 Wildcards in Methods That Accept Type Parameters 848 20.8 Wrap-Up 852 21 Custom Generic Data Structures 856 21.1 Introduction 857 21.2 Self-Referential Classes 858 21.3 Dynamic Memory Allocation 858 21.4 Linked Lists 859 21.4.1 Singly Linked Lists 859 21.4.2 Implementing a Generic List Class 860 21.4.3 Generic Classes ListNode and List 863
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
Back to List