103

CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 2: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Core Java® SE 9for the Impatient

Second Edition

Page 3: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

This page intentionally left blank

Page 4: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Core Java® SE 9for the ImpatientSecond Edition

Cay S. Horstmann

Boston • Columbus • Indianapolis • 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

Page 5: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Many of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in this book,and the publisher was aware of a trademark claim, the designations have beenprinted with initial capital letters or in all capitals.

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

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

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

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

Visit us on the Web: informit.com/aw

Library of Congress Control Number: 2017947587

Copyright © 2018 Pearson Education, Inc.

Screenshots of Eclipse. Published by The Eclipse Foundation.

Screenshots of Java. Published by Oracle.

All rights reserved. Printed in the United States of America. This publication isprotected by copyright, and permission must be obtained from the publisher priorto any prohibited reproduction, storage in a retrieval system, or transmission in anyform or by any means, electronic, mechanical, photocopying, recording, or likewise.For information regarding permissions, request forms and the appropriate contactswithin the Pearson Education Global Rights & Permissions Department, please visitwww.pearsoned.com/permissions/.

ISBN-13: 978-0-13-469472-6ISBN-10: 0-13-469472-4

1 17

Page 6: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

To Chi—the most patient person in my life.

Page 7: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

This page intentionally left blank

Page 8: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Preface xxi

Acknowledgments xxiii

About the Author xxv

FUNDAMENTAL PROGRAMMING STRUCTURES 11Our First Program 21.1

Dissecting the “Hello, World” Program 21.1.1Compiling and Running a Java Program 31.1.2Method Calls 61.1.3JShell 71.1.4

Primitive Types 101.2Signed Integer Types 101.2.1Floating-Point Types 121.2.2The char Type 131.2.3The boolean Type 141.2.4

Variables 141.3Variable Declarations 141.3.1Names 141.3.2

vii

Contents

Page 9: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Initialization 151.3.3Constants 151.3.4

Arithmetic Operations 171.4Assignment 181.4.1Basic Arithmetic 181.4.2Mathematical Methods 191.4.3Number Type Conversions 201.4.4Relational and Logical Operators 221.4.5Big Numbers 231.4.6

Strings 241.5Concatenation 241.5.1Substrings 251.5.2String Comparison 251.5.3Converting Between Numbers and Strings 271.5.4The String API 281.5.5Code Points and Code Units 301.5.6

Input and Output 321.6Reading Input 321.6.1Formatted Output 331.6.2

Control Flow 361.7Branches 361.7.1Loops 381.7.2Breaking and Continuing 391.7.3Local Variable Scope 411.7.4

Arrays and Array Lists 431.8Working with Arrays 431.8.1Array Construction 441.8.2Array Lists 451.8.3Wrapper Classes for Primitive Types 461.8.4The Enhanced for Loop 471.8.5Copying Arrays and Array Lists 471.8.6Array Algorithms 491.8.7Command-Line Arguments 491.8.8Multidimensional Arrays 501.8.9

Contentsviii

Page 10: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Functional Decomposition 521.9Declaring and Calling Static Methods 531.9.1Array Parameters and Return Values 531.9.2Variable Arguments 531.9.3

Exercises 54

OBJECT-ORIENTED PROGRAMMING 592Working with Objects 602.1

Accessor and Mutator Methods 622.1.1Object References 632.1.2

Implementing Classes 652.2Instance Variables 652.2.1Method Headers 652.2.2Method Bodies 662.2.3Instance Method Invocations 662.2.4The this Reference 672.2.5Call by Value 682.2.6

Object Construction 692.3Implementing Constructors 692.3.1Overloading 702.3.2Calling One Constructor from Another 712.3.3Default Initialization 712.3.4Instance Variable Initialization 722.3.5Final Instance Variables 732.3.6The Constructor with No Arguments 732.3.7

Static Variables and Methods 742.4Static Variables 742.4.1Static Constants 752.4.2Static Initialization Blocks 762.4.3Static Methods 772.4.4Factory Methods 782.4.5

Packages 782.5Package Declarations 792.5.1The jar Command 802.5.2

ixContents

Page 11: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

The Class Path 812.5.3Package Access 832.5.4Importing Classes 832.5.5Static Imports 852.5.6

Nested Classes 852.6Static Nested Classes 852.6.1Inner Classes 872.6.2Special Syntax Rules for Inner Classes 892.6.3

Documentation Comments 902.7Comment Insertion 902.7.1Class Comments 912.7.2Method Comments 922.7.3Variable Comments 922.7.4General Comments 922.7.5Links 932.7.6Package, Module, and Overview Comments 942.7.7Comment Extraction 942.7.8

Exercises 95

INTERFACES AND LAMBDA EXPRESSIONS 993Interfaces 1003.1

Declaring an Interface 1003.1.1Implementing an Interface 1013.1.2Converting to an Interface Type 1033.1.3Casts and the instanceof Operator 1033.1.4Extending Interfaces 1043.1.5Implementing Multiple Interfaces 1053.1.6Constants 1053.1.7

Static, Default, and Private Methods 1053.2Static Methods 1053.2.1Default Methods 1063.2.2Resolving Default Method Conflicts 1073.2.3Private Methods 1093.2.4

Contentsx

Page 12: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Examples of Interfaces 1093.3The Comparable Interface 1093.3.1The Comparator Interface 1113.3.2The Runnable Interface 1123.3.3User Interface Callbacks 1123.3.4

Lambda Expressions 1133.4The Syntax of Lambda Expressions 1143.4.1Functional Interfaces 1153.4.2

Method and Constructor References 1163.5Method References 1173.5.1Constructor References 1183.5.2

Processing Lambda Expressions 1193.6Implementing Deferred Execution 1193.6.1Choosing a Functional Interface 1203.6.2Implementing Your Own Functional Interfaces 1233.6.3

Lambda Expressions and Variable Scope 1243.7Scope of a Lambda Expression 1243.7.1Accessing Variables from the Enclosing Scope 1243.7.2

Higher-Order Functions 1273.8Methods that Return Functions 1273.8.1Methods That Modify Functions 1283.8.2Comparator Methods 1283.8.3

Local and Anonymous Classes 1293.9Local Classes 1293.9.1Anonymous Classes 1303.9.2

Exercises 131

INHERITANCE AND REFLECTION 1354Extending a Class 1364.1

Super- and Subclasses 1364.1.1Defining and Inheriting Subclass Methods 1374.1.2Method Overriding 1374.1.3Subclass Construction 1394.1.4

xiContents

Page 13: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Superclass Assignments 1394.1.5Casts 1404.1.6Final Methods and Classes 1414.1.7Abstract Methods and Classes 1414.1.8Protected Access 1424.1.9Anonymous Subclasses 1434.1.10Inheritance and Default Methods 1444.1.11Method Expressions with super 1454.1.12

Object: The Cosmic Superclass 1454.2The toString Method 1464.2.1The equals Method 1484.2.2The hashCode Method 1504.2.3Cloning Objects 1514.2.4

Enumerations 1544.3Methods of Enumerations 1554.3.1Constructors, Methods, and Fields 1564.3.2Bodies of Instances 1574.3.3Static Members 1574.3.4Switching on an Enumeration 1584.3.5

Runtime Type Information and Resources 1594.4The Class Class 1594.4.1Loading Resources 1624.4.2Class Loaders 1634.4.3The Context Class Loader 1644.4.4Service Loaders 1664.4.5

Reflection 1684.5Enumerating Class Members 1684.5.1Inspecting Objects 1694.5.2Invoking Methods 1714.5.3Constructing Objects 1714.5.4JavaBeans 1724.5.5Working with Arrays 1744.5.6Proxies 1754.5.7

Exercises 177

Contentsxii

Page 14: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

EXCEPTIONS, ASSERTIONS, AND LOGGING 1815Exception Handling 1825.1

Throwing Exceptions 1825.1.1The Exception Hierarchy 1835.1.2Declaring Checked Exceptions 1855.1.3Catching Exceptions 1865.1.4The Try-with-Resources Statement 1875.1.5The finally Clause 1895.1.6Rethrowing and Chaining Exceptions 1905.1.7Uncaught Exceptions and the Stack Trace 1925.1.8The Objects.requireNonNull Method 1935.1.9

Assertions 1935.2Using Assertions 1945.2.1Enabling and Disabling Assertions 1945.2.2

Logging 1955.3Using Loggers 1955.3.1Loggers 1965.3.2Logging Levels 1975.3.3Other Logging Methods 1975.3.4Logging Configuration 1995.3.5Log Handlers 2005.3.6Filters and Formatters 2025.3.7

Exercises 203

GENERIC PROGRAMMING 2076Generic Classes 2086.1Generic Methods 2096.2Type Bounds 2106.3Type Variance and Wildcards 2116.4

Subtype Wildcards 2126.4.1Supertype Wildcards 2136.4.2Wildcards with Type Variables 2146.4.3Unbounded Wildcards 2156.4.4Wildcard Capture 2166.4.5

xiiiContents

Page 15: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Generics in the Java Virtual Machine 2166.5Type Erasure 2176.5.1Cast Insertion 2176.5.2Bridge Methods 2186.5.3

Restrictions on Generics 2206.6No Primitive Type Arguments 2206.6.1At Runtime, All Types Are Raw 2206.6.2You Cannot Instantiate Type Variables 2216.6.3You Cannot Construct Arrays of ParameterizedTypes 223

6.6.4

Class Type Variables Are Not Valid in StaticContexts 224

6.6.5

Methods May Not Clash after Erasure 2246.6.6Exceptions and Generics 2256.6.7

Reflection and Generics 2266.7The Class<T> Class 2276.7.1Generic Type Information in the VirtualMachine 227

6.7.2

Exercises 229

COLLECTIONS 2357An Overview of the Collections Framework 2367.1Iterators 2407.2Sets 2427.3Maps 2437.4Other Collections 2477.5

Properties 2477.5.1Bit Sets 2487.5.2Enumeration Sets and Maps 2507.5.3Stacks, Queues, Deques, and Priority Queues 2507.5.4Weak Hash Maps 2517.5.5

Views 2527.6Small Collections 2527.6.1Ranges 2537.6.2

Contentsxiv

Page 16: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Unmodifiable Views 2547.6.3Exercises 255

STREAMS 2598From Iterating to Stream Operations 2608.1Stream Creation 2618.2The filter, map, and flatMap Methods 2638.3Extracting Substreams and Combining Streams 2648.4Other Stream Transformations 2658.5Simple Reductions 2668.6The Optional Type 2678.7

How to Work with Optional Values 2678.7.1How Not to Work with Optional Values 2698.7.2Creating Optional Values 2698.7.3Composing Optional Value Functions with flatMap 2698.7.4Turning an Optional Into a Stream 2708.7.5

Collecting Results 2718.8Collecting into Maps 2738.9Grouping and Partitioning 2748.10Downstream Collectors 2758.11Reduction Operations 2778.12Primitive Type Streams 2798.13Parallel Streams 2808.14

Exercises 283

PROCESSING INPUT AND OUTPUT 2879Input/Output Streams, Readers, and Writers 2889.1

Obtaining Streams 2889.1.1Reading Bytes 2899.1.2Writing Bytes 2909.1.3Character Encodings 2909.1.4Text Input 2939.1.5Text Output 2949.1.6Reading and Writing Binary Data 2959.1.7

xvContents

Page 17: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Random-Access Files 2969.1.8Memory-Mapped Files 2979.1.9File Locking 2979.1.10

Paths, Files, and Directories 2989.2Paths 2989.2.1Creating Files and Directories 3009.2.2Copying, Moving, and Deleting Files 3019.2.3Visiting Directory Entries 3029.2.4ZIP File Systems 3059.2.5

HTTP Connections 3069.3The URLConnection and HttpURLConnection Classes 3069.3.1The HTTP Client API 3079.3.2

Regular Expressions 3109.4The Regular Expression Syntax 3109.4.1Finding One Match 3149.4.2Finding All Matches 3159.4.3Groups 3169.4.4Splitting along Delimiters 3179.4.5Replacing Matches 3179.4.6Flags 3189.4.7

Serialization 3199.5The Serializable Interface 3199.5.1Transient Instance Variables 3219.5.2The readObject and writeObject Methods 3219.5.3The readResolve and writeReplace Methods 3229.5.4Versioning 3249.5.5

Exercises 325

CONCURRENT PROGRAMMING 32910Concurrent Tasks 33010.1

Running Tasks 33010.1.1Futures 33310.1.2

Asynchronous Computations 33510.2Completable Futures 33510.2.1

Contentsxvi

Page 18: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Composing Completable Futures 33710.2.2Long-Running Tasks in User-Interface Callbacks 34010.2.3

Thread Safety 34110.3Visibility 34210.3.1Race Conditions 34410.3.2Strategies for Safe Concurrency 34610.3.3Immutable Classes 34710.3.4

Parallel Algorithms 34810.4Parallel Streams 34810.4.1Parallel Array Operations 34910.4.2

Threadsafe Data Structures 35010.5Concurrent Hash Maps 35010.5.1Blocking Queues 35210.5.2Other Threadsafe Data Structures 35410.5.3

Atomic Counters and Accumulators 35410.6Locks and Conditions 35710.7

Locks 35710.7.1The synchronized Keyword 35810.7.2Waiting on Conditions 36010.7.3

Threads 36210.8Starting a Thread 36310.8.1Thread Interruption 36410.8.2Thread-Local Variables 36510.8.3Miscellaneous Thread Properties 36610.8.4

Processes 36610.9Building a Process 36710.9.1Running a Process 36810.9.2Process Handles 37010.9.3

Exercises 371

ANNOTATIONS 37711Using Annotations 37811.1

Annotation Elements 37811.1.1Multiple and Repeated Annotations 38011.1.2

xviiContents

Page 19: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Annotating Declarations 38011.1.3Annotating Type Uses 38111.1.4Making Receivers Explicit 38211.1.5

Defining Annotations 38311.2Standard Annotations 38611.3

Annotations for Compilation 38711.3.1Annotations for Managing Resources 38811.3.2Meta-Annotations 38911.3.3

Processing Annotations at Runtime 39111.4Source-Level Annotation Processing 39411.5

Annotation Processors 39411.5.1The Language Model API 39511.5.2Using Annotations to Generate Source Code 39511.5.3

Exercises 398

THE DATE AND TIME API 40112The Time Line 40212.1Local Dates 40412.2Date Adjusters 40712.3Local Time 40912.4Zoned Time 41012.5Formatting and Parsing 41312.6Interoperating with Legacy Code 41612.7

Exercises 417

INTERNATIONALIZATION 42113Locales 42213.1

Specifying a Locale 42313.1.1The Default Locale 42613.1.2Display Names 42613.1.3

Number Formats 42713.2Currencies 42813.3Date and Time Formatting 42913.4Collation and Normalization 43113.5

Contentsxviii

Page 20: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Message Formatting 43313.6Resource Bundles 43513.7

Organizing Resource Bundles 43513.7.1Bundle Classes 43713.7.2

Character Encodings 43813.8Preferences 43913.9

Exercises 441

COMPILING AND SCRIPTING 44314The Compiler API 44414.1

Invoking the Compiler 44414.1.1Launching a Compilation Task 44414.1.2Reading Source Files from Memory 44514.1.3Writing Byte Codes to Memory 44614.1.4Capturing Diagnostics 44714.1.5

The Scripting API 44814.2Getting a Scripting Engine 44814.2.1Bindings 44914.2.2Redirecting Input and Output 44914.2.3Calling Scripting Functions and Methods 45014.2.4Compiling a Script 45214.2.5

The Nashorn Scripting Engine 45214.3Running Nashorn from the Command Line 45214.3.1Invoking Getters, Setters, and OverloadedMethods 453

14.3.2

Constructing Java Objects 45414.3.3Strings in JavaScript and Java 45514.3.4Numbers 45614.3.5Working with Arrays 45714.3.6Lists and Maps 45814.3.7Lambdas 45814.3.8Extending Java Classes and Implementing JavaInterfaces 459

14.3.9

Exceptions 46114.3.10

xixContents

Page 21: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Shell Scripting with Nashorn 46114.4Executing Shell Commands 46214.4.1String Interpolation 46214.4.2Script Inputs 46314.4.3

Exercises 464

THE JAVA PLATFORM MODULE SYSTEM 46915The Module Concept 47015.1Naming Modules 47215.2The Modular “Hello, World!” Program 47215.3Requiring Modules 47415.4Exporting Packages 47615.5Modules and Reflective Access 47915.6Modular JARs 48215.7Automatic Modules and the Unnamed Module 48415.8Command-Line Flags for Migration 48515.9Transitive and Static Requirements 48715.10Qualified Exporting and Opening 48915.11Service Loading 49015.12Tools for Working with Modules 49115.13

Exercises 494

Index 497

Contentsxx

Page 22: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Java is now over twenty years old, and the classic book, Core Java, covers, inmeticulous detail, not just the language but all core libraries and a multitudeof changes between versions, spanning two volumes and well over2,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 li-braries. In this book, I don’t retrace history and don’t dwell on features ofpast versions. I show you the good parts of Java as it exists today, with Java 9,so you can put your knowledge to work quickly.

As with my previous “Impatient” books, I quickly cut to the chase, showingyou what you need to know to solve a programming problem without lecturingabout the superiority of one paradigm over another. I also present the infor-mation in small chunks, organized so that you can quickly retrieve it whenneeded.

Assuming you are proficient in some other programming language, such asC++, JavaScript, Objective C, PHP, or Ruby, with this book you will learnhow to become a competent Java programmer. I cover all aspects of Java thata developer needs to know, including the powerful concepts of lambda ex-pressions and streams. I tell you where to find out more about old-fashionedconcepts that you might still see in legacy code, but I don’t dwell on them.

A key reason to use Java is to tackle concurrent programming. With parallelalgorithms and threadsafe data structures readily available in the Java library,

xxi

Preface

Page 23: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

the way application programmers should handle concurrent programminghas completely changed. I provide fresh coverage, showing you how to usethe powerful library features instead of error-prone low-level constructs.

Traditionally, books on Java have focused on user interface programming—butnowadays, 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 distractedby desktop GUI code.

Finally, this book is written for application programmers, not for a collegecourse and not for systems wizards. The book covers issues that applicationprogrammers need to wrestle with, such as logging and working with files—butyou won’t learn how to implement a linked list by hand or how to write aweb server.

I hope you enjoy this rapid-fire introduction into modern Java, and I hope itwill make your work with Java productive and enjoyable.

If you find errors or have suggestions for improvement, please visithttp://horstmann.com/javaimpatient and leave a comment. On that page, you willalso find a link to an archive file containing all code examples from the book.

Prefacexxii

Page 24: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

My thanks go, as always, to my editor Greg Doench, who enthusiasticallysupported the vision of a short book that gives a fresh introduction to JavaSE 9. Dmitry Kirsanov and Alina Kirsanova once again turned an XHTMLmanuscript into an attractive book with amazing speed and attention to detail.My special gratitude goes to the excellent team of reviewers for both editionswho spotted many errors and gave thoughtful suggestions for improvement.They are: Andres Almiray, Gail Anderson, Paul Anderson, Marcus Biel, BrianGoetz, Marty Hall, Mark Lawrence, Doug Lea, Simon Ritter, Yoshiki Shibata,and Christian Ullenboom.

Cay HorstmannSan FranciscoJuly 2017

xxiii

Acknowledgments

Page 25: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

This page intentionally left blank

Page 26: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Cay S. Horstmann is the author of Java SE 8 for the Really Impatient and Scalafor the Impatient (both from Addison-Wesley), is principal author of Core Java™,Volumes I and II, Tenth Edition (Prentice Hall, 2016), and has written a dozenother books for professional programmers and computer science students.He is a professor of computer science at San Jose State University and is aJava Champion.

xxv

About the Author

Page 27: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Topics in This Chapter

3.1 Interfaces — page 100

3.2 Static, Default, and Private Methods — page 105

3.3 Examples of Interfaces — page 109

3.4 Lambda Expressions — page 113

3.5 Method and Constructor References — page 116

3.6 Processing Lambda Expressions — page 119

3.7 Lambda Expressions and Variable Scope — page 124

3.8 Higher-Order Functions — page 127

3.9 Local and Anonymous Classes — page 129

Exercises — page 131

Interfaces andLambda Expressions

Page 28: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Java was designed as an object-oriented programming language in the 1990swhen object-oriented programming was the principal paradigm for softwaredevelopment. Interfaces are a key feature of object-oriented programming:They let you specify what should be done, without having to provide animplementation.

Long before there was object-oriented programming, there were functionalprogramming languages, such as Lisp, in which functions and not objects arethe primary structuring mechanism. Recently, functional programming hasrisen in importance because it is well suited for concurrent and event-driven(or “reactive”) programming. Java supports function expressions that providea convenient bridge between object-oriented and functional programming. Inthis chapter, you will learn about interfaces and lambda expressions.

The key points of this chapter are:

1. An interface specifies a set of methods that an implementing class mustprovide.

2. An interface is a supertype of any class that implements it. Therefore,one can assign instances of the class to variables of the interface type.

3. An interface can contain static methods. All variables of an interface areautomatically public, static, and final.

99

3Chapter

Page 29: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

4. An interface can contain default methods that an implementing class caninherit or override.

5. An interface can contain private methods that cannot be called oroverridden by implementing classes.

6. The Comparable and Comparator interfaces are used for comparing objects.

7. A functional interface is an interface with a single abstract method.

8. A lambda expression denotes a block of code that can be executed at alater point in time.

9. Lambda expressions are converted to functional interfaces.

10. Method and constructor references refer to methods or constructorswithout invoking them.

11. Lambda expressions and local classes can access effectively final variablesfrom the enclosing scope.

3.1 Interfaces

An interface is a mechanism for spelling out a contract between two parties:the supplier of a service and the classes that want their objects to be usablewith the service. In the following sections, you will see how to define anduse interfaces in Java.

3.1.1 Declaring an Interface

Consider a service that works on sequences of integers, reporting the averageof the first n values:

public static double average(IntSequence seq, int n)

Such sequences can take many forms. Here are some examples:

• A sequence of integers supplied by a user

• A sequence of random integers

• The sequence of prime numbers

• The sequence of elements in an integer array

• The sequence of code points in a string

• The sequence of digits in a number

We want to implement a single mechanism for dealing with all these kinds ofsequences.

Chapter 3 Interfaces and Lambda Expressions100

Page 30: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

First, let us spell out what is common between integer sequences. At aminimum, one needs two methods for working with a sequence:

• Test whether there is a next element

• Get the next element

To declare an interface, you provide the method headers, like this:public interface IntSequence { boolean hasNext(); int next();}

You need not implement these methods, but you can provide default imple-mentations if you like—see Section 3.2.2, “Default Methods” (page 106). If noimplementation is provided, we say that the method is abstract.

NOTE: All methods of an interface are automatically public. Therefore,it is not necessary to declare hasNext and next as public. Someprogrammers do it anyway for greater clarity.

The methods in the interface suffice to implement the average method:public static double average(IntSequence seq, int n) { int count = 0; double sum = 0; while (seq.hasNext() && count < n) { count++; sum += seq.next(); } return count == 0 ? 0 : sum / count;}

3.1.2 Implementing an Interface

Now let’s look at the other side of the coin: the classes that want to be usablewith the average method. They need to implement the IntSequence interface. Hereis such a class:

public class SquareSequence implements IntSequence { private int i;

public boolean hasNext() { return true; }

1013.1 Interfaces

Page 31: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

public int next() { i++; return i * i; }}

There are infinitely many squares, and an object of this class delivers them all,one at a time. (To keep the example simple, we ignore integer overflow—seeExercise 6.)

The implements keyword indicates that the SquareSequence class intends to conformto the IntSequence interface.

CAUTION: The implementing class must declare the methods of theinterface as public. Otherwise, they would default to package access.Since the interface requires public access, the compiler would report anerror.

This code gets the average of the first 100 squares:SquareSequence squares = new SquareSequence();double avg = average(squares, 100);

There are many classes that can implement the IntSequence interface. For exam-ple, this class yields a finite sequence, namely the digits of a positive integerstarting with the least significant one:

public class DigitSequence implements IntSequence { private int number;

public DigitSequence(int n) { number = n; }

public boolean hasNext() { return number != 0; }

public int next() { int result = number % 10; number /= 10; return result; }

public int rest() { return number; }}

Chapter 3 Interfaces and Lambda Expressions102

Page 32: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

An object new DigitSequence(1729) delivers the digits 9 2 7 1 before hasNext returnsfalse.

NOTE: The SquareSequence and DigitSequence classes implement all methodsof the IntSequence interface. If a class only implements some of themethods, then it must be declared with the abstract modifier. SeeChapter 4 for more information on abstract classes.

3.1.3 Converting to an Interface Type

This code fragment computes the average of the digit sequence values:IntSequence digits = new DigitSequence(1729);double avg = average(digits, 100); // Will only look at the first four sequence values

Look at the digits variable. Its type is IntSequence, not DigitSequence. A variableof type IntSequence refers to an object of some class that implements theIntSequence interface. You can always assign an object to a variable whose typeis an implemented interface, or pass it to a method expecting such an interface.

Here is a bit of useful terminology. A type S is a supertype of the type T (thesubtype) when any value of the subtype can be assigned to a variable ofthe supertype without a conversion. For example, the IntSequence interface isa supertype of the DigitSequence class.

NOTE: Even though it is possible to declare variables of an interfacetype, you can never have an object whose type is an interface. All objectsare instances of classes.

3.1.4 Casts and the instanceof Operator

Occasionally, you need the opposite conversion—from a supertype to a sub-type. Then you use a cast. For example, if you happen to know that the objectstored in an IntSequence is actually a DigitSequence, you can convert the typelike this:

IntSequence sequence = ...;DigitSequence digits = (DigitSequence) sequence;System.out.println(digits.rest());

In this scenario, the cast was necessary because rest is a method of DigitSequencebut not IntSequence.

1033.1 Interfaces

Page 33: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

See Exercise 2 for a more compelling example.

You can only cast an object to its actual class or one of its supertypes. If youare wrong, a compile-time error or class cast exception will occur:

String digitString = (String) sequence; // Cannot possibly work—IntSequence is not a supertype of StringRandomSequence randoms = (RandomSequence) sequence; // Could work, throws a class cast exception if not

To avoid the exception, you can first test whether the object is of the desiredtype, using the instanceof operator. The expression

object instanceof Type

returns true if object is an instance of a class that has Type as a supertype. Itis a good idea to make this check before using a cast.

if (sequence instanceof DigitSequence) { DigitSequence digits = (DigitSequence) sequence; ...}

NOTE: The instanceof operator is null-safe: The expression obj instanceofType is false if obj is null. After all, null cannot possibly be a referenceto an object of any given type.

3.1.5 Extending Interfaces

An interface can extend another, requiring or providing additional methodson top of the original ones. For example, Closeable is an interface with a singlemethod:

public interface Closeable { void close();}

As you will see in Chapter 5, this is an important interface for closingresources when an exception occurs.

The Channel interface extends this interface:public interface Channel extends Closeable { boolean isOpen();}

A class that implements the Channel interface must provide both methods, andits objects can be converted to both interface types.

Chapter 3 Interfaces and Lambda Expressions104

Page 34: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.1.6 Implementing Multiple Interfaces

A class can implement any number of interfaces. For example, a FileSequenceclass that reads integers from a file can implement the Closeable interface inaddition to IntSequence:

public class FileSequence implements IntSequence, Closeable { ...}

Then the FileSequence class has both IntSequence and Closeable as supertypes.

3.1.7 Constants

Any variable defined in an interface is automatically public static final.

For example, the SwingConstants interface defines constants for compassdirections:

public interface SwingConstants { int NORTH = 1; int NORTH_EAST = 2; int EAST = 3; ...}

You can refer to them by their qualified name, SwingConstants.NORTH. If your classchooses to implement the SwingConstants interface, you can drop the SwingConstantsqualifier and simply write NORTH. However, this is not a common idiom. It isfar better to use enumerations for a set of constants; see Chapter 4.

NOTE: You cannot have instance variables in an interface. An interfacespecifies behavior, not object state.

3.2 Static, Default, and Private Methods

In earlier versions of Java, all methods of an interface had to be abstract—thatis, without a body. Nowadays you can add three kinds of methods with aconcrete implementation: static, default, and private methods. The followingsections describe these methods.

3.2.1 Static Methods

There was never a technical reason why an interface could not have staticmethods, but they did not fit into the view of interfaces as abstract

1053.2 Static, Default, and Private Methods

Page 35: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

specifications. That thinking has now evolved. In particular, factory methodsmake a lot of sense in interfaces. For example, the IntSequence interface canhave a static method digitsOf that generates a sequence of digits of a giveninteger:

IntSequence digits = IntSequence.digitsOf(1729);

The method yields an instance of some class implementing the IntSequenceinterface, but the caller need not care which one it is.

public interface IntSequence { ... static IntSequence digitsOf(int n) { return new DigitSequence(n); }}

NOTE: In the past, it had been common to place static methods in acompanion class. You find pairs of interfaces and utility classes, suchas Collection/Collections or Path/Paths, in the Java API. This split is nolonger necessary.

3.2.2 Default Methods

You can supply a default implementation for any interface method. You musttag such a method with the default modifier.

public interface IntSequence {default boolean hasNext() { return true; }

// By default, sequences are infinite int next();}

A class implementing this interface can choose to override the hasNext methodor to inherit the default implementation.

NOTE: Default methods put an end to the classic pattern of providingan interface and a companion class that implements most or all ofits methods, such as Collection/AbstractCollection or WindowListener/WindowAdapter in the Java API. Nowadays you should just implement themethods in the interface.

An important use for default methods is interface evolution. Consider for exam-ple the Collection interface that has been a part of Java for many years. Supposethat way back when, you provided a class

Chapter 3 Interfaces and Lambda Expressions106

Page 36: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

public class Bag implements Collection

Later, in Java 8, a stream method was added to the interface.

Suppose the stream method was not a default method. Then the Bag class nolonger compiles since it doesn’t implement the new method. Adding anondefault method to an interface is not source-compatible.

But suppose you don’t recompile the class and simply use an old JAR filecontaining it. The class will still load, even with the missing method. Programscan still construct Bag instances, and nothing bad will happen. (Adding amethod to an interface is binary-compatible.) However, if a program calls thestream method on a Bag instance, an AbstractMethodError occurs.

Making the method a default method solves both problems. The Bag class willagain compile. And if the class is loaded without being recompiled and thestream method is invoked on a Bag instance, the Collection.stream method is called.

3.2.3 Resolving Default Method Conflicts

If a class implements two interfaces, one of which has a default method andthe other a method (default or not) with the same name and parametertypes, then you must resolve the conflict. This doesn’t happen very often,and it is usually easy to deal with the situation.

Let’s look at an example. Suppose we have an interface Person with a getIdmethod:

public interface Person { String getName(); default int getId() { return 0; }}

And suppose there is an interface Identified, also with such a method.public interface Identified { default int getId() { return Math.abs(hashCode()); } }

You will see what the hashCode method does in Chapter 4. For now, all thatmatters is that it returns some integer that is derived from the object.

What happens if you form a class that implements both of them?public class Employee implements Person, Identified { ...}

The class inherits two getId methods provided by the Person and Identified in-terfaces. There is no way for the Java compiler to choose one over the other.The compiler reports an error and leaves it up to you to resolve the ambiguity.

1073.2 Static, Default, and Private Methods

Page 37: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Provide a getId method in the Employee class and either implement your ownID scheme, or delegate to one of the conflicting methods, like this:

public class Employee implements Person, Identified { public int getId() { return Identified.super.getId(); } ...}

NOTE: The super keyword lets you call a supertype method. In this case,we need to specify which supertype we want. The syntax may seem abit odd, but it is consistent with the syntax for invoking a superclassmethod that you will see in Chapter 4.

Now assume that the Identified interface does not provide a defaultimplementation for getId:

interface Identified { int getId();}

Can the Employee class inherit the default method from the Person interface? Atfirst glance, this might seem reasonable. But how does the compiler knowwhether the Person.getId method actually does what Identified.getId is expectedto do? After all, it might return the level of the person’s Freudian id, not anID number.

The Java designers decided in favor of safety and uniformity. It doesn’t matterhow two interfaces conflict; if at least one interface provides an implementa-tion, the compiler reports an error, and it is up to the programmer to resolvethe ambiguity.

NOTE: If neither interface provides a default for a shared method, thenthere is no conflict. An implementing class has two choices: implementthe method, or leave it unimplemented and declare the class as abstract.

NOTE: If a class extends a superclass (see Chapter 4) and implementsan interface, inheriting the same method from both, the rules are easier.In that case, only the superclass method matters, and any default methodfrom the interface is simply ignored. This is actually a more commoncase than conflicting interfaces. See Chapter 4 for the details.

Chapter 3 Interfaces and Lambda Expressions108

Page 38: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.2.4 Private Methods

As of Java 9, methods in an interface can be private. A private method canbe static or an instance method, but it cannot be a default method since thatcan be overridden. As private methods can only be used in the methods ofthe interface itself, their use is limited to being helper methods for the othermethods of the interface.

For example, suppose the IntSequence class provides methodsstatic of(int a)static of(int a, int b)static of(int a, int b, int c)

Then each of these methods could call a helper methodprivate static IntSequence makeFiniteSequence(int... values) { ... }

3.3 Examples of Interfaces

At first glance, interfaces don’t seem to do very much. An interface is just aset of methods that a class promises to implement. To make the importanceof interfaces more tangible, the following sections show you four examplesof commonly used interfaces from the Java API.

3.3.1 The Comparable Interface

Suppose you want to sort an array of objects. A sorting algorithm repeatedlycompares elements and rearranges them if they are out of order. Of course,the rules for doing the comparison are different for each class, and the sortingalgorithm should just call a method supplied by the class. As long as allclasses can agree on what that method is called, the sorting algorithm cando its job. That is where interfaces come in.

If a class wants to enable sorting for its objects, it should implement theComparable interface. There is a technical point about this interface. We wantto compare strings against strings, employees against employees, and so on.For that reason, the Comparable interface has a type parameter.

public interface Comparable<T> { int compareTo(T other);}

For example, the String class implements Comparable<String> so that its compareTomethod has the signature

int compareTo(String other)

1093.3 Examples of Interfaces

Page 39: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

NOTE: A type with a type parameter such as Comparable or ArrayList isa generic type. You will learn all about generic types in Chapter 6.

When calling x.compareTo(y), the compareTo method returns an integer value toindicate whether x or y should come first. A positive return value (not neces-sarily 1) indicates that x should come after y. A negative integer (not necessar-ily -1) is returned when x should come before y. If x and y are consideredequal, the returned value is 0.

Note that the return value can be any integer. That flexibility is useful becauseit allows you to return a difference of integers. That is handy, provided thedifference cannot produce integer overflow.

public class Employee implements Comparable<Employee> { ... public int compareTo(Employee other) { return getId() - other.getId(); // Ok if IDs always ≥ 0 }}

CAUTION: Returning a difference of integers does not always work. Thedifference can overflow for large operands of opposite sign. In that case,use the Integer.compare method that works correctly for all integers.However, if you know that the integers are non-negative, or their absolutevalue is less than Integer.MAX_VALUE / 2, then the difference works fine.

When comparing floating-point values, you cannot just return the difference.Instead, use the static Double.compare method. It does the right thing, even for±∞ and NaN.

Here is how the Employee class can implement the Comparable interface, orderingemployees by salary:

public class Employee implements Comparable<Employee> { ... public int compareTo(Employee other) { return Double.compare(salary, other.salary); }}

NOTE: It is perfectly legal for the compare method to access other.salary.In Java, a method can access private features of any object of its class.

Chapter 3 Interfaces and Lambda Expressions110

Page 40: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

The String class, as well as over a hundred other classes in the Java library,implements the Comparable interface. You can use the Arrays.sort method to sortan array of Comparable objects:

String[] friends = { "Peter", "Paul", "Mary" };Arrays.sort(friends); // friends is now ["Mary", "Paul", "Peter"]

NOTE: Strangely, the Arrays.sort method does not check at compile timewhether the argument is an array of Comparable objects. Instead, it throwsan exception if it encounters an element of a class that doesn’t implementthe Comparable interface.

3.3.2 The Comparator Interface

Now suppose we want to sort strings by increasing length, not in dictionaryorder. We can’t have the String class implement the compareTo method in twoways—and at any rate, the String class isn’t ours to modify.

To deal with this situation, there is a second version of the Arrays.sort methodwhose parameters are an array and a comparator—an instance of a class thatimplements the Comparator interface.

public interface Comparator<T> { int compare(T first, T second);}

To compare strings by length, define a class that implements Comparator<String>:class LengthComparator implements Comparator<String> { public int compare(String first, String second) { return first.length() - second.length(); }}

To actually do the comparison, you need to make an instance:Comparator<String> comp = new LengthComparator();if (comp.compare(words[i], words[j]) > 0) ...

Contrast this call with words[i].compareTo(words[j]). The compare method is calledon the comparator object, not the string itself.

NOTE: Even though the LengthComparator object has no state, you stillneed to make an instance of it. You need the instance to call the comparemethod—it is not a static method.

1113.3 Examples of Interfaces

Page 41: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

To sort an array, pass a LengthComparator object to the Arrays.sort method:String[] friends = { "Peter", "Paul", "Mary" };Arrays.sort(friends, new LengthComparator());

Now the array is either ["Paul", "Mary", "Peter"] or ["Mary", "Paul", "Peter"].

You will see in Section 3.4.2, “Functional Interfaces” (page 115) how to use aComparator much more easily, using a lambda expression.

3.3.3 The Runnable Interface

At a time when just about every processor has multiple cores, you want tokeep those cores busy. You may want to run certain tasks in a separate thread,or give them to a thread pool for execution. To define the task, you implementthe Runnable interface. This interface has just one method.

class HelloTask implements Runnable { public void run() { for (int i = 0; i < 1000; i++) { System.out.println("Hello, World!"); } }}

If you want to execute this task in a new thread, create the thread from theRunnable and start it.

Runnable task = new HelloTask();Thread thread = new Thread(task);thread.start();

Now the run method executes in a separate thread, and the current threadcan proceed with other work.

NOTE: In Chapter 10, you will see other ways of executing a Runnable.

NOTE: There is also a Callable<T> interface for tasks that return a resultof type T.

3.3.4 User Interface Callbacks

In a graphical user interface, you have to specify actions to be carried outwhen the user clicks a button, selects a menu option, drags a slider, and soon. These actions are often called callbacks because some code gets calledback when a user action occurs.

Chapter 3 Interfaces and Lambda Expressions112

Page 42: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

In Java-based GUI libraries, interfaces are used for callbacks. For example, inJavaFX, the following interface is used for reporting events:

public interface EventHandler<T> { void handle(T event);}

This too is a generic interface where T is the type of event that is beingreported, such as an ActionEvent for a button click.

To specify the action, implement the interface:class CancelAction implements EventHandler<ActionEvent> { public void handle(ActionEvent event) { System.out.println("Oh noes!"); }}

Then, make an object of that class and add it to the button:Button cancelButton = new Button("Cancel");cancelButton.setOnAction(new CancelAction());

NOTE: Since Oracle positions JavaFX as the successor to the SwingGUI toolkit, I use JavaFX in these examples. (Don’t worry—you neednot know any more about JavaFX than the couple of statements youjust saw.) The details don’t matter; in every user interface toolkit, be itSwing, JavaFX, or Android, you give a button some code that you wantto run when the button is clicked.

Of course, this way of defining a button action is rather tedious. In otherlanguages, you just give the button a function to execute, without goingthrough the detour of making a class and instantiating it. The next sectionshows how you can do the same in Java.

3.4 Lambda Expressions

A lambda expression is a block of code that you can pass around so it can beexecuted later, once or multiple times. In the preceding sections, you haveseen many situations where it is useful to specify such a block of code:

• To pass a comparison method to Arrays.sort

• To run a task in a separate thread

• To specify an action that should happen when a button is clicked

1133.4 Lambda Expressions

Page 43: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

However, Java is an object-oriented language where (just about) everythingis an object. There are no function types in Java. Instead, functions are ex-pressed as objects, instances of classes that implement a particular interface.Lambda expressions give you a convenient syntax for creating such instances.

3.4.1 The Syntax of Lambda Expressions

Consider again the sorting example from Section 3.3.2, “The Comparator Interface”(page 111). We pass code that checks whether one string is shorter thananother. We compute

first.length() - second.length()

What are first and second? They are both strings. Java is a strongly typedlanguage, and we must specify that as well:

(String first, String second) -> first.length() - second.length()

You have just seen your first lambda expression. Such an expression is simplya block of code, together with the specification of any variables that must bepassed to the code.

Why the name? Many years ago, before there were any computers, the logicianAlonzo Church wanted to formalize what it means for a mathematical functionto be effectively computable. (Curiously, there are functions that are known toexist, but nobody knows how to compute their values.) He used the Greekletter lambda (λ) to mark parameters, somewhat like

λfirst. λsecond. first.length() - second.length()

NOTE: Why the letter λ? Did Church run out of letters of thealphabet? Actually, the venerable Principia Mathematica (seehttp://plato.stanford.edu/entries/principia-mathematica) used the ^ accentto denote function parameters, which inspired Church to use anuppercase lambda Λ. But in the end, he switched to the lowercaseversion. Ever since, an expression with parameter variables has beencalled a lambda expression.

If the body of a lambda expression carries out a computation that doesn’t fitin a single expression, write it exactly like you would have written a method:enclosed in {} and with explicit return statements. For example,

Chapter 3 Interfaces and Lambda Expressions114

Page 44: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

(String first, String second) -> { int difference = first.length() < second.length(); if (difference < 0) return -1; else if (difference > 0) return 1; else return 0;}

If a lambda expression has no parameters, supply empty parentheses, just aswith a parameterless method:

Runnable task = () -> { for (int i = 0; i < 1000; i++) doWork(); }

If the parameter types of a lambda expression can be inferred, you can omitthem. For example,

Comparator<String> comp = (first, second) -> first.length() - second.length(); // Same as (String first, String second)

Here, the compiler can deduce that first and second must be strings becausethe lambda expression is assigned to a string comparator. (We will have acloser look at this assignment in the next section.)

If a method has a single parameter with inferred type, you can even omit theparentheses:

EventHandler<ActionEvent> listener = event -> System.out.println("Oh noes!"); // Instead of (event) -> or (ActionEvent event) ->

You never specify the result type of a lambda expression. However, thecompiler infers it from the body and checks that it matches the expected type.For example, the expression

(String first, String second) -> first.length() - second.length()

can be used in a context where a result of type int is expected (or acompatible type such as Integer, long, or double).

3.4.2 Functional Interfaces

As you already saw, there are many interfaces in Java that express actions,such as Runnable or Comparator. Lambda expressions are compatible with theseinterfaces.

You can supply a lambda expression whenever an object of an interface witha single abstract method is expected. Such an interface is called a functionalinterface.

1153.4 Lambda Expressions

Page 45: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

To demonstrate the conversion to a functional interface, consider the Arrays.sortmethod. Its second parameter requires an instance of Comparator, an interfacewith a single method. Simply supply a lambda:

Arrays.sort(words, (first, second) -> first.length() - second.length());

Behind the scenes, the second parameter variable of the Arrays.sortmethod receives an object of some class that implements Comparator<String>.Invoking the compare method on that object executes the body of the lambdaexpression. The management of these objects and classes is completelyimplementation-dependent and highly optimized.

In most programming languages that support function literals, you can declarefunction types such as (String, String) -> int, declare variables of those types,put functions into those variables, and invoke them. In Java, there is only onething you can do with a lambda expression: put it in a variable whose typeis a functional interface, so that it is converted to an instance of that interface.

NOTE: You cannot assign a lambda expression to a variable of typeObject, the common supertype of all classes in Java (see Chapter 4).Object is a class, not a functional interface.

The Java API provides a large number of functional interfaces (seeSection 3.6.2, “Choosing a Functional Interface,” page 120). One of them is

public interface Predicate<T> { boolean test(T t); // Additional default and static methods}

The ArrayList class has a removeIf method whose parameter is a Predicate. It isspecifically designed for receiving a lambda expression. For example, thefollowing statement removes all null values from an array list:

list.removeIf(e -> e == null);

3.5 Method and Constructor References

Sometimes, there is already a method that carries out exactly the action thatyou’d like to pass on to some other code. There is special syntax for a methodreference that is even shorter than a lambda expression calling the method. Asimilar shortcut exists for constructors. You will see both in the followingsections.

Chapter 3 Interfaces and Lambda Expressions116

Page 46: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.5.1 Method References

Suppose you want to sort strings regardless of letter case. You could callArrays.sort(strings, (x, y) -> x.compareToIgnoreCase(y));

Instead, you can pass this method expression:Arrays.sort(strings, String::compareToIgnoreCase);

The expression String::compareToIgnoreCase is a method reference that is equivalentto the lambda expression (x, y) -> x.compareToIgnoreCase(y).

Here is another example. The Objects class defines a method isNull. The callObjects.isNull(x) simply returns the value of x == null. It seems hardly worthhaving a method for this case, but it was designed to be passed as a methodexpression. The call

list.removeIf(Objects::isNull);

removes all null values from a list.

As another example, suppose you want to print all elements of a list. TheArrayList class has a method forEach that applies a function to each element.You could call

list.forEach(x -> System.out.println(x));

It would be nicer, however, if you could just pass the println method to theforEach method. Here is how to do that:

list.forEach(System.out::println);

As you can see from these examples, the :: operator separates the methodname from the name of a class or object. There are three variations:

1. Class::instanceMethod

2. Class::staticMethod

3. object::instanceMethod

In the first case, the first parameter becomes the receiver of the method,and any other parameters are passed to the method. For example,String::compareToIgnoreCase is the same as (x, y) -> x.compareToIgnoreCase(y).

In the second case, all parameters are passed to the static method. The methodexpression Objects::isNull is equivalent to x -> Objects.isNull(x).

In the third case, the method is invoked on the given object, and theparameters are passed to the instance method. Therefore, System.out::println isequivalent to x -> System.out.println(x).

1173.5 Method and Constructor References

Page 47: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

NOTE: When there are multiple overloaded methods with the samename, the compiler will try to find from the context which one you mean.For example, there are multiple versions of the println method. Whenpassed to the forEach method of an ArrayList<String>, the println(String)method is picked.

You can capture the this parameter in a method reference. For example,this::equals is the same as x -> this.equals(x).

NOTE: In an inner class, you can capture the this reference of anenclosing class as EnclosingClass.this::method. You can also capturesuper—see Chapter 4.

3.5.2 Constructor References

Constructor references are just like method references, except that the nameof the method is new. For example, Employee::new is a reference to an Employeeconstructor. If the class has more than one constructor, then it depends onthe context which constructor is chosen.

Here is an example for using such a constructor reference. Suppose you havea list of strings

List<String> names = ...;

You want a list of employees, one for each name. As you will see inChapter 8, you can use streams to do this without a loop: Turn the list intoa stream, and then call the map method. It applies a function and collects allresults.

Stream<Employee> stream = names.stream().map(Employee::new);

Since names.stream() contains String objects, the compiler knows that Employee::newrefers to the constructor Employee(String).

You can form constructor references with array types. For example, int[]::newis a constructor reference with one parameter: the length of the array. It isequivalent to the lambda expression n -> new int[n].

Array constructor references are useful to overcome a limitation of Java: It isnot possible to construct an array of a generic type. (See Chapter 6 for details.)For that reason, methods such as Stream.toArray return an Object array, not anarray of the element type:

Object[] employees = stream.toArray();

Chapter 3 Interfaces and Lambda Expressions118

Page 48: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

But that is unsatisfactory. The user wants an array of employees, not objects.To solve this problem, another version of toArray accepts a constructorreference:

Employee[] buttons = stream.toArray(Employee[]::new);

The toArray method invokes this constructor to obtain an array of the correcttype. Then it fills and returns the array.

3.6 Processing Lambda Expressions

Up to now, you have seen how to produce lambda expressions and passthem to a method that expects a functional interface. In the following sections,you will see how to write your own methods that can consume lambdaexpressions.

3.6.1 Implementing Deferred Execution

The point of using lambdas is deferred execution. After all, if you wanted toexecute some code right now, you’d do that, without wrapping it inside alambda. There are many reasons for executing code later, such as:

• Running the code in a separate thread

• Running the code multiple times

• Running the code at the right point in an algorithm (for example, thecomparison operation in sorting)

• Running the code when something happens (a button was clicked, datahas arrived, and so on)

• Running the code only when necessary

Let’s look at a simple example. Suppose you want to repeat an action n times.The action and the count are passed to a repeat method:

repeat(10, () -> System.out.println("Hello, World!"));

To accept the lambda, we need to pick (or, in rare cases, provide) a functionalinterface. In this case, we can just use Runnable:

public static void repeat(int n, Runnable action) { for (int i = 0; i < n; i++) action.run(); }

Note that the body of the lambda expression is executed when action.run() iscalled.

1193.6 Processing Lambda Expressions

Page 49: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Now let’s make this example a bit more sophisticated. We want to tell theaction in which iteration it occurs. For that, we need to pick a functional in-terface that has a method with an int parameter and a void return. Instead ofrolling your own, I strongly recommend that you use one of the standardones described in the next section. The standard interface for processing intvalues is

public interface IntConsumer { void accept(int value);}

Here is the improved version of the repeat method:public static void repeat(int n, IntConsumer action) { for (int i = 0; i < n; i++) action.accept(i); }

And here is how you call it:repeat(10, i -> System.out.println("Countdown: " + (9 - i)));

3.6.2 Choosing a Functional Interface

In most functional programming languages, function types are structural. Tospecify a function that maps two strings to an integer, you use a type thatlooks something like Function2<String, String, Integer> or (String, String) -> int. InJava, you instead declare the intent of the function using a functional interfacesuch as Comparator<String>. In the theory of programming languages this is callednominal typing.

Of course, there are many situations where you want to accept “any function”without particular semantics. There are a number of generic function typesfor that purpose (see Table 3-1), and it’s a very good idea to use one of themwhen you can.

For example, suppose you write a method to process files that match acertain criterion. Should you use the descriptive java.io.FileFilter class or aPredicate<File>? I strongly recommend that you use the standard Predicate<File>.The only reason not to do so would be if you already have many usefulmethods producing FileFilter instances.

Chapter 3 Interfaces and Lambda Expressions120

Page 50: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Table 3-1 Common Functional Interfaces

Othermethods

DescriptionAbstractmethodname

Returntype

Parametertypes

FunctionalInterface

Runs an actionwithoutarguments orreturn value

runvoidnoneRunnable

Supplies a valueof type T

getTnoneSupplier<T>

andThenConsumes avalue of type T

acceptvoidTConsumer<T>

andThenConsumes valuesof types T and U

acceptvoidT, UBiConsumer<T, U>

compose,andThen,identity

A function withargument oftype T

applyRTFunction<T, R>

andThenA function witharguments oftypes T and U

applyRT, UBiFunction<T, U, R>

compose,andThen,identity

A unary operatoron the type T

applyTTUnaryOperator<T>

andThen,maxBy,minBy

A binary operatoron the type T

applyTT, TBinaryOperator<T>

and, or,negate,isEqual

A boolean-valuedfunction

testbooleanTPredicate<T>

and, or,negate

A boolean-valuedfunction with twoarguments

testbooleanT, UBiPredicate<T, U>

1213.6 Processing Lambda Expressions

Page 51: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

NOTE: Most of the standard functional interfaces have nonabstractmethods for producing or combining functions. For example,Predicate.isEqual(a) is the same as a::equals, but it also works if a is null.There are default methods and, or, negate for combining predicates. Forexample,

Predicate.isEqual(a).or(Predicate.isEqual(b))

is the same as

x -> a.equals(x) || b.equals(x)

Table 3-2 lists the 34 available specializations for primitive types int, long, anddouble. It is a good idea to use these specializations to reduce autoboxing. Forthat reason, I used an IntConsumer instead of a Consumer<Integer> in the exampleof the preceding section.

Table 3-2 Functional Interfaces for Primitive Typesp, q is int, long, double; P, Q is Int, Long, Double

Abstract method nameReturn typeParametertypes

Functional Interface

getAsBooleanbooleannoneBooleanSupplier

getAsPpnonePSupplier

acceptvoidpPConsumer

acceptvoidT, pObjPConsumer<T>

applyTpPFunction<T>

applyAsQqpPToQFunction

applyAsPpTToPFunction<T>

applyAsPpT, UToPBiFunction<T, U>

applyAsPppPUnaryOperator

applyAsPpp, pPBinaryOperator

testbooleanpPPredicate

Chapter 3 Interfaces and Lambda Expressions122

Page 52: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.6.3 Implementing Your Own Functional Interfaces

Ever so often, you will be in a situation where none of the standard functionalinterfaces work for you. Then you need to roll your own.

Suppose you want to fill an image with color patterns, where the user suppliesa function yielding the color for each pixel. There is no standard type for amapping (int, int) -> Color. You could use BiFunction<Integer, Integer, Color>, butthat involves autoboxing.

In this case, it makes sense to define a new interface@FunctionalInterfacepublic interface PixelFunction { Color apply(int x, int y);}

NOTE: It is a good idea to tag functional interfaces with the@FunctionalInterface annotation. This has two advantages. First, thecompiler checks that the annotated entity is an interface with a singleabstract method. Second, the javadoc page includes a statement thatyour interface is a functional interface.

Now you are ready to implement a method:BufferedImage createImage(int width, int height, PixelFunction f) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { Color color = f.apply(x, y); image.setRGB(x, y, color.getRGB()); } return image;}

To call it, supply a lambda expression that yields a color value for twointegers:

BufferedImage frenchFlag = createImage(150, 100, (x, y) -> x < 50 ? Color.BLUE : x < 100 ? Color.WHITE : Color.RED);

1233.6 Processing Lambda Expressions

Page 53: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.7 Lambda Expressions and Variable Scope

In the following sections, you will learn how variables work inside lambdaexpressions. This information is somewhat technical but essential for workingwith lambda expressions.

3.7.1 Scope of a Lambda Expression

The body of a lambda expression has the same scope as a nested block. Thesame rules for name conflicts and shadowing apply. It is illegal to declare aparameter or a local variable in the lambda that has the same name as a localvariable.

int first = 0;Comparator<String> comp = (first, second) -> first.length() - second.length(); // Error: Variable first already defined

Inside a method, you can’t have two local variables with the same name,therefore you can’t introduce such variables in a lambda expression either.

As another consequence of the “same scope” rule, the this keyword in alambda expression denotes the this parameter of the method that createsthe lambda. For example, consider

public class Application() { public void doWork() { Runnable runner = () -> { ...; System.out.println(this.toString()); ... }; ... }}

The expression this.toString() calls the toString method of the Application object,not the Runnable instance. There is nothing special about the use of this in alambda expression. The scope of the lambda expression is nested inside thedoWork method, and this has the same meaning anywhere in that method.

3.7.2 Accessing Variables from the Enclosing Scope

Often, you want to access variables from an enclosing method or class in alambda expression. Consider this example:

public static void repeatMessage(String text, int count) { Runnable r = () -> { for (int i = 0; i < count; i++) { System.out.println(text); } }; new Thread(r).start(); }

Chapter 3 Interfaces and Lambda Expressions124

Page 54: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Note that the lambda expression accesses the parameter variables defined inthe enclosing scope, not in the lambda expression itself.

Consider a callrepeatMessage("Hello", 1000); // Prints Hello 1000 times in a separate thread

Now look at the variables count and text inside the lambda expression. If youthink about it, something nonobvious is going on here. The code of thelambda expression may run long after the call to repeatMessage has returnedand the parameter variables are gone. How do the text and count variablesstay around when the lambda expression is ready to execute?

To understand what is happening, we need to refine our understanding of alambda expression. A lambda expression has three ingredients:

1. A block of code

2. Parameters

3. Values for the free variables—that is, the variables that are not parametersand not defined inside the code

In our example, the lambda expression has two free variables, text and count.The data structure representing the lambda expression must store the valuesfor these variables—in our case, "Hello" and 1000. We say that these valueshave been captured by the lambda expression. (It’s an implementation detailhow that is done. For example, one can translate a lambda expression intoan object with a single method, so that the values of the free variables arecopied into instance variables of that object.)

NOTE: The technical term for a block of code together with the valuesof free variables is a closure. In Java, lambda expressions are closures.

As you have seen, a lambda expression can capture the value of a variablein the enclosing scope. To ensure that the captured value is well defined,there is an important restriction. In a lambda expression, you can only refer-ence variables whose value doesn’t change. This is sometimes described bysaying that lambda expressions capture values, not variables. For example,the following is a compile-time error:

for (int i = 0; i < n; i++) { new Thread(() -> System.out.println(i)).start(); // Error—cannot capture i}

The lambda expression tries to capture i, but this is not legal because ichanges. There is no single value to capture. The rule is that a lambda

1253.7 Lambda Expressions and Variable Scope

Page 55: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

expression can only access local variables from an enclosing scope that areeffectively final. An effectively final variable is never modified—it either is orcould be declared as final.

NOTE: The same rule applies to variables captured by local classes (seeSection 3.9, “Local and Anonymous Classes,” page 129). In the past, therule was more draconian and required captured variables to actually bedeclared final. This is no longer the case.

NOTE: The variable of an enhanced for loop is effectively final since itsscope is a single iteration. The following is perfectly legal:

for (String arg : args) { new Thread(() -> System.out.println(arg)).start(); // OK to capture arg}

A new variable arg is created in each iteration and assigned the nextvalue from the args array. In contrast, the scope of the variable i in thepreceding example was the entire loop.

As a consequence of the “effectively final” rule, a lambda expression cannotmutate any captured variables. For example,

public static void repeatMessage(String text, int count, int threads) { Runnable r = () -> { while (count > 0) { count--; // Error: Can’t mutate captured variable System.out.println(text); } }; for (int i = 0; i < threads; i++) new Thread(r).start();}

This is actually a good thing. As you will see in Chapter 10, if two threadsupdate count at the same time, its value is undefined.

NOTE: Don’t count on the compiler to catch all concurrent access errors.The prohibition against mutation only holds for local variables. If countis an instance variable or static variable of an enclosing class, then noerror is reported even though the result is just as undefined.

Chapter 3 Interfaces and Lambda Expressions126

Page 56: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

CAUTION: One can circumvent the check for inappropriate mutationsby using an array of length 1:

int[] counter = new int[1];button.setOnAction(event -> counter[0]++);

The counter variable is effectively final—it is never changed since it alwaysrefers to the same array, so you can access it in the lambda expression.

Of course, code like this is not threadsafe. Except possibly for a callbackin a single-threaded UI, this is a terrible idea. You will see how toimplement a threadsafe shared counter in Chapter 10.

3.8 Higher-Order Functions

In a functional programming language, functions are first-class citizens. Justlike you can pass numbers to methods and have methods that producenumbers, you can have arguments and return values that are functions.Functions that process or return functions are called higher-order functions. Thissounds abstract, but it is very useful in practice. Java is not quite a functionallanguage because it uses functional interfaces, but the principle is the same.In the following sections, we will look at some examples and examine thehigher-order functions in the Comparator interface.

3.8.1 Methods that Return Functions

Suppose sometimes we want to sort an array of strings in ascending orderand other times in descending order. We can make a method that producesthe correct comparator:

public static Comparator<String> compareInDirecton(int direction) { return (x, y) -> direction * x.compareTo(y);}

The call compareInDirection(1) yields an ascending comparator, and the callcompareInDirection(-1) a descending comparator.

The result can be passed to another method (such as Arrays.sort) that expectssuch an interface.

Arrays.sort(friends, compareInDirection(-1));

In general, don’t be shy to write methods that produce functions (or, techni-cally, instances of classes that implement a functional interface). This is usefulto generate custom functions that you pass to methods with functionalinterfaces.

1273.8 Higher-Order Functions

Page 57: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

3.8.2 Methods That Modify Functions

In the preceding section, you saw a method that yields an increasing or de-creasing string comparator. We can generalize this idea by reversing anycomparator:

public static Comparator<String> reverse(Comparator<String> comp) { return (x, y) -> comp.compare(y, x);}

This method operates on functions. It receives a function and returns amodified function. To get case-insensitive descending order, use

reverse(String::compareToIgnoreCase)

NOTE: The Comparator interface has a default method reversed thatproduces the reverse of a given comparator in just this way.

3.8.3 Comparator Methods

The Comparator interface has a number of useful static methods that arehigher-order functions generating comparators.

The comparing method takes a “key extractor” function that maps a type T to acomparable type (such as String). The function is applied to the objects tobe compared, and the comparison is then made on the returned keys. Forexample, suppose a Person class has a method getLastName. Then you can sortan array of Person objects by last name like this:

Arrays.sort(people, Comparator.comparing(Person::getLastName));

You can chain comparators with the thenComparing method to break ties. Forexample, sort an array of people by last name, then use the first namefor people with the same last name:

Arrays.sort(people, Comparator .comparing(Person::getLastName) .thenComparing(Person::getFirstName));

There are a few variations of these methods. You can specify a comparatorto be used for the keys that the comparing and thenComparing methods extract. Forexample, here we sort people by the length of their names:

Arrays.sort(people, Comparator.comparing(Person::getLastName, (s, t) -> s.length() - t.length()));

Moreover, both the comparing and thenComparing methods have variants that avoidboxing of int, long, or double values. An easier way of sorting by name lengthwould be

Chapter 3 Interfaces and Lambda Expressions128

Page 58: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Arrays.sort(people, Comparator.comparingInt(p -> p.getLastName().length()));

If your key function can return null, you will like the nullsFirst and nullsLastadapters. These static methods take an existing comparator and modify it sothat it doesn’t throw an exception when encountering null values but ranksthem as smaller or larger than regular values. For example, suppose getMiddleNamereturns a null when a person has no middle name. Then you can useComparator.comparing(Person::getMiddleName(), Comparator.nullsFirst(...)).

The nullsFirst method needs a comparator—in this case, one that comparestwo strings. The naturalOrder method makes a comparator for any class imple-menting Comparable. Here is the complete call for sorting by potentially nullmiddle names. I use a static import of java.util.Comparator.* to make theexpression more legible. Note that the type for naturalOrder is inferred.

Arrays.sort(people, comparing(Person::getMiddleName, nullsFirst(naturalOrder())));

The static reverseOrder method gives the reverse of the natural order.

3.9 Local and Anonymous Classes

Long before there were lambda expressions, Java had a mechanism for con-cisely defining classes that implement an interface (functional or not). Forfunctional interfaces, you should definitely use lambda expressions, but oncein a while, you may want a concise form for an interface that isn’t functional.You will also encounter the classic constructs in legacy code.

3.9.1 Local Classes

You can define a class inside a method. Such a class is called a local class.You would do this for classes that are just tactical. This occurs often whena class implements an interface and the caller of the method only cares aboutthe interface, not the class.

For example, consider a methodpublic static IntSequence randomInts(int low, int high)

that generates an infinite sequence of random integers with the given bounds.

Since IntSequence is an interface, the method must return an object of someclass implementing that interface. The caller doesn’t care about the class, soit can be declared inside the method:

1293.9 Local and Anonymous Classes

Page 59: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

private static Random generator = new Random();

public static IntSequence randomInts(int low, int high) { class RandomSequence implements IntSequence { public int next() { return low + generator.nextInt(high - low + 1); } public boolean hasNext() { return true; } }

return new RandomSequence();}

NOTE: A local class is not declared as public or private since it is neveraccessible outside the method.

There are two advantages of making a class local. First, its name is hiddenin the scope of the method. Second, the methods of the class can accessvariables from the enclosing scope, just like the variables of a lambdaexpression.

In our example, the next method captures three variables: low, high, and generator.If you turned RandomInt into a nested class, you would have to provide an ex-plicit constructor that receives these values and stores them in instancevariables (see Exercise 16).

3.9.2 Anonymous Classes

In the example of the preceding section, the name RandomSequence was usedexactly once: to construct the return value. In this case, you can make theclass anonymous:

public static IntSequence randomInts(int low, int high) { return new IntSequence() { public int next() { return low + generator.nextInt(high - low + 1); } public boolean hasNext() { return true; } }}

The expressionnew Interface() { methods }

means: Define a class implementing the interface that has the given methods,and construct one object of that class.

NOTE: As always, the () in the new expression indicate the constructionarguments. A default constructor of the anonymous class is invoked.

Chapter 3 Interfaces and Lambda Expressions130

Page 60: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Before Java had lambda expressions, anonymous inner classes were the mostconcise syntax available for providing runnables, comparators, and otherfunctional objects. You will often see them in legacy code.

Nowadays, they are only necessary when you need to provide two or moremethods, as in the preceding example. If the IntSequence interface has a defaulthasNext method, as in Exercise 16, you can simply use a lambda expression:

public static IntSequence randomInts(int low, int high) { return () -> low + generator.nextInt(high - low + 1); }

Exercises

1. Provide an interface Measurable with a method double getMeasure() that mea-sures an object in some way. Make Employee implement Measurable. Providea method double average(Measurable[] objects) that computes the averagemeasure. Use it to compute the average salary of an array of employees.

2. Continue with the preceding exercise and provide a method Measurablelargest(Measurable[] objects). Use it to find the name of the employee withthe largest salary. Why do you need a cast?

3. What are all the supertypes of String? Of Scanner? Of ImageOutputStream? Notethat each type is its own supertype. A class or interface without declaredsupertype has supertype Object.

4. Implement a static of method of the IntSequence class that yields a sequencewith the arguments. For example, IntSequence.of(3, 1, 4, 1, 5, 9) yields asequence with six values. Extra credit if you return an instance of ananonymous inner class.

5. Add a static method with the name constant of the IntSequence class thatyields an infinite constant sequence. For example, IntSequence.constant(1)yields values 1 1 1..., ad infinitum. Extra credit if you do this with alambda expression.

6. The SquareSequence class doesn’t actually deliver an infinite sequence ofsquares due to integer overflow. Specifically, how does it behave? Fix theproblem by defining a Sequence<T> interface and a SquareSequence class thatimplements Sequence<BigInteger>.

7. In this exercise, you will try out what happens when a method is addedto an interface. In Java 7, implement a class DigitSequence that implementsIterator<Integer>, not IntSequence. Provide methods hasNext, next, and a do-nothing remove. Write a program that prints the elements of an instance.

131Exercises

Page 61: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

In Java 8, the Iterator class gained another method, forEachRemaining. Doesyour code still compile when you switch to Java 8? If you put your Java 7class in a JAR file and don’t recompile, does it work in Java 8? What ifyou call the forEachRemaining method? Also, the remove method has becomea default method in Java 8, throwing an UnsupportedOperationException. Whathappens when remove is called on an instance of your class?

8. Implement the method void luckySort(ArrayList<String> strings, Comparator<String>comp) that keeps calling Collections.shuffle on the array list until the elementsare in increasing order, as determined by the comparator.

9. Implement a class Greeter that implements Runnable and whose run methodprints n copies of "Hello, " + target, where n and target are set in the con-structor. Construct two instances with different messages and executethem concurrently in two threads.

10. Implement methodspublic static void runTogether(Runnable... tasks)public static void runInOrder(Runnable... tasks)

The first method should run each task in a separate thread and then re-turn. The second method should run all methods in the current threadand return when the last one has completed.

11. Using the listFiles(FileFilter) and isDirectory methods of the java.io.Fileclass, write a method that returns all subdirectories of a given directory.Use a lambda expression instead of a FileFilter object. Repeat with amethod expression and an anonymous inner class.

12. Using the list(FilenameFilter) method of the java.io.File class, write a methodthat returns all files in a given directory with a given extension. Use alambda expression, not a FilenameFilter. Which variable from the enclosingscope does it capture?

13. Given an array of File objects, sort it so that directories come before files,and within each group, elements are sorted by path name. Use a lambdaexpression to specify the Comparator.

14. Write a method that takes an array of Runnable instances and returns aRunnable whose run method executes them in order. Return a lambdaexpression.

15. Write a call to Arrays.sort that sorts employees by salary, breaking ties byname. Use Comparator.thenComparing. Then do this in reverse order.

16. Implement the RandomSequence in Section 3.9.1, “Local Classes” (page 129) asa nested class, outside the randomInts method.

Chapter 3 Interfaces and Lambda Expressions132

Page 62: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Symbols and Numbers- (minus sign)

flag (for output), 35in dates, 414in regular expressions, 310operator, 17–18

--in command-line options, 81in shell scripts, 463operator, 17, 19

->, in lambda expressions, 114, 117-∞, in string templates, 434_ (underscore)

in number literals, 12in variable names, 14, 67

, (comma)flag (for output), 35in numbers, 422, 428, 433normalizing, 317trailing, in arrays, 44

; (semicolon)in Java vs. JavaScript, 450path separator (Windows), 81,

248

: (colon)in assertions, 194in dates, 414in switch statement, 37path separator (Unix), 81, 248

:: operator, 117, 145! (exclamation sign)

comments, in property files, 247operator, 17, 22

!= operator, 17, 22for wrapper classes, 47

? (quotation mark)in regular expressions, 310–311, 313replacement character, 295, 438wildcard, for types, 212–216, 227

? : operator, 17, 22/ (slash)

file separator (Unix), 248, 298in javac path segments, 5operator, 17–18root component, 298

//, /*...*/ comments, 3/**...*/ comments, 90–91/= operator, 17

497

Index

Page 63: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

. (period)in method calls, 6in numbers, 422, 428, 433in package names, 5, 79in regular expressions, 310–311, 319operator, 17

.., parent directory, 299

... (ellipsis), for varargs, 54`...` (back quotes), in shell scripts, 462^ (caret)

for function parameters, 114in regular expressions, 310–313, 318operator, 17, 23

^= operator, 17~ (tilde), operator, 17, 23'...' (single quotes)

for character literals, 13–14in JavaScript, 450in string templates, 434

"..." (double quotes)for strings, 6in javadoc hyperlinks, 94in shell scripts, 462

"" (empty string), 26–27, 147( (left parenthesis), in formatted output,

35(...) (parentheses)

empty, for anonymous classes, 130for anonymous functions (JavaScript),

458for casts, 21, 103in regular expressions, 310–313,

316–317operator, 17

[...] (square brackets)for arrays, 43–44, 50in JavaScript, 454, 457–458in regular expressions, 310–312operator, 17

{...} (curly braces)in annotation elements, 379in lambda expressions, 114in regular expressions, 310–313, 318in string templates, 433with arrays, 44

{{...}}, double brace initialization, 144

@ (at)in java command, 487in javadoc comments, 91

$ (dollar sign)currency symbol, 433flag (for output), 36in JavaScript function calls, 455, 460in regular expressions, 310–311, 313,

318in variable names, 14

${...}, in shell scripts, 462–463€ currency symbol, 428, 433* (asterisk)

for annotation processors, 394in documentation comments, 92in regular expressions, 310–313, 317operator, 17–18wildcard:

in class path, 81in imported classes, 83–84

*= operator, 17\ (backslash)

character literal, 14file separator (Windows), 248, 298in option files, 487in regular expressions, 310–311, 318

& (ampersand), operator, 17, 23&& (double ampersand)

in regular expressions, 312operator, 17, 22

&= operator, 17# (number sign)

comments, in property files, 247flag (for output), 35in javadoc hyperlinks, 93in option files, 487in string templates, 434

#!, in shell scripts, 464% (percent sign)

conversion character, 34–35operator, 17–18

%% pattern variable, 202%= operator, 17+ (plus sign)

flag (for output), 35in regular expressions, 310–313

Index498

Page 64: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

operator, 17–18for strings, 24–25, 27, 147

++ operator, 17, 19+= operator, 17< (left angle bracket)

flag (for output), 36in shell syntax, 33in string templates, 434operator, 22, 456

<< operator, 17, 23<<= operator, 17<= operator, 17, 22<%...%>, <%=...%> delimiters (JSP), 464≤, in string templates, 434<> (diamond syntax)

for array lists, 45for constructors of generic classes, 209

<...> (angle brackets)for type parameters, 109, 208in javadoc hyperlinks, 93in regular expressions, 313

=, -= operators, 17–18== operator, 17, 22, 149

for class objects, 160for enumerations, 155for strings, 26for wrapper classes, 47

=>, in JavaScript, 459> (right angle bracket)

in shell syntax, 33operator, 22

>=, >>, >>> operators, 17, 22–23>>=, >>>= operators, 17| (vertical bar)

in regular expressions, 310–312in string templates, 434operator, 17, 23

|= operator, 17|| operator, 17, 220 (zero)

as default value, 71, 74flag (for output), 35formatting symbol (date/time), 416prefix, for octal literals, 11

\0, in regular expressions, 3110b prefix, 11

0x prefix, 11, 350xFEFF byte order mark, 291

Aa formatting symbol (date/time), 416a, A conversion characters, 34\a, \A, in regular expressions, 311, 314abstract classes, 141–142abstract methods, of an interface, 115abstract modifier, 103, 141–142AbstractCollection class, 106AbstractMethodError, 107AbstractProcessor class, 394accept methods (Consumer, XxxConsumer),

121–122acceptEither method (CompletableFuture),

339–340AccessibleObject class, 172

setAccessible method, 170, 172trySetAccessible method, 170

accessors, 62accumulate method (LongAccumulator), 356accumulateAndGet method (AtomicXxx), 355accumulator functions, 278add method

of ArrayDeque, 250of ArrayList, 46, 62of BlockingQueue, 353of Collection, 236of List, 238of ListIterator, 241of LongAdder, 356

addAll methodof Collection, 214, 236of Collections, 239of List, 238

addExact method (Math), 20addHandler method (Logger), 200addition, 18

identity for, 278addSuppressed method (IOException), 189aggregators, 488allMatch method (Stream), 267allOf method

of CompletableFuture, 339–340of EnumSet, 250

499Index

Page 65: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

allProcesses method (ProcessHandle), 370and, andNot methods (BitSet), 249and, andThen methods (functional

interfaces), 121Android, 341AnnotatedConstruct interface, 395AnnotatedElement interface, 392–393annotation interfaces, 383–386annotation processors, 394annotations

accessing, 384from a different module, 489

and modifiers, 382container, 389, 392declaration, 380–381documented, 389generating source code with, 395–398inherited, 389, 392key/value pairs in. See elementsmeta, 384–390multiple, 380processing:

at runtime, 391–393source-level, 394–398

repeatable, 380, 389, 392standard, 386–390type use, 381–382

anonymous classes, 130–131anyMatch method (Stream), 267anyOf method (CompletableFuture), 339–340Apache Commons CSV, 484API documentation, 28–30

generating, 90Applet class, 163applications. See programsapply, applyAsXxx methods (functional

interfaces), 121–122applyToEither method (CompletableFuture),

339–340$ARG, in shell scripts, 463arguments array (jjs), 463arithmetic operations, 17–24Array class, 174–175array list variables, 45array lists, 45–46

anonymous, 144

checking for nulls, 215constructing, 45–46converting between, 212copying, 48filling, 49instantiating with type variables, 222size of, 46sorting, 49visiting all elements of, 47working with elements of, 46–47

array variablesassigning values to, 45copying, 47declaring, 43–44initializing, 43

ArrayBlockingQueue class, 353ArrayDeque class, 250ArrayIndexOutOfBoundsException, 43ArrayList class, 45–46, 237

add method, 46, 62clone method, 154forEach method, 117get, remove, set, size methods, 46removeIf method, 116

arrays, 43–45accessing nonexisting elements in,

43allocating, 222annotating, 381casting, 174checking, 174comparing, 149computing values of, 349constructing, 43–44constructor references with, 118converting:

to a reference of type Object, 146to/from streams, 271, 281, 350

copying, 48covariant, 212filling, 44, 49generating Class objects for, 160growing, 174–175hash codes of, 151in JavaScript, 457–458length of, 43, 45, 127

Index500

Page 66: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

multidimensional, 50–52, 147of bytes, 288–289of generic types, 118, 223of objects, 44, 349of primitive types, 349of strings, 317passing into methods, 53printing, 49, 52, 147serializable, 319sorting, 49, 109–111, 349–350superclass assignment in, 140using class literals with, 160

Arrays classasList method, 253copyOf method, 48deepToString method, 147equals method, 149fill method, 49hashCode method, 151parallelXxx methods, 49, 349sort method, 49, 111–112, 116–117stream method, 262, 279toString method, 49, 147

ArrayStoreException, 140, 212, 223ASCII, 30, 290

for property files, 437for source files, 438

ASM tool, 398assert statement, 194AssertionError, 194assertions, 193–195

checking, 381enabling/disabling, 194–195

assignment operators, 18associative operations, 278asString method (HttpResponse), 308asSubclass method (Class), 227asynchronous computations, 335–341AsyncTask class (Android), 341atomic operations, 346, 351, 354–357,

360and performance, 355

AtomicXxx classes, 355atZone method (LocalDateTime), 410@author tag (javadoc), 91, 95autoboxing, 46, 123

AutoCloseable interface, 187, 210close method, 188

availableCharsets method (Charset), 292availableProcessors method (Runtime),

331average method (XxxStream), 280

Bb, B conversion characters, 35\b (backspace), 14\b, \B, in regular expressions, 314bash scripts (Unix), 461BasicFileAttributes class, 303batch files (Windows), 461BeanInfo class, 173between method (Duration), 403BiConsumer interface, 121BiFunction interface, 121, 123BigDecimal class, 13, 23–24big-endian format, 291, 296–297BigInteger class, 11, 23–24binary data, reading/writing, 296binary numbers, 11, 13binary trees, 242BinaryOperator interface, 121binarySearch method (Collections), 240Bindings interface, 449BiPredicate interface, 121BitSet class, 248–249

collecting streams into, 279methods of, 249

bitwise operators, 23block statement, labeled, 41blocking queues, 352–353BlockingQueue interface, 353Boolean class, 46boolean type, 14

default value of, 71, 74formatting for output, 35reading/writing, 296streams of, 279

BooleanSupplier interface, 122bootstrap class loader, 163boxed method (XxxStream), 280branches, 36–38break statement, 37, 39–41

501Index

Page 67: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

bridge methods, 218–219clashes of, 225

BufferedReader class, 294build method (HttpClient), 308bulk operations, 352Byte class, 46

MIN_VALUE, MAX_VALUE constants, 11toUnsignedInt method, 12

byte codes, 4writing to memory, 446–447

byte order mark, 291byte type, 10–12, 289

streams of, 279type conversions of, 21

ByteArrayClass class, 446ByteArrayClassLoader class, 447ByteArrayXxxStream classes, 288–289ByteBuffer class, 297bytes

arrays of, 288–289converting to strings, 292reading, 289writing, 290

Cc, C conversion characters, 34C:\ root component, 298C/C++ programming languages

#include directive in, 84allocating memory in, 346integer types in, 11pointers in, 63

C# programming language, typeparameters in, 215

\c, in regular expressions, 311CachedRowSetImpl class, 486calculators, 157Calendar class, 401

getFirstDayOfWeek method, 431weekends in, 407

calendars, 60call method (CompilationTask), 445call by reference, 69Callable interface, 112

call method, 333extending, 445

callbacks, 112–113, 337registering, 335

camel case, 15cancel method

of CompletableFuture, 337of Future, 333

cancellation requests, 364CancellationException, 337cardinality method (BitSet), 249carriage return, character literal for,

14case label, 37cast method (Class), 227casts, 21, 103–104, 140

and generic types, 220annotating, 382inserting, 217–218

catch statement, 186–187annotating parameters of, 380in JavaScript, 461in try-with-resources, 189no type variables in, 225

ceiling method (NavigableSet), 243Channel interface, 104channels, 297char type, 13–14

streams of, 279type conversions of, 21

Character class, 46character classes, 310character encodings, 290–293

detecting, 292localizing, 438partial, 292, 295platform, 292, 438

character literals, 13–14characters, 288

combined, 432formatting for output, 34normalized, 432–433reading/writing, 296

charAt method (String), 31CharSequence interface, 28

chars, codePoints methods, 279splitting by regular expressions,

263

Index502

Page 68: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Charset classavailableCharsets method, 292defaultCharset method, 292, 438displayName method, 438forName method, 292

checked exceptions, 183–186and generic types, 226and no-argument constructors, 171combining in a superclass, 185declaring, 185–186documenting, 186in lambda expressions, 186not allowed in a method, 191rethrowing, 190

checked views, 221, 254checkedXxx methods (Collections), 240, 254Checker Framework, 381childrenNames method (Preferences), 440choice indicator, in string templates, 434Church, Alonzo, 114, 404Class class, 159–162, 228

asSubclass, cast methods, 227comparing objects of, 160forName method, 160–161, 164–165,

184, 192, 447generic, 227getCanonicalName method, 160–161getClassLoader method, 161getComponentType method, 161, 174getConstructor(s) methods, 162, 168,

171, 227getDeclaredConstructor(s) methods, 162,

168, 227getDeclaredField(s) methods, 162getDeclaredMethod(s) methods, 162, 171getDeclaringClass method, 161getEnclosingXxx methods, 161getEnumConstants method, 227getField(s) methods, 162, 168getInterfaces method, 161getMethod(s) methods, 162, 168, 171getModifiers method, 161getName method, 159–161getPackage, getPackageName methods, 161getResource method, 163, 435getResourceAsStream method, 161–162

getSimpleName method, 161getSuperclass method, 161, 227getTypeName method, 161getTypeParameters method, 228isXxx methods, 161, 174newInstance method, 171, 227toString, toGenericString methods, 161

class declarationsannotations in, 380, 389initialization blocks in, 72–73

class files, 4, 163paths of, 79processing annotations in, 398

class literals, 160no annotations for, 382no type variables in, 221

class loaders, 163–164class objects, 160class path, 80–81

problems with, 471.class suffix, 160ClassCastException, 104, 221classes, 2, 60

abstract, 103, 108, 141–142accessing from a different module, 489adding functionality to, 77adding to packages, 83anonymous, 130–131companion, 106compiling on the fly, 446constructing objects of, 14deprecated, 93documentation comments for, 90–92encapsulation of, 469–470enumerating members of, 158,

168–169evolving, 324extending, 136–145

in JavaScript, 459–460fields of, 135final, 141generic, 45immutable, 28, 347implementing, 65–69, 153importing, 83–84inner, 87–89

503Index

Page 69: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

classes (cont.)instances of, 6, 65, 78loading, 169local, 129–130members of, 135naming, 14–15, 78, 159nested, 85–90, 382not known at compile time, 160, 175protected, 142–143public, 83, 476static initialization of, 164system, 195testing, 83utility, 83, 165wrapper, 46–47

classes win rule, 151classifier functions, 274ClassLoader class

defineClass method, 486extending, 447findClass, loadClass methods, 164setXxxAssertionStatus methods, 195

classloader inversion, 165ClassNotFoundException, 184CLASSPATH environment variable, 82clear method

of BitSet, 249of Collection, 236of Map, 246

clone methodof ArrayList, 154of Enum, 156of Message, 153–154of Object, 143, 146, 151–154, 171protected, 152

Cloneable interface, 153CloneNotSupportedException, 153–154,

156cloning, 151–154close method

of AutoCloseable, 188of PrintWriter, 187–188throwing exceptions, 188

Closeable interface, 104close method, 188

closures, 125

code element (HTML), in documentationcomments, 91

code generator tools, 388code points, 31, 290

turning a string into, 263code units, 13, 31, 279

in regular expressions, 311codePoints method (CharSequence), 279codePoints, codePointXxx methods (String),

31–32Collator class, 27

methods of, 432collect method (Stream), 271–272, 279Collection interface, 106, 236

add method, 236addAll method, 214, 236clear method, 236contains, containsAll, isEmpty methods,

237iterator, spliterator methods, 237parallelStream method, 237, 260–261,

280, 348remove, removeXxx, retainAll methods, 236size method, 237stream method, 237, 260–261toArray method, 237

collections, 235–254generic, 254iterating over elements of, 260–261mutable, 253processing, 239serializable, 319threadsafe, 354unmodifiable views of, 253–254vs. streams, 261with given elements, 252

Collections class, 106, 239addAll method, 239binarySearch method, 240copy method, 239disjoint method, 239fill method, 49, 239frequency method, 239indexOfSubList, lastIndexOfSubList

methods, 240nCopies method, 237, 239

Index504

Page 70: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

replaceAll method, 239reverse, shuffle methods, 49, 240rotate, swap methods, 240sort method, 49, 215, 240synchronizedXxx, unmodifiableXxx methods,

240Collector interface, 272Collectors class, 85

counting method, 275filtering method, 277flatMapping method, 276groupingBy method, 274–277groupingByConcurrent method, 275, 282joining method, 272mapping method, 276maxBy, minBy methods, 276partitioningBy method, 275, 277reducing method, 277summarizingXxx methods, 272, 276summingXxx methods, 276toCollection, toList methods, 272toConcurrentMap method, 274toMap method, 273–274toSet method, 272, 275

com global object (JavaScript), 454command-line arguments, 49–50comments, 3

documentation, 90–95commonPool method (ForkJoinPool), 335companion classes, 106Comparable interface, 109–111, 155, 215,

242compareTo method, 109streams of, 265with priority queues, 251

Comparator interface, 85, 111–112,127–129, 242

comparing, comparingXxx methods, 128–129naturalOrder method, 129nullsFirst, nullsLast methods, 129reversed method, 128reverseOrder method, 129streams of, 265thenComparing method, 128–129with priority queues, 251

compare method (Integer, Double), 110

compareTo methodof Enum, 156of Instant, 403of String, 26–27, 109, 431

compareToIgnoreCase method (String), 117compareUnsigned method (Integer, Long), 20compatibility, drawbacks of, 216Compilable interface, 452compilation, 4CompilationTask interface, 444

call method, 445compile method (Pattern), 315, 318compiler

instruction reordering in, 343invoking, 444

compile-time errors, 15completable futures, 335–340

combining, 340composing, 337–340interrupting, 337

CompletableFuture class, 335–340acceptEither, applyToEither methods,

339–340allOf, anyOf methods, 339–340cancel method, 337complete, completeExceptionally methods,

336exceptionally method, 338–339handle method, 339isDone method, 336runAfterXxx methods, 339–340supplyAsync method, 335–337thenAccept method, 335, 339thenAcceptBoth, thenCombine methods,

339–340thenApply, thenApplyAsync, thenCompose

methods, 337–339thenRun method, 339whenComplete method, 336, 338–339

CompletionStage interface, 339compose method (functional interfaces),

121computations

asynchronous, 335–341mutator, 62reproducible floating-point, 20

505Index

Page 71: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

computations (cont.)with arbitrary precision, 13

compute, computeIfXxx methods (Map), 245concat method (Stream), 265concatenation, 24–25

objects with strings, 147concurrent access errors, 126concurrent programming, 329–369

for scripts, 449strategies for, 346

ConcurrentHashMap class, 350–352, 362compute method, 350–352computeIfXxx, forEachXxx, merge, putIfAbsent,

reduceXxx, searchXxx methods, 351keySet, newKeySet methods, 354no null values in, 244

ConcurrentModificationException, 241, 350ConcurrentSkipListXxx classes, 354conditional operator, 22configuration files, 439–441

editing, 199–200locating, 162resolving paths for, 299

confinement, 346connect method (URLConnection), 306Console class, 33console, displaying fonts on, 438ConsoleHandler class, 200, 203constants, 15–16, 105

naming, 15static, 75–76using in another class, 16

Constructor interface, 168–169getModifiers, getName methods, 168newInstance method, 171–172

constructor references, 118–119annotating, 382

constructors, 69–74annotating, 224, 380–381documentation comments for, 90executing, 70for subclasses, 139implementing, 69–70in abstract classes, 142invoking another constructor from, 71no-argument, 73, 139, 171

overloading, 70–71public, 70, 168references in, 348

Consumer interface, 121contains method (String), 28contains, containsAll methods (Collection),

237containsXxx methods (Map), 246Content-Type header, 292context class loaders, 164–166continue statement, 40–41control flow, 36–43conversion characters, 34–35cooperative cancellation, 364copy method

of Collections, 239of Files, 290, 301–302, 305

copyOf method (Arrays), 48CopyOnWriteArrayXxx classes, 354CORBA (Common Object Request

Broker Architecture), 470count method (Stream), 261, 266counters

atomic, 354–357de/incrementing, 189

counting method (Collectors), 275country codes, 275, 424covariance, 211createBindings method (ScriptEngine), 449createInstance method (Util), 165createTempXxx methods (Files), 301createXxx methods (Files), 300critical sections, 346, 357, 363Crockford, Douglas, 451currencies, 428–429

formatting, 433Currency class, 428current method (ProcessHandle), 370

Dd

conversion character, 34formatting symbol (date/time), 416

D suffix, 12\d, \D, in regular expressions, 312daemon threads, 366

Index506

Page 72: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

databases, 377annotating access to, 388persisting objects in, 479

DataInput/Output interfaces, 295–296read/writeXxx methods, 296–297, 322

DataXxxStream classes, 296Date class, 401, 416–417DateFormat class, 429dates

computing, 407–408formatting, 413–416, 422, 429–431,

433local, 404–407nonexistent, 407, 412, 430parsing, 415

datesUntil method (LocalDate), 406–407DateTimeFormat class, 429–431DateTimeFormatter class, 413–416

and legacy classes, 417format method, 413, 430ofLocalizedXxx methods, 413, 430ofPattern method, 415parse method, 415toFormat method, 415withLocale method, 413, 430

DateTimeParseException, 430daylight savings time, 410–413DayOfWeek enumeration, 61, 406–407,

411getDisplayName method, 415, 430

dayOfWeekInMonth method(TemporalAdjusters), 408

deadlocks, 346, 358, 362–363debugging

messages for, 183overriding methods for, 141primary arrays for, 49streams, 266threads, 366using anonymous subclasses for,

143–144with assertions, 194

DecimalFormat class, 78number format patterns of, 433

declaration-site variance, 215decomposition (for classes), 52–54

decomposition modes (for characters),432

decrement operator, 19decrementExact method (Math), 20deep copies, 153deepToString method (Arrays), 147default label (in switch), 37, 159default methods, 106–108

conflicts of, 107–108, 144–145in interfaces, 151

default modifier, 106, 385defaultCharset method (Charset), 292, 438defaultXxxObject methods (ObjectXxxStream),

322defensive programming, 193deferred execution, 119–120defineClass method (ClassLoader), 486delete, deleteIfExists methods (Files), 301delimiters, for scanners, 294@Deprecated annotation, 93, 386–387@deprecated tag (javadoc), 93, 387Deque interface, 238, 250destroy, destroyForcibly methods

of Process, 369of ProcessHandle, 370

DiagnosticCollector class, 447DiagnosticListener interface, 447diamond syntax (<>)

for array lists, 45for constructors of generic classes, 209

directories, 298checking for existence, 300, 302creating, 300–302deleting, 301, 304–305moving, 301temporary, 301user, 299visiting, 302–305working, 367

directory method (ProcessBuilder), 367disjoint method (Collections), 239displayName method (Charset), 438distinct method (Stream), 265, 282dividedBy method (Duration), 404divideUnsigned method (Integer, Long), 20division, 18

507Index

Page 73: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

do statement, 38doc-files directory, 91documentation comments, 90–95@Documented annotation, 387, 389domain names

for modules, 472for packages, 79

dot notation, 6, 16double brace initialization, 144Double class, 46

compare method, 110equals method, 149isFinite, isInfinite methods, 13NaN, NEGATIVE_INFINITY, POSITIVE_INFINITY

values, 13parseDouble method, 27toString method, 27

double type, 12–13atomic operations on, 357functional interfaces for, 122streams of, 279type conversions of, 20–22

DoubleAccumulator, DoubleAdder classes,357

DoubleConsumer, DoubleXxxOperator,DoublePredicate, DoubleSupplier,DoubleToXxxFunction interfaces, 122

DoubleFunction interface, 122, 220doubles method (Random), 280DoubleStream class, 279–280DoubleSummaryStatistics class, 272, 280doubleValue method (Number), 428downstream collectors, 275–277, 282Driver.parentLogger method, 488dropWhile method (Stream), 265Duration class

between method, 403dividedBy, isZero, isNegative, minus,

minusXxx, multipliedBy, negated, plus,plusXxx methods, 404

immutability of, 347, 404ofXxx methods, 403, 405, 413toXxx methods, 403

dynamic method lookup, 139–140,218–219

dynamically typed languages, 456

EE constant (Math), 20e, E

conversion characters, 34formatting symbols (date/time), 416

\e, \E, in regular expressions, 311Eclipse, 5ECMAScript standard, 452, 459edu global object (JavaScript), 454effectively final variables, 126efficiency, and final modifier, 141Element interface, 395element method (BlockingQueue), 353elements (in annotations), 378–379, 385else statement, 36em element (HTML), in documentation

comments, 91Emacs text editor, 453empty method

of Optional, 269of Stream, 262

empty string, 26, 147concatenating, 27

encapsulation, 60, 469–471, 479encodings. See character encodingsend method (Matcher, MatchResult), 315–316<<END, in shell scripts, 463endsWith method (String), 28engine scope, 449enhanced for loop, 47, 52, 126

for collections, 241for enumerations, 155for iterators, 167for paths, 300

entering, exiting methods (Logger), 197Entry class, 217entrySet method (Map), 246Enum class, 155–156enum instances

adding methods to, 157construction, 156referred by name, 159

enum keyword, 16, 154enumeration sets, 250enumerations, 154–159

annotating, 380

Index508

Page 74: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

comparing, 155constructing, 156defining, 16nested inside classes, 158serialization of, 323static members of, 157–158traversing instances of, 155using in switch, 158

EnumMap, EnumSet classes, 250$ENV, in shell scripts, 463environment variables, modifying, 368epoch, definition of, 402equality, testing for, 22equals method

final, 150for subclasses, 149for values from different classes, 149null-safe, 149of Arrays, 149of Double, 149of Instant, 403of Object, 146, 148–150of Objects, 149of String, 25–26of wrapper classes, 47overriding, 148–150symmetric, 150

equalsIgnoreCase method (String), 26$ERR, in shell scripts, 462Error class, 183error messages, for generic methods, 210eval method (ScriptEngine), 449–451even numbers, 18EventHandler interface, 113Exception class, 183exceptionally method (CompletableFuture),

338–339exceptions, 182–193

and generic types, 225–226annotating, 382catching, 186–190

in JavaScript, 461chaining, 190–191checked, 171, 183–186combining in a superclass, 185creating, 184

documenting, 186hierarchy of, 183–185logging, 198rethrowing, 189–191suppressed, 189throwing, 182–183uncaught, 192unchecked, 183

exec method (Runtime), 367Executable class

getModifiers method, 172getParameters method, 169

ExecutableElement interface, 395ExecutionException, 333Executor interface, 338executor services, 331

default, 335ExecutorCompletionService class, 334Executors class, 331ExecutorService interface, 445

execute method, 331invokeAll, invokeAny methods, 334

exists method (Files), 300, 302exit function (shell scripts), 464$EXIT, in shell scripts, 462exitValue method (Process), 369exports keyword, 473, 476–479

qualified, 489exportSubtree method (Preferences), 440extends keyword, 104, 136, 210–214Externalizable interface, 322

Ff conversion character, 34F suffix, 12\f, in regular expressions, 311factory methods, 70, 78failures, logging, 190falling through, 37false value (boolean), 14

as default value, 71, 74Field interface, 168–169

get, getXxx, set, setXxx methods, 170,172

getModifiers, getName method, 168, 172getType method, 168

509Index

Page 75: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

fields (instance and static variables), 135enumerating, 168–169final, 344provided, 143public, 168retrieving values of, 169–171setting, 170transient, 321

File class, 300file attributes

copying, 301filtering paths by, 303

file handlersconfiguring, 201–202default, 200

file managers, 446file pointers, 296file.encoding system property, 292file.separator system property, 248FileChannel class

get, getXxx, open, put, putXxx methods,297

lock, tryLock methods, 298FileFilter class, 120FileHandler class, 200–203FileNotFoundException, 183files

archiving, 305channels to, 297checking for existence, 183, 300–302closing, 187copying/moving, 301–302creating, 299–302deleting, 301empty, 300encoding of, 290–291locking, 297–298memory-mapped, 297missing, 447random-access, 296–297reading from/writing to, 33, 183, 289temporary, 301

Files classcopy method, 290, 301–302, 305createTempXxx methods, 301createXxx methods, 300

delete, deleteIfExists methods, 301exists method, 300, 302find method, 302–303isXxx methods, 300, 302lines method, 263, 293list method, 302–303move method, 301–302newBufferedReader method, 294, 448newBufferedWriter method, 294, 302newXxxStream methods, 288, 302, 320read, readNBytes methods, 289readAllBytes method, 289, 293readAllLines method, 293walk method, 302–305walkFileTree method, 302, 304write method, 295, 302

FileSystem, FileSystems classes, 305FileTime class, 417FileVisitor interface, 304fill method

of Arrays, 49of Collections, 49, 239

filter method (Stream), 261–263, 267Filter interface, 202filtering method (Collectors), 277final fields, 344final methods, 347final modifier, 15, 73, 141final variables, 343, 347finalize method

of Enum, 156of Object, 146

finally statement, 189–190for locks, 358

financial calculations, 13find method (Files), 302–303findAll method (Scanner), 316findAny method (Stream), 267findClass method (ClassLoader), 164findFirst method (Stream), 168, 267fine method (Logger), 197first method (SortedSet), 243first day of week, 431firstDayOfXxx methods (TemporalAdjusters),

408flag bits, sequences of, 248

Index510

Page 76: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

flatMap methodgeneral concept of, 264of Optional, 269–271of Stream, 264

flatMapping method (Collectors), 276flip method (BitSet), 249Float class, 46float type, 12–13

streams of, 279type conversions of, 20–22

floating-point types, 12–13and binary number system, 13comparing, 110division of, 18formatting for output, 34in hexadecimal notation, 13type conversions of, 20–22

floor method (NavigableSet), 243floorMod method (Math), 19fonts, missing, 438for statement, 39

declaring variables for, 42enhanced, 47, 52, 126, 155, 241, 300multiple variables in, 39

for each loop (JavaScript), 458forEach method

of ArrayList, 117of Map, 246

forEach, forEachOrdered methods (Stream),271

forEachXxx methods (ConcurrentHashMap),352

ForkJoinPool class, 338commonPool method, 335

forLanguageTag method (Locale), 426format method

of DateTimeFormatter, 413, 430of MessageFormat, 433–435of String, 427

Format class, 417format specifiers, 34formatted output, 33–36Formatter class, 203formatters, for date/time values,

414–415forms, posting data from, 307–309

forName methodof Charset, 292of Class, 160–161, 164–165, 184, 192,

447frequency method (Collections), 239from method (Instant, ZonedDateTime), 416full indicator, in string templates, 433Function interface, 121, 273function keyword (JavaScript), 458function types, 114

structural, 120functional interfaces, 115–116

as method parameters, 213–214common, 121contravariant in parameter types, 214for primitive types, 122implementing, 123

@FunctionalInterface annotation, 123, 386,388–389

functions, 60higher-order, 127–129

Future interface, 334cancel, isCancelled, isDone methods, 333get method, 333, 335

futures, 333–335completable, 335–340

GG formatting symbol (date/time), 416g, G conversion characters, 34\G, in regular expressions, 314%g pattern variable, 202garbage collector, 251generate method (Stream), 262, 279@Generated annotation, 387–388generators, converting to streams, 281generic classes, 45, 208–209

constructing objects of, 209information available at runtime, 227instantiating, 209

generic collections, 254generic constructors, 228generic methods, 209–210

calling, 210declaring, 210information available at runtime, 227

511Index

Page 77: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

generic type declarations, 228–229generic types, 110

and exceptions, 225–226and lambda expressions, 213and reflection, 226–229annotating, 381arrays of, 118casting, 220in JVM, 216–219invariant, 212–213restrictions on, 220–226

GenericArrayType interface, 228get method

of Array, 174of ArrayList, 46of BitSet, 249of Field, 170, 172of FileChannel, 297of Future, 333, 335of List, 238of LongAccumulator, 356of Map, 243, 245of Optional, 269–271of Path, 298–300of Preferences, 440of ServiceLoader.Provider, 167of Supplier, 121of ThreadLocal, 365

GET requests, 308getAndXxx methods (AtomicXxx), 355getAnnotation, getAnnotationsByType methods

(AnnotatedConstruct), 395getAnnotationXxx methods

(AnnotatedElement), 392–393getAsXxx methods

of OptionalXxx, 280of XxxSupplier, 122

getAudioClip method (Applet), 163getAvailableCurrencies method (Currency),

428getAvailableIds method (ZoneId), 410getAvailableLocales method (Locale), 425getAverage method (XxxSummaryStatistics),

272getBundle method (ResourceBundle), 436–438getCanonicalName method (Class), 160–161

getClass method (Object), 141, 146, 149,159, 221, 227

getClassLoader method (Class), 161getComponentType method (Class), 161, 174getConstructor(s) methods (Class), 162,

168, 171, 227getContents method (ListResourceBundle),

437getContextClassLoader method (Thread),

165getCountry method (Locale), 274getCurrencyInstance method (NumberFormat),

427getDayOfXxx methods

of LocalDate, 61, 406–407of LocalTime, 409of ZonedDateTime, 411

getDeclaredAnnotationXxx methods(AnnotatedElement), 392–393

getDeclaredConstructor(s) methods (Class),162, 168, 227

getDeclaredField(s) methods (Class), 162getDeclaredMethod(s) methods (Class), 162,

171getDeclaringClass method

of Class, 161of Enum, 156

getDefault method (Locale), 426, 436getDisplayName method

of Currency, 429of DayOfWeek, Month, 415, 430of Locale, 426

getElementsAnnotatedWith method(RoundEnvironment), 395

getEnclosedElements method (TypeElement),395

getEnclosingXxx methods (Class), 161getEngineXxx methods (ScriptEngineManager),

448getEnumConstants method (Class), 227getErrorStream method (Process), 368getField(s) methods (Class), 162, 168getFileName method (Path), 300getFilePointer method (RandomAccessFile),

297getFirstDayOfWeek method (Calendar), 431

Index512

Page 78: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

getGlobal method (Logger), 195getHead method (Formatter), 203getHeaderFields method (URLConnection), 307getInputStream method

of URL, 306of URLConnection, 307

getInstance methodof Collator, 432of Currency, 428

getInterfaces method (Class), 161getISOXxx methods (Locale), 425getLength method (Array), 174getLogger method (Logger), 196getMax method (XxxSummaryStatistics),

272getMethod(s) methods (Class), 162, 168,

171getMethodCallSyntax method

(ScriptEngineFactory), 451getModifiers method

of Class, 161of Constructor, 168of Executable, 172of Field, 168, 172of Method, 168

getMonthXxx methodsof LocalDate, 61, 406of LocalTime, 409of ZonedDateTime, 412

getName methodof Class, 159–161of Constructor, 168of Field, 168, 172of Method, 168of Parameter, 172of Path, 300of PropertyDescriptor, 173

getNumberInstance method (NumberFormat),427

getObject method (ResourceBundle), 437getOrDefault method (Map), 244–245getOutputStream method (URLConnection), 306getPackage, getPackageName methods (Class),

161getParameters method (Executable), 169getParent method (Path), 300

getPath method (FileSystem), 305getPercentInstance method (NumberFormat),

427getProperties method (System), 248getProperty method (System), 163getPropertyDescriptors method (BeanInfo),

173getPropertyType, getReadMethod methods

(PropertyDescriptor), 173getQualifiedName method (TypeElement), 395getResource method (Class), 163, 435getResourceAsStream method

of Class, 161–162of Module, 481

getRoot method (Path), 300getSimpleName method

of Class, 161of Element, 395

getString method (ResourceBundle), 436getSuperclass method (Class), 161, 227getSuppressed method (IOException), 189getSymbol method (Currency), 429getSystemJavaCompiler method (ToolProvider),

444getTail method (Formatter), 203getTask method (JavaCompiler), 444–445getType method (Field), 168getTypeName method (Class), 161getTypeParameters method (Class), 228getURLs method (URLClassLoader), 163getValue method (LocalDate), 61getWriteMethod method (PropertyDescriptor),

173getXxx methods (Array), 174getXxx methods (Field), 170, 172getXxx methods (FileChannel), 297getXxx methods (Preferences), 440getXxxInstance methods (NumberFormat), 78getXxxStream methods (Process), 367getYear method

of LocalDate, 406of LocalTime, 409of ZonedDateTime, 412

GlassFish administration tool, 463Goetz, Brian, 329Gregorian calendar reform, 406

513Index

Page 79: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

GregorianCalendar class, 416–417group method (Matcher, MatchResult), 315,

317grouping, 274–275

classifier functions of, 274reducing to numbers, 275

groupingBy method (Collectors), 274–277groupingByConcurrent method (Collectors),

275, 282GUI (graphical user interface)

callbacks in, 112–113long-running tasks in, 340–341missing fonts in, 438

HH formatting symbol (date/time), 416h, H conversion characters, 35\h, \H, in regular expressions, 312%h pattern variable, 202handle method (CompletableFuture), 339Handler class, 203Hansen, Per Brinch, 360hash method (Object), 151hash codes, 150–151

computing in String class, 150formatting for output, 35

hash functions, 150–151, 242hash maps

concurrent, 350–352weak, 251

hash tables, 242hashCode method

of Arrays, 151of Enum, 156of Object, 146, 148, 150–151

HashMap class, 243null values in, 244

HashSet class, 242Hashtable class, 360hasNext method (Iterator), 240hasNext, hasNextXxx methods (Scanner), 33,

293headMap method (SortedMap), 253headSet method

of NavigableSet, 243of SortedSet, 243, 253

heap pollution, 221, 254Hello, World! program, 2

modular, 472–474helper methods, 216here documents, 463hexadecimal numbers, 11, 13

formatting for output, 34higher method (NavigableSet), 243higher-order functions, 127–129hn, hr elements (HTML), in

documentation comments, 91Hoare, Tony, 360HTML documentation, generating,

398HTTP connections, 306–309HttpClient class, 306–309, 335

enabling logging for, 309HttpHeaders class, 309HttpResponse class, 308–309HttpURLConnection class, 306–307hyperlinks

in documentation comments, 93–94regular expressions for, 310

I[I prefix, 147, 160IANA (Internet Assigned Numbers

Authority), 410IDE (integrated development

environment), 3, 5identity method

of Function, 121, 273of UnaryOperator, 121

identity values, 278if statement, 36ifPresent, ifPresentOrElse methods

(Optional), 268IllegalArgumentException, 194IllegalStateException, 273, 353ImageIcon class, 163images, locating, 162img element (HTML), in documentation

comments, 91immutability, 346immutable classes, 347implements keyword, 101–102

Index514

Page 80: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

import statement, 7, 83–84no annotations for, 382static, 85

import static statement, 159importPreferences method (Preferences), 441InaccessibleObjectException, 170, 481increment method (LongAdder), 356increment operator, 19incrementAndGet method (AtomicXxx), 355incrementExact method (Math), 20indexOf method

of List, 238of String, 28

indexOfSubList method (Collections), 240info method

of Logger, 195of ProcessHandle, 370

inheritance, 136–154and default methods, 144–145classes win rule, 145, 151

@Inherited annotation, 387, 389initCause method (Throwable), 191initialization blocks, 72–73

static, 76inlining, 141inner classes, 87–89

anonymous, 130–131capturing this references in, 118invoking methods of outer classes, 88local, 126, 129–131syntax for, 89

inputreading, 32–33, 293–294redirecting, 449setting locales for, 427splitting along delimiters, 317

input prompts, 33input streams, 288

copying, 290obtaining, 288reading from, 289

InputStream class, 289transferTo method, 290

InputStreamReader class, 293INSTANCE instance (enum types), 323instance methods, 6, 66–67

instance variables, 65, 67–68annotating, 380comparing, 149default values of, 71–72final, 73in abstract classes, 142in JavaScript, 460initializing, 72–73, 139not accessible from static methods, 77of deserialized objects, 322–324protected, 143setting, 70transient, 321vs. local, 72

instanceof operator, 104, 140, 149annotating, 382

instances, 6Instant class, 402

and legacy classes, 417compareTo, equals methods, 403from method, 416immutability of, 347, 404minus, minusXxx, plus, plusXxx methods,

404now method, 403

instruction reordering, 343int type, 10–12

functional interfaces for, 122processing values of, 120random number generator for, 6, 38streams of, 279type conversions of, 20–22using class literals with, 160

IntBinaryOperator interface, 122IntConsumer interface, 120, 122Integer class, 46

compare method, 110MIN_VALUE, MAX_VALUE constants, 11parseInt method, 27, 184toString method, 27unsigned division in, 12xxxUnsigned methods, 20

integer indicator, in string templates, 433integer types, 10–12

comparing, 110computing, 18, 20

515Index

Page 81: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

integer types (cont.)formatting for output, 34in hexadecimal notation, 11reading/writing, 296–297type conversions of, 20–22values of:

even/odd, 18signed, 12

@interface declaration, 384–385interface keyword, 101interface methods, 106–108interfaces, 100–105

annotating, 380–381compatibility of, 107declarations of, 100–101defining variables in, 105documentation comments for, 90evolution of, 106extending, 104functional, 115–116implementing, 101–103

in JavaScript, 459–460in scripting engines, 451multiple, 105

methods of, 101–102nested, enumerating, 168–169no instance variables in, 105no redefining methods of the Object

class in, 151views of, 252

Internet Engineering Task Force, 423interrupted method (Thread), 364interrupted status, 364InterruptedException, 363–364intersects method (BitSet), 249IntFunction interface, 122, 220IntPredicate interface, 122intrinsic locks, 358–360ints method (Random), 280IntSequence interface, 129IntStream class, 279–280

parallel method, 280IntSummaryStatistics class, 272, 280IntSupplier, IntToXxxFunction,

IntUnaryOperator interfaces, 122InvalidClassException, 324

InvalidPathException, 298Invocable interface, 450InvocationHandler interface, 175invoke method (Method), 171–172invokeXxx methods (ExecutorService), 334IOException, 183, 293

addSuppressed, getSuppressed methods, 189isAfter, isBefore methods

of LocalDate, 406of LocalTime, 409of ZonedDateTime, 412

isAlive methodof Process, 369of ProcessHandle, 370

isCancelled method (Future), 333isDone method

of CompletableFuture, 336of Future, 333

isEmpty methodof BitSet, 249of Collection, 237of Map, 246

isEqual method (Predicate), 121–122isFinite, isInfinite methods (Double), 13isInterrupted method (Thread), 364isLoggable method (Filter), 202isNamePresent method (Parameter), 172isNull method (Objects), 117ISO 8601 format, 388ISO 8859-1 encoding, 292, 295isPresent method (Optional), 269–271isXxx methods (Class), 161, 174isXxx methods (Files), 300, 302isXxx methods (Modifier), 162, 168isZero, isNegative methods (Duration), 404Iterable interface, 240–241, 300, 458

iterator method, 240iterate method (Stream), 262, 266, 279,

349iterator method

of Collection, 237of ServiceLoader, 167of Stream, 271

Iterator interfacenext, hasNext methods, 240remove, removeIf methods, 241

Index516

Page 82: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

iterators, 240–241, 271converting to streams, 281for random numbers, 459invalid, 241traversing, 167weakly consistent, 350

JJAR files, 80–81

dependencies in, 491for split packages, 483manifest for, 484–485modular, 482–484processing order of, 82resources in, 163, 435scanning for deprecated elements, 387

jar program, 80–81-C option, 482–483-d option, 482–483--module-version option, 483

Java EE platform, 335, 486–487Java Persistence Architecture, 377Java Platform Module System, 469–493

layers in, 483migration to, 484–486no support for versioning in, 471, 474,

483service loading in, 490–491

java program, 4--add-exports, --add-opens options, 486--add-module option, 484, 487-cp (--class-path, -classpath) option,

81–82-disableassertions (-da) option, 195-enableassertions (-ea) option, 194-enablesystemassertions (-esa) option, 195--illegal-access option, 486-jar option, 81-m, -p (--module, --module-path) options,

473, 483option files for, 487specifying locales in, 426

Java programming languagecompatibility with older versions of,

145, 216online API documentation on, 28–30

portability of, 19strongly typed, 14Unicode support in, 30–32uniformity of, 3, 108

java, javax, javafx global objects(JavaScript), 454

java.activation module, 486–487java.awt package, 83, 471java.base module, 475java.class.path, java.home, java.io.tmpdir

system properties, 248java.corba module, 486–487java.desktop module, 474Java.extend function (JavaScript), 459Java.from function (JavaScript), 457java.lang, java.lang.annotation packages,

386java.lang.reflect package, 168java.logging module, 488java.sql package, 417Java.super function (JavaScript), 460java.time package, 401–417Java.to function (JavaScript), 457java.transaction module, 486–487Java.type function (JavaScript), 454–455java.util package, 7, 350java.util.concurrent package, 350, 353java.util.concurrent.atomic package, 355java.util.logging package, 196java.version system property, 248java.xml.bind, java.xml.ws,

java.xml.ws.annotation modules,486–487

JavaBeans, 172–173javac program, 4

-author option, 95-cp (--class-path, -classpath) option, 81-d option, 80, 94-encoding option, 438-link, -linksource options, 95-parameters option, 169-processor option, 394-version option, 95-Xlint option, 37-XprintRounds option, 398

JavaCompiler.getTask method, 444–445

517Index

Page 83: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

javadoc program, 90–95including annotations in, 389

JavaFileObject interface, 445JavaFX platform, 112–113

and threads, 341distributed over multiple modules,

489javafx.base, javafx.controls modules,

487–488javan.log files, 200JavaScript programming language

accessing classes of, from Java, 451anonymous functions in, 458anonymous subclasses in, 459arrays in, 457–458arrow function syntax, 459bracket notation in, 454, 457–458calling static methods in, 455catching Java exceptions in, 461constructing Java objects in,

454–455delimiters in, 450extending Java classes in, 459–460implementing Java interfaces in,

459–460inner classes in, 455instance variables in, 460lists and maps in, 458methods in, 453–454numbers in, 456objects in, 456REPL for, 452–453semicolons in, 450strings in, 456superclasses in, 460

JavaServer Faces framework, 246javax.annotation package, 386javax.swing package, 474JAXB (Java Architecture for XML

Binding), 479jconsole program, 200jdeprscan program, 387jdeps program, 491JDK (Java Development Kit), 3

obsolete features in, 470jdk.incubator.http package, 306

jjs program, 452–453command-line arguments in, 463executing commands in, 462

jlink program, 492jmod program, 493job scheduling, 251join method

of String, 25of Thread, 363

joining method (Collectors), 272JPA (Java Persistence API), 479JShell, 7–10

imported packages in, 9–10loading modules into, 484

JSP (JavaServer Pages), 464JUnit, 377–378

KK formatting symbol (date/time), 416\k, in regular expressions, 313key/value pairs

adding new keys to, 243in annotations. See elementsremoved by garbage collector, 251values of, 243

keys method (Preferences), 440keySet method

of ConcurrentHashMap, 354of Map, 246, 252

keywords, 15

LL suffix, 11[L prefix, 160labeled statements, 40–41lambda expressions, 113–116

and generic types, 213annotating targets for, 388capturing variables in, 124–127executing, 119for loggers, 196parameters of, 115processing, 119–123return type of, 115scope of, 124this reference in, 124

Index518

Page 84: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

throwing exceptions in, 186using with streams, 263vs. anonymous functions (JavaScript),

458with parallel streams, 348

language codes, 275, 424language model API, 395last method (SortedSet), 243lastIndexOf method

of List, 238of String, 28

lastIndexOfSubList method (Collections),240

lastXxx methods (TemporalAdjusters), 408lazy operations, 261, 266, 283, 317leap seconds, 402leap years, 405–406legacy code, 416–417length method

of arrays, 43of RandomAccessFile, 297of String, 6, 31

.level suffix, 199lib/modules file, 493limit method (Stream), 264, 282line feed

character literal for, 14formatting for output, 35in regular expressions, 314

line.separator system property, 248lines method

of BufferedReader, 294of Files, 263, 293

@link tag (javadoc), 93–94linked lists, 237, 241LinkedBlockingQueue class, 353, 362LinkedHashMap class, 246LinkedList class, 237list method (Files), 302–303List interface, 215, 237

add, addAll, get, indexOf, lastIndexOf,listIterator, remove, replaceAll, set,sort methods, 238

of method, 46, 48, 238, 252subList method, 238, 253

ListIterator interface, 241

ListResourceBundle class, 437lists

converting to streams, 281in Nashorn, 458mutable, 253printing elements of, 117removing null values from, 117sublists of, 253unmodifiable views of, 254

little-endian format, 291load method (ServiceLoader), 167load balancing, 319loadClass method (ClassLoader), 164local classes, 129–130local date/time, 404–410local variables, 41–43

annotating, 380–381vs. instance, 72

LocalDate class, 61and legacy classes, 417datesUntil method, 406–407getXxx methods, 61, 406–407isXxx methods, 406minus, minusXxx methods, 406–407now method, 70, 77, 405–406of method, 61, 70, 405–406ofInstant method, 406parse method, 430plus, plusXxx methods, 61–62, 64,

406–407toEpochSecond method, 406until method, 406withXxx methods, 406

LocalDateTime class, 410and legacy classes, 417atZone method, 410parse method, 430

Locale class, 273forLanguageTag method, 426getAvailableLocales method, 425getCountry method, 274getDefault method, 426, 436getDisplayName method, 426getISOXxx methods, 425setDefault method, 426predefined fields, 425

519Index

Page 85: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

locales, 273–276, 422–427date/time formatting for, 429–431default, 413, 426, 429–430, 436displaying names of, 426first day of week in, 431for template strings, 433–435formatting styles for, 415, 430sorting words for, 431–432specifying, 423–425weekdays and months in, 415

LocalTime class, 409–410and legacy classes, 417final, 141getXxx, isXxx, minus, minusXxx, now, of,

ofInstant, plus, plusXxx, toXxx, withXxxmethods, 409

parse method, 430lock method

of FileChannel, 298of ReentrantLock, 358

locks, 346error-prone, 347intrinsic, 358–360reentrant, 357–358releasing, 189, 343

log handlers, 200–202default, 197, 200filtering/formatting, 202installing custom, 200levels of, 200suppressing messages in, 197

Logger class, 488addHandler method, 200entering, exiting methods, 197fine method, 197getGlobal method, 195getLogger method, 196info method, 195log method, 197–198logp, logrb methods, 198setFilter method, 203setLevel method, 195, 197, 200setUseParentHandlers method,

200throwing method, 198warning method, 197

loggersdefining, 196filtering/formatting, 202hierarchy of, 196

logging, 195–203configuring, 197–200enabling/disabling, 197failures, 190levels of, 197–200localizing, 199overriding methods for, 141using for unexpected exceptions, 198

Long class, 46MIN_VALUE, MAX_VALUE constants, 11unsigned division in, 12xxxUnsigned methods, 20

long indicator, in string templates, 433long type, 10–12

atomic operations on, 356–357functional interfaces for, 122streams of, 279type conversions of, 20–22

LongAccumulator class, 356accumulate, get methods, 356

LongAdder class, 356–357add, increment, sum methods, 356

LongConsumer, LongXxxOperator, LongPredicate,LongSupplier, LongToXxxFunctioninterfaces, 122

LongFunction interface, 122, 220longs method (Random), 280LongStream class, 279–280LongSummaryStatistics class, 272, 280long-term persistence, 324Lookup class, 482lookup method (MethodHandles), 482loops, 38–39

exiting, 39–41infinite, 39

Mm, M formatting symbols (date/time), 416main method, 2, 6

decomposing, 52–54string array parameter of, 49

ManagedExecutorService class, 335

Index520

Page 86: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Map interface, 238clear method, 246compute, computeIfXxx methods, 245containsXxx methods, 246entrySet method, 246forEach method, 246get, getOrDefault methods, 243, 245isEmpty method, 246keySet method, 246, 252merge method, 244–245of method, 246, 252ofEntries method, 252put method, 243, 245putAll, putIfAbsent methods, 245remove, replace methods, 245replaceAll method, 246size method, 246values method, 246, 252

map methodof Optional, 268of Stream, 263

mapping method (Collectors), 276maps, 243–246

concurrent, 246, 274empty, 246in Nashorn, 458iterating over, 244of stream elements, 273–274, 282order of elements in, 246views of, 244

unmodifiable , 254mapToInt method (Stream), 278mapToXxx methods (XxxStream), 280marker interfaces, 153Matcher class, 315–317

quoteReplacement method, 318replaceAll method, 317–318replaceFirst method, 318

matcher, matches methods (Pattern), 314MatchResult interface, 315–318Math class

E constant, 20floorMod method, 19max, min methods, 19PI constant, 20, 75pow method, 19, 77

round method, 21sqrt method, 19xxxExact methods, 20, 22

max methodof Stream, 266of XxxStream, 280

MAX_VALUE constant (integer classes), 11maxBy method

of BinaryOperator, 121of Collectors, 276

medium indicator, in string templates, 433memory

allocating, 346caching, 342concurrent access to, 343

memory-mapped files, 297merge method

of ConcurrentHashMap, 351of Map, 244–245

Message class, 153–154MessageFormat class, 433–435meta-annotations, 384–390META-INF/MANIFEST.MF file, 484–485META-INF/services directory, 490Method interface, 168–169

getModifiers, getName methods, 168invoke method, 171–172

method calls, 6receiver of, 67

method expressions, 117, 145method references, 117–118, 221

annotating, 382MethodHandles.lookup method, 482methods, 2

abstract, 115, 141–142accessor, 62annotating, 224, 380atomic, 351body of, 66chaining calls of, 62clashes of, 224–225compatible, 151declarations of, 65default, 106–108deprecated, 93documentation comments for, 90, 92

521Index

Page 87: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

methods (cont.)enumerating, 168–169factory, 70, 78final, 141, 347header of, 65inlining, 141instance, 66–67invoking, 171modifying functions, 128mutator, 62, 254, 347naming, 14–15native, 76overloading, 71, 118overriding, 106, 137–139, 141,

185–186, 387parameters of, 169

null checks for, 193passing arrays into, 53private, 109proxied, 176public, 101–102, 168restricted to subclasses, 142–143return value of, 2, 66returning functions, 127static, 53, 77–78, 85, 105–106storing in variables, 6symmetric, 150synchronized, 359–361utility, 83variable number of arguments of, 53

Microsoft Notepad, 291Microsoft Windows

batch files, 461path separator, 81, 248registry, 439

min methodof Math, 19of Stream, 266of XxxStream, 280

MIN_VALUE constant (integer classes), 11minBy method

of BinaryOperator, 121of Collectors, 276

minus, minusXxx methodsof Instant, Duration, 404of LocalDate, 406–407

of LocalTime, 409of ZonedDateTime, 411

Modifier interfaceisXxx methods, 162, 168toString method, 162

modifiers, checking, 168module keyword, 473module path, 473, 483–485Module.getResourceAsStream method, 481module-info.class file, 473, 482module-info.java file, 473modules, 469–493

aggregator, 488and versioning, 471, 474, 483annotating, 474automatic, 484–485bundling up the minimal set of,

492declaration of, 472–473deprecated, 487documentation comments for, 91, 94illegal access to, 486inspecting files in, 493loading into JShell, 484naming, 472, 484open, 481reflective access for, 169–170required, 474–476, 487–489tools for, 491–493transitive, 487–489unnamed, 485

monads, 264monitors (classes), 360Month enumeration, 405–406, 412

getDisplayName method, 415, 430MonthDay class, 407move method (Files), 301–302multiplication, 18multipliedBy method (Duration), 404mutators, 62

and unmodifiable views, 254

Nn

conversion character, 35formatting symbol (date/time), 416

Index522

Page 88: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

\n (line feed)for character literals, 14in property files, 247–248in regular expressions, 311–313, 318

name method (Enum), 156NaN (not a number), 13Nashorn engine, 448, 452–461

anonymous subclasses in, 459arrays in, 457–458catching Java exceptions in, 461class objects in, 455extending Java classes in, 459–460getters/setters in, 454implementing Java interfaces in,

459–460instance variables in, 460lists and maps in, 458methods in, 453–454no standard input source in, 450numbers in, 456running from command line, 452shell scripting in, 461–464strings in, 455superclasses in, 460

native methods, 76naturalOrder method (Comparator), 129navigable maps/sets, 254NavigableMap interface, 354NavigableSet interface, 238, 242, 253

methods of, 243nCopies method (Collections), 237, 239negate method (Predicate, BiPredicate), 121negated method (Duration), 404negateExact method (Math), 20NEGATIVE_INFINITY value (Double), 13negative values, 10nested classes, 85–90

annotating, 382enumerating, 168–169inner, 87–89public, 86static, 85–86

new operator, 6, 14, 17, 70as constructor reference, 118for anonymous classes, 130for arrays, 43–44, 50

in JavaScript, 455–459newBufferedReader method (Files), 294, 448newBufferedWriter method (Files), 294, 302newBuilder, newHttpClient methods

(HttpClient), 308, 335newFileSystem method (FileSystems), 305newInputStream method (Files), 288, 302,

320newInstance method

of Array, 174of Class, 171, 227of Constructor, 171–172

newKeySet method (ConcurrentHashMap), 354newline. See line feednewOutputStream method (Files), 288, 302,

320newProxyInstance method (Proxy), 175newXxxThreadPool methods (Executors), 331next method (Iterator), 240next, nextOrSame methods

(TemporalAdjusters), 408next, nextXxx methods (Scanner), 32, 293nextInt method (Random), 6, 38nextXxxBit methods (BitSet), 249nominal typing, 120noneMatch method (Stream), 267noneOf method (EnumSet), 250noninterference, of stream operations,

283@NonNull annotation, 381normalize method (Path), 299Normalizer class, 433NoSuchElementException, 269, 353notify, notifyAll methods (Object), 146,

361–362NotSerializableException, 321now method

of Instant, 403of LocalDate, 70, 77, 405–406of LocalTime, 409of ZonedDateTime, 411

null value, 26, 64as default value, 71, 74checking parameters for, 193comparing against, 149converting to strings, 147

523Index

Page 89: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

NullPointerException, 26, 45, 64, 72, 184,193, 244

vs. Optional, 266nullsFirst, nullsLast methods (Comparator),

129Number class, 428number indicator, in string templates, 433Number type (JavaScript), 456NumberFormat class

getXxxInstance methods, 78, 427not threadsafe, 365–366parse method, 428setCurrency method, 429

NumberFormatException, 184numbers

big, 23–24comparing, 110converting to strings, 27default value of, 71, 74even or odd, 18formatting, 34, 422, 427, 433from grouped elements, 275in regular expressions, 312non-negative, 194, 248printing, 34random, 6, 38, 262, 264, 280reading/writing, 293, 296–297rounding, 13, 21type conversions of, 20–22unsigned, 12, 20with fractional parts, 12–13

Oo conversion character, 34Object class, 145–154

clone method, 143, 146, 151–154, 171equals method, 146, 148–150finalize method, 146getClass method, 141, 146, 149, 159,

221, 227hashCode method, 146, 148, 150–151notify, notifyAll methods, 146, 361–362toString method, 146–147wait method, 146, 361–362

object references, 63–64and serialization, 320

attempting to change, 69comparing, 148default value of, 71, 74null, 64passed by value, 69

ObjectInputStream class, 320–321defaultReadObject method, 322readFields method, 325readObject method, 320–323, 325

object-oriented programming, 59–97encapsulation, 469–470

ObjectOutputStream class, 320defaultWriteObject method, 322writeObject method, 320–322

object-relational mappers, 479objects, 2, 60–64

calling methods on, 6casting, 103–104cloning, 151–154comparing, 47, 148–150constructing, 6, 69–74, 171–172

in JavaScript, 454–455converting:

to strings, 146–147to XML, 480

deep/shallow copies of, 152–154deserialized, 322–324externalizable, 322immutable, 62initializing variables with, 14inspecting, 169–171invoking static methods on, 77mutable, 73serializable, 319–321sorting, 109–111state of, 60

Objects classequals method, 149hash method, 151isNull method, 117requireNonNull method, 193

ObjXxxConsumer interfaces, 122octal numbers, 11

formatting for output, 34octonions, 31odd numbers, 18

Index524

Page 90: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

of methodof EnumSet, 250of IntStream, 279of List, 46, 48, 238, 252of LocalDate, 61, 70, 405–406of LocalTime, 409of Map, 246, 252of Optional, 269of ProcessHandle, 370of Set, 252of Stream, 261–262of ZonedDateTime, 410–411

ofDateAdjuster method (TemporalAdjusters),408

ofDays method (Period), 413ofEntries method (Map), 252offer method (BlockingQueue), 353offsetByCodePoints method (String), 31OffsetDateTime class, 413ofInstant method

of LocalDate, 406of LocalTime, 409of ZonedDateTime, 411

ofLocalizedXxx methods (DateTimeFormatter),413, 430

ofNullable methodof Optional, 269of Stream, 271

ofPattern method (DateTimeFormatter), 415ofXxx methods (Duration), 403, 405, 413onExit method

of Process, 369of ProcessHandle, 370

open keyword, 481open method (FileChannel), 297openConnection method (URL), 306opens keyword, 481

qualified, 489openStream method (URL), 288Operation interface, 157operations

associative, 278atomic, 346, 351, 354–357, 360bulk, 352lazy, 261, 266, 283, 317parallel, 348–350

performed optimistically, 355stateless, 281threadsafe, 350–354

operators, 17–24precedence of, 17

option files, 487Optional class, 266–270

creating values of, 269empty method, 269flatMap method, 269–271for empty streams, 277–278for processes, 370get method, 269–271ifPresent, ifPresentOrElse methods, 268isPresent method, 269–271map method, 268of, ofNullable methods, 269orElse method, 266–268orElseXxx methods, 267–268stream method, 270–271

OptionalXxx classes, 280or method

of BitSet, 249of Predicate, BiPredicate, 121

order method (ByteBuffer), 297ordinal method (Enum), 156org global object (JavaScript), 454org.omg.corba package, 470os.arch, os.name, os.version system

properties, 248OSGi (Open Service Gateway Initiative),

471$OUT, in shell scripts, 462output

formatted, 33–36redirecting, 449setting locales for, 427writing, 294–295

output streams, 288closing, 290obtaining, 288writing to, 290

OutputStream class, 320write method, 290

OutputStreamWriter class, 294@Override annotation, 138, 386–387

525Index

Page 91: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

overriding, 137–139for logging/debugging, 141

overview.html file, 94

P\p, \P, in regular expressions, 312package statement, 79package declarations, 79–80Package object (JavaScript), 454package-info.java file, 94, 380packages, 3, 78–85

accessing, 83, 143, 470, 477–478, 481,484

adding classes to, 83annotating, 380–381default, 79documentation comments for, 91, 94exporting, 476–479, 481naming, 79not nesting, 79split, 483

parallel method (XxxStream), 280parallel streams, 348–349parallelStream method (Collection), 237,

260–261, 280, 348parallelXxx methods (Arrays), 49, 349@param tag (javadoc), 92Parameter class, 172parameter variables, 68

annotating, 380scope of, 42

ParameterizedType interface, 228parentLogger method (Driver), 488parse method

of DateTimeFormatter, 415of LocalXxx, ZonedDateTime, 430of NumberFormat, 428

Parse.quote method, 311parseDouble method (Double), 27ParseException, 428parseInt method (Integer), 27, 184partitioning, 347partitioningBy method (Collectors), 275,

277Pascal triangle, 51passwords, 33

Path interface, 106, 298–300get method, 298–300getXxx methods, 300normalize, relativize methods, 299resolve, resolveSibling methods, 299subpath method, 300toAbsolutePath, toFile methods, 299

path separators, 298path.separator system property, 248paths, 298

absolute vs. relative, 298–299filtering, 303resolving, 299taking apart/combining, 300

Paths class, 106Pattern class

compile method, 315, 318flags, 318–319matcher, matches methods, 314split method, 317splitAsStream method, 263, 317

pattern variables, 202PECS (producer extends, consumer super),

214peek method

of BlockingQueue, 353of Stream, 266

percent indicator, in string templates, 433performance

and atomic operations, 355and combined operators, 19and memory caching, 343

Period class, 405ofDays method, 413

@Persistent annotation, 389PI constant (Math), 20, 75placeholders, 433–435platform class loader, 163platform encoding, 292, 438plugins, loading, 164plus, plusXxx methods

of Instant, Duration, 404of LocalDate, 61–62, 64, 406–407of LocalTime, 409of ZonedDateTime, 411–412

Point class, 146–147

Index526

Page 92: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Point2D class (JavaFX), 321poll method (BlockingQueue), 353pollXxx methods (NavigableSet), 243pop method (ArrayDeque), 250portability, 19POSITIVE_INFINITY value (Double), 13POST requests, 308@PostConstruct annotation, 386, 388pow method (Math), 19, 77predefined character classes, 310, 312,

314@PreDestroy annotation, 386, 388predicate functions, 275Predicate interface, 116, 121

and, or, negate methods, 121isEqual method, 121–122test method, 121, 213

Preferences class, 439–441previous method (ListIterator), 241previous, previousOrSame methods

(TemporalAdjusters), 408previousXxxBit methods (BitSet), 249preVisitDirectory, postVisitDirectory

methods (FileVisitor), 304primitive types, 10–14

and type parameters, 220attempting to update parameters of,

68comparing, 149converting to strings, 147functions interfaces for, 122passed by value, 69streams of, 278–280wrapper classes for, 46–47

printStackTrace method (Throwable), 192PrintStream class, 6, 147, 295

print method, 6, 33, 195, 294–295printf method, 34–35, 53, 294–295println method, 6, 32–33, 49, 117,

294–295PrintWriter class, 294

close method, 187–188printf method, 427

priority queues, 251private modifier, 2, 83

for enum constructors, 157

Process class, 366–370destroy, destroyForcibly methods,

369exitValue method, 369getErrorStream method, 368getXxxStream methods, 367isAlive method, 369onExit method, 369supportsNormalTermination method, 369toHandle method, 370waitFor method, 369

ProcessBuilder class, 366–370directory method, 367redirectXxx methods, 368start method, 368

processes, 366–370building, 367–368getting info about, 370killing, 369running, 368–369

ProcessHandle interface, 370processing pipeline, 337Processor interface, 394Programmer’s Day, 405programming languages

dynamically typed, 456functional, 99object-oriented, 2scripting, 448

programscompiling, 3configuration options for, 247localizing, 421–441packaging, 493responsive, 340running, 3testing, 193

promises (in concurrent libraries),336

properties, 172–173loading from file, 247naming, 173read-only/write-only, 173testing for, 213

Properties class, 247–248.properties extension, 435

527Index

Page 93: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

property filesencoding, 247, 437generating, 398localizing, 435–437

protected modifier, 142–143Provider.get, Provider.type methods, 167provides keyword, 490Proxy class, 175–176

newProxyInstance method, 175public modifier, 2, 83

and method overriding, 139for interface methods, 101–102

push method (ArrayDeque), 250put method

of BlockingQueue, 353of FileChannel, 297of Map, 243, 245of Preferences, 440

putAll method (Map), 245putIfAbsent method

of ConcurrentHashMap, 351of Map, 245

putXxx methods (FileChannel), 297putXxx methods (Preferences), 440

Q\Q, in regular expressions, 311qualified exports, 489Queue interface, 238, 250

synchronizing methods in, 360using ArrayDeque with, 250

quote method (Parse), 311quoteReplacement method (Matcher), 318

R\r (carriage return)

for character literals, 14in property files, 248

\r, \R, in regular expressions, 311,314

race conditions, 281, 344–346Random class, 6

ints, longs, doubles methods, 280nextInt method, 6, 38

random numbers, 6, 38, 459streams of, 262, 264, 280

RandomAccess interface, 237RandomAccessFile class, 296–297

getFilePointer method, 297length method, 297seek method, 296–297

RandomNumbers class, 77range method (EnumSet), 250range, rangeClosed methods (XxxStream), 279ranges, 253

converting to streams, 281raw types, 217, 220–221read method

of Files, 289of InputStream, 289of InputStreamReader, 293

readAllXxx methods (Files), 289, 293Reader class, 293readers, 288readExternal method (Externalizable), 322readFields method (ObjectInputStream), 325readLine function (shell scripts), 464readLine method

of BufferedReader, 294of Console, 33

readNBytes method (Files), 289readObject method (ObjectInputStream),

320–323, 325readPassword method (Console), 33readResolve method (Serializable),

322–323readXxx methods (DataInput), 296–297, 322receiver parameters, 67, 383redirection syntax, 33redirectXxx methods (ProcessBuilder), 368reduce method (Stream), 277–279reduceXxx methods (ConcurrentHashMap), 352reducing method (Collectors), 277reductions, 266, 277–279ReentrantLock class, 357–358

lock, unlock methods, 358reflection, 168–176

and generic types, 222, 226–229and module system, 169–170, 479,

486processing annotations with, 391–393

ReflectiveOperationException, 160

Index528

Page 94: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

regular expressions, 310–319finding matches of, 314–316flags for, 318–319groups in, 316–317replacing matches with, 317splitting input with, 317

relational operators, 22relativize method (Path), 299remainderUnsigned method (Integer, Long),

20remove method

of ArrayDeque, 250of ArrayList, 46of BlockingQueue, 353of Collection, 236of Iterator, 241of List, 238of Map, 245of Preferences, 440

removeIf methodof ArrayList, 116of Iterator, 241

removeNode method (Preferences), 440removeXxx methods (Collection), 236@Repeatable annotation, 387, 389REPL (“read-eval-print” loop), 452–453replace method

of Map, 245of String, 28

replaceAll methodof Collections, 239of List, 238of Map, 246of Matcher, 317–318of String, 317

replaceFirst method (Matcher), 318requireNonNull method (Objects), 193requires keyword, 473, 476–479, 484,

487–489resolve, resolveSibling methods (Path), 299@Resource annotation, 386, 388resource bundles, 435–438resource injections, 388ResourceBundle class, 199

extending, 437getBundle method, 436–438

getObject method, 437getString method, 436

resources, 159–168loading, 162, 481managing, 187

@Resources annotation, 387resume method (Thread, deprecated),

363retainAll method (Collection), 236@Retention annotation, 384, 387return statement, 37, 53, 66

in lambda expressions, 114not in finally, 189

@return tag (javadoc), 92return types, covariant, 138, 219return values

as arrays, 53missing, 266providing type of, 53

reverse method (Collections), 49, 240reverse domain name convention, 79,

472reversed method (Comparator), 128reverseOrder method (Comparator), 129RFC 822, RFC 1123 formats, 414rlwrap program, 453rotate method (Collections), 240round method (Math), 21RoundEnvironment interface, 395roundoff errors, 13RowSetProvider class, 486rt.jar file, 493runAfterXxx methods (CompletableFuture),

339–340Runnable interface, 112, 121, 331, 333

executing on the UI thread, 341run method, 121, 330, 363–364using class literals with, 160

runtimeraw types at, 220–221safety checks at, 218

Runtime classavailableProcessors method, 331exec method, 367

runtime image file, 493RuntimeException, 183

529Index

Page 95: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

Ss formatting symbol (date/time), 416s, S conversion characters, 34\s, \S, in regular expressions, 312safety checks, as runtime, 218@SafeVarargs annotation, 224, 386, 388Scala programming language

REPL in, 453type parameters in, 215

Scanner class, 32findAll method, 316hasNext, hasNextXxx, next, nextXxx methods,

32, 293tokens method, 263, 294useLocale method, 427

scheduling applicationsand time zones, 405, 410computing dates for, 407–408

ScriptContext interface, 449ScriptEngine interface

createBindings method, 449eval method, 449–451

ScriptEngineFactory interface, 451ScriptEngineManager class

getEngineXxx methods, 448visibility of bindings in, 449

scripting engines, 448–449compiling code in, 452implementing Java interfaces in, 451

scripting languages, 448invoking functions in, 450

searchXxx methods (ConcurrentHashMap), 352security, 83SecurityException, 170@see tag (javadoc), 93–94seek method (RandomAccessFile), 296sequences, producing, 262serial numbers, 321Serializable interface, 319–321

readResolve, writeReplace methods,322–323

serialization, 319–325serialVersionUID instance variable, 324server-side software, 319ServiceLoader class, 166–168, 490

iterator, load method, 167

ServiceLoader.Provider interface, 167services

configurable, 166loading, 166–168, 490–491

ServletException class, 191Set interface, 238, 354

of method, 252working with EnumSet, 250

set methodof Array, 174of ArrayList, 46of BitSet, 249of Field, 172of List, 238of ListIterator, 241

setAccessible method (AccessibleObject),170, 172

setContextClassLoader method (Thread),165

setCurrency method (NumberFormat), 429setDaemon method (Thread), 366setDecomposition method (Collator), 432setDefault method (Locale), 426setDefaultUncaughtExceptionHandler method

(Thread), 192setDoOutput method (URLConnection), 306setFilter methods (Handler, Logger), 203setFormatter method (Handler), 203setLevel method (Logger), 195, 197, 200setOut method (System), 76setReader method (ScriptContext), 449setRequestProperty method (URLConnection),

306sets, 242–243

immutable, 347threadsafe, 354unmodifiable views of, 254

setStrength method (Collator), 432setUncaughtExceptionHandler method (Thread),

363setUseParentHandlers method (Logger), 200setWriter method (ScriptContext), 449setXxx methods (Array), 174setXxx methods (Field), 170, 172setXxxAssertionStatus methods

(ClassLoader), 195

Index530

Page 96: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

shallow copies, 152–154shared variables, 343–347

atomic mutations of, 354–357locking, 357–358

shebang, 464shell scripts, 461–464

command-line arguments in, 463environment variables in, 463executing, 462generating, 398string interpolation in, 462–463

shell, redirection syntax of, 33shift operators, 23Shift_JIS encoding, 292short circuit evaluation, 22Short class, 46

MIN_VALUE, MAX_VALUE constants, 11short indicator, in string templates, 433short type, 10–12

streams of, 279type conversions of, 21

short-term persistence, 324shuffle method (Collections), 49, 240SimpleFileVisitor class, 304SimpleJavaFileObject class, 446@since tag (javadoc), 92singletons, 323size method

of ArrayList, 46of Collection, 237of Map, 246

skip method (Stream), 264sleep method (Thread), 363, 365SLF4J (Simple Logging Fasade for Java),

196, 472SOAP protocol, 471SocketHandler class, 200sort method

of Arrays, 49, 111–112, 116–117of Collections, 49, 215, 240of List, 238

sorted maps, 253–254sorted method (Stream), 265sorted sets, 238, 253

traversing, 242unmodifiable views of, 254

sorted streams, 281SortedMap interface, 253SortedSet interface, 238, 242

first, last methods, 243headSet, subSet, tailSet methods, 243,

253sorting

array lists, 49arrays, 49, 109–111chaining comparators for, 128changing order of, 127streams, 265strings, 26–27, 117, 431–432

source code, generating, 395–398source files

documentation comments for, 94encoding of, 438placing, in a file system, 80reading from memory, 445

space flag (for output), 35spaces

in regular expressions, 312removing, 28

split methodof Pattern, 317of String, 25, 317

splitAsStream method (Pattern), 263, 317spliterator method (Collection), 237sqrt method (Math), 19square root, computing, 270Stack class, 250stack trace, 192–193StackWalker class, 192standard output, 3StandardCharsets class, 292StandardJavaFileManager interface, 445–447start method

of Matcher, MatchResult, 315–316of ProcessBuilder, 368of Thread, 363

startsWith method (String), 28stateless operations, 281statements, combining, 43static constants, 75–76static imports, 85static initialization, 164

531Index

Page 97: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

static methods, 53, 77–78accessing static variables from, 77importing, 85in interfaces, 105–106

static modifier, 2, 16, 53, 74–78, 158for modules, 488

static nested classes, 85–86static variables, 74–75

accessing from static methods, 77importing, 85visibility of, 343

stop, suspend methods (Thread, deprecated),363

Stream interfacecollect method, 271–272, 279concat method, 265count method, 261, 266distinct method, 265, 282dropWhile method, 265empty method, 262filter method, 261–263, 267findAny method, 267findFirst method, 168, 267flatMap method, 264forEach, forEachOrdered methods, 271generate method, 262, 279iterate method, 262, 266, 279, 349iterator method, 271limit method, 264, 282map method, 263mapToInt method, 278max, min methods, 266of method, 261–262ofNullable method, 271peek method, 266reduce method, 277–279skip method, 264sorted method, 265takeWhile method, 265toArray method, 118, 271unordered method, 282xxxMatch methods, 267

stream methodof Arrays, 262, 279of BitSet, 249of Collection, 237, 260–261

of Optional, 270–271streams, 259–283

collecting elements of, 271–274computing values from, 277–279converting to/from arrays, 262, 271,

281, 350creating, 261–263debugging, 266empty, 262, 266, 277–278filtering, 270finite, 262flattening, 264, 270infinite, 261–262, 264, 266intermediate operations for, 261locating services with, 167noninterference of, 283of primitive type values, 278–280of random numbers, 280ordered, 281parallel, 260, 267, 271, 274–275, 278,

280–283, 348–349processed lazily, 261, 266, 283reductions of, 266removing duplicates from, 265sorting, 265splitting/combining, 264–265summarizing, 272, 280terminal operation for, 261, 266transformations of, 263–264, 280vs. collections, 261

strictfp modifier, 19StrictMath class, 20String class, 6, 28

charAt method, 31codePoints, codePointXxx methods, 31–32compareTo method, 26–27, 109, 431compareToIgnoreCase method, 117contains method, 28endsWith method, 28equals method, 25–26equalsIgnoreCase method, 26final, 141format method, 427hash codes, 150immutability of, 28, 347indexOf, lastIndexOf methods, 28

Index532

Page 98: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

join method, 25length method, 6, 31offsetByCodePoints method, 31replace method, 28replaceAll method, 317split method, 25, 317startsWith method, 28substring method, 25toLowerCase method, 28, 263, 427toUpperCase method, 28, 427trim method, 28, 428

string interpolation, in shell scripts,462–463

StringBuilder class, 25strings, 6, 24–32

comparing, 25–27concatenating, 24–25, 147converting:

from byte arrays, 292from objects, 146–147to code points, 263to numbers, 27

empty, 26–27, 147formatting for output, 34internal representation of, 32normalized, 432sorting, 26–27, 117, 431–432splitting, 25, 263templates for, 433–435transforming to lower/uppercase, 263,

427StringSource class, 445StringWriter class, 295strong element (HTML), in

documentation comments, 91subclasses, 136–137

anonymous, 143–144, 157calling toString method in, 147constructors for, 139initializing instance variables in, 139methods in, 137preventing, 141public, 139superclass assignments in, 139

subList method (List), 238, 253subMap method (SortedMap), 253

subpath method (Path), 300subSet method

of NavigableSet, 243of SortedSet, 243, 253

substring method (String), 25subtractExact method (Math), 20subtraction, 18

accurate, 24not associative, 278

subtypes, 103wildcards for, 212

sum methodof LongAdder, 356of XxxStream, 280

summarizingXxx methods (Collectors), 272,276

summaryStatistics method (XxxStream), 280summingXxx methods (Collectors), 276super keyword, 108, 138–139, 145,

213–215superclasses, 136–137

annotating, 381calling equals method, 149default methods of, 144–145in JavaScript, 460methods of, 137–139public, 139

supertypes, 103–105wildcards for, 213–214

Supplier interface, 121, 336supplyAsync method (CompletableFuture),

335–337supportsNormalTermination method

of Process, 369of ProcessHandle, 370

@SuppressWarnings annotation, 37, 220, 386,388–389, 474

swap method (Collections), 240Swing GUI toolkit, 113, 341SwingConstants interface, 105SwingWorker class (Swing), 341switch statement, 37

using enumerations in, 158symbolic links, 302–303synchronized keyword, 358–361synchronized views, 254

533Index

Page 99: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

synchronizedXxx methods (Collections), 240System class

getProperties method, 248getProperty method, 163setOut method, 76

system class loader, 163, 165system classes, enabling/disabling

assertions for, 195system properties, 248System.err constant, 192, 200, 366, 444System.in constant, 32System.out constant, 6, 16, 32–35, 49, 53,

76, 117, 195, 294, 444systemXxx methods (Preferences), 439

TT, in dates, 414t, T conversion characters, 35\t

in regular expressions, 311tab, for character literals, 14

%t pattern variable, 202tab completion, 9tagging interfaces, 153tailMap method (SortedMap), 253tailSet method

of NavigableSet, 243of SortedSet, 243, 253

take method (BlockingQueue), 353takeWhile method (Stream), 265tar program, 80–81@Target annotation, 384–385, 387Task class (JavaFX), 341tasks, 330–335

cancelling, 333–334combining results from, 333–335computationally intensive, 331coordinating work between, 352–353defining, 112executing, 112, 331groups of, 366long-running, 340–341running, 330–332short-lived, 331submitting, 333vs. threads, 331

working simultaneously, 336Temporal interface, 408TemporalAdjuster.ofDateAdjuster method,

408TemporalAdjusters class, 408terminal window, 4test method

of BiPredicate, 121of Predicate, 121, 213of XxxPredicate, 122

@Test annotation, 378–379, 384TextStyle enumeration, 431thenAccept method (CompletableFuture), 335,

339thenAcceptBoth, thenCombine methods

(CompletableFuture), 339–340thenApply, thenApplyAsync methods

(CompletableFuture), 337–339thenComparing method (Comparator), 128–129thenCompose method (CompletableFuture),

338–339thenRun method (CompletableFuture), 339third-party libraries, 484–485this reference, 67–68

annotating, 383capturing, 118in constructors, 71, 348in lambda expressions, 124

Thread classget/setContextClassLoader methods, 165interrupted, isInterrupted methods, 364join method, 363properties, 366resume, stop, suspend methods

(deprecated), 363setDaemon method, 366setDefaultUncaughtExceptionHandler

method, 192setUncaughtExceptionHandler method, 363sleep method, 363, 365start method, 363

ThreadLocal class, 365–366get, withInitial methods, 365

threads, 331, 362–366and visibility, 342–344, 360atomic mutations in, 354–357

Index534

Page 100: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

creating, 112daemon, 366groups of, 366interrupting, 333, 364–365local variables in, 365–366locking, 357–358names of, 366priorities of, 366race conditions in, 281, 344–346running tasks in, 112starting, 363states of, 366temporarily inactive, 364terminating, 331–332uncaught exception handlers of, 366vs. tasks, 331waiting on conditions, 360worker, 340–341

throw statement, 183Throwable class, 183

getStackTrace, printStackTrace methods,192

in assertions, 194initCause method, 191no generic subtypes for, 225

throwing method (Logger), 198throws keyword, 185

type variables in, 225–226@throws tag (javadoc), 92, 186time

current, 402formatting, 413–416, 429–431measuring, 403parsing, 415

Time class, 416–417time indicator, in string templates, 433time zones, 410–413TimeoutException, 333Timestamp class, 150, 416–417timestamps, 413

using instants as, 403TimeZone class, 417™ (trademark symbol), 432–433toAbsolutePath method (Path), 299toArray method

of Collection, 237

of Stream, 118, 271of XxxStream, 280

toByteArray methodof BitSet, 249of ByteArrayOutputStream, 288–289

toCollection method (Collectors), 272toConcurrentMap method (Collectors), 274toEpochSecond method

of LocalDate, 406of LocalTime, 409

toFile method (Path), 300toFormat method (DateTimeFormatter), 415toGenericString method (Class), 161toHandle method (Process), 370toInstant method

of Date, 416of ZonedDateTime, 410, 412

toIntExact method (Math), 22tokens method (Scanner), 263, 294toList method (Collectors), 272toLocalXxx methods (ZonedDateTime), 412toLongArray method (BitSet), 249toLowerCase method (String), 28, 263, 427toMap method (Collectors), 273–274ToolProvider.getSystemJavaCompiler method,

444tools.jar file, 493toPath method (File), 300toSet method (Collectors), 272, 275toString method

calling from subclasses, 147of Arrays, 49, 147of BitSet, 249of Class, 161of Double, Integer, 27of Enum, 156of Modifier, 162of Object, Point, 146–147

toUnsignedInt method (Byte), 12toUpperCase method (String), 28, 427toXxx methods (Duration), 403ToXxxFunction interfaces, 122, 220toXxxOfDay methods (LocalTime), 409toZonedDateTime method (GregorianCalendar),

416–417transferTo method (InputStream), 290

535Index

Page 101: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

transient modifier, 321transitive keyword, 487–489TreeMap class, 243, 274TreeSet class, 242trim method (String), 28, 428true value (boolean), 14try statement, 186–190

for visiting directories, 302tryLock method (FileChannel), 298trySetAccessible method (AccessibleObject),

170try-with-resources statement, 187–189

closing output streams with, 290for file locking, 298

type bounds, 210–211, 229annotating, 382

type erasure, 216–219, 224clashes after, 224–225

Type interface, 228type method (ServiceLoader.Provider), 167type parameters, 109, 208–209

and primitive types, 209, 220annotating, 380

type variablesand exceptions, 225–226in static context, 224no instantiating of, 221–223wildcards with, 214–215

TypeElement interface, 395TypeVariable interface, 228

U\u

for character literals, 13–14, 437–438in regular expressions, 311

%u pattern variable, 202UnaryOperator interface, 121uncaught exception handlers, 363, 366unchecked exceptions, 183

and generic types, 226documenting, 186

UncheckedIOException, 293Unicode, 30–32, 279, 290

normalization forms in, 432replacement character in, 295

unit tests, 377

Unix operating systembash scripts, 461path separator, 81, 248specifying locales in, 426wildcard in classpath in, 82

unlock method (ReentrantLock), 358unmodifiableXxx methods (Collections), 240unordered method (Stream), 282until method (LocalDate), 405–406updateAndGet method (AtomicXxx), 355URI class, 308URL class, 308

final, 141getInputStream method, 306openConnection method, 306openStream method, 288

URLClassLoader class, 163URLConnection class, 306–307

connect method, 306getHeaderFields method, 307getInputStream method, 307getOutputStream method, 306setDoOutput method, 306setRequestProperty method, 306

URLs, reading from, 288, 306useLocale method (Scanner), 427user directory, 299user interface. See GUIuser preferences, 439–441user.dir, user.home, user.name system

properties, 248userXxx methods (Preferences), 439uses keyword, 491UTC (coordinated universal time), 411UTF-8 encoding, 290–291

for source files, 438modified, 296

UTF-16 encoding, 13, 31, 279, 291in regular expressions, 311

Util class, 165

VV formatting symbol (date/time), 416\v, \V, in regular expressions, 312valueOf method

of BitSet, 249

Index536

Page 102: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

of Enum, 155–156values method

of Enum, 155of Map, 246, 252

varargs parameterscorrupted, 388declaring, 54

VarHandle class, 482variable handles, 482VariableElement interface, 395variables, 6, 14–16

atomic mutations of, 354–357capturing, in lambda expressions,

124–127declaring, 14–15defined in interfaces, 105deprecated, 93documentation comments for, 91–92effectively final, 126final, 343, 347holding object references, 63–64initializing, 14–16local, 41–43naming, 14–15parameter, 68private, 65, 83public static final, 105redefining, 42scope of, 41, 83shared, 343–347, 357–358static final. See constantsstatic, 74–75, 77, 85, 343thread-local, 365–366using an abstract class as type of,

142visibility of, 342–344, 360volatile, 343–344

@version tag (javadoc), 91, 95versioning, 324views, 252–254virtual machine, 4

instruction reordering in, 343visibility, 342–344

guaranteed with locks, 360visitFile, visitFileFailed methods

(FileVisitor), 304

void keyword, 2, 53using class literals with, 160

volatile modifier, 343–344

W\w, \W, in regular expressions, 312wait method (Object), 146, 361–362waitFor method (Process), 369waiting on a condition, 361walk method (Files), 302–305walkFileTree method (Files), 302, 304warning method (Logger), 197warnings

for switch statements, 159suppressing, 220, 224, 388

weak references, 251weaker access privilege, 139WeakHashMap class, 251weakly consistent iterators, 350WeakReference class, 252web pages

extracting links from, 337reading, 338, 340

whenComplete method (CompletableFuture),336, 338–339

while statement, 38–39breaking/continuing, 40continuing, 40declaring variables for, 42

white spacein regular expressions, 312removing, 28

wildcardsannotating, 382capturing, 216for annotation processors, 394for types, 212–214in class path, 81unbounded, 215with imported classes, 83–84with type variables, 214–215

WildcardType interface, 228Window class, 83WindowAdapter class, 106WindowListener interface, 106with method (Temporal), 408

537Index

Page 103: CoreJava SE9 fortheImpatientptgmedia.pearsoncmg.com › images › 9780134694726 › ... · 4.2.2 The equals Method 148 4.2.3 The hashCode Method 150 4.2.4 Cloning Objects 151 4.3

withInitial method (ThreadLocal), 365withLocale method (DateTimeFormatter), 413,

430withXxx methods

of LocalDate, 406of LocalTime, 409of ZonedDateTime, 411

wordsin regular expressions, 312reading from a file, 293sorting alphabetically, 431–432

working directory, 367wrapper classes, 46–47write method

of Files, 295, 302of OutputStream, 290

writeExternal method (Externalizable),322

writeObject method (ObjectOutputStream),320–322

Writer class, 294–295write method, 294

writeReplace method (Serializable),322–323

writers, 288writeXxx methods (DataOutput), 296–297,

322

Xx formatting symbol (date/time), 416x, X conversion characters, 34

\x, in regular expressions, 311XML descriptors, generating, 398@XmlElement annotation, 480@XmlRootElement annotation, 480xor method (BitSet), 249

Yy formatting symbol (date/time), 416Year, YearMonth classes, 407

Zz, Z formatting symbols (date/time), 414,

416\z, \Z, in regular expressions, 314ZIP file systems, 305ZipInputStream, ZipOutputStream classes, 305zoned time, 404–407, 410–413ZonedDateTime class, 410–413

and legacy classes, 417getDayOfXxx methods, 411getMonthXxx, getYear, getXxx, isXxx

methods, 412minus, minusXxx, now, ofInstant methods,

411of method, 410–411parse method, 430plus, plusXxx methods, 411–412toInstant method, 410, 412toLocalXxx methods, 412withXxx methods, 411

ZoneId class, 410

Index538