32,99 €
Complete, trusted preparation for the Java Programmer II exam OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide is your comprehensive companion for preparing for Exam 1Z0-809 as well as upgrade Exam 1Z0-810 and Exam 1Z0-813. With full coverage of 100% of exam objectives, this invaluable guide reinforces what you know, teaches you what you don't know, and gives you the hands-on practice you need to boost your skills. Written by expert Java developers, this book goes beyond mere exam prep with the insight, explanations and perspectives that come from years of experience. You'll review the basics of object-oriented programming, understand functional programming, apply your knowledge to database work, and much more. From the basic to the advanced, this guide walks you through everything you need to know to confidently take the OCP 1Z0-809 Exam and upgrade exams 1Z0-810 and 1Z0-813. Java 8 represents the biggest changes to the language to date, and the latest exam now requires that you demonstrate functional programming competence in order to pass. This guide has you covered, with clear explanations and expert advice. * Understand abstract classes, interfaces, and class design * Learn object-oriented design principles and patterns * Delve into functional programming, advanced strings, and localization * Master IO, NIO, and JDBC with expert-led database practice If you're ready to take the next step in your IT career, OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide is your ideal companion on the road to certification.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 1039
Veröffentlichungsjahr: 2015
Jeanne Boyarsky
Scott Selikoff
Senior Acquisitions Editor: Kenyon Brown Development Editor: Gary Schwartz Technical Editors: Ernest Friedman-Hill and Matt Dalen Production Editor: Dassi Zeidel Copy Editor: Linda Recktenwald Editorial Manager: Mary Beth Wakefield Production Manager: Kathleen Wisor Associate Publisher: Jim Minatel Supervising Producer: Rich Graves Book Designers: Judy Fung and Bill Gibson Proofreader: Josh Chase, Word One New York Indexer: Ted Laux Project Coordinator, Cover: Brent Savage Cover Designer: Wiley Cover Image: ©Getty Images Inc./Jeremy Woodhouse
Copyright © 2016 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-119-06790-0 ISBN: 978-1-119-06788-7 (ebk.) ISBN: 978-1-119-06789-4 (ebk.)
Manufactured in the United States of America
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (877) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2015951679
TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Oracle and Java are registered trademarks of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
To the programmers on FIRST robotics team FRC 694 StuyPulse
— Jeanne
To my newborn daughters Olivia and Sophia, I love you both more and more every day.
— Scott
Jeanne and Scott would like to thank numerous individuals for their contribution to this book. Thank you, Gary Schwartz, for guiding us through the process and making the book better in so many ways. Thank you, Ernest Friedman-Hill, for being our Technical Editor as we wrote this book. Ernest pointed out many subtle errors in addition to the big ones. And thank you, Matt Dalen, for being our Technical Proofreader and finding the errors that managed to sneak by even Ernest. This book also wouldn't be possible without many people at Wiley, including Kenyon Brown, Dassi Zeidel, Mary Beth Wakefield, and so many others.
Jeanne would personally like to thank Chris Kreussling and Elena Felder for their feedback on early drafts of the trickier material. Elena even helped figure out a good way to explain upper bounds. Roel De Nijs reviewed the Java 8 date/time material for words that native English speakers take for granted, and he responded to lots of posts in the CodeRanch.com OCA forum on our first book. To all of the people at work and at CodeRanch.com who were so excited for me about writing this book, you made it even more exciting when we published our first book. Jeanne would like to thank the members of FIRST robotics FRC team 694 for their support. It was an awesome feeling seeing high school students pore over the book while waiting for dinner the night the hard copy arrived. Go StuyPulse! See if you can find JoeBot in this book. Finally, Jeanne would like to thank Scott for being a great co-author again.
Scott could not have reached this point without the help of a small army of people, led by his perpetually understanding wife Patti, the most wonderful mother their twin daughters could ask for. Professor Johannes Gehrke of Cornell University always believed in him and knew he would excel in his career. Jeanne's patience and striving for excellence was invaluable in creating this second book. A big thanks to fellow new father Matt Dalen, who has been a wonderful friend, sounding board, and technical reviewer over the last year. Joel McNary introduced Scott to CodeRanch.com and encouraged him to post regularly—a step that changed his life. Finally, Scott would like to thank his mother and retired teacher Barbara Selikoff, for teaching him the value of education, and his father Mark Selikoff, for instilling in him the benefits of working hard.
Finally, both Jeanne and Scott would like to give a big thank-you to the readers of our OCA 8 book. Hearing from all of you who enjoyed the book and passed the exam was great. We'd also like to thank those who pointed out errors and made suggestions for improvements in our OCA book. As of July 2015, the top three were Mushfiq Mammadov, Elena Felder, and Cédric Georges. Thank you for your attention to detail! We also would like to thank Mathias Bader, Maaike Zijderveld, Vincent Botteman, Edward Rance, Gabriel Jesus, Ilya Danilov, Marc ter Braak, Dominik Bauer, Saad Benbouzid, Evgeny Kapinos, Helen Colson, Alex Lord, and Kevin Abel.
Jeanne Boyarsky has worked as a Java developer for more than 13 years at a bank in New York City, where she develops, mentors, and conducts training. Besides being a senior moderator at CodeRanch.com in her free time, she leads the team that works on the forum's code base. Jeanne also mentors the programming division of a FIRST robotics team, where she works with students just getting started with Java.
Jeanne got her Bachelor of Arts degree in 2002 in Computer Science and her Master's in Computer Information Technology in 2005. She enjoyed getting her Master's degree in an online program while working full time. This was before online education was cool! Jeanne is also a Distinguished Toastmaster and a Scrum Master. You can find out more about Jeanne at http://www.coderanch.com/how-to/java/BioJeanneBoyarsky.
Scott Selikoff is a professional software consultant, author, and owner of Selikoff Solutions, LLC, which provides software development solutions to businesses in the tri-state New York City area. Skilled in a plethora of software languages and platforms, Scott specializes in database-driven systems, web-based applications, and service-oriented architectures.
A native of Toms River, New Jersey, Scott achieved his Bachelor of Arts from Cornell University in Mathematics and Computer Science in 2002, after three years of study. In 2003, he received his Master of Engineering in Computer Science, also from Cornell University.
As someone with a deep love of education, Scott has always enjoyed teaching others new concepts. He's given lectures at Cornell University and Rutgers University, as well as conferences including The Server Side Java Symposium. Scott lives in New Jersey with his loving wife, amazing twin baby girls, and two very playful dogs. You can find out more about Scott at http://www.linkedin.com/in/selikoff.
Jeanne and Scott are both moderators on the CodeRanch.com forums, and they can be reached there for questions and comments. They also co-author a technical blog called Down Home Country Coding at http://www.selikoff.net.
Introduction
The OCP Exam
Scheduling the Exam
The Day of the Exam
Finding Out Your Score
Exam Questions
Getting Started
Getting Help
Who Should Buy This Book
How This Book Is Organized
Conventions Used in This Book
OCP Exam Objectives
Assessment Test
Answers to Assessment Test
Chapter 1 Advanced Class Design
Reviewing OCA Concepts
Using
instanceof
Understanding Virtual Method Invocation
Annotating Overridden Methods
Coding
equals
,
hashCode
, and
toString
Working with
Enum
s
Creating Nested Classes
Summary
Exam Essentials
Review Questions
Chapter 2 Design Patterns and Principles
Designing an Interface
Introducing Functional Programming
Implementing Polymorphism
Understanding Design Principles
Working with Design Patterns
Summary
Exam Essentials
Review Questions
Chapter 3 Generics and Collections
Reviewing OCA Collections
Working with Generics
Using Lists, Sets, Maps, and Queues
Comparator
vs.
Comparable
Searching and Sorting
Additions in Java 8
Summary
Exam Essentials
Review Questions
Chapter 4 Functional Programming
Using Variables in Lambdas
Working with Built-In Functional Interfaces
Returning an
Optional
Using Streams
Working with Primitives
Working with Advanced Stream Pipeline Concepts
Summary
Exam Essentials
Review Questions
Chapter 5 Dates, Strings, and Localization
Working with Dates and Times
Reviewing the
String
class
Adding Internationalization and Localization
Summary
Exam Essentials
Review Questions
Chapter 6 Exceptions and Assertions
Reviewing Exceptions
Creating Custom Exceptions
Using Multi-catch
Using Try-With-Resources
Rethrowing Exceptions
Working with Assertions
Summary
Exam Essentials
Review Questions
Chapter 7 Concurrency
Introducing Threads
Creating Threads with the
ExecutorService
Synchronizing Data Access
Using Concurrent Collections
Working with Parallel Streams
Managing Concurrent Processes
Identifying Threading Problems
Summary
Exam Essentials
Review Questions
Chapter 8 IO
Understanding Files and Directories
Introducing Streams
Working with Streams
Interacting with Users
Summary
Exam Essentials
Review Questions
Chapter 9 NIO.2
Introducing NIO.2
Interacting with Paths and Files
Understanding File Attributes
Presenting the New Stream Methods
Comparing Legacy
File
and NIO.2 Methods
Summary
Exam Essentials
Review Questions
Chapter 10 JDBC
Introducing Relational Databases and SQL
Introducing the Interfaces of JDBC
Connecting to a Database
Obtaining a
Statement
Executing a
Statement
Getting Data from a
ResultSet
Closing Database Resources
Dealing with Exceptions
Summary
Exam Essentials
Review Questions
Appendix A Answers to Review Questions
Chapter 1: Advanced Class Design
Chapter 2: Design Patterns and Principles
Chapter 3: Generics and Collections
Chapter 4: Functional Programming
Chapter 5: Dates, Strings, and Localization
Chapter 6: Exceptions and Assertions
Chapter 7: Concurrency
Chapter 8: IO
Chapter 9: NIO.2
Chapter 10: JDBC
Appendix B Study Tips
Studying for the Test
Taking the Test
Appendix C Upgrading from Java 6 or Earlier
Enhancing the Java Language
Formatting and Parsing
Applying Locks
Working with Directories
Summary
Exam Essentials
Review Questions
Answers to Review Questions
Advert
EULA
Introduction
Table I.1
Chapter 1
Table 1.1
Table 1.2
Chapter 2
Table 2.1
Chapter 3
Table 3.1
Table 3.2
Table 3.3
Table 3.4
Table 3.5
Table 3.6
Table 3.7
Table 3.8
Table 3.9
Table 3.10
Table 3.11
Table 3.12
Chapter 4
Table 4.1
Table 4.2
Table 4.3
Table 4.4
Table 4.5
Table 4.6
Table 4.7
Table 4.8
Table 4.9
Table 4.10
Table 4.11
Chapter 5
Table 5.1
Table 5.2
Table 5.3
Table 5.4
Table 5.5
Table 5.6
Table 5.7
Table 5.8
Table 5.9
Table 5.10
Table 5.11
Chapter 6
Table 6.1
Table 6.2
Table 6.3
Table 6.4
Table 6.5
Chapter 7
Table 7.1
Table 7.2
Table 7.3
Table 7.4
Table 7.5
Table 7.6
Table 7.7
Table 7.8
Table 7.9
Table 7.10
Table 7.11
Table 7.12
Chapter 8
Table 8.1
Table 8.2
Chapter 9
Table 9.1
Table 9.2
Table 9.3
Table 9.4
Table 9.5
Chapter 10
Table 10.1
Table 10.2
Table 10.3
Table 10.4
Table 10.5
Table 10.6
Table 10.7
Table 10.8
Appendix B
Table B.1
Appendix C
Table C.1
Table C.2
Table C.3
Introduction
Figure I.1
Names for the exam
Figure I.2
Exam prerequisites
Chapter 2
Figure 2.1
Lambda syntax omitting optional parts
Figure 2.2
Lambda syntax, including optional parts
Figure 2.3
Object vs. reference
Figure 2.4
Good design—A
Cat
is-a
Pet
, because
Cat
extends
Pet
.
Figure 2.5
Poor design—A
Tiger
is-a
Pet
, because
Tiger
extends
Pet
.
Figure 2.6
Still poor design—All
Pet
s are now
Feline
s.
Figure 2.7
Good design-Pet is now an interface.
Figure 2.8
Bird
has-a
Beak
.
Figure 2.9
FoodFactory
data model
Chapter 3
Figure 3.1
The
Collection
interface is the root of all collections except maps.
Figure 3.2
Example of a
List
Figure 3.3
Example of a
Set
Figure 3.4
Examples of a
HashSet
and
TreeSet
Figure 3.5
Example of a
Queue
Figure 3.6
Working with a queue
Figure 3.7
Working with a stack
Figure 3.8
Example of a
Map
Chapter 4
Figure 4.1
Optional
Figure 4.2
Stream pipeline
Figure 4.3
Steps in running a stream pipeline
Figure 4.4
A stream pipeline with a limit
Figure 4.5
Stream pipeline with multiple intermediate operations
Chapter 5
Figure 5.1
Period format
Figure 5.2
How daylight savings time works
Figure 5.3
Locale
string formats
Chapter 6
Figure 6.1
Categories of exceptions
Figure 6.2
The syntax of a try statement
Figure 6.3
The syntax of multi-catch
Figure 6.4
The syntax of a basic try-with-resources
Figure 6.5
The syntax of try-with-resources including
catch
/
finally
Chapter 7
Figure 7.1
Process model
Figure 7.2
ExecutorService
life cycle
Figure 7.3
Lack of thread synchronization
Figure 7.4
Thread synchronization using atomic operations
Figure 7.5
Race condition on user creation
Chapter 8
Figure 8.1
Directory and file hierarchy
Figure 8.2
Visual representation of a stream
Figure 8.3
Diagram of
java.io
classes
Chapter 9
Figure 9.1
NIO.2 class and interface relationships
Figure 9.2
File and directory as a tree structure
Chapter 10
Figure 10.1
Tables in our relational database
Figure 10.2
Key JDBC interfaces
Figure 10.3
The JDBC URL format
Figure 10.4
The
ResultSet
cursor
Figure 10.5
First and last
Figure 10.6
Absolute rows
Figure 10.7
Negative absolute rows
Figure 10.8
Animal table
Appendix B
Figure B.1
Tracking objects and references
Figure B.2
Marking indices
Appendix C
Figure C.1
The structure of a
switch
statement
Cover
Table of Contents
Chapter
xix
xx
xxi
xxii
xxiii
xxiv
xxv
xxvi
xxvii
xxviii
xxix
xxx
xxxi
xxxii
xxxiii
xxxiv
xxxv
xxxvi
xxxvii
xxxviii
xxxix
xl
xli
xlii
xliii
xliv
xlv
xlvi
xlvii
xlviii
xlix
l
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
Java recently celebrated its 20th birthday, since it was “born” in 1995. As with anything 20 years old, there is a good amount of history and variation between different versions of Java. Over the years, the certification exams have changed to cover different topics. The names of the exams have even changed. This book covers the Java 8 OCP exam along with the upgrade exams to Java 8.
If you read about the exam on the web, you may see information about the older names for the exam. The name changes are shown in Figure I.1. Here’s what happened. Back when Sun Microsystems owned Java, they used to have two exams. The SCJA (Sun Certified Java Associate) was meant for new programmers and the SCJP (Sun Certified Java Programmer) was meant for those who wanted broader knowledge. When Oracle bought Sun Microsystems, they renamed all of the exams from Sun to Oracle, giving us the OCJA (Oracle Certified Java Associate) and OCJP (Oracle Certified Java Programmer).
Figure I.1 Names for the exam
Then Oracle made two strategic decisions with Java 7. They decided to stop updating the OCJA exam. They also decided to cover more in the programmer space, and they split it into two exams. Now you first take the OCAJP (Oracle Certified Associate Java Programmer), also known as Java Programmer I or OCA. Then you take the OCPJP (Oracle Certified Professional Java Programmer), also known as Java Programmer II or OCP, and that’s what this book is about. Most people refer to the current exams as OCA 8 and OCP 8.
Oracle also has upgrade exams in case you took an older version of the SCJP or OCPJP and you want to upgrade. While most people refer to them as the Java 8 upgrade exam, there are really two exams, and you choose the correct one based on the certification you currently hold. Table I.1 describes the exams that this book covers, while Figure I.2 helps you decide what exam to take next, assuming that you have passed a prior Java certification exam. Our book is designed to help you prepare for any of these three exams, all of which result in you being OCP 8 certified.
Table I.1 Exams this book covers
Exam Code
Name
Who Should Take
1Z0–809
Java Programmer II
Holders of the OCA
8
certification
1Z0–810
Upgrade Java SE 7 to Java SE 8 OCP Programmer
Holders of the OCPJP
7
certification
1Z0–813
Upgrade to Java SE 8 OCP (Java SE 6 and all prior versions)
Holders of any of the following certifications:
SCJP/OCJP 6
SCJP/OCJP 5
SCJP 1.4
Any older SCJP certs
Figure I.2 Exam prerequisites
We try to keep the history to a minimum in this book. There are some places on the exam where you need to know both an old way and a new way of doing things. When that happens, we will be sure to tell you what version of Java introduced which way. We will also let you know about topics that are not on the exam anymore, in case you see questions on them in the older free online mock exams.
All you need to do to become an Oracle Certified Professional for Java 8 is to pass an exam! That’s it.
Oracle has a tendency to fiddle with the length of the exam and the passing score once it comes out. Since it’s pretty much guaranteed that whatever we tell you here will become obsolete, we will instead give you a feel for the range. The OCP exam has varied between 60 and 90 questions since it was first introduced. The score to pass the exam has varied between 60 percent and 80 percent. The time allowed to take the exam has varied from two hours to two-and-a-half hours.
Oracle has a tendency to tweak the exam objectives over time as well. They do make minor additions and deletions from what is covered on the exam. For example, serialization has been added and removed from the objectives many times over the life of the OCP. As of this writing, it is on the exam.
While there will likely be minor changes to the scope of the exam, they certainly aren’t a secret. We’ve created a book page on our blog: http://www.selikoff.net/ocp. If there are any changes to the topics on the exam after this book is published, we will note them there.
That book page also contains a link to the official exam page, so you can check the length and passing score that Oracle has chosen for the moment. Finally, all known errata and links to discussion can be found at http://www.coderanch.com.
Pearson VUE administers the exam, and it can be taken at any Pearson VUE testing center. To find a testing center or to register for the exam, go to http://pearsonvue.com. Choose IT and then Oracle. If you haven’t been to the test center before, we recommend visiting in advance. Some testing centers are nice and professionally run. Others stick you in a closet with lots of people talking around you. You don’t want to be taking the test with someone complaining about his or her broken laptop nearby!
At this time, you can reschedule the exam without penalty until up to 24 hours in advance. This means that you can register for a convenient time slot well in advance knowing that you can delay taking the exam if you aren’t ready by that time. Rescheduling is easy and can be done completely on the Pearson VUE website. This may change, so check the rules before paying.
When you go to take the exam, remember to bring two forms of ID, including one that is government issued. See Pearson’s list of what is an acceptable ID at http://www.pearsonvue.com/policies/1S.pdf. Try not to bring too much extra with you, because it will not be allowed into the exam room. While you will be allowed to check your belongings, it is better to leave extra items at home or in your car.
You will not be allowed to bring paper, your phone, and so on into the exam room with you. Some centers are stricter than others. At one center, tissues were even taken away from us! Most centers allow you to keep your ID and money. They watch you taking the exam, though, so don’t even think about writing notes on money. Some centers place these articles in a locker and give you the key, whereas others just throw them in an administrator’s desk drawer. Suffice it to say, if you have something that you really don’t want to lose, we recommend that you leave it at home.
The exam center will give you writing materials to use during the exam. These are to be used as scratch paper during the exam to figure out answers and to keep track of your thought process. The exam center will dispose of them at the end. Notice how we said “writing materials” rather than “pen and paper.” Actually getting pen and paper is rare. Most centers provide a small erasable board and a dry erase marker. Before going into the exam room, we recommend testing that the marker writes and erases.
As we alluded to earlier, some exam centers are more professionally run than others, so we recommend visiting your local exam center before scheduling the exam if you have never been there before. Some exam centers also have problems keeping the temperature at a comfortable level. Regardless of whether it is winter or summer, when you take the exam, we strongly recommend that you dress in layers, such as a long-sleeve shirt or sweatshirt over a short-sleeve shirt. This way, you can add/remove layers of clothing to adjust for your own comfort.
Some exam centers are located in quiet suburban areas while others are near busy city streets with noisy traffic. Furthermore, you might get lucky and be the only person in your exam room the day you show up, or you might be unlucky and have 10 other people in the room coming and going at different times. If you are someone who gets easily distracted by noise and other people moving around, we recommend that you bring a pair of earplugs for the exam. Some exam centers will even offer you a pair of sterile earplugs if you ask. Double-check with your test administrator before using your own, so that they don’t think you’re trying to cheat!
While many exam centers permit bathroom breaks during the exam with permission, very few allow you to bring drinks inside. Since these exams are at least two hours long, make sure that you are well hydrated before you arrive. Just be aware that if you do need to use the facilities, your exam clock will not be paused.
Finally, if you have any issues like it being unbearably hot, cold, or noisy in your exam room, you should contact Oracle after you finish taking the exam to let them know the quality of the particular testing center was poor. Some exam centers have shown improvement after receiving such reports.
In the past, you would find out whether you passed or not right after finishing the exam. Now you have to wait nervously until you can check your score online.
If you go to the Pearson VUE website, it will just show a status of “Taken” rather than your result. Oracle uses a separate system for scores. You’ll need to go to http://certview.oracle.com to find out whether you passed and your score. It doesn’t update immediately upon taking the test, but we haven’t heard of it taking more than an hour. In addition to your score, you’ll also see objectives for which you got a question wrong and instructions on how to get a hardcopy certificate.
At some point, you’ll get an electronic certificate, and some more time after that, you’ll receive a printed certificate. Sound vague? It is. The times reported to receive certificates vary widely.
The OCP exam consists of multiple-choice questions. There are typically four to six possible answers for each question. If a question has more than one correct answer, the question specifically states exactly how many correct answers there are. This book does not do that. We say “choose all that apply” if there might be more than one correct answer to make the questions harder. This means that the questions in this book are generally harder than those on the exam. The idea is to give you more practice so that you can spot the correct answer more easily on the real exam.
You can right-click questions to cross out answers. This lets you mark answers as incorrect as you go so that you have less to think about as you read. It also helps you remember what you’ve eliminated when you go back to questions.
The exam uses two different formats for identifying line numbers. We use both approaches in this book to get you prepared. The first approach is a comment at the end of a line such as this:
list.stream() .map(s-> s.length()) // k1 .forEach(System.out::println);
One or more answer choices will refer to k1. With this approach, imports will be provided for any class definitions. For code snippets, you can assume that all necessary surrounding code is implied. The other approach is placing line numbers at the beginning of each line, like so:
4: list.stream() 5: .map(s-> s.length()) 6: .forEach(System.out::println); With this approach, the line numbers often begin with numbers higher than 1. This is to indicate that you are looking at a code snippet rather than a complete class.
If you read about older versions of the exam online, you might see references to drag-and-drop questions. These questions had you do a puzzle on how to complete a piece of code. There was also a bug in the exam software that caused your answers to be lost if you reviewed them. Luckily, these are no longer on the exam.
We recommend reading Appendix B, “Study Tips,” before diving into the technical material in this book. Knowing how to approach studying will help you make better use of your study time.
Next, make sure that you have downloaded version 8 of the JDK. If you learned Java some time ago, you might have version 7 or even earlier. Many of the examples won’t even compile in Java 7.
Also, please check our book page to make sure that Oracle hasn’t changed the objectives. For example, if Oracle changed their mind on whether to include serialization yet again, you’d want to know that before studying. We will post any updates that you should know about at http://www.selikoff.net/ocp.
Both of the authors are moderators at CodeRanch.com, a very large and active programming forum that is very friendly toward Java beginners. It has a forum just for this exam called “SCJP/OCPJP.” It also has a forum called “Java in General” for non-exam-specific questions. As you read the book, feel free to ask your questions in either of those forums. It could be that you are having trouble compiling a class or that you are just plain confused about something. You’ll get an answer from a knowledgeable Java programmer. It might even be one of us.
If you want to become Oracle Certified Java Programmer, this book is definitely for you. If you want to acquire a solid foundation in Java, and your goal is to prepare for the exam, this book is also for you. You’ll find clear explanations of the concepts you need to grasp and plenty of help to achieve the high level of professional competency you need in order to succeed in your chosen field.
This book is intended to be understandable to anyone who knows basic Java. Since the exam has a prerequisite of the Associate exam, we assume that you have a good handle on that much Java. We don’t assume that you know the Java 8–specific parts of the Associate exam, since some readers are taking the upgrade exam and are new to Java 8.
This book is for anyone from high school students to those beginning their programming journey to experienced professionals who need a review for the certification.
This book consists of 10 chapters plus supplementary information: a glossary, this introduction, four appendices, and the assessment test after this introduction. You might have noticed that there are more than 10 exam objectives. We split up what you need to know to make it easy to learn and remember. Each chapter begins with a list of the objectives that are covered in that chapter.
Java 8 lambdas and functional programming streams are prevalent throughout the exam and appear in questions on many topics. You have to know this topic as well as you knew loops on the OCA exam. We’ve made sure to use them in many chapters so that you will be ready. For example, Chapter 2 reviews functional interfaces and Chapter 3 introduces method references. Chapter 4 covers the Streams API in detail. Later chapters use “the new approach” to writing code often so that you keep using it and become fluent.
The chapters are organized as follows:
Chapter 1: Advanced Class Design This chapter covers inheritance, including abstract classes and the final keyword. It also discusses inner classes and enums.
Chapter 2: Design Patterns and Principles This chapter teaches you best practices for designing and writing applications that lead to code that is easier to understand and more maintainable.
Chapter 3: Generics and Collections This chapter goes beyond ArrayList and shows Sets, Maps, and Queues. It also shows new methods in Java 8 on these classes.
Chapter 4: Functional Programming This chapter explains lambdas and stream pipelines in detail. It also covers the built-in functional interfaces and the Optional class.
Chapter 5: Dates, Strings, and Localization This chapter shows the improved date and time classes in Java 8. It also covers more advanced String concepts that you need to know and how to make your application work in multiple languages.
Chapter 6: Exceptions and Assertions This chapter shows more advanced syntax for exceptions than what appears on the OCA. It also covers how to use assertions to verify the state of your program.
Chapter 7: Concurrency This chapter introduces the concept of thread management, and it teaches you how to write multi-threaded programs using the Concurrency API.
Chapter 8: IO This chapter introduces you to managing files and directories using the java.io API. It also instructs you on how to read and write file data using I/O streams.
Chapter 9: NIO.2 This chapter shows you how to manage files and directories using the newer NIO.2 API. It includes techniques for reading and writing file attributes, as well as traversing and searching for files using lambdas and streams.
Chapter 10: JDBC This chapter provides the basics of working with databases in Java including different types of ResultSets.
Appendix A: Answers to Review Questions This appendix lists the answers to the Review Questions along with explanations.
Appendix B: Study Tips This appendix covers how to approach studying for the exam.
Appendix C: Upgrading from Java 6 or Earlier This appendix covers topics that are on the upgrade exam for those holding a Java 6 or earlier programmer certification. These topics are not on the main OCP 8 exam, nor are they on the upgrade exam for holders of the OCP 7 certification.
At the end of each chapter, you’ll find a few elements that you can use to prepare for the exam:
Summary This section reviews the most important topics that were covered in the chapter, and it serves as a good review.
Exam Essentials This section summarizes the main points that were covered in the chapter. You should be able to convey the information requested.
Review Questions Each chapter concludes with at least 20 Review Questions. You should answer these questions and check your answers against the ones provided after the questions. If you can’t answer at least 80 percent of these questions correctly, go back and review the chapter, or at least review those sections that seem to be giving you difficulty.
The Review Questions, Assessment Test, and other testing elements included in this book are not derived from the real exam questions, so don’t memorize the answers to these questions and assume that doing so will enable you to pass the exam. You should learn the underlying topic, as described in the text of the book. This will let you answer the questions provided with this book and pass the exam. Learning the underlying topic is also the approach that will serve you best in the workplace—the ultimate goal of a certification.
To get the most out of this book, you should read each chapter from start to finish before going to the end-of-chapter elements. They are most useful for checking and reinforcing your understanding. Even if you’re already familiar with a topic, you should at least skim the chapter. There are a number of subtleties to Java that you may not encounter even when working with Java for years.
The interactive online learning environment that accompanies OCP Oracle Certified Professional SE 8 Programmer II: Exam 1Z0-809 provides a test bank with study tools to help you prepare for the certification exam, and it increases your chances of passing it the first time! The test bank includes the following:
Sample Tests All of the questions in this book are provided, including the Assessment Test, which you’ll find at the end of this introduction, and the Chapter Tests, which include the Review Questions at the end of each chapter. In addition, there are three Practice Exams—180 questions in total! Use these questions to test your knowledge of the study guide material. The online test bank runs on multiple devices.
Flashcards Over 250 questions are provided in digital flashcard format (a question followed by a single correct answer). You can use the flashcards to reinforce your learning and provide last-minute test prep before the exam.
Other Study Tools Several bonus study tools are included:
Glossary A glossary of key terms from this book and their definitions is available as a fully searchable PDF.
Nashorn Materials Early drafts of the exam objectives had Nashorn on the exam for using JavaScript with Java. Since it isn’t on the exam anymore, this topic isn’t in the printed book. The appendix is available in the bonus contents in case you want to learn about this topic, independent of the exam.
Go to http://sybextestbanks.wiley.com to register and gain access to this interactive online learning environment and test bank with study tools.
This book uses certain typographic styles in order to help you quickly identify important information and to avoid confusion over the meaning of words such as on-screen prompts. In particular, look for the following styles:
Italicized text
indicates key terms that are described at length for the first time in a chapter. (Italics are also used for emphasis.)
A monospaced font
indicates code or command-line text.
Italicized monospaced text
indicates a variable.
In addition to these text conventions, which can apply to individual words or entire paragraphs, a few conventions highlight segments of text:
A note indicates information that’s useful or interesting. It is often something to which you should pay special attention for the exam.
A sidebar is like a note but longer. The information in a sidebar is useful, but it doesn’t fit into the main flow of the text.
A real world scenario is a type of sidebar that describes a task or an example that’s particularly grounded in the real world. This is something that is useful in the real world but is not going to show up on the exam.
This book has been written to cover every objective on the OCP 8 exam along with both upgrade exams.
The following table provides a breakdown of this book’s exam coverage for the OCP 8 (1Z0–809) exam, showing you the chapter where each objective or sub-objective is covered:
Exam Objective
Chapter
Java Class Design
Implement encapsulation
2
Implement inheritance including visibility modifiers and composition
1,2
Implement polymorphism
2
Override hashCode, equals, and toString methods from Object class
1
Create and use singleton classes and immutable classes
2
Develop code that uses static keyword on initialize blocks, variables, methods, and classes
1
Advanced Java Class Design
Develop code that uses abstract classes and methods
1
Develop code that uses final keyword
1
Create inner classes including static inner class, local class, nested class, and anonymous inner class
1
Use enumerated types including methods and constructors in an enum type
1
Develop code that declares, implements and/or extends interfaces and use the @Override annotation.
1,2
Create and use Lambda expressions
2,3
Generics and Collections
Create and use a generic class
3
Create and use ArrayList, TreeSet, TreeMap, and ArrayDeque objects
3
Use java.util.Comparator and java.lang.Comparable interfaces
3
Collections Streams and Filters
4
Iterate using forEach methods of Streams and List
3,4
Describe Stream interface and Stream pipeline
4
Filter a collection by using lambda expressions
3
Use method references with Streams
3,4
Lambda Built-in Functional Interfaces
Use the built-in interfaces included in the java.util.function package such as Predicate, Consumer, Function, and Supplier
2,4
Develop code that uses primitive versions of functional interfaces
4
Develop code that uses binary versions of functional interfaces
4
Develop code that uses the UnaryOperator interface
4
Java Stream API
Develop code to extract data from an object using peek() and map() methods including primitive versions of the map() method
4
Search for data by using search methods of the Stream classes including findFirst, findAny, anyMatch, allMatch, noneMatch
4
Develop code that uses the Optional class
4
Develop code that uses Stream data methods and calculation methods
4
Sort a collection using Stream API
4
Save results to a collection using the collect method and group/partition data using the Collectors class
4
Use of merge() and flatMap() methods of the Stream API
3,4
Exceptions and Assertions
Use try-catch and throw statements
6
Use catch, multi-catch, and finally clauses
6
Use Autoclose resources with a try-with-resources statement
6
Create custom exceptions and AutoCloseable resources
6
Test invariants by using assertions
6
Use Java SE 8 Date/Time API
Create and manage date-based and time-based events including a combination of date and time into a single object using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration
5
Work with dates and times across time zones and manage changes resulting from daylight savings including Format date and times values
5
Define and create and manage date-based and time-based events using Instant, Period, Duration, and TemporalUnit
5
Java I/O Fundamentals
Read and write data from the console
8
Use BufferedReader, BufferedWriter, File, FileReader, FileWriter, FileInputStream, FileOutputStream, ObjectOutputStream, ObjectInputStream, and PrintWriter in the java.io package.
8
Java File I/O (NIO.2)
Use Path interface to operate on file and directory paths
9
Use Files class to check, read, delete, copy, move, manage metadata of a file or directory
9
Use Stream API with NIO.2
9
Java Concurrency
Create worker threads using Runnable, Callable, and use an ExecutorService to concurrently execute tasks
7
Identify potential threading problems among deadlock, starvation, livelock, and race conditions
7
Use synchronized keyword and java.util.concurrent.atomic package to control the order of thread execution
7
Use java.util.concurrent collections and classes including CyclicBarrier and CopyOnWriteArrayList
7
Use parallel Fork/Join Framework
7
Use parallel Streams including reduction, decomposition, merging processes, pipelines and performance.
7
Building Database Applications with JDBC
Describe the interfaces that make up the core of the JDBC API including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations
10
Identify the components required to connect to a database using the DriverManager class (including the JDBC URL)
10
Submit queries and read results from the database (including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections)
10
Localization
Read and set the locale by using the Locale object
5
Create and read a Properties file
5
Build a resource bundle for each locale and load a resource bundle in an application
5
This table shows the chapter where each objective or sub-objective is covered for the upgrade exam from Java 7 to Java 8 OCP (1Z0–810):
Exam Objective
Chapter
Lambda Expressions
Describe and develop code that uses Java inner classes, including nested class, static class, local class, and anonymous classes
1
Describe and write functional interfaces
2
Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing
4
Using Built-in Lambda Types
Describe the interfaces of the java.util.function package
4
Develop code that uses the Function interface
4
Develop code that uses the Consumer interface
4
Develop code that uses the Supplier interface
4
Develop code that uses the UnaryOperator interface
4
Develop code that uses the Predicate interface
4
Develop code that uses the primitive and binary variations of the base interfaces of the java.util.function package
4
Develop code that uses a method reference, including refactoring a lambda expression to a method reference
3,4
Filtering Collections with Lambdas
Develop code that iterates a collection by using the forEach() method and method chaining
3
Describe the Stream interface and pipelines
4
Filter a collection by using lambda expressions
3
Identify the lambda operations that are lazy
4
Collection Operations with Lambda
Develop code to extract data from an object by using the map() method
3
Search for data by using methods such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()
4
Describe the unique characteristics of the Optional class
4
Perform calculations by using Java Stream methods, such as count(), max(), min(), average(), and sum()
4
Sort a collection by using lambda expressions
4
Develop code that uses the Stream.collect() method and Collectors class methods, such as averagingDouble(), groupingBy(), joining(), and partitioningBy()
4
Parallel Streams
Develop code that uses parallel streams
7
Implement decomposition and reduction in streams
4,7
Lambda Cookbook
Develop code that uses Java SE 8 collection improvements, including Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods
3
Develop code that uses Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods
9
Use the merge() and flatMap() methods
3,4
Develop code that creates a stream by using the Arrays.stream() and IntStream.range() methods
Method Enhancements
Add static methods to interfaces
2
Define and use a default method of an interface and describe the inheritance rules for the default method
2
Use Java SE 8 Date/Time API
Create and manage date- and time-based events, including a combination of date and time in a single object, by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration
5
Work with dates and times across time zones and manage changes resulting from daylight savings, including Format date and times values
5
Define, create, and manage date- and time-based events using Instant, Period, Duration, and TemporalUnit
5
If you are studying for the 1Z0–813 exam, you must read Appendix C. It covers topics that are on your exam but not the other exams covered by the book.
This table shows the chapter where each objective or sub-objective is covered for the upgrade exam from a Java 6 or lower certification to Java 8 OCP (1Z0–813).
Exam Objective
Chapter
Language Enhancements
Develop code that uses String objects in the switch statement, binary literals, and numeric literals, including underscores in literals
Appendix C
Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface
6
Develop code that handles multiple Exception types in a single catch block
6
Use static and default methods of an interface including inheritance rules for a default method
2
Concurrency
Use collections from the java.util.concurrent package with a focus on the advantages over and differences from the traditional java.util collections
7
Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks and java.util.concurrent.atomic packages to support lock-free thread-safe programming on single variables
Appendix C
Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools
7
Use the parallel Fork/Join Framework
7
Localization
Describe the advantages of localizing an application and developing code that defines, reads, and sets the locale with a Locale object
5
Build a resource bundle for a locale and call a resource bundle from an application
5
Create and manage date- and time-based events by using LocalDate, LocalTime, LocalDateTime, Instant, Period, and Duration, including a combination of date and time in a single object
5
Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes, including number and date format patterns
5, Appendix C
Work with dates and times across time zones and manage changes resulting from daylight savings
5
Java File I/O (NIO.2)
Operate on file and directory paths by using the Path class
9
Check, delete, copy, or move a file or directory by using the Files class
9
Recursively access a directory tree by using the DirectoryStream and FileVisitor interfaces
Appendix C
Find a file by using the PathMatcher interface, and use Java SE 8 I/O improvements, including Files.find(), Files.walk(), and lines() methods
9
Observe the changes in a directory by using the WatchService interface
Appendix C
Lambda
Define and write functional interfaces and describe the interfaces of the java.util.function package
3,4
Describe a lambda expression; refactor the code that uses an anonymous inner class to use a lambda expression; describe type inference and target typing
3,4
Develop code that uses the built-in interfaces included in the java.util.function package, such as Function, Consumer, Supplier, UnaryOperator, Predicate, and Optional APIs, including the primitive and binary variations of the interfaces
4
Develop code that uses a method reference, including refactoring a lambda expression to a method reference
3
Java Collections
Develop code that uses diamond with generic declarations
Appendix C
Develop code that iterates a collection, filters a collection, and sorts a collection by using lambda expressions
3
Search for data by using methods, such as findFirst(), findAny(), anyMatch(), allMatch(), and noneMatch()
4
Perform calculations on Java Streams by using count, max, min, average, and sum methods and save results to a collection by using the collect method and Collector class, including the averagingDouble, groupingBy, joining, partitioningBy methods
4
Develop code that uses Java SE 8 collection improvements, including the Collection.removeIf(), List.replaceAll(), Map.computeIfAbsent(), and Map.computeIfPresent() methods
3
Develop code that uses the merge(), flatMap(), and map() methods on Java Streams
4
Java Streams
Describe the Stream interface and pipelines; create a stream by using the Arrays.stream() and IntStream.range() methods; identify the lambda operations that are lazy
4
Develop code that uses parallel streams, including decomposition operation and reduction operation in streams
7