42,99 €
Full coverage of functional programming and all OCA Java Programmer exam objectives OCA, Oracle Certified Associate Java SE 8 Programmer I Study Guide, Exam 1Z0-808 is a comprehensive study guide for those taking the Oracle Certified Associate Java SE 8 Programmer I exam (1Z0-808). With complete coverage of 100% of the exam objectives, this book provides everything you need to know to confidently take the exam. The release of Java 8 brought the language's biggest changes to date, and for the first time, candidates are required to learn functional programming to pass the exam. This study guide has you covered, with thorough functional programming explanation and information on all key topic areas Java programmers need to know. You'll cover Java inside and out, and learn how to apply it efficiently and effectively to create solutions applicable to real-world scenarios. * Work confidently with operators, conditionals, and loops * Understand object-oriented design principles and patterns * Master functional programming fundamentals
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 596
Veröffentlichungsjahr: 2014
Title Page
Copyright
Publisher's Note
Dedication
Acknowledgments
About the Authors
Introduction
The OCA 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
Free Online Learning Environment
Conventions Used in This Book
OCA Exam Objectives
Assessment Test
Answers to Assessment Test
Chapter 1: Java Building Blocks
Understanding the Java Class Structure
Writing a
main()
Method
Understanding Package Declarations and Imports
Creating Objects
Distinguishing Between Object References and Primitives
Declaring and Initializing Variables
Understanding Default Initialization of Variables
Understanding Variable Scope
Ordering Elements in a Class
Destroying Objects
Benefits of Java
Summary
Exam Essentials
Review Questions
Chapter 2: Operators and Statements
Understanding Java Operators
Working with Binary Arithmetic Operators
Working with Unary Operators
Using Additional Binary Operators
Understanding Java Statements
Understanding Advanced Flow Control
Summary
Exam Essentials
Review Questions
Chapter 3: Core Java APIs
Creating and Manipulating Strings
Using the
StringBuilder
Class
Understanding Equality
Understanding Java Arrays
Understanding an
ArrayList
Working with Dates and Times
Summary
Exam Essentials
Review Questions
Chapter 4: Methods and Encapsulation
Designing Methods
Working with Varargs
Applying Access Modifiers
Passing Data Among Methods
Overloading Methods
Creating Constructors
Encapsulating Data
Writing Simple Lambdas
Summary
Exam Essentials
Review Questions
Chapter 5: Class Design
Introducing Class Inheritance
Creating Abstract Classes
Implementing Interfaces
Understanding Polymorphism
Summary
Exam Essentials
Review Questions
Chapter 6: Exceptions
Understanding Exceptions
Using a
try
Statement
Recognizing Common Exception Types
Calling Methods That Throw Exceptions
Summary
Exam Essentials
Review Questions
Appendix A: Answers to Review Questions
Chapter 1: Java Building Blocks
Chapter 2: Operators and Statements
Chapter 3: Core Java APIs
Chapter 4: Methods and Encapsulation
Chapter 5: Class Design
Chapter 6: Exceptions
Appendix B: Study Tips
Studying for the Test
Taking the Test
Free Online Learning Environment
End User License Agreement
iv
v
vii
ix
xi
xxi
xxii
xxiii
xxiv
xxv
xxvi
xxvii
xxviii
xxix
xxx
xxxi
xxxii
xxxiii
xxxiv
xxxv
xxxvi
xxxvii
xxxviii
xxxix
xl
xli
xlii
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
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
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
324
325
326
327
328
329
330
331
332
Cover
Table of Contents
Introduction
Begin Reading
Figure 1.1
Figure 1.2
Figure 1.3
Figure 2.1
Figure 2.2
Figure 2.3
Figure 2.4
Figure 2.5
Figure 2.6
Figure 2.7
Figure 2.8
Figure 2.9
Figure 2.10
Figure 3.1
Figure 3.2
Figure 3.3
Figure 3.4
Figure 3.5
Figure 3.6
Figure 3.7
Figure 4.1
Figure 4.2
Figure 4.3
Figure 4.4
Figure 4.5
Figure 4.6
Figure 5.1
Figure 5.2
Figure 5.3
Figure 5.4
Figure 5.5
Figure 5.6
Figure 6.1
Figure 6.2
Figure 6.3
Figure 6.4
Figure B.1
Table 1.1
Table 1.2
Table 1.3
Table 1.4
Table 2.1
Table 2.2
Table 2.3
Table 2.4
Table 2.5
Table 3.1
Table 3.2
Table 3.3
Table 3.4
Table 3.5
Table 4.1
Table 4.2
Table 4.3
Table 4.4
Table 4.5
Table 6.1
Table B.1
Jeanne Boyarsky
Scott Selikoff
Senior Acquisitions Editor: Kenyon Brown
Development Editor: Alexa Murphy
Technical Editors: Ernest Friedman-Hill, Matt Dalen
Production Editor: Rebecca Anderson
Copy Editor: Liz Welch
Editorial Manager: Pete Gaughan
Vice President and Executive Group Publisher: Richard Swadley
Associate Publisher: Jim Minatel
Production Manager: Kathleen Wisor
Media Supervising Producer: Rich Graves
Book Designers: Judy Fung and Bill Gibson
Proofreader: Scott Klemp, Word One New York
Indexer: Ted Laux Project Coordinator, Cover: Patrick Redmond
Cover Designer: Wiley
Cover Image: ©Getty Images Inc./Jeremy Woodhouse
Copyright © 2015 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-95740-0
ISBN: 978-1-118-95741-7 (ebk.)
ISBN: 978-1-118-95742-4 (ebk.)
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: 2014954685
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.
Dear Reader,
Thank you for choosing OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide. This book is part of a family of premium-quality Sybex books, all of which are written by outstanding authors who combine practical experience with a gift for teaching.
Sybex was founded in 1976. More than 30 years later, we're still committed to producing consistently exceptional books. With each of our titles, we're working hard to set a new standard for the industry. From the paper we print on, to the authors we work with, our goal is to bring you the best books available.
I hope you see all that reflected in these pages. I'd be very interested to hear your comments and get your feedback on how we're doing. Feel free to let me know what you think about this or any other Sybex book by sending me an email at [email protected]. If you think you've found a technical error in this book, please visit http://sybex.custhelp.com. Customer feedback is critical to our efforts at Sybex.
Best regards,Chris WebbAssociate PublisherSybex, an Imprint of Wiley
To the programmers on FIRST robotics team 694.
—Jeanne
To my wife and the two little bundles of joy she is carrying.
—Scott
Jeanne and Scott would like to thank numerous individuals for their contribution to this book. Thank you to Developmental Editor Alexa Murphy for teaching us about Wiley's publishing process and making the book better in so many ways. Thank you to Ernest Friedman-Hill for being our Technical Editor as we wrote our first book. Ernest pointed out many subtle errors in addition to the big ones. And thank you to Matt Dalen for being our Technical Proofer and finding the errors we managed to sneak by Ernest. This book also wouldn't be possible without many people at Wiley, including Jeff Kellum, Kenyon Brown, Pete Gaughan, Rebecca Anderson, and so many others.
Jeanne would personally like to thank Chris Kreussling for knowing almost a decade ago that she would someday write a book. Erik Kariyev motivated her to write her first table of contents ever. Countless CodeRanch.com moderators warned Jeanne about how much work writing a book is to get her to the point where she was ready. Michael Ernest gave her extra advice on the Wiley process. Bert Bates let Jeanne dip her toe in by contributing to his Java 7 book and she learned a ton in the process. Scott was a great co-author and was available to bounce ideas off of or remind her to follow her own advice. Finally, Jeanne would like to thank all of the new programmers at CodeRanch.com and FIRST robotics team 694 for the constant reminders of how new programmers think.
Scott could not have reached this point without the help of a small army of people, led by his perpetually understanding wife Patti, without whose love and support this book would never have been possible. Professor Johannes Gehrke of Cornell University always believed in him and knew he would excel in his career. Jeanne's patience and guidance as co-author was invaluable while Scott adjusted to the learning curve of writing a book. Matt Dalen has been a wonderful friend and sounding board over the last year. Joel McNary introduced him 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.
Jeanne Boyarsky has worked as a Java developer for over 12 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 works on the forum codebase. 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 in 2002 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 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, NJ, Scott achieved his Bachelor of Arts from Cornell University in Mathematics and Computer Science in 2002, after 3 years of study. In 2003, he received his Master's 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 and two very playful dogs, a Siberian husky named Webby and standard poodle named Georgette. You can find out more about Scott at www.linkedin.com/in/selikoff.
Jeanne and Scott are both moderators on the CodeRanch.com forums and can be reached there for questions and comments. They also co-author a technical blog called Down Home Country Coding at www.selikoff.net.
Java, “born” in 1995, is now just about 20 years old. As with anything 20 years old, there is a good amount of history and variation between 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 Oracle Certified Associate (OCA) exam.
If you read about “the exam” on the Web, you may see information about the older names for the exam. We've showed the changes in name. Here's what happened. Sun Microsystems used to have two exams. The SCJP (Sun Certified Java Programmer) was meant for programmers and the SCJA (Sun Certified Java Associate) was meant for those who wanted broader knowledge. When Oracle bought Sun Microsystems, they changed all the names from Sun to Oracle, giving us the OCJP and OCJA.
Then Oracle made two strategic decisions with Java 7. They decided to stop updating the OCJA exam. They also decided to cover more on in the programmer space and split it into two exams. Now you first take the OCAJP (Oracle Certified Associate Java Programmer), also known as Java Programmer I, or OCA. That's what this book is about. Then you take the OCPJP (Oracle Certified Professional Java Programmer), also known as Java Programmer II, or OCP. There's also an upgrade exam in case you took an older version of the SCJP or OCPJP and want to upgrade. Most people refer to the current exams as OCA 8, OCP 8, and the Java 8 upgrade exam. We mention when a topic is split between the OCA and OCP so you know which parts are more advanced.
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 it. We will also let you know about topics that are not on the exam anymore in case you see questions in the older free online mock exams.
All you need to do to earn the Oracle Certified Associate Java SE 8 Programmer certification is to pass the 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 a guarantee that whatever we tell you here will become obsolete, we will give you a feel for the range of variation. The OCA exam has varied between 60 and 90 questions since it was introduced. The score to pass 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 removals from what is covered on the exam. Although this tends to affect the OCP exam more than the OCA exam, there are a few topics that were added to the OCA for Java 8. It wouldn't be a surprise for Oracle to make changes.
Although there will likely be minor changes to the scope of the exam, it certainly isn't a secret. We've created a book page on our blog: www.selikoff.net/oca. 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 that you can check the length and passing score that Oracle has chosen for the moment.
The exam is administered by Pearson VUE and can be taken at any Pearson VUE testing center. To find a testing center or register for the exam, go to www.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 their broken laptop nearby!
At this time, you can reschedule the exam without penalty until up to 24 hours before. This means that you can register for a convenient time slot well in advance, knowing that you can delay if you aren't ready by that time. Rescheduling is easy and can be done 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 acceptable ID at http://www.pearsonvue.com/policies/1S.pdf. Try not to bring too much extra with you as 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 the car.
You will not be allowed to bring paper, your phone, and so forth 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 keeping your ID and money. They watch you taking the exam, though, so don't even think about writing notes on money.
The exam center will give you writing materials to use during the exam. These are used as scratch paper during the exam to figure out answers and 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.” Some centers still give pen and paper. Most give a small erasable board and a dry erase marker. If you have a preference to which you receive, call the testing center in advance to inquire.
In the past, you would find out right after finishing the exam if you passed. Now you have to wait nervously until you can check your score online.
If you go onto the Pearson VUE website, it will just have 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 your printed certificate. Sound vague? It is. The times reported to receive certificates vary widely.
The OCA exam consists of multiple-choice questions. There are typically five or six possible answers. If a question has more than one answer, the question specifically states exactly how many correct answers there are. This book does not do that. We say “choose all that apply” to make the questions harder. This means the questions in this book are generally harder than those on the exam. The idea is to give you more practice so you can spot the correct answer more easily on the real exam.
Note that exam questions will sometimes have line numbers that begin with numbers higher than 1. This is to indicate that you are looking at a code snippet rather than a complete class. We follow this convention as well to get you used to it.
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 get lost if you reviewed them again. 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 you have downloaded version 8 of the JDK. If you learned Java some time ago, you might have version 7 or even earlier. There have been both big and small changes to the language. You could get a question wrong if you study with the wrong version.
Also, please check our book page to make sure Oracle hasn't changed the objectives. For example, if Oracle decided that lambdas weren't on the exam, you'd want to know that before studying. We will post any updates that you should know about at www.selikoff.net/oca.
Both of the authors are moderators at CodeRanch.com. CodeRanch.com is a very large and active programming forum that is very friendly toward Java beginners. It has a forum just for this exam called OCAJP. It also has a forum called Beginning Java for non-exam-specific questions. As you read the book, feel free to ask your questions in either of those forums. It could be 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 certified as a 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 has a tiny bit of Java knowledge. If you've never read a Java book before, we recommend starting with a book that teaches programming from the beginning and then returning to this study guide.
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 six chapters, plus supplementary information: a glossary, this introduction, three appendices, and the assessment test after the introduction. You might have noticed that there are more than six 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.
The chapters are organized as follows:
Chapter 1, “Java Building Blocks,” covers the basics of Java such as scoping variables and how to run a program. It also includes calling methods and types of variables.
Chapter 2, “Operators and Statements,” focuses on the core logical constructs such as conditionals and loops. It also talks about the meaning and precedence of operators.
Chapter 3, “Core Java APIs,” introduces you to array,
ArrayList
,
String
,
StringBuilder
, and various date classes.
Chapter 4, “Methods and Encapsulation,” explains how to write methods, including access modifiers. It also shows how to call lambdas.
Chapter 5, “Class Design,” adds interfaces and superclasses. It also includes casting and polymorphism.
Chapter 6, “Exceptions,” shows the different types of exception classes and how to use them.
At the end of each chapter, you'll find a few elements you can use to prepare for the exam:
Summary
This section reviews the most important topics that were covered in the chapter and serves as a good review.
Exam Essentials
This section summarizes highlights that were covered in the chapter. You should be readily familiar with the key points of each chapter and be able to explain them in detail.
Review Questions
Each chapter concludes with at least 20 review questions. You should answer these questions and check your answers against the ones provided in Appendix A. If you can't answer at least 80 percent of these questions correctly, go back and review the chapter, or at least 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 chapter-end elements. They are most useful for checking and reinforcing your understanding. Even if you're already familiar with a topic, you should skim the chapter. There are a number of subtleties to Java that you could easily not encounter even when working with Java, even for years.
This book provides a free online interactive learning environment and test bank with several additional elements. The online test bank includes:
Sample Tests
All of the questions in this book, including the 20-question assessment test at the end of this introduction and over 130 questions that make up the Review Question sections for each chapter. In addition, there are three 60-question Practice Exams to test your knowledge of the material. The online test bank runs on multiple devices.
Electronic Flashcards
Over 200 questions in flashcard format (a question followed by a single correct answer). You can use these to reinforce your learning and provide last-minute test prep before the exam.
Glossary
The key terms from this book and their definitions are available as a fully searchable PDF.
Go to www.sybex.com/go/ocajavase8 to register and gain access to this comprehensive study tool package.
This book uses certain typographic styles in order to help you quickly identify important information and to avoid confusion about the meaning of words, such as onscreen 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 pay special attention to 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 describes a task or an example that's particularly grounded in the real world. Although interesting, the scenario will not show up on the exam.
OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 has been written to cover every OCA exam objective. The following table provides a breakdown of this book's exam coverage, showing you the chapter where each objective or sub-objective is covered:
Exam Objective
Chapter
Java Basics
Define the scope of variables
1
Define the structure of a Java class
1
Create executable Java applications with a main method; run a Java program from the command line, including console output
1
Import other Java packages to make them accessible in your code
1
Compare and contrast the features and components of Java such as platform independence, object orientation, encapsulation, etc.
1
Working with Java Data Types
Declare and initialize variables (including casting of primitive data types)
1
Differentiate between object reference variables and primitive variables
1
Know how to read or write to object fields
1
Explain an Object's Lifecycle (creation, “dereference by reassignment,” and garbage collection)
1
Develop code that uses wrapper classes such as Boolean, Double, and Integer
1
Using Operators and Decision Constructs
Use Java operators, including parentheses to override operator precedence
2
Test equality between Strings and other objects using == and equals ()
3
Create if and if/else and ternary constructs
2
Use a switch statement
2
Creating and Using Arrays
Declare, instantiate, initialize, and use a one-dimensional array
3
Declare, instantiate, initialize, and use multi-dimensional array
3
Using Loop Constructs
Create and use while loops
2
Create and use for loops including the enhanced for loop
2
Create and use do/while loops
2
Compare loop constructs
2
Use break and continue
2
Working with Methods and Encapsulation
Create methods with arguments and return values, including overloaded methods
4
Apply the static keyword to methods and fields
4
Create and overload constructors, including impact on default constructors
4
Apply access modifiers
4
Apply encapsulation principles to a class
4
Determine the effect upon object references and primitive values when they are passed into methods that change the values
4
Working with Inheritance
Describe inheritance and its benefits
5
Develop code that demonstrates the use of polymorphism, including overriding and object type versus reference type
5
Determine when casting is necessary
5
Use super and this to access objects and constructors
5
Use abstract classes and interfaces
5
Handling Exceptions
Differentiate among checked exceptions, unchecked exceptions, and Errors
6
Create a try-catch block and determine how exceptions alter normal program flow
6
Describe the advantages of Exception handling
6
Create and invoke a method that throws an exception
6
Recognize common exception classes (such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException)
6
Working with Selected Classes from the Java API
Manipulate data using the StringBuilder class and its methods
3
Creating and manipulating Strings
3
Create and manipulate calendar data using classes from java.time.LocalDateTime, java.time.LocalDate, java.time.LocalTime, java.time.format.DateTimeFormatter, java.time.Period
3
Declare and use an ArrayList of a given type
3
Write a simple Lambda expression that consumes a Lambda Predicate expression
4
What is the result of the following class? (Choose all that apply)
1: public class _C { 2: private static int $; 3: public static void main(String[] main) { 4: String a_b; 5: System.out.print($); 6: System.out.print(a_b); 7: } }
Compiler error on line 1.
Compiler error on line 2.
Compiler error on line 4.
Compiler error on line 5.
Compiler error on line 6.
0null
nullnull
What is the result of the following code?
String s1 = "Java"; String s2 = "Java"; StringBuilder sb1 = new StringBuilder(); sb1.append("Ja").append("va"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); System.out.println(sb1.toString() == s1); System.out.println(sb1.toString().equals(s1));
true
is printed out exactly once.
true
is printed out exactly twice.
true
is printed out exactly three times.
true
is printed out exactly four times.
The code does not compile.
What is the output of the following code? (Choose all that apply)
1: interface HasTail { int getTailLength(); } 2: abstract class Puma implements HasTail { 3: protected int getTailLength() {return 4;} 4: } 5: public class Cougar extends Puma { 6: public static void main(String[] args) { 7: Puma puma = new Puma(); 8: System.out.println(puma.getTailLength()); 9: } 10: 11: public int getTailLength(int length) {return 2;} 12: }
2
4
The code will not compile because of line 3.
The code will not compile because of line 5.
The code will not compile because of line 7.
The code will not compile because of line 11.
The output cannot be determined from the code provided.
What is the output of the following program?
1: public class FeedingSchedule { 2: public static void main(String[] args) { 3: boolean keepGoing = true; 4: int count = 0; 5: int x = 3; 6: while(count++ < 3) { 7: int y = (1 + 2 * count) % 3; 8: switch(y) { 9: default: 10: case 0: x -= 1; break; 11: case 1: x += 5; 12: } 13: } 14: System.out.println(x); 15: } }
4
5
6
7
13
The code will not compile because of line 7.
What is the output of the following code snippet?
13: System.out.print("a"); 14: try { 15: System.out.print("b"); 16: throw new IllegalArgumentException(); 17: } catch (RuntimeException e) { 18: System.out.print("c"); 19: } finally { 20: System.out.print("d"); 21: } 22: System.out.print("e");
abe
abce
abde
abcde
The code does not compile.
An uncaught exception is thrown.
What is the result of the following program?
1: public class MathFunctions { 2: public static void addToInt(int x, int amountToAdd) { 3: x = x + amountToAdd; 4: } 5: public static void main(String[] args) { 6: int a = 15; 7: int b = 10; 8: MathFunctions.addToInt(a, b); 9: System.out.println(a); } }
10
15
25
Compiler error on line 3.
Compiler error on line 8.
None of the above.
What is the result of the following code?
int[] array = {6,9,8}; List<Integer> list = new ArrayList<>(); list.add(array[0]); list.add(array[2]); list.set(1, array[1]); list.remove(0); System.out.println(list);
[8]
[9]
Something like
[Ljava.lang.String;@160bc7c0
An exception is thrown.
The code does not compile.
What is the output of the following code?
1: public class Deer { 2: public Deer() { System.out.print("Deer"); } 3: public Deer(int age) { System.out.print("DeerAge"); } 4: private boolean hasHorns() { return false; } 5: public static void main(String[] args) { 6: Deer deer = new Reindeer(5); 7: System.out.println(","+deer.hasHorns()); 8: } 9: } 10: class Reindeer extends Deer { 11: public Reindeer(int age) { System.out.print("Reindeer"); } 12: public boolean hasHorns() { return true; } 13: }
DeerReindeer,false
DeerReindeer,true
ReindeerDeer,false
ReindeerDeer,true
DeerAgeReindeer,false
DeerAgeReindeer,true
The code will not compile because of line 7.
The code will not compile because of line 12.
Which of the following statements are true? (Choose all that apply)a
Checked exceptions are intended to be thrown by the JVM (and not the programmer).
Checked exceptions are required to be caught or declared.
Errors are intended to be thrown by the JVM (and not the programmer).
Errors are required to be caught or declared.
Runtime exceptions are intended to be thrown by the JVM (and not the programmer).
Runtime exceptions are required to be caught or declared.
Which are true of the following code? (Choose all that apply)
1: import java.util.*; 2: public class Grasshopper { 3: public Grasshopper(String n) { 4: name = n; 5: } 6: public static void main(String[] args) { 7: Grasshopper one = new Grasshopper("g1"); 8: Grasshopper two = new Grasshopper("g2"); 9: one = two; 10: two = null; 11: one = null; 12: } 13: private String name; }
Immediately after line 9, no grasshopper objects are eligible for garbage collection.
Immediately after line 10, no grasshopper objects are eligible for garbage collection.
Immediately after line 9, only one grasshopper object is eligible for garbage collection.
Immediately after line 10, only one grasshopper object is eligible for garbage collection.
Immediately after line 11, only one grasshopper object is eligible for garbage collection.
The code compiles.
The code does not compile.
What is the output of the following program?
1: public class FeedingSchedule { 2: public static void main(String[] args) { 3: int x = 5, j = 0; 4: OUTER: for(int i=0; i<3; ) 5: INNER: do { 6: i++; x++; 7: if(x > 10) break INNER; 8: x += 4; 9: j++; 10: } while(j <= 2); 11: System.out.println(x); 12: } }
10
12
13
17
The code will not compile because of line 4.
The code will not compile because of line 6.
What is the result of the following program?
1: public class Egret { 2: private String color; 3: public Egret() { 4: this("white"); 5: } 6: public Egret(String color) { 7: color = color; 8: } 9: public static void main(String[] args) { 10: Egret e = new Egret(); 11: System.out.println("Color:" + e.color); 12: } 13: }
Color:
Color:null
Color:White
Compiler error on line 4.
Compiler error on line 10.
Compiler error on line 11.
What is the output of the following program?
1: public class BearOrShark { 2: public static void main(String[] args) { 3: int luck = 10; 4: if((luck>10 ? luck++: --luck)<10) { 5: System.out.print("Bear"); 6: } if(luck<10) System.out.print("Shark"); 7: } }
Bear
Shark
BearShark
The code will not compile because of line 4.
The code will not compile because of line 6.
The code compiles without issue but does not produce any output.
Assuming we have a valid, non-
null
HenHouse
object whose value is initialized by the blank line shown here, which of the following are possible outputs of this application? (Choose all that apply)
1: class Chicken {} 2: interface HenHouse { public java.util.List<Chicken> getChickens(); } 3: public class ChickenSong { 4: public static void main(String[] args) { 5: HenHouse house = ______________ 6: Chicken chicken = house.getChickens().get(0); 7: for(int i=0; i<house.getChickens().size(); 8: chicken = house.getChickens().get(i++)) { 9: System.out.println("Cluck"); 10: } } }
The code will not compile because of line 6.
The code will not compile because of lines 7–8.
The application will compile but not produce any output.
The application will output
Cluck
exactly once.
The application will output
Cluck
more than once.
The application will compile but produce an exception at runtime.
Which of the following statements can be inserted in the blank line so that the code will compile successfully? (Choose all that apply)
public interface CanSwim {} public class Amphibian implements CanSwim {} class Tadpole extends Amphibian {} public class FindAllTadPole { public static void main(String[] args) { List<Tadpole> tadpoles = new ArrayList<Tadpole>(); for(Amphibian amphibian : tadpoles) { ___________ tadpole = amphibian; } } }
CanSwim
Long
Amphibian
Tadpole
Object
What individual changes, if any, would allow the following code to compile? (Choose all that apply)
1: public interface Animal { public default String getName() { return null; } } 2: interface Mammal { public default String getName() { return null; } } 3: abstract class Otter implements Mammal, Animal {}
The code compiles without issue.
Remove the
default
method modifier and method implementation on line 1.
Remove the
default
method modifier and method implementation on line 2.
Remove the
default
method modifier and method implementation on lines 1 and 2.
Change the return value on line 1 from
null
to
"Animal"
.
Override the
getName()
method with an
abstract
method in the
Otter
class.
Override the
getName()
method with a concrete method in the
Otter
class.
Which of the following lines can be inserted at line 11 to print
true
? (Choose all that apply)
10: public static void main(String[] args) { 11: // INSERT CODE HERE 12: } 13: private static boolean test(Predicate<Integer> p) { 14: return p.test(5); 15: }
System.out.println(test(i -> i == 5));
System.out.println(test(i -> {i == 5;}));
System.out.println(test((i) -> i == 5));
System.out.println(test((int i) -> i == 5);
System.out.println(test((int i) -> {return i == 5;}));
System.out.println(test((i) -> {return i == 5;}));
Which of the following print out a date representing April 1, 2015? (Choose all that apply)a
System.out.println(LocalDate.of(2015, Calendar.APRIL, 1));
System.out.println(LocalDate.of(2015, Month.APRIL, 1));
System.out.println(LocalDate.of(2015, 3, 1));
System.out.println(LocalDate.of(2015, 4, 1));
System.out.println(new LocalDate(2015, 3, 1));
System.out.println(new LocalDate(2015, 4, 1));
Bytecode is in a file with which extension?
.bytecode
.bytes
.class
.exe
.javac
.java
Which of the following are checked exceptions? (Choose all that apply)
Exception
IllegalArgumentException
IOException
NullPointerException
NumberFormatException
StackOverflowError
E. Option E is correct because local variables require assignment before referencing them. Option D is incorrect because class and instance variables have default values and allow referencing.
$
defaults to 0. Options A, B, and C are incorrect because identifiers may begin with a letter, underscore, or dollar sign. Options F and G are incorrect because the code does not compile. If
a_b
was an instance variable, the code would compile and output
0null
. For more information, see Chapter 1.
C. String literals are used from the string pool. This means that
s1
and
s2
refer to the same object and are equal. Therefore, the first two print statements print
true
. The third print statement prints
false
because
toString()
uses a method to compute the value and it is not from the string pool. The final print statement again prints
true
because
equals()
looks at the values of
String
objects. For more information, see Chapter 3.
C, D, E. First, the method
getTailLength()
in the interface
HasTail
is assumed to be
public
, since it is part of an interface. The implementation of the method on line 3 is therefore an invalid override, as
protected
is a more restrictive access modifier than
public
, so option C is correct. Next, the class
Cougar
implements an overloaded version of
getTailLength()
, but since the declaration in the parent class
Cougar
is invalid, it needs to implement a public version of the method. Since it does not, the declaration of
Cougar
is invalid, so option D is correct. Option E is correct, since
Puma
is marked
abstract
and cannot be instantiated. The overloaded method on line 11 is declared correctly, so option F is not correct. Finally, as the code has multiple compiler errors, options A, B, and G can be eliminated. For more information, see Chapter 5.
C. The code compiles and runs without issue; therefore, option F is incorrect. This type of problem is best examined one loop iteration at a time:
The loop starts as count loop expression evaluates to
0 < 3
, which is
true
, With count taking a new value of
1
. The value of
y
is set to:
y = (1 + 2 * 1) % 3
= (1 + 2) % 3
= 3 % 3
= 0
The first
case
block is called and the value of
x
is then set to:
x = 3 - 1 = 2
The loop continues as count loop expression evaluates to
1 < 3
, which is
true
, with
y
taking a new value of
2
. The value of
y
is set to:
y = (1 + 2 * 2) % 3
= (1 + 5) % 3
= 4 % 3
= 2
The
default
block is called and the value of
x
is set to:
x = 2 - 1 = 1
The loop continues as the count loop expression evaluates to
2 < 3
, which is
true
, with
y
taking a new value of
3
. The value of
y
is set to:
y = (1 + 2 * 3) % 3
= (1 + 6) % 3
= 7 % 3
= 1
The second
case
block is called and the value of
x
is then set to:
x = 1 + 5 = 6
The loop ends as the count loop expression evaluates to
3 < 3
, with
y
also taking a new value of
4
. The most recent value of
x
,
6
, is output, so the answer is option C. For more information, see Chapter 2.
D. The code starts running and prints
a
and
b
on lines 13 and 15. Line 16 throws an exception, which is caught on line 17. After line 18 prints
c
, the
finally
block is run and
d
is printed. Then the
try
statement ends and
e
is printed on line 22. For more information, see Chapter 6.
B. The code compiles successfully, so options D and E are incorrect. The value of
a
cannot be changed by the
addToInt
method, no matter what the method does, because only a copy of the variable is passed into the parameter
x
. Therefore,
a
does not change and the output on line 9 is 15. For more information, see Chapter 4.
B. The array is allowed to use an anonymous initializer because it is in the same line as the declaration. The
ArrayList
uses the diamond operator allowed since Java 7. This specifies the type matches the one on the left without having to re-type it. After adding the two elements,
list
contains
[6, 8]
. We then replace the element at index 1 with 9, resulting in
[6, 9]
. Finally, we remove the element at index 0, leaving
[9]
. Option C is incorrect because arrays output something like that rather than an
ArrayList
. For more information, see Chapter 3.
A. The code compiles and runs without issue, so options G and H are incorrect. First, the
Reindeer
object is instantiated using the constructor that takes an
int
value. Since there is no explicit call to the parent constructor, the default no-argument
super()
is inserted as the first line of the constructor. The output is then
Deer
, followed by
Reindeer
in the child constructor, so only options A and B can be correct. Next, the method
hasHorns()
looks like an overridden method, but it is actually a hidden method since it is declared private in the parent class. Because the hidden method is referenced in the parent class, the parent version is used, so the code outputs
false
, and option A is the correct answer.
B, C. Only checked exceptions are required to be handled (caught) or declared. Runtime exceptions are commonly thrown by both the JVM and programmer code. Checked exceptions are usually thrown by programmer code. Errors are intended to be thrown by the JVM. While a programmer could throw one, this would be a horrible practice. For more information, see Chapter 6.
C, D, F. Immediately after line 9, only
Grasshopper g1
is eligible for garbage collection since both
one
and
two
point to
Grasshopper g2
. Immediately after line 10, we still only have
Grasshopper g1
eligible for garbage collection. Reference
two
points to
g2
and reference
two
is
null
. Immediately after line 11, both
Grasshopper
objects are eligible for garbage collection since both
one
and
two
point to
null
. The code does compile. Although it is traditional to declare instance variables early in the class, you don't have to. For more information, see Chapter 1.
B. The code compiles and runs without issue; therefore, options E and F are incorrect. This type of problem is best examined one loop iteration at a time:
On the first iteration of the outer loop
i
is
0
, so the loop continues.
On the first iteration of the inner loop,
i
is updated to
1
and
x
to
6
. The
if-then
statement branch is not executed, and
x
is increased to
10
and
j
to
1
.
On the second iteration of the inner loop (since
j = 1
and
1 <= 2
),
i
is updated to
2
and
x
to
11
. At this point, the
if-then
branch will evaluate to
true
for the remainder of the program run, which causes the flow to break out of the inner loop each time it is reached.
On the second iteration of the outer loop (since
i = 2
),
i
is updated to
3
and
x
to
12
. As before, the inner loop is broken since
x
is still greater than
10
.
On the third iteration of the outer loop, the outer loop is broken, as
i
is already not less than
3
. The most recent value of
x
,
12
, is output, so the answer is option B. For more information, see Chapter 2.
B. Line 10 calls the constructor on lines 3–5. That constructor calls the other constructor. However, the constructor on lines 6–8 assigns the method parameter to itself, which leaves the
color
instance variable on line 2 set to its default value of
null
. For more information, see Chapter 4.
C. The code compiles and runs without issue, so options D and E are incorrect. Remember that only one of the right-hand ternary expressions will be evaluated at runtime. Since
luck
is not less than
10
, the second expression,
--luck
, will be evaluated, and since the pre-increment operator was used, the value returned will be
9
, which is less than
10
. So the first
if-then
statement will be visited and
Bear
will be output. Notice there is no
else
statement on line 6. Since
luck
is still less than
10
, the second
if-then
statement will also be reached and
Shark
will be output; therefore, the correct answer is option C. For more information, see Chapter 2.
D, E, F. The code compiles without issue, so options A and B are incorrect. If
house.getChickens()
returns an array of one element, the code will output
Cluck
once, so option D is correct. If
house.getChickens()
returns an array of multiple elements, the code will output
Cluck
once for each element in the array, so option E is correct. Alternatively, if
house.getChickens()
returns an array of zero elements, then the code will throw an
IndexOutOfBoundsException
on the call to
house.getChickens().get(0)
; therefore, option C is not possible and option F is correct. The code will also throw an exception if the array returned by
house.getChickens()
is
null
, so option F is possible under multiple circumstances. For more information, see Chapter 2.
A, C, E. The
for-each
loop automatically casts each
Tadpole
object to an
Amphibian
reference, which does not require an explicit cast because
Tadpole
is a subclass of
Amphibian
. From there, any parent class or interface that
Amphibian
inherits from is permitted without an explicit cast. This includes
CanSwim
, the interface
Amphibian
implements, and
Object
, which all classes extend from, so options A and E are correct. Option C is also correct since the reference is being cast to the same type, so no explicit cast is required. Option B is incorrect, since
Long
is not a parent of
Amphibian
. Option D is incorrect as well, although an explicit cast to
Tadpole
on the right-hand side of the expression would be required to allow the code to compile. For more information, see Chapter 5.
D, F, G. The code does not compile, since a class cannot inherit two interfaces that both define default methods with the same signature, unless the class implementing the interfaces overrides it with an abstract or concrete method. Therefore, option A is incorrect and options F and G are correct. The alternate approach is to make the
getName()
method abstract in the interfaces, because a class may inherit two abstract methods with the same signature. The change must be made to both interfaces, though, so options B and C are incorrect if taken individually, and option D is correct since the changes are taken together. For more information, see Chapter 5.
A, C, F. The only functional programming interface you need to memorize for the exam is
Predicate
. It takes a single parameter and returns a
boolean
. Lambda expressions with one parameter are allowed to omit the parentheses around the parameter list, making options A and C correct. The
return
statement is optional when a single statement is in the body, making option F correct. Option B is incorrect because a
return
statement must be used if braces are included around the body. Options D and E are incorrect because the type is
Integer
in the predicate and
int
in the lambda. Autoboxing works for collections not inferring predicates. If these two were changed to
Integer
, they would be correct. For more information, see Chapter 4.
B, D. The new date APIs added in Java 8 use static methods rather than a constructor to create a new date, making options E and F incorrect. The months are indexed starting with 1 in these APIs, making options A and C incorrect. Option A uses the old
Calendar
constants which are indexed from 0. Therefore, options B and D are correct. For more information, see Chapter 3.
C. Files with the
.java
extension contain the Java source code and are compiled to files with the
.class
extension that contain the bytecode. For more information, see Chapter 1.
A, C. Option A is the exception base class, which is a checked exception. Options B, D, and E extend
RuntimeException
directly or indirectly and therefore are unchecked exceptions. Option F is a throwable and not an exception, and so should not be caught or declared. For more information, see Chapter 6.
Java Basics
Define the scope of variables
Define the structure of a Java class
Create executable Java applications with a main method; run a Java program from the command line; including console output
Import other Java packages to make them accessible in your code
Compare and contrast the features and components of Java such as platform independence, object orientation, encapsulation, etc.
Working with Java Data Types
Declare and initialize variables (including casting or primitive types)
Differentiate between object reference variables and primitive variables
Know how to read or write to object fields
Explain an Object's Lifecycle (creation, “dereference by reassignment” and garbage collection
Welcome to the beginning of your journey to become certified on Java. We assume this isn't the first Java programming book you've read. Although we do talk about the basics, we do so only because we want to make sure you have all the terminology and detail you'll need for the OCA exam. If you've never written a Java program before, we recommend you pick up an introductory book on any version of Java—something like Head First Java, 2nd Edition (O'Reilly Media, 2005); Java for Dummies (For Dummies, 2014), or Thinking in Java, 4th Edition (Prentice Hall, 2006). (It's okay if the book covers an older version of Java—even Java 1.3 is fine.) Then come back to this certification study guide.
This chapter covers the fundamentals of Java. You'll see how to define and run a Java class, and learn about packages, variables, and the object life cycle.
In Java programs, classes are the basic building blocks. When defining a class, you describe all the parts and characteristics of one of those building blocks. To use most classes, you have to create objects. An object