0% found this document useful (0 votes)
172 views

Sample CoreJava For The Imaptient

dgg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

Sample CoreJava For The Imaptient

dgg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Core Java

for the Impatient


Third Edition
This page intentionally left blank
Core Java
for the Impatient
Third Edition

Cay S. Horstmann

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
Cover illustration by Morphart Creation / Shutterstock
Figures 1.1 and 1.3: Microsoft
Figure 1.2: Eclipse Foundation
Figures 1.4, 1.5, 11.1: Oracle Corporation

Many of the designations used by manufacturers and sellers to distinguish their


products are claimed as trademarks. Where those designations appear in this book,
and the publisher was aware of a trademark claim, the designations have been
printed with initial capital letters or in all capitals.

The author and publisher have taken care in the preparation of this book, but make
no expressed or implied warranty of any kind and assume no responsibility for
errors or omissions. No liability is assumed for incidental or consequential damages
in connection with or arising out of the use of the information or programs contained
herein.

For information about buying this title in bulk quantities, or for special sales
opportunities (which may include electronic versions; custom cover designs; and
content particular to your business, training goals, marketing focus, or branding
interests), please contact our corporate sales department at
[email protected] or (800) 382-3419.

For government sales inquiries, please contact [email protected].

For questions about sales outside the United States, please contact
[email protected].

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2022942895

Copyright © 2023 Pearson Education, Inc.

All rights reserved. This publication is protected by copyright, and permission must
be obtained from the publisher prior to any prohibited reproduction, storage in a
retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding permissions, request
forms and the appropriate contacts within the Pearson Education Global Rights &
Permissions Department, please visit www.pearson.com/permissions/.

ISBN-13: 978-0-13-805210-2
ISBN-10: 0-13-805210-7

ScoutAutomatedPrintCode
Pearson’s Commitment to Diversity, Equity, and
Inclusion

Pearson is dedicated to creating bias-free content that reflects the diver-


sity of all learners. We embrace the many dimensions of diversity, in-
cluding but not limited to race, ethnicity, gender, socioeconomic status,
ability, age, sexual orientation, and religious or political beliefs.
Education is a powerful force for equity and change in our world. It has
the potential to deliver opportunities that improve lives and enable
economic mobility. As we work with authors to create content for every
product and service, we acknowledge our responsibility to demonstrate
inclusivity and incorporate diverse scholarship so that everyone can
achieve their potential through learning. As the world’s leading learning
company, we have a duty to help drive change and live up to our pur-
pose to help more people create a better life for themselves and to create
a better world.
Our ambition is to purposefully contribute to a world where:
• Everyone has an equitable and lifelong opportunity to succeed
through learning.
• Our educational products and services are inclusive and represent
the rich diversity of learners.
• Our educational content accurately reflects the histories and
experiences of the learners we serve.
• Our educational content prompts deeper discussions with learners
and motivates them to expand their own learning (and worldview).
While we work hard to present unbiased content, we want to hear from
you about any concerns or needs with this Pearson product so that we
can investigate and address them.
• Please contact us with concerns about any potential bias at
https://www.pearson.com/report-bias.html.
This page intentionally left blank
To Chi—the most patient person in my life.
This page intentionally left blank
Contents

Preface xxiii
Acknowledgments xxv
About the Author xxvii

1 FUNDAMENTAL PROGRAMMING STRUCTURES 1


1.1 Our First Program 2
1.1.1 Dissecting the “Hello, World” Program 2
1.1.2 Compiling and Running a Java Program 4
1.1.3 Method Calls 6
1.1.4 JShell 7
1.2 Primitive Types 11
1.2.1 Signed Integer Types 11
1.2.2 Floating-Point Types 13
1.2.3 The char Type 14
1.2.4 The boolean Type 14
1.3 Variables 14
1.3.1 Variable Declarations 15
1.3.2 Identifiers 15

ix
x Contents

1.3.3 Initialization 16
1.3.4 Constants 16
1.4 Arithmetic Operations 17
1.4.1 Assignment 18
1.4.2 Basic Arithmetic 19
1.4.3 Mathematical Methods 20
1.4.4 Number Type Conversions 21
1.4.5 Relational and Logical Operators 22
1.4.6 Big Numbers 24
1.5 Strings 25
1.5.1 Concatenation 25
1.5.2 Substrings 26
1.5.3 String Comparison 26
1.5.4 Converting Between Numbers and Strings 28
1.5.5 The String API 28
1.5.6 Code Points and Code Units 31
1.5.7 Text Blocks 33
1.6 Input and Output 35
1.6.1 Reading Input 35
1.6.2 Formatted Output 36
1.7 Control Flow 38
1.7.1 Branches 38
1.7.2 Switches 39
1.7.3 Loops 41
1.7.4 Breaking and Continuing 43
1.7.5 Local Variable Scope 45
1.8 Arrays and Array Lists 46
1.8.1 Working with Arrays 46
1.8.2 Array Construction 47
1.8.3 Array Lists 48
1.8.4 Wrapper Classes for Primitive Types 49
1.8.5 The Enhanced for Loop 50
1.8.6 Copying Arrays and Array Lists 51
1.8.7 Array Algorithms 52
Contents xi

1.8.8 Command-Line Arguments 52


1.8.9 Multidimensional Arrays 53
1.9 Functional Decomposition 56
1.9.1 Declaring and Calling Static Methods 56
1.9.2 Array Parameters and Return Values 56
1.9.3 Variable Arguments 57
Exercises 58

2 OBJECT-ORIENTED PROGRAMMING 61
2.1 Working with Objects 62
2.1.1 Accessor and Mutator Methods 64
2.1.2 Object References 65
2.2 Implementing Classes 67
2.2.1 Instance Variables 67
2.2.2 Method Headers 67
2.2.3 Method Bodies 68
2.2.4 Instance Method Invocations 68
2.2.5 The this Reference 69
2.2.6 Call by Value 70
2.3 Object Construction 71
2.3.1 Implementing Constructors 71
2.3.2 Overloading 72
2.3.3 Calling One Constructor from Another 73
2.3.4 Default Initialization 73
2.3.5 Instance Variable Initialization 74
2.3.6 Final Instance Variables 75
2.3.7 The Constructor with No Arguments 75
2.4 Records 76
2.4.1 The Record Concept 77
2.4.2 Constructors: Canonical, Custom, and Compact 78
2.5 Static Variables and Methods 79
2.5.1 Static Variables 79
2.5.2 Static Constants 80
2.5.3 Static Initialization Blocks 81
xii Contents

2.5.4 Static Methods 81


2.5.5 Factory Methods 83
2.6 Packages 83
2.6.1 Package Declarations 83
2.6.2 The jar Command 85
2.6.3 The Class Path 86
2.6.4 Package Access 87
2.6.5 Importing Classes 88
2.6.6 Static Imports 89
2.7 Nested Classes 90
2.7.1 Static Nested Classes 90
2.7.2 Inner Classes 91
2.7.3 Special Syntax Rules for Inner Classes 94
2.8 Documentation Comments 95
2.8.1 Comment Insertion 95
2.8.2 Class Comments 96
2.8.3 Method Comments 97
2.8.4 Variable Comments 97
2.8.5 General Comments 97
2.8.6 Links 98
2.8.7 Package, Module, and Overview Comments 99
2.8.8 Comment Extraction 99
Exercises 100

3 INTERFACES AND LAMBDA EXPRESSIONS 105


3.1 Interfaces 106
3.1.1 Using Interfaces 106
3.1.2 Declaring an Interface 107
3.1.3 Implementing an Interface 108
3.1.4 Converting to an Interface Type 110
3.1.5 Casts and the instanceof Operator 110
3.1.6 The “Pattern-Matching” Form of instanceof 111
3.1.7 Extending Interfaces 112
Contents xiii

3.1.8 Implementing Multiple Interfaces 113


3.1.9 Constants 113
3.2 Static, Default, and Private Methods 113
3.2.1 Static Methods 113
3.2.2 Default Methods 114
3.2.3 Resolving Default Method Conflicts 115
3.2.4 Private Methods 117
3.3 Examples of Interfaces 117
3.3.1 The Comparable Interface 117
3.3.2 The Comparator Interface 119
3.3.3 The Runnable Interface 120
3.3.4 User Interface Callbacks 120
3.4 Lambda Expressions 121
3.4.1 The Syntax of Lambda Expressions 122
3.4.2 Functional Interfaces 123
3.5 Method and Constructor References 124
3.5.1 Method References 124
3.5.2 Constructor References 126
3.6 Processing Lambda Expressions 127
3.6.1 Implementing Deferred Execution 127
3.6.2 Choosing a Functional Interface 128
3.6.3 Implementing Your Own Functional Interfaces 130
3.7 Lambda Expressions and Variable Scope 131
3.7.1 Scope of a Lambda Expression 131
3.7.2 Accessing Variables from the Enclosing Scope 132
3.8 Higher-Order Functions 135
3.8.1 Methods that Return Functions 135
3.8.2 Methods That Modify Functions 135
3.8.3 Comparator Methods 136
3.9 Local and Anonymous Classes 137
3.9.1 Local Classes 137
3.9.2 Anonymous Classes 138
Exercises 139
xiv Contents

4 INHERITANCE AND REFLECTION 143


4.1 Extending a Class 144
4.1.1 Super- and Subclasses 145
4.1.2 Defining and Inheriting Subclass Methods 145
4.1.3 Method Overriding 145
4.1.4 Subclass Construction 147
4.1.5 Superclass Assignments 147
4.1.6 Casts 148
4.1.7 Anonymous Subclasses 149
4.1.8 Method Expressions with super 150
4.2 Inheritance Hierarchies 150
4.2.1 Final Methods and Classes 150
4.2.2 Abstract Methods and Classes 151
4.2.3 Protected Access 152
4.2.4 Sealed Types 153
4.2.5 Inheritance and Default Methods 157
4.3 Object: The Cosmic Superclass 157
4.3.1 The toString Method 158
4.3.2 The equals Method 159
4.3.3 The hashCode Method 162
4.3.4 Cloning Objects 163
4.4 Enumerations 166
4.4.1 Methods of Enumerations 166
4.4.2 Constructors, Methods, and Fields 168
4.4.3 Bodies of Instances 168
4.4.4 Static Members 169
4.4.5 Switching on an Enumeration 170
4.5 Runtime Type Information and Resources 170
4.5.1 The Class Class 170
4.5.2 Loading Resources 174
4.5.3 Class Loaders 174
4.5.4 The Context Class Loader 176
4.5.5 Service Loaders 177
Contents xv

4.6 Reflection 179


4.6.1 Enumerating Class Members 179
4.6.2 Inspecting Objects 180
4.6.3 Invoking Methods 182
4.6.4 Constructing Objects 182
4.6.5 JavaBeans 183
4.6.6 Working with Arrays 185
4.6.7 Proxies 186
Exercises 188

5 EXCEPTIONS, ASSERTIONS, AND LOGGING 191


5.1 Exception Handling 192
5.1.1 Throwing Exceptions 192
5.1.2 The Exception Hierarchy 193
5.1.3 Declaring Checked Exceptions 195
5.1.4 Catching Exceptions 196
5.1.5 The Try-with-Resources Statement 197
5.1.6 The finally Clause 199
5.1.7 Rethrowing and Chaining Exceptions 201
5.1.8 Uncaught Exceptions and the Stack Trace 202
5.1.9 API Methods for Throwing Exceptions 203
5.2 Assertions 204
5.2.1 Using Assertions 204
5.2.2 Enabling and Disabling Assertions 205
5.3 Logging 206
5.3.1 Should You Use the Java Logging
Framework? 206
5.3.2 Logging 101 207
5.3.3 The Platform Logging API 208
5.3.4 Logging Configuration 209
5.3.5 Log Handlers 211
5.3.6 Filters and Formatters 213
Exercises 214
xvi Contents

6 GENERIC PROGRAMMING 219


6.1 Generic Classes 220
6.2 Generic Methods 221
6.3 Type Bounds 222
6.4 Type Variance and Wildcards 223
6.4.1 Subtype Wildcards 224
6.4.2 Supertype Wildcards 225
6.4.3 Wildcards with Type Variables 226
6.4.4 Unbounded Wildcards 227
6.4.5 Wildcard Capture 228
6.5 Generics in the Java Virtual Machine 228
6.5.1 Type Erasure 229
6.5.2 Cast Insertion 229
6.5.3 Bridge Methods 230
6.6 Restrictions on Generics 231
6.6.1 No Primitive Type Arguments 231
6.6.2 At Runtime, All Types Are Raw 232
6.6.3 You Cannot Instantiate Type Variables 233
6.6.4 You Cannot Construct Arrays of Parameterized
Types 235
6.6.5 Class Type Variables Are Not Valid in Static
Contexts 236
6.6.6 Methods May Not Clash after Erasure 236
6.6.7 Exceptions and Generics 237
6.7 Reflection and Generics 238
6.7.1 The Class<T> Class 239
6.7.2 Generic Type Information in the Virtual
Machine 239
Exercises 241

7 COLLECTIONS 247
7.1 An Overview of the Collections Framework 248
7.2 Iterators 252
7.3 Sets 254
Contents xvii

7.4 Maps 255


7.5 Other Collections 259
7.5.1 Properties 259
7.5.2 Bit Sets 260
7.5.3 Enumeration Sets and Maps 262
7.5.4 Stacks, Queues, Deques, and Priority Queues 262
7.5.5 Weak Hash Maps 263
7.6 Views 264
7.6.1 Small Collections 264
7.6.2 Ranges 265
7.6.3 Unmodifiable Views 266
Exercises 267

8 STREAMS 271
8.1 From Iterating to Stream Operations 272
8.2 Stream Creation 273
8.3 The filter, map, and flatMap Methods 276
8.4 Extracting Substreams and Combining Streams 278
8.5 Other Stream Transformations 279
8.6 Simple Reductions 280
8.7 The Optional Type 281
8.7.1 Producing an Alternative 281
8.7.2 Consuming the Value If Present 281
8.7.3 Pipelining Optional Values 282
8.7.4 How Not to Work with Optional Values 282
8.7.5 Creating Optional Values 284
8.7.6 Composing Optional Value Functions with flatMap 284
8.7.7 Turning an Optional into a Stream 285
8.8 Collecting Results 286
8.9 Collecting into Maps 287
8.10 Grouping and Partitioning 289
8.11 Downstream Collectors 289
8.12 Reduction Operations 292
8.13 Primitive Type Streams 294
xviii Contents

8.14 Parallel Streams 295


Exercises 298

9 PROCESSING INPUT AND OUTPUT 301


9.1 Input/Output Streams, Readers, and Writers 302
9.1.1 Obtaining Streams 302
9.1.2 Reading Bytes 303
9.1.3 Writing Bytes 304
9.1.4 Character Encodings 305
9.1.5 Text Input 307
9.1.6 Text Output 308
9.1.7 Reading and Writing Binary Data 310
9.1.8 Random-Access Files 310
9.1.9 Memory-Mapped Files 311
9.1.10 File Locking 312
9.2 Paths, Files, and Directories 312
9.2.1 Paths 312
9.2.2 Creating Files and Directories 314
9.2.3 Copying, Moving, and Deleting Files 315
9.2.4 Visiting Directory Entries 316
9.2.5 ZIP File Systems 319
9.3 HTTP Connections 320
9.3.1 The URLConnection and HttpURLConnection Classes 320
9.3.2 The HTTP Client API 321
9.4 Regular Expressions 323
9.4.1 The Regular Expression Syntax 324
9.4.2 Testing a Match 329
9.4.3 Finding All Matches 329
9.4.4 Groups 330
9.4.5 Splitting along Delimiters 331
9.4.6 Replacing Matches 332
9.4.7 Flags 333
9.5 Serialization 333
9.5.1 The Serializable Interface 334
Contents xix

9.5.2 Transient Instance Variables 336


9.5.3 The readObject and writeObject Methods 336
9.5.4 The readExternal and writeExternal Methods 338
9.5.5 The readResolve and writeReplace Methods 339
9.5.6 Versioning 340
9.5.7 Deserialization and Security 342
Exercises 344

10 CONCURRENT PROGRAMMING 347


10.1 Concurrent Tasks 348
10.1.1 Running Tasks 348
10.1.2 Futures 351
10.2 Asynchronous Computations 353
10.2.1 Completable Futures 353
10.2.2 Composing Completable Futures 355
10.2.3 Long-Running Tasks in User-Interface Callbacks 358
10.3 Thread Safety 360
10.3.1 Visibility 360
10.3.2 Race Conditions 362
10.3.3 Strategies for Safe Concurrency 364
10.3.4 Immutable Classes 365
10.4 Parallel Algorithms 366
10.4.1 Parallel Streams 366
10.4.2 Parallel Array Operations 367
10.5 Threadsafe Data Structures 368
10.5.1 Concurrent Hash Maps 369
10.5.2 Blocking Queues 370
10.5.3 Other Threadsafe Data Structures 372
10.6 Atomic Counters and Accumulators 373
10.7 Locks and Conditions 375
10.7.1 Locks 375
10.7.2 The synchronized Keyword 377
10.7.3 Waiting on Conditions 379
10.8 Threads 381
xx Contents

10.8.1 Starting a Thread 381


10.8.2 Thread Interruption 382
10.8.3 Thread-Local Variables 384
10.8.4 Miscellaneous Thread Properties 385
10.9 Processes 386
10.9.1 Building a Process 386
10.9.2 Running a Process 388
10.9.3 Process Handles 389
Exercises 390

11 ANNOTATIONS 397
11.1 Using Annotations 398
11.1.1 Annotation Elements 398
11.1.2 Multiple and Repeated Annotations 400
11.1.3 Annotating Declarations 400
11.1.4 Annotating Type Uses 401
11.1.5 Making Receivers Explicit 402
11.2 Defining Annotations 403
11.3 Standard Annotations 406
11.3.1 Annotations for Compilation 407
11.3.2 Meta-Annotations 408
11.4 Processing Annotations at Runtime 410
11.5 Source-Level Annotation Processing 413
11.5.1 Annotation Processors 413
11.5.2 The Language Model API 414
11.5.3 Using Annotations to Generate Source Code 415
Exercises 417

12 THE DATE AND TIME API 421


12.1 The Time Line 422
12.2 Local Dates 424
12.3 Date Adjusters 428
12.4 Local Time 429
12.5 Zoned Time 430
Contents xxi

12.6 Formatting and Parsing 433


12.7 Interoperating with Legacy Code 436
Exercises 437

13 INTERNATIONALIZATION 441
13.1 Locales 442
13.1.1 Specifying a Locale 443
13.1.2 The Default Locale 445
13.1.3 Display Names 446
13.2 Number Formats 447
13.3 Currencies 448
13.4 Date and Time Formatting 449
13.5 Collation and Normalization 451
13.6 Message Formatting 453
13.7 Resource Bundles 455
13.7.1 Organizing Resource Bundles 455
13.7.2 Bundle Classes 457
13.8 Character Encodings 458
13.9 Preferences 459
Exercises 461

14 COMPILING AND SCRIPTING 463


14.1 The Compiler API 463
14.1.1 Invoking the Compiler 464
14.1.2 Launching a Compilation Task 464
14.1.3 Capturing Diagnostics 465
14.1.4 Reading Source Files from Memory 465
14.1.5 Writing Byte Codes to Memory 466
14.2 The Scripting API 467
14.2.1 Getting a Scripting Engine 468
14.2.2 Evaluating Scripts 468
14.2.3 Bindings 469
14.2.4 Redirecting Input and Output 469
14.2.5 Calling Scripting Functions and Methods 470
xxii Contents

14.2.6 Compiling a Script 471


Exercises 472

15 THE JAVA PLATFORM MODULE SYSTEM 475


15.1 The Module Concept 476
15.2 Naming Modules 478
15.3 The Modular “Hello, World!” Program 478
15.4 Requiring Modules 480
15.5 Exporting Packages 482
15.6 Modules and Reflective Access 485
15.7 Modular JARs 488
15.8 Automatic Modules 489
15.9 The Unnamed Module 491
15.10 Command-Line Flags for Migration 491
15.11 Transitive and Static Requirements 493
15.12 Qualified Exporting and Opening 495
15.13 Service Loading 496
15.14 Tools for Working with Modules 497
Exercises 499

Index 501
Preface

Java has seen many changes since its initial release in 1996. The classic book,
Core Java, covers, in meticulous detail, not just the language but all core li-
braries and a multitude of changes between versions, spanning two volumes
and over 2,000 pages. However, if you just want to be productive with
modern Java, there is a much faster, easier pathway for learning the language
and core libraries. In this book, I don’t retrace history and don’t dwell on
features of past versions. I show you the good parts of Java as it exists today,
so you can put your knowledge to work quickly.
As with my previous “Impatient” books, I quickly cut to the chase, showing
you what you need to know to solve a programming problem without lecturing
about the superiority of one paradigm over another. I also present the infor-
mation in small chunks, organized so that you can quickly retrieve it when
needed.
Assuming you are proficient in some other programming language, such as
C++, JavaScript, Swift, PHP, or Ruby, with this book you will learn how to
become a competent Java programmer. I cover all aspects of Java that a de-
veloper needs to know today, including the powerful concepts of lambda
expressions and streams, as well as modern constructs such as records and
sealed classes.
A key reason to use Java is to tackle concurrent programming. With parallel
algorithms and threadsafe data structures readily available in the Java library,

xxiii
xxiv Preface

the way application programmers should handle concurrent programming


has completely changed. I provide fresh coverage, showing you how to use
the powerful library features instead of error-prone low-level constructs.
Traditionally, books on Java have focused on user interface programming,
but nowadays, few developers produce user interfaces on desktop computers.
If you intend to use Java for server-side programming or Android program-
ming, you will be able to use this book effectively without being distracted
by desktop GUI code.
Finally, this book is written for application programmers, not for a college
course and not for systems wizards. The book covers issues that application
programmers need to wrestle with, such as logging and working with files,
but you won’t learn how to implement a linked list by hand or how to write
a web server.
I hope you enjoy this rapid-fire introduction into modern Java, and I hope it
will make your work with Java productive and enjoyable.
If you find errors or have suggestions for improvement, please visit
http://horstmann.com/javaimpatient, head for the errata page, and leave a comment.
Be sure to visit that site to download the runnable code examples that
complement this book.

Register your copy of Core Java for the Impatient, Third Edition, on the InformIT
site for convenient access to updates and/or corrections as they become
available. To start the registration process, go to informit.com/register and log
in or create an account. Enter the product ISBN (9780138052102) and click
Submit. Look on the Registered Products tab for an Access Bonus Content
link next to this product, and follow that link to access any available bonus
materials. If you would like to be notified of exclusive offers on new editions
and updates, please check the box to receive email from us.
Acknowledgments

My thanks go, as always, to my editor Greg Doench, who enthusiastically


supported the vision of a short book that gives a fresh introduction to Java.
Dmitry Kirsanov and Alina Kirsanova once again turned an XHTML manuscript
into an attractive book with amazing speed and attention to detail. My special
gratitude goes to the excellent team of reviewers for all editions who spotted
many errors and gave thoughtful suggestions for improvement. They are:
Andres Almiray, Gail Anderson, Paul Anderson, Marcus Biel, Brian Goetz,
Mark Lawrence, Doug Lea, Simon Ritter, Yoshiki Shibata, and Christian
Ullenboom.
Cay Horstmann
Berlin
August 2022

xxv
This page intentionally left blank
About the Author

Cay S. Horstmann is the author of JavaScript for the Impatient and Scala for
the Impatient (both from Addison-Wesley), is principal author of Core Java,
Volumes I and II, Twelfth Edition (Pearson, 2022), and has written a dozen
other books for professional programmers and computer science students.
He is professor emeritus of computer science at San Jose State University and
is a Java Champion.

xxvii
Fundamental
Programming
Structures

Topics in This Chapter


1.1 Our First Program — page 2
1.2 Primitive Types — page 11
1.3 Variables — page 14
1.4 Arithmetic Operations — page 17
1.5 Strings — page 25
1.6 Input and Output — page 35
1.7 Control Flow — page 38
1.8 Arrays and Array Lists — page 46
1.9 Functional Decomposition — page 56
Exercises — page 58
Processing
Input and Output

Topics in This Chapter


9.1 Input/Output Streams, Readers, and Writers — page 302
9.2 Paths, Files, and Directories — page 312
9.3 HTTP Connections — page 320
9.4 Regular Expressions — page 323
9.5 Serialization — page 333
Exercises — page 344
Chapter 9

In this chapter, you will learn how to work with files, directories, and web
pages, and how to read and write data in binary and text format. You will
also find a discussion of regular expressions, which can be useful for process-
ing input. (I couldn’t think of a better place to handle that topic, and appar-
ently neither could the Java developers—when the regular expression API
specification was proposed, it was attached to the specification request for
“new I/O” features.) Finally, this chapter shows you the object serialization
mechanism that lets you store objects as easily as you can store text or
numeric data.
The key points of this chapter are:
1. An InputStream is a source of bytes, and an OutputStream is a destination for
bytes.
2. A Reader reads characters, and a Writer writes them. Be sure to specify a
character encoding.
3. The Files class has convenience methods for reading all bytes or lines of
a file.
4. The DataInput and DataOutput interfaces have methods for writing numbers
in binary format.
5. Use a RandomAccessFile or a memory-mapped file for random access.

301
302 Chapter 9 Processing Input and Output

6. A Path is an absolute or relative sequence of path components in a file


system. Paths can be combined (or “resolved”).
7. Use the methods of the Files class to copy, move, or delete files and to
recursively walk through a directory tree.
8. To read or update a ZIP file, use a ZIP file system.
9. You can read the contents of a web page with the URL class. To read
metadata or write data, use the URLConnection class.
10. With the Pattern and Matcher classes, you can find all matches of a regular
expression in a string, as well as the captured groups for each match.
11. The serialization mechanism can save and restore any object implementing
the Serializable interface, provided its instance variables are also serializable.

9.1 Input/Output Streams, Readers, and Writers


In the Java API, a source from which one can read bytes is called an input
stream. The bytes can come from a file, a network connection, or an array in
memory. (These streams are unrelated to the streams of Chapter 8.) Similarly,
a destination for bytes is an output stream. In contrast, readers and writers
consume and produce sequences of characters. In the following sections, you
will learn how to read and write bytes and characters.

9.1.1 Obtaining Streams


The easiest way to obtain a stream from a file is with the static methods
InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(path);

Here, path is an instance of the Path class that is covered in Section 9.2.1,
“Paths” (page 312). It describes a path in a file system.
If you have a URL, you can read its contents from the input stream returned
by the openStream method of the URL class:
var url = new URL("https://horstmann.com/index.html");
InputStream in = url.openStream();

Section 9.3, “HTTP Connections” (page 320) shows how to send data to a
web server.
The ByteArrayInputStream class lets you read from an array of bytes.
9.1 Input/Output Streams, Readers, and Writers 303

byte[] bytes = ...;


var in = new ByteArrayInputStream(bytes);
Read from in
Conversely, to send output to a byte array, use a ByteArrayOutputStream:
var out = new ByteArrayOutputStream();
Write to out
byte[] bytes = out.toByteArray();

9.1.2 Reading Bytes


The InputStream class has a method to read a single byte:
InputStream in = ...;
int b = in.read();

This method either returns the byte as an integer between 0 and 255, or returns
-1 if the end of input has been reached.

CAUTION: The Java byte type has values between -128 and 127. You
can cast the returned value into a byte after you have checked that it
is not -1.

More commonly, you will want to read the bytes in bulk. The most convenient
method is the readAllBytes method that simply reads all bytes from the stream
into a byte array:
byte[] bytes = in.readAllBytes();

TIP: If you want to read all bytes from a file, call the convenience
method
byte[] bytes = Files.readAllBytes(path);

If you want to read some, but not all bytes, provide a byte array and call the
readNBytes method:
var bytes = new byte[len];
int bytesRead = in.readNBytes(bytes, offset, n);

The method reads until either n bytes are read or no further input is available,
and returns the actual number of bytes read. If no input was available at all,
the methods return -1.
304 Chapter 9 Processing Input and Output

NOTE: There is also a read(byte[], int, int) method whose description


seems exactly like readNBytes. The difference is that the read method only
attempts to read the bytes and returns immediately with a lower count
if it fails. The readNBytes method keeps calling read until all requested
bytes have been obtained or read returns -1.

Finally, you can skip bytes:


long bytesToSkip = ...;
in.skipNBytes(bytesToSkip);

9.1.3 Writing Bytes


The write methods of an OutputStream can write individual bytes and byte arrays.
OutputStream out = ...;
int b = ...;
out.write(b);
byte[] bytes = ...;
out.write(bytes);
out.write(bytes, start, length);

When you are done writing a stream, you must close it in order to commit
any buffered output. This is best done with a try-with-resources statement:
try (OutputStream out = ...) {
out.write(bytes);
}

If you need to copy an input stream to an output stream, use the


InputStream.transferTo method:
try (InputStream in = ...; OutputStream out = ...) {
in.transferTo(out);
}

Both streams need to be closed after the call to transferTo. It is best to use a
try-with-resources statement, as in the code example.
To write a file to an OutputStream, call
Files.copy(path, out);

Conversely, to save an InputStream to a file, call


Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
9.1 Input/Output Streams, Readers, and Writers 305

9.1.4 Character Encodings


Input and output streams are for sequences of bytes, but in many cases you
will work with text—that, is, sequences of characters. It then matters how
characters are encoded into bytes.
Java uses the Unicode standard for characters. Each character or “code point”
has a 21-bit integer number. There are different character encodings—methods
for packaging those 21-bit numbers into bytes.
The most common encoding is UTF-8, which encodes each Unicode code
point into a sequence of one to four bytes (see Table 9-1). UTF-8 has the
advantage that the characters of the traditional ASCII character set, which
contains all characters used in English, only take up one byte each.

Table 9-1 UTF-8 Encoding


Character range Encoding

0...7F 0a6a5a4a3a2a1a0

80...7FF 110a10a9a8a7a6 10a5a4a3a2a1a0

800...FFFF 1110a15a14a13a12 10a11a10a9a8a7a6 10a5a4a3a2a1a0

10000...10FFFF 11110a20a19a18 10a17a16a15a14a13a12 10a11a10a9a8a7a6 10a5a4a3a2a1a0

Another common encoding is UTF-16, which encodes each Unicode code


point into one or two 16-bit values (see Table 9-2). This is the encoding used
in Java strings. Actually, there are two forms of UTF-16, called “big-endian”
and “little-endian.” Consider the 16-bit value 0x2122. In big-endian format, the
more significant byte comes first: 0x21 followed by 0x22. In little-endian format,
it is the other way around: 0x22 0x21. To indicate which of the two is used, a
file can start with the “byte order mark,” the 16-bit quantity 0xFEFF. A reader
can use this value to determine the byte order and discard it.

Table 9-2 UTF-16 Encoding


Character range Encoding

0...FFFF a15a14a13a12a11a10a9a8a7a6a5a4a3a2a1a0

10000...10FFFF 110110b19b18b17b16a15a14a13a12a11a10 110111a9a8a7a6a5a4a3a2a1a0


where b19b18b17b16 = a20a19a18a17a16 – 1
306 Chapter 9 Processing Input and Output

CAUTION: Some programs, including Microsoft Notepad, add a byte


order mark at the beginning of UTF-8 encoded files. Clearly, this is
unnecessary since there are no byte ordering issues in UTF-8. But the
Unicode standard allows it, and even suggests that it’s a pretty good
idea since it leaves little doubt about the encoding. It is supposed to
be removed when reading a UTF-8 encoded file. Sadly, Java does not
do that, and bug reports against this issue are closed as “will not fix.”
Your best bet is to strip out any leading \uFEFF that you find in your
input.

In addition to the UTF encodings, there are partial encodings that cover a
character range suitable for a given user population. For example, ISO 8859-1
is a one-byte code that includes accented characters used in Western European
languages. Shift_ JIS is a variable-length code for Japanese characters. A large
number of these encodings are still in widespread use.
There is no reliable way to automatically detect the character encoding from
a stream of bytes. Some API methods let you use the “default charset”—the
character encoding that is preferred by the operating system of the computer.
Is that the same encoding that is used by your source of bytes? These bytes
may well originate from a different part of the world. Therefore, you should
always explicitly specify the encoding. For example, when reading a web
page, check the Content-Type header.

NOTE: The platform encoding is returned by the static method


Charset.defaultCharset. The static method Charset.availableCharsets returns
all available Charset instances, as a map from canonical names to Charset
objects.

CAUTION: The Oracle implementation has a system property file.encoding


for overriding the platform default. This is not an officially supported
property, and it is not consistently followed by all parts of Oracle’s
implementation of the Java library. You should not set it.

The StandardCharsets class has static variables of type Charset for the character
encodings that every Java virtual machine must support:
StandardCharsets.UTF_8
StandardCharsets.UTF_16
StandardCharsets.UTF_16BE
StandardCharsets.UTF_16LE
9.1 Input/Output Streams, Readers, and Writers 307

StandardCharsets.ISO_8859_1
StandardCharsets.US_ASCII

To obtain the Charset for another encoding, use the static forName method:
Charset shiftJIS = Charset.forName("Shift_JIS");

Use the Charset object when reading or writing text. For example, you can
turn an array of bytes into a string as
var contents = new String(bytes, StandardCharsets.UTF_8);

TIP: Some methods allow you to specify a character encoding with a


Charset object or a string. Choose the StandardCharsets constants, so you
don’t have to worry about the correct spelling. For example, new
String(bytes, "UTF 8") is not acceptable and will cause a runtime error.

CAUTION: Some methods (such as the String(byte[]) constructor) use


the default platform encoding if you don’t specify any; others (such as
Files.readAllLines) use UTF-8.

9.1.5 Text Input


To read text input, use a Reader. You can obtain a Reader from any input stream
with the InputStreamReader adapter:
InputStream inStream = ...;
var in = new InputStreamReader(inStream, charset);

If you want to process the input one UTF-16 code unit at a time, you can
call the read method:
int ch = in.read();

The method returns a code unit between 0 and 65536, or -1 at the end of input.
That is not very convenient. Here are several alternatives.
With a short text file, you can read it into a string like this:
String content = Files.readString(path, charset);

But if you want the file as a sequence of lines, call


List<String> lines = Files.readAllLines(path, charset);

If the file is large, process them lazily as a Stream<String>:


try (Stream<String> lines = Files.lines(path, charset)) {
...
}
308 Chapter 9 Processing Input and Output

NOTE: If an IOException occurs as the stream fetches the lines, that


exception is wrapped into an UncheckedIOException which is thrown out of
the stream operation. (This subterfuge is necessary because stream
operations are not declared to throw any checked exceptions.)

To read numbers or words from a file, use a Scanner, as you have seen in
Chapter 1. For example,
var in = new Scanner(path, StandardCharsets.UTF_8);
while (in.hasNextDouble()) {
double value = in.nextDouble();
...
}

TIP: To read alphabetic words, set the scanner’s delimiter to a regular


expression that is the complement of what you want to accept as a
token. For example, after calling
in.useDelimiter("\\PL+");

the scanner reads in letters since any sequence of nonletters is a


delimiter. See Section 9.4.1, “The Regular Expression Syntax” (page 324)
for the regular expression syntax.
You can then obtain a stream of all words as
Stream<String> words = in.tokens();

If your input does not come from a file, wrap the InputStream into a BufferedReader:
try (var reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
Stream<String> lines = reader.lines();
...
}

A BufferedReader reads input in chunks for efficiency. (Oddly, this is not an


option for basic readers.) It has methods readLine to read a single line and
lines to yield a stream of lines.

If a method asks for a Reader and you want it to read from a file, call
Files.newBufferedReader(path, charset).

9.1.6 Text Output


To write text, use a Writer. With the write method, you can write strings. You
can turn any output stream into a Writer:
9.1 Input/Output Streams, Readers, and Writers 309

OutputStream outStream = ...;


var out = new OutputStreamWriter(outStream, charset);
out.write(str);

To get a writer for a file, use


Writer out = Files.newBufferedWriter(path, charset);

It is more convenient to use a PrintWriter, which has the print, println, and
printf that you have always used with System.out. Using those methods, you
can print numbers and use formatted output.
If you write to a file, construct a PrintWriter like this:
var out = new PrintWriter(Files.newBufferedWriter(path, charset));

If you write to another stream, use


var out = new PrintWriter(new OutputStreamWriter(outStream, charset));

NOTE: System.out is an instance of PrintStream, not PrintWriter. This is a


relic from the earliest days of Java. However, the print, println, and
printf methods work the same way for the PrintStream and PrintWriter
classes, using a character encoding for turning characters into bytes.

If you already have the text to write in a string, call


String content = ...;
Files.write(path, content.getBytes(charset));

or
Files.write(path, lines, charset);

Here, lines can be a Collection<String>, or even more generally, an Iterable<?


extends CharSequence>.

To append to a file, use


Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);
Files.write(path, lines, charset, StandardOpenOption.APPEND);

CAUTION: When writing text with a partial character set such as


ISO 8859-1, any unmappable characters are silently changed to a
“replacement”—in most cases, either the ? character or the Unicode
replacement character U+FFFD.

Sometimes, a library method wants a Writer to write output. If you want to


capture that output in a string, hand it a StringWriter. Or, if it wants a PrintWriter,
wrap the StringWriter like this:
310 Chapter 9 Processing Input and Output

var writer = new StringWriter();


throwable.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();

9.1.7 Reading and Writing Binary Data


The DataInput interface declares the following methods for reading a number,
a character, a boolean value, or a string in binary format:
byte readByte()
int readUnsignedByte()
char readChar()
short readShort()
int readUnsignedShort()
int readInt()
long readLong()
float readFloat()
double readDouble()
void readFully(byte[] b)

The DataOutput interface declares corresponding write methods.

NOTE: These methods read and write numbers in big-endian format.

CAUTION: There are also readUTF/writeUTF methods that use a “modified


UTF-8” format. These methods are not compatible with regular UTF-8,
and are only useful for JVM internals.

The advantage of binary I/O is that it is fixed width and efficient. For example,
writeInt always writes an integer as a big-endian 4-byte binary quantity regard-
less of the number of digits. The space needed is the same for each value of
a given type, which speeds up random access. Also, reading binary data is
faster than parsing text. The main drawback is that the resulting files cannot
be easily inspected in a text editor.
You can use the DataInputStream and DataOutputStream adapters with any stream.
For example,
DataInput in = new DataInputStream(Files.newInputStream(path));
DataOutput out = new DataOutputStream(Files.newOutputStream(path));

9.1.8 Random-Access Files


The RandomAccessFile class lets you read or write data anywhere in a file. You
can open a random-access file either for reading only or for both reading and
9.1 Input/Output Streams, Readers, and Writers 311

writing; specify the option by using the string "r" (for read access) or "rw" (for
read/write access) as the second argument in the constructor. For example,
var file = new RandomAccessFile(path.toString(), "rw");

A random-access file has a file pointer that indicates the position of the next
byte to be read or written. The seek method sets the file pointer to an arbitrary
byte position within the file. The argument to seek is a long integer between
zero and the length of the file (which you can obtain with the length method).
The getFilePointer method returns the current position of the file pointer.
The RandomAccessFile class implements both the DataInput and DataOutput interfaces.
To read and write numbers from a random-access file, use methods such as
readInt/writeInt that you saw in the preceding section. For example,
int value = file.readInt();
file.seek(file.getFilePointer() - 4);
file.writeInt(value + 1);

9.1.9 Memory-Mapped Files


Memory-mapped files provide another, very efficient approach for random
access that works well for very large files. However, the API for data access
is completely different from that of input/output streams. First, get a channel
to the file:
FileChannel channel = FileChannel.open(path,
StandardOpenOption.READ, StandardOpenOption.WRITE)

Then, map an area of the file (or, if it is not too large, the entire file) into
memory:
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE,
0, channel.size());

Use methods get, getInt, getDouble, and so on to read values, and the equivalent
put methods to write values.
int offset = ...;
int value = buffer.getInt(offset);
buffer.put(offset, value + 1);

At some point, and certainly when the channel is closed, these changes are
written back to the file.

NOTE: By default, the methods for reading and writing numbers use
big-endian byte order. You can change the byte order with the command
buffer.order(ByteOrder.LITTLE_ENDIAN);
312 Chapter 9 Processing Input and Output

9.1.10 File Locking


When multiple simultaneously executing programs modify the same file, they
need to communicate in some way, or the file can easily become damaged.
File locks can solve this problem.
Suppose your application saves a configuration file with user preferences. If
a user invokes two instances of the application, it could happen that both of
them want to write the configuration file at the same time. In that situation,
the first instance should lock the file. When the second instance finds the
file locked, it can decide to wait until the file is unlocked or simply skip
the writing process. To lock a file, call either the lock or tryLock methods of the
FileChannel class.
FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE);
FileLock lock = channel.lock();

or
FileLock lock = channel.tryLock();

The first call blocks until the lock becomes available. The second call returns
immediately, either with the lock or with null if the lock is not available. The
file remains locked until the lock or the channel is closed. It is best to use a
try-with-resources statement:
try (FileLock lock = channel.lock()) {
...
}

9.2 Paths, Files, and Directories


You have already seen Path objects for specifying file paths. In the following
sections, you will see how to manipulate these objects and how to work with
files and directories.

9.2.1 Paths
A Path is a sequence of directory names, optionally followed by a file name.
The first component of a path may be a root component, such as / or C:\. The
permissible root components depend on the file system. A path that starts
with a root component is absolute. Otherwise, it is relative. For example, here
we construct an absolute and a relative path. For the absolute path, we
assume we are running on a Unix-like file system.
Path absolute = Path.of("/", "home", "cay");
Path relative = Path.of("myapp", "conf", "user.properties");
9.2 Paths, Files, and Directories 313

The static Path.of method receives one or more strings, which it joins with
the path separator of the default file system (/ for a Unix-like file system, \
for Windows). It then parses the result, throwing an InvalidPathException if the
result is not a valid path in the given file system. The result is a Path object.
You can also provide a string with separators to the Path.of method:
Path homeDirectory = Path.of("/home/cay");

NOTE: A Path object does not have to correspond to a file that actually
exists. It is merely an abstract sequence of names. To create a file, first
make a path, then call a method to create the corresponding file—see
Section 9.2.2, “Creating Files and Directories” (page 314).

It is very common to combine or “resolve” paths. The call p.resolve(q) returns


a path according to these rules:
• If q is absolute, then the result is q.
• Otherwise, the result is “p then q,” according to the rules of the file system.
For example, suppose your application needs to find its configuration file
relative to the home directory. Here is how you can combine the paths:
Path workPath = homeDirectory.resolve("myapp/work");
// Same as homeDirectory.resolve(Path.of("myapp/work"));

There is a convenience method resolveSibling that resolves against a path’s


parent, yielding a sibling path. For example, if workPath is /home/cay/myapp/work,
the call
Path tempPath = workPath.resolveSibling("temp");

yields /home/cay/myapp/temp.

The opposite of resolve is relativize. The call p.relativize(r) yields the path q
which, when resolved with p, yields r. For example,
Path.of("/home/cay").relativize(Path.of("/home/fred/myapp"))

yields ../fred/myapp, assuming we have a file system that uses .. to denote the
parent directory.
The normalize method removes any redundant . and .. components (or what-
ever the file system may deem redundant). For example, normalizing the path
/home/cay/../fred/./myapp yields /home/fred/myapp.

The toAbsolutePath method yields the absolute path of a given path. If the path
is not already absolute, it is resolved against the “user directory”—that is, the
directory from which the JVM was invoked. For example, if you launched
314 Chapter 9 Processing Input and Output

a program from /home/cay/myapp, then Path.of("config").toAbsolutePath() returns


/home/cay/myapp/config.

The Path interface has methods for taking paths apart and combining them
with other paths. This code sample shows some of the most useful ones:
Path p = Path.of("/home", "cay", "myapp.properties");
Path parent = p.getParent(); // The path /home/cay
Path file = p.getFileName(); // The last element, myapp.properties
Path root = p.getRoot(); // The initial segment / (null for a relative path)
Path first = p.getName(0); // The first element
Path dir = p.subpath(1, p.getNameCount());
// All but the first element, cay/myapp.properties

The Path interface extends the Iterable<Path> element, so you can iterate over
the name components of a Path with an enhanced for loop:
for (Path component : path) {
...
}

NOTE: Occasionally, you may need to interoperate with legacy APIs that
use the File class instead of the Path interface. The Path interface has a
toFile method, and the File class has a toPath method.

9.2.2 Creating Files and Directories


To create a new directory, call
Files.createDirectory(path);

All but the last component in the path must already exist. To create
intermediate directories as well, use
Files.createDirectories(path);

You can create an empty file with


Files.createFile(path);

The call throws an exception if the file already exists. The checks for existence
and the creation are atomic. If the file doesn’t exist, it is created before anyone
else has a chance to do the same.
The call Files.exists(path) checks whether the given file or directory exists. To
test whether it is a directory or a “regular” file (that is, with data in it, not
something like a directory or symbolic link), call the static methods isDirectory
and isRegularFile of the Files class.
9.2 Paths, Files, and Directories 315

There are convenience methods for creating a temporary file or directory in


a given or system-specific location.
Path tempFile = Files.createTempFile(dir, prefix, suffix);
Path tempFile = Files.createTempFile(prefix, suffix);
Path tempDir = Files.createTempDirectory(dir, prefix);
Path tempDir = Files.createTempDirectory(prefix);

Here, dir is a Path, and prefix/suffix are strings which may be null. For
example, the call Files.createTempFile(null, ".txt") might return a path such as
/tmp/1234405522364837194.txt.

9.2.3 Copying, Moving, and Deleting Files


To copy a file from one location to another, simply call
Files.copy(fromPath, toPath);

To move a file (that is, copy and delete the original), call
Files.move(fromPath, toPath);

You can also use this command to move an empty directory.


The copy or move will fail if the target exists. If you want to overwrite
an existing target, use the REPLACE_EXISTING option. If you want to copy all file
attributes, use the COPY_ATTRIBUTES option. You can supply both like this:
Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);

You can specify that a move should be atomic. Then you are assured that
either the move completed successfully, or the source continues to be present.
Use the ATOMIC_MOVE option:
Files.move(fromPath, toPath, StandardCopyOption.ATOMIC_MOVE);

See Table 9-3 for a summary of the options that are available for file
operations.
Finally, to delete a file, simply call
Files.delete(path);

This method throws an exception if the file doesn’t exist, so instead you may
want to use
boolean deleted = Files.deleteIfExists(path);

The deletion methods can also be used to remove an empty directory.


316 Chapter 9 Processing Input and Output

Table 9-3 Standard Options for File Operations


Option Description

StandardOpenOption; use with newBufferedWriter, newInputStream, newOutputStream, write

READ Open for reading.


WRITE Open for writing.
APPEND If opened for writing, append to the end of the file.
TRUNCATE_EXISTING If opened for writing, remove existing contents.
CREATE_NEW Create a new file and fail if it exists.
CREATE Atomically create a new file if it doesn’t exist.
DELETE_ON_CLOSE Make a “best effort” to delete the file when it is closed.
SPARSE A hint to the file system that this file will be sparse.
DSYNC|SYNC Requires that each update to the file data|data and metadata
be written synchronously to the storage device.
StandardCopyOption; use with copy, move

ATOMIC_MOVE Move the file atomically.


COPY_ATTRIBUTES Copy the file attributes.
REPLACE_EXISTING Replace the target if it exists.
LinkOption; use with all of the above methods and exists, isDirectory, isRegularFile

NOFOLLOW_LINKS Do not follow symbolic links.


FileVisitOption; use with find, walk, walkFileTree

FOLLOW_LINKS Follow symbolic links.

9.2.4 Visiting Directory Entries


The static Files.list method returns a Stream<Path> that reads the entries of
a directory. The directory is read lazily, making it possible to efficiently process
directories with huge numbers of entries.
Since reading a directory involves a system resource that needs to be closed,
you should use a try-with-resources block:
try (Stream<Path> entries = Files.list(pathToDirectory)) {
...
}
9.2 Paths, Files, and Directories 317

The list method does not enter subdirectories. To process all descendants of
a directory, use the Files.walk method instead.
try (Stream<Path> entries = Files.walk(pathToRoot)) {
// Contains all descendants, visited in depth-first order
}

Here is a sample traversal of the unzipped src.zip tree:


java
java/nio
java/nio/DirectCharBufferU.java
java/nio/ByteBufferAsShortBufferRL.java
java/nio/MappedByteBuffer.java
...
java/nio/ByteBufferAsDoubleBufferB.java
java/nio/charset
java/nio/charset/CoderMalfunctionError.java
java/nio/charset/CharsetDecoder.java
java/nio/charset/UnsupportedCharsetException.java
java/nio/charset/spi
java/nio/charset/spi/CharsetProvider.java
java/nio/charset/StandardCharsets.java
java/nio/charset/Charset.java
...
java/nio/charset/CoderResult.java
java/nio/HeapFloatBufferR.java
...

As you can see, whenever the traversal yields a directory, it is entered before
continuing with its siblings.
You can limit the depth of the tree that you want to visit by calling
Files.walk(pathToRoot, depth). Both walk methods have a varargs parameter of type
FileVisitOption..., but there is only one option you can supply: FOLLOW_LINKS to
follow symbolic links.

NOTE: If you filter the paths returned by walk and your filter criterion
involves the file attributes stored with a directory, such as size, creation
time, or type (file, directory, symbolic link), then use the find method
instead of walk. Call that method with a predicate function that accepts
a path and a BasicFileAttributes object. The only advantage is efficiency.
Since the directory is being read anyway, the attributes are readily
available.
318 Chapter 9 Processing Input and Output

This code fragment uses the Files.walk method to copy one directory to another:
Files.walk(source).forEach(p -> {
try {
Path q = target.resolve(source.relativize(p));
if (Files.isDirectory(p))
Files.createDirectory(q);
else
Files.copy(p, q);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});

Unfortunately, you cannot easily use the Files.walk method to delete a tree of
directories since you need to first visit the children before deleting the parent.
In that case, use the walkFileTree method. It requires an instance of the FileVisitor
interface. Here is when the file visitor gets notified:
1. Before a directory is processed:
FileVisitResult preVisitDirectory(T dir, IOException ex)

2. When a file is encountered:


FileVisitResult visitFile(T path, BasicFileAttributes attrs)

3. When an exception occurs in the visitFile method:


FileVisitResult visitFileFailed(T path, IOException ex)

4. After a directory is processed:


FileVisitResult postVisitDirectory(T dir, IOException ex)
In each case, the notification method returns one of the following results:
• Continue visiting the next file: FileVisitResult.CONTINUE

• Continue the walk, but without visiting the entries in this directory:
FileVisitResult.SKIP_SUBTREE

• Continue the walk, but without visiting the siblings of this file:
FileVisitResult.SKIP_SIBLINGS

• Terminate the walk: FileVisitResult.TERMINATE

If any of the methods throws an exception, the walk is also terminated, and
that exception is thrown from the walkFileTree method.
The SimpleFileVisitor class implements this interface, continuing the iteration
at each point and rethrowing any exceptions.
Here is how you can delete a directory tree:
9.2 Paths, Files, and Directories 319

Files.walkFileTree(root, new SimpleFileVisitor<Path>() {


public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
public FileVisitResult postVisitDirectory(Path dir,
IOException ex) throws IOException {
if (ex != null) throw ex;
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});

9.2.5 ZIP File Systems


The Paths class looks up paths in the default file system—the files on the user’s
local disk. You can have other file systems. One of the more useful ones is a
ZIP file system. If zipname is the name of a ZIP file, then the call
FileSystem zipfs = FileSystems.newFileSystem(Path.of(zipname));

establishes a file system that contains all files in the ZIP archive. It’s an easy
matter to copy a file out of that archive if you know its name:
Files.copy(zipfs.getPath(sourceName), targetPath);

Here, zipfs.getPath is the analog of Path.of for an arbitrary file system.


To list all files in a ZIP archive, walk the file tree:
Files.walk(zipfs.getPath("/")).forEach(p -> {
Process p
});

You have to work a bit harder to create a new ZIP file. Here is the magic
incantation:
Path zipPath = Path.of("myfile.zip");
var uri = new URI("jar", zipPath.toUri().toString(), null);
// Constructs the URI jar:file://myfile.zip
try (FileSystem zipfs = FileSystems.newFileSystem(uri,
Collections.singletonMap("create", "true"))) {
// To add files, copy them into the ZIP file system
Files.copy(sourcePath, zipfs.getPath("/").resolve(targetPath));
}

NOTE: There is an older API for working with ZIP archives, with classes
ZipInputStream and ZipOutputStream, but it’s not as easy to use as the one
described in this section.
320 Chapter 9 Processing Input and Output

9.3 HTTP Connections


You can read from a URL by using the input stream returned from
URL.getInputStream method. However, if you want additional information about
a web resource, or if you want to write data, you need more control over
the process than the URL class provides. The URLConnection class was designed
before HTTP was the universal protocol of the Web. It provides support for
a number of protocols, but its HTTP support is somewhat cumbersome. When
the decision was made to support HTTP/2, it became clear that it would be
best to provide a modern client interface instead of reworking the existing
API. The HttpClient provides a more convenient API and HTTP/2 support.
In the following sections, I provide a cookbook for using the HttpURLConnection
class, and then give an overview of the API.

9.3.1 The URLConnection and HttpURLConnection Classes


To use the URLConnection class, follow these steps:
1. Get an URLConnection object:
URLConnection connection = url.openConnection();

For an HTTP URL, the returned object is actually an instance of


HttpURLConnection.

2. If desired, set request properties:


connection.setRequestProperty("Accept-Charset", "UTF-8, ISO-8859-1");

If a key has multiple values, separate them by commas.


3. To send data to the server, call
connection.setDoOutput(true);
try (OutputStream out = connection.getOutputStream()) {
// Write to out
}

4. If you want to read the response headers and you haven’t called
getOutputStream, call
connection.connect();

Then query the header information:


Map<String, List<String>> headers = connection.getHeaderFields();

For each key, you get a list of values since there may be multiple header
fields with the same key.
9.3 HTTP Connections 321

5. Read the response:


try (InputStream in = connection.getInputStream()) {
// Read from in
}
A common use case is to post form data. The URLConnection class automatically
sets the content type to application/x-www-form-urlencoded when writing data to a
HTTP URL, but you need to encode the name/value pairs:
URL url = ...;
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
try (var out = new OutputStreamWriter(
connection.getOutputStream(), StandardCharsets.UTF_8)) {
Map<String, String> postData = ...;
boolean first = true;
for (Map.Entry<String, String> entry : postData.entrySet()) {
if (first) first = false;
else out.write("&");
out.write(URLEncoder.encode(entry.getKey(), "UTF-8"));
out.write("=");
out.write(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
}
try (InputStream in = connection.getInputStream()) {
...
}

9.3.2 The HTTP Client API


The HTTP client API provides another mechanism for connecting to a web
server which is simpler than the URLConnection class with its rather fussy set of
stages. More importantly, the implementation supports HTTP/2.
An HttpClient can issue requests and receive responses. You get a client by
calling
HttpClient client = HttpClient.newHttpClient();

Alternatively, if you need to configure the client, use a builder API like this:
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();

That is, you get a builder, call methods to customize the item that is going
to be built, and then call the build method to finalize the building process.
This is a common pattern for constructing immutable objects.
Follow the same pattern for formulating requests. Here is a GET request:
322 Chapter 9 Processing Input and Output

HttpRequest request = HttpRequest.newBuilder()


.uri(new URI("https://horstmann.com"))
.GET()
.build();

The URI is the “uniform resource identifier” which is, when using HTTP, the
same as a URL. However, in Java, the URL class has methods for actually
opening a connection to a URL, whereas the URI class is only concerned with
the syntax (scheme, host, port, path, query, fragment, and so on).
When sending the request, you have to tell the client how to handle the
response. If you just want the body as a string, send the request with a
HttpResponse.BodyHandlers.ofString(), like this:
HttpResponse<String> response
= client.send(request, HttpResponse.BodyHandlers.ofString());

The HttpResponse class is a template whose type denotes the type of the body.
You get the response body string simply as
String bodyString = response.body();

There are other response body handlers that get the response as a byte array
or a file. One can hope that eventually the JDK will support JSON and provide
a JSON handler.
With a POST request, you similarly need a “body publisher” that turns the re-
quest data into the data that is being posted. There are body publishers for
strings, byte arrays, and files. Again, one can hope that the library designers
will wake up to the reality that most POST requests involve form data or JSON
objects, and provide appropriate publishers.
In the meantime, to send a form post, you need to URL-encode the request
data, just like in the preceding section.
Map<String, String> postData = ...;
boolean first = true;
var body = new StringBuilder();
for (Map.Entry<String, String> entry : postData.entrySet()) {
if (first) first = false;
else body.append("&");
body.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
body.append("=");
body.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
HttpRequest request = HttpRequest.newBuilder()
.uri(httpUrlString)
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body.toString()))
.build();
9.4 Regular Expressions 323

Note that, unlike with the URLConnection class, you need to specify the content
type for forms.
Similarly, for posting JSON data, you specify the content type and provide a
JSON string.
The HttpResponse object also yields the status code and the response headers.
int status = response.statusCode();
HttpHeaders responseHeaders = response.headers();

You can turn the HttpHeaders object into a map:


Map<String, List<String>> headerMap = responseHeaders.map();

The map values are lists since in HTTP, each key can have multiple values.
If you just want the value of a particular key, and you know that there won’t
be multiple values, call the firstValue method:
Optional<String> lastModified = headerMap.firstValue("Last-Modified");

You get the response value or an empty optional if none was supplied.

TIP: To enable logging for the HttpClient, add this line to net.properties
in your JDK:
jdk.httpclient.HttpClient.log=all

Instead of all, you can specify a comma-separated list of headers, requests,


content, errors, ssl, trace, and frames, optionally followed by :control, :data,
:window, or :all. Don’t use any spaces.

Then set the logging level for the logger named jdk.httpclient.HttpClient
to INFO, for example by adding this line to the logging.properties file in
your JDK:
jdk.httpclient.HttpClient.level=INFO

9.4 Regular Expressions


Regular expressions specify string patterns. Use them whenever you need to
locate strings that match a particular pattern. For example, suppose you want
to find hyperlinks in an HTML file. You need to look for strings of the pattern
<a href="...">. But wait—there may be extra spaces, or the URL may be enclosed
in single quotes. Regular expressions give you a precise syntax for specifying
what sequences of characters are legal matches.
In the following sections, you will see the regular expression syntax used by
the Java API, and how to put regular expressions to work.
324 Chapter 9 Processing Input and Output

9.4.1 The Regular Expression Syntax


In a regular expression, a character denotes itself unless it is one of the
reserved characters
. * + ? { | ( ) [ \ ^ $

For example, the regular expression Java only matches the string Java.

The symbol . matches any single character. For example, .a.a matches Java
and data.
The * symbol indicates that the preceding constructs may be repeated 0 or
more times; for a +, it is 1 or more times. A suffix of ? indicates that a con-
struct is optional (0 or 1 times). For example, be+s? matches be, bee, and bees.
You can specify other multiplicities with { } (see Table 9-4).
A | denotes an alternative: .(oo|ee)f matches beef or woof. Note the parenthe-
ses—without them, .oo|eef would be the alternative between .oo and eef.
Parentheses are also used for grouping—see Section 9.4.4, “Groups” (page 330).
A character class is a set of character alternatives enclosed in brackets, such
as [Jj], [0-9], [A-Za-z], or [^0-9]. Inside a character class, the - denotes a range
(all characters whose Unicode values fall between the two bounds). However,
a - that is the first or last character in a character class denotes itself. A ^ as
the first character in a character class denotes the complement (all characters
except those specified).
There are many predefined character classes such as \d (digits) or \p{Sc} (Unicode
currency symbols). See Tables 9-4 and 9-5.
The characters ^ and $ match the beginning and end of input.
If you need to have a literal . * + ? { | ( ) [ \ ^ $, precede it by a backslash.
Inside a character class, you only need to escape [ and \, provided you are
careful about the positions of ] - ^. For example, []^-] is a class containing
all three of them.
Alternatively, surround a string with \Q and \E. For example, \(\$0\.99\) and
\Q($0.99)\E both match the string ($0.99).

TIP: If you have a string that may contain some of the many special
characters in the regular expression syntax, you can escape them all by
calling Parse.quote(str). This simply surrounds the string with \Q and \E,
but it takes care of the special case where str may contain \E.
9.4 Regular Expressions 325

Table 9-4 Regular Expression Syntax


Expression Description Example

Characters

c, not one of . * + ? { | The character c. J


( ) [ \ ^ $

. Any character except


line terminators, or any
character if the DOTALL
flag is set.
\x{p} The Unicode code point \x{1D546}
with hex code p.
\uhhhh, \xhh, \0o, \0oo, The UTF-16 code unit \uFEFF
\0ooo with the given hex or
octal value.
\a, \e, \f, \n, \r, \t Alert (\x{7}), escape \n
(\x{1B}), form feed
(\x{B}), newline (\x{A}),
carriage return (\x{D}),
tab (\x{9}).
\cc, where c is in [A-Z] The control character \cH is a backspace (\x{8}).
or one of @ [ \ ] ^ _ ? corresponding to the
character c.
\c, where c is not in The character c. \\
[A-Za-z0-9]

\Q ... \E Everything between the \Q(...)\E matches the


start and the end of string (...).
the quotation.
Character Classes

[C1C2...], where Ci are Any of the characters [0-9+-]


characters, ranges c-d, or represented by C1,
character classes C2, . . .
[^...] Complement of a [^\d\s]
character class.
[...&&...] Intersection of character [\p{L}&&[^A-Za-z]]
classes.
(Continues)
326 Chapter 9 Processing Input and Output

Table 9-4 Regular Expression Syntax (Continued)


Expression Description Example

\p{...}, \P{...} A predefined character \p{L} matches a Unicode


class (see Table 9-5); its letter, and so does
complement. \pL—you can omit braces
around a single letter.
\d, \D Digits ([0-9], or \d+ is a sequence of
\p{Digit} when the digits.
UNICODE_CHARACTER_CLASS
flag is set); the
complement.
\w, \W Word characters
([a-zA-Z0-9_], or Unicode
word characters when
the UNICODE_CHARACTER_CLASS
flag is set); the
complement.
\s, \S Spaces ([\n\r\t\f\x{B}], \s*,\s* is a comma
or \p{IsWhite_Space} when surrounded by optional
the UNICODE_CHARACTER_CLASS white space.
flag is set); the
complement.
\h, \v, \H, \V Horizontal whitespace,
vertical whitespace, their
complements.
Sequences and Alternatives

XY Any string from X, [1-9][0-9]* is a positive


followed by any string number without leading
from Y. zero.
X|Y Any string from X or Y. http|ftp

Grouping

(X) Captures the match of X. '([^']*)' captures the


quoted text.
\n The nth group. (['"]).*\1 matches 'Fred'
or "Fred" but not "Fred'.
(Continues)
9.4 Regular Expressions 327

Table 9-4 Regular Expression Syntax (Continued)


Expression Description Example

(?<name>X) Captures the match of X '(?<id>[A-Za-z0-9]+)'


with the given name. captures the match with
name id.
\k<name> The group with the \k<id> matches the group
given name. with name id.
(?:X) Use parentheses without In (?:http|ftp)://(.*), the
capturing X. match after :// is \1.
(?f1f2...:X), Matches, but does not (?i:jpe?g) is a
(?f1...-fk...:X), with fi in capture, X with the case-insensitive match.
[dimsuUx] given flags on or off
(after -).
Other (?...) See the Pattern API
documentation.
Quantifiers

X? Optional X. \+? is an optional + sign.

X*, X+ 0 or more X, 1 or [1-9][0-9]+ is an integer


more X. ≥ 10.
X{n}, X{n,}, X{m,n} n times X, at least n [0-7]{1,3} are one to three
times X, between m and octal digits.
n times X.
Q?, where Q is a Reluctant quantifier, .*(<.+?>).* captures the
quantified expression attempting the shortest shortest sequence
match before trying enclosed in angle
longer matches. brackets.
Q+, where Q is a Possessive quantifier, '[^']*+' matches strings
quantified expression taking the longest match enclosed in single quotes
without backtracking. and fails quickly on
strings without a closing
quote.
Boundary Matches

^ $ Beginning, end of input ^Java$ matches the input


(or beginning, end of or line Java.
line in multiline mode).
(Continues)
328 Chapter 9 Processing Input and Output

Table 9-4 Regular Expression Syntax (Continued)


Expression Description Example

\A \Z \z Beginning of input, end


of input, absolute end of
input (unchanged in
multiline mode).
\b \B Word boundary, \bJava\b matches the word
nonword boundary. Java.

\R A Unicode line break.


\G The end of the previous
match.

Table 9-5 Predefined Character Classes \p{...}

Name Description

posixClass posixClass is one of Lower, Upper, Alpha,


Digit, Alnum, Punct, Graph, Print, Cntrl,
XDigit, Space, Blank, ASCII, interpreted as
POSIX or Unicode class, depending on
the UNICODE_CHARACTER_CLASS flag.
IsScript, sc=Script, script=Script A script accepted by
Character.UnicodeScript.forName.

InBlock, blk=Block, block=Block A block accepted by


Character.UnicodeBlock.forName.

Category, InCategory, gc=Category, A one- or two-letter name for a


general_category=Category Unicode general category.
IsProperty Property is one of Alphabetic, Ideographic,
Letter, Lowercase, Uppercase, Titlecase,
Punctuation, Control, White_Space, Digit,
Hex_Digit, Join_Control,
Noncharacter_Code_Point, Assigned.

javaMethod Invokes the method Character.isMethod


(must not be deprecated).
9.4 Regular Expressions 329

9.4.2 Testing a Match


Generally, there are two ways to use a regular expression: Either you want
to test whether a string conforms to the expression, or you want to find all
matches of the expressions in a string.
In the first case, simply use the static matches method:
String regex = "[+-]?\\d+";
CharSequence input = ...;
if (Pattern.matches(regex, input)) {
...
}

If you need to use the same regular expression many times, it is more efficient
to compile it. Then, create a Matcher for each input:
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) ...

If the match succeeds, you can retrieve the location of matched groups—see
Section 9.4.4, “Groups” (page 330).
If you want to test whether the input contains a match, use the find method
instead:
if (matcher.find()) ...

You can turn the pattern into a predicate:


Pattern digits = Pattern.compile("[0-9]+");
List<String> strings = List.of("December", "31st", "1999");
List<String> matchingStrings = strings.stream()
.filter(digits.asMatchPredicate())
.toList(); // ["1999"]

The result contains all strings that match the regular expression.
Use the asPredicate method to test whether a string contains a match:
List<String> sringsContainingMatch = strings.stream()
.filter(digits.asPredicate())
.toList(); // ["31st", "1999"]

9.4.3 Finding All Matches


In this section, we consider the other common use case for regular
expressions—finding all matches in an input. Use this loop:
330 Chapter 9 Processing Input and Output

String input = ...;


Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String match = matcher.group();
int matchStart = matcher.start();
int matchEnd = matcher.end();
...
}

In this way, you can process each match in turn. As shown in the code
fragment, you can get the matched string as well as its position in the input
string.
More elegantly, you can call the results method to get a Stream<MatchResult>. The
MatchResult interface has methods group, start, and end, just like Matcher. (In fact,
the Matcher class implements this interface.) Here is how you get a list of all
matches:
List<String> matches = pattern.matcher(input)
.results()
.map(Matcher::group)
.toList();

If you have the data in a file, then you can use the Scanner.findAll method to
get a Stream<MatchResult>, without first having to read the contents into a string.
You can pass a Pattern or a pattern string:
var in = new Scanner(path, StandardCharsets.UTF_8);
Stream<String> words = in.findAll("\\pL+")
.map(MatchResult::group);

9.4.4 Groups
It is common to use groups for extracting components of a match. For exam-
ple, suppose you have a line item in the invoice with item name, quantity,
and unit price such as
Blackwell Toaster USD29.95

Here is a regular expression with groups for each component:


(\p{Alnum}+(\s+\p{Alnum}+)*)\s+([A-Z]{3})([0-9.]*)

After matching, you can extract the nth group from the matcher as
String contents = matcher.group(n);

Groups are ordered by their opening parenthesis, starting at 1. (Group 0 is


the entire input.) In this example, here is how to take the input apart:
9.4 Regular Expressions 331

Matcher matcher = pattern.matcher(input);


if (matcher.matches()) {
item = matcher.group(1);
currency = matcher.group(3);
price = matcher.group(4);
}

We aren’t interested in group 2; it only arose from the parentheses that were
required for the repetition. For greater clarity, you can use a noncapturing
group:
(\p{Alnum}+(?:\s+\p{Alnum}+)*)\s+([A-Z]{3})([0-9.]*)

Or, even better, capture by name:


(?<item>\p{Alnum}+(\s+\p{Alnum}+)*)\s+(?<currency>[A-Z]{3})(?<price>[0-9.]*)

Then, you can retrieve the items by name:


item = matcher.group("item");

With the start and end methods, you can get the group positions in the input:
int itemStart = matcher.start("item");
int itemEnd = matcher.end("item");

NOTE: Retrieving groups by name only works with a Matcher, not with
a MatchResult.

NOTE: When you have a group inside a repetition, such as


(\s+\p{Alnum}+)* in the example above, it is not possible to get all of its
matches. The group method only yields the last match, which is rarely
useful. You need to capture the entire expression with another group.

9.4.5 Splitting along Delimiters


Sometimes, you want to break an input along matched delimiters and keep
everything else. The Pattern.split method automates this task. You obtain an
array of strings, with the delimiters removed:
String input = ...;
Pattern commas = Pattern.compile("\\s*,\\s*");
String[] tokens = commas.split(input);
// "1, 2, 3" turns into ["1", "2", "3"]
332 Chapter 9 Processing Input and Output

If there are many tokens, you can fetch them lazily:


Stream<String> tokens = commas.splitAsStream(input);

If you don’t care about precompiling the pattern or lazy fetching, you can
just use the String.split method:
String[] tokens = input.split("\\s*,\\s*");

If the input is in a file, use a scanner:


var in = new Scanner(path, StandardCharsets.UTF_8);
in.useDelimiter("\\s*,\\s*");
Stream<String> tokens = in.tokens();

9.4.6 Replacing Matches


If you want to replace all matches of a regular expression with a string, call
replaceAll on the matcher:
Matcher matcher = commas.matcher(input);
String result = matcher.replaceAll(",");
// Normalizes the commas

Or, if you don’t care about precompiling, use the replaceAll method of the
String class.
String result = input.replaceAll("\\s*,\\s*", ",");

The replacement string can contain group numbers $n or names ${name}. They
are replaced with the contents of the corresponding captured group.
String result = "3:45".replaceAll(
"(\\d{1,2}):(?<minutes>\\d{2})",
"$1 hours and ${minutes} minutes");
// Sets result to "3 hours and 45 minutes"

You can use \ to escape $ and \ in the replacement string, or you can call
the Matcher.quoteReplacement convenience method:
matcher.replaceAll(Matcher.quoteReplacement(str))

If you want to carry out a more complex operation than splicing in group
matches, then you can provide a replacement function instead of a replacement
string. The function accepts a MatchResult and yields a string. For example, here
we replace all words with at least four letters with their uppercase version:
String result = Pattern.compile("\\pL{4,}")
.matcher("Mary had a little lamb")
.replaceAll(m -> m.group().toUpperCase());
// Yields "MARY had a LITTLE LAMB"

The replaceFirst method replaces only the first occurrence of the pattern.
9.5 Serialization 333

9.4.7 Flags
Several flags change the behavior of regular expressions. You can specify them
when you compile the pattern:
Pattern pattern = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS);

Or you can specify them inside the pattern:


String regex = "(?iU:expression)";

Here are the flags:


• or i: Match characters independently of the letter
Pattern.CASE_INSENSITIVE
case. By default, this flag takes only US ASCII characters into account.
• Pattern.UNICODE_CASE
or u: When used in combination with CASE_INSENSITIVE, use
Unicode letter case for matching.
• Pattern.UNICODE_CHARACTER_CLASS or U: Select Unicode character classes instead
of POSIX. Implies UNICODE_CASE.

• Pattern.MULTILINE
or m: Make ^ and $ match the beginning and end of a line,
not the entire input.
• Pattern.UNIX_LINESor d: Only '\n' is a line terminator when matching ^ and
$ in multiline mode.
• Pattern.DOTALL or s: Make the . symbol match all characters, including line
terminators.
• Pattern.COMMENTS
or x: Whitespace and comments (from # to the end of a
line) are ignored.
• Pattern.LITERAL: The pattern is taking literally and must be matched exactly,
except possibly for letter case.
• Pattern.CANON_EQ:
Take canonical equivalence of Unicode characters into
account. For example, u followed by ¨ (diaeresis) matches ü.
The last two flags cannot be specified inside a regular expression.

9.5 Serialization
In the following sections, you will learn about object serialization—a mecha-
nism for turning an object into a bunch of bytes that can be shipped some-
where else or stored on disk, and for reconstituting the object from those
bytes.
334 Chapter 9 Processing Input and Output

Serialization is an essential tool for distributed processing, where objects are


shipped from one virtual machine to another. It is also used for fail-over and
load balancing, when serialized objects can be moved to another server. If
you work with server-side software, you will often need to enable serialization
for classes. The following sections tell you how to do that.

9.5.1 The Serializable Interface


In order for an object to be serialized—that is, turned into a bunch of bytes—it
must be an instance of a class that implements the Serializable interface. This
is a marker interface with no methods, similar to the Cloneable interface that
you saw in Chapter 4.
For example, to make Employee objects serializable, the class needs to be
declared as
public class Employee implements Serializable {
private String name;
private double salary;
...
}

It is appropriate for a class to implement the Serializable interface if all instance


variables have primitive or enum type, or contain references to serializable ob-
jects. Many classes in the standard library are serializable. Arrays and the
collection classes that you saw in Chapter 7 are serializable provided their
elements are.
In the case of the Employee class, and indeed with most classes, there is no
problem. In the following sections, you will see what to do when a little extra
help is needed.
To serialize objects, you need an ObjectOutputStream, which is constructed with
another OutputStream that receives the actual bytes.
var out = new ObjectOutputStream(Files.newOutputStream(path));

Now call the writeObject method:


var peter = new Employee("Peter", 90000);
var paul = new Manager("Paul", 180000);
out.writeObject(peter);
out.writeObject(paul);

To read the objects back in, construct an ObjectInputStream:


var in = new ObjectInputStream(Files.newInputStream(path));
9.5 Serialization 335

Retrieve the objects in the same order in which they were written, using the
readObject method.
var e1 = (Employee) in.readObject();
var e2 = (Employee) in.readObject();

When an object is written, the name of the class and the names and values
of all instance variables are saved. If the value of an instance variable belongs
to a primitive type, it is saved as binary data. If it is an object, it is again
written with the writeObject method.
When an object is read in, the process is reversed. The class name and the
names and values of the instance variables are read, and the object is
reconstituted.
There is just one catch. Suppose there were two references to the same object.
Let’s say each employee has a reference to their boss:
var peter = new Employee("Peter", 90000);
var paul = new Manager("Barney", 105000);
var mary = new Manager("Mary", 180000);
peter.setBoss(mary);
paul.setBoss(mary);
out.writeObject(peter);
out.writeObject(paul);

When reading these two objects back in, both of them need to have the same
boss, not two references to identical but distinct objects.
In order to achieve this, each object gets a serial number when it is saved.
When you pass an object reference to writeObject, the ObjectOutputStream checks
if the object reference was previously written. In that case, it just writes out
the serial number and does not duplicate the contents of the object.
In the same way, an ObjectInputStream remembers all objects it has encountered.
When reading in a reference to a repeated object, it simply yields a reference
to the previously read object.

NOTE: If the superclass of a serializable class is not serializable, it must


have an accessible no-argument constructor. Consider this example:
class Person // Not serializable
class Employee extends Person implements Serializable

When an Employee object is deserialized, its instance variables are read


from the object input stream, but the Person instance variables are set
by the Person constructor.
336 Chapter 9 Processing Input and Output

9.5.2 Transient Instance Variables


Certain instance variables should not be serialized—for example, database
connections that are meaningless when an object is reconstituted. Also, when
an object keeps a cache of values, it might be better to drop the cache and
recompute it instead of storing it.
To prevent an instance variable from being serialized, simply tag it with the
transient modifier. Always mark instance variables as transient if they hold
instances of nonserializable classes. Transient instance variables are skipped
when objects are serialized.

9.5.3 The readObject and writeObject Methods


In rare cases, you need to tweak the serialization mechanism. A serializable
class can add any desired action to the default read and write behavior, by
defining methods with the signature
@Serial private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
@Serial private void writeObject(ObjectOutputStream out)
throws IOException

Then, the object headers continue to be written as usual, but the instance
variables fields are no longer automatically serialized. Instead, these methods
are called.
Note the @Serial annotation. The methods for tweaking serialization don’t be-
long to interfaces. Therefore, you can’t use the @Override annotation to have
the compiler check the method declarations. The @Serial annotation is meant
to enable the same checking for serialization methods. Up to Java 17, the
javac compiler doesn’t do that checking, but it might happen in the future.
Some IDEs check the annotation.
A number of classes in the java.awt.geom package, such as Point2D.Double, are not
serializable. Now, suppose you want to serialize a class LabeledPoint that stores
a String and a Point2D.Double. First, you need to mark the Point2D.Double field as
transient to avoid a NotSerializableException.
public class LabeledPoint implements Serializable {
private String label;
private transient Point2D.Double point;
...
}

In the writeObject method, first write the object descriptor and the String field,
label, by calling the defaultWriteObject method. This is a special method of the
ObjectOutputStream class that can only be called from within a writeObject method
9.5 Serialization 337

of a serializable class. Then we write the point coordinates, using the standard
DataOutput calls.
@Serial before private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeDouble(point.getX());
out.writeDouble(point.getY());
}

In the readObject method, we reverse the process:


@Serial before private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
double x = in.readDouble();
double y = in.readDouble();
point = new Point2D.Double(x, y);
}

Another example is the HashSet class that supplies its own readObject and
writeObject methods. Instead of saving the internal structure of the hash table,
the writeObject method simply saves the capacity, load factor, size, and elements.
The readObject method reads back the capacity and load factor, constructs a
new table, and inserts the elements.
The readObject and writeObject methods only need to save and load their
data. They do not concern themselves with superclass data or any other class
information.
The Date class uses this approach. Its writeObject method saves the milliseconds
since the “epoch” (January 1, 1970). The data structure that caches calendar
data is not saved.

CAUTION: Just like a constructor, the readObject method operates on


partially initialized objects. If you call a non-final method inside readObject
that is overridden in a subclass, it may access uninitialized data.

NOTE: If a serializable class defines a field


@Serial private static final ObjectStreamField[] serialPersistentFields

then serialization uses those field descriptors instead of the non-transient


non-static fields. There is also an API for setting the field values before
serialization or reading them after deserialization. This is useful for
preserving a legacy layout after a class has evolved. For example, the
BigDecimal class uses this mechanism to serialize its instances in a format
that no longer reflects the instance fields.
338 Chapter 9 Processing Input and Output

9.5.4 The readExternal and writeExternal Methods


Instead of letting the serialization mechanism save and restore object data,
a class can define its own mechanism. For example, you can encrypt the data
or use a format that is more efficient than the serialization format.
To do this, a class must implement the Externalizable interface. This, in turn,
requires it to define two methods:
public void readExternal(ObjectInputStream in)
throws IOException
public void writeExternal(ObjectOutputStream out)
throws IOException

Unlike the readObject and writeObject methods, these methods are fully respon-
sible for saving and restoring the entire object, including the superclass data.
When writing an object, the serialization mechanism merely records the class
of the object in the output stream. When reading an externalizable object,
the object input stream creates an object with the no-argument constructor
and then calls the readExternal method.
In this example, the LabeledPixel class extends the serializable Point class, but
it takes over the serialization of the class and superclass. The fields of the
object are not stored in the standard serialization format. Instead, the data
are placed in an opaque block.
public class LabeledPixel extends Point implements Externalizable {
private String label;

public LabeledPixel() {} // required for externalizable class

@Override public void writeExternal(ObjectOutput out)


throws IOException {
out.writeInt((int) getX());
out.writeInt((int) getY());
out.writeUTF(label);
}

@Override public void readExternal(ObjectInput in)


throws IOException, ClassNotFoundException {
int x = in.readInt();
int y = in.readInt();
setLocation(x, y);
label = in.readUTF();
}
...
}
9.5 Serialization 339

NOTE: The readExternal and writeExternal methods should not be


annotated with @Serial. Since they are defined in the Externalizable
interface, you can simply annotate them with @Override.

CAUTION: Unlike the readObject and writeObject methods, which are


private and can only be called by the serialization mechanism, the
readExternal and writeExternal methods are public. In particular, readExternal
potentially permits modification of the state of an existing object.

9.5.5 The readResolve and writeReplace Methods


We take it for granted that objects can only be constructed with the construc-
tor. However, a deserialized object is not constructed. Its instance variables are
simply restored from an object stream.
This is a problem if the constructor enforces some condition. For example, a
singleton object may be implemented so that the constructor can only be
called once. As another example, database entities can be constructed so that
they always come from a pool of managed instances.
You shouldn’t implement your own mechanism for singletons. If you need a
singleton, make an enumerated type with one instance that is, by convention,
called INSTANCE.
public enum PersonDatabase {
INSTANCE;

public Person findById(int id) { ... }


...
}

This works because enum are guaranteed to be deserialized properly.


Now let’s suppose that you are in the rare situation where you want to control
the identity of each deserialized instance. As an example, suppose a Person
class wants to restore its instances from a database when deserializing. Then
don’t serialize the object itself but some proxy that can locate or construct
the object. Provide a writeReplace method that returns the proxy object:
public class Person implements Serializable {
private int id;
// Other instance variables
...
340 Chapter 9 Processing Input and Output

@Serial private Object writeReplace() {


return new PersonProxy(id);
}
}

When a Person object is serialized, none of its instance variables are saved.
Instead, the writeReplace method is called and its return value is serialized and
written to the stream.
The proxy class needs to implement a readResolve method that yields a Person
instance:
class PersonProxy implements Serializable {
private int id;

public PersonProxy(int id) {


this.id = id;
}

@Serial private Object readResolve() {


return PersonDatabase.INSTANCE.findById(id);
}
}

When the readObject method finds a PersonProxy in an ObjectInputStream, it


deserializes the proxy, calls its readResolve method, and returns the result.

NOTE: Unlike the readObject and writeObject methods, the readResolve and
writeReplace methods need not be private.

NOTE: With enumerations and records, readObject/writeObject or


readExternal/writeExternal methods are not used for serialization. With
records, but not with enumerations, the writeReplace method will be used.

9.5.6 Versioning
Serialization was intended for sending objects from one virtual machine to
another, or for short-term persistence of state. If you use serialization for
long-term persistence, or in any situation where classes can change between
serialization and deserialization, you will need to consider what happens
when your classes evolve. Can version 2 read the old data? Can the users
who still use version 1 read the files produced by the new version?
The serialization mechanism supports a simple versioning scheme. When an
object is serialized, both the name of the class and its serialVersionUID are
9.5 Serialization 341

written to the object stream. That unique identifier is assigned by the


implementor, by defining an instance variable
@Serial private static final long serialVersionUID = 1L; // Version 1

When the class evolves in an incompatible way, the implementor should


change the UID. Whenever a deserialized object has a nonmatching UID, the
readObject method throws an InvalidClassException.

If the serialVersionUID matches, deserialization proceeds even if the implemen-


tation has changed. Each non-transient instance variable of the object to be
read is set to the value in the serialized state, provided that the name and
type match. All other instance variables are set to the default: null for object
references, zero for numbers, and false for boolean values. Anything in the
serialized state that doesn’t exist in the object to be read is ignored.
Is that process safe? Only the implementor of the class can tell. If it is,
then the implementor should give the new version of the class the same
serialVersionUID as the old version.

If you don’t assign a serialVersionUID, one is automatically generated by hashing


a canonical description of the instance variables, methods, and supertypes.
You can see the hash code with the serialver utility. The command
serialver ch09.sec05.Employee

displays
private static final long serialVersionUID = -4932578720821218323L;

When the class implementation changes, there is a very high probability that
the hash code changes as well.
If you need to be able to read old version instances, and you are certain that
is safe to do so, run serialver on the old version of your class and add the
result to the new version.

NOTE: If you want to implement a more sophisticated versioning scheme,


override the readObject method and call the readFields method instead of
the defaultReadObject method. You get a description of all fields found
in the stream, and you can do with them what you want.

NOTE: Enumerations and records ignore the serialVersionUID field. An


enumeration always has a serialVersionUID of 0L. You can declare the
serialVersionUID of a record, but the IDs don’t have to match for
deserialization.
342 Chapter 9 Processing Input and Output

NOTE: In this section, you saw what happens when the reader’s version
of a class has instance variables that aren’t present in the object stream.
It is also possible during class evolution for a superclass to be added.
Then a reader using the new version may read an object stream in which
the instance variables of the superclass are not set. By default, those
instance fields are set to their 0/false/null default. That may leave the
superclass in an unsafe state. The superclass can defend against that
problem by defining an initialization method
@Serial private void readObjectNoData() throws ObjectStreamException

The method should either set the same state as the no-argument
constructor or throw an InvalidObjectException. It is only called in the
unusual circumstance where an object stream is read that contains an
instance of a subclass with missing superclass data.

9.5.7 Deserialization and Security


During deserialization of a serializable class, objects are created without in-
voking any constructor of the class. Even if the class has a no-argument
constructor, it is not used. The field values are set directly from the values
of the object input stream.

NOTE: For serializable records, deserialization calls the canonical


constructor, passing it the values of the components from the object
input stream. (As a consequence, cyclic references in records are not
restored.)

Bypassing construction is a security risk. An attacker can craft bytes describing


an invalid object that could have never been constructed. Suppose, for exam-
ple, that the Employee constructor throws an exception when called with
a negative salary. We would like to think that no Employee object can have a
negative salary as a result. But it is not difficult to inspect the bytes for a se-
rialized object and modify some of them. This way, one can craft bytes for
an employee with a negative salary and then deserialize them.
A serializable class can optionally implement the ObjectInputValidation interface
and define a validateObject method to check whether its objects are properly
deserialized. For example, the Employee class can check that salaries are not
negative:
9.5 Serialization 343

public void validateObject() throws InvalidObjectException {


System.out.println("validateObject");
if (salary < 0)
throw new InvalidObjectException("salary < 0");
}

Unfortunately, the method is not invoked automatically. To invoke it, you


also must provide the following method:
@Serial private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.registerValidation(this, 0);
in.defaultReadObject();
}

The object is then scheduled for validation, and the validateObject method is
called when this object and all dependent objects have been loaded. The
second parameter lets you specify a priority. Validation requests with higher
priorities are done first.
There are other security risks. Adversaries can create data structures that
consume enough resources to crash a virtual machine. More insidiously, any
class on the class path can be deserialized. Hackers have been devious about
piecing together “gadget chains”—sequences of operations in various utility
classes that use reflection and culminate in calling methods such as Runtime.exec
with a string of their choice.
Any application that receives serialized data from untrusted sources over a
network connection is vulnerable to such attacks. For example, some servers
serialize session data and deserialize whatever data are returned in the HTTP
session cookie.
You should avoid situations in which arbitrary data from untrusted sources
are deserialized. In the example of session data, the server should sign the
data, and only deserialize data with a valid signature.
A serialization filter mechanism can harden applications from such attacks. The
filters see the names of deserialized classes and several metrics (stream size,
array sizes, total number of references, longest chain of references). Based
on those data, the deserialization can be aborted.
In its simplest form, you provide a pattern describing the valid and invalid
classes. For example, if you start our sample serialization demo as
java -Djdk.serialFilter='serial.*;java.**;!*' serial.ObjectStreamTest

then the objects will be loaded. The filter allows all classes in the serial
package and all classes whose package name starts with java, but no others.
If you don’t allow java.**, or at least java.util.Date, deserialization fails.
344 Chapter 9 Processing Input and Output

You can place the filter pattern into a configuration file and specify multiple
filters for different purposes. You can also implement your own filters. See
https://docs.oracle.com/en/java/javase/17/core/serialization-filtering1.html for details.

Exercises
1. Write a utility method for copying all of an InputStream to an OutputStream,
without using any temporary files. Provide another solution, without a
loop, using operations from the Files class, using a temporary file.
2. Write a program that reads a text file and produces a file with the same
name but extension .toc, containing an alphabetized list of all words in
the input file together with a list of line numbers in which each word
occurs. Assume that the file’s encoding is UTF-8.
3. Write a program that reads a file containing text and, assuming that most
words are English, guesses whether the encoding is ASCII, ISO 8859-1,
UTF-8, or UTF-16, and if the latter, which byte ordering is used.
4. Using a Scanner is convenient, but it is a bit slower than using a
BufferedReader.
Read in a long file a line at a time, counting the number of
input lines, with (a) a Scanner and hasNextLine/nextLine, (b) a BufferedReader and
readLine, (c) a BufferedReader and lines. Which is the fastest? The most
convenient?
5. When an encoder of a Charset with partial Unicode coverage can’t encode
a character, it replaces it with a default—usually, but not always, the en-
coding of "?". Find all replacements of all available character sets that
support encoding. Use the newEncoder method to get an encoder, and call
its replacement method to get the replacement. For each unique result, report
the canonical names of the charsets that use it.
6. The BMP file format for uncompressed image files is well documented
and simple. Using random access, write a program that reflects each row
of pixels in place, without writing a new file.
7. Look up the API documentation for the MessageDigest class and write a
program that computes the SHA-512 digest of a file. Feed blocks of bytes
to the MessageDigest object with the update method, then display the result
of calling digest. Verify that your program produces the same result as the
sha512sum utility.

8. Write a utility method for producing a ZIP file containing all files from
a directory and its descendants.
Exercises 345

9. Using the URLConnection class, read data from a password-protected web


page with “basic” authentication. Concatenate the user name, a colon,
and the password, and compute the Base64 encoding:
String input = username + ":" + password;
String encoding = Base64.getEncoder().encodeToString(
input.getBytes(StandardCharsets.UTF_8));

Set the HTTP header Authorization to the value "Basic " + encoding. Then read
and print the page contents.
10. Using a regular expression, extract all decimal integers (including negative
ones) from a string into an ArrayList<Integer> (a) using find, and (b) using
split. Note that a + or - that is not followed by a digit is a delimiter.

11. Using regular expressions, extract the directory path names (as an array
of strings), the file name, and the file extension from an absolute or
relative path such as /home/cay/myfile.txt.
12. Come up with a realistic use case for using group references in
Matcher.replaceAll and implement it.

13. Implement a method that can produce a clone of any serializable object
by serializing it into a byte array and deserializing it.
14. Implement a serializable class Point with instance variables for x and y.
Write a program that serializes an array of Point objects to a file, and
another that reads the file.
15. Continue the preceding exercise, but change the data representation of
Point so that it stores the coordinates in an array. What happens when
the new version tries to read a file generated by the old version? What
happens when you fix up the serialVersionUID? Suppose your life depended
upon making the new version compatible with the old. What could
you do?
16. Which classes in the standard Java library implement Externalizable? Which
of them use writeReplace/readResolve?
17. Unzip the API source and investigate how the LocalDate class is serialized.
Why does the class define writeExternal and readExternal methods even
though it doesn’t implement Externalizable? (Hint: Look at the Ser class.
Why does the class define a readObject method? How could it be invoked?
Index

Symbols and Numbers in dates, 434


- (minus sign) in switch statement, 40
flag (for output), 38 path separator (Unix), 86, 260
in dates, 434 :: operator, 125, 150
in regular expressions, 324 ! (exclamation sign)
operator, 18–19 in property files, 259
-- operator, 18, 23
in command-line options, 85 != operator, 18, 22–23
operator, 18, 20 for wrapper classes, 50
-= operator, 18–19 ? (quotation mark)
->, in lambda expressions, 122, 125 in regular expressions, 324–325, 327
-∞, in string templates, 454 replacement character, 309, 458
_ (underscore) wildcard, for types, 224–228, 239
in number literals, 12 ? : operator, 18, 23
in variable names, 15, 69 / (slash)
, (comma) file separator (Unix), 260, 313
flag (for output), 38 in javac path segments, 5
in numbers, 442, 448, 453 operator, 18–19
normalizing, 332 root component, 312
trailing, in arrays, 48 //, /*...*/ comments, 3
; (semicolon) /**...*/ comments, 95
in Java vs. JavaScript, 470 /= operator, 18
path separator (Windows), 86, 260 . (period)
: (colon) in method calls, 6
in assertions, 204–205 in numbers, 442, 448, 453

501
502 Index

in package names, 5, 83 in regular expressions, 324–325, 327,


in regular expressions, 324–325, 333 332–333
operator, 18 in variable names, 15
.., parent directory, 313 € currency symbol, 448, 453
... (ellipsis), for varargs, 57 * (asterisk)
^ (caret) for annotation processors, 413
for function parameters, 122 in documentation comments, 96
in regular expressions, 324–327, 333 in regular expressions, 324–327, 331
operator, 18, 23 operator, 18–19
^= operator, 18 wildcard:
~ (tilde), operator, 18, 23 in class path, 86
'...' (single quotes) in imported classes, 88–89
for character literals, 14 *= operator, 18
in JavaScript, 470 \ (backslash)
in string templates, 454 character literal, 14
"..." (double quotes) file separator (Windows), 260, 313
for strings, 6 in option files, 493
in javadoc hyperlinks, 98 in regular expressions, 324–325, 332
in text blocks, 34 in text blocks, 34
"" (empty string), 27–28, 159 & (ampersand), operator, 18, 23–24
""", for text boxes, 33–34 && (double ampersand)
( (left parenthesis), in formatted output, in regular expressions, 325
38 operator, 18, 23
(...) (parentheses) &= operator, 18
empty, for anonymous classes, 138 # (number sign)
for casts, 22, 110 flag (for output), 38
in regular expressions, 324–326, in javadoc hyperlinks, 98
330–331 in option files, 493
operator, 18 in property files, 259
[...] (square brackets) in string templates, 454
for arrays, 46–47, 53 % (percent sign)
in regular expressions, 324–325 conversion character, 37
operator, 18 operator, 18–19
{...} (curly braces) %% pattern variable, 213
in annotation elements, 399 %= operator, 18
in lambda expressions, 122 + (plus sign)
in regular expressions, 324–327, 332 flag (for output), 38
in string templates, 453 in regular expressions, 324–327
with arrays, 47 operator, 18–19
{{...}}, double brace initialization, 149 for strings, 25, 28, 159
@ (at) ++ operator, 18, 20
in java command, 492–493 += operator, 18
in javadoc comments, 95 < (left angle bracket)
$ (dollar sign) flag (for output), 38
currency symbol, 453 in shell syntax, 36
flag (for output), 38 in string templates, 454
Index 503

operator, 22 abstract modifier, 109, 151–152


<< operator, 18, 23–24 AbstractCollection class, 114
<<= operator, 18 AbstractMethodError, 115
<= operator, 18, 22 AbstractProcessor class, 413
<%...%>, <%=...%> delimiters (JSP), 472 accept methods (Consumer, Xxx Consumer),
≤, in string templates, 454 129–130, 277
<> (diamond syntax) acceptEither method (CompletableFuture),
for constructors of generic classes, 221 357–358
<...> (angle brackets) AccessibleObject class
for element types, in array lists, 48 setAccessible method, 181, 183
for type parameters, 117, 220 trySetAccessible method, 181
in javadoc hyperlinks, 98 accessors, 64
in regular expressions, 327 accumulate method (LongAccumulator), 374
= operator, 18–19 accumulateAndGet method (AtomicXxx ), 373
== operator, 18, 22–23, 161 accumulator functions, 293
for class objects, 172 ActionListener interface, 120
for enumerations, 166 add method
for strings, 26 of ArrayDeque, 262
for wrapper classes, 50 of ArrayList, 49, 64
> (right angle bracket) of BlockingQueue, 371
in shell syntax, 36 of Collection, 249
operator, 22 of List, 250
>=, >>, >>> operators, 18, 22–23 of ListIterator, 253
>>=, >>>= operators, 18 of LongAdder, 374
| (vertical bar) addAll method
in regular expressions, 324–326 of Collection, 226, 249
in string templates, 454 of Collections, 251
operator, 18, 23–24 of List, 250
|= operator, 18 addExact method (Math), 20
|| operator, 18, 23 addition, 19
0 (zero) identity for, 292
as default value, 73, 76 addSuppressed method (IOException), 199
flag (for output), 38 aggregators, 494
formatting symbol (date/time), 436 allMatch method (Stream), 280
prefix (for octal literals), 12 allOf method
0b prefix, 12 of CompletableFuture, 357–358
0x prefix, 12, 38 of EnumSet, 262
0xFEFF byte order mark, 305 allProcesses method (ProcessHandle), 389
\0, in regular expressions, 325 and, andNot methods (BitSet), 261
and, andThen methods (functional
A interfaces), 129
a formatting symbol (date/time), 436 Android, 121, 359
a, A conversion characters, 37 AnnotatedConstruct interface, 414
\a, \A, in regular expressions, 325, 328 AnnotatedElement interface, 411–413
abstract classes, 151–152 annotation interfaces, 403–406
abstract methods, 123 annotation processors, 413
504 Index

annotations copying, 51
accessing, 404, 494 declaring, 46–47
applicability of, 406–407 initializing, 46
container, 409, 412 ArrayBlockingQueue class, 371
declaration, 400–401 ArrayDeque class, 262
documented, 407–408 ArrayIndexOutOfBoundsException, 47
generating source code with, 415–417 ArrayList class, 48–49, 248
inherited, 407–408, 411 add method, 49, 64
key/value pairs in, 398–399, 405 clone method, 165–166
meta, 404–410 forEach method, 125
modifiers and, 402 get, remove methods, 49
multiple, 400 removeIf method, 124
processing: set, size methods, 49
at runtime, 410–413 arrays, 46–48
source-level, 413–417 accessing nonexisting elements in,
repeatable, 400, 407, 409–410, 412 47
standard, 406–410 allocating, 234
type use, 401–402 annotating, 401
anonymous classes, 138 casting, 185
anyMatch method (Stream), 280 checking, 185
anyOf method (CompletableFuture), 357–358 comparing, 161
Apache Commons CSV, 490 computing values of, 367
API documentation, 29–31 constructing, 46–47
generating, 95 constructor references with, 126
Applet class, 174 converting:
applications. See programs to a reference of type Object, 157
apply, applyAsXxx methods (functional to/from streams, 286, 296, 368
interfaces), 129–130 copying, 51
applyToEither method (CompletableFuture), covariant, 223
357–358 filling, 47, 52
arithmetic operations, 17–24 generating Class objects for, 171
Array class, 185–186 growing, 185–186
array lists, 48–49 hash codes of, 163
anonymous, 149 length of, 47–48, 134
checking for nulls, 227 multidimensional, 53–55, 159
constructing, 49 of bytes, 302–303
converting between, 224 of generic types, 126, 235
copying, 51 of objects, 47, 367
elements of, 49–50 of primitive types, 367
filling, 52 of strings, 331
instantiating with type variables, 234 passing into methods, 56
size of, 49 printing, 52, 55, 159
sorting, 52 serializable, 334
variables of, 49 sorting, 52, 117–119, 367–368
array variables superclass assignment in, 148
assigning values to, 48 using class literals with, 171
Index 505

Arrays class B
asList method, 265 b, B conversion characters, 37
copyOf method, 51, 186 \b (backspace), 14
deepToString method, 159 \b, \B, in regular expressions, 328
equals method, 161 BasicFileAttributes class, 317
fill method, 52 BeanInfo class, 184
hashCode method, 163 between method (Duration), 423
parallelXxx methods, 52, 367 BiConsumer interface, 129
setAll method, 127 BiFunction interface, 129, 131
sort method, 52, 119, 123–124 BigDecimal class, 14, 24, 337
stream method, 274, 294 big-endian format, 305, 310–311
toString method, 52, 159 BigInteger class, 12, 24
ArrayStoreException, 148, 223, 235 binary data, reading/writing, 310
ASCII (American Standard Code for binary numbers, 12, 14
Information Interchange), 31–32, binary trees, 254
305 BinaryOperator interface, 129
for property files, 457 binarySearch method (Collections), 252
for source files, 458 bindings, 469
ASM tool, 417 Bindings interface, 469
asMatchPredicate, asPredicate methods BiPredicate interface, 129
(Pattern), 329 BitSet class, 260–261
assert statement, 204–205 collecting streams into, 293
AssertionError, 204 methods of, 261
assertions, 204–206 bitwise operators, 23–24
checking, 401 block statement, labeled, 44
enabling/disabling, 205–206 blocking queues, 370–372
assignment operators, 18–19 BlockingQueue interface, 371
associative operations, 292 Boolean class, 49
asSubclass method (Class), 239 boolean type, 14
asynchronous computations, default value of, 73, 76
353–359 formatting for output, 37
AsyncTask class (Android), 359 reading/writing, 310
atomic operations, 364, 369, 373–375, streams of, 294
379 BooleanSupplier interface, 130
performance and, 374 bootstrap class loader, 174
AtomicXxx classes, 373 boxed method (Xxx Stream), 294
atZone method (LocalDateTime), 430 branches, 38–39
@author tag (javadoc), 96, 99 break statement, 40–41, 43–44
autoboxing, 50, 131 bridge methods, 230–231
AutoCloseable interface, 197, 222 clashes of, 237
close method, 198 BufferedReader class, 308
automatic modules, 489–491 build method (HttpClient), 321
availableCharsets method (Charset), 306 bulk operations, 370
availableProcessors method (Runtime), Byte class, 49
349 MAX_VALUE, MIN_VALUE constants, 11
average method (Xxx Stream), 295 toUnsignedInt method, 12
506 Index

byte codes, 4 carriage return, 14


writing to memory, 466–467 case label, 39–41
byte order mark, 305 cast method (Class), 239
byte type, 11–12, 303 cast operator, 22
streams of, 294 casts, 22, 110–111, 148
type conversions of, 21 annotating, 402
ByteArrayClass class, 466 generic types and, 232
ByteArrayClassLoader class, 467 inserting, 229–230
ByteArrayXxx Stream classes, 302–303 catch statement, 196–197
ByteBuffer class, 311 annotating parameters of, 400
bytes in try-with-resources, 199
arrays of, 302–303 no type variables in, 237
converting to strings, 307 ceiling method (NavigableSet), 255
reading, 303 Channel interface, 112
skipping, writing, 304 channels, 311
char type, 14
C streams of, 294
c, C conversion characters, 37 type conversions of, 21
C:\ root component, 312 Character class, 49
C/C++ programming languages character classes, 324
#include directive in, 89 character encodings, 305–307
allocating memory in, 364 detecting, 306
integer types in, 12 localizing, 458
pointers in, 65 partial, 306, 309
C# programming language, 227 platform, 306, 458
\c, in regular expressions, 325 character literals, 14
CachedRowSetImpl class, 492 characters, 302
calculators, 168–169 combined, 452
Calendar class, 421 formatting for output, 37
getFirstDayOfWeek method, 451 normalized, 452–453
weekends in, 427 reading/writing, 310
calendars, 62 charAt method (String), 32
call by reference, 71 CharSequence interface, 29, 275
call method (CompilationTask), 465 chars, codePoints methods, 294
Callable interface, 120 Charset class
call method, 351 availableCharsets method, 306
extending, 465 defaultCharset method, 306, 458
callbacks, 120–121, 355 displayName method, 458
registering, 353 forName method, 307
camel case, 16 checked exceptions, 194–196
cancel method combining in a superclass, 195
of CompletableFuture, 355 declaring, 195–196
of Future, 351 documenting, 196
cancellation requests, 382 generic types and, 238
CancellationException, 355 in lambda expressions, 196
cardinality method (BitSet), 261 no-argument constructors and, 182
Index 507

not allowed in a method, 202 class declarations


rethrowing, 201 annotations in, 400, 408
checked views, 233, 266 initialization blocks in, 74–75
checkedXxx methods (Collections), 252, 266 class files, 4, 174
Checker Framework, 401 paths of, 84
checkIndex method (Objects), 204 processing annotations in, 417
childrenNames method (Preferences), 460 class literals, 171
choice indicator, in string templates, 454 no annotations for, 402
Church, Alonzo, 122, 424 no type variables in, 233
Class class, 170–173, 240 class loaders, 174–176, 467
asSubclass, cast methods, 239 class objects, 171
comparing objects of, 172 class path, 85, 477
forName method, 171–172, 175–176, .class suffix, 171–172
194, 203, 467 ClassCastException, 110, 232
generic, 239 classes, 2, 62
getCanonicalName method, 171–172 abstract, 109, 116, 151–152
getClassLoader method, 173 accessing from a different module, 494
getComponentType method, 172, 185 adding to packages, 88
getConstructor(s) methods, 173, 179, anonymous, 138
182, 239 companion, 114
getDeclaredConstructor(s) methods, 173, compiling on the fly, 466
179, 239 constructing objects of, 15
getDeclaredField(s) methods, 173 deprecated, 97, 406–407
getDeclaredMethod(s) methods, 173, 182 deserialization of, 342–344
getDeclaringClass method, 172 documentation comments for, 95–96
getEnclosingXxx methods, 172 encapsulation of, 475–476
getEnumConstants method, 239 evolving, 340
getField(s) methods, 173, 179 extending, 144–150
getInterfaces method, 172 fields of, 143
getMethod(s) methods, 173, 179, 182 final, 150–151
getModifiers method, 172 generic, 48
getName method, 171–172 immutable, 29, 365
getPackage method, 172 implementing, 67–71, 164
getPackageName method, 173 importing, 88–89
getPermittedSubclasses method, 172 inner, 91–93
getRecordComponents method, 173 instances of, 6, 67, 83
getResource method, 174, 455 loading, 180
getResourceAsStream method, 173–174 local, 137–138
getSimpleName method, 172 members of, 143
getSuperclass method, 172, 239 enumerating, 169, 179–180
getTypeName method, 172 naming, 15–16, 83, 171
getTypeParameters method, 240 nested, 90–95, 402
isXxx methods, 172–173, 185 not known at compile time, 171, 186
newInstance method, 182, 239 protected, 152–153
toGenericString method, 172 public, 88, 482
toString method, 172 sealed, 154
508 Index

serializable, 336–337 codePointXxx methods (String), 32


static initialization of, 175 Collator class, 28
static methods of, 82 methods of, 452
system, 205 collect method (Stream), 286–287, 293
testing, 88 Collection interface, 114, 248
utility, 87, 176 add method, 249
wrapper, 49–50 addAll method, 226, 249
classes win rule, 163 clear, contains, containsAll methods, 249
classifier functions, 289 isEmpty method, 249
ClassLoader class iterator method, 249
defineClass method, 492 parallelStream method, 249, 272–273,
extending, 467 295, 366
findClass, loadClass methods, 175 remove, removeXxx, retainAll methods, 249
setXxx AssertionStatus methods, 206 size method, 249
classloader inversion, 176 spliterator method, 249
ClassNotFoundException, 194 stream method, 249, 272–273
CLASSPATH environment variable, 87 toArray method, 249
clear method collections, 247–266
of BitSet, 261 branching, 291
of Collection, 249 generic, 266
of Map, 257 given elements of, 264
clone method iterating over elements of, 272–273
of ArrayList, 165–166 mutable, 265
of Enum, 167 processing, 251
of Message, 165–166 serializable, 334
of Object, 153, 158, 163–166, 182 threadsafe, 372
protected, 163 unmodifiable views of, 265–266
Cloneable interface, 165 vs. streams, 273
CloneNotSupportedException, 165–167 Collections class, 114, 251
cloning, 163–166 addAll method, 251
close method binarySearch method, 252
of AutoCloseable, Closeable, 198 copy method, 251
of PrintWriter, 197–198 disjoint method, 251
throwing exceptions, 198 fill method, 52, 251
Closeable interface, 112 frequency method, 251
close method, 198 indexOfSubList, lastIndexOfSubList
closures, 133 methods, 251
COBOL, scripting engine for, 468 nCopies method, 249, 251
code element (HTML), 96 replaceAll method, 251
code generator tools, 408 reverse method, 52, 252
code points, 32, 276, 305 rotate method, 252
code units, 14, 32, 294 shuffle method, 52, 252
in regular expressions, 325 sort method, 52, 226–227, 241, 252
codePoints method swap method, 252
of CharSequence, 294 synchronizedXxx methods, 252
of String, 32–33, 276–278 unmodifiableXxx methods, 252
Index 509

Collector interface, 286 compareToIgnoreCase method (String), 124


Collectors class, 90 compareUnsigned method (Integer, Long), 21
counting method, 290 compatibility, drawbacks of, 228
filtering method, 291 Compilable interface, 471
flatMapping method, 291 compilation, 4
groupingBy method, 289–292 CompilationTask interface, 464
groupingByConcurrent method, 289, 296 call method, 465
joining method, 286–287 compile method (Pattern), 329, 333
mapping method, 290 compiler
maxBy, minBy methods, 290 instruction reordering in, 361
partitioningBy method, 289, 292 invoking, 464
reducing method, 291 compile-time errors, 16, 112
summarizingXxx methods, 287, 291 completable futures, 353–358
summingXxx methods, 290 combining, 358
teeing method, 291 composing, 355–358
toCollection method, 286 interrupting, 355
toConcurrentMap method, 288 CompletableFuture class, 353–358
toMap method, 287–288 acceptEither method, 357–358
toSet method, 286, 290 allOf, anyOf methods, 357–358
command-line arguments, 52–53 applyToEither method, 357–358
comments, 3 cancel method, 355
documentation, 95–100 complete, completeExceptionally methods,
commonPool method (ForkJoinPool), 297, 354
353 completeOnTimeout method, 357
companion classes, 114 exceptionally method, 356–357
Comparable interface, 117–119, 167, 226, exceptionallyCompose method, 357
254 handle method, 357
compareTo method, 117 isDone method, 354
priority queues with, 263 orTimeout method, 357
streams of, 279 runAfterXxx methods, 357–358
Comparator interface, 90, 119–120, supplyAsync method, 353–355
135–137, 254 thenAccept method, 353, 357
comparing, comparingXxx methods, thenAcceptBoth method, 357–358
136–137 thenApply, thenApplyAsync methods,
naturalOrder method, 136 355–357
nullsFirst, nullsLast methods, 136 thenCombine method, 357–358
priority queues with, 263 thenCompose method, 356–357
reversed method, 136 thenRun method, 357
reverseOrder method, 137 whenComplete method, 354, 356–357
streams of, 279 CompletionStage interface, 358
thenComparing method, 136–137 compose method (functional interfaces),
compare method (Integer, Double), 118 129
compareTo method computations
of Enum, 167 asynchronous, 353–359
of Instant, 423 mutator, 64
of String, 27–28, 117, 451 precision of, 14
510 Index

compute method constructor references, 126


of ConcurrentHashMap, 369–370 annotating, 402
of Map, 256 constructors, 71–76
computeIfXxx methods abstract classes and, 152
of ConcurrentHashMap, 369 annotating, 236, 400–401
of Map, 256–257 canonical, compact, custom, 78–79
concat method (Stream), 278 documentation comments for, 95
concatenation, 25 executing, 72
objects with strings, 159 for subclasses, 147
concurrent programming, 347–389 implementing, 71–72
access errors in, 134 invoking another constructor from, 73
for scripts, 469 no-argument, 75, 147, 182
strategies for, 364 overloading, 72–73
ConcurrentHashMap class, 369–370, 381 public, 72, 179
compute method, 369–370 references in, 366
computeIfXxx methods, 369 Consumer interface, 129, 277
forEachXxx methods, 370 contains method
keySet method, 372 of String, 29
merge method, 369–370 of Collection, 249
newKeySet method, 372 containsAll method (Collection), 249
no null values in, 258 containsXxx methods (Map), 257
putIfAbsent method, 369 Content-Type header, 306
reduceXxx methods, 370 context class loaders, 176–177
searchXxx methods, 370 continue statement, 43–44
threadsafe, 377 control flow, 38–46
ConcurrentModificationException, 253, conversion characters, 37
368 cooperative cancellation, 382
ConcurrentSkipListXxx classes, 372 copy method
conditional operator, 23 of Collections, 251
configuration files, 459–461 of Files, 304, 315–316, 319
editing, 209–211 copyOf method (Arrays), 51, 186
locating, 174 CopyOnWriteArrayXxx classes, 372
resolving paths for, 313 CORBA (Common Object Request
confinement, 364 Broker Architecture), 476
connect method (URLConnection), 320 count method (Stream), 273, 280
Console class, 36 counters
console, displaying fonts on, 458 atomic, 373–375
ConsoleHandler class, 211, 213 de/incrementing, 199
constants, 16–17, 113 counting method (Collectors), 290
naming, 16 country codes, 289, 443–444
static, 80–81 covariance, 223
using in another class, 17 createBindings method (ScriptEngine), 469
Constructor class, 179–180 createDirectory, createDirectories, createFile
getModifiers method, 179 methods (Files), 314
getName method, 179 createInstance method (Util), 176–177
newInstance method, 182–183 createTempXxx methods (Files), 315
Index 511

critical sections, 364, 375, 382 deadlocks, 364, 376, 380, 382
Crockford, Douglas, 471 debugging
currencies, 448–449 messages for, 193
formatting, 453 overriding methods for, 151
Currency class, 448 primary arrays for, 52
current method streams, 279
of ProcessHandlex, 389 threads, 385
of ThreadLocalRandomx, 384 with anonymous subclasses, 149–150
with assertions, 204
D DecimalFormat class, 83
d number format patterns of, 453
conversion character, 37 declaration-site variance, 227
formatting symbol (date/time), 436 decomposition
D suffix, 13 of characters, 452
\d, \D, in regular expressions, 326 of classes, 56–57
daemon threads, 385 decrement operator, 20
databases, 397 decrementExact method (Math), 20
persisting objects in, 485 deep copies, 164
DataInput/Output interfaces, 310 deepToString method (Arrays), 159
read/writeXxx methods, 310–311 default label (in switch), 39–41
DataXxx Stream classes, 310 default methods, 114–116
Date class, 421, 436–437 conflicts of, 115–116, 157
DateFormat class, 449 in interfaces, 163
dates default modifier, 114, 405
computing, 428–429 defaultCharset method (Charset), 306, 458
formatting, 433–436, 442, 449–451, defaultReadObject method
453 (ObjectInputStream), 337, 341
local, 424–427 defaultWriteObject method
nonexistent, 427, 431, 450 (ObjectOutputStream), 336–337
parsing, 435 defensive programming, 204
datesUntil method (LocalDate), 426–427 deferred execution, 127–128
DateTimeFormat class, 449–451 defineClass method (ClassLoader), 492
DateTimeFormatter class, 433–436 delete method (Files), 315
format method, 433, 450 deleteIfExists method (Files), 315
legacy classes and, 437 delimiters, for scanners, 308
ofLocalizedXxx methods, 433, 449 @Deprecated annotation, 97, 406–407
ofPattern method, 435 @deprecated tag (javadoc), 97, 407
parse method, 435 Deque interface, 250, 262
toFormat method, 435 destroy, destroyForcibly methods
withLocale method, 434, 450 of Process, 389
DateTimeParseException, 450 of ProcessHandle, 390
daylight savings time, 430–433 DiagnosticCollector class, 465
DayOfWeek enumeration, 63, 426–427, 432 DiagnosticListener interface, 465
getDisplayName method, 435, 450 diamond syntax (<>)
dayOfWeekInMonth method (TemporalAdjusters), for array lists, 49
428 for constructors of generic classes, 221
512 Index

directories, 312 doubleValue method (Number), 448


checking for existence, 314, 316 downstream collectors, 289–292, 296
creating, 314–316 Driver.parentLogger method, 494
deleting, 315, 318–319 dropWhile method (Stream), 278
moving, 315 Duration class
temporary, 315 between method, 423
user, 314 dividedBy method, 424
visiting, 316–319 immutability of, 365, 424
working, 386 isNegative, isZero methods, 424
directory method (ProcessBuilder), 386 minus, minusXxx, multipliedBy, negated
disjoint method (Collections), 251 methods, 424
displayName method (Charset), 458 ofXxx methods, 423–424, 426, 431
distinct method (Stream), 279, 296 plus, plusXxx methods, 424
dividedBy method (Duration), 424 toXxx methods, 423
divideUnsigned method (Integer, Long), 21 dynamic method lookup, 148, 230–231
division, 19
do statement, 42 E
doc-files directory, 96 E constant (Math), 20
documentation comments, 95–100 e, E
@Documented annotation, 407–408 conversion characters, 37
domain names formatting symbols (date/time), 436
for modules, 478 \e, \E, in regular expressions, 324–325
for packages, 83 Eclipse IDE, 5
dot notation, 6, 17 effectively final variables, 133–134
double brace initialization, 149 efficiency, and final modifier, 151
Double class, 49 Element interface, 414
compare method, 118 element method (BlockingQueue), 371
equals method, 161 elements (in annotations), 398–399, 405
isFinite, isInfinite methods, 13 else statement, 39
NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY em element (HTML), 96
values, 13 empty method
parseDouble method, 28 of Optional, 284
toString method, 28 of Stream, 274
double type, 13–14 empty string, 27, 159
atomic operations on, 375 concatenating, 28
functional interfaces for, 130 encapsulation, 62, 475–477, 485
streams of, 294 encodings. See character encodings
type conversions of, 21–22 end method (Matcher, MatchResult), 330–331
DoubleAccumulator, DoubleAdder classes, 375 endsWith method (String), 29
DoubleConsumer, DoubleXxx Operator, engine scope, 469
DoublePredicate, DoubleSupplier, enhanced for loop, 50, 55, 134
DoubleToXxx Function interfaces, 130 for collections, 253
DoubleFunction interface, 130, 232 for enumerations, 167
doubles method (RandomGenerator), 294 for iterators, 178
DoubleStream class, 294–295 for paths, 314
DoubleSummaryStatistics class, 287, 295 Entry class, 229
Index 513

entrySet method (Map), 257–258 Exception class, 194


Enum class, 166–167 exceptionally method (CompletableFuture),
enum instances 356–357
adding methods to, 168–169 exceptionallyCompose method
construction, 168 (CompletableFuture), 357
referred by name, 170 exceptions, 192–204
enum keyword, 17, 166 annotating, 402
enumeration sets, 262 ArrayIndexOutOfBoundsException, 47
enumerations, 166–170 ArrayStoreException, 148, 223, 235
annotating, 400 CancellationException, 355
comparing, 166–167 catching, 196–200
constructing, 168 chaining, 201–202
defining, 17 checked, 182, 194–196
nested inside classes, 169 ClassCastException, 110, 232
serialization of, 339 ClassNotFoundException, 194
static members of, 169 CloneNotSupportedException, 165–167
traversing instances of, 167 combining in a superclass, 195
using in switch, 170 ConcurrentModificationException, 253, 368
EnumMap, EnumSet classes, 262 creating, 194–195
environment variables, 387 DateTimeParseException, 450
epoch, 422 documenting, 196
equality, testing for, 22–23 ExecutionException, 351
equals method FileNotFoundException, 194
final, 162 generic types and, 237–238
null-safe, 161 hierarchy of, 193–195
of Arrays, 161 IllegalArgumentException, 204
of Double, 161 IllegalStateException, 287, 371
of Instant, 423 InaccessibleObjectException, 181, 486
of Object, 158–162 IndexOutOfBoundsException, 204
of Objects, 161 InterruptedException, 381, 383
of records, 77 InvalidClassException, 341
of String, 26–27 InvalidPathException, 313
of subclasses vs. superclass, 161 IOException, 194, 199, 308
of wrapper classes, 50 NoSuchElementException, 283, 371
overriding, 160–162 NullPointerException, 27, 48, 66, 74, 194,
symmetric, 161 203, 256, 280
values from different classes and, 161 NumberFormatException, 194
equalsIgnoreCase method (String), 27 ParseException, 448
Error class, 193 ReflectiveOperationException, 171
error messages, for generic methods, 222 rethrowing, 199–202
errorReader method (Process), 387 RuntimeException, 194
errors SecurityException, 181
AbstractMethodError, 115 ServletException, 201–202
AssertionError, 204 suppressed, 199
eval method (ScriptEngine), 468–471 throwing, 192–193
even numbers, 19 TimeoutException, 351
514 Index

uncaught, 202 provided, 153


unchecked, 194 public, 179
UncheckedIOException, 308 retrieving values of, 180–181
exec method (Runtime), 386 setting, 181
Executable class transient, 336
getModifiers method, 183 file attributes
getName method, 183 copying, 315
getParameters method, 180, 183 filtering paths by, 317
ExecutableElement interface, 414 File class, 314
ExecutionException, 351 file handlers, 211–212
Executor interface, 356 file managers, 466
executor services, 349, 353 file pointers, 311
ExecutorCompletionService class, 352 file.encoding system property, 306
Executors class, 349 file.separator system property, 260
ExecutorService interface, 465 FileChannel class
execute method, 349 get, getXxx methods, 311
invokeAll, invokeAny methods, 352 lock method, 312
exists method (Files), 314, 316 open method, 311
exitValue method (Process), 389 put, putXxx methods, 311
exports keyword, 479, 482–485 tryLock method, 312
qualified, 495 FileFilter class, 128
exportSubtree method (Preferences), 460 FileHandler class, 211–213
extends keyword, 112, 145, 222–226 FileNotFoundException, 194
Externalizable interface, read/writeExternal files
methods, 338–339 archiving, 319
channels to, 311
F checking for existence, 194, 314–316
f conversion character, 37 closing, 197
F suffix, 13 copying, 315–316
\f, in regular expressions, 325 creating, 313–316
factory methods, 72, 83 deleting, 315
failures, logging, 201 empty, 314
false value (boolean), 14 encoding of, 305
as default value, 73, 76 locking, 312
Field class, 179–180 memory-mapped, 297, 311
get method, 181, 183 missing, 465
getBoolean, getByte, getChar, getDouble, moving, 315–316
getFloat, getInt, getLong methods, random-access, 310–311
181, 183 reading from/writing to, 36, 194, 303
getModifiers, getName methods, 179, 183 temporary, 315
getShort method, 181, 183 Files class
getType method, 179 copy method, 304, 315–316, 319
set, setXxx methods, 183 createTempXxx methods, 315
fields (instance and static variables), 143 createXxx methods, 314
enumerating, 179–180 delete, deleteIfExists methods, 315
final, 362 exists method, 314, 316
Index 515

find method, 316–317 flag bits, sequences of, 260


isDirectory, isRegularFile methods, 314, flatMap method
316 of Optional, 284–285
lines method, 275, 297, 307 of Stream, 277
list method, 316–317 flatMapping method (Collectors), 291
move method, 315–316 flip method (BitSet), 261
newBufferedReader method, 308, 468 Float class, 49
newBufferedWriter method, 308, 316 float type, 13–14
newXxx Stream methods, 302, 316, 334 streams of, 294
read method, 304 type conversions of, 21–22
readAllBytes method, 303, 307 floating-point types, 13–14
readAllLines method, 307 binary number system and, 14
readNBytes method, 303 comparing, 118
skipNBytes method, 304 division of, 19
walk method, 316–319 formatting for output, 37
walkFileTree method, 316, 318 in hexadecimal notation, 13
write method, 309, 316 type conversions of, 21–22
FileSystem, FileSystems classes, 319 floor method (NavigableSet), 255
FileTime class, 437 floorMod method (Math), 20
FileVisitor interface, 318 fonts, displaying, 458
fill method for statement, 42–43
of Arrays, 52 declaring variables for, 45
of Collections, 52, 251 enhanced, 50, 55, 134, 167, 253, 314
Filter interface, 213 multiple variables in, 43
filter method forEach method
of Optional, 282 of ArrayList, 125
of Stream, 273–276, 280 of Map, 257
filtering method (Collectors), 291 of Stream, 286
final fields, 362 forEachOrdered method (Stream), 286
final methods, 366 forEachXxx methods (ConcurrentHashMap),
final modifier, 16, 75, 150 370
final variables, 361, 365 ForkJoinPool class, 356
finalize method (Object), 158 commonPool method, 297, 353
finally statement, 199–200 forLanguageTag method (Locale), 446
for locks, 376 Format class, 437
return statements in, 199 format method
financial calculations, 14 of DateTimeFormatter, 433, 450
find method (Files), 316–317 of MessageFormat, 453–454
findAll method (Scanner), 330 of String, 447
findAny method (Stream), 280 format specifiers, 37
findClass method (ClassLoader), 175 formatted method (String), 38
findFirst method (Stream), 179, 280 formatted output, 36–38
first day of week, 451 Formatter class, 213
first method (SortedSet), 255 formatters, for date/time values,
firstDayOfXxx methods (TemporalAdjusters), 434–435
428 forms, posting data from, 321–323
516 Index

forName method generic type declarations, 240–241


of Charset, 307 generic types, 118
of Class, 171–172, 175–176, 194, 203, annotating, 401
467 arrays of, 126
frequency method (Collections), 251 casting, 232
from method (Instant, ZonedDateTime), 436 exceptions and, 237–238
full indicator, in string templates, 453 in JVM, 228–231
Function interface, 129, 287 invariant, 223, 225
function types, 121, 128 lambda expressions and, 225
functional interfaces, 123–124, 406, 408 reflection and, 238–241
as method parameters, 225–226 restrictions on, 231–238
common, 129 GenericArrayType interface, 240
contravariant in parameter types, 225 get method
for primitive types, 130 of Array, 186
implementing, 130–131 of ArrayList, 49
@FunctionalInterface annotation, 131, 406, of BitSet, 261
408 of Field, 181, 183, 311
functions, 62 of Future, 351, 353
higher-order, 135–137 of List, 250
Future interface, 352 of LongAccumulator, 374
cancel, isCancelled, isDone methods, 351 of Map, 255–256
get method, 351, 353 of Optional, 283–285
futures, 351–353 of Path, 314
completable, 353–358 of Preferences, 460
of ServiceLoader.Provider, 178
G of Supplier, 129
g, G GET requests, 321
conversion characters, 37 getAndXxx methods (AtomicXxx ), 373
formatting symbols (date/time), 436 getAnnotation, getAnnotationsByType methods
\G, in regular expressions, 328 of AnnotatedConstruct, 414
%g pattern variable, 213 of AnnotatedElement, 411–413
gadget chains, 343 getAsXxx methods
garbage collector, 263 of OptionalXxx, 295
generate method (Stream), 274, 294 of Xxx Supplier, 130
@Generated annotation, 406, 408 getAudioClip method (Applet), 174
generators, converting to streams, 296 getAvailableCurrencies method (Currency),
generic classes, 48, 220–221 448
constructing objects of, 221 getAvailableIds method (ZoneId), 430
information available at runtime, 239 getAvailableLocales method (Locale), 445
instantiating, 221 getAverage method (Xxx SummaryStatistics),
generic collections, 266 287
generic constructors, 240 getBoolean method
generic methods, 221–222 of Array, 186
calling, 221 of Field, 181, 183
declaring, 221 of FileChannel, 311
information available at runtime, 239 of Preferences, 460
Index 517

getBundle method (ResourceBundle), 456–458 getDouble method


getByte method of Array, 186
of Array, 186 of Field, 181, 183
of Field, 181, 183 of FileChannel, 311
of FileChannel, 311 of Preferences, 460
getByteArray method (Preferences), 460 getElementsAnnotatedWith method
getCanonicalName method (Class), (RoundEnvironment), 414
171–172 getEnclosedElements method (TypeElement),
getChar method 414
of Array, 186 getEnclosingXxx methods (Class), 172
of Field, 181, 183 getEngineXxx methods (ScriptEngineManager),
of FileChannel, 311 468
getClass method (Object), 151, 158, 160, getEnumConstants method (Class), 239
170, 233, 239 getErrorStream method (Process), 386–387
getClassLoader method (Class), 173 getFactory method (ScriptEngine), 469
getComponentType method (Class), 172, getField(s) methods (Class), 173, 179
185 getFileName method (Path), 314
getConstructor(s) methods (Class), 173, getFilePointer method (RandomAccessFile),
179, 182, 239 311
getContents method (ListResourceBundle), getFirstDayOfWeek method (Calendar), 451
457 getFloat method
getContextClassLoader method (Thread), of Array, 186
176–177 of Field, 181, 183
getCountry method (Locale), 289 of FileChannel, 311
getCurrencyInstance method (NumberFormat), of Preferences, 460
83, 447 getHead method (Formatter), 214
getDayOfXxx methods getHeaderFields method (URLConnection), 320
of LocalDate, 63, 425–427 getInputStream method
of ZonedDateTime, 432 of Process, 386
getDeclaredAnnotationXxx methods of URL, 320
(AnnotatedElement), 411–413 of URLConnection, 321
getDeclaredConstructor(s) methods (Class), getInstance method
173, 179, 239 of Collator, 452
getDeclaredField(s) methods (Class), 173 of Currency, 448
getDeclaredMethod(s) methods (Class), 173, getInstant method (LogRecord), 214
182 getInt method
getDeclaringClass method of Array, 186
of Class, 172 of Field, 181, 183
of Enum, 167 of FileChannel, 311
getDefault method (Locale), 445–446 of Preferences, 460
getDisplayDefault method (Locale), 456 getInterfaces method (Class), 172
getDisplayName method getISOXxx methods (Locale), 445
of Currency, 449 getLength method (Array), 186
of DayOfWeek, 435, 450 getLevel method (LogRecord), 214
of Locale, 446 getLogger method (System), 207–208
of Month, 435, 450 getLoggerName method (LogRecord), 214
518 Index

getLong method getOutputStream method


of Array, 186 of Process, 386
of Field, 181, 183 of URLConnection, 320
of FileChannel, 311 getPackage method (Class), 172
of Preferences, 460 getPackageName method (Class), 173
getLongThreadID method (LogRecord), 214 getParameters method
getMax method (Xxx SummaryStatistics), of Executable, 180, 183
287 of LogRecord, 214
getMessage method (LogRecord), 214 getParent method (Path), 314
getMethod(s) methods (Class), 173, 179, getPath method (FileSystem), 319
182 getPercentInstance method (NumberFormat),
getMethodCallSyntax method 83, 447
(ScriptEngineFactory), 471 getPermittedSubclasses method (Class), 172
getMinute method getProperties method (System), 260
of LocalTime, 429 getProperty method (System), 175, 204, 259
of ZonedDateTime, 432 getPropertyDescriptors method (BeanInfo),
getModifiers method 184
of Class, 172 getPropertyType, getReadMethod methods
of Constructor, 179 (PropertyDescriptor), 184
of Executable, 183 getQualifiedName method (TypeElement), 414
of Field, 179, 183 getRecordComponents method (Class), 173
of Method, 179 getResource method (Class), 174, 455
getMonth method getResourceAsStream method
of LocalDate, 426 of Class, 173–174
of ZonedDateTime, 432 of Module, 487
getMonthValue method getResourceBundle, getResourceBundleName
of LocalDate, 63, 426 methods (LogRecord), 214
of ZonedDateTime, 432 getRoot method (Path), 314
getName method getSecond method
of Class, 171–172 of LocalTime, 429
of Constructor, 179 of ZonedDateTime, 432
of Executable, 183 getSequenceNumber method (LogRecord), 214
of Field, 179, 183 getShort method
of Method, 179 of Array, 186
of Parameter, 183 of Field, 181, 183
of Path, 314 of FileChannel, 311
of PropertyDescriptor, 184 getSimpleName method
of System.Logger, 209 of Class, 172
getNano method of Element, 414
of LocalTime, 429 getSourceXxx Name methods (LogRecord), 214
of ZonedDateTime, 432 getString method (ResourceBundle), 456
getNumberInstance method (NumberFormat), getSuperclass method (Class), 172, 239
447 getSuppressed method (IOException), 199
getObject method (ResourceBundle), 457 getSymbol method (Currency), 449
getOffset method (ZonedDateTime), 433 getSystemJavaCompiler method (ToolProvider),
getOrDefault method (Map), 256 464
Index 519

getTail method (Formatter), 214 hash maps


getTask method (JavaCompiler), concurrent, 369–370
464–465 weak, 263
getThrown method (LogRecord), 214 hash method (Object), 163
getType method hash tables, 254
of Field, 179 hashCode method
of Parameter, 183 of Arrays, 163
getTypeName method (Class), 172 of Enum, 167
getTypeParameters method (Class), 240 of Object, 158, 160, 162–163
getURLs method (URLClassLoader), 175 of records, 77
getValue method (LocalDate), 63 HashMap class, 255
getWriteMethod method (PropertyDescriptor), null values in, 258
184 HashSet class, 254
getYear method readObject, writeObject methods, 337
of LocalDate, 426 Hashtable class, 378
of LocalTime, 429 hasNext method
of ZonedDateTime, 432 declaring, 107
Goetz, Brian, 347 of Iterator, 252
Gregorian calendar reform, 426 of Scanner, 35, 308
GregorianCalendar class, 436–437 hasNextXxx methods (Scanner), 35, 308
toZonedDateTime method, 436–437 headMap method (SortedMap), 265
group method (Matcher, MatchResult), headSet method
330–331 of NavigableSet, 255
grouping, 289 of SortedSet, 255, 265
classifier functions of, 289 heap pollution, 232–233, 266
reducing to numbers, 290 Hello, World! program, 2
groupingBy method (Collectors), 289–292 modular, 478–480
groupingByConcurrent method (Collectors), helper methods, 228
289, 296 hexadecimal numbers, 12–13
GUI (graphical user interface) formatting for output, 37
callbacks in, 120–121 higher method (NavigableSet), 255
long-running tasks in, 358–359 higher-order functions, 135–137
missing fonts in, 458 hn, hr elements (HTML), 96
Hoare, Tony, 379
H HTML (HyperText Markup Language)
H formatting symbol (date/time), generating documentation in, 417
436 including code in, 34
h, H conversion characters, 37 HTTP connections, 320–323
\h, \H, in regular expressions, 326 HTTP/2 support, 320
%h pattern variable, 213 HttpClient class, 320–323
handle method (CompletableFuture), 357 enabling logging for, 323
Hansen, Per Brinch, 379 newBuilder, newHttpClient methods, 321,
hash codes, 162–163 353
computing in String class, 162 HttpHeaders class, 323
formatting for output, 37 HttpResponse class, 322–323
hash functions, 162–163, 254 HttpURLConnection class, 320–321
520 Index

hyperlinks initialization blocks, 74–75


in documentation comments, 98 static, 81
regular expressions for, 323 inlining, 151
inner classes, 91–93
I anonymous, 138
[I prefix, 159, 171 capturing this references in, 126
IANA (Internet Assigned Numbers invoking methods of outer classes, 93
Authority), 430 local, 133, 137–138
IDE (integrated development syntax for, 94
environment), 4–5 input
identity method reading, 35–36, 307–308
of Function, 129, 287 redirecting, 469
of UnaryOperator, 129 setting locales for, 447
identity values, 292 splitting along delimiters, 331
if statement, 38–39 input prompts, 36
ifPresent, ifPresentOrElse methods input streams, 302
(Optional), 281 copying, 304
IllegalArgumentException, 204 obtaining, 302
IllegalStateException, 287, 371 reading from, 303
ImageIcon class, 174 inputReader method (Process), 387
images, locating, 174 InputStream class, 303
img element (HTML), 96 transferTo method, 304
immutability, 364 InputStreamReader class, 307
immutable classes, 365 INSTANCE instance (enum types), 339
implements keyword, 108 instance methods, 6, 68–69
import statement, 7, 88–89 instance variables, 67, 69
no annotations for, 402 abstract classes and, 152
static, 89–90 annotating, 400
import static statement, 170 comparing, 161
importPreferences method (Preferences), 461 default values of, 73–74
InaccessibleObjectException, 181, 486 final, 75
increment method (LongAdder), 374 in records, 77–78
increment operator, 20 initializing, 74–75, 147
incrementAndGet method (AtomicXxx ), 373 not accessible from static methods, 82
incrementExact method (Math), 20 of deserialized objects, 339–341
indexOf method protected, 152
of List, 250 setting, 72
of String, 29 transient, 336
indexOfSubList method (Collections), 251 vs. local, 74
IndexOutOfBoundsException, 204 instanceof operator, 110, 149, 160–161
info method (ProcessHandle), 390 annotating, 402
inheritance, 144–166 with pattern matching, 111–112
classes win rule, 157, 163 instances, 2, 6
default methods and, 157 Instant class, 422
@Inherited annotation, 407–408 compareTo method, 423
initCause method (Throwable), 202 equals method, 423
Index 521

from method, 436 functional, 123–124, 406, 408


immutability of, 365, 424 implementing, 108–109
legacy classes and, 437 in scripting engines, 471
minus, minusXxx methods, 424 multiple, 113
now method, 423 methods of, 108–109
plus, plusXxx methods, 424 nested, enumerating, 179–180
instruction reordering, 361 no instance variables in, 113
int type, 11–12 no redefining methods of the Object
functional interfaces for, 130 class in, 163
processing values of, 128 views of, 264
random number generator for, 7, 41 Internet Engineering Task Force, 444
streams of, 294 interrupted method (Thread), 382
type conversions of, 21–22 interrupted status, 382
using class literals with, 171 InterruptedException, 381, 383
IntBinaryOperator interface, 130 intersects method (BitSet), 261
IntConsumer interface, 128, 130 IntFunction interface, 130, 232
Integer class, 49 IntPredicate interface, 130
compare method, 118 intrinsic locks, 377–379
MAX_VALUE, MIN_VALUE constants, 11 ints method (RandomGenerator), 294
parseInt method, 28, 194 IntSequence interface, 109, 137
toString method, 28 IntStream class, 294–295
unsigned division in, 12 mapToObj method, 277
xxx Unsigned methods, 21 parallel method, 295
integer indicator, in string templates, 453 IntSummaryStatistics class, 287, 295
integer types, 11–12 IntSupplier, IntToXxx Function,
comparing, 118 IntUnaryOperator interfaces, 130
computing, 19–20 InvalidClassException, 341
formatting for output, 37 InvalidPathException, 313
in hexadecimal notation, 12 Invocable interface, 470
reading/writing, 310–311 InvocationHandler interface, 186
type conversions of, 21–22 invoke method (Method), 182–183
values of: invokeAll, invokeAny methods
even/odd, 19 (ExecutorService), 352
signed, 12 IOException, 194, 308
@interface declaration, 404–405 addSuppressed, getSuppressed methods, 199
interface keyword, 107 isAbstract method (Modifier), 173, 179
sealed, 154 isAfter method
interface methods, 114–116 of LocalDate, 426
interfaces, 106–113 of LocalTime, 429
annotating, 400–401 of ZonedDateTime, 433
compatibility of, 115 isAlive method
declarations of, 107–108 of Process, 389
defining variables in, 113 of ProcessHandle, 390
documentation comments for, 95 isAnnotation method (Class), 172
evolution of, 114 isAnonymousClass method (Class), 172
extending, 112 isArray method (Class), 172, 185
522 Index

isAssignableFrom method (Class), 173 iterate method (Stream), 274, 279, 294,
isBefore method 367
of LocalDate, 426 Iterator interface
of LocalTime, 429 next, hasNext methods, 252
of ZonedDateTime, 433 remove, removeIf methods, 253
isCancelled method (Future), 351 iterator method
isDirectory method (Files), 314, 316 of Collection, 249
isDone method of ServiceLoader, 178
of CompletableFuture, 354 of Stream, 286
of Future, 351 iterators, 252–253, 286
isEmpty method converting to streams, 275, 296
of BitSet, 261 invalid, 253
of Collection, 249 traversing, 178
of Map, 257 weakly consistent, 368
isEnum method (Class), 172
isEqual method (Predicate), 129–130 J
isFinite, isInfinite methods (Double), 13 j.u.l. See java.util.logging package
isInstance method (Class), 173 JAR files, 85
isInterface method (Modifier), 173, 179 dependencies in, 497
isInterrupted method (Thread), 382 for split packages, 488
isLeapYear method (LocalDate), 426 manifest for, 490
isLocalClass method (Class), 172 modular, 488–489
isLoggable method processing order of, 87
of Filter, 213 resources in, 174, 455
of System.Logger, 209 scanning for deprecated elements, 407
isMemberClass method (Class), 172 jar program, 85
isNamePresent method (Parameter), 183 -C option, 488
isNative method (Modifier), 173, 179 -d option, 488
isNegative method (Duration), 424 --module-version option, 488
isNull method (Objects), 125 Java EE platform, 353
ISO 8601 format, 408 Java Persistence Architecture, 397
ISO 8859-1 encoding, 306, 309 Java Platform Module System, 475
isPresent method (Optional), 283–285 layers in, 489
isPrimitive method (Class), 172 migration to, 489–491
isPrivate, isProtected, isPublic methods no support for versioning in, 477, 480,
(Modifier), 173, 179 488
isRecord method (Class), 172 service loading in, 496–497
isRegularFile method (Files), 314, 316 java program, 4
isSealed method (Class), 172 --add-exports, --add-opens options, 492
isStatic, isStrict, isSynchronized methods --add-module option, 489
(Modifier), 173, 179 -cp (--class-path, -classpath) option,
isSynthetic method (Class), 172 86–87
isVolatile method (Modifier), 173, 179 -da (-disableassertions) option, 205
isZero method (Duration), 424 -ea (-enableassertions) option, 205
Iterable interface, 252–253, 314 -esa (-enablesystemassertions) option, 205
iterator method, 252 --illegal-access option, 492
Index 523

-m, -p (--module, --module-path) options, JavaFX platform, 121, 359


479, 488 javan.log files, 211
option files for, 492–493 JavaScript programming language
option names in, 85 accessing classes of, from Java, 471
specifying locales in, 446 delimiters in, 470
Java programming language semicolons in, 470
compatibility with older versions of, JavaServer Faces framework, 258
156–157, 228 javax.annotation package, 406
online API documentation on, 29–31 javax.swing package, 480
strongly typed, 15 JAXB (Java Architecture for XML
Unicode support in, 31–33 Binding), 485
uniformity of, 3, 116 jconsole program, 211
java.awt package, 88, 477 jdeprscan program, 407
java.awt.geom package, 336 jdeps program, 497
java.base module, 481 JDK (Java Development Kit), 4
java.class.path system property, 260 obsolete features in, 476
java.desktop module, 480 JEP 246 (platform logging API), 206
java.home system property, 260 jlink program, 498
java.io.tmpdir system property, 260 jmod program, 499
java.lang, java.lang.annotation packages, job scheduling, 263
406 join method
java.lang.reflect package, 179 of String, 25
java.logging module, 494 of Thread, 381
java.sql package, 437 joining method (Collectors), 286–287
java.time package, 421–437 JPA (Java Persistence API), 485
java.util package, 7, 368 JShell (Java Shell tool), 7–11
java.util.concurrent package, 368, 371 imported packages in, 10–11
java.util.concurrent.atomic package, 373 loading modules into, 489
java.util.logging package, 206–211 JSON (JavaScript Object Notation),
java.util.random package, 106 153–156
java.version system property, 260 JSP (JavaServer Pages), 472
JavaBeans, 183–184 JSR 223 support, 468
javac program, 4 JUnit framework, 397–398
-author option, 99
-cp (--class-path, -classpath) option, 86 K
-d option, 85, 99 K formatting symbol (date/time), 436
-encoding option, 458 \k, in regular expressions, 327
-link, -linksource options, 99 key/value pairs
-parameters option, 180 adding new keys to, 255
-processor option, 413 in annotations, 398–399, 405
-version option, 99 removed by garbage collector, 263
-XprintRounds option, 417 values of, 255
JavaCompiler.getTask method, 464–465 keys method (Preferences), 460
javadoc program, 95–100 keySet method
including annotations in, 408 of ConcurrentHashMap, 372
JavaFileObject interface, 464 of Map, 257, 264
524 Index

keywords, 15 line.separator system property, 260


contextual, 156 lines method
of BufferedReader, 308
L of Files, 275, 297, 307
L suffix, 12 @link tag (javadoc), 98
[L prefix, 171 linked lists, 248, 253
L64X128MixRandom algorithm, 106 LinkedBlockingQueue class, 371, 381
lambda expressions, 121–124 LinkedHashMap class, 258
annotating targets for, 408 LinkedList class, 248
capturing variables in, 132–134 List interface, 226, 248–249
executing, 127 add, addAll, get, indexOf, lastIndexOf,
for loggers, 208 listIterator methods, 250
generic types and, 225 of method, 49, 51, 250, 264
parameters of, 122 remove, replaceAll, set, sort methods, 250
processing, 127–131 subList method, 250, 265
return type of, 123 list method (Files), 316–317
scope of, 131–132 ListIterator interface, 253
this reference in, 132 ListResourceBundle class, 457
throwing exceptions in, 196 lists
using with streams, 276, 366 converting to streams, 296
language codes, 289, 443–444 mutable, 265
language model API, 414–415 printing elements of, 125
last method (SortedSet), 255 removing null values from, 125
lastDayOfXxx methods (TemporalAdjusters), sublists of, 265
428 unmodifiable views of, 266
lastIndexOf method literals
of List, 250 character, 14
of String, 29 floating-point, 13
lastIndexOfSubList method (Collections), integer, 12
251 string, 26–27, 33
lastInMonth method (TemporalAdjusters), 428 little-endian format, 305
lazy operations, 273, 276, 279, 332 load balancing, 334
leap seconds, 422 load method (ServiceLoader), 178, 497
leap years, 426 loadClass method (ClassLoader), 175
legacy code, 436–437 local classes, 137–138
length method local date/time, 424–430
of arrays, 47 local variables, 45–46
of RandomAccessFile, 311 annotating, 400–401
of String, 6, 32 vs. instance, 74
.level suffix, 210 LocalDate class, 63
lib/modules file, 499 datesUntil method, 426–427
limit method (Stream), 278, 296 getXxx methods, 63, 425–427
line feed, 34 isXxx methods, 426
character literal for, 14 legacy classes and, 437
formatting for output, 37 minus, minusXxx methods, 425, 427
in regular expressions, 328 now method, 72, 82, 425
Index 525

of method, 63, 72, 425–426 reentrant, 375–377


ofInstant method, 425 releasing, 199, 362
parse method, 450 log handlers, 211–213
plus, plusXxx methods, 63–64, 66, 425, default, 211
427 filtering/formatting, 213
toEpochSecond method, 426 levels of, 211
until method, 426–427 Log4j framework, 206
withXxx methods, 425 Logback framework, 206
LocalDateTime class, 430 Logger class (java.util.logging), 494
atZone method, 430 Logger interface (System), 207–209
legacy classes and, 437 getName method, 209
parse method, 450 isLoggable method, 209
Locale class, 288 log method, 207–209
forLanguageTag method, 446 loggers
getAvailableLocales method, 445 filtering/formatting, 213
getCountry method, 289 hierarchy of, 210
getDefault method, 445–446 naming, 207
getDisplayDefault method, 456 logging, 206–214
getDisplayName method, 446 configuring, 209–211
getISOXxx methods, 445 failures, 201
predefined fields, 445 levels of, 208–211
setDefault method, 445–446 overriding methods for, 151
locales, 287–291, 442–447 LogRecord class, methods of, 214
date/time formatting for, 449–451 Long class, 49
default, 434, 445–446, 449–450, 456 MAX_VALUE, MIN_VALUE constants, 11
displaying names of, 446 unsigned division in, 12
first day of week in, 451 xxx Unsigned methods, 21
for template strings, 453–454 long indicator, in string templates, 453
formatting styles for, 435, 450 long type, 11–12
sorting words for, 451–452 atomic operations on, 374–375
specifying, 443–445 functional interfaces for, 130
weekdays and months in, 435 streams of, 294
LocalTime class, 429–430 type conversions of, 21–22
final, 151 LongAccumulator class, 374
getXxx, isXxx methods, 429 accumulate, get methods, 374
legacy classes and, 437 LongAdder class, 374–375
minus, minusXxx, now, of, ofInstant add, increment, sum methods, 374
methods, 429 threadsafe, 377
parse method, 450 LongConsumer, LongXxx Operator, LongPredicate,
plus, plusXxx, toXxx, withXxx methods, 429 LongSupplier, LongToXxx Function
lock method interfaces, 130
of FileChannel, 312 LongFunction interface, 130, 232
of ReentrantLock, 376 longs method (RandomGenerator), 294
locks, 364 LongStream class, 294–295
error-prone, 365 LongSummaryStatistics class, 287, 295
intrinsic, 377–379 long-term persistence, 340
526 Index

Lookup class, 487 mapToInt method (Stream), 293


lookup method (MethodHandles), 487 mapToObj method (IntStream), 277
loops, 41–43 mapToXxx methods (Xxx Stream), 294
exiting, 43–44 marker interfaces, 165
infinite, 43 Matcher class, 329–331
lower method (NavigableSet), 255 methods of, 332
matcher, matches methods (Pattern), 329
M MatchResult interface, 330–332
m, M formatting symbols (date/time), 436 Math class
main method, 2, 6 E constant, 20
decomposing, 56–57 floorMod method, 20
string array parameter of, 52 max, min methods, 20
ManagedExecutorService class, 353 PI constant, 20, 80, 89
Map interface, 250 pow method, 20, 81, 89
clear method, 257 round method, 22
compute method, 256 sqrt method, 20
computeIfXxx methods, 256–257 xxx Exact methods, 20, 22
containsXxx methods, 257 max method
entrySet method, 257–258 of Stream, 280
forEach method, 257 of Xxx Stream, 295
get, getOrDefault methods, 255–256 MAX_VALUE constant (integer classes), 11
isEmpty method, 257 maxBy method
keySet method, 257, 264 of BinaryOperator, 129
merge method, 256 of Collectors, 290
of method, 257, 264 medium indicator, in string templates, 453
ofEntries method, 264 memory
put method, 255–256 allocating, 364
putAll method, 257 caching, 361
putIfAbsent method, 256 concurrent access to, 361
remove method, 257 memory-mapped files, 311
replace, replaceAll methods, 257 merge method
size method, 257 of ConcurrentHashMap, 369–370
values method, 257, 264 of Map, 256
map method Message class, 165–166
of Optional, 282 MessageFormat class, 453–454
of Stream, 276 meta-annotations, 404–410
mapMulti method (Stream), 278 META-INF/MANIFEST.MF file, 490
mapping method (Collectors), 290 META-INF/services directory, 496
maps, 255–258 method calls, 6
concurrent, 257, 288 receiver of, 69
empty, 257 Method class, 179–180
iterating over, 258 getModifiers, getName methods, 179
of stream elements, 287–288, 296 invoke method, 182–183
order of elements in, 258 method expressions, 124, 150
views of, 257 method references, 124–126, 233
unmodifiable, 266 annotating, 402
Index 527

MethodHandles.lookup method, 487 Microsoft Windows


methods, 2 line ending in, 34
abstract, 123, 151–152 path separator in, 86, 260
accessor, 64, 77 registry in, 459
annotating, 236, 400 min method
atomic, 369 of Math, 20
body of, 68 of Stream, 280
chaining calls of, 64 of Xxx Stream, 295
clashes of, 236–237 MIN_VALUE constant (integer classes), 11
compatible, 162 minBy method
declarations of, 67 of BinaryOperator, 129
default, 114–116 of Collectors, 290
deprecated, 97, 406–407 minus, minusXxx methods
documentation comments for, 95, 97 of Duration, 424
enumerating, 179–180 of Instant, 424
factory, 72, 83 of LocalDate, 425, 427
final, 150, 366 of LocalTime, 429
for throwing exceptions, 203–204 of ZonedDateTime, 432
header of, 67 Modifier interface
inlining, 151 isXxx methods, 173, 179
instance, 68–69 toString method, 173
invoking, 182 modifiers, checking, 179
modifying functions, 135 module keyword, 479
mutator, 64, 266, 366 module path, 479, 488, 490–491
naming, 15–16, 77 Module.getResourceAsStream method, 487
native, 81 module-info.class file, 479, 488
overloading, 73, 125 module-info.java file, 479
overriding, 114, 145–147, 151, modules, 475
195–196, 406–407 aggregator, 494
parameters of, 180 annotating, 480
null checks for, 203 automatic, 489–491
passing arrays into, 56 bundling up the minimal set of, 498
private, 117 declaration of, 478–479
proxied, 187 documentation comments for, 95, 99
public, 108–109, 179 explicit, 491
restricted to subclasses, 152–153 illegal access to, 492
return value of, 2, 68 inspecting files in, 499
returning functions, 135 loading into JShell, 489
static, 56, 81–83, 90, 113–114 naming, 478, 490
storing in variables, 7 open, 486
symmetric, 161 reflective access for, 180–181
synchronized, 377–380 required, 480–482, 493–495
used for serialization, 406–407 tools for, 497–499
utility, 87 transitive, 493–495
variable number of arguments of, 57 unnamed, 491
Microsoft Notepad, 306 versioning and, 477, 480, 488
528 Index

monitors (classes), 379 newFileSystem method (FileSystems), 319


Month enumeration, 425–426, 432 newHttpClient method (HttpClient), 321, 353
getDisplayName method, 435, 450 newInputStream method (Files), 302, 316,
MonthDay class, 427 334
move method (Files), 315–316 newInstance method
multiplication, 19 of Array, 186
multipliedBy method (Duration), 424 of Class, 182, 239
mutators, 64 of Constructor, 182–183
unmodifiable views and, 266 newKeySet method (ConcurrentHashMap), 372
newline. See line feed
N newOutputStream method (Files), 302, 316,
n 334
conversion character, 37 newProxyInstance method (Proxy), 187
formatting symbol (date/time), 436 next method
\n (line feed) declaring, 107
for character literals, 14 of Iterator, 252
in property files, 259–260 of Scanner, 35
in regular expressions, 325–326, 333 of TemporalAdjusters, 428
name method (Enum), 167 nextClearBit method (BitSet), 261
NaN (not a number), 13 nextDouble method
native methods, 81 common for all generators, 106
naturalOrder method (Comparator), 136 of Scanner, 35, 308
navigable maps/sets, 266 nextInt method
NavigableMap interface, 372 common for all generators, 106
NavigableSet interface, 249, 254, 265 of Random, 7, 41
methods of, 255 of Scanner, 35
nCopies method (Collections), 249, 251 nextLine method (Scanner), 35
negate method (Predicate, BiPredicate), 129 nextOrSame method (TemporalAdjusters), 428
negated method (Duration), 424 nextSetBit method (BitSet), 261
negateExact method (Math), 20 nominal typing, 128
NEGATIVE_INFINITY value (Double), 13 noneMatch method (Stream), 280
negative values, 11 noneOf method (EnumSet), 262
nested classes, 90–95 noninterference, of stream operations,
annotating, 402 275
enumerating, 179–180 @NonNull annotation, 401
inner, 91–93 non-sealed modifier, 156
public, 91 normalize method (Path), 313
static, 90–91 Normalizer class, 453
new operator, 7, 15, 18, 72 NoSuchElementException, 283, 371
as constructor reference, 126 notify, notifyAll methods (Object),
for anonymous classes, 138 380–381
for arrays, 46–47, 54 now method
newBufferedReader method (Files), 308, 468 of Instant, 423
newBufferedWriter method (Files), 308, 316 of LocalDate, 72, 82, 425
newBuilder method (HttpClient), 321, 353 of LocalTime, 429
newCachedThreadPool method (Executors), 349 of ZonedDateTime, 432
Index 529

null value, 27, 66 toString method, 158–159


as default value, 73, 76 wait method, 379–381
checking parameters for, 203 object references, 65–66
comparing against, 160 attempting to change, 71
converting to strings, 159 comparing, 159
NullPointerException, 27, 48, 66, 74, 194, default value of, 73, 76
203, 256 null, 66
vs. Optional, 280 passed by value, 71
nullsFirst, nullsLast methods (Comparator), serialization and, 335
136 ObjectInputStream class, 334–335
Number class, 448 defaultReadObject method, 337, 341
number indicator, in string templates, 453 readDouble method, 337
NumberFormat class readFields method, 341
getXxx Instance methods, 83, 447 readObject method, 335–343
parse method, 448 ObjectInputValidation interface, 342–343
setCurrency method, 448 object-oriented programming, 61–102
NumberFormatException, 194 encapsulation in, 475–476
numbers ObjectOutputStream class, 334
average of, 108–109 defaultWriteObject method, 336–337
big, 24 writeDouble method, 337
comparing, 118 writeObject method, 334–337
converting to strings, 28 object-relational mappers, 485
default value of, 73, 76 objects, 2, 62–66
even or odd, 19 calling methods on, 7
formatting, 37, 442, 447, 453 casting, 110–111
from grouped elements, 290 cloning, 163–166
in regular expressions, 326 comparing, 50, 159–162
non-negative, 205, 260 constructing, 7, 71–76, 182–183
printing, 36 converting:
random, 7, 41, 106, 274, 278, 294, 384 to JSON, 486
reading/writing, 308, 310–311 to strings, 158–159
rounding, 14, 22 deep/shallow copies of, 164–165
type conversions of, 21–22 deserialized, 339–341
unsigned, 12, 21 immutable, 64
with fractional parts, 13–14 initializing variables with, 15
inspecting, 180–181
O invoking static methods on, 82
o conversion character, 37 mutable, 75
Object class, 157–166 serializable, 334–335
clone method, 153, 158, 163–166, 182 sorting, 117–119
equals method, 158–162 state of, 62
finalize method, 158 Objects class
getClass method, 151, 158, 160, 170, checkIndex method, 204
233, 239 converting to streams, 274
hashCode method, 158, 160, 162–163 equals method, 161
notify, notifyAll methods, 380–381 hash method, 163
530 Index

isNull method, 125 onExit method


requireNonNull, requireNonNullXxx of Process, 389
methods, 203–204 of ProcessHandle, 390
ObjXxx Consumer interfaces, 130 open keyword, 487
octal numbers, 12 open method (FileChannel), 311
formatting for output, 37 openConnection method (URL), 320
octonions, 32 opens keyword, 486
odd numbers, 19 qualified, 495
of method openStream method (URL), 302
of EnumSet, 262 Operation interface, 169
of IntStream, 294 operations
of List, 49, 51, 250, 264 associative, 292
of LocalDate, 63, 72, 425–426 atomic, 364, 369, 373–375, 379
of LocalTime, 429 bulk, 370
of Map, 257, 264 lazy, 273, 276, 279, 332
of Optional, 284 parallel, 366–368
of Path, 312, 314, 319 performed optimistically, 374
of ProcessHandle, 389 stateless, 295
of Set, 264 threadsafe, 368–372
of Stream, 273–274 operators, 17–24
of ZonedDateTime, 430–432 cast, 22
ofDateAdjuster method (TemporalAdjusters), precedence of, 18
428 option files, 492–493
ofDays method Optional class, 280–285
of Duration, 423–424, 426, 431 creating values of, 284
of Period, 431 empty method, 284
ofEntries method (Map), 264 filter method, 282
offer method (BlockingQueue), 371 flatMap method, 284–285
offsetByCodePoints method (String), 33 for empty streams, 292
OffsetDateTime class, 433 for processes, 390
ofHours method (Duration), 423–424 get method, 283–285
ofInstant method ifPresent method, 281
of LocalDate, 425 ifPresentOrElse method, 281
of LocalTime, 429 isPresent method, 283–285
of ZonedDateTime, 432 map method, 282
ofLocalizedXxx methods (DateTimeFormatter), of, ofNullable methods, 284
433, 449 or method, 282
ofMillis, ofMinutes, ofNanos methods orElse method, 280
(Duration), 423–424 orElseThrow method, 281, 283
ofNullable method proper usage of, 283
of Optional, 284 stream method, 285–286
of Stream, 274, 286 OptionalXxx classes, 295
ofPattern method (DateTimeFormatter), 435 or method
ofSeconds method (Duration), 423–424 of BitSet, 261
ofString method (HttpResponse), 322 of Predicate, BiPredicate, 129
ofYears method (Period), 426 Oracle JDK, 468
Index 531

order method (ByteBuffer), 311 parallelStream method (Collection), 249,


ordinal method (Enum), 167 272–273, 295, 366
orElseThrow method (Optional), 281, 283 parallelXxx methods (Arrays), 52, 367
org.omg.corba package, 476 @param tag (javadoc), 97
orTimeout method (CompletableFuture), 357 Parameter class, 183
os.arch, os.name, os.version system parameter variables, 70
properties, 260 annotating, 400
OSGi (Open Service Gateway Initiative), scope of, 45
477 ParameterizedType interface, 240
output parentLogger method (Driver), 494
formatted, 36–38 parse method
redirecting, 469 of DateTimeFormatter, 435
setting locales for, 447 of LocalXxx, ZonedDateTime, 450
writing, 308–310 of NumberFormat, 448
output streams, 302 Parse.quote method, 324
closing, 304 parseDouble method (Double), 28
obtaining, 302 ParseException, 448
writing to, 304 parseInt method (Integer), 28, 194
OutputStream class, 334 partitioning, 365
write method, 304 partitioningBy method (Collectors), 289,
OutputStreamWriter class, 308 292
outputWriter method (Process), 387 Pascal triangle, 54
@Override annotation, 146, 336, 339, passwords, 36
406–407 Path interface, 114, 312–314
overriding, 145–147 get method, 314
for logging/debugging, 151 getXxx methods, 314
overview.html file, 99 normalize method, 313
of method, 312, 314, 319
P relativize method, 313
\p, \P, in regular expressions, 326 resolve, resolveSibling methods, 313
package declarations, 83–85 subpath method, 314
package statement, 84 toAbsolutePath method, 314
package-info.java file, 99, 400 toFile method, 314
packages, 3, 83–90 path separators, 313
accessing, 87–88, 153, 476, 483–484, path.separator system property, 260
486, 490 paths, 312
adding classes to, 88 absolute vs. relative, 312–314
annotating, 400–401 combining, 314
default, 84 filtering, 317
documentation comments for, 95, 99 resolving, 313
exporting, 482–485, 487 taking apart, 314
naming, 83 Paths class, 114
not nesting, 84 Pattern class
split, 488 asMatchPredicate, asPredicate methods,
parallel method (Xxx Stream), 295 329
parallel streams, 366–367 compile method, 329, 333
532 Index

flags, 333 predefined character classes, 324, 326,


matcher, matches methods, 329 328
split method, 331 predicate functions, 289
splitAsStream method, 275, 332 Predicate interface, 124, 129
pattern variables, 213 and method, 129
PECS (producer extends, consumer super), isEqual method, 129–130
226 or, negate methods, 129
peek method test method, 129, 225
of BlockingQueue, 371 Preferences class, 459–461
of Stream, 279 childrenNames method, 460
percent indicator, in string templates, 453 exportSubtree method, 460
performance get, getXxx methods, 460
atomic operations and, 374 importPreferences method, 461
big numbers and, 24 keys method, 460
combined operators and, 20 put, putXxx methods, 460
memory caching and, 361 remove, removeNode methods, 460
Period class systemXxx methods, 459–460
ofDays method, 431 userXxx methods, 459–460
ofYears method, 426 previous method
plusYears method, 426 of ListIterator, 253
permits keyword, 155–156 of TemporalAdjusters, 428
@Persistent annotation, 409 previousClearBit method (BitSet), 261
PHP, scripting engine for, 468 previousOrSame method (TemporalAdjusters),
PI constant (Math), 20, 80, 89 428
placeholders, 453–454 previousSetBit method (BitSet), 261
platform class loader, 174 preVisitDirectory method (FileVisitor), 318
platform encoding, 306, 458 primitive types, 11–14
platform logging API, 206–210 comparing, 161
plugins, loading, 175 converting to strings, 159
plus, plusXxx methods functions interfaces for, 130
of Duration, 424 passed by value, 71
of Instant, 424 streams of, 293–294
of LocalDate, 63–64, 66, 425, 427 type parameters and, 231
of LocalTime, 429 variables of, no updating for, 70
of ZonedDateTime, 431–432 wrapper classes for, 49–50
plusYears method (Period), 426 printStackTrace method (Throwable), 203
Point class, 158–159 PrintStream class, 6, 159, 309
poll method (BlockingQueue), 371 print method, 6, 36, 206, 309
pollXxx methods (NavigableSet), 255 printf method, 36–37, 57, 309
pools, for parallel streams, 297 println method, 6, 35–36, 52, 125, 309
pop method (ArrayDeque), 262 PrintWriter class, 309
POSITIVE_INFINITY value (Double), 13 close method, 197–198
POST requests, 322 print method, 309
postVisitDirectory method (FileVisitor), printf method, 309, 447
318 println method, 309
pow method (Math), 20, 81, 89 priority queues, 263
Index 533

private modifier, 3, 87 responsive, 358


for enum constructors, 168 running, 4
Process class, 386–390 testing, 204
destroy, destroyForcibly methods, 389 promises (in concurrent libraries), 354
errorReader method, 387 properties, 183–184
exitValue method, 389 loading from file, 259
getErrorStream method, 386–387 naming, 184
getInputStream, getOutputStream methods, read-only/write-only, 184
386 testing for, 225
inputReader method, 387 Properties class, 259–260
isAlive method, 389 .properties extension, 455
onExit method, 389 property files
outputWriter method, 387 encoding, 259, 457
supportsNormalTermination method, 389 generating, 417
toHandle method, 389 localizing, 455–457
waitFor method, 388–389 protected modifier, 152–153
ProcessBuilder class, 386–390 Provider.get, Provider.type methods, 178
directory method, 386 provides keyword, 496
redirectXxx methods, 387 Proxy class, 186–188
start, startPipeline methods, 388 newProxyInstance method, 187
processes, 386–390 public modifier, 3, 87
building, 386–388 for interface methods, 108–109
getting info about, 389–390 method overriding and, 147
killing, 389 push method (ArrayDeque), 262
running, 388–389 put method
ProcessHandle interface, 389–390 of BlockingQueue, 371
allProcesses method, 389 of FileChannel, 311
current method, 389 of Map, 255–256
destroy, destroyForcibly methods, 390 of Preferences, 460
info method, 390 putAll method (Map), 257
isAlive method, 390 putBoolean method
of method, 389 of FileChannel, 311
onExit method, 390 of Preferences, 460
supportsNormalTermination method, 390 putByte method (FileChannel), 311
processing pipeline, 355, 388 putByteArray method (Preferences), 460
Processor interface, 413 putChar method (FileChannel), 311
Programmer’s Day, 426 putDouble, putFloat methods
programming languages of FileChannel, 311
functional, 105 of Preferences, 460
object-oriented, 2 putIfAbsent method
scripting, 467 of ConcurrentHashMap, 369
programs of Map, 256
compiling, 4 putInt, putLong methods
configuration options for, 259 of FileChannel, 311
localizing, 441–461 of Preferences, 460
packaging, 499 putShort method (FileChannel), 311
534 Index

Q Reader class, 307


\Q, in regular expressions, 324–325 readers, 302
qualified exports, 495 readExternal method (Externalizable),
Queue interface, 250, 262 338–339
synchronizing methods in, 379 readFields method (ObjectInputStream), 341
using ArrayDeque with, 262 readFloat, readFully methods (DataInput),
quote method (Parse), 324 310
quoteReplacement method (Matcher), 332 readInt method (DataInput), 310–311
readLine method
R of BufferedReader, 308
R language, scripting engine for, 468 of Console, 36
\r (carriage return) readLong method (DataInput), 310
for character literals, 14 readNBytes method (Files), 303
in property files, 260 readObject method
\r, \R, in regular expressions, 325, 328 of HashSet, 337
race conditions, 295, 362–364 of ObjectInputStream, 335–343
Random class, 7, 106 readPassword method (Console), 36
nextInt method, 7, 41 readResolve method (Serializable), 339–340
threadsafe, 384 readShort method (DataInput), 310
random numbers, 7, 41, 106 readUnsignedXxx , readUTF methods
in multiple threads, 384 (DataOutput), 310
streams of, 274, 278, 294 receiver parameters, 69, 403
RandomAccess interface, 249 records, 76–79
RandomAccessFile class, 310–311 serializable, 342
getFilePointer method, 311 redirection syntax, 36
length method, 311 redirectXxx methods (ProcessBuilder), 387
seek method, 310–311 reduce method (Stream), 292–293
RandomGenerator interface, 107 reduceXxx methods (ConcurrentHashMap), 370
methods of, 294 reducing method (Collectors), 291
RandomNumbers class, 82 reductions, 280, 292–293
range method ReentrantLock class, 375–377
of EnumSet, 262 lock, unlock methods, 376
of Xxx Stream, 294 reflection, 179–188
rangeClosed method (Xxx Stream), 294 generic types and, 234, 238–241
ranges, 265 module system and, 180–181, 485,
converting to streams, 296 492
raw types, 229, 232–233 processing annotations with, 410–413
read method security and, 343
of Files, 304 ReflectiveOperationException, 171
of InputStream, 303 regular expressions, 323–333
of InputStreamReader, 307 flags for, 333
readAllXxx methods (Files), 303, 307 groups in, 330–331
readByte, readChar methods (DataInput), 310 replacing matches with, 332
readDouble method splitting input with, 331
of DataInput, 310 testing matches of, 329–330
of ObjectInputStream, 337 turning into predicates, 329
Index 535

relational operators, 22–23 @Retention annotation, 404, 407


relativize method (Path), 313 return statement, 56, 68
remainderUnsigned method (Integer, Long), in finally blocks, 199
21 in lambda expressions, 122
remove method @return tag (javadoc), 97
of ArrayDeque, 262 return types, covariant, 147, 231
of ArrayList, 49 return values
of BlockingQueue, 371 as arrays, 56
of Collection, 249 missing, 280
of Iterator, 253 providing type of, 56
of List, 250 reverse domain name convention, 83,
of Map, 257 478
of Preferences, 460 reverse method (Collections), 52, 252
removeAll method (Collection), 249 reversed method (Comparator), 136
removeIf method reverseOrder method (Comparator), 137
of ArrayList, 124 RFC 822, RFC 1123 formats, 434
of Collection, 249 Rhino JavaScript engine, 468, 470
of Iterator, 253 rotate method (Collections), 252
removeNode method (Preferences), 460 round method (Math), 22
@Repeatable annotation, 407, 409–410 RoundEnvironment interface, 414
replace method roundoff errors, 14
of Map, 257 RowSetProvider class, 492
of String, 29 rt.jar file, 499
replaceAll method Ruby, scripting engine for, 468
of Collections, 251 runAfterXxx methods (CompletableFuture),
of List, 250 357–358
of Map, 257 Runnable interface, 120, 129, 349, 351
of Matcher, 332 executing on the UI thread, 359
of String, 332 run method, 129, 348, 381, 383
replaceFirst method (Matcher), 332 using class literals with, 171
requireNonNull, requireNonNullXxx methods runtime
(Objects), 203–204 raw types at, 232–233
requires keyword, 479, 482–485, 490, safety checks at, 229
493–495 Runtime class
resolve, resolveSibling methods (Path), 313 availableProcessors method, 349
resource bundles, 455–458 exec method, 386
ResourceBundle class runtime image file, 499
extending, 457 RuntimeException, 194
getBundle method, 456–458
getObject method, 457 S
getString method, 456 s formatting symbol (date/time), 436
resources, 170–179 s, S conversion characters, 37
loading, 174, 487 \s, \S, in regular expressions, 326
managing, 197 safety checks, as runtime, 229
resume method (Thread, deprecated), 382 @SafeVarargs annotation, 236, 406, 408
retainAll method (Collection), 249 sample code, 5
536 Index

Scala programming language, 227 ServiceLoader class, 177–179, 496


Scanner class, 35 iterator method, 178
findAll method, 330 load method, 178, 497
hasNext, hasNextXxx methods, 35, 308 ServiceLoader.Provider interface, 178
next, nextXxx methods, 35, 308 services
tokens method, 275, 308 configurable, 177
useLocale method, 447 loading, 177–179, 496–497
scheduling applications ServletException, 201–202
computing dates for, 428–429 Set interface, 249, 372
time zones and, 425, 430 of method, 264
Scheme, scripting engine for, 468 working with EnumSet, 262
ScriptContext interface, 469 set method
ScriptEngine interface of Array, 186
createBindings method, 469 of ArrayList, 49
eval method, 468–471 of BitSet, 261
getFactory method, 469 of Field, 183
ScriptEngineFactory interface, 471 of List, 250
ScriptEngineManager class of ListIterator, 253
getEngineXxx methods, 468 setAccessible method (AccessibleObject),
visibility of bindings in, 469 181, 183
scripting engines, 468 setAll method (Arrays), 127
compiling code in, 471 setBoolean, setByte, setChar methods
implementing Java interfaces in, 471 of Array, 186
scripting languages, 467 of Field, 183
invoking functions in, 470 setClassAssertionStatus method
scripts (ClassLoader), 206
compiling, 471 setContextClassLoader method (Thread),
evaluating, 468 176–177
sealed modifier, 154–156 setCurrency method (NumberFormat), 448
sealed types, 153–156 setDaemon method (Thread), 385
searchXxx methods (ConcurrentHashMap), setDecomposition method (Collator),
370 452
security, 88, 342–344 setDefault method (Locale), 445–446
SecurityException, 181 setDefaultAssertionStatus method
@see tag (javadoc), 98 (ClassLoader), 206
seek method (RandomAccessFile), 311 setDefaultUncaughtExceptionHandler method
sequences, producing, 274 (Thread), 202
@Serial annotation, 336, 339, 406–407 setDoOutput method (URLConnection), 320
serial numbers, 335 setDouble, setFloat, setInt, setLong methods
Serializable interface, 334–335 of Array, 186
readResolve, writeReplace methods, of Field, 183
339–340 setOut method (System), 81
serialization, 333–344 setPackageAssertionStatus method
filters for, 343 (ClassLoader), 206
serialVersionUID instance variable, 341 setProperty method (System), 210
server-side software, 334 setReader method (ScriptContext), 469
Index 537

setRequestProperty method (URLConnection), SocketHandler class, 211


320 sort method
sets, 254–255 of Arrays, 52, 119, 123–124
immutable, 365 of Collections, 52, 226–227, 241, 252
threadsafe, 372 of List, 250
unmodifiable views of, 266 sorted maps, 265–266
setShort method sorted method (Stream), 279
of Array, 186 sorted sets, 249, 265
of Field, 183 traversing, 254
setStrength method (Collator), 452 unmodifiable views of, 266
setUncaughtExceptionHandler method (Thread), sorted streams, 296
381 SortedMap interface, 265
setWriter method (ScriptContext), 469 SortedSet interface, 249, 254
shallow copies, 164–165 first method, 255
shared variables, 362–365 headSet method, 255, 265
atomic mutations of, 373–375 last method, 255
locking, 375–377 subSet, tailSet methods, 255, 265
shell sorting
redirection syntax of, 36 array lists, 52
scripts for, generating, 417 arrays, 52, 117–119
shift operators, 23–24 chaining comparators for, 136
Shift_JIS encoding, 306 changing order of, 135
short circuit evaluation, 23 streams, 279
Short class, 49 strings, 27–28, 124, 451–452
MAX_VALUE, MIN_VALUE constants, 11 source code, generating, 406, 408,
short indicator, in string templates, 453 415–417
short type, 11–12 source files
streams of, 294 documentation comments for, 99
type conversions of, 21 encoding of, 458
short-term persistence, 340 placing, in a file system, 84
shuffle method (Collections), 52, 252 reading from memory, 465
SimpleDateFormat class, 384–385 space flag (for output), 38
SimpleFileVisitor class, 318 spaces
SimpleJavaFileObject class, 466 in regular expressions, 326
@since tag (javadoc), 97 removing, 29
singletons, 339 split method
size method of Pattern, 331
of ArrayList, 49 of String, 26, 332
of Collection, 249 splitAsStream method (Pattern), 275, 332
of Map, 257 spliterator method (Collection), 249
skip method (Stream), 278 Spliterators.spliteratorUnknownSize
skipNBytes method (Files), 304 method, 275
sleep method (Thread), 381, 383 SQL (Structured Query Language), 34
SLF4J (Simple Logging Fasade for Java), sqrt method (Math), 20
206, 478 square root, computing, 284
SOAP protocol, 477 Stack class, 262
538 Index

stack trace, 202–203 mapMulti method, 278


StackWalker class, 203 mapToInt method, 293
standard output, 3 max, min methods, 280
StandardCharsets class, 306 noneMatch method, 280
StandardJavaFileManager interface, 464–466 of method, 273–274
start method ofNullable method, 274, 286
of Matcher, MatchResult, 330–331 peek method, 279
of ProcessBuilder, 388 reduce method, 292–293
of Thread, 381 skip method, 278
startPipeline method (ProcessBuilder), 388 sorted method, 279
startsWith method (String), 29 takeWhile method, 278
stateless operations, 295 toArray method, 126, 286
statements, combining, 46 toList method, 275
static constants, 80–81 unordered method, 296
static imports, 89–90 stream method
static initialization, 175 of Arrays, 274, 294
static methods, 56, 81–83 of BitSet, 261
accessing static variables from, 82 of Collection, 249, 272–273
importing, 90 of Optional, 285–286
in interfaces, 113–114 of StreamSupport, 275
static modifier, 2, 16, 56, 79–83, 169 streams, 271–275
for modules, 494 collecting elements of, 286–288
static nested classes, 90–91 combining, 278
static variables, 79–80 computing values from, 292–293
accessing from static methods, 82 converting to/from arrays, 274, 286,
importing, 90 296, 368
visibility of, 361 creating, 273–276
stop method (Thread, deprecated), 382 debugging, 279
Stream interface empty, 274, 280, 292
anyMatch method, 280 filtering, 285
collect method, 286–287, 293 finite, 274
concat method, 278 flattening, 277, 285
count method, 273, 280 infinite, 273–274, 278–279
distinct method, 279, 296 intermediate operations for, 273
dropWhile method, 278 locating services with, 178
empty method, 274 noninterference of, 275
filter method, 273–276, 280 of primitive type values, 293–294
findAny method, 280 of random numbers, 294
findFirst method, 179, 280 ordered, 296
flatMap method, 277 parallel, 272, 280, 286, 288–289, 292,
forEach, forEachOrdered methods, 286 295–297, 366–367
generate method, 274, 294 processed lazily, 273, 276, 279
iterate method, 274, 279, 294, 367 reductions of, 280
iterator method, 286 removing duplicates from, 279
limit method, 278, 296 returned by Files.lines, 297
map method, 276 sorting, 279
Index 539

splitting, 278 normalized, 452


summarizing, 287, 295 sorting, 27–28, 124, 451–452
terminal operation for, 273, 280 splitting, 26, 275
transformations of, 276–278, 294 templates for, 453–454
vs. collections, 273 transforming to lower/uppercase, 276,
StreamSupport.stream method, 275 447
String class, 6, 28 StringSource class, 465
charAt method, 32 StringWriter class, 309
codePoints method, 32–33, strip method (String), 29, 448
276–278 strong element (HTML), 96
codePointXxx methods, 32 subclasses, 145
compareTo method, 27–28, 117, 451 anonymous, 149–150, 169
compareToIgnoreCase method, 124 calling toString method in, 158
contains method, 29 constructors for, 147
endsWith method, 29 inheriting annotations, 407
equals method, 26–27 initializing instance variables in, 147
equalsIgnoreCase method, 27 methods in, 145
final, 151 preventing, 151
format method, 447 public, 147
formatted method, 38 superclass assignments in, 147
hash codes, 162 subList method (List), 250, 265
immutability of, 29, 365 subMap method (SortedMap), 265
indexOf, lastIndexOf methods, 29 subpath method (Path), 314
join method, 25 subSet method
length method, 6, 32 of NavigableSet, 255
offsetByCodePoints method, 33 of SortedSet, 255, 265
replace method, 29 substring method (String), 26
replaceAll method, 332 subtractExact method (Math), 20
split method, 26, 332 subtraction, 19
startsWith method, 29 accurate, 24
strip method, 448 not associative, 292
substring method, 26 subtypes, 110
toLowerCase method, 29, 276, 447 wildcards for, 224
toUpperCase method, 29, 447 sum method
StringBuilder class, 25 of LongAdder, 374
strings, 6, 25–34 of Xxx Stream, 295
comparing, 26–28 summarizingXxx methods (Collectors), 287,
concatenating, 25, 159 291
converting: summaryStatistics method (Xxx Stream), 295
from byte arrays, 307 summingXxx methods (Collectors), 290
from objects, 158–159 super keyword, 116, 146–147, 150,
to code points, 276 225–227
to numbers, 28 superclasses, 145
empty, 27–28, 159 annotating, 401
formatting for output, 37 calling equals method on, 161
internal representation of, 33 default methods of, 157
540 Index

methods of, 145–147 T


public, 147 T, in dates, 434
serializability of, 335 t, T conversion characters, 37
supertypes, 110, 113 \t
wildcards for, 225–226 in regular expressions, 325
Supplier interface, 129, 354 tab, for character literals, 14
supplyAsync method (CompletableFuture), %t pattern variable, 213
353–355 tab completion, 9–10
supportsNormalTermination method tagging interfaces, 165
of Process, 389 tailMap method (SortedMap), 265
of ProcessHandle, 390 tailSet method
@SuppressWarnings annotation, 232, 406–408, of NavigableSet, 255
480 of SortedSet, 255, 265
suspend method (Thread, deprecated), 382 take method (BlockingQueue), 371
swap method (Collections), 252 takeWhile method (Stream), 278
Swing GUI toolkit, 120–121, 359 tar program, 85
SwingConstants interface, 113 @Target annotation, 404–406
SwingWorker class (Swing), 359 tasks, 348–353
switch statement, 39–41 canceling, 351–352
fall-through variant of, 40 combining results from, 351–353
using enumerations in, 170 computationally intensive, 349
with pattern matching, 154 coordinating work between, 370–372
symbolic links, 316–317 defining, 120
synchronized keyword, 376–380 executing, 120, 349
synchronized views, 266 groups of, 385
synchronizedXxx methods (Collections), 252 long-running, 358–359
System class running, 348–350
getLogger method, 207–208 short-lived, 349
getProperties method, 260 submitting, 351
getProperty method, 175, 204, 259 vs. threads, 349
setOut method, 81 working simultaneously, 354
setProperty method, 210 teeing method (Collectors), 291
system class loader, 174, 176 Temporal interface, 428
system classes, enabling/disabling TemporalAdjuster.ofDateAdjuster
assertions for, 205 method, 428
system properties, 260 TemporalAdjusters class, 428
System.err constant, 202, 211, 385, 464 terminal window, 4
System.in constant, 35 test method
System.Logger interface, 207–209 of BiPredicate, 129
getName method, 209 of Predicate, 129, 225
isLoggable method, 209 of Xxx Predicate, 130
log method, 207–209 @Test annotation, 398–399, 404
System.Logger.Level enumeration, 208 text blocks, 33–34
System.out constant, 6, 17, 35–38, 52, 57, TextStyle enumeration, 451
81, 125, 206, 309, 464 thenAccept method (CompletableFuture), 353,
systemXxx methods (Preferences), 459–460 357
Index 541

thenAcceptBoth method (CompletableFuture), temporarily inactive, 383


357–358 terminating, 349–350
thenApply, thenApplyAsync methods uncaught exception handlers of, 385
(CompletableFuture), 355–357 visibility and, 360–362, 378
thenCombine method (CompletableFuture), vs. tasks, 349
357–358 waiting on conditions, 379
thenComparing method (Comparator), 136–137 worker, 358–359
thenCompose method (CompletableFuture), throw statement, 193
356–357 Throwable class, 193
thenRun method (CompletableFuture), 357 in assertions, 205
third-party libraries, 489–490 initCause method, 202
this reference, 69–70 no generic subtypes for, 237
annotating, 403 printStackTrace method, 203
capturing, 125 throws keyword, 195
in constructors, 73, 366 type variables in, 237–238
in lambda expressions, 132 @throws tag (javadoc), 97, 196
Thread class time
getContextClassLoader method, 176–177 current, 422
interrupted, isInterrupted methods, 382 formatting, 433–436, 449–451
join method, 381 measuring, 423
properties, 385 parsing, 435
resume method (deprecated), 382 Time class, 436–437
setContextClassLoader method, 176–177 time indicator, in string templates, 453
setDaemon method, 385 time zones, 430–433
setDefaultUncaughtExceptionHandler TimeoutException, 351
method, 202 Timestamp class, 162, 436–437
setUncaughtExceptionHandler method, 381 timestamps, 423, 433
sleep method, 381, 383 TimeZone class, 437
start method, 381 ™ (trademark symbol), 452–453
stop, suspend methods (deprecated), 382 toAbsolutePath method (Path), 314
ThreadLocal class, 384–385 toArray method
ThreadLocalRandom.current method, 384 of Collection, 249
threads, 349, 381–385 of Stream, 126, 286
atomic mutations in, 373–375 of Xxx Stream, 295
creating, 120 toByteArray method
daemon, 385 of BitSet, 261
groups of, 385 of ByteArrayOutputStream, 302–303
interrupting, 351, 382–383 toCollection method (Collectors), 286
local variables in, 384–385 toConcurrentMap method (Collectors), 288
locking, 375–377 toDays method (Duration), 423
names of, 385 ToDoubleFunction interface, 130, 232
priorities of, 385 toEpochSecond method
race conditions in, 295, 362–364 of LocalDate, 426
running tasks in, 120 of LocalTime, 429
starting, 381–382 toFile method (Path), 314
states of, 385 toFormat method (DateTimeFormatter), 435
542 Index

toGenericString method (Class), 172 try statement, 196–200


toHandle method (Process), 389 for visiting directories, 316
toHours method (Duration), 423 tryLock method (FileChannel), 312
toInstant method trySetAccessible method (AccessibleObject),
of Date, 436 181
of ZonedDateTime, 431, 433 try-with-resources statement, 197–199
toIntExact method (Math), 22 closing output streams with, 304
ToIntFunction interface, 130, 232 for file locking, 312
tokens method (Scanner), 275, 308 type bounds, 222–223, 241
toList method (Stream), 275 annotating, 402
toLocalXxx methods (ZonedDateTime), 433 type erasure, 228–231, 236
toLongArray method (BitSet), 261 clashes after, 236–237
ToLongFunction interface, 130, 232 Type interface, 240
toLowerCase method (String), 29, 276, 447 type method (ServiceLoader.Provider), 178
toMap method (Collectors), 287–288 type parameters, 117, 220–221
toMillis, toMinutes (Duration), 423 annotating, 400
toNanoOfDay method (LocalTime), 429 primitive types and, 221, 231
toNanos method (Duration), 423 type variables
ToolProvider.getSystemJavaCompiler method, exceptions and, 237–238
464 in static context, 236
toPath method (File), 314 no instantiating of, 233–235
toSecondOfDay method (LocalTime), 429 wildcards with, 226–227
toSeconds method (Duration), 423 TypeElement interface, 414
toSet method (Collectors), 286, 290 TypeVariable interface, 240
toString method
calling from subclasses, 158 U
of Arrays, 52, 159 U+, for code points, 32
of BitSet, 261 \u
of Class, 172 for character literals, 14, 457–458
of Double, 28 in regular expressions, 325
of Enum, 167 %u pattern variable, 213
of Integer, 28 UnaryOperator interface, 129
of Modifier, 173 uncaught exception handlers, 381, 385
of Object, 158–159 unchecked exceptions, 194
of Point, 158–159 documenting, 196
of records, 77 generic types and, 238
toUnsignedInt method (Byte), 12 UncheckedIOException, 308
toUpperCase method (String), 29, 447 Unicode, 31–33, 294, 305
toZonedDateTime method (GregorianCalendar), normalization forms in, 452
436–437 replacement character in, 309
transferTo method (InputStream), 304 unit tests, 397
transient modifier, 336 Unix operating system
transitive keyword, 493–495 executable files in, 5
TreeMap class, 255, 288 path separator in, 86, 260
TreeSet class, 254 specifying locales in, 446
true value (boolean), 14 wildcard in classpath in, 86
Index 543

unlock method (ReentrantLock), 376 values method


unmodifiableXxx methods (Collections), of Enum, 167
252 of Map, 257, 264
unordered method (Stream), 296 var keyword, 15–16
until method (LocalDate), 426–427 varargs parameters
updateAndGet method (AtomicXxx ), 373 declaring, 57
URI class, 322 safety of, 406, 408
URL class, 322 VarHandle class, 487
final, 151 variable handles, 487
getInputStream method, 320 VariableElement interface, 414
openConnection method, 320 variables, 7, 14–17
openStream method, 302 atomic mutations of, 373–375
URLClassLoader class, 175 capturing, in lambda expressions,
URLConnection class, 320–321 132–134
connect method, 320 declaring, 15–16
getHeaderFields method, 320 defined in interfaces, 113
getInputStream method, 321 deprecated, 97, 406–407
getOutputStream method, 320 documentation comments for, 95, 97
setDoOutput method, 320 effectively final, 133–134
setRequestProperty method, 320 final, 361, 365
URLs, reading from, 302, 320 holding object references, 65–66
useLocale method (Scanner), 447 initializing, 15–17
user directory, 314 instance, 67, 69, 72–75, 77–78, 82,
user interface. See GUI 147, 152, 161, 336, 339–341
user preferences, 459–461 local, 45–46
user.dir, user.home, user.name system naming, 15–16
properties, 260 parameter, 70
userXxx methods (Preferences), 459–460 private, 67, 88
uses keyword, 497 public static final, 113
UTC (coordinated universal time), 431 redefining, 46
UTF-8 encoding, 305 scope of, 45, 88
for source files, 458 shared, 362–365, 375–377
modified, 310 static final. See constants
UTF-16 encoding, 14, 32, 294, 305 static, 79–80, 82, 90, 361
in regular expressions, 325 thread-local, 384–385
Util.createInstance method, 176–177 using an abstract class as type of,
utility classes, 87, 176 152
visibility of, 360–362, 378
V volatile, 361–362
V formatting symbol (date/time), 436 @version tag (javadoc), 96, 99
\v, \V, in regular expressions, 326 versioning, 340–342
validateObject method views, 264–266
(ObjectInputValidation), 342–343 virtual machine, 4
valueOf method instruction reordering in, 361
of BitSet, 261 visibility, 360–362
of Enum, 166–167 guaranteed with locks, 378
544 Index

visitFile, visitFileFailed methods withDayOfXxx methods


(FileVisitor), 318 of LocalDate, 425
void keyword, 2, 56 of ZonedDateTime, 432
using class literals with, 171 withHour method
volatile modifier, 362 of LocalTime, 429
of ZonedDateTime, 432
W withLocale method (DateTimeFormatter), 434,
\w, \W, in regular expressions, 326 450
wait method (Object), 379–381 withMinute, withNano, withSecond methods
waitFor method (Process), 388–389 of LocalTime, 429
waiting on a condition, 380 of ZonedDateTime, 432
walk method (Files), 316–319 withMonth method
walkFileTree method (Files), 316, 318 of LocalDate, 425
warning method (Logger), 406 of LocalTime, 429
warnings, suppressing, 232, 236, 407 of ZonedDateTime, 432
weak references, 263 withYear method
weaker access privilege, 147 of LocalDate, 425
WeakHashMap class, 263 of ZonedDateTime, 432
weakly consistent iterators, 368 withZoneSameXxx methods (ZonedDateTime),
WeakReference class, 264 432
web pages words
extracting links from, 355 in regular expressions, 326
reading, 356, 358 reading from a file, 308
whenComplete method (CompletableFuture), sorting alphabetically, 451–452
354, 356–357 working directory, 386
while statement, 41–43 wrapper classes, 49–50
breaking/continuing, 43–44 write method
declaring variables for, 45 of Files, 309, 316
white space of OutputStream, 304
in regular expressions, 326 of Writer, 308
in text blocks, 34 writeByte, writeChar methods (DataOutput),
removing, 29 310
wildcards writeDouble method
annotating, 402 of DataOutput, 310
capturing, 228 of ObjectOutputStream, 337
for annotation processors, 413 writeExternal method (Externalizable),
for types, 224–226 338–339
in class path, 86 writeFloat, writeFully methods (DataOutput),
unbounded, 227 310
with imported classes, 88–89 writeInt method (DataOutput), 310–311
with type variables, 226–227 writeLong method (DataOutput), 310
WildcardType interface, 240 writeObject method
Window class, 88 of HashSet, 337
WindowAdapter class, 114 of ObjectOutputStream, 334–337
WindowListener interface, 114 Writer class, 308–309
with method (Temporal), 428 write method, 308
Index 545

writeReplace method (Serializable), Z


339–340 z, Z formatting symbols (date/time), 434,
writers, 302 436
writeShort, writeUnsignedXxx , writeUTF \z, \Z, in regular expressions, 328
methods (DataOutput), 310 ZIP file systems, 319
ZipInputStream, ZipOutputStream classes, 319
X zoned time, 424–427, 430–433
x, X ZonedDateTime class, 430–433
conversion characters, 37 getXxx, isXxx methods, 432–433
formatting symbols (date/time), 436 legacy classes and, 437
\x, in regular expressions, 325 minus, minusXxx, now methods, 432
XML descriptors, generating, 417 of method, 430–432
xor method (BitSet), 261 ofInstant method, 432
Xoroshiro128PlusPlus algorithm, 106 parse method, 450
plus, plusXxx methods, 431–432
Y toInstant method, 431, 433
y formatting symbol (date/time), 436 toLocalXxx methods, 433
Year, YearMonth classes, 427 withXxx methods, 432
yield statement, 40–41 ZoneId class, 430

You might also like