Table of Contents
Introduction xxi
Assessment Test xliv
Chapter 1 Java Fundamentals 1
Applying the final Modifier 2
Declaring final Local Variables 3
Adding final to Instance and static Variables 4
Writing final Methods 5
Marking Classes final 5
Working with Enums 6
Creating Simple Enums 6
Using Enums in Switch Statements 8
Adding Constructors, Fields, and Methods 9
Creating Nested Classes 12
Declaring an Inner Class 12
Creating a static Nested Class 15
Writing a Local Class 17
Defining an Anonymous Class 18
Reviewing Nested Classes 21
Understanding Interface Members 22
Relying on a default Interface Method 23
Using static Interface Methods 27
Introducing private Interface Methods 28
Introducing private static Interface Methods 29
Reviewing Interface Members 31
Introducing Functional Programming 32
Defining a Functional Interface 32
Declaring a Functional Interface with Object Methods 34
Implementing Functional Interfaces with Lambdas 36
Writing Lambda Expressions 38
Working with Lambda Variables 40
Summary 43
Exam Essentials 44
Review Questions 46
Chapter 2 Annotations 59
Introducing Annotations 60
Understanding Metadata 60
Purpose of Annotations 61
Creating Custom Annotations 64
Creating an Annotation 64
Specifying a Required Element 65
Providing an Optional Element 66
Selecting an Element Type 67
Applying Element Modifiers 67
Adding a Constant Variable 68
Reviewing Annotation Rules 68
Applying Annotations 69
Using Annotations in Declarations 69
Mixing Required and Optional Elements 71
Creating a value() Element 71
Passing an Array of Values 73
Declaring Annotation-Specific Annotations 74
Limiting Usage with @Target 74
Storing Annotations with @Retention 77
Generating Javadoc with @Documented 77
Inheriting Annotations with @Inherited 79
Supporting Duplicates with @Repeatable 79
Reviewing Annotation-Specific Annotations 81
Using Common Annotations 83
Marking Methods with @Override 83
Declaring Interfaces with @FunctionalInterface 84
Retiring Code with @Deprecated 85
Ignoring Warnings with @SuppressWarnings 86
Protecting Arguments with @SafeVarargs 88
Reviewing Common Annotations 89
Summary 91
Exam Essentials 92
Review Questions 94
Chapter 3 Generics and Collections 105
Using Method References 107
Calling Static Methods 108
Calling Instance Methods on a Particular Object 109
Calling Instance Methods on a Parameter 109
Calling Constructors 110
Reviewing Method References 110
Using Wrapper Classes 111
Using the Diamond Operator 113
Using Lists, Sets, Maps, and Queues 114
Common Collections Methods 115
Using the List Interface 119
Using the Set Interface 124
Using the Queue Interface 126
Using the Map Interface 128
Comparing Collection Types 135
Sorting Data 137
Creating a Comparable Class 137
Comparing Data with a Comparator 141
Comparing Comparable and Comparator 142
Comparing Multiple Fields 143
Sorting and Searching 145
Working with Generics 147
Generic Classes 148
Generic Interfaces 151
Raw Types 152
Generic Methods 153
Bounding Generic Types 154
Putting It All Together 159
Summary 161
Exam Essentials 163
Review Questions 164
Chapter 4 Functional Programming 175
Working with Built-in Functional Interfaces 176
Implementing Supplier 178
Implementing Consumer and BiConsumer 179
Implementing Predicate and BiPredicate 180
Implementing Function and BiFunction 181
Implementing UnaryOperator and BinaryOperator 183
Checking Functional Interfaces 184
Convenience Methods on Functional Interfaces 185
Returning an Optional 187
Creating an Optional 188
Dealing with an Empty Optional 189
Using Streams 191
Understanding the Pipeline Flow 191
Creating Stream Sources 194
Using Common Terminal Operations 197
Using Common Intermediate Operations 204
Putting Together the Pipeline 209
Working with Primitive Streams 213
Creating Primitive Streams 214
Mapping Streams 217
Using Optional l with Primitive Streams 219
Summarizing Statistics 220
Learning the Functional Interfaces for Primitives 221
Working with Advanced Stream Pipeline Concepts 224
Linking Streams to the Underlying Data 224
Chaining Optionals 224
Collecting Results 227
Summary 234
Exam Essentials 236
Review Questions 238
Chapter 5 Exceptions, Assertions, and Localization 247
Reviewing Exceptions 248
Handling Exceptions 248
Distinguishing between throw and throws 250
Examining Exception Categories 250
Inheriting Exception Classes 252
Creating Custom Exceptions 253
Declaring Exception Classes 253
Adding Custom Constructors 253
Printing Stack Traces 255
Automating Resource Management 256
Constructing Try-With-Resources Statements 256
Learning the New Effectively Final Feature 259
Understanding Suppressed Exceptions 261
Declaring Assertions 264
Validating Data with the assert Statement 264
Enabling Assertions 266
Disabling Assertions 267
Applying Assertions 267
Writing Assertions Correctly 268
Working with Dates and Times 268
Creating Dates and Times 269
Formatting Dates and Times 271
Supporting Internationalization and Localization 276
Picking a Locale 276
Localizing Numbers 279
Localizing Dates 283
Specifying a Locale Category 284
Loading Properties with Resource Bundles 285
Creating a Resource Bundle 286
Picking a Resource Bundle 288
Selecting Resource Bundle Values 289
Formatting Messages 291
Using the Properties Class 292
Summary 293
Exam Essentials 294
Review Questions 295
Chapter 6 Modular Applications 309
Reviewing Module Directives 310
Comparing Types of Modules 311
Named Modules 311
Automatic Modules 312
Unnamed Modules 315
Comparing Module Types 315
Analyzing JDK Dependencies 316
Identifying Built-in Modules 316
Using jdeps 318
Migrating an Application 321
Determining the Order 321
Exploring a Bottom-Up Migration Strategy 322
Exploring a Top-Down Migration Strategy 324
Splitting a Big Project into Modules 325
Failing to Compile with a Cyclic Dependency 326
Creating a Service 328
Declaring the Service Provider Interface 329
Creating a Service Locator 330
Invoking from a Consumer 332
Adding a Service Provider 333
Merging Service Locator and Consumer 334
Reviewing Services 337
Summary 337
Exam Essentials 338
Review Questions 339
Chapter 7 Concurrency 345
Introducing Threads 347
Distinguishing Thread Types 348
Understanding Thread Concurrency 348
Defining a Task with Runnable 349
Creating a Thread 351
Polling with Sleep 353
Creating Threads with the Concurrency API 355
Introducing the Single-Thread Executor 355
Shutting Down a Thread Executor 356
Submitting Tasks 357
Waiting for Results 358
Submitting Task Collections 362
Scheduling Tasks 363
Increasing Concurrency with Pools 366
Writing Thread-Safe Code 367
Understanding Thread-Safety 367
Protecting Data with Atomic Classes 369
Improving Access with Synchronized Blocks 371
Synchronizing on Methods 373
Understanding the Lock Framework 375
Orchestrating Tasks with a CyclicBarrier 379
Using Concurrent Collections 382
Understanding Memory Consistency Errors 383
Working with Concurrent Classes 383
Obtaining Synchronized Collections 388
Identifying Threading Problems 389
Understanding Liveness 390
Managing Race Conditions 393
Working with Parallel Streams 394
Creating Parallel Streams 395
Performing a Parallel Decomposition 396
Processing Parallel Reductions 398
Avoiding Stateful Operations 403
Summary 404
Exam Essentials 405
Review Questions 406
Chapter 8 I/O 419
Understanding Files and Directories 420
Conceptualizing the File System 420
Storing Data as Bytes 422
Introducing the File Class 422
Introducing I/O Streams 426
Understanding I/O Stream Fundamentals 426
Learning I/O Stream Nomenclature 427
Common I/O Stream Operations 433
Reading and Writing Data 433
Closing the Stream 435
Manipulating Input Streams 436
Flushing Output Streams 438
Reviewing Common I/O Stream Methods 439
Working with I/O Stream Classes 440
Reading and Writing Binary Data 440
Buffering Binary Data 441
Reading and Writing Character Data 443
Buffering Character Data 444
Serializing Data 445
Printing Data 452
Review of Stream Classes 457
Interacting with Users 458
Printing Data to the User 459
Reading Input as a Stream 460
Closing System Streams 460
Acquiring Input with Console 461
Summary 464
Exam Essentials 464
Review Questions 466
Chapter 9 NIO.2 475
Introducing NIO.2 476
Introducing Path 477
Creating Paths 478
Understanding Common NIO.2 Features 483
Interacting with Paths 486
Viewing the Path with toString(), getNameCount(), and getName() 486
Creating a New Path with subpath() 487
Accessing Path Elements with getFileName(), getParent(), and getRoot() 488
Checking Path Type with isAbsolute() and toAbsolutePath() 490
Joining Paths with resolve() 491
Deriving a Path with relativize() 491
Cleaning Up a Path with normalize() 493
Retrieving the File System Path with toRealPath() 493
Reviewing Path Methods 494
Operating on Files and Directories 495
Checking for Existence with exists() 495
Testing Uniqueness with isSameFile() 496
Making Directories with createDirectory() and createDirectories() 497
Copying Files with copy() 498
Moving or Renaming Paths with move() 500
Deleting a File with delete() and deleteIfExists() 500
Reading and Writing Data with newBufferedReader() and newBufferedWriter() 501
Reading a File with readAllLines() 502
Reviewing Files Methods 502
Managing File Attributes 503
Discovering File Attributes 503
Improving Attribute Access 506
Applying Functional Programming 508
Listing Directory Contents 508
Traversing a Directory Tree 510
Searching a Directory with find() 514
Reading a File with lines() 515
Comparing Legacy java.io.File and NIO.2 Methods 517
Summary 518
Exam Essentials 518
Review Questions 520
Chapter 10 JDBC 529
Introducing Relational Databases and SQL 530
Identifying the Structure of a Relational Database 532
Writing Basic SQL Statements 533
Introducing the Interfaces of JDBC 535
Connecting to a Database 537
Building a JDBC URL 537
Getting a Database Connection 539
Working with a PreparedStatement 542
Obtaining a PreparedStatement 543
Executing a PreparedStatement 543
Working with Parameters 546
Updating Multiple Times 549
Getting Data from a ResultSet 551
Reading a ResultSet 551
Getting Data for a Column 555
Using Bind Variables 556
Calling a CallableStatement 557
Calling a Procedure without Parameters 558
Passing an IN Parameter 559
Returning an OUT Parameter 559
Working with an INOUT Parameter 560
Comparing Callable Statement Parameters 560
Closing Database Resources 561
Summary 564
Exam Essentials 564
Review Questions 566
Chapter 11 Security 575
Designing a Secure Object 576
Limiting Accessibility 576
Restricting Extensibility 577
Creating Immutable Objects 578
Cloning Objects 581
Introducing Injection and Input Validation 583
Preventing Injection with a PreparedStatement 583
Invalidating Invalid Input with Validation 586
Working with Confidential Information 588
Guarding Sensitive Data from Output 589
Protecting Data in Memory 589
Limiting File Access 590
Serializing and Deserializing Objects 591
Specifying Which Fields to Serialize 591
Customizing the Serialization Process 592
Pre/Post-Serialization Processing 593
Reviewing Serialization Methods 596
Constructing Sensitive Objects 597
Making Methods final 598
Making Classes final 598
Making the Constructor private 599
Preventing Denial of Service Attacks 600
Leaking Resources 600
Reading Very Large Resources 600
Including Potentially Large Resources 601
Overflowing Numbers 601
Wasting Data Structures 602
Summary 603
Exam Essentials 604
Review Questions 605
Appendices 611
Appendix A The Upgrade Exam 611
Working with Local Variable Type Inference 612
Type Inference of var 613
Examples with var 614
Review of var Rules 617
Introducing Modules 617
Exploring a Module 618
Benefits of Modules 619
Creating and Running a Modular Program 621
Creating the Files 622
Compiling Our First Module 623
Running Our First Module 625
Packaging Our First Module 627
Updating Our Example for Multiple Modules 628
Updating the Feeding Module 628
Creating a Care Module 629
Creating the Talks Module 631
Creating the Staff Module 634
Diving into the module-info File 635
exports 635
requires transitive 636
provides, uses, and opens 639
Discovering Modules 639
The java Command 639
The jar Command 643
The jdeps Command 643
The jmod Command 645
Reviewing Command-Line Options 645
Summary 648
Exam Essentials 649
Review Questions 650
Appendix B Answers to Review Questions 657
Chapter 1: Java Fundamentals 658
Chapter 2: Annotations 662
Chapter 3: Generics and Collections 665
Chapter 4: Functional Programming 669
Chapter 5: Exceptions, Assertions, and Localization 672
Chapter 6: Modular Applications 676
Chapter 7: Concurrency 678
Chapter 8: I/O 682
Chapter 9: NIO.2 685
Chapter 10: JDBC 689
Chapter 11: Security 691
Appendix A: The Upgrade Exam 693
Index 697