(This page has no text content)
The Rheinwerk Computing series from Rheinwerk Publishing offers new and established professionals comprehensive guidance to enrich their skillsets and enhance their career prospects. Our publications are written by leading experts in the fields of programming, administration, security, analytics, and more. Each book is detailed and hands-on to help readers develop essential, practical skills that they can apply to their daily work. For further information, please visit our website: www.rheinwerk-computing.com. Philip Ackermann JavaScript: The Comprehensive Guide 2022, 982 pages, paperback and e-book www.rheinwerk-computing.com/5554 Sebastian Springer Node.js: The Comprehensive Guide 2022, 834 pages, paperback and e-book www.rheinwerk-computing.com/5556 Johannes Ernesti, Peter Kaiser Python 3: The Comprehensive Guide 2022, 1036 pages, paperback and e-book www.rheinwerk-computing.com/5566 Bernd Öggl, Michael Kofler Git: Project Management for Developers and DevOps Teams 2023, 407 pages, paperback and e-book www.rheinwerk-computing.com/5555 Bernd Öggl, Michael Kofler Docker: Practical Guide for Developers and DevOps Teams 2023, approx. 496 pp, paperback and e-book www.rheinwerk-computing.com/5650 Rheinwerk Computing
Christian Ullenboom Java The Comprehensive Guide
Dear Reader, The first iteration of the book that you now hold in your hands was published for Ger- man readers in 2003. Today, that bestselling guide is in its 16th edition in Germany. What does it mean to write 16 editions of a book? Consider: reading your work repeat- edly over the course of 20 years; expanding, rewriting, and refining, until you know the text like the back of your hand; evaluating changes to the topic area and sorting through hundreds of pages of text to implement the minutest updates to the Java lan- guage; reading, reviewing, and testing code snippets; and, of course, working through 16 editions of editor feedback and critique. In many ways, this translation is a 17th edition, built on years of previous work. Chris- tian Ullenboom has honed his manuscript once again, making key updates to ensure that this guide is the best resource for both new Java programmers and experienced professionals. And he’s done this in a new language, to bring his decades of knowledge to English readers. I’m certain that you will find his expertise invaluable. What did you think about Java: The Comprehensive Guide? Your comments and sugges- tions are the most useful tools to help us make our books the best they can be. Please feel free to contact me and share any praise or criticism you may have. Thank you for purchasing a book from Rheinwerk Publishing! Hareem Shafi Editor, SAP PRESS hareems@rheinwerk-publishing.com www.rheinwerk-computing.com Rheinwerk Publishing • Boston, MA
Imprint This e-book is a publication many contributed to, specifically: Editor Hareem Shafi German Edition Editors Anne Scheibe, Almut Poll Translation Winema Language Services, Inc. Copyeditor Yvette Chin Technical Reviewer Dirk Evers Illustration Leo Leowald, Germany Cover Design Graham Geary Photo Credit iStockphoto: 1332719560/© zxvisual; Shutterstock: 190908608/© picoStudio Layout Design Vera Brauner Production E-Book Graham Geary Typesetting E-Book III-satz, Germany We hope that you liked this e-book. Please share your feedback with us and read the Service Pages to find out how to contact us. The Library of Congress has cataloged the printed edition as follows: Names: Ullenboom, Christian, author. Title: Java : the comprehensive guide / by Christian Ullenboom. Description: 1st edition. | Bonn ; Boston : Rheinwerk Publishing/SAP Press, 2022. | Includes bibliographical references and index. Identifiers: LCCN 2022029163 | ISBN 9781493222957 (hardcover) | ISBN 9781493222964 (ebook) Subjects: LCSH: Java (Computer program language) | Computer programming. Classification: LCC QA76.73.J38 U45 2022 | DDC 005.13/3--dc23/eng/20220812 LC record available at https://lccn.loc.gov/2022029163LC record available at https://lccn.loc. gov/2020023822 LC ebook record available at https://lccn.loc.gov/2020023823 ISBN 978-1-4932-2295-7 (print) ISBN 978-1-4932-2296-4 (e-book) ISBN 978-1-4932-2297-1 (print and e-book) © 2023 by Rheinwerk Publishing, Inc., Boston (MA) 1st edition 2023 16th German edition published 2022 by Rheinwerk Verlag, Bonn, Germany
7 Contents Preface ....................................................................................................................................................... 31 1 Introduction 43 1.1 Historical Background ......................................................................................................... 43 1.2 On the Popularity of Java: The Key Features ............................................................ 45 1.2.1 Bytecode .................................................................................................................... 46 1.2.2 Executing the Bytecode via a Virtual Machine ............................................. 46 1.2.3 Platform Independence ........................................................................................ 46 1.2.4 Java as a Language, Runtime Environment, and Standard Library ........ 47 1.2.5 Object Orientation in Java ................................................................................... 47 1.2.6 Java Is Widespread and Well Known ............................................................... 48 1.2.7 Java Is Fast: Optimization and Just-In-Time Compilation ........................ 48 1.2.8 Pointers and References ....................................................................................... 50 1.2.9 Take Out the Trash, Garbage Collector! .......................................................... 51 1.2.10 Exception Handling ............................................................................................... 52 1.2.11 The Range of Libraries and Tools ....................................................................... 52 1.2.12 Comparably Simple Syntax ................................................................................. 53 1.2.13 Abandoning Controversial Concepts ............................................................... 53 1.2.14 Java Is Open Source ............................................................................................... 54 1.2.15 What Java Is Less Suitable for ............................................................................ 55 1.3 Java versus Other Languages* ......................................................................................... 56 1.3.1 Java and C(++) .......................................................................................................... 56 1.3.2 Java and JavaScript ................................................................................................ 57 1.3.3 A Word about Microsoft, Java, and J++ ........................................................... 57 1.3.4 Java and C#/.NET .................................................................................................... 58 1.4 Further Development and Losses ................................................................................... 59 1.4.1 The Development of Java and Its Future Prospects .................................... 59 1.4.2 Features, Enhancements, and Specification Requests .............................. 60 1.4.3 Applets ....................................................................................................................... 61 1.4.4 JavaFX ......................................................................................................................... 61 1.5 Java Platforms ......................................................................................................................... 62 1.5.1 Java Platform, Standard Edition ........................................................................ 62 1.5.2 Java Platform, Micro Edition: Java for the Little Ones ................................ 65 1.5.3 Java for the Very, Very Little Ones .................................................................... 65 1.5.4 Java for the Big Ones: Jakarta EE (Formerly Java Platform, Enterprise Edition) .................................................................................................. 65 1.5.5 Real-Time Java ......................................................................................................... 66
Contents1.6 Java Platform, Standard Edition, Implementations ............................................... 67 1.6.1 OpenJDK .................................................................................................................... 67 1.6.2 Oracle JDK ................................................................................................................. 68 1.7 Installing the Java Development Kit ............................................................................. 69 1.7.1 Installing Oracle JDK on Windows .................................................................... 70 1.8 Compiling and Testing the First Program ................................................................... 71 1.8.1 A Square Numbers Program ............................................................................... 72 1.8.2 The Compiler Run ................................................................................................... 73 1.8.3 The Runtime Environment .................................................................................. 74 1.8.4 Common Compiler and Interpreter Issues .................................................... 74 1.9 Development Environments ............................................................................................ 75 1.9.1 IntelliJ IDEA ............................................................................................................... 76 1.9.2 Eclipse Integrated Development Environment ............................................ 80 1.9.3 NetBeans ................................................................................................................... 81 1.10 Further Reading ...................................................................................................................... 81 2 Imperative Language Concepts 83 2.1 Elements of the Java Programming Language ......................................................... 83 2.1.1 Tokens ........................................................................................................................ 84 2.1.2 Text Encoding by Unicode Characters ............................................................. 85 2.1.3 Identifiers .................................................................................................................. 85 2.1.4 Literals ........................................................................................................................ 87 2.1.5 (Reserved) Keywords ............................................................................................. 87 2.1.6 Summary of the Lexical Analysis ....................................................................... 88 2.1.7 Comments ................................................................................................................ 89 2.2 From Classes to Statements ............................................................................................. 91 2.2.1 What Are Statements? ......................................................................................... 91 2.2.2 Class Declaration .................................................................................................... 92 2.2.3 The Journey Begins with main(String[]) ......................................................... 93 2.2.4 The First Method Call: println(...) ...................................................................... 93 2.2.5 Atomic Statements and Statement Sequences ........................................... 95 2.2.6 More about print(...), println(...), and printf(...) for Screen Output ......... 95 2.2.7 Application Programming Interface Documentation ................................ 97 2.2.8 Expressions ............................................................................................................... 98 2.2.9 Expression Statements ......................................................................................... 98 2.2.10 First Insights into Object Orientation .............................................................. 99 2.2.11 Modifiers ................................................................................................................... 100 2.2.12 Grouping Statements with Blocks .................................................................... 1018
Contents2.3 Data Types, Typing, Variables, and Assignments ................................................... 102 2.3.1 Overview of Primitive Data Types ..................................................................... 104 2.3.2 Variable Declarations ............................................................................................ 106 2.3.3 Automatic Type Detection with var ................................................................. 109 2.3.4 Final Variables and the final Modifier ............................................................. 110 2.3.5 Console Inputs ......................................................................................................... 110 2.3.6 Truth Values ............................................................................................................. 112 2.3.7 Integer Data Types ................................................................................................. 112 2.3.8 Underscores in Numbers ..................................................................................... 114 2.3.9 Alphanumeric Characters .................................................................................... 115 2.3.10 The float and double Data Types ...................................................................... 115 2.3.11 Good Names, Bad Names .................................................................................... 117 2.3.12 No Automatic Initialization of Local Variables ............................................. 118 2.4 Expressions, Operands, and Operators ........................................................................ 119 2.4.1 Assignment Operator ............................................................................................ 119 2.4.2 Arithmetic Operators ............................................................................................ 121 2.4.3 Unary Minus and Plus ........................................................................................... 124 2.4.4 Prefix or Postfix Increment and Decrement .................................................. 124 2.4.5 Assignment with Operation (Compound Assignment Operator) .......... 126 2.4.6 Relational Operators and Equality Operators ............................................... 128 2.4.7 Logical Operators: NOT, AND, OR, and XOR ................................................... 129 2.4.8 Short-Circuit Operators ........................................................................................ 130 2.4.9 The Rank of Operators in Evaluation Order ................................................... 132 2.4.10 Typecasting (Casting) ............................................................................................ 135 2.4.11 Overloaded Plus for Strings ................................................................................. 140 2.4.12 Operators Missing* ................................................................................................ 141 2.5 Conditional Statements or Case Distinctions ........................................................... 142 2.5.1 Branching with the if Statement ...................................................................... 142 2.5.2 Choosing the Alternative with an if-else Statement .................................. 145 2.5.3 The Condition Operator ....................................................................................... 148 2.5.4 The Switch Statement Provides an Alternative ........................................... 151 2.5.5 Switch Expressions ................................................................................................ 157 2.6 Always the Same with Loops ........................................................................................... 160 2.6.1 The while Loop ........................................................................................................ 161 2.6.2 The do-while Loop .................................................................................................. 163 2.6.3 The for Loop .............................................................................................................. 164 2.6.4 Loop Conditions and Comparisons with ==* ................................................. 168 2.6.5 Loop Termination with break and back to Test with continue ............... 171 2.6.6 break and continue with Labels* ....................................................................... 174 2.7 Methods of a Class ................................................................................................................ 177 2.7.1 Components of a Method ................................................................................... 1779
Contents2.7.2 Signature Description in the Java Application Programming Interface Documentation .................................................................................... 179 2.7.3 Calling a Method .................................................................................................... 180 2.7.4 Declaring Methods without Parameters ........................................................ 181 2.7.5 Static Methods (Class Methods) ....................................................................... 182 2.7.6 Parameters, Arguments, and Value Transfers .............................................. 183 2.7.7 Ending Methods Prematurely with return ..................................................... 185 2.7.8 Unreachable Source Code for Methods* ........................................................ 185 2.7.9 Methods with Returns .......................................................................................... 186 2.7.10 Overloading Methods ........................................................................................... 191 2.7.11 Scope ........................................................................................................................... 193 2.7.12 Default Values for Unlisted Arguments* ........................................................ 195 2.7.13 Recursive Methods* ............................................................................................... 195 2.7.14 Towers of Hanoi* .................................................................................................... 198 2.8 Further Reading ...................................................................................................................... 200 3 Classes and Objects 201 3.1 Object-Oriented Programming ....................................................................................... 201 3.1.1 Why Object-Oriented Programming at All? .................................................. 202 3.1.2 When I Think of Java, I Think of Reusability .................................................. 202 3.2 Members of a Class ............................................................................................................... 203 3.3 Natural Modeling Using Unified Modeling Language* ........................................ 204 3.4 Creating New Objects .......................................................................................................... 206 3.4.1 Creating an Instance of a Class Using the new Keyword ......................... 206 3.4.2 Declaring Reference Variables ........................................................................... 207 3.4.3 Let’s Get to the Point: Accessing Object Variables and Methods .......... 208 3.4.4 The Connection between new, the Heap, and the Garbage Collector ..................................................................................................................... 212 3.4.5 Overview of Point Methods ................................................................................ 213 3.4.6 Using Constructors ................................................................................................ 217 3.5 ZZZZZnake ................................................................................................................................ 218 3.6 Tying Packages, Imports, and Compilation Units ................................................... 220 3.6.1 Java Packages ........................................................................................................... 220 3.6.2 Packages in the Standard Library ...................................................................... 221 3.6.3 Full Qualification and Import Declaration ..................................................... 221 3.6.4 Reaching All Types of a Package with Type-Import-on-Demand ........... 223 3.6.5 Hierarchical Structures across Packages and Mirroring in the File System ................................................................................................................ 224 3.6.6 The Package Declaration ...................................................................................... 22410
Contents3.6.7 Unnamed Package (Default Package) ............................................................. 225 3.6.8 Compilation Unit .................................................................................................... 226 3.6.9 Static Import* ........................................................................................................... 226 3.7 Using References, Diversity, Identity, and Equality ............................................... 228 3.7.1 null References and the Question of Philosophy ......................................... 228 3.7.2 Everything to null? Testing References ........................................................... 230 3.7.3 Assignments with References ............................................................................ 231 3.7.4 Methods with Reference Types as Parameters ............................................ 232 3.7.5 Identity of Objects .................................................................................................. 236 3.7.6 Equivalence and the equals(...) Method .......................................................... 237 3.8 Further Reading ...................................................................................................................... 239 4 Arrays and Their Areas of Use 241 4.1 Simple Field Work ................................................................................................................. 241 4.1.1 Basic Components .................................................................................................. 242 4.1.2 Declaring Array Variables .................................................................................... 243 4.1.3 Creating Array Objects with new ...................................................................... 244 4.1.4 Arrays with { contents } ........................................................................................ 245 4.1.5 Reading the Length of an Array via the Object Variable Length ............ 246 4.1.6 Accessing the Elements via the Index ............................................................. 246 4.1.7 Typical Array Errors ................................................................................................ 248 4.1.8 Passing Arrays to Methods .................................................................................. 250 4.1.9 Multiple Return Values* ....................................................................................... 250 4.1.10 Preinitialized Arrays ............................................................................................... 251 4.2 The Extended for Loop ........................................................................................................ 252 4.2.1 Using Anonymous Arrays in the Extended for Loop ................................... 253 4.2.2 Example: Searching Arrays with Strings ......................................................... 254 4.2.3 Creating Random Player Positions .................................................................... 255 4.3 A Method with a Variable Number of Arguments ................................................. 256 4.3.1 System.out.printf(...) Accepts Any Number of Arguments ....................... 257 4.3.2 Finding the Average of Variable Arguments ................................................. 257 4.3.3 Vararg Design Tips* ............................................................................................... 259 4.4 Multidimensional Arrays* .................................................................................................. 259 4.4.1 Nonrectangular Arrays* ........................................................................................ 262 4.5 Library Support for Arrays ................................................................................................. 264 4.5.1 Cloning Can Be Worthwhile: Propagating Arrays ....................................... 264 4.5.2 Why Can Arrays “Do” So Little? ......................................................................... 265 4.5.3 Copying Array Contents ....................................................................................... 26611
Contents4.6 Using the Arrays Class for Comparing, Filling, Searching, and Sorting ......... 267 4.6.1 String Representation of an Array .................................................................... 267 4.6.2 Sorting ........................................................................................................................ 268 4.6.3 Parallel Sorting ........................................................................................................ 269 4.6.4 Comparing Arrays of Primitives with Arrays.equals(...) and Arrays.deepEquals(...)* .......................................................................................... 269 4.6.5 Comparing Object Arrays Using Arrays.equals(...) and Arrays.deepEquals(...)* .......................................................................................... 271 4.6.6 Searching Differences Using Mismatch (...)* ................................................. 272 4.6.7 Filling Arrays* ........................................................................................................... 272 4.6.8 Copying Array Sections* ....................................................................................... 273 4.6.9 Binary Search* .......................................................................................................... 275 4.6.10 Lexicographic Array Comparisons Using compare(...) and compareUnsigned(...) ............................................................................................ 276 4.6.11 Arrays for Lists with Arrays.asList(...): Convenient for Searching and Comparing* ...................................................................................................... 277 4.6.12 A Long Snake ............................................................................................................ 278 4.7 The Entry Point for the Runtime System: main(...) ................................................ 281 4.7.1 Correct Declaration of the Start Method ....................................................... 281 4.7.2 Processing Command Line Arguments ........................................................... 282 4.7.3 The Return Type of main(...) and System.exit(int)* ..................................... 283 4.8 Further Reading ...................................................................................................................... 285 5 Handling Characters and Strings 287 5.1 From ASCII via ISO-8859-1 to Unicode ......................................................................... 287 5.1.1 ASCII ............................................................................................................................ 287 5.1.2 ISO/IEC 8859-1 ........................................................................................................ 288 5.1.3 Unicode ...................................................................................................................... 289 5.1.4 Unicode Character Encoding .............................................................................. 291 5.1.5 Escape Sequences ................................................................................................... 292 5.1.6 Notation for Unicode Characters and Unicode Escapes ........................... 292 5.1.7 Java Versions Go Hand in Hand with the Unicode Standard* ................. 294 5.2 Data Types for Characters and Strings ......................................................................... 295 5.3 The Character Class ............................................................................................................... 296 5.3.1 Is That So? ................................................................................................................. 296 5.3.2 Converting Characters to Uppercase/Lowercase ........................................ 298 5.3.3 From Character to String ..................................................................................... 299 5.3.4 From char to int: From Character to Number* ............................................. 29912
Contents5.4 Strings ......................................................................................................................................... 301 5.5 The String Class and Its Methods ................................................................................... 303 5.5.1 String Literals as String Objects for Constant Strings ................................ 303 5.5.2 Concatenation with + ........................................................................................... 303 5.5.3 Multiline Text Blocks with “”” ............................................................................ 304 5.5.4 String Length and Testing for Empty Strings ................................................ 309 5.5.5 Accessing a Specific Character with charAt(int) .......................................... 310 5.5.6 Searching for Contained Characters and Strings ........................................ 311 5.5.7 The Hangman Game ............................................................................................. 314 5.5.8 Good That We Have Compared ......................................................................... 316 5.5.9 Extracting String Sections ................................................................................... 320 5.5.10 Appending Strings, Merging Strings, Case Sensitivity, and Whitespace ............................................................................................................... 325 5.5.11 Searched, Found, and Replaced ......................................................................... 328 5.5.12 Creating String Objects with Constructors and from Repeats* .............. 330 5.6 Mutable Strings with StringBuilder and StringBuffer .......................................... 333 5.6.1 Creating StringBuilder Objects .......................................................................... 334 5.6.2 Converting StringBuilder to Other String Formats ..................................... 335 5.6.3 Requesting Characters or Strings ...................................................................... 335 5.6.4 Appending Data ...................................................................................................... 335 5.6.5 Setting, Deleting, and Reversing Characters and Strings ......................... 337 5.6.6 Length and Capacity of a StringBuilder Object* ........................................... 339 5.6.7 Comparison of StringBuilder Instances and Strings with StringBuilder ............................................................................................................ 340 5.6.8 hashCode() with StringBuilder* ......................................................................... 342 5.7 CharSequence as Base Type .............................................................................................. 342 5.7.1 Basic Operations of the Interface ..................................................................... 343 5.7.2 Static compare(...) Method in CharSequence ................................................ 344 5.7.3 Default Methods in the CharSequence Interface* ...................................... 345 5.8 Converting Primitives and Strings ................................................................................. 345 5.8.1 Converting Different Types to String Representations ............................. 345 5.8.2 Converting String Contents to a Primitive Value ........................................ 347 5.8.3 String Representation in Binary, Hex, and Octal Formats* ...................... 349 5.8.4 parse*(...) and print*() Methods in DatatypeConverter* ............................ 353 5.9 Concatenating Strings ......................................................................................................... 353 5.9.1 Concatenating Strings with StringJoiner ....................................................... 353 5.10 Decomposing Strings ........................................................................................................... 355 5.10.1 Splitting Strings via split(...) ................................................................................ 356 5.10.2 Yes We Can, Yes We Scan: The Scanner Class ............................................... 35613
Contents5.11 Formatting Outputs ............................................................................................................. 360 5.11.1 Formatting and Outputting via format() ....................................................... 361 5.12 Further Reading ...................................................................................................................... 367 6 Writing Custom Classes 369 6.1 Declaring Custom Classes with Members .................................................................. 369 6.1.1 Minimum Class ....................................................................................................... 370 6.1.2 Declaring Object Variables .................................................................................. 370 6.1.3 Declaring Methods ................................................................................................. 373 6.1.4 Shadowed Variables .............................................................................................. 375 6.1.5 The this Reference .................................................................................................. 377 6.2 Privacy and Visibility ............................................................................................................ 380 6.2.1 For the Public: public ............................................................................................. 381 6.2.2 Not Public: Passwords Are private .................................................................... 381 6.2.3 Why Not Free Methods and Variables for All? .............................................. 383 6.2.4 private Is Not Quite Private: It Depends on Who Sees It* ......................... 383 6.2.5 Declaring Access Methods for Object Variables .......................................... 384 6.2.6 Setters and Getters according to the JavaBeans Specification ............... 384 6.2.7 Package-Visibility ................................................................................................... 386 6.2.8 Visibility Summary ................................................................................................. 388 6.3 One for All: Static Methods and Class Variables ..................................................... 390 6.3.1 Why Static Members Are Useful ....................................................................... 391 6.3.2 Static Members with static ................................................................................. 392 6.3.3 Using Static Members via References?* ......................................................... 393 6.3.4 Why Case Sensitivity Is Important* .................................................................. 394 6.3.5 Static Variables for Data Exchange* ................................................................ 395 6.3.6 Static Members and Object Members* ........................................................... 396 6.4 Constants and Enumerations ........................................................................................... 397 6.4.1 Constants via Static Final Variables ................................................................. 397 6.4.2 Type-Unsafe Enumerations ................................................................................ 398 6.4.3 Enumeration Types: Type-Safe Enumerations with enum ...................... 400 6.5 Creating and Destroying Objects ................................................................................... 405 6.5.1 Writing Constructors ............................................................................................ 405 6.5.2 Relationship of Method and Constructor ...................................................... 406 6.5.3 The Default Constructor ...................................................................................... 407 6.5.4 Parameterized and Overloaded Constructors .............................................. 408 6.5.5 Copy Constructors .................................................................................................. 410 6.5.6 Calling Another Constructor of the Same Class via this(...) ...................... 41214
Contents6.5.7 Immutable Objects and Wither Methods ...................................................... 414 6.5.8 We Don’t Miss You: The Garbage Collector ................................................... 416 6.6 Class and Object Initialization* ....................................................................................... 418 6.6.1 Initializing Object Variables ................................................................................ 418 6.6.2 Static Blocks as Class Initializers ....................................................................... 420 6.6.3 Initializing Class Variables ................................................................................... 421 6.6.4 Compiled Assignments of the Class Variables ............................................. 421 6.6.5 Instance Initializer .................................................................................................. 422 6.6.6 Setting Final Values in the Constructor and Static Blocks ........................ 425 6.7 Conclusion ................................................................................................................................ 426 7 Object-Oriented Relationship 427 7.1 Associations between Objects ......................................................................................... 427 7.1.1 Association Types ................................................................................................... 427 7.1.2 Unidirectional 1-to-1 Relationship ................................................................... 428 7.1.3 Becoming Friends: Bidirectional 1-to-1 Relationships ............................... 429 7.1.4 Unidirectional 1-to-n Relationships ................................................................. 431 7.2 Inheritance ............................................................................................................................... 436 7.2.1 Inheritance in Java ................................................................................................. 437 7.2.2 Modeling Events ..................................................................................................... 438 7.2.3 The Implicit Base Class java.lang.Object ........................................................ 440 7.2.4 Single and Multiple Inheritance* ...................................................................... 440 7.2.5 Do Children See Everything? The Protected Visibility ................................ 441 7.2.6 Constructors in Inheritance and super(...) ...................................................... 442 7.3 Types in Hierarchies ............................................................................................................. 447 7.3.1 Automatic and Explicit Typecasting ................................................................ 447 7.3.2 The Substitution Principle ................................................................................... 450 7.3.3 Testing Types with the instanceof Operator ................................................. 452 7.3.4 Pattern Matching for instanceof ....................................................................... 455 7.4 Overriding Methods ............................................................................................................. 457 7.4.1 Providing Methods in Subclasses with a New Behavior ........................... 457 7.4.2 With super to the Parents ................................................................................... 461 7.5 Testing Dynamic Bindings ................................................................................................. 463 7.5.1 Bound to toString() ................................................................................................ 463 7.5.2 Implementing System.out.println(Object) .................................................... 465 7.6 Final Classes and Final Methods ..................................................................................... 466 7.6.1 Final Classes ............................................................................................................. 466 7.6.2 Non-Overridable (final) Methods ...................................................................... 46615
Contents7.7 Abstract Classes and Abstract Methods ...................................................................... 468 7.7.1 Abstract Classes ...................................................................................................... 468 7.7.2 Abstract Methods ................................................................................................... 470 7.8 Further Information on Overriding and Dynamic Binding ................................. 476 7.8.1 No Dynamic Binding for Private, Static, and final Methods ..................... 476 7.8.2 Covariant Return Types ........................................................................................ 476 7.8.3 Array Types and Covariance* .............................................................................. 477 7.8.4 Dynamic Binding even with Constructor Calls* ........................................... 478 7.8.5 No Dynamic Binding for Covered Object Variables* ................................... 480 7.9 A Programming Task ............................................................................................................ 482 8 Interfaces, Enumerations, Sealed Classes, Records 483 8.1 Interfaces ................................................................................................................................... 483 8.1.1 Interfaces Are New Types .................................................................................... 483 8.1.2 Declaring Interfaces ............................................................................................... 484 8.1.3 Abstract Methods in Interfaces ......................................................................... 484 8.1.4 Implementing Interfaces ..................................................................................... 485 8.1.5 A Polymorphism Example with Interfaces ..................................................... 487 8.1.6 Multiple Inheritance with Interfaces ............................................................... 488 8.1.7 No Risk of Collision with Multiple Inheritance* ........................................... 491 8.1.8 Extending Interfaces: Subinterfaces ................................................................ 493 8.1.9 Constant Declarations for Interfaces ............................................................... 494 8.1.10 Subsequent Implementation of Interfaces* .................................................. 494 8.1.11 Static Programmed Methods in Interfaces .................................................... 495 8.1.12 Extending and Modifying Interfaces ............................................................... 497 8.1.13 Default Methods ..................................................................................................... 498 8.1.14 Declaring and Using Extended Interfaces ...................................................... 500 8.1.15 Public and Private Interface Methods ............................................................. 503 8.1.16 Extended Interfaces, Multiple Inheritance, and Ambiguities* ................ 504 8.1.17 Creating Building Blocks with Default Methods* ........................................ 508 8.1.18 Marker Interfaces* .................................................................................................. 512 8.1.19 (Abstract) Classes and Interfaces in Comparison ........................................ 513 8.2 Enumeration Types ............................................................................................................... 513 8.2.1 Methods on Enum Objects .................................................................................. 514 8.2.2 Enumerations with Custom Methods, Constructors, and Initializers* ................................................................................................................ 518 8.3 Sealed Classes and Interfaces .......................................................................................... 523 8.3.1 Sealed Classes and Interfaces ............................................................................ 525 8.3.2 Subclasses Are Final, Sealed, and Non-Sealed .............................................. 527 8.3.3 Abbreviated Notations ......................................................................................... 52816
Contents8.4 Records ....................................................................................................................................... 529 8.4.1 Simple Records ........................................................................................................ 529 8.4.2 Records with Methods .......................................................................................... 531 8.4.3 Customizing Record Constructors .................................................................... 532 8.4.4 Adding Constructors ............................................................................................. 534 8.4.5 Sealed Interfaces and Records ........................................................................... 535 8.4.6 Records: Summary ................................................................................................. 536 9 There Must Be Exceptions 539 9.1 Fencing In Problem Areas .................................................................................................. 539 9.1.1 Exceptions in Java with try and catch ............................................................. 540 9.1.2 Checked and Unchecked Exceptions ............................................................... 540 9.1.3 A NumberFormatException (Unchecked Exception) .................................. 541 9.1.4 Appending a Date/Timestamp to a Text File (Checked Exception) ....... 543 9.1.5 Repeating Canceled Sections* ............................................................................ 545 9.1.6 Empty catch Blocks ................................................................................................ 546 9.1.7 Catching Multiple Exceptions ............................................................................ 547 9.1.8 Combining Identical catch Blocks with Multi-Catch .................................. 548 9.2 Redirecting Exceptions and throws at the Head of Methods/ Constructors ............................................................................................................................. 549 9.2.1 throws in Constructors and Methods ............................................................. 549 9.3 The Class Hierarchy of Exceptions ................................................................................. 550 9.3.1 Members of the Exception Object .................................................................... 550 9.3.2 Base Type Throwable ............................................................................................ 551 9.3.3 The Exception Hierarchy ...................................................................................... 552 9.3.4 Catching Super-Exceptions ................................................................................. 552 9.3.5 Already Caught? ...................................................................................................... 554 9.3.6 Procedure of an Exceptional Situation ............................................................ 555 9.3.7 No General Catching! ............................................................................................ 555 9.3.8 Known RuntimeException Classes ................................................................... 557 9.3.9 Interception Is Possible, but Not Mandatory ................................................ 558 9.4 Final Handling Using finally ............................................................................................. 558 9.4.1 The Ignorant Version ............................................................................................. 559 9.4.2 The Well-Intentioned Attempt .......................................................................... 560 9.4.3 From Now On, Closing Is Part of the Agenda ................................................ 560 9.4.4 Summary ................................................................................................................... 562 9.4.5 A try without a catch, but a try-finally ............................................................ 562 9.5 Triggering Custom Exceptions ......................................................................................... 564 9.5.1 Triggering Exceptions via throw ....................................................................... 564 9.5.2 Knowing and Using Existing Runtime Exception Types ............................ 56617
Contents9.5.3 Testing Parameters and Good Error Messages ............................................ 568 9.5.4 Declaring New Exception Classes ..................................................................... 570 9.5.5 Custom Exceptions as Subclasses of Exception or RuntimeException? ................................................................................................ 571 9.5.6 Catching and Redirecting Exceptions* ............................................................ 574 9.5.7 Changing the Call Stack of Exceptions* .......................................................... 575 9.5.8 Nested Exceptions* ................................................................................................ 576 9.6 try with Resources (Automatic Resource Management) ..................................... 579 9.6.1 try with Resources .................................................................................................. 580 9.6.2 The AutoCloseable Interface .............................................................................. 581 9.6.3 Exceptions to close() .............................................................................................. 582 9.6.4 Types That Are AutoCloseable and Closeable ............................................... 583 9.6.5 Using Multiple Resources .................................................................................... 583 9.6.6 Suppressed Exceptions* ....................................................................................... 585 9.7 Special Features of Exception Handling* .................................................................... 588 9.7.1 Return Values for Thrown Exceptions ............................................................. 588 9.7.2 Exceptions and Returns Disappear: The Duo return and finally ............ 589 9.7.3 throws on Overridden Methods ........................................................................ 590 9.7.4 Unreachable catch Clauses ................................................................................. 592 9.8 Hard Errors: Error* ................................................................................................................. 593 9.9 Assertions* ................................................................................................................................ 594 9.9.1 Using Assertions in Custom Programs ............................................................ 595 9.9.2 Enabling Assertions and Runtime Errors ........................................................ 595 9.9.3 Enabling or Disabling Assertions More Detailed ......................................... 597 9.10 Conclusion ................................................................................................................................ 597 10 Nested Types 599 10.1 Nested Classes, Interfaces, and Enumerations ........................................................ 599 10.2 Static Nested Types .............................................................................................................. 601 10.2.1 Modifiers and Visibility ......................................................................................... 602 10.2.2 Records as Containers ........................................................................................... 602 10.2.3 Implementing Static Nested Types* ................................................................ 602 10.3 Non-Static Nested Types .................................................................................................... 603 10.3.1 Creating Instances of Inner Classes ................................................................. 603 10.3.2 The this Reference .................................................................................................. 604 10.3.3 Class Files Generated by the Compiler* .......................................................... 605 10.4 Local Classes ............................................................................................................................. 605 10.4.1 Example with a Custom Declaration ............................................................... 60618
Contents10.4.2 Using a Local Class for a Timer ........................................................................... 606 10.5 Anonymous Inner Classes .................................................................................................. 607 10.5.1 Using an Anonymous Inner Class for the Timer .......................................... 608 10.5.2 Implementing Anonymous Inner Classes* .................................................... 609 10.5.3 Constructors of Anonymous Inner Classes .................................................... 609 10.5.4 Accessing Local Variables from Local and Anonymous Classes* ............ 611 10.5.5 Nested Classes Access Private Members ........................................................ 612 10.6 Nests ............................................................................................................................................ 613 10.7 Conclusion ................................................................................................................................ 614 11 Special Types of Java SE 615 11.1 Object Is the Mother of All Classes ................................................................................ 616 11.1.1 Class Objects ............................................................................................................ 616 11.1.2 Object Identification with toString() ............................................................... 617 11.1.3 Object Equivalence with equals(...) and Identity ......................................... 619 11.1.4 Cloning an Object Using clone()* ...................................................................... 625 11.1.5 Returning Hash Values via hashCode()* ......................................................... 630 11.1.6 System.identityHashCode(...) and the Problem of Non-Unique Object References* ....................................................................... 636 11.1.7 Synchronization* .................................................................................................... 637 11.2 Weak References and Cleaners ....................................................................................... 638 11.3 The java.util.Objects Utility Class .................................................................................. 639 11.3.1 Built-In Null Tests for equals(...)/hashCode() ................................................ 639 11.3.2 Objects.toString(…) ................................................................................................ 640 11.3.3 null Checks with Built-In Exception Handling .............................................. 640 11.3.4 Tests for null ............................................................................................................. 641 11.3.5 Checking Index-Related Program Arguments for Correctness ............... 642 11.4 Comparing Objects and Establishing Order ............................................................... 643 11.4.1 Naturally Ordered or Not? ................................................................................... 643 11.4.2 compare*() Method of the Comparable and Comparator Interfaces .................................................................................................................. 644 11.4.3 Return Values Encode the Order ....................................................................... 645 11.4.4 Sorting Candy by Calories Using a Sample Comparator ........................... 645 11.4.5 Tips for Comparator and Comparable Implementations ......................... 647 11.4.6 Static and Default Methods in Comparator .................................................. 648 11.5 Wrapper Classes and Autoboxing .................................................................................. 651 11.5.1 Creating Wrapper Objects ................................................................................... 653 11.5.2 Conversions to a String Representation ......................................................... 65419
Contents11.5.3 Parsing from a String Representation ............................................................. 655 11.5.4 The Number Base Class for Numeric Wrapper Objects ............................. 655 11.5.5 Performing Comparisons with compare*(...), compareTo(...), equals(...), and Hash Values ................................................................................ 657 11.5.6 Static Reduction Methods in Wrapper Classes ............................................ 660 11.5.7 Constants for the Size of a Primitive Type* ................................................... 661 11.5.8 Handling Unsigned Numbers* ........................................................................... 661 11.5.9 The Integer and Long Classes ............................................................................. 663 11.5.10 The Double and Float Classes for Floats ......................................................... 664 11.5.11 The Boolean Class ................................................................................................... 664 11.5.12 Autoboxing: Boxing and Unboxing .................................................................. 665 11.6 Iterator, Iterable* ................................................................................................................... 670 11.6.1 The Iterator Interface ............................................................................................ 670 11.6.2 The Supplier of the Iterator ................................................................................. 673 11.6.3 The Iterable Interface ............................................................................................ 674 11.6.4 Extended for and Iterable .................................................................................... 674 11.6.5 Internal Iteration .................................................................................................... 675 11.6.6 Implementing a Custom Iterable* .................................................................... 676 11.7 Annotations in Java Platform, Standard Edition ..................................................... 677 11.7.1 Places for Annotations .......................................................................................... 677 11.7.2 Annotation Types from java.lang ...................................................................... 678 11.7.3 @Deprecated ........................................................................................................... 678 11.7.4 Annotations with Additional Information ..................................................... 679 11.7.5 @SuppressWarnings ............................................................................................. 679 11.8 Further Reading ...................................................................................................................... 682 12 Generics<T> 683 12.1 Introduction to Java Generics .......................................................................................... 683 12.1.1 Man versus Machine: Type Checking of the Compiler and the Runtime Environment .......................................................................................... 683 12.1.2 Rockets ....................................................................................................................... 684 12.1.3 Declaring Generic Types ....................................................................................... 686 12.1.4 Using Generics ......................................................................................................... 688 12.1.5 Diamonds Are Forever .......................................................................................... 690 12.1.6 Generic Interfaces .................................................................................................. 693 12.1.7 Generic Methods/Constructors and Type Inference .................................. 695 12.2 Implementing Generics, Type Erasure, and Raw Types ........................................ 699 12.2.1 Implementation Options ..................................................................................... 699 12.2.2 Type Erasure ............................................................................................................. 69920
Contents12.2.3 Problems with Type Erasure ............................................................................... 700 12.2.4 Raw Types ................................................................................................................. 704 12.3 Restricting Types via Bounds ........................................................................................... 706 12.3.1 Simple Restrictions with extends ..................................................................... 707 12.3.2 Other Supertypes with & ..................................................................................... 709 12.4 Type Parameters in the throws Clause* ...................................................................... 710 12.4.1 Declaring a Class with Type Variable <E extends Exception> ................. 710 12.4.2 Parameterized Type for Type Variable <E extends Exception> ............... 710 12.5 Inheritance and Invariance with Generics ................................................................. 713 12.5.1 Arrays Are Covariant .............................................................................................. 713 12.5.2 Generics Aren’t Covariant, but Invariant ........................................................ 714 12.5.3 Wildcards with ? ..................................................................................................... 715 12.5.4 Bounded Wildcards ................................................................................................ 717 12.5.5 Bounded Wildcard Types and Bounded Type Variables ............................ 720 12.5.6 The PECS Principle .................................................................................................. 722 12.6 Consequences of Type Erasure: Type Tokens, Arrays* .......................................... 725 12.6.1 Type Tokens .............................................................................................................. 725 12.6.2 Supertype Tokens ................................................................................................... 727 12.6.3 Generics and Arrays ............................................................................................... 728 12.7 Further Reading ...................................................................................................................... 729 13 Lambda Expressions and Functional Programming 731 13.1 Functional Interfaces and Lambda Expressions ....................................................... 731 13.1.1 Classes Implement Interfaces ............................................................................ 731 13.1.2 Lambda Expressions Implement Interfaces .................................................. 733 13.1.3 Functional Interfaces ............................................................................................ 734 13.1.4 The Type of a Lambda Expression Depends on the Target Type ............ 735 13.1.5 @FunctionalInterface Annotations ................................................................. 740 13.1.6 Syntax for Lambda Expressions ......................................................................... 741 13.1.7 The Environment of Lambda Expressions and Variable Accesses ......... 745 13.1.8 Exceptions in Lambda Expressions ................................................................... 751 13.1.9 Classes with an Abstract Method as a Functional Interface?* ................ 755 13.2 Method References ............................................................................................................... 755 13.2.1 Motivation ................................................................................................................ 755 13.2.2 Method References with :: .................................................................................. 756 13.2.3 Variations of Method References ..................................................................... 75621
Comments 0
Loading comments...
Reply to Comment
Edit Comment