oca-oracle-certified-associate-java-se-8-programmer-i-study-guide-exam-1z0-808 (1)


Чтобы посмотреть этот PDF файл с форматированием и разметкой, скачайте его и откройте на своем компьютере.
rs.indd 1봀
4/2014 Page i
OCA: Oracle
Certified Associate Java
SE 8 Programmer I
Exam 1Z0-808
rs.indd 1봀
4/2014 Page iii
OCA: Oracle
Certified Associate Java
SE 8 Programmer I
Exam 1Z0-808
Jeanne Boyarsky
Scott Selikoff
rs.indd 1봀
4/2014 Page iv
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 permit-
ted 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
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-
ranties 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
. For more information about Wiley
products, visit
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.
10 9 8 7 6 5 4 3 2 1
rs.indd 1봀
4/2014 Page v
Dear Reader,
Thank you for choosing
OCA: Oracle Certi■
ed 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 re.
ected in these pages. I’d be very interested to hear your com-
ments 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
. If you think you’ve found a technical error in this book, please visit
. Customer feedback is critical to our efforts at Sybex.
Best regards,
Chris Webb
Associate Publisher
Sybex, an Imprint of Wiley
rs.indd 1봀
4/2014 Page vii
To the programmers on FIRST robotics team 694.
葊eanne
To my wife and the two little bundles of joy she is carrying.
葓cott
rs.indd 1봀
4/2014 Page ix
Acknowledgments
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 ou爠■
rst book. Ernest pointed
out many subtle errors in addition to the big ones. And thank you to Matt Dalen for being
our Technical Proofer an搠■
nding 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 
rst
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 contrib-
uting 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. Jean湥’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 bene■
ts of working hard.
rs.indd 1봀
4/2014 Page xi
About the Authors
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 men-
tors 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 ca渠■
nd out more about Jeanne at
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 confer-
ences 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 ca渠■
nd out more about Scott at
wwwlinkedincom/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
rs.indd 1봀
4/2014 Page xiii
Contents at a Glance
Introduction
xxi
Assessment Test xxxi
Chapter
Java Building Blocks 1
Chapter
Operators and Statements 51
Chapter
Core Java APIs 101
Chapter
Methods and Encapsulation 165
Chapter
Class Design 233
Chapter
Exceptions 299
Appendix
Answers to Review Questions 333
Appendix
Study Tips 353
Index
367
ftoc.indd 1봀
4/2014 Page xv
Contents
Introduction
xxi
Assessment Test xxxi
Chapter
1 Java Building Blocks 1
Understanding the Java Class Structure 2
Fields and Methods 2
Comments 4
Classes vs. Files 5
Writing a
main⠩
Method 6
Understanding Package Declarations and Imports 9
Wildcards 10
Redundant Imports 11
Naming Conflicts 12
Creating a New Package 13
Code Formatting on the Exam 16
Creating Objects 16
Constructors 17
Reading and Writing Object Fields 18
Instance Initializer Blocks 18
Order of Initialization 19
Distinguishing Between Object References and Primitives 20
Primitive Types 20
Reference Types 24
Key Differences 25
Declaring and Initializing Variables 25
Declaring Multiple Variables 26
Identifiers 27
Understanding Default Initialization of Variables 29
Local Variables 29
Instance and Class Variables 30
Understanding Variable Scope 31
Ordering Elements in a Class 34
Destroying Objects 36
Garbage Collection 36
finalize⠀⤀
38
Benefits of Java 39
Summary 40
Exam Essentials 41
Review Questions 42
xvi
Contents
ftoc.indd 1봀
4/2014 Page xvi
Chapter
2 Operators and Statements 51
Understanding Java Operators 52
Working with Binary Arithmetic Operators 53
Arithmetic Operators 53
Numeric Promotion 55
Working with Unary Operators 57
Logical Complement and Negation Operators 57
Increment and Decrement Operators 58
Using Additional Binary Operators 60
Assignment Operators 60
Compound Assignment Operators 62
Relational Operators 63
Logical Operators 64
Equality Operators 65
Understanding Java Statements 66
The
if-then
Statement 67
The
if-then
else
Statement 68
The
switch
Statement 72
The
while
Statement 76
The
do-while
Statement 78
The
for
Statement 80
Understanding Advanced Flow Control 86
Nested Loops 87
Adding Optional Labels 87
The
break
Statement 88
The
continue
Statement 90
Summary 92
Exam Essentials 92
Review Questions 94
Chapter
3 Core Java APIs 101
Creating and Manipulating Strings 102
Concatenation 102
Immutability 104
The String Pool 105
Important String Methods 105
Method Chaining 110
Using the
StringBuilder
Class 111
Mutability and Chaining 112
Creating a
StringBuilder
113
Important
StringBuilder
Methods 114
StringBuilder
vs.
StringBuffer
Contents
xvii
ftoc.indd 1봀
4/2014 Page xvii
Understanding Equality 117
Understanding Java Arrays 119
Creating an Array of Primitives 119
Creating an Array with Reference Variables 121
Using an Array 123
Sorting 124
Searching 125
Varargs 126
Multidimensional Arrays 126
Understanding an
ArrayList
129
Creating an
ArrayList
Using an
ArrayList
130
Wrapper Classes 134
Autoboxing 136
Converting Between array and
List
136
Sorting 138
Working with Dates and Times 138
Creating Dates and Times 138
Manipulating Dates and Times 142
Working with Periods 145
Formatting Dates and Times 148
Parsing Dates and Times 151
Summary 151
Exam Essentials 152
Review Questions 153
Chapter
4 Methods and Encapsulation 165
Designing Methods 166
Optional Specifiers 168
Return Type 169
Method Name 170
Parameter List 171
Optional Exception List 171
Method Body 171
Working with Varargs 172
Applying Access Modifiers 173
Private Access 173
Default (Package Private⤀ Access 175
Protected Access 176
Public Access 180
Designing Static Methods and Fields 181
Calling a Static Variable or Method 182
Static vs. Instance 183
Static Variables 185
xviii
Contents
ftoc.indd 1봀
4/2014 Page xviii
Static Initialization 186
Static Imports 187
Passing Data Among Methods 188
Overloading Methods 191
Creating Constructors 196
Default Constructor 197
Overloading Constructors 199
Final Fields 202
Order of Initialization 202
Encapsulating Data 205
Creating Immutable Classes 207
Writing Simple Lambdas 208
Lambda Example 209
Lambda Syntax 211
Predicates 214
Summary 215
Exam Essentials 216
Review Questions 218
Chapter
5 Class Design 233
Introducing Class Inheritance 234
Extending a Class 235
Applying Class Access Modifiers 237
Creating Java Objects 237
Defining Constructors 238
Calling Inherited Class Members 244
Inheriting Methods 246
Inheriting Variables 257
Creating Abstract Classes 259
Defining an Abstract Class 260
Creating a Concrete Class 262
Extending an Abstract Class 263
Implementing Interfaces 266
Defining an Interface 267
Inheriting an Interface 269
Interface Variables 273
Default Interface Methods 274
Static Interface Methods 278
Understanding Polymorphism 279
Object vs. Reference 281
Casting Objects 282
Virtual Methods 284
Polymorphic Parameters 285
Polymorphism and Method Overriding 287
Contents
ftoc.indd 1봀
4/2014 Page xix
Summary 288
Exam Essentials 289
Review Questions 291
Chapter
6 Exceptions 299
Understanding Exceptions 300
The Role of Exceptions 300
Understanding Exception Types 302
Throwing an Exception 304
Using a
try
Statement 305
Adding a
finally
Block 307
Catching Various Types of Exceptions 309
Throwing a Second Exception 311
Recognizing Common Exception Types 313
Runtime Exceptions 314
Checked Exceptions 317
Errors 317
Calling Methods That Throw Exceptions 318
Subclasses 319
Printing an Exception 321
Summary 323
Exam Essentials 324
Review Questions 325
Appendix
A Answers to Review Questions 333
Chapter 1: Java Building Blocks 334
Chapter 2: Operators and Statements 336
Chapter 3: Core Java APIs 339
Chapter 4: Methods and Encapsulation 342
Chapter 5: Class Design 346
Chapter 6: Exceptions 349
Appendix
B Study Tips 353
Studying for the Test 354
Creating a Study Plan 354
Creating and Running Sample Applications 355
Taking the Test 359
Understanding the Question 359
Applying Process of Elimination 362
Optimizing Your Time 364
Getting a Good Night’s Rest 366
Index
367
ast.indd 1봀
4/2014 Page xxi
Introduction
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 cer-
ti.
cation exams have changed to cover different topics. The names of the exams have even
changed. This book covers the Java 8 Oracle Certi.
ed Associate (OCA) exam.
If you read abou琠贀the examŽ on the Web, you may see information about the older
names for the exam. We’ve showed the changes in name. He牥’s what happened. Sun
Microsystems used to have two exams. The SCJP (Sun Certi.
ed Java Programmer) was
meant for programmers and the SCJA (Sun Certi.
ed 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 yo甠.
rst take the OCAJP (Oracle Certi.
ed Associate Java Programmer⤀,
also known as Java Programmer I, or OCA. That’s what this book is about. Then you
take the OCPJP (Oracle Certi.
ed 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.
xxii
Introduction
ast.indd 1봀
4/2014 Page xxii
The OCA Exam
All you need to do to earn the Oracle Certi.
ed Associate Java SE 8 Programmer certi.
ca-
tion is to pass the exam! That’s it.
Oracle has a tendency to 
ddle 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:
Introduction
xxiii
ast.indd 1봀
4/2014 Page xxiii
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 
gure out answers and keep track of your thought pro-
cess. The exam center will dispose of them at the end. Notice how we said₍writing materi-
als踀 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.
Finding Out Your Score
In the past, you woul搠.
nd out right afte爠.
nishing 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
nd 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 certi.
cate.
At some point, you’ll get an electronic certi.
cate and some more time after that you’ll
receive your printed certi.
cate. Sound vague? It is. The times reported to receive certi.
cates
vary widely.
Exam Questions
The OCA exam consists of multiple-choice questions. There are typicall礠.
ve or six possi-
ble answers. If a question has more than one answer, the question speci.
cally states exactly
how many correct answers there are. This book does not do that. We sa礠贀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 com-
plete 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
xxiv
Introduction
ast.indd 1봀
4/2014 Page xxiv
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.
Getting Started
We recommend reading Appendix B,₍Study Tips,踀 before diving into the technical mate-
rial 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
Introduction
xxv
ast.indd 1봀
4/2014 Page xxv
This book is intended to be understandable to anyone who has a tiny bit of Java knowl-
edge. 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 program-
ming journey to experienced professionals who need a review for the certi.
cation.
How This Book Is Organized
This book consists of six chapters, plus supplementary information: a glossary, this intro-
duction, 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,
, 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 
nd 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.
xxvi
Introduction
ast.indd 1봀
4/2014 Page xxvi
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 dif.
culty.
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
pass the exam. Learning the underlying topic
is also the approach that will serve you best in the workplac斄the ultimate
goal of a certification.
To get the most out of this book, you should read each chapter from start to 
nish
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 chap-
ter. There are a number of subtleties to Java that you could easily not encounter even when
working with Java, even for years.
Free Online Learning Environment
This book provides a free online interactive learning environment and test bank with sev-
eral 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 
ashcard 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 de.
nitions are available as a fully
searchable PDF.
Go to
to register and gain access to this
comprehensive study tool package.
Introduction
xxvii
ast.indd 1봀
4/2014 Page xxvii
Conventions Used in This Book
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.⤀
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 some-
thing to pay special attention to for the exam.
Sidebars
A sidebar is like a note but longer. The information in a sidebar is useful, but it doesn’琠fi
t
into the main ”
ow of the text.
Real World Scenario
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 Exam Objectives
OCA: Oracle Certi■
ed 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 break-
down of this book’s exam coverage, showing you the chapter where each objective or
sub-objective is covered:
xxviii
Introduction
ast.indd 1봀
4/2014 Page xxviii
Exam Objective
Chapter
Java Basics
Define the scope of variables1
Define the structure of a Java class1
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 code1
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 of primitive data types⤀1
Differentiate between object reference variables and primitive variables1
Know how to read or write to object fields1
Explain an Object’s Lifecycle (creation,₍dereference by reassignment,踀 and
garbage collection⤀
Develop code that uses wrapper classes such as Boolean, Double, and Integer1
Using Operators and Decision Constructs
Use Java operators, including parentheses to override operator precedence2
Test equality between Strings and other objects using == and equals ()3
Create if and if/else and ternary constructs2
Use a switch statemen琂2
Creating and Using Arrays
Declare, instantiate, initialize, and use a one-dimensional array3
Declare, instantiate, initialize, and use multi-dimensional array3
Introduction
xxix
ast.indd 1봀
4/2014 Page xxix
Exam Objective
Chapter
Using Loop Constructs
Create and use while loops2
Create and use for loops including the enhanced for loop2
Create and use do/while loops2
Compare loop constructs2
Use break and continue2
Working with Methods and Encapsulation
Create methods with arguments and return values, including overloaded
methods
Apply the static keyword to methods and fields4
Create and overload constructors, including impact on default constructors4
Apply access modifiers4
Apply encapsulation principles to a class4
Determine the effect upon object references and primitive values when they
are passed into methods that change the values
Working with Inheritance
Describe inheritance and its benefits5
Develop code that demonstrates the use of polymorphism, including
overriding and object type versus reference type
Determine when casting is necessary5
Use super and this to access objects and constructors5
Use abstract classes and interfaces5
Handling Exceptions
Differentiate among checked exceptions, unchecked exceptions, and Errors6
Create a try-catch block and determine how exceptions alter normal
program flow
Introduction
ast.indd 1봀
4/2014 Page xxx
Exam Objective
Chapter
Describe the advantages of Exception handling6
Create and invoke a method that throws an exception6
Recognize common exception classes (such as NullPointerException, Arith-
meticException, ArrayIndexOutOfBou
ndsException, ClassCastException⤀
Working with Selected Classes from the Java API
Manipulate data using the StringBuilder class and its methods3
Creating and manipulating Strings3
Create and manipulate calendar data using classes from java.time.LocalDate-
Time, java.time.LocalDate, java.time.LocalTime, java.time.format.DateTime-
Formatter, java.time.Period
Declare and use an ArrayList of a given type3
Write a simple Lambda expression that consumes a Lambda Predicate
expression
(continued⤀
Introduction
xxxi
ast.indd 1봀
4/2014 Page xxxi
Assessment Test
What is the result of the following class? (Choose all that apply⤀
)4: String a_b;5: System.out.print($);6: System.out.print(a_b);7: } }A. 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.
What is the result of the following code?
is printed out exactly once.
is printed out exactly twice.
is printed out exactly three times.
is printed out exactly four times.
The code does not compile.
What is the output of the following code? (Choose all that apply⤀
xxxii
Introduction
ast.indd 1봀
4/2014 Page xxxii
Introduction
xxxiii
ast.indd 1봀
4/2014 Page xxxiii
What is the output of the following code snippet?
The code does not compile.
An uncaught exception is thrown.
What is the result of the following program?
)6: int a = 15;7: int b = 10;8: MathFunctions.addToInt(a, b);9: System.out.println(a); } }A. 10B. 15C. 25D. Compiler error on line 3.
Compiler error on line 8.
None of the above.
What is the result of the following code?
xxxiv
Introduction
ast.indd 1봀
4/2014 Page xxxiv
Introduction
xxxv
ast.indd 1봀
4/2014 Page xxxv
10.
Which are true of the following code? (Choose all that apply⤀
)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; }A. 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.
11.
What is the output of the following program?
)3: int x = 5, j = 0;4: OUTER: for(int i=0; i3; ) 5: INNER: do {6: i++; x++; ;&#x Tj ;.83; 0;&#x 0 8;&#x.75 ;Ő ;ʈ.;ቅ&#x Tm ;: ;&#x ;&#xINNE;&#xR: d;&#xo { ;&#xTj 7;&#x.831; 0 ;� 8.;u 1;P 2;u.1;Ɇ ;&#xTm 6;&#x: ;&#x ;&#x i++;&#x; x+;&#x+; T;&#xj 7.;茒&#x 0 0;&#x 8.7; 15;� 26;.12;H T;&#xm 7:;&#x ;&#x ;&#xifx ;7: if(x 10) break INNER;8: x += 4;9: j++;10: } while(j = 2);11: System.out.println(x);12: } }A. 10B. 12C. 13D. 17E. The code will not compile because of line 4.
The code will not compile because of line 6.
xxxvi
Introduction
ast.indd 1봀
4/2014 Page xxxvi
12.
What is the result of the following program?
Introduction
xxxvii
ast.indd 1봀
4/2014 Page xxxvii
xxxviii
Introduction
ast.indd 1봀
4/2014 Page xxxviii
Override the
Introduction
xxxix
ast.indd 1봀
4/2014 Page xxxix
Answers to Assessment Test
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 a null value. 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
was an instance variable, the
code would compile and output
. For more information, see Chapter 1.
C. String literals are used from the string pool. This means that
and
refer to the
same object and are equal. Therefore, the first two print statements print
. The
third print statement prints
because
uses a method to compute the
value and it is not from the string pool. The final print statement again prints
because
looks at the values of
objects. For more information, see
Chapter 3.
C, D, E. First, the method
Introduction
ast.indd 1봀
4/2014 Page xl
The
block is called and the value of
is set to:
The loop continues as the count loop expression evaluates to
, which is
with
taking a new value of
. The value of
is set to:
The second
block is called and the value of
is then set to:
The loop ends as the count loop expression evaluates to
, with
also taking a
new value of
. The most recent value of
, is output, so the answer is option C.
For more information, see Chapter 2.
D. The code starts running and prints
and
on lines 13 and 15. Line 16 throws an
exception, which is caught on line 17. After line 18 prints
, the
block is run
and
is printed. Then the
statement ends and
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
cannot be changed by the
method, no matter what the method does, because
only a copy of the variable is passed into the parameter
. Therefore,
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
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
. We then replace the element at index 1 with 9,
resulting in
. Finally, we remove the element at index 0, leaving
. Option C
is incorrect because arrays output something like that rather than an
more information, see Chapter 3.
A. The code compiles and runs without issue, so options G and H are incorrect. First,
the
object is instantiated using the constructor that takes an
value. Since
there is no explicit call to the parent constructor, the default no-argument
is inserted as the first line of the constructor. The output is then
, followed by
in the child constructor, so only options A and B can be correct. Next,
the method
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
and option A is the correct answer.
B, C. Only checked exceptions are required to be handled (caught⤀ or declared. Run-
time exceptions are commonly thrown by both the JVM and programmer code.
Checked exceptions are usually thrown by programmer code. Errors are intended to be
Introduction
xli
ast.indd 1봀
4/2014 Page xli
thrown by the JVM. While a programmer could throw one, this would be a horrible
practice. For more information, see Chapter 6.
10.
C, D, F. Immediately after line 9, only
is eligible for garbage collection
since both
and
point to
. Immediately after line 10, we still
only have
eligible for garbage collection. Reference
points to
and reference
is
. Immediately after line 11, both
objects are eli-
gible for garbage collection since both
and
point to
. The code does com-
pile. Although it is traditional to declare instance variables early in the class, you don’t
have to. For more information, see Chapter 1.
11.
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
is
, so the loop continues.
On the first iteration of the inner loop,
is updated to
and
. The
statement branch is not executed, and
is increased to
and
On the second iteration of the inner loop (since
and
),
is updated
and
. At this point, the
branch will evaluate to
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
),
is updated to
and
. As before, the inner loop is broken since
is still greater than
On the third iteration of the outer loop, the outer loop is broken, as
is already
not less than
. The most recent value of
, is output, so the answer is option B.
For more information, see Chapter 2.
12.
B. Line 10 calls the constructor on lines 3–5. That constructor calls the other construc-
tor. 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
more information, see Chapter 4.
13.
C. The code compiles and runs without issue, so options D and E are correct. Remem-
ber that only one of the right-hand ternary expressions will be evaluated at runtime.
Since
is not less than
, the second expression,
, will be evaluated, and
since the pre-increment operator was used, the value returned will be
, which is less
than
. So the first
statement will be visited and
will be output. Notice
there is no
statement on line 6. Since
is still less than
, the second
statement will also be reached and
will be output; therefore, the correct answer
is option C. For more information, see Chapter 2.
14.
D, E, F. The code compiles without issue, so options A and B are incorrect. If
xlii
Introduction
ast.indd 1봀
4/2014 Page xlii
throw an
on the call to
ast.indd 1봀
4/2014 Page xliii
OCA: Oracle
Certified Associate Java
SE 8 Programmer I
Exam 1Z0-808
c01.indd 1봀
4/2014 Page 1
Chapter
Java Building Blocks
OCA EXAM OBJECTIVES COVERED IN THIS
CHAPTER:
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, encapsu-
lation, etc.
Working with Java Data Types
Declare and initialize variables (including casting or primitive
types⤀
Differentiate between object reference variables and primi-
tive variables
Know how to read or write to object fields
Explain an Object’s Lifecycle (creation,₍dereference by
reassignment踀 and garbage collection
c01.indd 1봀
4/2014 Page 2
Welcome to the beginning of your journey to become certi■
ed
on Java. We assume this isn’t th攠■
rst 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 
ne.⤀ Then come back to this certi■
cation study guide.
This chapter covers the fundamentals of Java. You’ll see how to de■
ne and run a Java
class, and learn about packages, variables, and the object life cycle.
Understanding the Java Class Structure
In Java programs, classes are the basic building blocks. When de■
ning 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
is a runtime instance of a class in memory. All the various
objects of all the different classes represent the state of your program.
In the following sections, well look at 
elds, methods, and comments. We’ll also explore
the relationship between classes an搠■
les.
Fields and Methods
Java classes have two primary elements:
Understanding the Java Class Structure
c01.indd 1봀
4/2014 Page 3
The simplest Java class you can write looks like this:
Java calls a word with special meaning a
keyword
. The
keyword on line 1 means
the class can be used by other classes. The
keyword indicates you’re de■
ning a class.
gives the name of the class. Granted, this isn’t a very interesting class, so add your
rst ■
eld:
The line numbers aren’t part of the program; they’re just there to make the
code easier to talk about.
On line 2, we de■
ne a variable named
. We also de■
ne the type of that variable to
be a
is a value that we can put text into, such as
is also a class supplied with Java. Next you can add methods:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 4
The return type is
, which is a numeric type. Theres one parameter named
month
which is of type
as well.
Comments
Another common part of the code is called a
comment
. Because comments aren’t execut-
able code, you can place them anywhere. Comments make your code easier to read. You
won’t see many comments on the exam—the exam creators are trying to make the code
dif■
cult to read—but you’ll see them in this book as we explain the code. And we hope you
use them in your own code. There are three types of comments in Java. Th攠■
rst is called a
single-line comment:
A single-line comment begins with two slashes. Anything you type after that on the
same line is ignored by the compiler. Next comes the multiple-line comment:
A multiple-line comment (also known as a multiline comment⤀ includes anything
starting from the symbol
until the symbol
. People often type an asterisk (
) at the
beginning of each line of a multiline comment to make it easier to read, but you don’t have
to. Finally, we have a Javadoc comment:
This comment is similar to a multiline comment except it starts with
. This special
syntax tells the Javadoc tool to pay attention to the comment. Javadoc comments have a
speci■
c structure that the Javadoc tool knows how to read. You won’t see a Javadoc com-
ment on the exam—just remember it exists so you can read up on it online when you start
writing programs for others to use.
As a bit of practice, can you identify which type of comment each of thes攠■
ve words is
in? Is it a single-line or a multiline comment?
Understanding the Java Class Structure
c01.indd 1봀
4/2014 Page 5
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 6
Writing a
main⠀⤀
Method
A Java program begins execution with its
Writing a main⠀⤀ Method
c01.indd 1봀
4/2014 Page 7
Suppose we replace line 3 in
with
. When
we compile and run the code again, well get the line of output that matches what’s between
the quotes. In other words, the program will output
Let’猠■
rst review the words in the
method’s signature, one at a time. The key-
word
is what’s called an
access modi■
er.
It declares this method’s level of exposure
to potential callers in the program. Naturally,
means anyplace in the program.
You’ll learn about access modi■
ers in Chapter 4,₍Methods and Encapsulation.踀
The keyword
static
binds a method to its class so it can be called by just the class name,
as in, for example,
. Java doesn’t need to create an object to call the
method—which is good since you haven’t learned about creating objects yet! In fact, the
JVM does this, more or less, when loading the class name given to it. If a
method
isn’t present in the class we name with the .
executable, the process will throw an error
and terminate. Even if a
method is present, Java will throw an exception if it isn’t
static. A nonstatic
method might as well be invisible from the point of view of the
JVM. We’ll see
again in Chapter 4.
The keyword
void
represents the
return type
. A method that returns no data returns
control to the caller silently. In general, it’s good practice to use
for methods that
change an object’s state. In that sense, the
method changes the program state
from started to 
nished. We will explore return types in Chapter 4 as well. Excited for
Chapter 4 yet?
Finally we arrive at the
method’s parameter list, represented as an array of
objects. In practice, you can write
, String args[] or String...
; the compiler accepts any of these. The variable name
args
hints that this list contains
values that were read in (arguments) when the JVM started. You can use any name you like,
though. The characters
are brackets and represent an array. An array is a 
xed-size list of
items that are all of the same type. The characters
are called varargs (variable argument
lists⤀. You will learn about
in Chapter 2,₍Operators and Statements.踀 Arrays and
varargs will follow in Chapter 3,₍Core Java APIs.踀
Let’s see how to use the
args
parameter. First we modify the Zoo program to print out
th攠■
rst two arguments passed in:
) System.out.println(args[0]); System.out.println(args[1]);} }args[0] accesses th攠■
rst element of the array. That’s right: array indexes begin with 0
in Java. To run it, type this:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 8
The output is what you might expect:
The program correctly identi■
es th攠■
rst two words踠as the arguments. Spaces are used
to separate the arguments. If you want spaces inside an argument, you need to use quotes
as in this example:
Now we have a space in the output:
All command-line arguments are treated as
objects, even if they represent
another data type:
No matter. You still get the values output as
s. In Chapter 2, you’ll learn how to
convert
s to numbers.
Finally, what happens if you don’t pass in enough arguments?
Reading
goes 
ne and
is printed out. Then Java panics. Theres no sec-
ond argument! What to do? Java prints out an exception telling you it has no idea what
to do with this argument at position 1. (You’ll learn about exceptions in Chapter 6,
赅xceptions.踀⤀
Understanding Package Declarations and Imports
c01.indd 1봀
4/2014 Page 9
Understanding Package Declarations
and Imports
Java comes with thousands of built-in classes, and there are countless more from developers
like you. With all those classes, Java needs a way to organize them. It handles this in a way
similar to a 
le cabinet. You put all your pieces of paper in folders. Java puts classes in
packages
. These are logical groupings for classes.
We wouldn’t put you in front of a 
le cabinet and tell you to 
nd a speci■
c paper.
Instead, wed tell you which folder to look in. Java works the same way. It needs you to tell
it which packages to look in to 
nd code.
Suppose you try to compile this code:
) Random r = new Random(); // DOES NOT COMPILE System.out.println(r.nextInt(10)); }}The Java compiler helpfully gives you an error that looks like this:
This error could mean you made a typo in the name of the class. You double-check and
discover that you didn’t. The other cause of this error is omitting a needed
import
state-
ment. Import statements tell Java which packages to look in for classes. Since you didn’t tell
Java where to look for
, it has no clue.
Trying this again with the import allows you to compile:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 10
Imagine you are mailing a letter to 123 Main St., Apartment 9. The mail carrier 
rst brings
the letter to 123 Main St. Then she looks for the mailbox for apartment number 9. The
address is like the package name in Java. The apartment number is like the class name in
Java. Just as the mail carrier only looks at apartment numbers in the building, Java only
looks for class names in the package.
Package names are hierarchical like the mail as well. The postal service starts with the
top level, looking at your countr礠■
rst. You start reading a package name at the begin-
ning too. If it begins with
, this means it came with the JDK. If it starts with
something else, it likely shows where it came from using the website name in reverse. From
example,
tells us the code came from amazon.com. After the web-
site name, you can add whatever you want. For example,
also
came from amazon.com. Java calls more detailed packages
child packages
is a child package of
. You can tell because it’s longer and thus
more speci■
You’ll see package names on the exam that don’t follow this convention. Don’t be
surprised to see package names like
. The rule for package names is that they are
mostly letters or numbers separated by dots. Technically, you’re allowed a couple of other
characters between the dots. The rules are the same as for variable names, which you’ll see
later in the chapter. The exam may try to trick you with invalid variable names. Luckily, it
doesn’t try to trick you by giving invalid package names.
In the following sections, well look at imports with wildcards, naming con.
icts with
imports, how to create a package of your own, and how the exam formats code.
Wildcards
Classes in the same package are often imported together. You can use a shortcut to import
all the classes in a package:
) Random r = new Random(); System.out.println(r.nextInt(10)); }}In this example, we imported
and a pile of other classes. The
is a
wildcard that matches all classes in the package. Every class in the
package is
available to this program when Java compiles it. It doesn’t import child packagesⰠ■
elds, or
methods; it imports only classes. (Okay, it’s only classes for now, but theres a special type
of import called th攠贀static import踠that imports other types. You’ll learn more about that
in Chapter 4.⤀
You might think that including so many classes slows down your program, but it doesn’t. The
compiler 
gures out what’s actually needed. Which approach you choose is personal preference.
Understanding Package Declarations and Imports
c01.indd 1봀
4/2014 Page 11
Listing the classes used makes the code easier to read, especially for new programmers. Using the
wildcard can shorten the import list. You’ll see both approaches on the exam.
Redundant Imports
Wait a minute! We’ve been referring to
without an import and Java found it just
ne. Theres one special package in the Java world called
. This package is
special in that it is automatically imported. You can still type this package in an
statement, but you don’t have to. In the following code, how many of the imports do you
think are redundant?
)7: Random r = new Random();8: System.out.println(r.nextInt(10));9: }10: }The answer is that three of the imports are redundant. Lines 1 and 2 are redundant
because everything in
is automatically considered to be imported. Line 4 is also
redundant in this example because
is already imported from
If line 3 wasn’t present,
wouldn’t be redundant, though, since it would cover
importing
Another case of redundancy involves importing a class that is in the same package as the
class importing it. Java automatically looks in the current package for other classes.
Let’s take a look at one more example to make sure you understand the edge cases for
imports. For this example,
and
are both in the package
. You
don’t need to memorize this package for the OCA exam (but you should know it for the
OCP exam⤀. When testing your understanding of packages and imports, the OCA exam
will use packages you may never have seen before. The question will let you know which
package the class is in if you need to know that in order to answer the question.
What imports do you think would work to get this code to compile?
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 12
There are two possible answers. The shorter one is to use a wildcard to import both at
the same time:
The other answer is to import both classes explicitly:
Now let’s consider some imports that don’t work:
Understanding Package Declarations and Imports
c01.indd 1봀
4/2014 Page 13
Ah, now it works. If you explicitly import a class name, it takes precedence over any
wildcards present. Java thinksⰠ贀Okay! The programmer really wants me to assume use of
the
class.踠
One more example. What does Java do with₍ties踀 for precedence?
Java is smart enough to detect that this code is no good. As a programmer, you’ve
claimed to explicitly want the default to be both the
and
implementations. Because there can’t be two defaults, the compiler tells you:
If You Really Need to Use Two Classes with the Same Name…
Sometimes you really do want to use
from two different packages. When this hap-
pens, you can pick one to use in the import and use the other’s fully qualifi
ed class name
(the package name, a dot, and the class name) to specify that it’s special. For example:
Date date;
java.sql.Date sqlDate;
Or you could have neither with an import and always use the fully qualifi
ed class name:
java.util.Date date;
java.sql.Date sqlDate;
Creating a New Package
Up to now, all the code weve written in this chapter has been in the
default package
. This
is a special unnamed package that you should use only for throwaway code. You can tell
the code is in the default package, because theres no package name. On the exam, you’ll
see the default package used a lot to save space in code listings. In real life, always name
your packages to avoid naming con.
icts and to allow others to reuse your code.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 14
Now it’s time to create a new package. The directory structure on your computer is
related to the package name. Suppose we have these two classes:
) ClassA a; System.out.println("Got it"); }}When you run a Java program, Java knows where to look for those package names. In this
case, running from
works because both
and
are underneath it.
Compiling Code with Packages
You’ll learn Java much more easily by using the command line to compile and test
your examples. Once you know the Java syntax well, you can switch to an integrated
development environment (IDE) like Eclipse. An IDE will save you time in coding. But
for the exam, your goal is to know details about the language and not have the IDE hide
them for you.
Follow this example to make sure you know how to use the command line. If you have
any problems following this procedure, post a question in the Beginning Java forum at
CodeRanch (
⤀. Describe what you tried and what
the error said.
Windows Setup
Create the tw漠fi
les:
Then type this command:
Understanding Package Declarations and Imports
c01.indd 1봀
4/2014 Page 15
Mac/Linux Setup
Create the tw漠fi
les:
Then type this command:
To Compile
Type this command:
If this command doesn’t work, you’ll get an error message. Check your “
les carefully for
typos against the providedₓ
les. If the command does work, two ne眠fi
les will be created:
and
To Run
Type this command:
If it works, you’ll see
printed. You might have noticed we typed
rather than
. In Java you don’t pass the extension when running a program.
Class Paths and JARs
You can also specify the location of the othe爠fi
les explicitly using a class path. This tech-
nique is useful when the clas猠fi
les are located elsewhere or in special JA删fi
les. A JAR
le is like a zi瀠fi
le of mainly Java clas猠fi
les. This goes beyond what you’ll need to do on
version 8 of the exam, although it appears on older versions.
On Windows, you type the following:
And on Mac OS/Linux, you type this:
The dot indicates you want to include the current directory in the class path. The rest of
the command says to look for loose clas猠fi
les (or packages) in
and
within
. Windows uses semicolons to separate parts of the class path; other
operating systems use colons.
Finally, you can use a wildcard (
) to match all the JARs in a directory. Here’s an example:
This command will add all the JARs to the class path that are in
. It
won’t include any JARs in the class path that are in a subdirectory of
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 16
Code Formatting on the Exam
Not all questions will include the imports. If the exam isn’t asking about imports in the
question, it will often omit the imports to save space. You’ll see examples with line numbers
that don’t begin with 1 in this case. The question is telling you,₍Don’t worry—imagine
the code we omitted is correct; just focus on what I’m giving you.踠This means when you
do see the line number 1 or no line numbers at all, you have to make sure imports aren’t
missing. Another thing the exam does to save space is to merge code on the same line. You
should expect to see code like the following and to be asked whether it compiles. (You’ll
learn about
in Chapter 3—assume that part is good for now.⤀
Creating Objects
c01.indd 1봀
4/2014 Page 17
Constructors
To create an instance of a class, all you have to do is write
before it. For example:
First you declare the type that you’ll be creating (
) and give the variable a name
⤀. This gives Java a place to store a reference to the object. Then you write
to actually create the object.
looks like a method since it is followed by parentheses. It’s called a
construc-
, which is a special type of method that creates a new object. Now it’s time to de■
ne a
constructor of your own:
There are two key points to note about the constructor: the name of the constructor
matches the name of the class, and theres no return type. You’ll likely see a method like
this on the exam:
When you see a method name beginning with a capital letter and having a return type,
pay special attention to it. It is
not
a constructor since theres a return type. It’s a regular
method that won’t be called when you write
The purpose of a constructor is to initialize 
elds, although you can put any code in
there. Another way to initialize 
elds is to do so directly on the line on which they’re
declared. This example shows both approaches:
For most classes, you don’t have to code a constructor—the compiler will supply a do
nothingŽ default constructor for you. Theres one scenario that requires you to declare a
constructor that you’ll learn about in Chapter 5.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 18
Reading and Writing Object Fields
It’s possible to read and write instance variables directly from the caller. In this example, a
mother swan lays eggs:
Creating Objects
c01.indd 1봀
4/2014 Page 19
There are three code blocks and one instance initializer. Counting code blocks is easy:
you just count the number of pairs of braces. If there aren’t the same number of open (
and close (
) braces, the code doesn’t compile. It doesn’t matter that one set of braces is
inside the
method—it still counts.
When counting instance initializers, keep in mind that it does matter whether the braces
are inside a method. Theres only one pair of braces outside a method. Line 6 is an instance
initializer.
Order of Initialization
When writing code that initialize猠■
elds in multiple places, you have to keep track of the
order of initialization. We’ll add some more rules to the order of initialization in Chapters 4
and 5. In the meantime, you need to remember:
Fields and instance initializer blocks are run in the order in which they appear in
the file.
The constructor runs after all fields and instance initializer blocks have run.
Let’s look at an example:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 20
Order matters for th攠■
elds and blocks of code. You can’t refer to a variable before it has
been initialized:
You should expect to see a question about initialization on the exam. Let’s try one more.
What do you think this code prints out?
) Egg egg = new Egg(); System.out.println(egg.number); } private int number = 3; { number = 4; } }If you answered 5, you got it right. Fields and blocks are ru渠■
rst in order, setting
number
to 3 and then 4. Then the constructor runs, setting
number
to 5.
Distinguishing Between Object
References and Primitives
Java applications contain two types of data: primitive types
and reference types. In this
section, well discuss the differences between a primitive type and a reference type.
Primitive Types
Java has
eight built-in data types, referred to as the Java
primitive types
. These eight data
types represent the building blocks for Java objects, because all Java objects are just a com-
plex collection of these primitive data types. The exam assumes you are well versed in the
eight primitive data types, their relative sizes, and what can be stored in them.
Distinguishing Between Object References and Primitives
c01.indd 1봀
4/2014 Page 21
Table 1.1 shows the Java primitive types together with their size in bytes and the range of
values that each holds.
TABLE 1.1
Java primitive types
Keyword
Type
Example
true or false
8-bit integral value
16-bit integral value
32-bit integral value
64-bit integral value
32-bit floating-point value
64-bit floating-point value
16-bit Unicode value
Theres a lot of information in Table 1.1. Let’s look at some key points:
and
are used for floating-point (decimal) values.
A float requires the letter
following the number so Java knows it is a float.
, and
are used for numbers without decimal points.
Each numeric type uses twice as many bits as the smaller similar type. For example,
uses twice as many bits as
does.
You won’t be asked about the exact sizes of most of these types. You should know that
a byte can hold a value from …128 to 127. So you aren’t stuck memorizing this, let’s look
at how Java gets that. A byte is 8 bits. A bit has two possible values. (These are basic com-
puter science de■
nitions that you should memorize.⤀ 2
is 2
2 = 16
32
2 = 64
2 = 256. Since 0 needs to be included in the range, Java takes it
away from the positive side. Or if you don’t like math, you can just memorize it.
The number of bits is used by Java when it 
gures out how much memory to reserve for
your variable. For example, Java allocates 32 bits if you write this:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 22
What Is the Largest int?
You do not have to know this for the exam, but the maximum number an
can hold is
. How do we know this? One way is to have Java tell us:
The other way is with math. An
is 32 bits. 2
32
is
. Divide that by 2 and
you get 2,147,483,648. Then subtract 1 as we did with bytes and you get 2,147,483,647. It’s
easier to just ask Java to print the value, isn’t it?
There are a few more things you should know about numeric primitives. When a number
is present in the code, it is called a
literal
. By default, Java assumes you are de■
ning an
value with a literal. In this example, the number listed is bigger than what 
ts in an
Remember, you aren’t expected to memorize the maximum value for an
. The exam will
include it in the question if it comes up.
Java complains the number is out of range. And it is—for an
. However, we don’t
have an
. The solution is to add the character
to the number:
Alternatively, you could add a lowercase
to the number. But please use the uppercase
The lowercase l looks like the number 1.
Another way to specify numbers is to change th攠贀base.踠When you learned how to
count, you studied the digits 0–9. This numbering system is called base 10 since there are
10 numbers. It is also known as the decimal number system. Java allows you to specify dig-
its in several other formats:
octal (digits 0–7⤀, which uses the number 0 as a prefix—for example, 017
hexadecimal (digits 0–9 and letters A–F⤀, which uses the number 0 followed by x or X
as a prefix—for example, 0xFF
binary (digits 0–1⤀, which uses the number 0 followed by b or B as a prefix—for exam-
ple, 0b10
You won’t need to convert between number systems on the exam. You’ll have to recog-
nize valid literal values that can be assigned to numbers.
Distinguishing Between Object References and Primitives
c01.indd 1봀
4/2014 Page 23
Converting Back to Binary
Although you don’t need to convert between number systems on the exam, well look at
one example in case you’re curious:
First we have our normal base 10 value. We know you already know how to read that, but
bear with us. The rightmost digit is 6, so it’s₍worth踠6. The second-to-rightmost digit is
5, so it’s₍worth踠50 (5 times 10.⤀ Adding these together, we get 56.
Next we have binary, or base 2. The rightmost digit is 1 and is₍worth踠1. The second-to-
rightmost digit is also 1. In this case, it’s₍worthŽ 2 (1 times 2⤀ because the base is 2. Add-
ing these gets us 3.
Then comes octal, or base 8. The rightmost digit is 7 and is₍worth踠7. The second-to-
rightmost digit is 1. In this case, it’s₍worthŽ 8 (1 times 8) because the base is 8. Adding
these gets us 15.
Finally, we have hexadecimal, or base 16, which is also known as hex. The rightmost
贀digit踠is F and it’s₍worth踠15 (9 is₍worthŽ 9, A is₍worth踠10, B is₍worth踠11, and so
forth⤀. The second-to-rightmost digit is 1. In this case, it’s₍worth踠16 (1 times 16) because
the base is 16. Adding these gets us 31.
The last thing you need to know about numeric literals is a feature added in Java 7. You
can have underscores in numbers to make them easier to read:
We’d rather be reading the latter one because the zeroes don’t run together. You can add
underscores anywhere except at the beginning of a literal, the end of a literal, right before a
decimal point, or right after a decimal point. Let’s look at a few examples:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 24
Reference Types
reference type
refers to an object (an instance of a class⤀. Unlike primitive types that hold
their values in the memory where the variable is allocated, references do not hold the value
of the object they refer to. Instead, a referenc攠贀points踀 to an object by storing the memory
address where the object is located, a concept referred to as a
pointer
. Unlike other
languages, Java does not allow you to learn what the physical memory address is. You can
only use the reference to refer to the object.
Let’s take a look at some examples that declare and initialize reference types. Suppose
we declare a reference of type
and a reference of type
Declaring and Initializing Variables
c01.indd 1봀
4/2014 Page 25
Key Differences
There are a few important differences you should know between primitives and reference
types. First, reference types can be assigned
, which means they do not currently refer
to an object. Primitive types will give you a compiler error if you attempt to assign them
. In this example,
value
cannot point to
because it is of type
Next, reference types can be used to call methods when they do not point to
Primitives do not have methods declared on them. In this example, we can call a method on
reference
since it is of a reference type. You can tell
is a method because it has
after it. The following line is gibberish. No methods exist on
len
because it is an
primi-
tive. Primitives do not have methods.
Finally, notice that all the primitive types have lowercase type names. All classes that
come with Java begin with uppercase. You should follow this convention for classes you
create as well.
Declaring and Initializing Variables
We’ve seen some variables already. A
variable
is a name for a piece of memory that stores
data. When you declare a variable, you need to state the variable type along with giving it a
name. For example, the following code declares two variables. One is named
zooName
and
is of type
. The other is named
numberAnimals
and is of type
Now that weve declared a variable, we can give it a value. This is called initializing a
variable. To initialize a variable, you just type the variable name followed by an equal sign,
followed by the desired value:
Since you often want to initialize a variable right away, you can do so in the same state-
ment as the declaration. For example, here we merge the previous declarations and initial-
izations into more concise code:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 26
In the following sections, well look at how to declare multiple variables in one-line and
legal identi■
ers.
Declaring Multiple Variables
You can also declare and initialize multiple variables in the same statement. How many
variables do you think are declared and initialized in the following two lines?
Four
variables were declared:
, and
. You can declare many variables
in the same declaration as long as they are all of the same type. You can also initialize any
or all of those values inline. In the previous example, we have two initialized variables:
and
. The other two variables remain declared but not yet initialized.
This is where it gets tricky. Pay attention to tricky things! The exam will attempt to trick
you. Again, how many variables do you think are declared and initialized in this code?
As you should expect, three variables were declared:
, and
. However, only one
of those values was initialized:
. The other two remain declared but not yet initialized.
That’s the trick. Each snippet separated by a comma is a little declaration of its own. The
initialization of
only applies to
. It doesn’t have anything to do with
despite
being in the same statement.
Another way the exam could try to trick you is to show you code like this line:
This code doesn’t compile because it tries to declare multiple variables of
different
types
in the same statement. The shortcut to declare multiple variables in the same statement only
works when they share a type.
To make sure you understand this, see if you ca渠■
gure out which of the following are
legal declarations. Legal,踀₍valid,踀 an搠贀compiles踀 are all synonyms in the Java exam
world. We try to use all the terminology you could encounter on the exam.
Th攠■
rst statement is legal. It declares two variables without initializing them. The
second statement is also legal. It declares two variables and initializes only one of them.
The third statement is
not
legal. Java does not allow you to declare two different types
in the same statement. Wait a minute! Variables
and
are the same type. They are both
Declaring and Initializing Variables
c01.indd 1봀
4/2014 Page 27
of type
. Although that’s true, it still isn’t allowed. If you want to declare multiple
variables in the same statement, they must share the same type declaration and not repeat
it.
would have been legal.
The fourth statement is legal. Although
does appear twice, each one is in a separate
statement. A semicolon (
) separates statements in Java. It just so happens there are two
completely different statements on the same line. Th攠■
fth statement is
not
legal. Again,
we have two completely different statements on the same line. The second one is not a
valid declaration because it omits the type. When you see an oddly placed semicolon on the
exam, pretend the code is on separate lines and think about whether the code compiles that
way. In this case, we have the following:
Looking at the last line on its own, you can easily see that the declaration is invalid.
And yes, the exam really does cram multiple statements onto the same line—partly to
try to trick you and partly to 
t more code on the screen. In the real world, please limit
yourself to one declaration per statement and line. Your teammates will thank you for the
readable code.
Identifiers
It probably comes as no surprise that Java has precise rules about
identi■
er
names. Luckily,
the same rules for identi■
ers apply to anything you are free to name, including variables,
methods, classes, an搠■
elds.
There are only three rules to remember for legal identi■
ers:
The name must begin with a letter or the symbol
Subsequent characters may also be numbers.
You cannot use the same name as a Java
reserved word
. As you might imagine, a
reserved word is a keyword that Java has reserved so that you are not allowed to use it.
Remember that Java is case sensitive, so you can use versions of the keywords that only
differ in case. Please don’t, though.
Don’t worry—you won’t need to memorize the full list of reserved words. The exam will
only ask you about ones you’ve already learned, such as
. The following is a list of all
the reserved words in Java.
and
aren’t actually used in Java. They are reserved
so that people coming from other languages don’t use them by accident—and in theory, in
case Java wants to use them one day.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 28
abstractassertbooleanbreakbyte
casecatchcharclassconst*
continuedefaultdodoubleelse
enumextendsfalsefinalfinally
floatforgoto*ifimplements
importinstanceofintinterfacelong
nativenewnullpackageprivate
Understanding Default Initialization of Variables
c01.indd 1봀
4/2014 Page 29
Identifi
ers in the Real World
Most Java developers follow these conventions for identifi
er names:
Method and variables names begin with a lowercase letter followed by CamelCase.
Class names begin with an uppercase letter followed by CamelCase. Don’t start any
identifi
ers with
. The compiler uses this symbol for someₓ
les.
Also, know that valid letters in Java are not just characters in the English alphabet. Java
supports the Unicode character set, so there are more than 45,000 characters that can
start a legal Java identifi
er. A few hundred more are non-Arabic numerals that may
appear after th攠fi
rst character in a legal identifi
er. Luckily, you don’t have to worry about
memorizing those for the exam. If you are in a country that doesn’t use the English alpha-
bet, this is useful to know for a job.
Understanding Default Initialization of
Variables
Before you can use a variable, it needs a value. Some types of variables get this value
set automatically, and others require the programmer to specify it. In the following
sections, well look at the differences between the defaults for local, instance, and
class variables.
Local Variables
local variable
is a variable de■
ned within a method. Local variables must be initialized
before use. They do not have a default value and contain garbage data until initialized. The
compiler will not let you read an uninitialized value. For example, the following code
generates a compiler error:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 30
is initialized to 10. However, because
is not initialized before it is used in the expres-
sion on line 7, the compiler generates the following error:
Until
is assigned a value, it cannot appear within an expression, and the compiler will
gladly remind you of this rule. The compiler knows your code has control of what happens
inside the method and can be expected to initialize values.
The compiler is smart enough to recognize variables that have been initialized after their
declaration but before they are used. He牥’s an example:
Understanding Variable Scope
c01.indd 1봀
4/2014 Page 31
You can tell a variable is a class variable because it has the keyword
before it. You’ll
learn about this in Chapter 4. For now, just know that a variable is a class variable if it has
the
keyword in its declaration.
Instance and class variables do not require you to initialize them. As soon as you declare
these variables, they are given a default value. You’ll need to memorize everything in table
1.2 except the default value of
. To make this easier, remember that the compiler
doesn’t know what value to use and so wants the simplest type it can give the value:
for an object and
for a primitive.
TABLE 1.2
Default initialization values by type
Variable type
Default initialization value
booleanfalse
long0
(in the type’s bit-length⤀
double0.0
(in the type’s bit-length⤀
char'\u0000'
(NUL⤀
All object references (everything else⤀
Understanding Variable Scope
You’ve learned that local variables are declared within a method. How many local variables
do you see in this example?
There are two local variables in this method.
bitesOfCheese
is declared inside the
method.
piecesOfCheese
is called a method parameter. It is also local to the method. Both
of these variables are said to have a
scope
local to the method. This means they cannot be
used outside the method.
Local variables can never have a scope larger than the method they are de■
ned in.
However, they can have a smaller scope. Consider this example:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 32
hungry
has a scope of the entire method.
bitesOfCheese
has a smaller scope. It is only
available for use in the
statement because it is declared inside of it. When you see a set of
braces (
) in the code, it means you have entered a new block of code. Each block of code
has its own scope. When there are multiple blocks, you match them from the inside out.
In our case, the
statement block begins at line 4 and ends at line 6. The method’s block
begins at line 3 and ends at line 8.
Since
bitesOfCheese
is declared in such a block, the scope is limited to that block. When
the compiler gets to line 7, it complains that it doesn’t know anything about this
bitesOf-
Cheese
thing and gives an error:
Remember that blocks can contain other blocks. These smaller contained blocks can ref-
erence variables de■
ned in the larger scoped blocks, but not vice versa. For example:
The variable de■
ned on line 18 is in scope until the block ends on line 23. Using it in the
smaller block from lines 19 to 22 is 
ne. The variable de■
ned on line 20 goes out of scope
on line 22. Using it on line 24 is not allowed.
The exam may attempt to trick you with questions on scope. You’ll probably see a ques-
tion that appears to be about something complex and fails to compile because one of the
variables is out of scope. Let’s try one. Don’t worry if you aren’t familiar with
state-
ments or
loops yet. It doesn’t matter what the code does since we are talking about
scope. See if you ca渠■
gure out on which line each of th攠■
ve local variables goes into and
out of scope:
Understanding Variable Scope
c01.indd 1봀
4/2014 Page 33
Th攠■
rst step in 
guring out the scope is to identify the blocks of code. In this case, there
are three blocks. You can tell this because there are three sets of braces. Starting from the
innermost set, we can see where the
loop’s block starts and ends. Repeat this as we
go out for the
statement block and method block. Table 1.3 shows the line numbers that
each block starts and ends on.
TABLE 1.3
Blocks for scope
First line in block
Last line in block
1519
1320
Method1122
You’ll want to practice this skill a lot. Identifying blocks needs to be second nature for
the exam. The good news is that there are lots of code examples to practice on. You can
look at any code example in this book on any topic and match up braces.
Now that we know where the blocks are, we can look at the scope of each variable.
hungry
and
amountOfFood
are method parameters, so they are available for the entire
method. This means their scope is lines 11 to 22.
roomInBelly
goes into scope on line 12
because that is where it is declared. It stays in scope for the rest of the method and so goes
out of scope on line 22.
timeToEat
goes into scope on line 14 where it is declared. It goes
out of scope on line 20 where the
block ends.
amountEaten
goes into scope on line 16
where it is declared. It goes out of scope on line 19 where the
block ends.
All that was for local variables. Luckily the rule for instance variables is easier: they are
available as soon as they are de■
ned and last for the entire lifetime of the object itself. The
rule for class (static⤀ variables is even easier: they go into scope when declared like the other
variables types. However, they stay in scope for the entire life of the program.
Let’s do one more example to make sure you have a handle on this. Again, try to 
gure
out the type of the four variables and when they go into and out of scope.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 34
In this class, we have one class variable (
MAX_LENGTH
⤀, one instance variable (
length
),
and two local variables (
inches
and
newSize
.)
MAX_LENGTH
is a class variable because it has
the
keyword in its declaration.
MAX_LENGTH
goes into scope on line 2 where it is
declared. It stays in scope until the program ends.
length
goes into scope on line 3 where
it is declared. It stays in scope as long as this
object exists.
inches
goes into scope
where it is declared on line 4. It goes out of scope at the end of the method on line 9.
newSize
goes into scope where it is declared on line 6. Since it is de■
ned inside the
state-
ment block, it goes out of scope when that block ends on line 8.
Got all that? Let’s review the rules on scope:
Local variables—in scope from declaration to end of block
Instance variables—in scope from declaration until object garbage collected
Class variables—in scope from declaration until program ends
Ordering Elements in a Class
Now that you’ve seen the most common parts of a class, let’s take a look at the correct
order to type them into a 
le. Comments can go anywhere in the code. Beyond that, you
need to memorize the rules in Table 1.4.
TABLE 1.4
Elements of a class
Element
Example
Required?
Where does it go?
Package declaration
NoFirst line in the file
Import statements
NoImmediately after the package
Class declaration
YesImmediately after the import
Field declarations
NoAnywhere inside a class
Method declarations
Ordering Elements in a Class
c01.indd 1봀
4/2014 Page 35
Let’s look at a few examples to help you remember this. Th攠■
rst example contains one
of each element:
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 36
Destroying Objects
Now that weve played with our objects, it is time to put them away. Luckily, Java auto-
matically takes care of that for you. Java provides a garbage collector to automatically look
for objects that aren’t needed anymore.
All Java objects are stored in your program memory’s
heap
. The heap, which is also
referred to as the free store
represents a large pool of unused memory allocated to your
Java application. The heap may be quite large, depending on your environment, but there is
always a limit to its size. If your program keeps instantiating objects and leaving them on
the heap, eventually it will run out of memory.
In the following sections, well look at garbage collection and the
method.
Garbage Collection
Garbage collection refers to the process of automatically freeing memory on the heap by
deleting objects that are no longer reachable in your program. There are many different
algorithms for garbage collection, but you don’t need to know any of them for the exam.
You
need to know that
is not guaranteed to run, and you should be able to
recognize when objects become eligible for garbage collection.
Let’s start with th攠■
rst one. Java provides a method called
. Now you
might think from the name that this tells Java to run garbage collection. Nope! It meekly
suggests
that now might be a good time for Java to kick off a garbage collection run. Java is
free to ignore the request.
The more interesting part of garbage collection is when the memory belonging to an
object can be reclaimed. Java waits patiently until the code no longer needs that memory.
An object will remain on the heap until it is no longer reachable. An object is no longer
reachable when one of two situations occurs:
The object no longer has any references pointing to it.
All references to the object have gone out of scope.
Objects vs. References
Do not confuse a reference with the object that it refers to; they are two different enti-
ties. The reference is a variable that has a name and can be used to access the contents
of an object. A reference can be assigned to another reference, passed to a method, or
returned from a method. All references are the same size, no matter what their type is.
An object sits on the heap and does not have a name. Therefore, you have no way to
access an object except through a reference. Objects come in all different shapes and
sizes and consume varying amounts of memory. An object cannot be assigned to another
Destroying Objects
c01.indd 1봀
4/2014 Page 37
object, nor can an object be passed to a method or returned from a method. It is the
object that gets garbage collected, not its reference.
accessed via a reference. Objects vary in
Realizing the difference between a reference and an object goes a long way toward
understanding garbage collection, the
operator, and many other facets of the Java
language. Look at this code and see if you ca渠■
gure out when each object 
rst becomes
eligible for garbage collection:
)3: String one, two;4: one = new String("a");5: two = new String("b");6: one = two;7: String three = one;8: one = null;9: } }When you get asked a question about garbage collection on the exam, we recommend
you draw what’s going on. Theres a lot to keep track of in your head and it’s easy to make
a silly mistake trying to keep it all in your memory. Let’s try it together now. Really. Get a
pencil and paper. We’ll wait.
Got that paper? Okay, let’s get started. On line 3, we write
and
two
. Just the words.
No need for boxes or arrows yet since no objects have gone on the heap yet. On line 4,
we have ou爠■
rst object. Draw a box with the string
in it and draw an arrow from the
word
to that box. Line 5 is similar. Draw another box with the string
in it this time
and an arrow from the word
two
. At this point, your work should look like Figure 1.2.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 38
FIGURE 1.2
Your drawing after line 5
On line 6, the variable
changes to point to
. Either erase or cross out the arrow
from
and draw a new arrow from
. On line 7, we have a new variable, so
write the word
three
and draw an arrow from
three
. Notice that
three
points to
what
is pointing to right now and not what it was pointing to at the beginning. This
is why we are drawing pictures. It’s easy to forget something like that. At this point, your
work should look like Figure 1.3.
FIGURE 1.3
Your drawing after line 7
Finally, cross out the line between
and
since line 8 sets this variable to null.
Now, we were trying to 
nd out when the objects were 
rst eligible for garbage collection.
On line 6, we got rid of the only arrow pointing to
, making that object eligible for
garbage collection.
has arrows pointing to it until it goes out of scope. This means
doesn’t go out of scope until the end of the method on line 9.
finalize⠀⤀
Java allows objects to implement a method called
that might get called. This
method gets called if the garbage collector tries to collect the object. If the garbage collector
doesn’t run, the method doesn’t get called. If the garbage collector fails to collect the object
and tries to run it again later, the method doesn’t get called a second time.
In practice, this means you are highly unlikely to use it in real projects. Luckily, there
isn’t much to remember about
for the exam. Just keep in mind that it might not
get called and that it de■
nitely won’t be called twice.
With that said, this call produces no output when we run it:
Benefits of Java
c01.indd 1봀
4/2014 Page 39
) Finalizer f = new Finalizer(); } }The reason is that the program exits before there is any need to run the garbage collec-
tor. While
is eligible for garbage collection, Java has better things to do than take out the
trash constantly. For the exam, you need to know that this
call could run zero
or one time. Now for a more interesting example:
Remember,
is only run when the object is eligible for garbage collection. The
problem here is that by the end of the method, the object is no longer eligible for garbage
collection because a static variable is referring to it and static variables stay in scope until
the program ends. Java is smart enough to realize this and aborts the attempt to throw out
the object. Now suppose later in the program
objects
is set to
. Oh, good, we can
nally remove the object from memory. Java remembers already running
this object and will not do so again. The lesson is that the
call could run zero
or one time. This is the exact same lesson as the simple example—that’s why it’s so easy to
remember.
Benefits of Java
Java has some key bene■
ts that you’ll need to k
now for the exam:
Object Oriented
Java is an object-oriented language, which means all code is de■
ned in
classes and most of those classes can be instantiated into objects. We’ll discuss this more
throughout the book. Many languages before Java were procedural, which meant there were
routines or methods but no classes. Another common approach is functional programming.
Java allows for functional programming within a class, but object oriented is still the main
organization of code.
Encapsulation
Java supports access modi■
ers to protect data from unintended access
and modi■
cation. Most people consider encapsulation to be an aspect of object-oriented
languages. Since the exam objectives call attention to it speci■
cally, so do we.
Platform Independent
Java is an interpreted language because it gets compiled to
bytecode. A key bene■
t is that Java code gets compiled once rather than needing to be
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 40
recompiled for different operating systems. This is known as₍write once, run everywhere.踀
On the OCP exam, you’ll learn that it is possible to write code that does not run every-
where. For example, you might refer to a 
le in a speci■
c directory. If you get asked on the
OCA exam, the answer is that the same clas猠■
les run everywhere.
Robust
One of the major advantages of Java over C++ is that it prevents memory leaks.
Java manages memory on its own and does garbage collection automatically. Bad memory
management in C++ is a big source of errors in programs.
Simple
Java was intended to be simpler than C++. In addition to eliminating pointers,
it got rid of operator overloading. In C++, you could write a + b and have it mean almost
anything.
Secure
Java code runs inside the JVM. This creates a sandbox that makes it hard for Java
code to do evil things to the computer it is running on.
Summary
In this chapter, you saw that Java classes consist of members called 
elds and methods. An
object is an instance of a Java class. There are three styles of comment: a single-line com-
ment (
⤀, a multiline comment (
⤀, and a Javadoc comment (
Java begins program execution with a
method. The most common signature for
this method run from the command line is
). Arguments are passed in after the class name, as in
Arguments are indexed starting with 0.
Java code is organized into folders called packages. To reference classes in other pack-
ages, you use an import statement. A wildcard ending an import statement means you want
to import all classes in that package. It does not include packages that are inside that one.
is a special package that does not need to be imported.
Constructors create Java objects. A constructor is a method matching the class name and
omitting the return type. When an object is instantiatedⰠ■
elds and blocks of code are
initialize搠■
rst. Then the constructor is run.
Primitive types are the basic building blocks of Java types. They are assembled into
reference types. Reference types can have methods and be assigned to
. In addition to
贀normal踀 numbers, numeric literals are allowed to begin with 0 (octal⤀, 0x (hex⤀, 0X (hex⤀,
0b (binary⤀, or 0B (binary⤀. Numeric literals are also allowed to contain underscores as long
as they are directly between two other numbers.
Declaring a variable involves stating the data type and giving the variable a name.
Variables that represen琠■
elds in a class are automatically initialized to their correspond-
in朠贀zero踀 or null value during object instantiation. Local variables must be speci■
cally
initialized. Identi■
ers may contain letters, numbers, $, or _. Identi■
ers may not begin with
numbers.
Scope refers to that portion of code where a variable can be accessed. There are three
kinds of variables in Java, depending on their scope: instance variables, class variables, and
Exam Essentials
c01.indd 1봀
4/2014 Page 41
local variables. Instance variables are the nonstati挠■
elds of your class. Class variables are
the static 
elds within a class. Local variables are declared within a method.
For some class elements, order matters within th攠■
le. The package statement come猠■
rst
if present. Then comes the import statements if present. Then comes the class declaration.
Fields and methods are allowed to be in any order within the class.
Garbage collection is responsible for removing objects from memory when they can
never be used again. An object becomes eligible for garbage collection when there are no
more references to it or its references have all gone out of scope. The
method
will run once for each object if/when it is 
rst garbage collected.
Java code is object oriented, meaning all code is de■
ned in classes. Access modi■
ers
allow classes to encapsulate data. Java is platform independent, compiling to bytecode. It is
robust and simple by not providing pointers or operator overloading. Finally, Java is secure
because it runs inside a virtual machine.
Exam Essentials
Be able to write code using a main⠀⤀ method.
method is usually written as
public
⤀. Arguments are referenced starting with
. Accessing
an argument that wasn’t passed in will cause the code to throw an exception.
Understand the effect of using packages and imports.
Packages contain Java classes.
Classes can be imported by class name or wildcard. Wildcards do not look at subdirecto-
ries. In the event of a con.
ict, class name imports take precedence.
Be able to recognize a constructor.
A constructor has the same name as the class. It looks
like a method without a return type.
Be able to identify legal and illegal declarations and initialization.
Multiple variables can
be declared and initialized in the same statement when they share a type. Local variables
require an explicit initialization; others use the default value for that type. Identi■
ers may
contain letters, numbers, $, or _. Identi■
ers may not begin with numbers. Numeric literals
may contain underscores between two digits and begin with‱–9, 0, 0x, 0X, 0b, and 0B.
Be able to determine where variables go into and out of scope.
All variables go into scope
when they are declared. Local variables go out of scope when the block they are declared
in ends. Instance variables go out of scope when the object is garbage collected. Class vari-
ables remain in scope as long as the program is running.
Be able to recognize misplaced statements in a class.
Package and import statements are
optional. If present, both go before the class declaration in that order. Fields and methods
are also optional and are allowed in any order within the class declaration.
Know how to identify when an object is eligible for garbage collection.
Draw a diagram
to keep track of references and objects as you trace the code. When no arrows point to a
box (object⤀, it is eligible for garbage collection.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 42
Review Questions
Which of the following are valid Java identifiers? (Choose all that apply⤀
What is the output of the following program?
)5: WaterBottle wb = new WaterBottle();6: System.out.print("Empty = " + wb.empty);7: System.out.print(", Brand = " + wb.brand);8: } } A. Line 6 generates a compiler error.
Line 7 generates a compiler error.
There is no output.
Which of the following are true? (Choose all that apply⤀
Review Questions
c01.indd 1봀
4/2014 Page 43
Line 9 generates a compiler error.
The code compiles as is.
Given the following class, which of the following is true? (Choose all that apply⤀
If
is inserted on line 2, the code will compile.
If
is inserted on line 4, the code will compile.
If
is inserted on line 6, the code will compile.
If
is inserted on line 9, the code will compile.
None of the above changes will make the code compile.
Given the following classes, which of the following can independently replace
to make the code compile? (Choose all that apply⤀
None of these can make the code compile.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 44
Given the following classes, what is the maximum number of imports that can be removed
and have the code still compile?
Does not compile.
Given the following classes, which of the following snippets can be inserted in place of
and have the code compile? (Choose all that apply⤀
Review Questions
c01.indd 1봀
4/2014 Page 45
None of these imports can make the code compile.
Given the following class, which of the following calls print out
? (Choose all that
apply⤀
) System.out.println(name[1]);} }A. java BirdDisplay Sparrow Blue JayB. java BirdDisplay Sparrow "Blue Jay"C. java BirdDisplay Blue Jay SparrowD. java BirdDisplay "Blue Jay" SparrowE. java BirdDisplay.class Sparrow "Blue Jay"F. java BirdDisplay.class "Blue Jay" SparrowG. Does not compile.
Which of the following legally fill in the blank so you can run the
method from the
command line? (Choose all that apply⤀
B. String[] 123C. String abc[]D. String _Names[]E. String... $nF. String namesG. None of the above.
10.
Which of the following are legal entry point methods that can be run from the command
line? (Choose all that apply⤀
)B. public static final main(String[] args) C. public void main(String[] args) D. public static void test(String[] args) E. public static void main(String[] args) F. public static main(String[] args) G. None of the above.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 46
11.
Which of the following are true? (Choose all that apply⤀
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
None of the above.
12.
Which of the following are true? (Choose all that apply⤀
A local variable of type
defaults to
A local variable of type
defaults to
A local variable of type
defaults to
A local variable of type
defaults to
A local variable of type
defaults to
A local variable of type
defaults to
None of the above.
13.
Which of the following are true? (Choose all that apply⤀
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
An instance variable of type
defaults to
None of the above.
14.
Given the following class in the file
Which of the following replaces
if we compile from
⠀Choose all that apply⤀
Does not compile.
Review Questions
c01.indd 1봀
4/2014 Page 47
15.
Which of the following lines of code compile? (Choose all that apply⤀
None of the above.
16.
Given the following class, which of the following lines of code can replace
to make the code compile? (Choose all that apply⤀
None of the above.
17.
Which of the following are true? (Choose all that apply⤀
) Bunny bun = new Bunny();} }A. Bunny is a class.
is a class.
is a class.
is a reference to an object.
is a reference to an object.
is a reference to an object.
None of the above.
18.
Which represent the order in which the following statements can be assembled into a pro-
gram that will compile successfully? (Choose all that apply⤀
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 48
A, B, C
B, C, A
C, B, A
B, A
C, A
A, C
A, B
19.
Suppose we have a class named
. Which of the following statements are true?
⠀Choose all that apply⤀
)3: Rabbit one = new Rabbit();4: Rabbit two = new Rabbit();5: Rabbit three = one;6: one = null;7: Rabbit four = one;8: three = null;9: two = null;10: two = new Rabbit();11: System.gc();12: } }A. The
object from line 3 is first eligible for garbage collection immediately
following line 6.
The
object from line 3 is first eligible for garbage collection immediately
following line 8.
The
object from line 3 is first eligible for garbage collection immediately
following line 12.
The
object from line 4 is first eligible for garbage collection immediately
following line 9.
The
object from line 4 is first eligible for garbage collection immediately
following line 11.
The
object from line 4 is first eligible for garbage collection immediately
following line 12.
20.
What is true about the following code? (Choose all that apply⤀
Review Questions
c01.indd 1봀
4/2014 Page 49
) Bear bear = new Bear(); bear = null; System.gc();} }A. finalize() is guaranteed to be called.
might or might not be called
is guaranteed not to be called.
Garbage collection is guaranteed to run.
Garbage collection might or might not run.
Garbage collection is guaranteed not to run.
The code does not compile.
21.
What does the following code output?
)7: Salmon s = new Salmon();8: System.out.println(s.count);9: } }A. 0B. 4C. Compilation fails on line 3.
Compilation fails on line 4.
Compilation fails on line 7.
Compilation fails on line 8.
22.
Which of the following are true statements? (Choose all that apply⤀
Java allows operator overloading.
Java code compiled on Windows can run on Linux.
Java has pointers to specific locations in memory.
Java is a procedural language.
Java is an object-oriented language.
Java is a functional programming language.
Chapter 1
Java Building Blocks
c01.indd 1봀
4/2014 Page 50
23.
Which of the following are true? (Choose all that apply⤀
compiles a
file into a
file.
compiles a
file into a
file.
compiles a
file into a
file.
Java takes the name of the class as a parameter.
Java takes the name of the
file as a parameter.
Java takes the name of the
file as a parameter.
c02.indd 1봀
5/2014 Page 51
Chapter
Operators and
Statements
OCA EXAM OBJECTIVES COVERED IN THIS
CHAPTER:
Using Operators and Decision Constructs
Use Java operators; including parentheses to override opera-
tor precedence
Create if and if/else and ternary constructs
Use a switch statement
Using Loop Constructs
Create and use while loops
Create and use for loops including the enhanced for loop
Create and use do/while loops
Compare loop constructs
Use break and continue
c02.indd 1봀
5/2014 Page 52
Like many programming languages, Java is composed primar-
ily of variables, operators, and statements put together in some
logical order. In the previous chapter, we discussed variables
and gave some examples; in this chapter well discuss the various operators and statements
available to you within the language. This knowledge will allow you to build complex func-
tions and class structures that you’ll see in later chapters.
Understanding Java Operators
A Java
operator
is a special symbol that can be applied to a set of variables, values, or
literals—referred to as operands—and that returns a result. Thre攠■
avors of operators are
available in Java: unary, binary, and ternary. These types of operators can be applied to
one, two, or three operands, respectively. For the OCA exam, you’ll need know a speci.
c
subset of Java operators, how to apply them, and the order in which they should be applied.
Java operators are not necessarily evaluated from left-to-right order. For example, the
following Java expression is actually evaluated from right-to-left given the speci.
c opera-
tors involved:
In this example, you woul搠.
rst decrement
, and then multiply the resulting value
, an搠.
nally add
. The value would then be automatically upcast from
and
assigned to
. Th攠.
nal values of
and
would be
and
, respectively. If you didn’t
follow that evaluation, don’t worry. By the end of this chapter, solving problems like this
should be second nature.
Unless overridden with parentheses, Java operators follow
order of operation
, listed in
Table 2.1, by decreasing order of
operator precedence
. If two operators have the same level
of precedence, then Java guarantees left-to-right evaluation. You need to know only those
operators in bold for the OCA exam.
TABLE 2.1
Order of operator precedence
Operator
Symbols and examples
Post-unary operators
expression
expression
Pre-unary operators
expression
expression
Working with Binary Arithmetic Operators
c02.indd 1봀
5/2014 Page 53
Operator
Symbols and examples
Other unary operators
Multiplication/Division/Modulus
Addition/Subtraction
Shift operators
Relational operators
Equal to/not equal to
Logical operators
Short-circuit logical operators
Ternary operators
Assignment operators
We’ll spend th攠.
rst half of this chapter discussing many of the operators in this list as
well as how operator precedence determines which operators should be applie搠.
rst. Note
that you won’t be tested on some operators, although we recommend that you be aware of
their existence.
Working with Binary Arithmetic
Operators
We’ll begin our discussion with
binary operators
, by far the most common operators in
the Java language. They can be used to perform mathematical operations on variables,
create logical expressions, as well as perform basic variable assignments. Binary operators
are commonly combined in complex expressions with more than two variables; therefore,
operator precedence is very important in evaluating expressions.
Arithmetic Operators
⤀, multiplication (
⤀, division (
⤀, and modulus (
⤀. They also include the
unary operators,
and
, although we cover them later in this chapter. As you may have
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 54
noticed in Table 2.1, the
multiplicative
operators (
) have a higher order of precedence
than the
additive
operators (
⤀. That means when you see an expression such as this:
yo甠.
rst evaluate the
and
, which reduces the expression to the following:
Then, you evaluate the remaining terms in left-to-right order, resulting in a value of
of
. Make sure you understand why the result is
as you’ll likely see this kind of operator
precedence question on the exam.
Notice that we said₍Unless overridden with parenthese玃Ž prior to Table 2.1. That’s
because you can change the order of operation explicitly by wrapping parentheses around
the sections you want evaluate搠.
rst. Compare the previous example with the following
one containing the same values and operators, in the same order, but with two sets of
parentheses:
This time you would evaluate the addition operator
, which reduces the expres-
sion to the following:
You can further reduce this expression by multiplying th攠.
rst two values within the
parentheses:
Next, you subtract the values within the parentheses before applying terms outside the
parentheses:
Finally, you would multiply the result by
, resulting in a value of
All of the arithmetic operators may be applied to any Java primitives, except
and
. Furthermore, only the addition operators
and += may be applied to
values, which results in
concatenation.
Although we are sure you have seen most of the arithmetic operators before, the modu-
lus operator,
, may be new to you. The modulus, or remainder operator, is simply the
remainder when two numbers are divided. For example,
divided by
divides evenly and
has no remainder; therefore, the remainder, or
, is
. On the other hand,
divided
does not divide evenly; therefore, the remainder, or
, is
Be sure to understand the difference between arithmetic division and modulus. For inte-
ger values, division results in th攠■
oor value of the nearest integer that ful.
lls the operation,
whereas modulus is the remainder value. The following examples illustrate this distinction:
Working with Binary Arithmetic Operators
c02.indd 1봀
5/2014 Page 55
Note that the division results only increase when the value on the left-hand side goes
from
, whereas the modulus remainder value increases by
each time the left-hand
side is increased until it wraps around to zero. For a given divisor
, which is
in these
examples, the modulus operation results in a value between
and
for positive divi-
dends. This means that the result of a modulus operation is always
The modulus operation is not limited to positive integer values in Java
and may also be applied to negative integers and floating-point integers.
For a given divisor
and negative dividend, the resulting modulus value
is between and
and
. For the OCA exam, though, you are not
required to be able to take the modulus of a negative integer or a floating-
point number.
Numeric Promotion
Now that you understand the basics of arithmetic operators, it is vital we talk about primi-
tive
numeric promotion
, as Java may do things that seem unusual to you at 
rst. If you
recall in Chapter 1,₍Java Building Blocks,踀 where we listed the primitive numeric types,
each primitive has a bit-length. You don’t need to know the exact size of these types for the
exam, but you should know which are bigger than others. For example, you should know
that a
takes up more space than an
, which in turn takes up more space than a
, and so on.
You should memorize certain rules Java will follow when applying operators to data
types:
Numeric Promotion Rules
If two values have different data types, Java will automatically promote one of the val-
ues to the larger of the two data types.
If one of the values is integral and the other is floating-point, Java will automatically
promote the integral value to the floating-point valu斐s data type.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 56
Smaller data types, namely
, and
, are first promoted to
any time
they’re used with a Java binary arithmetic operator, even if neither of the operands is
After all promotion has occurred and the operands have the same data type, the result-
ing value will have the same data type as its promoted operands.
The last two rules are the ones most people have trouble with, and the ones likely to trip
you up on the exam. For the third rule, note that unary operators are excluded from this
rule. For example, applying
value results in a
value. We’ll discuss unary
operators in the next section.
Let’s tackle some examples for illustrative purposes:
What is the data type of
If we follow th攠.
rst rule, since one of the values is
and the other is
, and
is larger than
, then the
value is promoted to a
, and the resulting value is
What is the data type of
This is actually a trick question, as this code will not compile! As you may remember
from Chapter 1, 
oating-point literals are assumed to be
, unless post.
xed with
an
, as in
. If the value was set properly to
, then the promotion would be
similar to the last example, with both operands being promoted to a
, and the
result would be a
value.
What is the data type of
In this case, we must apply the third rule, namely that
and
will both be promoted
before the operation, resulting in an output of type
. Pay close attention to
the fact that the resulting output is not a
, as well come back to this example in
the upcoming section on assignment operators.
What is the data type of
In this case, we must apply all of the rules. First,
will automatically be promoted to
solely because it is a
and it is being used in an arithmetic binary operation.
Working with Unary Operators
c02.indd 1봀
5/2014 Page 57
The promoted
value will then be automatically promoted to a
so that it can be
multiplied with
. The result of
will then be automatically promoted to a
so that it can be multiplied with
, resulting in a
value.
Working with Unary Operators
By de.
nition, a
unary
operator is one that requires exactly one operand, or variable, to
function. As shown in Table 2.2, they often perform simple tasks, such as increasing a
numeric variable by one, or negating a
value.
TABLE 2.2
Java unary operators
Unary operator
Description
Indicates a number is positive, although numbers are assumed
to be positive in Java unless accompanied by a negative unary
operator
Indicates a literal number is negative or negates an expression
Increments a value by 1
Decrements a value by 1
Inverts a Boolean’s logical value
Logical Complement and Negation Operators
The
logical complement operator,
ips the value of a
expression. For example,
if the value is
, it will be converted to
, and vice versa. To illustrate this, compare
the outputs of the following statements:
Likewise, the
negation operator
, reverses the sign of a numeric expression, as shown
in these statements:
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 58
Based on the description, it might be obvious that some operators require the variable
or expression they’re acting upon to be of a speci.
c type. For example, you cannot apply
a negation operator,
expression, nor can you apply a logical complement
operator,
, to a numeric expression. Be wary of questions on the exam that try to do this,
as they’ll cause the code to fail to compile. For example, none of the following lines of code
will compile:
Th攠.
rst statement will not compile due the fact that in Java you cannot perform a
logical inversion of a numeric value. The second statement does not compile because you
cannot numerically negate a
value; you need to use the logical inverse operator.
Finally, the last statement does not compile because you cannot take the logical comple-
ment of a numeric value, nor can you assign an integer to a
variable.
Keep an eye out for questions on the exam that use the logical complement
operator or numeric values with
expressions or variables. Unlike
some other programming languages, in Java
and
are not related in
any way, just as
and
are not related.
Increment and Decrement Operators
Increment and decrement operators,
and
, respectively, can be applied to numeric
operands and have the higher order or precedence, as compared to binary operators. In
other words, they often get applie搠.
rst to an expression.
Increment and decrement operators require special care because the order they are
applied to their associated operand can make a difference in how an expression is pro-
cessed. If the operator is placed before the operand, referred to as the
pre-increment opera-
and the
pre-decrement operator
, then the operator is applie搠.
rst and the value return
is the
new value
of the expression. Alternatively, if the operator is placed after the operand,
referred to as the
post-increment operator
and the
post-decrement operator
, then the
origi-
nal value
of the expression is returned, with operator applied after the value is returned.
Working with Unary Operators
c02.indd 1봀
5/2014 Page 59
The following code snippet illustrates this distinction:
Th攠.
rst pre-increment operator updates the value for
and outputs the new
value of
. The next post-decrement operator also updates the value of
but outputs
the value before the decrement occurs.
One common practice in a certi.
cation exam, albeit less common in the real world, is to
apply multiple increment or decrement operators to a single variable on the same line:
This one is more complicated than the previous example because
is modi.
ed three
times on the same line. Each time it is modi.
ed, as the expression moves from left to right,
the value of
changes, with different values being assigned to the variable. As you’ll recall
from our discussion on operator precedence, order of operation plays an important part in
evaluating this example.
So how do you read this code? First, the
is incremented and returned to the expression,
which is multiplied by
. We can simplify this:
Next,
is decremented, but the original value of
is used in the expression, leading to
this:
Th攠.
nal assignment of
reduces the value to
, and since this is a pre-increment opera-
tor, that value is returned to the expression:
Finally, we evaluate the multiple and division from left-to-right, an搠.
nish with the addi-
tion. The result is then printed:
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 60
Using Additional Binary Operators
We’ll now expand our discussion of binary operators to include all other binary operators
that you’ll need to know for the exam. This includes operators that perform assignments,
those that compare arithmetic values and return
results, and those that compare
and object values and return
results.
Assignment Operators
An
assignment operator
is a binary operator that modi.
es, or assigns, the variable on
the left-hand side of the operator, with the result of the value on the right-hand side of
the equation. The simplest assignment operator is the
assignment, which you have seen
already:
This statement assigns
the value of
Java will automatically promote from smaller to larger data types, as we saw in the pre-
vious section on arithmetic operators, but it will throw a compiler exception if it detects
you are trying to convert from larger to smaller data types.
Let’s return to some examples similar to what you saw in Chapter 1 in order to show
how casting can resolve these issues:
Th攠.
rst statement does not compile because you are trying to assign a double
to an
integer value. Even though the value is a mathematic integer, by adding
, you’re instruct-
ing the compiler to treat it as a
. The second statement does not compile because the
literal value
is outside the range of
and the compiler detects this. The third
statement does not compile because of the
added to the end of the number that instructs
the compiler to treat the number as 
oating-point value. Finally, the last statement does not
compile because Java interprets the literal as an
and notices that the value is larger than
allows. The literal would need a post.
x
to be considered a
Casting Primitive Values
We ca渠.
x the examples in the previous section by casting the results to a smaller data
type. Casting primitives is required any time you are going from a larger numerical data
type to a smaller numerical data type, or converting from a 
oating-point number to an
integral value.
Using Additional Binary Operators
c02.indd 1봀
5/2014 Page 61
Over鐀
ow and Under鐀
ow
The expressions in the previous example now compile, although there’s a cost. The sec-
ond value,
, is too large to be stored as a
, so numeric over鐀
ow occurs
and it becomes
Over鐀
ow
is when a number is so large that it will no longerₓ
t
within the data type, so the system₍wraps around踠to the next lowest value and counts
up from there. There’s also an analogous
under鐀
ow
, when the number is too low toₓ
t in
the data type.
This is beyond the scope of the exam, but something to be careful of in your own code.
For example, the following statement outputs a negative number:
Since
is the maximum
value, adding any strictly positive value to it will
cause it to wrap to the next negative number.
Let’s return to one of our earlier examples for a moment:
Based on everything you have learned up until now, can you understand why the last
line of this statement will not compile? If you remember,
values are automatically
promoted to
when applying any arithmetic operator, with the resulting value being of
type
. Trying to set a
variable to an
results in a compiler error, as Java thinks
you are trying to implicitly convert from a larger data type to a smaller one.
There are times that you may want to override the default behavior of the compiler. For
example, in the preceding example, we know the result of
is
, which can easily
t into a
variable. If you need the result to be a
, though, you can override this
behavior by casting the result of the multiplication:
By performing this explicit cast of a larger value into a smaller data type, you are
instructing the compiler to ignore its default behavior. In other words, you are telling the
compiler that you have taken additional steps to prevent over■
ow or under■
ow. It is also
possible that in your particular application and scenario, over■
ow or under■
ow would
result in acceptable values.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 62
Compound Assignment Operators
Besides the simple assignment operator,
, there are also numerous
compound assignment
operators
. Only two of the compound operators listed in Table 2.1 are required for the
exam,
and
. Complex operators are really just glori.
ed forms of the simple assignment
operator, with a built-in arithmetic or logical operation that applies the left- and right-hand
sides of the statement and stores the resulting value in a variable in the left-hand side of the
statement. For example, the following two statements after the declaration of
and z are
equivalent:
The left-hand side of the compound operator can only be applied to a variable that is
already de.
ned and cannot be used to declare a new variable. In the previous example, if
was not already de.
ned, then the expression
would not compile.
Compound operators are useful for more than just shorthand—they can also save us
from having to explicitly cast a value. For example, consider the following example, in
which the last line will not compile due to the result being promoted to a
and assigned
to an
variable:
Based on the last two sections, you should be able to spot the problem in the last line.
This last line could be 
xed with an explicit cast to
, but theres a better way using the
compound assignment operator:
The compound operator will 
rst cast
, apply the multiplication of two
values, and then cast the result to an
. Unlike the previous example, in which the com-
piler threw an exception, in this example we see that the compiler will automatically cast
the resulting value to the data type of the value on the left-hand side of the compound
operator.
On攠.
nal thing to know about the assignment operator is that the result of the assign-
ment is an expression in and of itself, equal to the value of the assignment. For example, the
following snippet of code is perfectly valid, if not a little odd looking:
Using Additional Binary Operators
c02.indd 1봀
5/2014 Page 63
The key here is that
does two things. First, it sets the value of the variable
to be
. Second, it returns a value of the assignment, which is also
. The exam creators are fond
of inserting the assignment operator
in the middle of an expression and using the value of
the assignment as part of a more complex expression.
Relational Operators
We now move on to
relational operators
, which compare two expressions and return a
value. Th攠.
rst four relational operators (see Table 2.3⤀ are applied to numeric
primitive data types only. If the two numeric operands are not of the same data type, the
smaller one is promoted in the manner as previously discussed.
TABLE 2.3
Relational operators
Strictly less than
Less than or equal to
Strictly greater than
Greater than or equal to
Let’s look at examples of these operators in action:
Notice that the last example outputs
, because although
and
are the same
value,
is not strictly greater than
Th攠.
fth relational operator (Table 2.4⤀ is applied to object references and classes or
interfaces.
TABLE 2.4
Relational
operator
bTrue if the reference that a points to is an instance of
a class, subclass, or class that implements a particular
interface, as named in b
The
operator, while useful for determining whether an arbitrary object is a
member of a particular class or interface, is out of scope for the OCA exam.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 64
Logical Operators
If you have studied computer science, you may have already come across logical operators
before. If not, no need to panic—睥’ll be covering them in detail in this section.
The
logical operators
), (
⤀, and (
⤀, may be applied to both numeric and
data
types. When they’re applied to
data types, they’re referred to as
logical operators
Alternatively, when they’re applied to numeric data types, they’re referred to as
bitwise
operators
, as they perform bitwise comparisons of the bits that compose the number. For
the exam, though, you don’t need to know anything about numeric bitwise comparisons, so
睥’ll leave that educational aspect to other books.
You should familiarize with the truth tables in Figure 2.1, where
and
are assumed to
be
data types.
FIGURE 2.1
The logical true tables for
, and
Here are some tips to help remember this table:
AND is only true if both operands are true.
Inclusive OR is only false if both operands are false.
Exclusive OR is only true if the operands are different.
Finally, we present the conditional operators,
and
, which are often referred to as
short-circuit operators. The
short-circuit operators
are nearly identical to the logical opera-
tors,
and
, respectively, except that the right-hand side of the expression may never be
evaluated if th攠.
nal result can be determined by the left-hand side of the expression. For
example, consider the following statement:
Referring to the truth tables, the value
can only be false if both sides of the expression
are false. Since we know the left-hand side is true, theres no need to evaluate the right-hand
side, since no value of
will ever make the value of
anything other than true. It may help
you to illustrate this concept by executing the previous line of code for various values of
Using Additional Binary Operators
c02.indd 1봀
5/2014 Page 65
A more common example of where short-circuit operators are used is checking for
objects before performing an operation, such as this:
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 66
The comparisons for equality are limited to these three cases, so you cannot mix and
match types. For example, each of the following would result in a compiler error:
Pay close attention to the data types when you see an equality operator on the exam.
The exam creators also have a habit of mixing assignment operators and equality opera-
tors, as in the following snippet:
At 
rst glance, you might think the output should be
, and if the expression was
, then you would be correct. In this example, though, the expression is assign-
ing the value of
, and as you saw in the section on assignment operators, the
assignment itself has the value of the assignment. Therefore, the output would be
For object comparison, the equality operator is applied to the references to the objects,
not the objects they point to. Two references are equal if and only if they point to the same
object, or both point to
. Let’s take a look at some examples:
Even though all of the variables point to the same 
le information, only two,
and
are equal in terms of
. In this example, as well as during the OCA exam, you may be pre-
sented with classnames that are unfamiliar, such as
. Many times you can answer ques-
tions about these classes without knowing the speci.
c details of these classes. In particular,
you should be able to answer questions that indicate
and
are two separate and distinct
objects, even if you do not know the data types of these objects.
In Chapter 3,₍Core Java APIs,踀 well continue the discussion of object equality by intro-
ducing what it means for two different objects to be equivalent. We’ll also cover
equality and show how this can be a nontrivial topic.
Understanding Java Statements
Java operators allow you to create a lot of complex expressions, but they’re limited in the
manner in which they can control progra洠■
ow. For example, imagine you want a sec-
tion of code to only be executed under certain conditions that cannot be evaluated until
Understanding Java Statements
c02.indd 1봀
5/2014 Page 67
runtime. Or suppose you want a particular segment of code to repeat once for every item in
some list.
As you may recall from Chapter 1, a Java
statement
is a complete unit of execution in
Java, terminated with a semicolon (
⤀. For the remainder of the chapter, well be introduc-
ing you to various Java control 
ow statements.
Control 
ow statements
break up th攠■
ow
of execution by using decision making, looping, and branching, allowing the application to
selectively execute particular segments of code.
These statements can be applied to single expressions as well as a block of Java code.
As described in the previous chapter, a
block
of code in Java is a group of zero or more
statements between balanced braces, (
⤀, and can be used anywhere a single statement is
allowed.
if-then
Statement
Often, we only want to execute a block of code under certain circumstances. The
if-then
statement, as shown in Figure 2.2, accomplishes this by allowing our application to execute
a particular block of code if and only if a
expression evaluates to
at runtime.
FIGURE 2.2
The structure of an
statement
For example, imagine we had a function that used the hour of day, an integer value from
, to display a message to the user:
If the hour of the day is less than 11, then the message will be displayed. Now let’s say
we also wanted to increment some value,
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 68
The block allows multiple statements to be executed based on the
evaluation.
Notice that th攠.
rst statement didn’t contain a block around the print section, but it easily
could have. For readability, it is considered good coding practice to put blocks around the
execution component of
statements, as well as many other control 
ow statements,
although it is not required.
Watch Indentation and Braces
One area that the exam writers will try to trip you up is on
statements without
braces (
⤀. For example, take a look at this slightly modifi
ed form of our example:
Understanding Java Statements
c02.indd 1봀
5/2014 Page 69
FIGURE 2.3
The structure of an
statement
Let’s return to this example:
Now our code is truly branching between one of the two possible options, with the
evaluation happening only once. The
operator takes a statement or block of
statement, in the same manner as the
statement does. In this manner, we can append
additional
statements to an
block to arrive at a more re.
ned example:
In this example, the Java process will continue execution until it encounters an
statement that evaluates to
. If neither of th攠.
rst two expressions are
, it will
execute th攠.
nal code of the
block. One thing to keep in mind in creating complex
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 70
statements is that order is important. For example, see what happens if we
reorder the previous snippet of code as follows:
For hours of the day less than 11, this code behaves very differently than the previous set
of code. See if you can determine why the second block can never be executed regardless of
the value of
If a value is less than
, then it must be also less than
by de.
nition. Therefore, if the
second branch in the example can be reached, th攠.
rst branch can also be reached. Since
execution of each branch is mutually exclusive in this example—that is, only one branch
can be executed—if th攠.
rst branch is executed, then the second cannot be executed.
Therefore, there is no way the second branch will ever be executed, and the code is deemed
unreachable.
Verifying the
Statement Evaluates to a Boolean Expression
Another common place the exam may try to lead you astray is by providing code where
the
expression inside the
statement is not actually a
expres-
sion. For example, take a look at the following lines of code:
This statement may be valid in some other programming and scripting languages, but not
in Java, where
and
are not considered
values. Also, be wary of assignment
operators being used as if they were equals
operators in
statements:
Understanding Java Statements
c02.indd 1봀
5/2014 Page 71
Ternary Operator
Now that we have discussed
statements, we can brie■
y return to our discus-
sion of operators and present th攠.
nal operator that you need to learn for the exam. The
conditional operator
, otherwise known as the
ternary operator
, is the only operator
that takes three operands and is of the form:
Th攠.
rst operand must be a
expression, and the second and third can be any
expression that returns a value. The ternary operation is really a condensed form of an
statement that returns a value. For example, the following two snippets of code
are equivalent:
Compare the previous code snippet with the following equivalent ternary operator code
snippet:
Note that it is often helpful for readability to add parentheses around the expressions in
ternary operations, although it is certainly not required.
There is no requirement that second and third expressions in ternary operations have
the same data types, although it may come into play when combined with the assignment
operator. Compare the following two statements:
Both expressions evaluate similar
values and return an
and a
although only th攠.
rst line will compile. The
does not care that the
statements are completely different types, because it can convert both to
. On the
other hand, the compiler does know that
is of the wrong data type and cannot be
assigned to an
; therefore, it will not allow the code to be compiled.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 72
Ternary Expression Evaluation
As of Java 7, only one of the right-hand expressions of the ternary operator will be evalu-
ated at runtime. In a manner similar to the short-circuit operators, if one of the two right-
hand expressions in a ternary operator performs a side effect, then it may not be applied
at runtime. Let’s illustrate this principle with the following example:
Notice that since the left-hand
expression was
, only
was incremented.
Contrast the preceding example with the following modifi
cation:
Now that the left-hand
expression evaluates to
, only
was incremented.
In this manner, we see how the expressions in a ternary operator may not be applied if
the particular expression is not used.
For the exam, be wary of any question that includes a ternary expression in which a vari-
able is modifi
ed in one of the right-hand side expressions.
switch
Statement
We now expand on our discussion of
statements by discussing a
statement. A
switch
statement, as shown in Figure 2.4, is a complex decision-making struc-
ture in which a single value is evaluated an搠■
ow is redirected to th攠.
rst matching branch,
known as a
case
statement. If no such
statement is found that matches the value, an
optional
default
statement will be called. If no such
option is available, the entire
statement will be skipped.
Supported Data Types
As shown in Figure 2.4, a
statement has a target variable that is not evaluated until
runtime. Prior to Java 5.0, this variable could only be
values or those values that could
be promoted to
, speci.
cally
. When
was added in Java
5.0, support was added to
statements to support
values. In Java 7,
Understanding Java Statements
c02.indd 1봀
5/2014 Page 73
statements were further updated to allow matching on
values. Finally, the
statement also supports any of the primitive numeric wrapper classes, such as
FIGURE 2.4
The structure of a
statement
Data types supported by
statements include the following:
and
and
and
and
and
values
For the exam, we recommend you memorize this list. Note that
and
, and
their associated wrapper classes, are not supported by
statements.
Compile-time Constant Values
The values in each
statement must be compile-time constant values of the same data
type as the
value. This means you can use only literals,
constants, or
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 74
constant variables of the same data type. By
constant, we mean that the variable
must be marked with the
modi.
er and initialized with a literal value in the same
expression in which it is declared.
Let’s look at a simple example using the day of the week, with
for Sunday,
Monday, and so on:
With a value of
of
, this code will output:
Th攠.
rst thing you may notice is that there is a
statement at the end of each
and
section. We’ll discuss
statements in detail when we discuss loops, but
for now all you need to know is that they terminate the
statement and return 
ow
control to the enclosing statement. As well soon see, if you leave out the
statement,
ow will continue to the next proceeding
block automatically.
Another thing you might notice is that the
block is not at the end of the
statement. There is no requirement that the
statements be in a particular
order, unless you are going to have pathways that reach multiple sections of the
block in a single execution.
To illustrate both of the preceding points, consider the following variation:
Understanding Java Statements
c02.indd 1봀
5/2014 Page 75
This code looks a lot like the previous example except two of the
statements have
been removed and the order has been changed. This means that for the given value of
, the code will jump to the
block and then execute all of the proceeding
statements in order until it 
nds a
statement or 
nishes the structure:
The order of the
and
statements is now important since placing the
statement at the end of the
statement would cause only one word to be
output.
What if the value of
was
in this example? Would the
block still be
executed? The output of this example with
set to
would be:
Even though the
block was before the
block, only the
block was exe-
cuted. If you recall the de.
nition of the
block, it is only branched to if there is no
matching
value for the
statement, regardless of its position within the
statement.
Finally, if the value of
was
, all three statements would be output:
Notice that in this last example, the
is executed since there was no
state-
ment at the end of the preceding
block. While the code will not branch to the
statement if there is a matching
value within the
statement, it will execute the
statement if it encounters it after a
statement for which there is no terminat-
ing
statement.
The exam creators are fond of
examples that are missing
statements!
When evaluating
statements on the exam, always consider that multiple branches
may be visited in a single execution.
We conclude our discussion on
statements by acknowledging that the data type
statements must all match the data type of the
variable. As already dis-
cussed, the
statement value must also be a literal,
constant, or
constant
variable. For example, given the following
statement, notice which
statements
will compile and which will not:
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 76
Understanding Java Statements
c02.indd 1봀
5/2014 Page 77
The simplest such repetition control structure in Java is the
while
statement, described
in Figure 2.5. Like all repetition control structures, it has a termination condition, imple-
mented as a
expression, that will continue as long as the expression evaluates to
FIGURE 2.5
The structure of a
statement
As shown in Figure 2.5, a
loop is similar to an
statement in that it is
composed of a
expression and a statement, or block of statements. During execu-
tion, the
expression is evaluated before each iteration of the loop and exits if the
evaluation returns
. It is important to note that a
loop may terminate after its
rst evaluation of the
expression. In this manner, the statement block may never
be executed.
Let’s return to our mouse example from Chapter 1 and show a loop can be used to
model a mouse eating a meal:
This method takes an amount of food, in this case cheese, and continues until the mouse
has no room in its belly or there is no food left to eat. With each iteration of the loop, the
mous攠贀eats踀 one bite of food and loses one spot in its belly. By using a compound
statement, you ensure that the
loop can end for either of the conditions.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 78
Infi
nite Loops
Consider the following segment of code:
You may notice one glaring problem with this statement: it will never end! The
expression that is evaluated prior to each loop iteration is never modifi
ed, so the expres-
sion
will always evaluate to
. The result is that the loop will never end, cre-
ating what is commonly referred to as an
nite loop
Infi
nite loops are something you should be aware of any time you create a loop in your
application. You should be absolutely certain that the loop will eventually terminate
under some condition. First, make sure the loop variable is modifi
ed. Then, ensure that
the termination condition will be eventually reached in all circumstances. As you’ll see
in the upcoming sectio渠贀Understanding Advanced Flow Control,Ž a loop may also exit
under other conditions such as a
statement.
do-while
Statement
Java also allows for the creation of a
do-while
loop, which like a
loop, is a
repetition control structure with a termination condition and statement, or block of
statements, as shown in Figure 2.6. Unlike a
loop, though, a
loop guaran-
tees that the statement or block will be executed at least once.
FIGURE 2.6
The structure of a
statement
Understanding Java Statements
c02.indd 1봀
5/2014 Page 79
The primary difference between the syntactic structure of a
loop and a
loop is that a
loop purposely orders the statement or block of statements before
the conditional expression, in order to reinforce that the statement will be executed before
the expression is ever evaluated. For example, take a look at the output of the following
statements:
Java will execute the statement bloc欠.
rst, and then check the loop condition. Even
though the loop exits right away, the statement block was still executed once and the pro-
gram outputs a
When to Use
while
vs.
do-while
Loops
In practice, it might be diffi
cult to determine when you should use a
loop and when
you should use a
loop. The short answer is that it does not actually matter. Any
loop can be converted to a
loop, and vice versa. For example, compare
this
loop:
and this
loop:
Though one of the loops is certainly easier to read, they are functionally equivalent. Java
recommends you use a
loop when a loop might not be executed at all and a
loop when the loop is executed at least once. But determining whether you should
use a
loop or a
loop in practice is sometimes about personal preference
and code readability.
For example, although th攠fi
rst statement is shorter, the second has the advantage that
you could leverage the existing
statement and perform some other operation in
a new
branch, as shown in the following example:
continues
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 80
for
Statement
Now that you can build applications with simple
and
statements, we
expand our discussion of loops to a more complex repetition control structure called a
loop.
Starting in Java 5.0, there are now two types of
statements. Th攠.
rst is referred to as
the basic
loop, and the second is often called the enhanced
loop. For clarity, well
refer to the enhanced
loop as the
statement throughout the book.
The Basic
for
Statement
A basic
for loop
has the same conditional
expression and statement, or block of
statements, as the other loops you have seen, as well as two new sections: an
initialization
block
and an
update
statement. Figure 2.7 shows how these components are laid out.
FIGURE 2.7
The structure of a basic
statement
1 Initialization statement executes
2 If booleanExpression is true continue, else exit loop
3 Body executes
4 Execute updateStatements
continued
Understanding Java Statements
c02.indd 1봀
5/2014 Page 81
Although Figure 2.7 might seem a little confusing and almost arbitrary at 
rst, the orga-
nization of the components an搠■
ow allow us to create extremely powerful statements in a
very small amount of space that otherwise would take multiple lines with a standard
loop. Note that each section is separated by a semicolon. The initialization and update sec-
tions may contain multiple statements, separated by commas.
Variables declared in the initialization block of a
loop have limited scope and
are only accessible within the
loop. Be wary of any exam questions in which a vari-
able declared within the initialization block of a
loop is available outside the loop.
Alternatively, variables declared before the
loop and assigned a value in the initializa-
tion block may be used outside the
loop because their scope precedes the
loop
creation.
Let’s take a look at an example that prints the numbers
The local variable
is initialize搠.
rst to
. The variable
is only in scope for the dura-
tion of the loop and is not available outside the loop once the loop has completed. Like a
loop, the
condition is evaluated on every iteration of the loop
before
the
loop executes. Since it returns
, the loop executes and outputs the
followed by a
space. Next, the loop executes the update section, which in this case increases the value
of
. The loop then evaluates the
expression a second time, and the process
repeats multiple times, printing:
On the 10th iteration of the loop, the value of
reaches
and is incremented by
reach
. On the 11th iteration of the loop, the
expression is evaluated and since
returns
, the loop terminates without executing the statement loop body.
Although most
loops you are likely to encounter in practice will be well de.
ned and
similar to the previous example, there are a number of variations and edge cases you could
see on the exam. You should familiarize yourself with the followin朠.
ve examples:
variations of these are likely to be seen on the exam.
Let’s tackle some examples for illustrative purposes:
1. Creating an Infinite Loop
Although this
loop may look like it will throw a compiler error, it will in fact compile
and run without issue. It is actually an in.
nite loop that will print the same statement
repeatedly. This example reinforces the fact that the components of the
loop are each
optional. Note that the semicolons separating the three sections are required, as
and
will not compile.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 82
2. Adding Multiple Terms to the
Statement
This code demonstrates three variations of the
loop you may not have seen. First, you
can declare a variable, such as
in this example, before the loop begins and use it after it
completes. Second, your initialization block,
expression, and update statements
can include extra variables that may not reference each other. For example,
is de.
ned in
the initialization block and is never used. Finally, the
statement can modify multiple
variables. This code will print the following when executed:
Keep this example in mind when we look at the next three examples, none of which
compile.
3. Redeclaring a Variable in the Initialization Block
This example looks similar to the previous one, but it does not compile because of the ini-
tialization block. The difference is that
is repeated in the initialization block after already
being declared before the loop, resulting in the compiler stopping because of a duplicate
variable declaration. We ca渠.
x this loop by changing the declaration of
and
as follows:
Note that this variation will now compile because the initialization block simply assigns a
value to
and does not declare it.
4. Using Incompatible Data Types in the Initialization Block
This example also looks a lot like our second example, but like the third example will not
compile, although this time for a different reason. The variables in the initialization block
must all be of the same type. In th攠.
rst example,
and
were both
, so the code com-
piled without issue, but in this example they have differing types, so the code will not compile.
Understanding Java Statements
c02.indd 1봀
5/2014 Page 83
5. Using Loop Variables Outside the Loop
Th攠.
nal variation on the second example will not compile for a different reason than the
previous examples. If you notice,
is de.
ned in the initialization block of the loop, and
then used after the loop terminates. Since
was only scoped for the loop, using it outside
the loop will throw a compiler error.
for-each
Statement
Starting with Java 5.0, Java developers have had a new type of enhanced
loop at their
disposal, one speci.
cally designed for iterating over arrays and
objects. This
enhanced
loop, which for clarity well refer to as a
for-each
loop, is shown in Figure 2.8.
FIGURE 2.8
The structure of an enhancement
statement
The
loop declaration is composed of an initialization section and an object to
be iterated over. The right-hand side of the
loop statement must be a built-in Java
array or an object whose class implements
, which includes most of
the Java
framework. The left-hand side of the
loop must include a
declaration for an instance of a variable, whose type matches the type of a member of the
array or collection in the right-hand side of the statement. On each iteration of the loop, the
named variable on the left-hand side of the statement is assigned a new value from the array
or collection on the right-hand side of the statement.
For the OCA exam, the only members of the
framework that
you need to be aware of are
and
. In this chapter, well
show how to iterate over
objects, and in Chapter 3 well go into detail
about how to create
objects and how they differ from traditional Java
arrays.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 84
Let’s review some examples:
What will this code output?
names[0] = "Lisa";names[1] = "Kevin";names[2] = "Roger";for(String name : names) { System.out.print(name + ", ");}This code will compile and print:
What will this code output?
This code will compile and print the same values:
When you see a
loop on the exam, make sure the right-hand side is an array
object and the left-hand side has a matching type. For example, the two
examples that follow will not compile.
Why will the following fail to compile?
In this example, the
is not an array, nor does it implement
, so the compiler will throw an exception since it does not know how to iter-
ate over the
Why will the following fail to compile?
Understanding Java Statements
c02.indd 1봀
5/2014 Page 85
This code will fail to compile because the left-hand side of the
statement does
not de.
ne an instance of
. Notice that in this last example, the array is initial-
ized with three
pointer values. In and of itself, that will not cause the code to not
compile, as a corrected loop would just output
three times.
Comparing
for
and
for-each
Loops
Since
and
both use the same keyword, you might be wondering how they
are related. While this discussion is out of scope for the exam, let’s take a moment to
explore how
loops are converted to
loops by the compiler.
When
was introduced in Java 5, it was added as a compile-time enhancement.
This means that Java actually converts the
loop into a standard
loop during
compilation. For example, assuming
is an array of
as we saw in th攠fi
rst
example, the following two loops are equivalent:
System.out.print(name + ", ");}For objects that inherit
, there is a different, but similar, conversion.
For example, assuming
is an instance of
, as we saw in the second
example, the following two loops are equivalent:
Notice that in the second version, there is no
statement as it is not required when
using the
class.
You may have noticed that in the previous
examples, there was an extra
comma printed at the end of the list:
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 86
While the
statement is convenient for working with lists in many cases, it does
hide access to the loop iterator variable. If we wanted to print only the comma between
names, we could convert the example into a standard
loop, as in the following example:
Understanding Advanced Flow Control
c02.indd 1봀
5/2014 Page 87
Nested Loops
First off, loops can contain other loops. For example, consider the following code that iter-
ates over a two-dimensional array, an array that contains other arrays as its members. We’ll
cover multidimensional arrays in detail in Chapter 3, but for now assume the following is
how you would declare a two-dimensional array.
for(int[] mySimpleArray : myComplexArray) { for(int i=0; imySimpleArray.length; i++) { System.out.print(mySimpleArray[i]+"\t"); } System.out.println();}Notice that we intentionally mix a
and
loop in this example. The outer
loops will execute a total of three times. Each time the outer loop executes, the inner loop
is executed four times. When we execute this code, we see the following output:
Nested loops can include
and
, as shown in this example. See if you can
determine what this code will output.
Th攠.
rst time this loop executes, the inner loop repeats until the value of
is
. The
value will then be decremented to
and that will be the output at the end of th攠.
rst itera-
tion of the outer loop. On the second iteration of the outer loop, the inner
will
be executed once, even though
is already not greater than
. As you may recall,
statements always execute the body at least once. This will reduce the value to
, which will
be further lowered by the decrement operator in the outer loop to
. Once the value reaches
, the outer loop will terminate. The result is that the code will output the following:
Adding Optional Labels
One thing we skipped when we presented
statements,
statements, and
loops is that they can all have optional labels. A
label
is an optional pointer to the head of a
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 88
statement that allows the applicatio渠■
ow to jump to it or break from it. It is a single word
that is proceeded by a colon (
⤀. For example, we can add optional labels to one of the pre-
vious examples:
OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) { INNER_LOOP: for(int i=0; imySimpleArray.length; i++) { System.out.print(mySimpleArray[i]+"\t"); } System.out.println();}When dealing with only one loop, they add no value, but as well see in the next sec-
tion, they are extremely useful in nested environments. Optional labels are often only used
in loop structures. While this topic is not on the OCA exam, it is possible to add optional
labels to control and block structures. That said, it is rarely considered good coding prac-
tice to do so.
For formatting, labels follow the same rules for identi.
ers. For readability, they are com-
monly expressed in uppercase, with underscores between words, to distinguish them from
regular variables.
break
Statement
As you saw when working with
statements, a
break
statement transfers th攠■
ow
of control out to the enclosing statement. The same holds true for
statements that
appear inside of
, and
loops, as it will end the loop early, as shown in
Figure 2.9
FIGURE 2.9
The structure of a
statement
Notice in Figure 2.9 that the
statement can take an optional label parameter.
Without a label parameter, the
statement will terminate the nearest inner loop it is
Understanding Advanced Flow Control
c02.indd 1봀
5/2014 Page 89
currently in the process of executing. The optional label parameter allows us to break out
of a higher level outer loop. In the following example, we search for th攠.
rst
array
index position of a number within an unsorted two-dimensional array:
) int[][] list = {{1,13,5},{1,2,5},{2,7,2}}; int searchValue = 2; int positionX = -1; int positionY = -1; PARENT_LOOP: for(int i=0; ilist.length; i++) { for(int j=0; jlist[i].length; j++) { if(list[i][j]==searchValue) { positionX = i; positionY = j; break PARENT_LOOP; } } } if(positionX==-1 || positionY==-1) { System.out.println("Value "+searchValue+" not found"); } else { System.out.println("Value "+searchValue+" found at: " + "("+positionX+","+positionY+")"); } }}When executed, this code will output:
In particular, take a look at the statement
. This statement will break
out of the entire loop structure as soon as th攠.
rst matching value is found. Now, imagine
what would happen if we replaced the body of the inner loop with the following:
) positionX = i; positionY = j; break;}How would this change ou爠■
ow and would the output change? Instead of exiting when
th攠.
rst matching value is found, the program will now only exit the inner loop when the
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 90
condition is met. In other words, the structure will no眠.
nd th攠.
rst matching value of the
last inner loop to contain the value, resulting in the following output:
Finally, what if we removed the
altogether?
) positionX = i; positionY = j;}In this case, the code will search for the last value in the entire structure that has the
matching value. The output will look like this:
You can see from this example that using a label on a
statement in a nested
loop, or not using the
statement at all, can cause the loop structure to behave quite
differently.
continue
Statement
Let’s now complete our discussion of advanced loop control with the
continue
statement, a
statement that causes 
ow to 
nish the execution of the current loop, as shown in Figure 2.10.
FIGURE 2.10
The structure of a
statement
You may notice the syntax of the
statement mirrors that of the
state-
ment. In fact, the statements are similar in how they are used, but with different results.
While the
statement transfers control to the enclosing statement, the
statement transfers control to the
expression that determines if the loop should
continue. In other words, it ends the current iteration of the loop. Also like the
statement, the
statement is applied to the nearest inner loop under execution
using optional label statements to override this behavior. Let’s take a look at the following
example:
Understanding Advanced Flow Control
c02.indd 1봀
5/2014 Page 91
) FIRST_CHAR_LOOP: for (int a = 1; a = 4; a++) { for (char x = 'a'; x = 'c'; x++) { if (a == 2 || x == 'b') continue FIRST_CHAR_LOOP; System.out.print(" " + a + x); } } }}With the structure as de.
ned, the loop will return control to the parent loop any time
th攠.
rst value is
or the second value is
. This results in one execution of the inner loop
for each of three outer loop calls. The output looks like this:
Now, imagine we removed the
label
in the
statement so that
control is returned to the inner loop instead of the outer. See if you can understand how the
output will be changed to:
Finally, if we remove the
statement and associated
statement alto-
gether, we arrive at a structure that outputs all the values, such as:
Table 2.5 will help remind you when labels,
, and
statements are permit-
ted in Java. Although for illustrative purposes our examples have included using these state-
ments in nested loops, they can be used inside single loops as well.
TABLE 2.5
Advanced flow control usage
Allows optional labels
Allows
break
statement
Allows
continue
statement
Yes *NoNo
YesYesYes
YesYesYes
YesYesYes
YesYesNo
* Labels are allowed for any block statement, including those that are preceded with an
statement.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 92
Summary
This chapter covered a wide variety of topics, including dozens of Java operators, along
with numerous control 
ow statements. Many of these operators and statements may have
been new to you.
It is important that you understand how to use all of the required Java operators covered
in this chapter and know how operator precedence in■
uences the way a particular expres-
sion is interpreted. There will likely be numerous questions on the exam that appear to test
one thing, such as
or exception handling, when in fact the answer is related
to the misuse of a particular operator that causes the application to fail to compile. When
you see an operator on the exam, always check that the appropriate data types are used and
that they match each other where applicable.
For statements, this chapter covered two types of control structures: decision-making
controls structures, including
, and
statements, as well as
repetition control structures including
, and
. Remember that
most of these structures require the evaluation of a particular
expression either for
branching decisions or once per repetition. The
statement is the only one that sup-
ports a variety of data types, including
variables as of Java 7.
With a
statement you don’t need to explicitly write a
expression, since
the compiler builds them implicitly. For clarity, we referred to an enhanced
loop as a
loop, but syntactically they are written as a
statement.
We concluded this chapter by discussing advanced control options and ho眠■
ow can be
enhanced through nested loops,
statements, and
statements. Be wary of
questions on the exam that use nested statements, especially ones with labels, and verify
they are being used correctly.
This chapter is especially important because at least one component of this chapter will
likely appear in every exam question with sample code. Many of the questions on the exam
focus on proper syntactic use of the structures, as they will be a large source of questions
that end in₍Does not compile.踠You should be able to answer all of the review questions
correctly or fully understand those that you answered incorrectly before moving on to later
chapters.
Exam Essentials
Be able to write code that uses Java operators.
This chapter covered a wide variety of
operator symbols. Go back and review them several times so that you are familiar with
them throughout the rest of the book.
Be able to recognize which operators are associated with which data types.
Some opera-
tors may be applied only to numeric primitives, some only to
values, and some
only to objects. It is important that you notice when an operator and operand(s⤀ are mis-
matched, as this issue is likely to come up in a couple of exam questions.
Exam Essentials
c02.indd 1봀
5/2014 Page 93
Understand Java operator precedence.
Most Java operators you’ll work with are binary,
but the number of expressions is often greater than two. Therefore, you must understand
the order in which Java will evaluate each operator symbol.
Be able to write code that uses parentheses to override operator precedence.
You can use
parentheses in your code to manually change the order of precedence.
Understand
and
decision control statements.
The
and
state-
ments come up frequently throughout the exam in questions unrelated to decision control,
so make sure you fully understand these basic building blocks of Java.
Understand loop statements.
Know the syntactical structure of all loops, including
, and
. Each loop has its own special properties and structures. Also, be famil-
iar with the enhanced
loops that iterate over lists.
Understand how
and
can change flow control.
Know how to change the
ow control within a statement by applying a
command. Also know
which control statements can accept
statements and which can accept
statements. Finally, understand how these statements work inside embedded loops or
statements.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 94
Review Questions
Which of the following Java operators can be used with
variables? (Choose all that
apply⤀
What data type (or types⤀ will allow the following code snippet to compile? (Choose all that
apply⤀
What is the output of the following application?
)3: int x = 0;4: while(x++ 10) {}&#x 10 ;&#x{} T;&#xj 7.;茒&#x 0 0;&#x 8.7; 14; 26;.02; T;&#xm 5:;&#x ;&#x Str;&#xing ;&#xmess; ge ;&#x= x ;5: String message = x 10 ? "Greater than" : false;6: System.out.println(message+","+x);7: }8: }A. Greater than,10B. false,10C. Greater than,11D. false,11E. The code will not compile because of line 4.
The code will not compile because of line 5.
Review Questions
c02.indd 1봀
5/2014 Page 95
What change would allow the following code snippet to compile? (Choose all that apply⤀
No change; it compiles as is.
Cast
on line 4 to
Change the data type of
on line 3 to
Cast
on line 4 to
Change the data type of
on line 4 to
Change the data type of
on line 4 to
What is the output of the following code snippet?
The code will not compile because of line 7.
The code will not compile because of line 8.
The code contains an infinite loop and does not terminate.
What is the output of the following code snippet?
Compiles but throws a
The code will not compile because of line 6.
The code will not compile because of line 7.
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 96
What is the output of the following code?
)3: int x = 5;�4: System.out.println(x 2 ? x 4 ? 10 : 8 : 7);5: }}A. 5B. 4C. 10D. 8E. 7F. The code will not compile because of line 4.
What is the output of the following code snippet?
The code will not compile because of line 5.
How many times will the following code print
10
11
The code will not compile because of line 3.
The code will not compile because of line 5.
The code contains an infinite loop and does not terminate.
10.
What is the output of the following code?
Review Questions
c02.indd 1봀
5/2014 Page 97
The code will not compile because of line 4.
An undefined value.
11.
What is the output of the following code?
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 98
The code will not compile because of line 5.
15.
What is the output of the following code snippet?
The code will not compile because of line 3.
The code will not compile because of line 4.
The code contains an infinite loop and does not terminate.
16.
What is the output of the following code snippet?
The code will not compile because of line 6.
The code contains an infinite loop and does not terminate.
17.
What is the output of the following code snippet?
Review Questions
c02.indd 1봀
5/2014 Page 99
The code will not compile because of line 8.
18.
What is the output of the following code snippet?
The code will not compile because of line 6.
19.
What is the result of the following code snippet?
The code will not compile because of line 7.
20.
What is the result of the following code snippet?
100
Chapter 2
Operators and Statements
c02.indd 1봀
5/2014 Page 100
The code will not compile because of line 3.
The code will not compile because of line 6.
The code will not compile because of lines 6 and 9.
c03.indd 1봀
4/2014 Page 101
Chapter
Core Java APIs
OCA EXAM OBJECTIVES COVERED
IN THIS CHAPTER:
Using Operators and Decision Constructs
Test equality between Strings and other objects using == and
equals⠀⤀
Creating and Using Arrays
Declare, instantiate, initialize and use a one-dimensional
array
Declare, instantiate, initialize and use a multi-dimensional
array
Working with Selected classes from the Java API
Creating and manipulating Strings
Manipulate data using the StringBuilder class and its methods
Declare and use an ArrayList of a given type
Create and manipulate calendar data using classes from java.
time.LocalDateTime, java.time.LocalDate, java.time.Local-
Time, java.time.format.DateTimeFormatter, java.time.Period
Working with Java Data Types
Develop code that uses wrapper classes such as Boolean,
Double, and Integer.
c03.indd 1봀
4/2014 Page 102
The OCA exam expects you to know the core data structures
and classes used in Java, and in this chapter readers will learn
about the most common methods available. For example,
and
are used for text data. An array and an
are used
when you have multiple values. A variety of classes are used for working with dates. In this
chapter, you’ll also learn how to determine whether two objects are equal.
API
stands for application programming interface. In Java, an interface is something
special. In the context of an API, it can be a group of class or interface de■
nitions that gives
you access to a service or functionality. You will learn about the most common APIs for
each of the classes covered in this chapter.
Creating and Manipulating Strings
The
class is such a fundamental class that you’d be hard-pressed to write code with-
out it. After all, you can’t even write a
method without using the
class. A
string
is basically a sequence of characters; heres an example:
As you learned in Chapter 1,₍Java Building Blocks,踀 this is an example of a reference
type. You also learned that reference types are created using the
keyword. Wait a minute.
Something is missing from the previous example: it doesn’t have
in it! In Java, these two
snippets both create a
Both give you a reference variable of type
name
pointing to the
object
. They
are subtly different, as you’ll see in the sectio渠贀String Pool,踀 later in this chapter. For now, just
remember that the
class is special and doesn’t need to be instantiated with
In this section, well look at concatenation, immutability, the string pool, common methods,
and method chaining.
Concatenation
In Chapter 2,₍Operators and Statements,踀 you learned how to add numbers. 1 + 2 is clearly
3. But what is
? It’s actually
because Java combines the two
objects.
Creating and Manipulating Strings
103
c03.indd 1봀
4/2014 Page 103
Placing one
before the other
and combining them together is called string
concatenation
. The OCA exam creators like string concatenation because the
operator
can be used in two ways within the same line of code. There aren’t a lot of rules to know for
this, but you have to know them well:
If both operands are numeric,
means numeric addition.
If either operand is a
means concatenation.
The expression is evaluated left to right.
Now let’s look at some examples:
The 
rst example uses th攠■
rst rule. Both operands are numbers, so we use normal addition.
The second example is simple string concatenation, described in the second rule. The quotes for
the
are only used in code—they don’t get output.
The third example combines both the second and third rules. Since we start on the left,
Java 
gures out what
evaluates to. You already know that one: it’s
. Then
Java looks at the remaining expression of
. The second rule tells us to concatenate
since one of the operands is a
In the fourth example, we start with the third rule, which tells us to consider
Both operands are numeric, so th攠■
rst rule tells us the answer is
. Then we have
which uses the second rule to give us
. Notice all three rules get used in one line? The
exam takes this a step further and will try to trick you with something like this:
When you see this, just take it slow and remember the three rules—and be sure to check
the variable types. In this example, we start with the third rule, which tells us to consider
. Th攠■
rst rule gives us
. Next we have
. Since
is of type
still use the 
rst rule, giving us
. Next we have
. Since
is of type
switch to the second rule and get a 
nal answer of
. When you see questions like this,
just take your time and check the types. Being methodical pays off.
There is only one more thing to know about concatenation, but it is an easy one. In this
example, you just have to remember what
does.
means the same thing as
104
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 104
On line 5, we ar攠贀addingŽ two strings, which means we concatenate them. Line 6 tries
to trick you by adding a number, but it’s just like we wrote
. We know that a
string plus踀 anything else means to use concatenation.
To review the rules one more time: use numeric addition if two numbers are involved,
use concatenation otherwise, and evaluate from left to right. Have you memorized these
three rules yet? Be sure to do so before the exam!
Immutability
Once a
object is created, it is not allowed to change. It cannot be made larger or
smaller, and you cannot change one of the characters inside it.
You can think of a string as a storage box you have perfectly full and whose sides can’t
bulge. Theres no way to add objects, nor can you replace objects without disturbing the
entire arrangement. The trade-off for the optimal packing is zero 
exibility.
Mutable
is another word for changeable.
Immutable
is the opposite—an object that
can’t be changed once it’s created. On the OCA exam, you need to know that
is
immutable.
More on Immutability
You won’t be asked to identify whether custom classes are immutable on the exam, but
it’s helpful to see an example. Consider the following code:
Creating and Manipulating Strings
105
c03.indd 1봀
4/2014 Page 105
You learned that + is used to do
concatenation in Java. There’s another way,
which isn’t used much on real projects but is great for tricking people on the exam. What
does this print out?
Did you say
? Good. The trick is to see if you forget that the String class is immutable
by throwing a method at you.
The String Pool
Since strings are everywhere in Java, they use up a lot of memory. In some production appli-
cations, they can use up 25–40 percent of the memory in the entire program. Java realizes
that many strings repeat in the program and solves this issue by reusing common ones. The
string pool
, also known as the intern pool, is a location in the Java virtual machine (JVM)
that collects all these strings.
The string pool contains literal values that appear in your program. For example,
贀name踀 is a literal and therefore goes into the string pool.
is a string
but not a literal, so it does not go into the string pool. Strings not in the string pool are gar-
bage collected just like any other object.
Remember back when we said these two lines are subtly different?
The former says to use the string pool normally. The second says₍No, JVM. I really
don’t want you to use the string pool. Please create a new object for me even though it is
less ef■
cient.踠When you write programs, you wouldn’t want to do this. For the exam, you
need to know that it is allowed.
Important String Methods
The
class has dozens of methods. Luckily, you need to know only a handful for the
exam. The exam creators pick most of the methods developers use in the real world.
For all these methods, you need to remember that a string is a sequence of characters
and Java counts from 0 when indexed. Figure 3.1 shows how each character in the string
is indexed.
106
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 106
FIGURE 3.1
Indexing for a string
animas
012346
Let’s look at thirteen methods from the
class. Many of them are straightforward
so we won’t discuss them at length. You need to know how to use these methods.
length⠀⤀
The method
returns the number of characters in the
. The method signa-
ture is as follows:
The following code shows how to use
Wait. It outputs 7? Didn’t we just tell you that Java counts from 0? The difference is
that zero counting happens only when you’re using indexes or positions within a list. When
determining the total size or length, Java uses normal counting again.
charAt⠀⤀
The method
lets you query the string to 
nd out what character is at a speci■
c
index. The method signature is as follows:
The following code shows how to use
Since indexes start counting with 0,
returns th攠贀■
rstŽ character in the
sequence. Similarly,
returns th攠贀seventhŽ character in the sequence.
is a problem. It asks for th攠贀eighth踀 character in the sequence, but there are only seven
characters present. When something goes wrong that Java doesn’t know how to deal with,
it throws an exception, as shown here. You’ll learn more about exceptions in Chapter 6,
赅xceptions.踀
indexOf⠀⤀
The method
looks at the characters in the string an搠■
nds th攠■
rst index that
matches the desired value.
can work with an individual character or a whole
as input. It can also start from a requested position. The method signatures are as follows:
Creating and Manipulating Strings
107
c03.indd 1봀
4/2014 Page 107
The following code shows how to use
Since indexes begin with 0, th攠■
rst
matches at that position. The second statement
looks for a more speci■
c string and so matches later on. The third statement says Java
shouldn’t even look at the characters until it gets to index 4. Th攠■
nal statement doesn’t
nd anything because it starts looking after the match occurred. Unlike
, the
method doesn’t throw an exception if it can’琠■
nd a match.
returns
–1 when no match is found. Because indexes start with 0, the caller knows that₅1 couldn’t
be a valid index. This makes it a common value for a method to signify to the caller that no
match is found.
substring(⤀
The method
also looks for characters in a string. It returns parts of the string.
Th攠■
rst parameter is the index to start with for the returned string. As usual, this is a
zero-based index. There is an optional second parameter, which is the end index you want
to stop at.
Notice we said₍stop atŽ rather than₍include.踀 This means the
parameter is
allowed to be 1 past the end of the sequence if you want to stop at the end of the sequence.
That would be redundant, though, since you could omit the second parameter entirely in
that case. In your own code, you want to avoid this redundancy. Don’t be surprised if the
exam uses it though. The method signatures are as follows:
The following code shows how to use
108
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 108
The
method is the trickiest
method on the exam. Th攠■
rst example
says to take the characters starting with index 3 through the end, which gives us
The second example does the same thing: it calls
to get the index rather than
hard-coding it. This is a common practice when coding because you may not know the
index in advance.
The third example says to take the characters starting with index 3 until, but not includ-
ing, the character at index 4—which is a complicated way of saying we want a
with
one character: the one at index 3. This results in
. Th攠■
nal example says to take the
characters starting with index 3 until we get to index 7. Since index 7 is the same as the end
of the string, it is equivalent to th攠■
rst example.
We hope that wasn’t too confusing. The next examples are less obvious:
The 
rst example in this set prints an empty string. The request is for the characters start-
ing with index 3 until you get to index 3. Since we start and end with the same index, there
are
characters in between. The second example in this set throws an exception because
the indexes can be backward. Java knows perfectly well that it will never get to index 2 if
it starts with index 3. The third example says to continue until the eighth character. There
is no eighth position, so Java throws an exception. Granted, there is no seventh character
either, but at least there is th攠贀end of stringŽ invisible position.
Let’s review this one more time since
is so tricky. The method returns the
string starting from the requested index. If an end index is requested, it stops right before
that index. Otherwise, it goes to the end of the string.
toLowerCase⠀⤀
toUpperCase⠀⤀
Whew. After that mental exercise, it is nice to have methods that do exactly what they
sound like! These methods make it easy to convert your data. The method signatures are as
follows:
The following code shows how to use these methods:
These methods do what they say.
converts any lowercase characters to
uppercase in the returned string.
converts any uppercase characters to low-
ercase in the returned string. These methods leave alone any characters other than letters.
Also, remember that strings are immutable, so the original string stays the same.
Creating and Manipulating Strings
109
c03.indd 1봀
4/2014 Page 109
equals(⤀
equalsIgnoreCase(⤀
The
method checks whether two
objects contain exactly the same char-
acters in the same order. The
method checks whether two
objects contain the same characters with the exception that it will convert the characters造
case if needed. The method signatures are as follows:
The following code shows how to use these methods:
This example should be fairly intuitive. In th攠■
rst example, the values aren’t exactly the
same. In the second, they are exactly the same. In the third, they differ only by case, but it
is okay because we called the method that ignores differences in case.
startsWith⠀⤀
endsWith⠀⤀
The
and
methods look at whether the provided value matches
part of the
. The method signatures are as follows:
The following code shows how to use these methods:
Again, nothing surprising here. Java is doing a case-sensitive check on the values provided.
contains⠀⤀
The
method also looks for matches in the
. It isn’t as particular as
and
—the match can be anywhere in the
. The method
signature is as follows:
The following code shows how to use these methods:
110
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 110
Again, we have a case-sensitive search in the
. The
method is a conve-
nience method so you don’t have to write
replace⠀⤀
The
method does a simple search and replace on the string. Theres a ver-
sion that takes
parameters as well as a version that takes
parameters.
is a general way of representing several classes, including
and
. It’s called an interface, which well cover in Chapter 5,₍Class Design.踀
The method signatures are as follows:
The following code shows how to use these methods:
Th攠■
rst example uses th攠■
rst method signature, passing in
parameters. The
second example uses the second method signature, passing in
parameters.
trim(⤀
You’ve made it through the all the
methods you need to know except one. We left
the easy one for last. The
method removes whitespace from the beginning and end
of a
. In terms of the exam, whitespace consists of spaces along with the
(tab) and
(newline) characters. Other characters, such as
(carriage return⤀, are also included in
what gets trimmed. The method signature is as follows:
The following code shows how to use this method:
Th攠■
rst example prints the original string because there are no whitespace characters
at the beginning or end. The second example gets rid of the leading tab, subsequent spaces,
and the trailing newline. It leaves the spaces that are in the middle of the string.
Method Chaining
It is common to call multiple methods on the same
, as shown here:
c03.indd 1봀
4/2014 Page 111
This is just a series of
methods. Each time one is called, the returned value is put
in a new variable. There are four
values along the way, and
is output.
However, on the exam there is a tendency to cram as much code as possible into a small
space. You’ll see code using a technique called method chaining. He牥’s an example:
This code is equivalent to the previous example. It also creates four
objects and
outputs
. To read code that uses method chaining, start at the left and evaluate the
rst method. Then call the next method on the returned value of th攠■
rst method. Keep
going until you get to the semicolon.
Remember that
is immutable. What do you think the result of this code is?
On line 5, we set
to point to
and never pointed
to anything else. Since we are
dealing with an immutable object, none of the code on lines 6 or 7 changes
is a little trickier. Line 6 has
pointing to
, which is straightforward. On line 7,
we have method chaining. First,₍
is called. This returns
Next,
is called. This returns
. Finally,
changes to point
to this returned
. When line 9 executes,
is
Using the
StringBuilder
Class
A small program can create a lot of
objects very quickly. For example, how many
do you think this piece of code creates?
The empty
on line 10 is instantiated, and then line 12 appends an
. However,
because the
object is immutable, a new
object is assigned to
alpha
and the
Using the
StringBuilder
Class
112
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 112
贀踀 object becomes eligible for garbage collection. The next time through the loop,
alpha
is
assigned a new
object,
, and the
object becomes eligible for garbage
collection. The next iteration assigns
alpha
and the
object becomes eligible
for garbage collection, and so on.
This sequence of events continues, and after 26 iterations through the loop, a total of 27
objects are instantiated, most of which are immediately eligible for garbage collection.
This is very inef■
cient. Luckily, Java has a solution. The
class
creates a
without storing all those interim
values. Unlike the
class,
is not immutable.
On line 15, a new
object is instantiated. The call to
on line 17
adds a character to the
object each time through the for loop and appends
the value of current to the end of
alpha
. This code reuses the same
without
creating an interim
each time.
In this section, well look at creating a
, common methods, and a com-
parison to
Mutability and Chaining
We’re sure you noticed this from the previous example, but
is not immu-
table. In fact, we gave it 27 different values in the example (blank plus adding each
letter in the alphabet⤀. The exam will likely try to trick you with respect to
and
being mutable.
Chaining makes this even more interesting. When we chained
method calls, the
result was a new
with the answer. Chaining
objects doesn’t work
this way. Instead, the
changes its own state and returns a reference to itself!
Let’s look at an example to make this clearer:
Line 5 adds text to the end of
. It also returns a reference to
, which is ignored. Line
6 also adds text to the end of
and returns a reference to
. This time the reference is
stored in
same
—which means
and
same
point to the exact same object and would print
out the same value.
The exam won’t always make the code easy to read by only having one method per line.
What do you think this example prints?
c03.indd 1봀
4/2014 Page 113
Did you say both print
? Good. Theres only one
object
here. We know that because
was called only once. On line 5, there
are two variables referring to that object, which has a value of
. On line 6, those
two variables are still referring to that same object, which now has a value of
Incidentally, the assignment back to
does absolutely nothing.
is already pointing to that
Creating a
StringBuilder
There are three ways to construct a
The 
rst says to create a
containing an empty sequence of characters and
assign
sb1
to point to it. The second says to create a
containing a speci■
value and assign
sb2
to point to it. For th攠■
rst two, it tells Java to manage the implementa-
tion details. The 
nal example tells Java that we have some idea of how big the eventual value
will be and would like the
to reserve a certain number of slots for characters.
Size vs. Capacity
The behind-the-scenes process of how objects are stored isn’t on the exam, but some
knowledge of this process may help you better understand and remember
Size is the number of characters currently in the sequence, and capacity is the number
of characters the sequence can currently hold. Since a
is immutable, the size and
capacity are the same. The number of characters appearing in the
is both the size
and capacity.
For
, Java knows the size is likely to change as the object is used. When
is constructed, it may start at the default capacity (which happens to be
16) or one of the programmer’s choosing. In the example, we request a capacity of 5. At
this point, the size is 0 since no characters have been added yet, but we have space for 5.
Using the
StringBuilder
Class
113
continues
114
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 114
Next we add four characters. At this point, the size is 4 since four slots are taken. The
capacity is still 5. Then we add three more characters. The size is now 7 since we have
used up seven slots. Because the capacity wasn’t large enough to store seven characters,
Java automatically increased it for us.
anim
animas
012346
Important
StringBuilder
Methods
As with
, we aren’t going to cover every single method in the
class.
These are the ones you might see on the exam.
charAt⠀⤀
indexOf⠀⤀
length⠀⤀
, and
substring(⤀
These four methods work exactly the same as in the
class. Be sure you can identify
the output of this example:
The correct answer is
. The
method calls return 0 and 4, respectively.
returns the
starting with index 0 and ending right before index 4.
returns 7 because it is the number of characters in the
rather
than an index. Finally,
returns the character at index 6. Here we do start with 0
because we are referring to indexes. If any of this doesn’t sound familiar, go back and read
the section on
again.
(continued⤀
c03.indd 1봀
4/2014 Page 115
Notice that
returns a
rather than a
. That is why
is not changed.
is really just a method that inquires about where the substring
happens to be.
append(⤀
The
method is by far the most frequently used method in
. In fact,
it is so frequently used that we just started using it without comment. Luckily, this method
does just what it sounds like: it adds the parameter to the
and returns a ref-
erence to the current
. One of the method signatures is as follows:
Notice that we said
one
of the method signatures. There are more than 10 method signa-
tures that look similar but that take different data types as parameters. All those methods
are provided so you can write code like this:
Nice method chaining, isn’t it?
is called directly after the constructor. By hav-
ing all these method signatures, you can just call
without having to convert your
parameter to a
rst.
insert⠀⤀
The
method adds characters to the
at the requested index and
returns a reference to the current
. Just like
, there are lots of
method signatures for different types. He牥’s one:
116
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 116
Understanding Equality
117
c03.indd 1봀
4/2014 Page 117
Often
is used internally for performance purposes but the end result
needs to be a
. For example, maybe it needs to be passed to another method that is
expecting a
StringBuilder
vs.
StringBuffer
When writing new code that concatenates a lot of
objects together, you should
use
was added to Java in Java 5. If you come across older
code, you will see
used for this purpose.
does the same thing
but more slowly because it is thread safe. You’ll learn about threads for the OCP exam. In
theory, you don’t need to know about
on the exam at all. However, we bring
this up anyway, since an older question might still be left on the exam.
Understanding Equality
In Chapter 2, you learned how to use
to compare numbers and that object references
refer to the same object.
Since this example isn’t dealing with primitives, we know to look for whether the
references are referring to the same object.
and
two
are both completely separate
s, giving us two objects. Therefore, th攠■
rst print statement gives us
three
is more interesting. Remember how
methods like to return the cur-
rent reference for chaining? This means
and
three
both point to the same object and
the second print statement gives us
Let’s now visit the more complex and confusing scenario,
equality, made so in
part because of the way the JVM reuses
literals:
Remember that
s are immutable and literals are pooled. The JVM created only
one literal in memory.
and
both point to the same location in memory; therefore, the
statement outputs true. It gets even trickier. Consider this code:
118
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 118
In this example, we don’t have two of the same
literal. Although
and
hap-
pen to evaluate to the same string, one is computed at runtime. Since it isn’t the same at
compile-time, a new
object is created.
You can even force the issue by creating a new
Since you have speci■
cally requested a different
object, the pooled value isn’t
shared.
The lesson is to never use
to compare
objects. The only time
you should have to deal with
for
s is on the exam.
You saw earlier that you can say you want logical equality rather than object equality
objects:
This works because the authors of the
class implemented a standard method
called
to check the values inside the
rather than the
itself. If a
class doesn’t have an
method, Java determines whether the references point to the
same object—which is exactly what
does. In case you are wondering, the authors of
did not implement
. If you call
on two
instances, it will check reference equality.
The exam will test you on your understanding of equality with objects they de■
ne too.
For example:
)4: Tiger t1 = new Tiger();5: Tiger t2 = new Tiger();6: Tiger t3 = t1;7: System.out.println(t1 == t1); // true8: System.out.println(t1 == t2); // false9: System.out.println(t1.equals(t2)); // false10: } }Th攠■
rst two statements check object reference equality. Line 7 prints
because we
are comparing references to the same object. Line 8 prints
because the two object
Understanding Java Arrays
119
c03.indd 1봀
4/2014 Page 119
references are different. Line 9 prints
since
does not implement
Don’t worry—you aren’t expected to know how to implement
for the OCA exam.
Understanding Java Arrays
Up to now, weve been referring to the
and
classes as a sequence of
characters.踀 This is true. They are implemented using an
array
of characters. An array is an
area of memory on the heap with space for a designated number of elements. A
is
implemented as an array with some methods that you might want to use when dealing with
characters speci■
cally. A
is implemented as an array where the array object is
replaced with a new bigger array object when it runs out of space to store all the characters. A
big difference is that an array can be of any other Java type. If we didn’t want to use a
for some reason, we could use an array of
primitives directly:
Type of array
120
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 120
When using this form to instantiate an array, set all the elements to the default value for
that type. As you learned in Chapter 1, the default value of an
is 0. Since
numbers1
is a
reference variable, it points to the array object, as shown in Figure 3.3. As you can see, the
default value for all the elements is 0. Also, the indexes start with 0 and count up, just as
they did for a
FIGURE 3.3
An empty array
Another way to create an array is to specify all the elements it should start out with:
numbers2 = new int[] {42, 55, 99};In this example, we also create an
array of size 3. This time, we specify the initial
values of those three elements instead of using the defaults. Figure 3.4 shows what this
array looks like.
FIGURE 3.4
An initialized array
5599
Java recognizes that this expression is redundant. Since you are specifying the type of
the array on the left side of the equal sign, Java already knows the type. And since you
are specifying the initial values, it already knows the size. As a shortcut, Java lets you
write this:
This approach is called an anonymous array. It is anonymous because you don’t specify
the type and size.
Finally, you can type the [] before or after the name, and adding a space is optional.
This means that all four of these statements do the exact same thing:
Understanding Java Arrays
121
c03.indd 1봀
4/2014 Page 121
Most people use th攠■
rst one. You could see any of these on the exam, though, so get
used to seeing the brackets in odd places.
Multiple₍Arrays踀 in Declarations
What types of reference variables do you think the following code creates?
The correct answer is two variables of type
. This seems logical enough. After all,
created two
variables. What about this example?
All we did was move the brackets, but it changed the behavior. This time we get one vari-
able of type
and one variable of type
. Java sees this line of code and thinks
something like this㨠贀They want two variables of type
. Th攠fi
rst one is called
. This one is a
called
ids
. The second one is just called
types
. No brackets, so it is a
regular integer.踀
Needless to say, you shouldn’t write code that looks like this. But you do still need to
understand it for the exam.
Creating an Array with Reference Variables
You can choose any Java type to be the type of the array. This includes classes you create
yourself. Let’s take a look at a built-in type with
122
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 122
Since Java 5, Java has provided a method that prints an array nicely:
would print
As a quick review, what do you think this array points to?
}You got us. It was a review of Chapter 1 and not our discussion on arrays. The answer
is
. The code never instantiated the array so it is just a reference variable to
. Let’s
try that again—what do you think this array points to?
}It is an array because it has brackets. It is an array of type
since that is the type
mentioned in the declaration. It has two elements because the length is 2. Each of those two
slots currently is
, but has the potential to point to a
object.
Remember casting from the previous chapter when you wanted to force a bigger type
into a smaller type? You can do that with arrays too:
Understanding Java Arrays
123
c03.indd 1봀
4/2014 Page 123
Line 3 creates an array of type
. Line 4 doesn’t require a cast because
is
a broader type than
. On line 5, a cast is needed because we are moving to a more
speci■
c type. Line 6 doesn’t compile because a
only allows
objects and
is not a
Line 7 is where this gets interesting. From the point of view of the compiler, this is just
ne. A
object can clearly go in an
. The problem is that we don’t
actually have an
. We have a
referred to from an
variable. At
runtime, the code throws an
. You don’t need to memorize the name
of this exception, but you do need to know that the code will throw an exception.
Using an Array
Now that we know how to create an array, let’s try accessing one:
5: System.out.println(mammals.length); // 36: System.out.println(mammals[0]); // monkey7: System.out.println(mammals[1]); // chimp8: System.out.println(mammals[2]); // donkeyLine 4 declares and initializes the array. Line 5 tells us how many elements the array
can hold. The rest of the code prints the array. Notice elements are indexed starting with 0.
This should be familiar from
and
, which also start counting with 0.
Those classes also counted
as the number of elements.
To make sure you understand how
works, what do you think this prints?
System.out.println(birds.length);The answer is 6. Even though all 6 elements of the array are
, there are still 6 of
them.
does not consider what is in the array; it only considers how many slots have
been allocated.
It is very common to use a loop when reading from or writing to an array. This loop sets
each element of
to 5 higher than the current index:
6: for (int i = 0; i numbers.length; i++) 7: numbers[i] = i + 5;Line 5 simply instantiates an array with 10 slots. Line 6 is a
loop using an extremely
common pattern. It starts at index 0, which is where an array begins as well. It keeps going,
one at a time, until it hits the end of the array. Line 7 sets the current element of
numbers
The exam will test whether you are being observant by trying to access elements that are
not in the array. Can you tell why each of these throws an
for our array of size 10?
124
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 124
numbers[numbers.length] = 5;for (int i = 0; i = numbers.length; i++) numbers[i] = i + 5;Th攠■
rst one is trying to see if you know that indexes start with 0. Since we have 10 ele-
ments in our array, this means only
through
are valid. The second
example assumes you are clever enough to know 10 is invalid and disguises it by using the
variable. However, the length is always one more than the maximum valid index.
Finally, the
loop incorrectly uses
instead of
, which is also a way of referring to that
10th element.
Sorting
Java makes it easy to sort an array by providing a sort method—or rather, a bunch of sort
methods. Just like
allowed you to pass almost anything to
, you
can pass almost any array to
is th攠■
rst class provided by Java we have used that requires an import. To use it,
you must have either of the following two statements in your class:
There is one exception, although it doesn’t come up often on the exam. You can write
every time it is used in the class instead of specifying it as an import.
Remember that if you are shown a code snippet with a line number that doesn’t begin
with 1, you can assume the necessary imports are there. Similarly, you can assume the
imports are present if you are shown a snippet of a method.
This simple example sorts three numbers:
Arrays.sort(numbers);for (int i = 0; i numbers.length; i++) L System.out.print (numbers[i] + " ");The result is
, as you should expect it to be. Notice that we had to loop through
the output to print the values in the array. Just printing the array variable directly would
give the annoying hash of
.Try this again with
types:
Understanding Java Arrays
125
c03.indd 1봀
4/2014 Page 125
This time the result might not be what you expect. This code outputs
. The
problem is that String sorts in alphabetic order, and 1 sorts before 9. (Numbers sort before
letters and uppercase sorts before lowercase, in case you were wondering.) For the OCP
exam, you’ll learn how to create custom sort orders using something called a comparator.
Did you notice we snuck in the enhanced
loop in this example? Since we aren’t using
the index, we don’t need the traditional
loop. That won’t stop the exam creators from
using it, though, so well be sure to use both to keep you sharp!
Searching
Java also provides a convenient way to search—but only if the array is already sorted.
Table 3.1 covers the rules for binary search.
TABLE 3.1
Binary search rules
Scenario
Result
Target element found in sorted
array
Index of match
Target element not found in
sorted array
Negative value showing one smaller than the
negative of index, where a match needs to be
inserted to preserve sorted order
Unsorted arrayA surprise—this result isn’t predictable
Let’s try out these rules with an example:
4: System.out.println(Arrays.binarySearch(numbers, 2)); // 05: System.out.println(Arrays.binarySearch(numbers, 4)); // 16: System.out.println(Arrays.binarySearch(numbers, 1)); // -17: System.out.println(Arrays.binarySearch(numbers, 3)); // -28: System.out.println(Arrays.binarySearch(numbers, 9)); // -5Take note of the fact that line 3 is a sorted array. If it weren’t, we couldn’t apply either
of the other rules. Line 4 searches for the index of 2. The answer is index 0. Line 5 searches
for the index of 4, which is 1.
Line 5 searches for the index of 1. Although 1 isn’t in the list, the search can determine
that it should be inserted at element 0 to preserve the sorted order. Since 0 already means
something for array indexes, Java needs to subtract 1 to give us the answer of₅1. Line 7
is similar. Although 3 isn’t in the list, it would need to be inserted at element 1 to preserve
the sorted order. We negate and subtract 1 for consistency, gettin朠–1₅1, also known as
–2. Finally, line 8 wants to tell us that 9 should be inserted at index 4. We again negate and
subtract 1, gettin朠–4₅1, also known as₅5.
126
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 126
What do you think happens in this example?
6: System.out.println(Arrays.binarySearch(numbers, 2)); 7: System.out.println(Arrays.binarySearch(numbers, 3));Note that on line 5, the array isn’t sorted. This means the output will not be predictable.
When testing this example, line 6 correctly gave 1 as the output. However, line 3 gave the
wrong answer. The exam creators will not expect you to know what incorrect values come
out. As soon as you see the array isn’t sorted, look for an answer choice about unpredict-
able output.
On the exam, you need to know what a binary search returns in various scenarios.
Oddly, you don’t need to know wh礠贀binaryŽ is in the name. In case you are curious, a
binary search splits the array into two equal pieces (remember 2 is binary) and determines
which half the target it is. It repeats this process until only one element is left.
Varargs
When creating an array yourself, it looks like what weve seen thus far. When one is passed
to your method, there is another way it can look. Here are three examples with a
method:
)public static void main(String args[]) public static void main(String... args) // varargsThe third example uses a syntax called varargs (variable arguments⤀, which you saw in
Chapter 1. You’ll learn how to call a method using varargs in Chapter 4,₍Methods and
Encapsulation.Ž For now, all you need to know is that you can use a variable de■
ned using
varargs as if it were a normal array. For example
and
are legal.
Multidimensional Arrays
Arrays are objects, and of course array components can be objects. It doesn’t take much
time, rubbing those two facts together, to wonder if arrays can hold other arrays, and of
course they can.
Creating a Multidimensional Array
Multiple array separators are all it takes to declare arrays with multiple dimensions. You
can locate them with the type or variable name in the declaration, just as before:
Understanding Java Arrays
127
c03.indd 1봀
4/2014 Page 127
Th攠■
rst two examples are nothing surprising and declare a two-dimensional (2D⤀ array.
The third example also declares a 2D array. Theres no good reason to use this style other
than to confuse readers of your code. Th攠■
nal example declares two arrays on the same
line. Adding up the brackets, we see that the
is a 2D array and
is a 3D array.
Again, there no reason to use this style other than to confuse readers of your code. The
exam creators like to try to confuse you, though. Luckily you are on to them and won’t let
this happen to you!
You can specify the size of your multidimensional array in the declaration if you like:
The result of this statement is an array rectangle with three elements, each of which
refers to an array of two elements. You can think of the addressable range as [0][0] through
[2][1], but don’t think of it as a structure of addresses like [0,0] or [2,1].
Now suppose we set one of these values:
While that array happens to be rectangular in shape, an array doesn’t need to be.
Consider this one:
We still start with an array of three elements. However, this time the elements in the
next level are all different sizes. One is of length 2, the next length 1, and the last length 3
⠀see Figure 3.7⤀. This time the array is of primitives, so they are shown as if they are in the
array themselves.
128
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 128
FIGURE 3.7
An asymmetric multidimensional array
Another way to create an asymmetric array is to initialize just an array’猠■
rst dimension,
and de■
ne the size of each array component in a separate statement:
args[0] = new int[5];args[1] = new int[3];This technique reveals what you really get with Java: arrays of arrays that, properly
managed, offer a multidimensional effect.
Using a Multidimensional Array
The most common operation on a multidimensional array is to loop through it. This example
prints out a 2D array:
for (int i = 0; i twoD.length; i++) { for (int j = 0; j twoD[i].length; j++) System.out.print(twoD[i][j] + " "); // print element System.out.println(); // time for a new row}We have two loops here. Th攠■
rst uses index
and goes through th攠■
rst subarray for
. The second uses a different loop variable
. It is very important these be different
variable names so the loops don’t get mixed up. The inner loop looks at how many elements
are in the second-level array. The inner loop prints the element and leaves a space for read-
ability. When the inner loop completes, the outer loop goes to a new line and repeats the
process for the next element.
This entire exercise would be easier to read with the enhanced
loop.
c03.indd 1봀
4/2014 Page 129
We’ll grant you that it isn’t fewer lines, but each line is less complex and there aren’t any
loop variables or terminating conditions to mix up.
Understanding an
ArrayList
An array has one glaring shortcoming: you have to know how many elements will be in the
array when you create it and then you are stuck with that choice. Just like a
can change size at runtime as needed. Like an array, an
is an ordered
sequence that allows duplicates.
As when we used
requires an import. To use it, you must have
either of the following two statements in your class:
Remember that if you are shown a code snippet with a line number that doesn’t begin
with 1, you can assume the necessary imports are there. Similarly, you can assume the
imports are present if you are shown a snippet of a method.
In this section, well look at creating an
, common methods, autoboxing,
conversion, and sorting.
Experienced programmers, take note: This section is simpli■
ed and doesn’t cover a
number of topics that are out of scope for the OCA exam.
Creating an
ArrayList
As with
, there are three ways to create an
Th攠■
rst says to create an
containing space for the default number of
elements but not to 
ll any slots yet. The second says to create an
containing a
speci■
c number of slots, but again not to assign any. Th攠■
nal example tells Java that we
want to make a copy of another
. We copy both the size and contents of that
. Granted,
list2
is empty in this example so it isn’t particularly interesting.
Although these are the only three constructors you need to know, you do need to learn
some variants of it. The previous examples were the old pre–Java 5 way of creating an
. They still work and you still need to know they work. You also need to know
Understanding an
ArrayList
129
130
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 130
the new and improved way. Java 5 introduced
generics
, which allow you to specify the type
of class that the
will contain.
Java 5 allows you to tell the compiler what the type would be by specifying it between
and
. Starting in Java 7, you can even omit that type from the right side. The
and
are
still required, though. This is called the diamond operator because
looks like a diamond.
Just when you thought you knew everything about creating an
, there is one
more thing you need to know.
implements an interface called
. In other
words, an
is a
. You will learn about interfaces in Chapter 5. In the mean-
time, just know that you can store an
in a
reference variable but not vice
versa. The reason is that
is an interface and interfaces can’t be instantiated.
Using an
ArrayList
has many methods, but you only need to know a handful of them—even fewer
than you did for
and
Before reading any further, you are going to see something new in the method signatures:
愠贀class踠渀amed
. Don’t worry—it isn’t really a class.
is used by convention in generics
to mean₍any class that this array can hold.踀 If you didn’t specify a type when creating the
means
. Otherwise, it means the class you put between
and
You should also know that
implements
so you can easily see the
contents just by printing it. Arrays do not do produce such pretty output.
add(⤀
The
methods insert a new value in the
. The method signatures are as
follows:
Don’t worry about the
return value. It always returns
. It is there because
other classes in the collections family need a return value in the signature when adding an
element.
Since
is the most critical
method you need to know for the exam, we are
going to show a few sets of examples for it. Let’s start with the most straightforward case:
c03.indd 1봀
4/2014 Page 131
System.out.println(list); // [hawk, true]add() does exactly what we expect: it stores the
in the no longer empty
. It then does the same thing for the
. This is okay because we didn’t
specify a type for
; therefore, the type is
, which includes everything
except primitives. It may not have been what we intended, but the compiler doesn’t know
that. Now, let’s use generics to tell the compiler we only want to allow
objects in
our
This time the compiler knows that only
objects are allowed in and prevents the
attempt to add a
. Now let’s try adding multiple values to different positions.
6: birds.add(1, "robin"); // [hawk, robin]7: birds.add(0, "blue jay"); // [blue jay, hawk, robin]8: birds.add(1, "cardinal"); // [blue jay, cardinal, hawk, robin]9: System.out.println(birds); // [blue jay, cardinal, hawk, robin]When a question has code that adds objects at indexed positions, draw it so that you
won’t lose track of which value is at which index. In this example, line 5 adds
to the
end of
. Then line 6 adds
to index 1 of
, which happens to be the end.
Line 7 adds
to index 0, which happens to be the beginning of
. Finally,
line 8 adds
Ž to index 1, which is now near the middle of
remove⠀⤀
The
methods remove th攠■
rst matching value in the
or remove the
element at a speci■
ed index. The method signatures are as follows:
This time the
return value tells us whether a match was removed. The
return
type is the element that actually got removed. The following shows how to use these
methods:
5: birds.add("hawk"); // [hawk, hawk]6: System.out.println(birds.remove("cardinal")); // prints false7: System.out.println(birds.remove("hawk")); // prints trueUnderstanding an
ArrayList
131
132
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 132
Line 6 tries to remove an element that is not in
. It returns
because no such
element is found. Line 7 tries to remove an element that is in
and so returns
Notice that it removes only one match. Line 8 removes the element at index 0, which is the
last remaining element in the
Since calling
with an
uses the index, an index that doesn’t exist will throw
an exception. For example,
throws an
There is also a
method. We’ll cover it in the next chapter because it uses
lambda expressions (a topic in that chapter⤀.
set⠀⤀
The
c03.indd 1봀
4/2014 Page 133
At the beginning,
has a size of 0 and is empty. It has a capacity that is greater
than 0. However, as with
, we don’t use the capacity in determining size or
length. After adding elements, the size becomes positive and it is no longer empty.
clear⠀⤀
The
method provides an easy way to discard all elements of the
. The
method signature is as follows:
The following shows how to use this method:
birds.add("hawk"); // [hawk, hawk]System.out.println(birds.isEmpty()); // falseSystem.out.println(birds.size()); // 2birds.clear(); // []System.out.println(birds.isEmpty()); // trueSystem.out.println(birds.size()); // 0After we call
is back to being an empty
of size 0.
contains⠀⤀
The
method checks whether a certain value is in the
. The method
signature is as follows:
The following shows how to use this method:
System.out.println(birds.contains("hawk")); // trueSystem.out.println(birds.contains("robin")); // falseThis method calls
on each element of the
to see whether there are
any matches. Since
implements
, this works out well.
equals(⤀
Finally,
has a custom implementation of
so you can compare two lists
to see if they contain the same elements in the same order.
Understanding an
ArrayList
133
134
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 134
The following shows an example:
35: System.out.println(one.equals(two)); // false36: two.add("a"); // [a]37: System.out.println(one.equals(two)); // true38: one.add("b"); // [a,b]39: two.add(0, "b"); // [b,a]40: System.out.println(one.equals(two)); // falseOn line 33, the two
objects are equal. An empty list is certainly the same
elements in the same order. On line 35, the
objects are not equal because the size
is different. On line 37, they are equal again because the same one element is in each. On
line 40, they are not equal. The size is the same and the values are the same, but they are
not in the same order.
Wrapper Classes
Up to now, weve only put
objects in the
. What happens if we want to
put primitives in? Each primitive type has a wrapper class, which is an object type that
corresponds to the primitive. Table 3.2 lists all the wrapper classes along with the
constructor for each.
TABLE 3.2
Wrapper classes
Primitive type
Wrapper class
Example of constructing
booleanBoolean
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
c03.indd 1봀
4/2014 Page 135
The wrapper classes also have a method that converts back to a primitive. You don’t
need to know much about the constructors or i
type methods for the exam
because autoboxing has removed the need for them (see the next section⤀. You might
encounter this syntax on questions that have been on the exam for many years. However,
you just need to be able to read the code and not look for tricks in it.
There are also methods for converting a
to a primitive or wrapper class. You do
need to know these methods. The parse methods, such as
, return a primitive,
and the
method returns a wrapper class. This is easy to remember because the
name of the returned primitive is in the method name. For example:
Th攠■
rst line converts a
to an
primitive. The second converts a
to an
wrapper class. If the
passed in is not valid for the given type, Java throws
an exception. In these examples, letters and dots are not valid for an integer value:
Before you worry, the exam won’t make you recognize that the method
is used rather than
. You simply need to be able to recognize the meth-
ods when put in front of you. Also, the
class doesn’t participate in the
methods. Since a
is made up of characters, you can just call
normally.
Table 3.3 lists the methods you need to recognize for creating a primitive or wrapper
class object from a
. In real coding, you won’t be so concerned which is returned
from each method due to autoboxing.
TABLE 3.3
Converting from a
Wrapper class
Converting
to primitive
Converting
to
wrapper class
Boolean
Boolean.parseBoolean("true");Boolean.valueOf("TRUE");
Byte
Byte.parseByte("1");Byte.valueOf("2");
Short
Short.parseShort("1");Short.valueOf("2");
Integer
Integer.parseInt("1");Integer.valueOf("2");
Long
Long.parseLong("1");Long.valueOf("2");
Float
Float.parseFloat("1");Float.valueOf("2.2");
Double
Double.parseDouble("1");Double.valueOf("2.2");
CharacterNoneNone
Understanding an
ArrayList
135
136
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 136
Autoboxing
Why won’t you need to be concerned with whether a primitive or wrapper class is returned,
you ask? Since Java 5, you can just type the primitive value and Java will convert it to the
relevant wrapper class for you. This is called
autoboxing
. Let’s look at an example:
Understanding an ArrayList
137
c03.indd 1봀
4/2014 Page 137
()7: System.out.println(objectArray.length); // 28: String[] stringArray = list.toArray(new String[0]);9: System.out.println(stringArray.length); // 2Line 6 shows that an
knows how to convert itself to an array. The only prob-
lem is that it defaults to an array of class
. This isn’t usually what you want. Line 8
speci■
es the type of the array and does what we actually want. The advantage of specifying
a size of 0 for the parameter is that Java will create a new array of the proper size for the
return value. If you like, you can suggest a larger array to be used instead. If the
ts in that array, it will be returned. Otherwise, a new one will be created.
Converting from an array to a
is more interesting. The original array and created
array backed
are linked. When a change is made to one, it is available in the other. It
is a 
xed-size list and is also known a
backed
because the array changes with it. Pay
careful attention to the values here:
138
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 138
Sorting
Sorting an
is very similar to sorting an array. You just use a different helper class:
As you can see, the numbers got sorted, just like you’d expect. Isn’t it nice to have some-
thing that works just like you think it will?
Working with Dates and Times
In Java 8, Oracle completely revamped how we work with dates and times. You can still
write code th攠贀old way,踠but those classes aren’t on the exam. We’ll mention th攠贀old wa禎
in real-world scenarios so that you can learn th攠贀new wayŽ more easily if yo甠■
rst learned
Java before version 8. Even if you are learning Java starting with version 8, this will help
you when you need to read older code. Just know that th攠贀old wayŽ is not on the exam.
As with an
, you need an import statement to work with the date and time classes.
Most of them are in the
package. To use it, add this
to your program:
In the following sections, well look at creating, manipulating, and formatting dates and times.
Creating Dates and Times
In the real world, we usually talk about dates and time zones as if the other person is
located near us. For example, if you say I’ll call you at 11:00 on Tuesday morning,Ž we
assume that 11:00 means the same thing to both of us. But if you live in New York and we
live in California, you need to be more speci■
c. California is three hours earlier than New
York because the states are in different time zones. You would instead say,₍I’ll call you at
11:00 EST on Tuesday morning.踠Luckily, the exam doesn’t cover time zones, so discussing
dates and times is easier.
When working with dates and times, th攠■
rst thing to do is decide how much informa-
tion you need. The exam gives you three choices:
Contains just a date—no time and no time zone. A good example of
is your birthday this year. It is your birthday for a full day regardless of what
time it is.
Working with Dates and Times
139
c03.indd 1봀
4/2014 Page 139
Contains just a time—no date and no time zone. A good example of
is midnight. It is midnight at the same time every day.
140
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 140
Now that you know how to create the current date and time, let’s look at other speci■
c
dates and times. To begin, let’s create just a date with no time. Both of these examples
create the same date:
Both pass in the year, month, and date. Although it is good to use the
constants
⠀to make the code easier to read⤀, you can pass the
number of the month directly.
Just use the number of the month the same way you would if you were writing the date
in real life.
The method signatures are as follows:
Month is a special type of class called an enum. You don’t need to know about enums on
the OCA exam and can just treat them as constants.
Up to now, weve been like a broken record telling you that Java counts
starting with 0. Well, months are an exception. For months in the new date
and time methods, Java counts starting from 1 like we human beings do.
When creating a time, you can choose how detailed you want to be. You can specify just
the hour and minute, or you can add the number of seconds. You can even add nanosec-
onds if you want to be very precise. (A nanosecond is a billionth of a second—you probably
won’t need to be that speci■
c.⤀
These three times are all different but within a minute of each other. The method signa-
tures are as follows:
Finally, we can combine dates and times:
Working with Dates and Times
141
c03.indd 1봀
4/2014 Page 141
to specify different things. Having that many numbers in a row gets to be hard to read,
though. The second line of code shows how you can create
and
objects separately 
rst and then combine them to create a
continues
142
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 142
There’s an old way to create a date. In Java 1.1, you created a specifi
c
with this:
. You could use the
class
beginning with Java 1.2.
exists mainly for backward compatibility and so that
can work with code—making th攠贀new way踀 the third way. Th攠贀new way踀 is
much better so it looks like this is a case of the third time is the charm!
Old way
New way (Java 8 and
later⤀
Importing
import java.util.*;import java
Creating an
object with
the
current
date
Date d = new Date();LocalDate d =
Creating an
object with
the
current
date and time
continued
Working with Dates and Times
143
c03.indd 1봀
4/2014 Page 143
This code is nice because it does just what it sounds like. We start out with January 20,
2014. On line 14, we add two days to it and reassign it to our reference variable. On line 16,
we add a week. This method allows us to write clearer code than
. Now
is
January 29, 2014. On line 18, we add a month. This would bring us to February 29, 2014.
However, 2014 is not a leap year. (2012 and 2016 are leap years.) Java is smart enough to
realize February 29, 2014 does not exist and gives us February 28, 2014 instead. Finally, line
20 adds 
ve years.
There are also nice easy methods to go backward in time. This time, let’s work with
full day, bringing us to January 19, 2020 at 5:15 a.m. Line 28 subtracts 10 hours, showing
that the date will change if the hours cause it to and brings us to January 18, 2020 at 19:15
⠀7:15 p.m.⤀. Finally, line 30 subtracts 30 seconds. We see that all of a sudden the display
value starts displaying seconds. Java is smart enough to hide the seconds and nanoseconds
when we aren’t using them.
It is common for date and time methods to be chained. For example, without the print
statements, the previous example could be rewritten as follows:
144
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 144
It prints January 20, 2020. Adding 10 days was useless because we ignored the result.
Whenever you see immutable types, pay attention to make sure the return value of a
method call isn’t ignored.
The exam also may test to see if you remember what each of the date and time objects
includes. Do you see what is wrong here?
does not contain time. This means you cannot add minutes to it. This can be
tricky in a chained sequence of additions/subtraction operations, so make sure you know
which methods in Table 3.4 can be called on which of the three objects.
TABLE 3.4
Methods in
, and
Can call on
Can call on
Can call on
Working with Dates and Times
145
c03.indd 1봀
4/2014 Page 145
Old way
New way (Java 8 and later⤀
Adding a day
getInstance
getInstance
146
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 146
This code work猠■
ne. It adds a month to the date until it hits the end date. The problem
is that this method can’t be reused. Our zookeeper wants to try different schedules to see
which works best.
Converting to a
and
Working with Dates and Times
147
c03.indd 1봀
4/2014 Page 147
Theres one catch. You cannot chain methods when creating a
. The following
code looks like it is equivalent to the
example, but it’s not. Only the
last method is used because the
.ofXXX methods are static methods.
This tricky code is really like writing the following:
This is clearly not what you intended! That’s why the
method allows us to pass in
the number of years, months, and days. They are all included in the same period. You will
get a compiler warning about this. Compiler warnings tell you something is wrong or suspi-
cious without failing compilation.
You’ve probably noticed by now that a
is a day or more of time. There is also
, which is intended for smaller units of time. For
, you can specify the
number of days, hours, minutes, seconds, or nanoseconds. And yes, you could pass 365
days to make a year, but you really shouldn’t—that’s what
is for.
isn’t
on the exam since it roughly works the same way as
. It’s good to know it exists,
though.
The last thing to know about
is what objects it can be used with. Let’s look at
some code:
148
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 148
Formatting Dates and Times
The date and time classes support many methods to get data out of them:
Working with Dates and Times
149
c03.indd 1봀
4/2014 Page 149
Calling
Calling
Calling
Legal … shows
whole object
Legal … shows
just date part
Throws runtime
exception
150
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 150
Before we look at the syntax, know you are not expected to memorize what different
numbers of each symbol mean. The most you will need to do is recognize the date and time
pieces.
represents the month. The more
s you have, the more verbose the Java output.
For example,
outputs 1,
outputs 01,
outputs Jan, and
outputs January.
represents the date in the month. As with month, the more
s you have, the more
verbose the Java output.
means to include the leading zero for a single-digit month.
Use
if you want to output a comma (this also appears after the year⤀.
represents the year.
outputs a two-digit year and
outputs a four-digit year.
represents the hour. Use
to include the leading zero if you’re outputting a single-
digit hour.
Use : if you want to output a colon.
represents the minute.
Formatting Dates in Java 7 and Earlier
Formatting is roughly equivalent to th攠贀old way踀; it just uses a different class.
Old way
New way (Java 8 and later⤀
Formatting the
times
Summary
151
c03.indd 1봀
4/2014 Page 151
Parsing Dates and Times
Now that you know how to convert a date or time to a formatted
, you’ll 
nd it easy
to convert a
to a date or time. Just like the
method, the
method
takes a formatter as well. If you don’t specify one, it uses the default for that type.
152
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 152
need to be inserted and subtracts 1. Methods that are passed varargs (…) can be used as
if a normal array was passed in. In a multidimensional array, the second-level arrays and
beyond can be different sizes.
An
can change size over its life. It can be stored in an
reference. Generics can specify the type that goes in the
. You need to know the
methods
Review Questions
153
c03.indd 1봀
4/2014 Page 153
Review Questions
What is output by the following code? (Choose all that apply⤀
)3: int numFish = 4;4: String fishType = "tuna";5: String anotherFish = numFish + 1;6: System.out.println(anotherFish + " " + fishType);7: System.out.println(numFish + " " + 1);8: } }A. 4 1B. 41C. 5D. 5 tunaE. 5tunaF. 51tunaG. The code does not compile.
Which of the following are output by this code? (Choose all that apply⤀
The code does not compile.
Which are true statements? (Choose all that apply⤀
An immutable object can be modified.
An immutable object cannot be modified.
An immutable object can be garbage collected.
154
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 154
An immutable object cannot be garbage collected.
is immutable.
is immutable.
is immutable.
What is the result of the following code?
bbaaccca
An exception is thrown.
The code does not compile.
What is the result of the following code?
No output is printed.
An exception is thrown.
The code does not compile.
What is the result of the following code?
Review Questions
155
c03.indd 1봀
4/2014 Page 155
An exception is thrown.
The code does not compile.
Which are the results of the following code? (Choose all that apply⤀
156
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 156
An exception is thrown.
The code does not compile.
10.
What is the result of the following code? (Choose all that apply⤀
16: a += false;
Compile error on line 14.
Compile error on line 15.
Compile error on line 16.
Compile error on another line.
==
equals
An exception is thrown.
11.
What is the result of the following code?
Review Questions
157
c03.indd 1봀
4/2014 Page 157
12.
What is the result of the following code? (Choose all that apply⤀
158
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 158
16.
Which of these compile when replacing line 8? (Choose all that apply⤀
8: // INSERT CODE HEREA. int length = c.capacity;B. int length = c.capacity();C. int length = c.length;D. int length = c.length();E. int length = c.size;F. int length = c.size();G. None of the above.
17.
Which of these compile when replacing line 8? (Choose all that apply⤀
None of the above.
18.
Which of the following are true? (Choose all that apply⤀
An array has a fixed size.
An
has a fixed size.
An array allows multiple dimensions.
An array is ordered.
An
is ordered.
An array is immutable.
An
is immutable.
19.
Which of the following are true? (Choose all that apply⤀
Two arrays with the same content are equal.
Two
with the same content are equal.
If you call
using an empty
object, it will compile successfully.
If you call
using an empty
object, it will run successfully.
None of the above.
Review Questions
159
c03.indd 1봀
4/2014 Page 159
20.
What is the result of the following statements?
160
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 160
23.
What is the result of the following?
()7: System.out.println(array[0]);A. 蔱B. 10C. Compiler error on line 4.
Compiler error on line 5.
Compiler error on line 6.
An exception is thrown.
What is the result of the following?
Review Questions
161
c03.indd 1봀
4/2014 Page 161
The code compiles.
The code throws a runtime exception.
Exactly one of the add statements uses autoboxing.
Exactly two of the add statements use autoboxing.
Exactly three of the add statements use autoboxing.
27.
What is the result of the following?
An exception is thrown.
The code does not compile.
Which of the following can be inserted into the blank to create a date of June 21, 2014?
⠀Choose all that apply⤀
162
Chapter 3
Core Java APIs
c03.indd 1봀
4/2014 Page 162
29.
What is the output of the following code?
Review Questions
163
c03.indd 1봀
4/2014 Page 163
A runtime exception is thrown.
32.
What is the output of the following code?
c04.indd 1봀
4/2014 Page 165
Chapter
c04.indd 1봀
4/2014 Page 166
In previous chapters, weve used methods and constructors
without examining them in detail. In this chapter, well explore
methods and constructors in depth and cover everything you
need to know about them for the OCA exam. (Well, almost—Chapter 5,₍Class Design,踀
will explain the effects of inheritance on both methods and constructors.) This chapter dis-
cusses instance variables, the
keyword, access modi■
ers, and initialization. You’ll also
learn how to write a simple lambda expression.
Designing Methods
Every interesting Java program weve seen has had a
method. We can write other meth-
ods, too. For example, we can write a basic method to take a nap, as shown in Figure 4.1.
FIGURE 4.1
Method signature
This is called a
Element
Value in
example
Required?
Access modifier
Optional specifier
Designing Methods
167
c04.indd 1봀
4/2014 Page 167
Element
Value in
example
Required?
Return type
Yes
Method name
Yes
Parameter list
Yes, but can be empty parentheses
Optional exception
list
Method body
Yes, but can be empty braces
To call this method, just type its name, followed by a single
value in parentheses:
Let’s start by taking a look at each of these parts of a basic method.
Access Modifiers
Java offers four choices of access modi■
er:
public
The method can be called from any class.
private
The method can only be called from within the same class.
protected
The method can only be called from classes in the same package or subclasses.
You’ll learn about subclasses in Chapter 5.
Default (Package Private⤀ Access
The method can only be called from classes in the same
package. This one is tricky because there is no keyword for default access. You simply omit
the access modi■
er.
There’s a
keyword in Java. You saw it in the
statement in
Chapter 2, Operators and Statements,踀 and you’ll see it again in the next
chapter when we discuss interfaces. It’s not used for access control.
We’ll explore the impact of the various access modi■
ers later in this chapter. For now, just
master identifying valid syntax of methods. The exam creators like to trick you by putting
method elements in the wrong order or using incorrect values.
We’ll have practice examples as we go through each of the method elements in this sec-
tion. Make sure you understand why each of these is a valid or invalid method declaration.
Pay attention to the access modi■
ers as yo甠■
gure out what is wrong with the ones that
don’t compile:
168
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 168
is a valid method declaration with public access.
is a valid method
declaration with default access.
doesn’t compile because default is not a valid access
modi■
er.
doesn’t compile because the access modi■
er is speci■
ed after the return
type.
Optional Specifiers
There are a number of optional speci■
ers, but most of them aren’t on the exam. Optional
speci■
ers come from the following list. Unlike with access modi■
ers, you can have multiple
speci■
ers in the same method (although not all combinations are legal⤀. When this happens,
you can specify them in any order. And since it is optional, you can’t have any of them at
all. This means you can have zero or more speci■
ers in a method declaration.
static
Covered later in this chapter. Used for class methods.
abstract
Covered in Chapter 5. Used when not providing a method body.
final
Covered in Chapter 5. Used when a method is not allowed to be overridden by a
subclass.
synchronized
On the OCP but not the OCA exam.
native
Not on the OCA or OCP exam. Used when interacting with code written in
another language such as C++.
strictfp
Not on the OCA or OCP exam. Used for making 
oating-point calcu-
lations portable.
Again, just focus on syntax for now. Do you see why these compile or don’t compile?
is a valid method declaration with no optional speci■
er. This is okay; it is
optional, after all.
is a valid method declaration, with
as the optional
speci■
er.
and
are valid method declarations with both
and
as optional speci■
ers. The order of these two keywords doesn’t matter.
doesn’t
Designing Methods
169
c04.indd 1봀
4/2014 Page 169
compile because
modi■
er
is not a valid optional speci■
er.
doesn’t compile because
the optional speci■
er is after the return type.
does compile. Java allows the optional speci■
ers to appear before the access
modi■
er. This is a weird case and not one you need to know for the exam. We are mentioning
it so you don’t get confused when practicing.
Return Type
The next item in a method declaration is the return type. The return type might be an
actual Java type such as
. If there is no return type, the
keyword is used.
This special return type comes from the English language:
void
means without contents. In
Java, we have no type there.
Remember that a method must have a return type. If no value is returned,
the return type is
. You cannot omit the return type.
When checking return types, you also have to look inside the method body. Methods
with a return type other than
are required to have a
170
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 170
When returning a value, it needs to be assignable to the return type. Imagine there is a
local variable of that type to which it is assigned before being returned. Can you think of
how to add a line of code with a local variable in these two methods?
Designing Methods
171
c04.indd 1봀
4/2014 Page 171
Parameter List
Although the parameter list is required, it doesn’t have to contain any parameters. This
means you can just have an empty pair of parentheses after the method name, such as
. If you do have multiple parameters, you separate them with a comma. There are
a couple more rules for the parameter list that you’ll see when we cover varargs shortly. For
now, let’s practice looking at method signatures with₍regularŽ parameters:
is a valid method declaration without any parameters.
doesn't compile
because it is missing the parentheses around the parameter list.
is a valid method
declaration with one parameter.
doesn't compile because the parameters are sepa-
rated by a semicolon rather than a comma. Semicolons are for separating statements, not
parameter lists.
is a valid method declaration with two parameters.
Optional Exception List
In Java, code can indicate that something went wrong by throwing an exception. We’ll cover
this in Chapter 6,₍Exceptions.Ž For now, you just need to know that it is optional and
where in the method signature it goes if present. In the example,
is a
type of
. You can list as many types of exceptions as you want in this clause sepa-
rated by commas. For example:
You might be wondering what methods do with these exceptions. The calling
method can throw the same exceptions or handle them. You’ll learn more about
this in Chapter 6.
Method Body
The 
nal part of a method declaration is the method body (except for abstract methods and
interfaces, but you don’t need to know about either of those until next chapter⤀. A method
body is simply a code block. It has braces that contain zero or more Java statements. We’ve
spent several chapters looking at Java statements by now, so you should 
nd it easy to 
gure
out why these compile or don’t:
172
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 172
is a valid method declaration without an empty method body.
doesn't
compile because it is missing the braces around the empty method body.
is a valid
method declaration with one statement in the method body.
You’ve made it through the basics of identifying correct and incorrect method declara-
tions. Now we can delve into more detail.
Working with Varargs
As you saw in the previous chapter, a method may use a vararg parameter (variable argu-
ment) as if it is an array. It is a little different than an array, though. A vararg parameter
must be the last element in a method’s parameter list. This implies you are only allowed to
have one vararg parameter per method.
Can you identify why each of these does or doesn’t compile? (Yes, there is a lot of
practice in this chapter. You have to be really good at identifying valid and invalid methods
for the exam.⤀
is a valid method declaration with one vararg parameter.
is a valid
method declaration with one
parameter and one vararg parameter.
and
do not compile because they have a vararg parameter in a position that is not the
last one.
When calling a method with a vararg parameter, you have a choice. You can pass in an
array, or you can list the elements of the array and let Java create it for you. You can even
omit the vararg values in the method call and Java will create an array of length zero for
you.
Finally! We get to do something other than identify whether method declarations are
valid. Instead we get to look at method calls. Can yo甠■
gure out why each method call out-
puts what it does?
Applying Access Modifiers
173
c04.indd 1봀
4/2014 Page 173
)23: }Line 19 passes 1 as
but nothing else. This means Java creates an array of length 0 for
. Line 20 passes 1 as
and one more value. Java converts this one value to an array of
length 1. Line 21 passes 1 as
and two more values. Java converts these two values to an
array of length 2. Line 22 passes 1 as
and an array of length 2 directly as
You’ve seen that Java will create an empty array if no parameters are passed for a
vararg. However, it is still possible to pass
explicitly:
Since
isn’t an
, Java treats it as an array reference that happens to be
just passes on the
array object to
. Then the
method throws an exception
because it tries to determine the length of
Accessing a vararg parameter is also just like accessing an array. It uses array indexing.
For example:
)18: }19: public static void main(String[] args) {20: run(11, 22); // 2221: }Line 20 calls a vararg parameter two parameters. When the method gets called, it sees
an array of size 2. Since indexes are 0 based, 22 is printed.
Applying Access Modifiers
You already saw that there are four access modi■
ers:
, and
default access. We are going to discuss them in order from most restrictive to least restrictive:
: Only accessible within the same class
default (package private⤀ access:
and other classes in the same package
: default access and child classes
and classes in the other packages
Private Access
174
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 174
Before we start, take a look at Figure 4.2. It shows the classes well use to explore pri-
vate and default access. The big boxes are the names of the packages. The smaller boxes
inside them are the classes in each package. You can refer back to this 
gure if you want to
quickly see how the classes relate.
FIGURE 4.2
Classes used to show private and default access
This is perfectly legal code because everything is one class:
So far, so good.
makes a call to private method
on line 8 and uses
private instance variable
noise
on line 5.
Now we add another class:
Applying Access Modifiers
175
c04.indd 1봀
4/2014 Page 175
is trying to access members it has no business touching. On line 5, it tries
to access a private method in another class. On line 6, it tries to access a private instance
variable in another class. Both generate compiler errors. Bad duckling!
Our bad duckling is only a few days old and doesn’t know better yet. Luckily, you know
that accessing private members of other classes is not allowed and you need to use a differ-
ent type of access.
Default (Package Private⤀ Access
Luckily,
is more accommodating about what her ducklings can do. She allows
classes in the same package to access her members. When there is no access modi■
er, Java
uses the default, which is package private access. This means that the member is₍private踠
to classes in the same package. In other words, only classes in the package may access it.
can call
and refer to
noise
. After all, members in the same class
are certainly in the same package. The big difference is
lets other classes in the
same package access members (due to being package private⤀ whereas
doesn’t
⠀due to being private⤀.
has a much better experience than
succeeds in learning to
and make
noise
by copying its mother.
Notice that all the classes weve covered so far are in the same package
. This
allows default (package private⤀ access to work.
In this same pond, a swan just gave birth to a baby swan. A baby swan is called a cygnet.
The cygnet sees the ducklings learning to quack and decides to learn from
as well.
176
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 176
GooseWatcher
BirdWatcherFromAfar
BirdWatcher
Applying Access Modifiers
177
c04.indd 1봀
4/2014 Page 177
First, we create a
class and give
access to its members:
Next we create a subclass:
This is a very simple subclass. It
the
class. Extending means creating a
subclass that has access to any
members of the parent class. Running
this code prints
twice: once from calling
and once from the print
statement in
. Since
is a subclass of
, it can access these members even
though it is in a different package.
Remember that
also gives us access to everything that default access does.
This means that a class in the same package as
can access its
members.
Since
and
are in the same package,
can access members
of the
bird
variable. The de■
nition of
allows access to subclasses and classes in
the same package. This example uses the same package part of that de■
nition.
Now let’s try the same thing from a different package:
178
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 178
is not in the same package as
and it doesn’t inherit from
. This means that it is not allowed to access
members of
Got that? Subclasses and classes in the same package are the only ones
allowed to access
members.
There is one gotcha for
access. Consider this class:
Take a deep breath. This is interesting.
is not in the same package as
, but does
extend it—which implies it has access to the
members of
since it is a sub-
class. And it does. Lines 5 and 6 refer to
members via inheriting them.
Lines 10 and 11 also successfully use
members of
. This is allowed
because these lines refer to a
object. Swan inherits from
so this is okay. It is sort
of a two-phase check. The
class is allowed to use
members of
and we
are referring to a
object. Granted, it is a
object created on line 9 rather than an
inherited one, but it is still a
object.
Lines 15 and 16 do
not
compile. Wait a minute. They are almost exactly the same as
lines 10 and 11! Theres one key difference. This time a
reference is used. It is created
on line 14.
is in a different package, and this code isn’t inheriting from
, so it
doesn’t get to use
members. Say what now? We just got through saying repeat-
edly that
inherits from
. And it does. However, the variable reference isn’t a
The code just happens to be in the
class.
Applying Access Modifiers
179
c04.indd 1봀
4/2014 Page 179
It’s okay to be confused. This is arguably one of the most confusing points on the exam.
Looking at it a different way, the
rules apply under two scenarios:
A member is used without referring to a variable. This is the case on lines 5 and 6. In
this case, we are taking advantage of inheritance and
access is allowed.
A member is used through a variable. This is the case on lines 10, 11, 15, and 16.
In this case, the rules for the reference type of the variable are what matter. If it is a
subclass,
access is allowed. This works for references to the same class or a
subclass.
We’re going to try this again to make sure you understand what is going on. Can you
gure out why these examples don’t compile?
Th攠■
rst method is 
ne. In fact, it is equivalent to the
example.
extends
. Since we are in the
subclass and referring to a
reference, it can access
members. The second method is a problem. Although the object happens to be
, it is stored in a
reference. We are not allowed to refer to members of the
class since we are not in the same package and
is not a subclass of
What about this one?
This code doesn’t compile because we are not in the
class. The
method is declared in
is not in the same package as
, nor does it
180
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 180
extend
extends
. That only lets
and not
callers of
If this is still puzzling, try it out. Type in the code and try to make it compile. Then
reread this section. Don’t worry—it wasn’t obvious to the authors th攠■
rst time either!
Public Access
Protected access was a tough concept. Luckily, the last type of access modi■
er is easy:
means anyone can access the member from anywhere.
allows access to any class that wants it. Now we can try it out:
is able to refer to
and
because they are pub-
lic. The story has a happy ending.
has learned to swim and ca渠■
nd its par-
ents—all because
made them public.
To review access modi■
ers, make sure you know why everything in Table 4.2 is true.
Remember that a member is a method or 
eld.
TABLE 4.2
Access modifiers
Can access
If that member
is private?
If that member has
default (package
private⤀ access?
If that member
is protected?
If that
member is
public?
Member in the same
class
YesYesYesYes
Member in another
class in same package
NoYesYesYes
Applying Access Modifiers
181
c04.indd 1봀
4/2014 Page 181
Can access
If that member
is private?
If that member has
default (package
private⤀ access?
If that member
is protected?
If that
member is
public?
Member in a
superclass in a
different package
NoNoYesYes
Method/field in a non-
superclass class in a
different package
NoNoNoYes
Designing Static Methods and Fields
182
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 182
Applying Access Modifiers
183
c04.indd 1봀
4/2014 Page 183
One more time because this is really important: what does the following output?
Hopefully, you answered 5. There is only one
count
variable since it is static. It is set to
4, then 6, an搠■
nally winds up as 5. All the
variables are just distractions.
Static vs. Instance
Theres another way the exam creators will try to trick you regarding static and instance
members. (Remember that₍member踀 mean猠■
eld or method.⤀ A static member cannot call
an instance member. This shouldn’t be a surprise since static doesn’t require any instances
of the class to be around.
The following is a common mistake for rookie programmers to make:
) first(); second(); third(); // DOES NOT COMPILE } }The compiler will give you an error about making a static reference to a nonstatic
method. If we 
x this by adding
, we create a new problem. Can you
gure out what it is?
All this does is move the problem. Now,
is referring to nonstatic
. Adding
as well would solve the problem. Another solution would have been to call
as an instance method—for example,
The exam creators like this topic. A static method or instance method can call a static
method because static methods don’t require an object to use. Only an instance method can
call another instance method on the same class without using a reference variable, because
instance methods do require an object. Similar logic applies for the instance and static vari-
ables. Make sure you understand Table 4.3 before continuing.
184
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 184
TABLE 4.3
Static vs. instance calls
Type
Calling
Legal?
How?
Static methodAnother static method or
variable
YesUsing the classname
Static methodAn instance method or
variable
Instance methodA static method or variableYesUsing the classname or a
reference variable
Instance methodAnother instance method
or variable
YesUsing a reference variable
Let’s try one more example so you have more practice at recognizing this scenario. Do
you understand why the following lines fail to compile?
Lines 3 and 4 ar攠■
ne because both static and instance methods can refer to a static
variable. Lines 5–8 ar攠■
ne because an instance method can call a static method. Line 11
doesn’t compile because a static method cannot call an instance method. Similarly, line 14
doesn’t compile because a static variable is trying to use an instance variable.
A common use for static variables is counting the number of instances:
Applying Access Modifiers
185
c04.indd 1봀
4/2014 Page 185
) Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); System.out.println(count); // 3 }}Each time the constructor gets called, it increments
count
by 1. This example relies on
the fact that static (and instance) variables are automatically initialized to the default value
for that type, which is 0 for
. See Chapter 1 to review the default values.
Also notice that we didn’t write
. We could have. It isn’t necessary
because we are already in that class so the compiler can infer it.
Static Variables
Some static variables are meant to change as the program runs. Counters are a common
example of this. We want the count to increase over time. Just as with instance variables,
you can initialize a static variable on the line it is declared:
Other static variables are meant to never change during the program. This type of vari-
able is known as a
constant
. It uses the
modi■
er to ensure the variable never changes.
constants use a different naming convention than other variables. They use
all uppercase letters with underscores between words.踀 For example:
186
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 186
Static Initialization
In Chapter 1, we covered instance initializers that looked like unnamed methods. Just code
inside braces. Static initializers look similar. They add the
keyword to specify they
should be run when the class is 
rst used. For example:
The static initializer runs when the class is 
rst used. The statements in it run
and assign any static variables as needed. There is something interesting about
this example. We just got through saying that 
nal variables aren’t allowed to
be reassigned. The key here is that the static initializer is th攠■
rst assignment.
And since it occurs up front, it is okay.
Let’s try another example to make sure you understand the distinction:
Line 14 declares a static variable that is no琠■
nal. It can be assigned as many times as we
like. Line 15 declares a 
nal variable without initializing it. This means we can initialize it
exactly once in a static block. Line 22 doesn’t compile because this is the second attempt. Line
16 declares a 
nal variable and initializes it at the same time. We are not allowed to assign it
again, so line 21 doesn’t compile. Line 17 declares a 
nal variable that never gets initialized.
The compiler gives a compiler error because it knows that the static blocks are the only place
the variable could possibly get initialized. Since the programmer forgot, this is clearly an error.
Try to Avoid Static and Instance Initializers
Using static and instance initializers can make your code much harder to read.
Everything that could be done in an instance initializer could be done in a con-
structor instead. The constructor approach is easier to read.
Applying Access Modifiers
187
c04.indd 1봀
4/2014 Page 187
There is a common case to use a static initializer: when you need to initialize a
staticₓ
eld and the code to do so requires more than one line. This often occurs
when you want to initialize a collection like an
. When you do need to
use a static initializer, put all the static initialization in the same block. That way,
the order is obvious.
Static Imports
Back in Chapter 1, you saw that we could import a speci■
c class or all the classes in a
package:
We could use this technique to import:
)&#xStri;&#xng00; ListString list = Arrays.asList("one", "two"); }} Imports are convenient because you don’t need to specify where each class comes
from each time you use it. There is another type of import called a static import. Regular
imports are for importing classes. Static imports are for importing static members of
classes. Just like regular imports, you can use a wildcard or import a speci■
c member. The
idea is that you shouldn’t have to specify where each static method or variable comes from
each time you use it. An example of when static interfaces shine are when you are referring
to a lot of constants in another class.
In a large program, static imports can be overused. When importing from
too many places, it can be hard to remember where each static member
comes from.
The previous method has one static method call:
. Rewriting the code to
use a static import yields the following:
188
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 188
In this example, we are speci■
cally importing the
method. This means that any
time we refer to
in the class, it will call
An interesting case is what would happen if we created an
method in our
class. Java would give it preference over the imported one and the method
we coded would be used.
The exam will try to trick you with misusing static imports. This example shows almost
everything you can do wrong. Can yo甠■
gure out what is wrong with each one?
)6: Arrays.asList("one"); // DOES NOT COMPILE7: } }Line 1 tries to use a static import to import a class. Remember that static imports are
only for importing static members. Regular imports are for importing a class. Line 3 tries
to see if you are paying attention to the order of keywords. The syntax is
and not vice versa. Line 6 is sneaky. We imported the
method on line 2. However,
we did not import the
class anywhere. This makes it okay to write
but not
Theres only one more scenario with static imports. In Chapter 1, you learned that
importing two classes with the same name gives a compiler error. This is true of static
imports as well. The compiler will complain if you try to explicitly do a static import of
two methods with the same name or two static variables with the same name. For example:
Luckily when this happens, we can just refer to the static members via their classname in
the code instead of trying to use a static import.
Passing Data Among Methods
Java is a pass-by-value踠language. This means that a copy of the variable is made and the
method receives that copy. Assignments made in the method do not affect the caller. Let’s
look at an example:
Passing Data Among Methods
189
c04.indd 1봀
4/2014 Page 189
On line 3,
is assigned the value of 4. On line 4, we call a method. On line 8, the
parameter in the method gets set to 8. Although this parameter has the same name as the
variable on line 3, this is a coincidence. The name could be anything. The exam will often
use the same name to try to confuse you. The variable on line 3 never changes because no
assignments are made to it.
Now that you’ve seen primitives, let’s try an example with a reference type. What do you
think is output by the following code?
) String name = "Webby"; speak(name); System.out.println(name); }public static void speak(String name) { name = "Sparky";}The correct answer is
. Just as in the primitive example, the variable assignment is
only to the method parameter and doesn’t affect the caller.
Notice how we keep talking about variable assignments. This is because we can call
methods on the parameters. As an example, we have code that calls a method on the
passed into the method:
) StringBuilder name = new StringBuilder(); speak(name); System.out.println(name); // Webby}public static void speak(StringBuilder s) { s.append("Webby");}In this case, the output is
because the method merely calls a method on the
parameter. It doesn’t reassign
name
to a different object. In Figure 4.4, you can see
how pass-by-value is still used.
is a copy of the variable
name
. Both point to the same
, which means that changes made to the
are available to
both references.
190
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 190
FIGURE 4.4
Copying a reference with pass-by-value
Pass-by-Value vs. Pass-by-Reference
Different languages handle parameters in different ways. Pass-by-value is used by many
languages, including Java. In this example, the swap method does not change the origi-
nal values. It only changes
and
within the method.
) int original1 = 1; int original2 = 2; swap(original1, original2); System.out.println(original1); // 1
System.out.println(original2); // 2
The other approach is pass-by-reference. It is used by default in a few languages, such as
Perl. We aren't going to show you Perl code here because you are studying for the Java
exam and we don't want to confuse you. The following example is in a made-up language
that shows pass-by-reference:
print(original1); // 2 (not in Java)
print(original2); // 1 (not in Java)
See the difference? In our made-up language, the caller is affected by variable assign-
ments made in the method.
Overloading Methods
191
c04.indd 1봀
4/2014 Page 191
To review, Java uses pass-by-value to get data into a method. Assigning a new primitive
or reference to a parameter doesn’t change the caller. Calling methods on a reference to an
object does affect the caller.
Getting data back from a method is easier. A copy is made of the primitive or reference
and returned from the method. Most of the time, this returned value is used. For example,
it might be stored in a variable. If the returned value is not used, the result is ignored.
Watch for this on the exam. Ignored returned values are tricky.
Let’s try an example. Pay attention to the return types.
192
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 192
only change was the type of the parameter. Overloading also allows different numbers
of parameters.
Everything other than the method signature can vary for overloaded methods. This
means there can be different access modi■
ers, speci■
ers (like static⤀, return types, and
exception lists.
These are all valid overloaded methods:
Overloading Methods
193
c04.indd 1봀
4/2014 Page 193
Trick question! Remember that Java treats varargs as if they were an array. This means
that the method signature is the same for both methods. Since we are not allowed to over-
load methods with the same parameter list, this code doesn't compile. Even though the code
doesn't look the same, it compiles to the same parameter list.
Now that weve just gotten through explaining that they are the same, it is time to men-
tion how they are not the same. It shouldn’t be a surprise that you can call either method by
passing an array:
)However, you can only call the varargs version with stand-alone parameters:
Obviously, this means they don't compile
exactly
the same. The parameter list is the
same, though, and that is what you need to know with respect to overloading for the exam.
Autoboxing
In the previous chapter, you saw how Java will convert a primitive
to an object
to add it to an
through the wonders of autoboxing. This works for code you
write too.
This means calling
will call the previous method as expected. However, what
happens if we have both a primitive and an integer version?
Java will match the
version. Java tries to use the most speci■
c parameter
list it ca渠■
nd. When the primitive
version isn't present, it will autobox. However, when
the primitive
version is provided, there is no reason for Java to do the extra work of
autoboxing.
Reference Types
Given the rule about Java picking the most speci■
c version of a method that it can, what do
you think this code outputs?
194
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 194
The answer is
. Th攠■
rst call is a
an搠■
nds a direct match.
There's no reason to use the
version when there is a nice
parameter list just
waiting to be called. The second call looks for an
parameter list. When it doesn'琠■
nd
one, it autoboxes to
. Since it still doesn't 
nd a match, it goes to the
one.
Primitives
Primitives work in a way similar to reference variables. Java tries to 
nd the most speci■
c
matching overloaded method. What do you think happens here?
) Plane p = new Plane(); p.fly(123); p.fly(123L); } }The answer is
. Th攠■
rst call passes an
and sees an exact match. The sec-
ond call passes a
and also sees an exact match. If we comment out the overloaded
method with the
parameter list, the output becomes
. Java has no problem
calling a larger primitive. However, it will not do so unless a better match is not found.
Note that Java can only accept wider types. An
can be passed to a method taking a
parameter. Java will not automatically convert to a narrower type. If you want to pass
to a method taking an
parameter, you have to add a cast to explicitly say nar-
rowing is okay.
Putting It All Together
So far, all the rules for when an overloaded method is called should be logical. Java calls
the most speci■
c method it can. When some of the types interact, the Java rules focus
on backward compatibility. In Java 1.4 and earlier, autoboxing and varargs didn’t exist.
Although that was a long time ago, old code still needs to work葷hich means autoboxing
and varargs come last when Java looks at overloaded methods. Ready for the of■
cial order?
Table 4.4 lays it out for you.
Overloading Methods
195
c04.indd 1봀
4/2014 Page 195
TABLE 4.4
Order Java uses to choose the right overloaded method
Example of what will be chosen for
Exact match by type
Larger primitive type
Autoboxed type
Varargs
Let’s give this a practice run using the rules in Table 4.4. What do you think this
outputs?
196
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 196
) play(4); // DOES NOT COMPILE play(4L); // calls the Long version } }Here we have a problem. Java is happy to convert the
4 or an
It cannot handle converting in two steps to a
and then to a
. If we had
, it would match because only one conversion would be
necessary: from
. An
is an
, as you’ll see in Chapter 5.
Creating Constructors
As you learned in Chapter 1, a constructor is a special method that matches the name of
the class and has no return type. He牥’s an example:
The name of the constructor,
, matches the name of the class,
, and there is
no return type, not even
. That makes this a constructor. Can you tell why these two
are not valid constructors for the
class?
Th攠■
rst one doesn't match the classname because Java is case sensitive. Since it doesn't
match, Java knows it can't be a constructor and is supposed to be a regular method.
However, it is missing the return type and doesn't compile. The second method is a per-
fectly good method, but is not a constructor because it has a return type.
Constructors are used when creating a new object. This process is called
instantiation
because it creates a new instance of the class. A constructor is called when we write
followed by the name of the class we want to instantiate. For example:
When Java sees the
keyword, it allocates memory for the new object. Java also looks
for a constructor and calls it.
A constructor is typically used to initialize instance variables. The
keyword tells
Java you want to reference an instance variable. Most of the time,
is optional. The
problem is that sometimes there are two variables with the same name. In a constructor,
one is a parameter and one is an instance variable. If you don’t say otherwise, Java gives
Creating Constructors
197
c04.indd 1봀
4/2014 Page 197
you the one with the most granular scope, which is the parameter. Using
tells
Java you want the instance variable.
He牥’s a common way of writing a constructor:
On line 4, we assign the parameter
to the instance variable
color
. The right
side of the assignment refers to the parameter because we don’t specify anything
special. The left side of the assignment uses
to tell Java we want it to use the
instance variable.
Now let's look at some examples that aren't common but that you might see on the
exam:
)11: Bunny b = new Bunny(1, 2);12: System.out.println(b.length + " " + b.height + " " + b.color);13: } }Line 6 is incorrect and you should watch for it on the exam. The instance variable
length
starts out with a 0 value. That 0 is assigned to the method parameter
length
. The
instance variable stays at 0. Line 7 is more straightforward. The parameter
theHeight
and
instance variable
height
have different names. Since there is no naming collision,
is
not required. Finally, line 8 shows that it is allowed to use
even when there is no dupli-
cation of variable names.
In this section, well look at default constructors, overloading constructors, 
nal ■
elds,
and the order of initialization in a class.
Default Constructor
Every class in Java has a constructor whether you code one or not. If you don’t include any
constructors in the class, Java will create one for you without any parameters.
198
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 198
This Java-created constructor is called the
default constructor
. Sometimes we call it the
default no-arguments constructor for clarity. He牥’s an example:
) Rabbit rabbit = new Rabbit(); // Calls default constructor }}In the
class, Java sees no constructor was coded and creates one. This default
constructor is equivalent to typing this:
The default constructor has an empty parameter list and an empty body. It is 
ne for you
to type this in yourself. However, since it doesn't do anything, Java is happy to supply it for
you and save you some typing.
We keep saying
generated
. This happens during the compile step. If you look at th攠■
le
with the
extension, the constructor will still be missing. It is only in the compiled 
le
with the
extension that it makes an appearance.
Remember that a default constructor is only supplied if there are no constructors
present. Which of these classes do you think has a default constructor?
Only
gets a default no-argument constructor. It doesn't have a constructor
coded so Java generates a default no-argument constructor.
and
both have
public constructors already.
has a private constructor. Since these three classes
have a constructor de■
ned, the default no-argument constructor is not inserted for you.
Let’s take a quick look at how to call these constructors:
Creating Constructors
199
c04.indd 1봀
4/2014 Page 199
Line 3 calls the generated default no-argument constructor. Lines 4 and 5 call the user-
provided constructors. Line 6 does not compile.
made the constructor private so
that other classes could not call it.
Having a private constructor in a class tells the compiler not to provide a default no-
argument constructor. It also prevents other classes from instantiating the class. This is
useful when a class only has static methods or the class wants to control all calls to create
new instances of itself.
Overloading Constructors
Up to now, you’ve only seen one constructor per class. You can have multiple constructors
in the same class as long as they have different method signatures. When overloading meth-
ods, the method name and parameter list needed to match. With constructors, the name is
always the same since it has to be the same as the name of the class. This means construc-
tors must have different parameters in order to be overloaded.
This example shows two constructors:
One of the constructors takes a single
parameter. The other takes an
and a
. These parameter lists are different, so the constructors are successfully overloaded.
There is a problem here, though. There is a bit of duplication. In programming, even a
bit of duplication tends to turn into a lot of duplication as we keep adding just one more
200
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 200
thing.踠What we really want is for th攠■
rst constructor to call the second constructor with
two parameters. You might be tempted to write this:
This will not work. Constructors can be called only by writing
before the name of the
constructor. They are not like normal methods that you can just call. What happens if we
stick
before the constructor name?
This attempt does compile. It doesn't do what we want, though. When the constructor
with one parameter is called, it creates an object with the default
and
. It then
constructs a different object with the desired
and
and ignores the new object.
That's not what we want. We want
and
set on the object we are trying to
instantiate in the 
rst place.
Java provides a solution:
—yes, the same keyword we used to refer to instance vari-
ables. When
is used as if it were a method, Java calls another constructor on the same
instance of the class.
Success! Now Java calls the constructor that takes two parameters.
and
get
set on this instance.
has one special rule you need to know. If you choose to call it, the
call
must be th攠■
rst noncommented statement in the constructor.
Even though a print statement on line 4 doesn't change any variables, it is still a Java state-
ment and is not allowed to be inserted before the call to
. The comment on line 5 is
just 
ne. Comments don't run Java statements and are allowed anywhere.
Creating Constructors
201
c04.indd 1봀
4/2014 Page 201
Constructor Chaining
Overloaded constructors often call each other. One common technique is to have each
constructor add one parameter until getting to the constructor that does all the work.
This approach is called
constructor chaining
. In this example, all three constructors are
chained.
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 202
Final Fields
As you saw earlier in the chapter,
instance variables must be assigned a value exactly
once. We saw this happen in the line of the declaration and in an instance initializer. There
is one more location this assignment can be done: in the constructor.
The constructor is part of the initialization process, so it is allowed to assign
instance variables in it. By the time the constructor completes, all
instance variables
must have been set.
Order of Initialization
Chapter 1 covered the order of initialization. Now that you’ve learned about static initializers,
it is time to revisit that. Unfortunately, you do have to memorize this list. We’ll give you lots of
practice, but you do need to know this order by heart.
If there is a superclass, initialize it first (w斐ll cover this rule in the next chapter. For
now, just sa礠贀no superclass踠and go on to the next rule.⤀
Static variable declarations and static initializers in the order they appear in the file.
Instance variable declarations and instance initializers in the order they appear in the file.
The constructor.
Let’s try th攠■
rst example:
Creating Constructors
203
c04.indd 1봀
4/2014 Page 203
The output is:
Let's look at why. Rule 1 doesn't apply because there is no superclass. Rule 2 says to run
the
variable declarations and
initializers—in this case, lines 5 and 6, which
output
and
. Rule 3 says to run the instance variable declarations and instance initial-
izers—here, lines 2 and 3, which output
. Finally, rule 4 says to run the construc-
tor—here, lines 7–9, which output
The next example is a little harder. Keep in mind that the four rules apply only if an
object is instantiated. If the class is referred to without a
call, only rules 1 and 2 apply.
The other two rules relate to instances and constructors. They have to wait until there is
code to instantiate the object.
What do you think happens here?
)11: System.out.println("read to construct");12: new InitializationOrder();13: }14: }The output looks like this:
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 204
Again, rule 1 doesn’t apply because there is no superclass. Rule 2 tells us to look at the
variables and
initializers—lines 4 and 5, in that order. Line 5 outputs
Now that the statics are out of the way, the
method can run. Next, we can use rule
3 to run the instance variables and instance initializers. Here that is lines 2 and 3, which
output
. Finally, rule 4 says to run the constructor—in this case, lines 7–9, which
output
We are going to try one more example. This one is as hard as it gets. If you understand
the output of this next one, congratulations on a job well done; if not, don’t worry. Write
some programs to play with this. Try typing in the examples in this section and making
minor changes to see what happens. For example, you might try commenting out part of
the code. This will give you a better feel for what is going on. Then come back and reread
this section to try the examples.
Ready for the tough example? Here it is:
Encapsulating Data
c04.indd 1봀
4/2014 Page 205
Encapsulating Data
In Chapter 1, we had an example of a class with a 
eld that wasn’t private:
Why do we care? Since there is default (package private⤀ access, that means any class
in the package can set
numberEggs
. We no longer have control of what gets set in our own
class. A caller could even write this:
This is clearly no good. We do not want the mother
to have a negative number of
eggs!
Encapsulation
to the rescue. Encapsulation means we set up the class so only methods
in the class with the variables can refer to the instance variables. Callers are required to use
these methods. Let’s take a look at our newly encapsulated
class:
206
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 206
TABLE 4.5
Rules for JavaBeans naming conventions
Example
Properties are private.
Getter methods begin with
if the
property is a
Encapsulating Data
207
c04.indd 1봀
4/2014 Page 207
Creating Immutable Classes
Encapsulating data is helpful because it prevents callers from making uncontrolled changes
to your class. Another common technique is making classes immutable so they cannot be
changed at all.
Immutable classes are helpful because you know they will always be the same. You can
pass them around your application with a guarantee that the caller didn’t change anything.
This helps make programs easier to maintain. It also helps with performance by limiting
the number of copies, as you saw with
in Chapter 3,₍Core Java APIs.踀
One step in making a class immutable is to omit the setters. But wait: we still want the
caller to be able to specify the initial value—we just don’t want it to change after the object
is created. Constructors to the rescue!
continues
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 208
continued
Writing Simple Lambdas
209
c04.indd 1봀
4/2014 Page 209
anonymous method. It has parameters and a body just like full-.
edged methods do, but it
doesn’t have a name like a real method. Lambda expressions are often referred to as lamb-
das for short. You might also know them as closures if Java isn’t your 
rst language. If you
had a bad experience with closures in the past, don’t worry. They are far simpler in Java.
In other words, a lambda expression is like a method that you can pass as if it were a
variable. For example, there are different ways to calculate age. One human year is equiva-
lent to seven dog years. You want to write a method that that takes an
method as
input. To do this in an object-oriented program, you’d need to de■
ne a
subclass and a
subclass. With lambdas, you can just pass in the relevant expression to calculate age.
Lambdas allow you to write powerful code in Java. Only the simplest lambda expres-
sions are on the OCA exam. The goal is to get you comfortable with the syntax and the
concepts. This means you aren’t truly doing functional programming yet. You’ll see
lambdas again on the OCP exam.
In this section, well cover an example of why lambdas are helpful, the syntax of
lambdas, and how to use predicates.
Lambda Example
Our goal is to print out all the animals in a list according to some criteria. We’ll show you
how to do this without lambdas to illustrate how lambdas are useful. We start out with the
class:
210
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 210
Th攠■
rst thing we want to check is whether the
can hop. We provide
a class that can check this:
Writing Simple Lambdas
211
c04.indd 1봀
4/2014 Page 211
Don’t worry that the syntax looks a little funky. You’ll get used to it and well describe it
in the next section. We’ll also explain the bits that look like magic. For now, just focus on
how easy it is to read. We are telling Java that we only care about
s that can hop.
It doesn’t take much imagination to 
gure how we would add logic to get the
that can swim. We only have to add one line of code—no need for an extra class to do
something simple. He牥’s that other line:
How about
s that cannot swim?
The point here is that it is really easy to write code that uses lambdas once you get the
basics in place. This code uses a concept called deferred execution.
Deferred execution
means that code is speci■
ed now but will run later. In this case, later is when the
method calls it.
Lambda Syntax
One of the simplest lambda expressions you can write is the one you just saw:
This means that Java should call a method with an
parameter that returns a
value that’s the result of
. We know all this because we wrote the code.
But how does Java know?
Java replies on context when 
guring out what lambda expressions mean. We are pass-
ing this lambda as the second parameter of the
method. That method expects a
as the second parameter. Since we are passing a lambda instead, Java tries to
map our lambda to that interface:
Since that interfac斐s method takes an
, that means the lambda parameter has to
be an
. And since that interfac斐s method returns a
, we know the lambda
returns a
The syntax of lambdas is tricky because many parts are optional. These two lines do the
exact same thing:
212
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 212
FIGURE 4.5
Lambda syntax omitting optional parts
The second example also has three parts; it’s just more verbose (see
Figure 4.6):
Specify a single parameter with the name
and stating the type is
The arrow operator to separate the parameter and body
A body that has one or more lines of code, including a semicolon and a return statement
FIGURE 4.6
Lambda syntax, including optional parts
The parentheses can only be omitted if there is a single parameter and its type is not
explicitly stated. Java does this because developers commonly use lambda expressions this
way and they can do as little typing as possible.
It shouldn’t be news to you that we can omit braces when we only have a single state-
ment. We did this with
statements and loops already. What is different here is that the
rules change when you omit the braces. Java doesn’t require you to type
Writing Simple Lambdas
213
c04.indd 1봀
4/2014 Page 213
Notice that all of these examples have parentheses around the parameter list except the
one that takes only one parameter and doesn’t specify the type. Line 3 takes 0 parameters
and always returns the Boolean
. Line 4 takes one parameter and calls a method on
it, returning the result. Line 5 does the same except that it explicitly de■
nes the type of the
variable. Lines 6 and 7 take two parameters and ignore one of them—there isn’t a rule that
says you must use all de■
ned parameters.
Now let’s make sure you can identify invalid syntax. Do you see what’s wrong with each
of these?
214
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 214
Predicates
In our earlier example, we created an interface with one method:
Lambdas work with interfaces that have only one method. These are called functional
interfaces—interfaces that can be used with functional programming. (It’s actually more
complicated than this, but for the OCA exam this de■
nition is 
ne.⤀
You can imagine that wed have to create lots of interfaces like this to use lambdas. We
want to test
s and
s and
s and anything else that we come across.
Luckily, Java recognizes that this is a common problem and provides such an interface
for us. It’s in the package
and the gist of it is as follows:
That looks a lot like our method. The only difference is that it uses this type
instead of
. That’s the syntax for generics. It’s like when we created an
and got to
specify any type that goes in it.
This means we don’t need our own interface anymore and can put everything
related to our search in one class:
) nim; l00; nim; l00;5: ListAnimal animals = new ArrayListAnimal();6: animals.add(new Animal("fish", false, true));7: nim; l00;8: print(animals, a - a.canHop());9: }10: nim; l00; nim; l00;private static void print(ListAnimal animals, PredicateAnimal■checker) {11: for (Animal animal : animals) {12: if (checker.test(animal))13: System.out.print(animal + " ");14: }15: System.out.println();16: }17: }This time, line 10 is the only one that changed. We expect to have a
passed in that uses type
. Pretty cool. We can just use it with-
out having to write extra code.
Summary
215
c04.indd 1봀
4/2014 Page 215
Java 8 even integrated the
interface into some existing classes. There is only
one you need to know for the exam.
declares a
method that takes a
. Imagine we have a list of names for pet bunnies. We decide we want to remove
all of the bunny names that don’t begin with the letter h because our little cousin really
wants us to choose an H name. We could solve this problem by writing a loop. Or we could
solve it in one line:
�8: bunnies.removeIf(s - s.charAt(0) != 'h');9: System.out.println(bunnies); // [hoppy]Line 8 takes care of everything for us. It de■
nes a predicate that takes a
and
returns a
. The
method does the rest.
For the OCA exam, you only need to know how to implement lambda expressions that
use the
interface. Remember the one method in the interface called
takes any one reference type parameter and returns a
. Functional programming
is a large topic and just the basics are covered. On the OCP exam, you’ll learn how to get
rid of the loop entirely for more than just
. You’ll also learn the rules for imple-
menting your own functional interfaces as we did with
Summary
As you learned in this chapter, Java methods start with an access modi■
er of
or blank (default access⤀. This is followed by an optional speci■
er such
as
. Next comes the return type, which is
or a Java type.
The method name follows, using standard Java identi■
er rules. Zero or more parameters go
in parentheses as the parameter list. Next come any optional exception types. Finally, zero
or more statements go in braces to make up the method body.
Using the
keyword means the code is only available from within the same class.
Default (package private⤀ access means the code is only available from within the same
package. Using the
keyword means the code is available from the same package
or subclasses. Using the
keyword means the code is available from anywhere. Static
methods and static variables are shared by the class. When referenced from outside the
class, they are called using the classname—for example,
216
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 216
Calling methods on objects that are method parameters changes the state of those objects and
is re.
ected in the caller.
Overloaded methods are methods with the same name but a different parameter list.
Java calls the most speci■
c method it ca渠■
nd. Exact matches are preferred, followed by
wider primitives. After that comes autoboxing an搠■
nally varargs.
Constructors are used to instantiate new objects. The default no-argument constructor
is called when no constructor is coded. Multiple constructors are allowed and can call each
other by writing
. If
is present, it must be th攠■
rst statement in the constructor.
Constructors can refer to instance variables by writing
before a variable name to indi-
cate they want the instance variable and not the method parameter with that name. The order
of initialization is the superclass (which we will cover in Chapter 5⤀; static variables and static
initializers in the order they appear; instance variables and instance initializers in the order
they appear; an搠■
nally the constructor.
Encapsulation refers to preventing callers from changing the instance variables directly.
This is done by making instance variables private and getters/setters public. Immutability
refers to preventing callers from changing the instance variables at all. This uses several
techniques, including removing setters. JavaBeans use methods beginning with
and
Exam Essentials
217
c04.indd 1봀
4/2014 Page 217
Recognize the correct overloaded method. Exact matches are used 
rst, followed by wider
primitives, followed by autoboxing, followed by varargs. Assigning new values to method
parameters does not change the caller, but calling methods on them does.
Evaluate code involving constructors.
Constructors can call other constructors by call-
ing
as th攠■
rst line of the constructor. Recognize when the default constructor is
provided. Remember the order of initialization is the superclass, static variables/initializers,
instance variables/initializers, and the constructor.
Be able to recognize when a class is properly encapsulated.
Look for
instance
variables and
getters and setters when identifying encapsulation.
Write simple lambda expressions.
Look for the presence or absence of optional elements
in lambda code. Parameter types are optional. Braces and the
218
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 218
Review Questions
Which of the following can fill in the blank in this code to make it compile? (Choose all
that apply⤀
Review Questions
219
c04.indd 1봀
4/2014 Page 219
Given the following method, which of the method calls return
? (Choose all that apply⤀
Which of the following are true? (Choose all that apply⤀
Package private access is more lenient than protected access.
A
class that has private fields and package private methods is not visible to
classes outside the package.
You can use access modifiers so only some of the classes in a package see a particular
package private class.
You can use access modifiers to allow read access to all methods, but not any instance
variables.
You can use access modifiers to restrict read access to all classes that begin with the
word
Given the following
and
class definitions, which
line numbers in
generate a compiler error? (Choose all that apply⤀
220
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 220
None, the code compiles fine.
Line 5
Line 6
Line 7
Line 8
Line 9
Which of the following are true? (Choose all that apply⤀
Encapsulation uses package private instance variables.
Encapsulation uses private instance variables.
Encapsulation allows setters.
Immutability uses package private instance variables.
Immutability uses private instance variables.
Immutability allows setters.
Which are methods using JavaBeans naming conventions for accessors and mutators?
⠀Choose all that apply⤀
Review Questions
221
c04.indd 1봀
4/2014 Page 221
)5: Rope.swing();6: new Rope().swing();7: System.out.println(LENGTH);8: } 9: }A. swing swing 5B. swing swing 10C. Compiler error on line 2 of
Compiler error on line 5 of
Compiler error on line 6 of
Compiler error on line 7 of
11.
Which are true of the following code? (Choose all that apply⤀
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 222
The code compiles as is.
There is exactly one compiler error in the code.
There are exactly two compiler errors in the code.
If the lines with compiler errors are removed, the output is
If the lines with compiler errors are removed, the output is
If the lines with compile errors are removed, the code throws a
12.
What is the output of the following code?
) rope1.length = 2; rope2.length = 8; System.out.println(rope1.length); }}package rope;public class Rope { public static int length = 0;}A. 02B. 08C. 2D. 8E. The code does not compile.
An exception is thrown.
13.
How many compiler errors are in the following code?
Review Questions
c04.indd 1봀
4/2014 Page 223
14.
Which of the following can replace line 2 to make this code compile? (Choose
all that apply⤀
224
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 224
)15: Test t = new Test();16: short s = 123;17: t.print(s);18: t.print(true);19: t.print(6.789);20: }21: }A. bytefloatObjectB. intfloatObjectC. byteObjectfloatD. intObjectfloatE. intObjectObjectF. byteObjectObject16.
What is the result of the following program?
Review Questions
225
c04.indd 1봀
4/2014 Page 225
17.
Which of the following are output by the following code? (Choose all that apply⤀
226
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 226
20.
Which code can be inserted to have the code print
) BirdSeed seed = new BirdSeed(); System.out.println(seed.numberBags); } }A. Replace line 1 with
Replace line 2 with
Replace line 1 with
Replace line 2 with
Replace line 1 with
Replace line 2 with
21.
Which of the following complete the constructor so that this code prints out
? (Choose
all that apply⤀
Review Questions
227
c04.indd 1봀
4/2014 Page 227
None of the above.
22.
What is the result of the following?
)3: System.out.print(Order.result + " ");4: System.out.print(Order.result + " ");5: new Order();6: new Order();7: System.out.print(Order.result + " ");8: }9: }A. cururB. ucrcrC. u ucrcrD. u u curcurE. u u ucrcrF. ur ur urcG. The code does not compile.
23.
What is the result of the following?
228
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 228
)12: Order order = new Order("f");13: order = new Order();14: System.out.println(order.value);15: } }A. tacbB. tacfC. tacbfD. tacfbE. tacftacbF. The code does not compile.
An exception is thrown.
Which of the following will compile when inserted in the following code? (Choose
all that apply⤀
Review Questions
229
c04.indd 1봀
4/2014 Page 229
25.
Which of the following are true about the following code? (Choose all that apply⤀
) new Create(100); new Create(1000L); }}A. The code prints out
The code prints out
The code prints out
The code prints out
The code prints
if you remove the constructor
The code prints
if you remove the constructor
The code prints
if you remove the constructor
What is the result of the following class?
Chapter 4
Methods and Encapsulation
c04.indd 1봀
4/2014 Page 230
Compiler error on line 8.
Compiler error on line 10.
Compiler error on line 11.
A runtime exception is thrown.
27.
What is the result of the following code?
)�7: check((h, l) - h.append(l).isEmpty(), 5);8: }9: private static void check(Climb climb, int height) {10: if (climb.isTooHigh(height, 10)) 11: System.out.println("too high");12: else 13: System.out.println("ok");14: }15: }A. okB. too highC. Compiler error on line 7.
Compiler error on line 10.
Compiler error on a different line.
A runtime exception is thrown.
Which of the following lambda expressions can fill in the blank? (Choose all that apply⤀
Review Questions
231
c04.indd 1봀
4/2014 Page 231
c05.indd 1봀
4/2014 Page 233
Chapter
Class Design
OCA EXAM OBJECTIVES COVERED IN THIS
CHAPTER:
Working with Inheritance
Describe inheritance and its benefits
Develop code that demonstrates the use of polymorphism;
including overriding and object type versus reference type
Determine when casting is necessary
Use super and this to access objects and constructors
Use abstract classes and interfaces
c05.indd 1봀
4/2014 Page 234
In Chapter 1,₍Java Building Blocks,踀 we introduced the
basic de■
nition for a class in Java. In Chapter 4,₍Methods
and Encapsulation,Ž we delved into constructors, methods,
and modi■
ers, and showed how you can use them to build more structured classes. In this
chapter, well take things one step further and show how class structure is one of the most
powerful features in the Java language.
At its core, proper Java class design is about code reusability, increased functionality,
and standardization. For example, by creating a new class that extends an existing class,
you may gain access to a slew of inherited primitives, objects, and methods. Alternatively,
by designing a standard interface for your application, you ensure that any class that imple-
ments the interface has certain required methods de■
ned. Finally, by creating abstract class
de■
nitions, you’re de■
ning a platform that other developers can extend and build on top of.
Introducing Class Inheritance
When creating a new class in Java, you can de■
ne the class to inherit from an existing class.
Inheritance
is the process by which the new child subclass automatically includes any
primitives, objects, or methods de■
ned in the parent class.
For illustrative purposes, we refer to any class that inherits from another class as a
child
class
, or a descendent of that class. Alternatively, we refer to the class that the child inherits
from as the
parent class
, or an ancestor of the class. If child X inherits from class Y, which
in turn inherits from class Z, then X would be considered an indirect child, or descendent,
of class Z.
Java supports
single inheritance
, by which a class may inherit from only one direct par-
ent class. Java also supports multiple levels of inheritance, by which one class may extend
another class, which in turn extends another class. You can extend a class any number of
times, allowing each descendent to gain access to its ancestor’s members.
To truly understand single inheritance, it may helpful to contrast it with
multiple inheri-
tance
, by which a class may have multiple direct parents. By design, Java doesn’t support
multiple inheritance in the language because studies have shown that multiple inheritance
can lead to complex, often dif■
cult-to-maintain code. Java does allow one exception to the
single inheritance rule: classes may implement multiple interfaces, as you’ll see later in this
chapter.
Figure 5.1 illustrates the various types of inheritance models. The items on the left are
considered single inheritance because each child has exactly one parent. You may notice
that single inheritance doesn’t preclude parents from having multiple children. The right
Introducing Class Inheritance
235
c05.indd 1봀
4/2014 Page 235
side shows items that have multiple inheritance. For example, a dog object has multiple par-
ent designations. Part of what makes multiple inheritance complicated is determining which
parent to inherit values from in case of a con.
ict. For example, if you have an object or
method de■
ned in all of the parents, which one does the child inherit? There is no natural
ordering for parents in this example, which is why Java avoids these issues by disallowing
multiple inheritance altogether.
FIGURE 5.1
Types of inheritance
It is possible in Java to prevent a class from being extended by marking the class with
the
modi■
er. If you try to de■
ne a class that inherits from a
class, the compiler
will throw an error and not compile. Unless otherwise speci■
ed, throughout this chapter
you can assume the classes we work with are not marked as
Extending a Class
In Java, you can extend a class by adding the parent class name in the de■
nition using the
keyword. The syntax of de■
ning and extending a class is shown in Figure 5.2.
FIGURE 5.2
Defining and extending a class
We’ll discuss what it means for a class to be
and
, as well as the class
access modi■
ers, later in this chapter.
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 236
Because Java allows only one
class pe爠■
le, we can create tw漠■
les,
and
, in which the
class extends the
class. Assuming they are in the
same package, an
statement is not required in
to access the
class.
Here are the contents of
Introducing Class Inheritance
237
c05.indd 1봀
4/2014 Page 237
Applying Class Access Modifiers
As discussed in Chapter 4, you can apply access modi■
ers ⠀
default⤀ to both class methods and variables. It probably comes as no surprise that you can
also apply access modi■
ers to class de■
nitions, since we have been adding the
access
modi■
er to nearly every class up to now.
For the OCA exam, you should only be familiar with
and default
package-level class access modifiers, because these are the only ones that
can be applied to top-level classes within a Java file. The
and
modifiers can only be applied to inner classes, which are classes
that are defined within other classes, but this is well out of scope for the
OCA exam.
The
access modi■
er applied to a class indicates that it can be referenced and used
in any class. The default package private modi■
er, which is the lack of any access modi■
er,
indicates the class can be accessed only by a subclass or class within the same package.
As you know, a Java 
le can have many classes but at most one
class. In fact, it
may have no
class at all. One feature of using the default package private modi■
is that you can de■
ne many classes within the same Java 
le. For example, the following
de■
nition could appear in a single Java 
le named
, since it contains only
class:
If we were to update the
class with the
access modi■
er, the
le would not compile unless the
class was moved to its own
le.
The rules for applying class access modi■
ers are identical for interfaces. There can be at
most one
class or interface in a Java 
le. Like classes, top-level interfaces can also
be declared with the
or default modi■
ers. We’ll discuss interfaces in detail later in
this chapter.
For simplicity, any time you see multiple
classes or interfaces
defined in the same code block in this chapter, assume each class is
defined in its own Java file.
Creating Java Objects
Throughout our discussion of Java in this book, we have thrown around the word
object
numerous times—and with good reason. In Java, all classes inherit from a single class,
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 238
. Furthermore,
is the only class that doesn’t have any
parent classes.
You might be wondering,₍None of the classes I’ve written so far extend
, so how do all classes inherit from it?踀 The answer is that the compiler has been
automatically inserting code into any class you write that doesn’t extend a speci■
c class.
For example, consider the following two equivalent class de■
nitions:
The key is that when Java sees you de■
ne a class that doesn’t extend another class, it
immediately adds the syntax
to the class de■
nition.
If you de■
ne a new class that extends an existing class, Java doesn’t add this syntax,
although the new class still inherits from
. Since all classes inherit from
, extending an existing class means the child automatically inherits from
by construction. This means that if you look at the inheritance structure
of any class, it will always end with
on the top of the tree, as shown in
Figure 5.3.
FIGURE 5.3
Java object inheritance
Defining Constructors
As you may recall from Chapter 4, every class has at least one constructor. In the case that
no constructor is declared, the compiler will automatically insert a default no-argument
constructor. In the case of extending a class, though, things are a bit more interesting.
In Java, th攠■
rst statement of every constructor is either a call to another constructor
within the class, using
, or a call to a constructor in the direct parent class, using
Introducing Class Inheritance
239
c05.indd 1봀
4/2014 Page 239
. If a parent constructor takes arguments, the super constructor would also take
arguments. For simplicity in this section, we refer to the
command as any par-
ent constructor, even those that take an argument. Notice the user of both
and
in the following example:
In th攠■
rst class,
, th攠■
rst statement of the constructor is a call to the parent
constructor de■
ned in
, which takes no arguments. In the second class,
, th攠■
rst statement of th攠■
rst constructor is a call to
’s constructor, which
takes a single argument. The class
also includes a second no-argument construc-
tor that doesn’t call
but instead calls the other constructor within the
class
using
Like the
command that you saw in Chapter 4, the
command may only
be used as th攠■
rst statement of the constructor. For example, the following two class de■
nitions will not compile:
240
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 240
Th攠■
rst class will not compile because the call to the parent constructor must be the
rst statement of the constructor, not the second statement. In the second code snippet,
is th攠■
rst statement of the constructor, but it also used as the third statement.
Since
can only be used as th攠■
rst statement of the constructor, the code will like-
wise not compile.
If the parent class has more than one constructor, the child class may use any valid
parent constructor in its de■
nition, as shown in the following example:
In this example, th攠■
rst child constructor takes one argument,
, and calls the par-
ent constructor, which takes two arguments,
and
. The second child constructor
takes no arguments, and it calls the parent constructor, which takes one argument,
In this example, notice that the child constructors are not required to call matching parent
constructors. Any valid parent constructor is acceptable as long as the appropriate input
parameters to the parent constructor are provided.
Introducing Class Inheritance
241
c05.indd 1봀
4/2014 Page 241
Understanding Compiler Enhancements
Up to now, we de■
ned numerous classes that did not explicitly call the parent construc-
tor via the
keyword, so why did the code compile? The answer is that the Java
compiler automatically inserts a call to the no-argument constructor
if th攠■
rst
statement is not a call to the parent constructor. For example, the following three class
and constructor de■
nitions are equivalent, because the compiler will automatically convert
them all to the last example:
Make sure you understand the differences between these three
class de■
nitions
and why Java will automatically convert them all to the last de■
nition. Keep the process the
Java compile performs in mind as we discuss the next few examples.
What happens if the parent class doesn’t have a no-argument constructor? Recall that
the no-argument constructor is not required and only inserted if there is no constructor
de■
ned in the class. In this case, the Java compiler will not help and you must create at least
one constructor in your child class that explicitly calls a parent constructor via the
command. For example, the following code will not compile:
In this example no constructor is de■
ned within the
class, so the compiler tries
to insert a default no-argument constructor with a
call, as it did in the
example. The compiler stops, though, when it realizes there is no parent constructor that
takes no arguments. In this example, we must explicitly de■
ne at least one constructor, as
in the following code:
242
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 242
This code still doesn’t compile, though, because the compiler tries to insert the no-
argument
as th攠■
rst statement of the constructor in the
class, and there
is no such constructor in the parent class. We ca渠■
x this, though, by adding a call to a par-
ent constructor that takes a 
xed argument:
This code will compile because we have added a constructor with an explicit call to a
parent constructor. Note that the class
now has a no-argument constructor even
though its parent class
doesn’t. Subclasses may de■
ne no-argument constructors
even if their parent classes do not, provided the constructor of the child maps to a parent
constructor via an explicit call of the
command.
You should be wary of any exam question in which the parent class de■
nes a constructor
that takes arguments and doesn’t de■
ne a no-argument constructor. Be sure to check that
the code compiles before answering a question about it.
Reviewing Constructor Rules
Let’s review the rules we covered in this section.
Constructor De“
nition Rules:
The first statement of every constructor is a call to another constructor within the class
using
, or a call to a constructor in the direct parent class using
The
call may not be used after the first statement of the constructor.
Introducing Class Inheritance
243
c05.indd 1봀
4/2014 Page 243
If no
call is declared in a constructor, Java will insert a no-argument
as the first statement of the constructor.
If the parent doesn’t have a no-argument constructor and the child doesn’t define any
constructors, the compiler will throw an error and try to insert a default no-argument
constructor into the child class.
If the parent doesn’t have a no-argument constructor, the compiler requires an explicit
call to a parent constructor in each child constructor.
Make sure you understand these rules; the exam will often provide code that breaks one
or many of these rules and therefore doesn’t compile.
Calling Constructors
Now that we have covered how to de■
ne a valid constructor, well show you how Java calls
the constructors. In Java, the parent constructor is always executed before the child con-
structor. For example, try to determine what the following code outputs:
) new Chimpanzee(); }}The compiler 
rst inserts the
command as th攠■
rst statement of both the
and
constructors. Next, the compiler inserts a default no-argument construc-
tor in the
class with
as th攠■
rst statement of the constructor. The code
will execute with the parent constructors called 
rst and yields the following output:
244
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 244
The exam creators are fond of questions similar to the previous one that try to get
you to determine the output of statements involving constructors. Just remember to
贀think like the compiler踠as much as possible and insert the missing constructors or
statements as needed.
Calling Inherited Class Members
Java classes may use any
member of the parent class, including meth-
ods, primitives, or object references. If the parent class and child class are part of the same
package, the child class may also use any default members de■
ned in the parent class.
Finally, a child class may never access a
member of the parent class, at least not
through any direct reference. As you saw in th攠■
rst example in this chapter, a
member
may be accessed indirectly via a
method.
To reference a member in a parent class, you can just call it directly, as in the following
example with the output function
Introducing Class Inheritance
245
c05.indd 1봀
4/2014 Page 245
246
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 246
super⠀⤀
vs.
super
As discussed in Chapter 4,
and
are unrelated in Java. Likewise,
and
are quite different but may be used in the same methods on the exam. Th攠fi
rst,
, is a statement that explicitly calls a parent constructor and may only be used in
th攠fi
rst line of a constructor of a child class. The second,
, is a keyword used to ref-
erence a member defi
ned in a parent class and may be used throughout the child class.
The exam may try to trick you by using both
and
in a constructor. For
example, consider the following code:
Introducing Class Inheritance
247
c05.indd 1봀
4/2014 Page 247
248
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 248
The method in the child class must be at least as accessible or more accessible than the
method in the parent class.
The method in the child class may not throw a checked exception that is new or
broader than the class of any exception thrown in the parent class method.
If the method returns a value, it must be the same or a subclass of the method in the
parent class, known as
covariant return types
Th攠■
rst rule of overriding a method is somewhat self-explanatory. If two methods have
the same name but different signatures, the methods are overloaded, not overridden. As you
may recall from our discussion of overloaded methods in Chapter 4, the methods are unre-
lated to each other and do not share any properties.
Overloading vs. Overriding
Overloading a method and overriding a method are similar in that they both involve
ning a method using the same name. They differ in that an overloaded method will
use a different signature than an overridden method. This distinction allows overloaded
methods a great deal more freedom in syntax than an overridden method would have.
For example, take a look at the following code sample:
Introducing Class Inheritance
249
c05.indd 1봀
4/2014 Page 249
Th攠fi
rst method,
, is overloaded in the subclass
, since the signature changes
from a no-argument constructor to a constructor with one
argument. Because the
method is being overloaded and not overridden, the return type can be changed from
to
without issue.
The second method,
, is overridden in the subclass
, since the signature is the
same as it is in the parent class
—they both take a single argument
. Because the
method is being overridden, the return type of the method in
must be a subclass of
the return type of the method in
. In this example, the return type
is not a sub-
class of
; therefore, the compiler will throw an exception on this method defi
nition.
Any time you see a method on the exam with the same name as a method in the parent
class, determine whether the method is being overloaded or overriddenₓ
rst; doing so
will help you with questions about whether the code will compile.
Let’s review some examples of the last three rules of overriding methods so you can
learn to spot the issues when they arise:
250
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 250
Introducing Class Inheritance
251
c05.indd 1봀
4/2014 Page 251
252
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 252
Introducing Class Inheritance
253
c05.indd 1봀
4/2014 Page 253
) Panda.eat(); }}In this example, the code compiles and runs without issue. The
method in the
child class hides the
method in the parent class. Because they are both marked as
, this is not considered an overridden method. Let’s contrast this with examples that
violate th攠■
fth rule:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 254
As you saw in the previous example, hiding static methods is fraught
with pitfalls and potential problems and as a practice should be avoided.
Though you might see questions on the exam that contain hidden static
methods that are syntactically correct, avoid hiding static methods in your
own work, since it tends to lead to confusing and difficult-to-read code.
You should not reuse the name of a static method in your class if it is
already used in the parent class.
Overriding vs. Hiding Methods
In our description of hiding of static methods, we indicated there was a distinction between
overriding and hiding methods. Unlike overriding a method, in which a child method
replaces the parent method in calls de■
ned in both the parent and child, hidden methods
only replace parent methods in the calls de■
ned in the child class.
At runtime the child version of an overridden method is always executed for an instance
regardless of whether the method call is de■
ned in a parent or child class method. In this
manner, the parent method is never used unless an explicit call to the parent method is
referenced, using the syntax
ParentClassName■method⠀⤀
. Alternatively, at runtime the par-
ent version of a hidden method is always executed if the call to the method is de■
ned in the
parent class. Let’s take a look at an example:
Introducing Class Inheritance
c05.indd 1봀
4/2014 Page 255
In this example, the code compiles and runs without issue, outputting the following:
Notice that
returns
in the parent class and
in the child class.
In th攠■
rst method call, the parent method
256
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 256
Creating
final
methods
We conclude our discussion of method inheritance with a somewhat self-explanatory
rule:
methods cannot be overridden. If you recall our discussion of modi■
ers from
Chapter 4, you can create a method with the
keyword. By doing so, though, you for-
bid a child class from overriding this method. This rule is in place both when you override
a method and when you hide a method. In other words, you cannot hide a static method in
a parent class if it is marked as
Let’s take a look at an example:
Introducing Class Inheritance
257
c05.indd 1봀
4/2014 Page 257
Inheriting Variables
As you saw with method overriding, there were a lot of rules when two methods have the
same signature and are de■
ned in both the parent and child classes. Luckily, the rules for
variables with the same name in the parent and child classes are a lot simpler, because Java
doesn’t allow variables to be overridden but instead hidden.
Hiding Variables
When you hide a variable, you de■
ne a variable with the same name as a variable in a par-
ent class. This creates two copies of the variable within an instance of the child class: one
instance de■
ned for the parent reference and another de■
ned for the child reference.
As when hiding a static method, you can’t override a variable; you can only hide it. Also
similar to hiding a static method, the rules for accessing the parent and child variables are
quite similar. If you’re referencing the variable from within the parent class, the variable
de■
ned in the parent class is used. Alternatively, if you’re referencing the variable from
within a child class, the variable de■
ned in the child class is used. Likewise, you can refer-
ence the parent value of the variable with an explicit use of the
keyword. Consider
the following example:
258
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 258
Notice that the instance of
contains two copies of the
variables: one
de■
ned in the parent and one de■
ned in the child. These instances are kept separate from
each other, allowing our instance of
to reference both
values indepen-
dently. In th攠■
rst method call,
Creating Abstract Classes
c05.indd 1봀
4/2014 Page 259
Notice the same type of object was created twice, but the reference to the object deter-
mines which value is seen as output. If the object
was passed to a method by
an
reference, as you’ll see in the sectio渠贀Understanding Polymorphism,踀 later in
this chapter, the wrong value might be used.
Hiding variables makes the code very confusing and diffi
cult to read, especially if you
start modifying the value of the variable in both the parent and child methods, since it
may not be clear which variable you’re updating.
When defi
ning a new variable in a child class, it is considered good coding practice to
select a name for the variable that is not already a
, or default variable
in use in a parent class. Hiding
variables is considered less problematic because
the child class did not have access to the variable in the parent class to begin with.
Creating Abstract Classes
Let’s say you want to de■
ne a parent class that other developers are going to subclass. Your
goal is to provide some reusable variables and methods to developers in the parent class,
whereas the developers provide speci■
c implementations or overrides of other methods in
the child classes. Furthermore, let’s say you also don’t want an instance of the parent class
to be instantiated unless it is an instance of the child class.
For example, you might de■
ne an
parent class that a number of classes extend
from and use but for which an instance of
itself cannot be instantiated. All sub-
classes of the
class, such as
, are required to implement a
260
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 260
Creating Abstract Classes
261
c05.indd 1봀
4/2014 Page 261
The 
rst method,
, doesn’t compile because two brackets are provided instead of
a semicolon, and Java interprets this as providing a body to an abstract method. The second
method,
262
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 262
In this example, the abstract method
de■
ned in the parent class
is not vis-
ible to the subclass
. Even though
does provide an implemen-
tation, it is not considered an override of the abstract method since the abstract method is
unreachable. The compiler recognizes this in the parent class and throws an exception as
soon as
and
are applied to the same method.
If we changed the access modi■
ed from
in the parent class
would the code compile? Let’s take a look:
In this modi■
ed example, the code will still not compile but for a completely differ-
ent reason. If you remember the rules earlier in this chapter for overriding a method, the
subclass cannot reduce the visibility of the parent method,
. Because the method is
declared
in the parent class, it must be marked as
in the
child class. Even with abstract methods, the rules for overriding methods must be followed.
Creating a Concrete Class
When working with abstract classes, it is important to remember that by themselves, they
cannot be instantiated and therefore do not do much other than de■
ne static variables and
methods. For example, the following code will not compile as it is an attempt to instantiate
an abstract class.
) final Eel eel = new Eel(); // DOES NOT COMPILE }}An abstract class becomes useful when it is extended by a concrete subclass. A
concrete
class
is th攠■
rst nonabstract subclass that extends an abstract class and is required to imple-
ment all inherited abstract methods. When you see a concrete class extending an abstract
class on the exam, check that it implements all of the required abstract methods. Let’s
review this with the following example.
Creating Abstract Classes
263
c05.indd 1봀
4/2014 Page 263
First, note that
is marked as
and
is not. In this example,
is considered th攠■
rst concrete subclass of
. Second, since
is th攠■
rst concrete
subclass, it must implement all inherited abstract methods,
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 264
In this example, we again have an abstract class
with a concrete subclass
that doesn’t compile since it doesn’t implement a
Creating Abstract Classes
c05.indd 1봀
4/2014 Page 265
266
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 266
Implementing Interfaces
Although Java doesn’t allow multiple inheritance, it does allow classes to implement any
number of interfaces. An
interface
is an abstract data type that de■
nes a list of abstract
public methods that any class implementing the interface must provide. An interface can
also include a list of constant variables and default methods, which well cover in this sec-
tion. In Java, an interface is de■
ned with the
keyword, analogous to the
keyword used when de■
ning a class. A class invokes the interface by using the
keyword in its class de■
nition. Refer to Figures 5.4 and 5.5 for proper syntax usage.
FIGURE 5.4
Defining an interface
interface keyword (required)
interface name
FIGURE 5.5
Implementing an interface
interface name
As you see in this example, an interface is not declared an abstract class, although it
has many of the same properties of abstract class. Notice that the method modi■
ers in this
Implementing Interfaces
c05.indd 1봀
4/2014 Page 267
example,
and
, are assumed. In other words, whether or not you provide
them, the compiler will automatically insert them as part of the method de■
nition.
A class may implement multiple interfaces, each separated by a comma, such as in the
following example:
In the example, if any of the interfaces de■
ned abstract methods, the concrete class
would be required to implement those methods.
New to Java 8 is the notion of default and static interface methods, which well cover at
the end of this section.
Defining an Interface
It may be helpful to think of an interface as a specialized kind of abstract class, since it
shares many of the same properties and rules as an abstract class. The following is a list
of rules for creating an interface, many of which you should recognize as adaptions of the
rules for de■
ning abstract classes.
Interfaces cannot be instantiated directly.
An interface is not required to have any methods.
An interface may not be marked as
All top-level interfaces are assumed to have
or default access, and they must
include the
modifier in their definition. Therefore, marking an interface as
will trigger a compiler error, since this is incompatible
with these assumptions.
All nondefault methods in an interface are assumed to have the modifiers
and
in their definition. Therefore, marking a method as
will trigger compiler errors as these are incompatible with the
and
keywords.
The fourth rule doesn’t apply to inner interfaces, although inner classes and interfaces
are not in scope for the OCA exam. Th攠■
rst three rules are identical to th攠■
rst three rules
for creating an abstract class. Imagine we have an interface
, de■
ned as
follows:
It compiles without issue, since interfaces are not required to de■
ne any methods. Now
consider the following two examples, which do not compile:
268
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 268
Th攠■
rst example doesn’t compile, as
is an interface and cannot be
instantiated directly. The second example,
, doesn’t compile since inter-
faces may not be marked as
for the same reason that
classes cannot be
marked as
The fourth an搠■
fth rule abou琠贀assumed keywords踠might be new to you, but you
should think of these in the same light as the compiler inserting a default no-argument con-
structor or
statement into your constructor. You may provide these modi■
ers your-
self, although the compiler will insert them automatically if you do not. For example, the
following two interface de■
nitions are equivalent, as the compiler will convert them both to
the second example:
In this example, the
keyword is 
rst automatically added to the interface
de■
nition. Then, each method is prepended with
and
keywords. If the
method already has either of these keywords, then no change is required. Let’s take a look
at an example that violates the assumed keywords:
Every single line of this example doesn’t compile. Th攠■
rst line doesn’t compile for two
reasons. First, it is marked as
, which cannot be applied to an interface since it con-
icts with the assumed
keyword. Next, it is marked as
, which con.
icts
with the
or default required access for interfaces. The second and third line do
not compile because all interface methods are assumed to be
and marking them
Implementing Interfaces
c05.indd 1봀
4/2014 Page 269
as
throws a compiler error. Finally, the last line doesn’t compile
because the method is marked as
and since interface methods are assumed to be
, the compiler throws an exception for using both
and
keywords
on a method.
Adding the assumed keywords to an interface is a matter of personal
preference, although it is considered good coding practice to do so. Code
with the assumed keywords written out tends to be easier and clearer to
read, and leads to fewer potential conflicts, as you saw in the previous
examples.
Be sure to review the previous example and understand why each of the lines doesn’t
compile. There will likely be at least one question on the exam in which an interface or
interface method uses an invalid modi■
er.
Inheriting an Interface
There are two inheritance rules you should keep in mind when extending an interface:
An interface that
another interface, as well as an abstract class that
an interface, inherits all of the abstract methods as its own abstract
methods.
The first concrete class that
an interface, or
an abstract class
that
an interface, must provide an implementation for all of the inherited
abstract methods.
Like an abstract class, an interface may be extended using the
keyword. In this
manner, the new child interface inherits all the abstract methods of the parent interface.
Unlike an abstract class, though, an interface may extend multiple interfaces. Consider the
following example:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 270
What about an abstract class that implements an interface? In this scenario, the abstract
class is treated in the same way as an interface extending another interface. In other words,
the abstract class inherits the abstract methods of the interface but is not required to imple-
ment them. That said, like an abstract class, th攠■
rst concrete class to extend the abstract
class must implement all the inherited abstract methods of the interface. We illustrate this
in the following example:
Implementing Interfaces
271
c05.indd 1봀
4/2014 Page 271
Be wary of examples on the exam that mix class and interface de■
nitions. Make sure the
only connection between a class and an interface is with the
class
interface
syntax.
Abstract Methods and Multiple Inheritance
Since Java allows for multiple inheritance via interfaces, you might be wondering what
will happen if you de■
ne a class that inherits from two interfaces that contain the same
method:
In this scenario, the signatures for the two interface methods
are compat-
ible, so you can de■
ne a class that ful■
lls both interfaces simultaneously:
Why does this work? Remember that interface methods in this example are
and de■
ne th攠贀behavior踀 that the class implementing the interface must have. If two
interface methods have identical behaviors—or in this case the same method
signature— creating a class that implements one of the two methods automatically imple-
ments the second method. In this manner, the interface methods are considered duplicates
since they have the same signature.
What happens if the two methods have different signatures? If the method name is the
same but the input parameters are different, there is no con.
ict because this is considered a
method overload. We demonstrate this principle in the following example:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 272
Implementing Interfaces
c05.indd 1봀
4/2014 Page 273
The code doesn’t compile, as the class de■
nes two methods with the same name and
input parameters but different return types. If we were to remove either de■
nition of
, the compiler would stop because the de■
nition of
would be missing one
of the required methods. In other words, there is no implementation of the
class that
inherits from
and
that the compiler would accept.
The compiler would also throw an exception if you de■
ne an interface or
class
that inherits from two con.
icting interfaces, as shown here:
Even without implementation details, the compiler detects the problem with the
de■
nition and prevents compilation.
This concludes our discussion of
interface methods and multiple inheritance.
We’ll return to this discussion shortly after we introduce default interface methods. You’ll
see that things work a bit differently with default interface methods.
Interface Variables
Let’s expand our discussion of interfaces to include interface variables, which can be
de■
ned within an interface. Like interface methods, interface variables are assumed to
be
. Unlike interface methods, though, interface variables are also assumed to be
and
Here are two interface variables rules:
Interface variables are assumed to be
, and
. Therefore, marking
a variable as
will trigger a compiler error, as will marking any
variable as
The value of an interface variable must be set when it is declared since it is marked as
In this manner, interface variables are essentially constant variables de■
ned on the
interface level. Because they are assumed to be
, they are accessible even without
274
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 274
an instance of the interface. Like our earlier
example, the following two interface
de■
nitions are equivalent, because the compiler will automatically convert them both to the
second example:
As we see in this example, the compile will automatically insert
any constant interface variables it 
nds missing those modi■
ers. Also note that it is a com-
mon coding practice to use uppercase letters to denote constant values within a class.
Based on these rules, it should come as no surprise that the following entries will not
compile:
Th攠■
rst example,
, doesn’t compile because the
modi■
er is used,
and all interface variables are assumed to be
. The second line,
, doesn’t
compile for two reasons. It is marked as
, which con.
icts with the assumed
modi■
, and it is marked as
, which con.
icts with the assumed modi■
. Finally, the last example,
, doesn’t compile because it is missing a value. Unlike
the other examples, the modi■
ers are correct, but as you may remember from Chapter 4,
you must provide a value to a
member of the class when it is de■
ned.
Default Interface Methods
With the release of Java 8, the authors of Java have introduced a new type of method to an
interface, referred to as a default method. A
Implementing Interfaces
275
c05.indd 1봀
4/2014 Page 275
A default method within an interface de■
nes an abstract method with a default imple-
mentation. In this manner, classes have the option to override the default method if they
need to, but they are not required to do so. If the class doesn’t override the method, the
default implementation will be used. In this manner, the method de■
nition is concrete, not
abstract.
The purpose of adding default methods to the Java language was in part to help with
code development and backward compatibility. Imagine you have an interface that is
shared among dozens or even hundreds of users that you would like to add a new method
to. If you just update the interface with the new method, the implementation would break
among all of your subscribers, who would then be forced to update their code. In practice,
this might even discourage you from making the change altogether. By providing a default
implementation of the method, though, the interface becomes backward compatible with
the existing codebase, while still providing those individuals who do want to use the new
method with the option to override it.
The following is an example of a default method de■
ned in an interface:
276
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 276
Like all methods in an interface, a default method is assumed to be
and will not
compile if marked as
Th攠■
rst rule should give you some comfort in that you’ll only see default methods in
interfaces. If you see them in a class on the exam, assume the code will not compile. The
second rule just denotes syntax, as default methods must use the
keyword. For
example, the following code snippets will not compile:
Implementing Interfaces
c05.indd 1봀
4/2014 Page 277
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 278
In this example,
inherits the two default methods for
Understanding Polymorphism
c05.indd 1봀
4/2014 Page 279
The method
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 280
Understanding Polymorphism
281
c05.indd 1봀
4/2014 Page 281
In this example, the reference
has direct access only to methods de■
ned with
the
interface; therefore, it doesn’t know the variable
is part of the object.
Likewise, the reference
has access only to methods de■
ned in the
class,
and it doesn’t have direct access to the
method.
Object vs. Reference
In Java, all objects are accessed by reference, so as a developer you never have direct access
to the object itself. Conceptually, though, you should consider the object as the entity that
exists in memory, allocated by the Java runtime environment. Regardless of the type of the
reference you have for the object in memory, the object itself doesn’t change. For example,
since all objects inherit
, they can all be reassigned to
as shown in the following example:
Even though the
object has been assigned a reference with a different type, the
object itself has not changed and still exists as a
object in memory. What has changed,
then, is our ability to access methods within the
class with the
refer-
ence. Without an explicit cast back to
, as you’ll see in the next section, we no longer
have access to the
properties of the object.
We can summarize this principle with the following two rules:
The type of the object determines which properties exist within the object in memory.
The type of the reference to the object determines which methods and variables are
accessible to the Java program.
It therefore follows that successfully changing a reference of an object to a new reference
type may give you access to new properties of the object, but those properties existed before
the reference change occurred.
Let’s illustrate this property using the previous example in Figure 5.6. As you can see in
th攠■
gure, the same object exists in memory regardless of which reference is pointing to it.
Depending on the type of the reference, we may only have access to certain methods. For
example, the
reference has access to the method
but doesn’t have
access to the variable
de■
ned in the
class. As you’ll learn in the next section, it is
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 282
possible to reclaim access to the variable
by explicitly casting the
reference to a
reference of type
FIGURE 5.6
Object vs. reference
Reference of interface HasTail
Lemur object in memory
Casting Objects
In the previous example, we created a single instance of a
object and accessed it
via superclass and interface references. Once we changed the reference type, though,
we lost access to more speci■
c methods de■
ned in the subclass that still exist within the
object. We can reclaim those references by casting the object back to the speci■
c sub-
class it came from:
In this example, we 
rst try to convert the
reference back to a
reference,
, without an explicit cast. The result is that the code will not compile. In the second
example, though, we explicitly cast the object to a subclass of the object
and we
gain access to all the methods available to the
class.
Here are some basic rules to keep in mind when casting variables:
Casting an object from a subclass to a superclass doesn’t require an explicit cast.
Casting an object from a superclass to a subclass requires an explicit cast.
The compiler will not allow casts to unrelated types.
Even when the code compiles without issue, an exception may be thrown at runtime if
the object being cast is not actually an instance of that class.
Understanding Polymorphism
283
c05.indd 1봀
4/2014 Page 283
The third rule is important; the exam may try to trick you with a cast that the compiler
doesn’t allow. For example, we were able to cast a
reference to a
reference,
because
is a subclass of
and therefore related.
Consider this example:
) Fish fish = new Fish(); Bird bird = (Bird)fish; // DOES NOT COMPILE }}In this example, the classes
and
are not related through any class hierarchy
that the compiler is aware of; therefore, the code will not compile.
Casting is not without its limitations. Even though two classes share a related hierar-
chy, that doesn’t mean an instance of one can automatically be cast to another. He牥’s an
example:
) Rodent rodent = new Rodent(); Capybara capybara = (Capybara)rodent; // Throws ClassCastException at runtime }}This code creates an instance of
and then tries to cast it to a subclass of
. Although this code will compile without issue, it will throw a
at runtime since the object being referenced is not an instance of the
class. The thing to keep in mind in this example is the object that was created is
not related to the
class in any way.
Although this topic is out of scope for the OCA exam, keep in mind that the
operator can be used to check whether an object belongs to a
particular class and to prevent
s at runtime. Unlike the
previous example, the following code snippet doesn’t throw an exception at
runtime and performs the cast only if the
operator returns
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 284
When reviewing a question on the exam that involves casting and polymorphism, be
sure to remember what the instance of the object actually is. Then, focus on whether the
compiler will allow the object to be referenced with or without explicit casts.
Virtual Methods
The most important feature of polymorphism—and one of the primary reasons we have
class structure at all—is to support virtual methods. A
virtual method
is a method in which
the speci■
c implementation is not determined until runtime. In fact, all non-■
nal, non-
static, and non-private Java methods are considered virtual methods, since any of them can
be overridden at runtime. What makes a virtual method special in Java is that if you call a
method on an object that overrides a method, you get the overridden method, even if the
call to the method is on a parent reference or within the parent class.
We’ll illustrate this principle with the following example:
Understanding Polymorphism
c05.indd 1봀
4/2014 Page 285
In other words, even though the parent class
de■
nes its own version of
explicit cast is not required. This property is referred to as
polymorphic parameters
of a
method, and we demonstrate it in the following example:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 286
) feed(new Alligator()); feed(new Crocodile()); feed(new Reptile()); }}This code compiles and executes without issue, yielding the following output:
Let’s focus on the
method in this example. As you can see, that
method was able to handle instances of
and
without issue, because
both are subclasses of the
class. It was also able to accept a matching type
class. If we had tried to pass an unrelated class, such as the previously de■
ned
classes, or a superclass such as
, to the
method, the
code would not have compiled.
Polymorphic Parameters and Code Reusability
If you’re defi
ning a method that will be accessible outside the current class, either to
subclasses of the current class or publicly to objects outside the current class, it is con-
sidered good coding practice to use the superclass or interface type of input parameters
whenever possible.
As you may remember from Chapter 3,₍Core Java APIs,踀 the type
is an
interface, not a class. Although there are many classes that implement
such as
and
, when you’re passing an existing
you’re not usually interested in the particular subclass of the
. In this manner, a
method that passes a
should use the interface type
as the polymor-
phic parameter type, rather than a specifi
c class that implements
, as the code will be
more reusable for other types of lists.
For example, it is common to see code such as the following that uses the interface refer-
ence type over the class type for greater reusability:
Understanding Polymorphism
287
c05.indd 1봀
4/2014 Page 287
Polymorphism and Method Overriding
Let’s conclude this chapter by returning to the last three rules for method overriding to
demonstrate how polymorphism requires them to be included as part of the Java speci■
ca-
tion. You’ll see that without such rules in place, it is easy to construct an example with
polymorphism in Java.
Th攠■
rst rule is that an overridden method must be at least as accessible as the method it
is overriding. Let’s assume this rule is not necessary and consider the following example:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 288
贀uncheckedŽ checked exceptions. Therefore, the Java compiler disallows overriding meth-
ods with new or broader exceptions.
Finally, overridden methods must use covariant return types for the same kinds of
reasons as just discussed. If an object is cast to a superclass reference and the overridden
method is called, the return type must be compatible with the return type of the parent
method. If the return type in the child is too broad, it will result an inherent cast exception
when accessed through the superclass reference.
Exam Essentials
c05.indd 1봀
4/2014 Page 289
Finally, this chapter introduced the concept of polymorphism, central to the Java lan-
guage, and showed how objects can be accessed in a variety of forms. Make sure you
understand when casts are needed for accessing objects, and be able to spot the difference
between compile-time and runtime cast problems.
Exam Essentials
Be able to write code that extends other classes.
A Java class that extends another class
inherits all of its
and
methods and variables. Th攠■
rst line of every
constructor is a call to another constructor within the class using
or a call to a con-
structor of the parent class using the
call. If the parent class doesn’t contain a no-
argument constructor, an explicit call to the parent constructor must be provided. Parent
methods and objects can be accessed explicitly using the
keyword. Finally, all classes
in Java extend
either directly or from a superclass.
Understand the rules for method overriding.
The Java compiler allows methods to be
overridden in subclasses if certain rules are followed: a method must have the same signa-
ture, be at least as accessible as the parent method, must not declare any new or broader
exceptions, and must use covariant return types.
Understand the rules for hiding methods and variables.
When a static method is re-
created in a subclass, it is referred to as method hiding. Likewise, variable hiding is when
a variable name is reused in a subclass. In both situations, the original method or variable
still exists and is used in methods that reference the object in the parent class. For method
hiding, the use of
in the method declaration must be the same between the parent
and child class. Finally, variable and method hiding should generally be avoided since it
leads to confusing and dif■
cult-to-follow code.
Recognize the difference between method overriding and method overloading.
Both
method overloading and overriding involve creating a new method with the same name
as an existing method. When the method signature is the same, it is referred to as method
overriding and must follow a speci■
c set of override rules to compile. When the method
signature is different, with the method taking different inputs, it is referred to as method
overloading and none of the override rules are required.
Be able to write code that creates and extends abstract classes.
In Java, classes and meth-
ods can be declared as
. Abstract classes cannot be instantiated and require a con-
crete subclass to be accessed. Abstract classes can include any number, including zero, of
abstract and nonabstract methods. Abstract methods follow all the method override rules
and may only be de■
ned within abstract classes. Th攠■
rst concrete subclass of an abstract
class must implement all the inherited methods. Abstract classes and methods may not be
marked as
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 290
Be able to write code that creates, extends, and implements interfaces.
Interfaces are similar
to a specialized abstract class in which only abstract methods and constant
variables are allowed. New to Java 8, an interface can also de■
ne default and static meth-
ods with method bodies. All members of an interface are assumed to be public. Methods
are assumed to be abstract if not explicitly marked as
. An interface that
extends another interface inherits all its abstract methods. An interface cannot extend a class,
nor can a class extend an interface. Finally, classes may implement any number of interfaces.
Be able to write code that uses default and static interface methods.
A default method
allows a developer to add a new method to an interface used in existing implementations,
without forcing other developers using the interface to recompile their code. A developer
using the interface may override the default method or use the provided one. A static
method in an interface follows the same rules for a static method in a class.
Understand polymorphism.
An object in Java may take on a variety of forms, in part
depending on the reference used to access the object. Methods that are overridden will be
replaced everywhere they are used, whereas methods and variables that are hidden will
only be replaced in the classes and subclasses that they are de■
ned. It is common to rely on
polymorphic parameters—the ability of methods to be automatically passed as a superclass
or interface reference—when creating method de■
nitions.
Recognize valid reference casting.
An instance can be automatically cast to a superclass
or interface reference without an explicit cast. Alternatively, an explicit cast is required if
the reference is being narrowed to a subclass of the object. The Java compiler doesn’t per-
mit casting to unrelated types. You should be able to discern between compiler-time casting
errors and those that will not occur until runtime and that throw a
Review Questions
291
c05.indd 1봀
4/2014 Page 291
Review Questions
What modifiers are implicitly applied to all interface methods? (Choose all that apply⤀
What is the output of the following code?
)11: new Mammal(5);12: }13: }A. PlatypusB. MammalC. PlatypusMammalD. MammalPlatypusE. The code will not compile because of line 8.
The code will not compile because of line 11.
Which of the following statements can be inserted in the blank line so that the code will
compile successfully? (Choose all that apply⤀
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 292
Which statement⠀s⤀ are correct about the following code? (Choose all that apply⤀
Review Questions
c05.indd 1봀
4/2014 Page 293
Choose the correct statement about the following code:
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 294
Choose the correct statement about the following code:
Review Questions
295
c05.indd 1봀
4/2014 Page 295
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 296
The
interface doesn’t compile.
A class that implements
must override the
method.
A class that implements
inherits both the
and
methods.
A class that implements
only inherits the
method.
An interface cannot extend another interface.
15.
Which of the following is true about a concrete subclass? (Choose all that apply⤀
A concrete subclass can be declared as
A concrete subclass must implement all inherited abstract methods.
A concrete subclass must implement all methods defined in an inherited interface.
A concrete subclass cannot be marked as
Abstract methods cannot be overridden by a concrete subclass.
16.
What is the output of the following code?
)4: Reptile reptile = new Lizard();5: reptile.layEggs();6: }7: }8: public class Lizard extends Reptile {9: public void layEggs() { System.out.println("Lizard laying eggs"); }10: }A. Reptile laying eggsB. Lizard laying eggsC. The code will not compile because of line 4.
The code will not compile because of line 5.
The code will not compile because of line 9.
17.
What is the output of the following code?
Review Questions
297
c05.indd 1봀
4/2014 Page 297
The code will not compile because of line 2.
The code will not compile because of line 8.
The code will not compile because of line 9.
The output cannot be determined from the code provided.
18.
What is the output of the following code? (Choose all that apply⤀
Chapter 5
Class Design
c05.indd 1봀
4/2014 Page 298
20.
What is the result of the following code?
)4: Bird bird = new Pelican();5: bird.fly();6: }7: }8: class Pelican extends Bird {9: protected void fly() { System.out.println("Pelican is flying"); }10: }A. Bird is flyingB. Pelican is flying C. The code will not compile because of line 4.
The code will not compile because of line 5.
The code will not compile because of line 9.
c06.indd 1봀
4/2014 Page 299
Chapter
Exceptions
OCA EXAM OBJECTIVES COVERED
IN THIS CHAPTER:
Handling Exceptions
Differentiate among checked exceptions, unchecked
exceptions and Errors
Create a try-catch block and determine how exceptions alter
normal program flow
Describe the advantages of Exception handling
Create and invoke a method that throws an exception
Recognize common exception classes (such as
NullPointerException, ArithmeticException,
ArrayIndexOutOfBoundsException, ClassCastException⤀
c06.indd 1봀
4/2014 Page 300
Many things can go wrong in a program. Java uses exceptions to
deal with some of these scenarios. The OCA exam covers only the
basics of working with exceptions. The rest are on the OCP exam.
Understanding Exceptions
A program can fail for just about any reason. Here are just a few possibilities:
The code tries to connect to a website, but the Internet connection is down.
You made a coding mistake and tried to access an invalid index in an array.
One method calls another with a value that the method doesn’t support.
As you can see, some of these are coding mistakes. Others are completely beyond your
control. Your program can’t help it if the Internet connection goes down. What it
can
do is
deal with the situation.
First, well look at the role of exceptions. Then well cover the various types of exceptions,
followed by an explanation of how to throw an exception in Java.
The Role of Exceptions
An
exception
is Java’s way of saying, I give up. I don’t know what to do right now. You
deal with it.踀 When you write a method, you can either deal with the exception or make it
the calling co摥’s problem.
As an example, think of Java as a child who visits the zoo. The
happy path
is when
nothing goes wrong. The child continues to look at the animals until the program nicely
ends. Nothing went wrong and there were no exceptions to deal with.
This chil撐s younger sister doesn’t experience the happy path. In all the excitement she
trips and falls. Luckily, it isn’t a bad fall. The little girl gets up and proceeds to look at
more animals. She has handled the issue all by herself. Unfortunately, she falls again later
in the day and starts crying. This time, she has declared she needs help by crying. The
story ends well. Her daddy rubs her knee and gives her a hug. Then they go back to seeing
more animals and enjoy the rest of the day.
These are the two approaches Java uses when dealing with exceptions. A method can
handle the exception case itself or make it the caller’s responsibility. You saw both in the
trip to the zoo.
Understanding Exceptions
301
c06.indd 1봀
4/2014 Page 301
You saw an exception in Chapter 1,₍Java Building Blocks,踀 with a very simple
example. You wrote a class that printed out the name of the zoo:
)3: System.out.println(args[0]);4: System.out.println(args[1]);5: } }Then you tried to call it without enough arguments:
On line 4, Java realized theres only one element in the array and index 1 is not allowed.
Java threw up its hands in defeat and threw an exception. It didn’t try to handle the exception.
It just said, I can’t deal with it踠and the exception was displayed:
continues
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 302
This approach is common when writing a method that does a search. For example,
imagine being asked toₓ
nd the name Joe in the array. It is perfectly reasonable that
Joe might not appear in the array. When this happens, a special value is returned. An
exception should be reserved for exceptional conditions like
names
being
In general, try to avoid return codes. Return codes are commonly used in searches, so
programmers are expecting them. In other methods, you will take your callers by surprise
by returning a special value. An exception forces the program to deal with them or end
with the exception if left unhandled, whereas a return code could be accidentally ignored
and cause problems later in the program. An exception is like shoutingⰠ贀Deal with me!踀
Understanding Exception Types
As weve explained, an exception is an event that alters progra洠.
ow. Java has a
superclass for all objects that represent these events. Not all of them have the word excep-
tion in their classname, which can be confusing. Figure 6.1 shows the key subclasses of
FIGURE 6.1
Categories of exception
means something went so horribly wrong that your program should not attempt to
recover from it. For example, the disk driv攠贀disappeared.踀 These are abnormal conditions
that you aren’t likely to encounter.
runtime exception
is de■
ned as the
class and its subclasses. Runtime
exceptions tend to be unexpected but not necessarily fatal. For example, accessing an invalid
array index is unexpected. Runtime exceptions are also known as
unchecked exceptions
continued
Understanding Exceptions
c06.indd 1봀
4/2014 Page 303
Runtime vs. at the Time the Program is Run
A runtime (unchecked) exception is a specifi
c type of exception. All exceptions occur at the
time that the program is run. (The alternative is compile time, which would be a compiler
error.) People don’t refer to them as run time exceptions because that would be too easy to
confuse with runtime! When you see runtime, it means unchecked.
checked exception
includes
and all subclasses that do not extend
. Checked exceptions tend to be more anticipated—for example, trying
to read a 
le that doesn’t exist.
Checked exceptions? What are we checking? Java has a rule called the
handle or declare
rule
. For checked exceptions, Java requires the code to either handle them or declare them
in the method signature.
For example, this method declares that it might throw an exception:
Notice that you’re using two different keywords here.
tells Java that you want to
throw an
simply declares that the method might throw an
also might not. You will see the
keyword more later in the chapter.
Because checked exceptions tend to be anticipated, Java enforces that the programmer do
something to show the exception was thought about. Maybe it was handled in the method.
Or maybe the method declares that it can’t handle the exception and someone else should.
An example of a runtime exception is a
, which happens when
you try to call a member on a null reference. This can occur in any method. If you had to
declare runtime exceptions everywhere, every single method would have that clutter!
Checked vs. Unchecked (Runtime) Exceptions
In the past, developers used checked exceptions more often than they do now. Accord-
ing to Oracle, they are intended for issues a programmer₍might reasonably be expected
to recover from.踀 Then developers started writing code where a chain of methods kept
declaring the same exception and nobody actually handled it. Some libraries started
using runtime exceptions for issues a programmer might reasonably be expected to
recover from. Many programmers can hold a debate with you on which approach is bet-
ter. For the OCA exam, you need to know the rules for how checked versus unchecked
exceptions function. You don’t have to decide philosophically whether an exception
should be checked or unchecked.
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 304
Throwing an Exception
Any Java code can throw an exception; this includes code you write. For the OCP exam,
you’ll learn how to create your own exception classes. The OCA exam is limited to
exceptions that someone else has created. Most likely, they will be exceptions that are
provided with Java. You might encounter an exception that was made up for the exam.
This is 
ne. The question will make it obvious that these are exceptions by having the
classname end with
. For example,₍MyMadeUpException踠is clearly an
exception.
On the exam, you will see two types of code that result in an exception. Th攠■
rst is code
that’s wrong. For example:
System.out.println(animals[0]);This code throws an
. That means questions about
exceptions can be hidden in questions that appear to be about something else.
On the OCA exam, the vast majority of questions have a choice about
not compiling and about throwing an exception. Pay special attention to
code that calls a method on a null or that references an invalid array or
index. If you spot this, you know the correct answer is that the
code throws an exception.
The second way for code to result in an exception is to explicitly request Java to throw
one. Java lets you write statements like these:
The
keyword tells Java you want some other part of the code to deal with the
exception. This is the same as the young girl crying for her daddy. Someone else needs to
gure out what to do about the exception.
When creating an exception, you can usually pass a
parameter with a message or
you can pass no parameters and use the defaults. We say
usually
because this is a conven-
tion. Someone could create an exception class that does not have a constructor that takes
a message. Th攠■
rst two examples create a new object of type
and throw it.
The last two show that the code looks the same regardless of which type of exception you
throw.
c06.indd 1봀
4/2014 Page 305
Using a
try
Statement
These rules are very important. Be sure to closely study everything in Table 6.1.
TABLE 6.1
Types of exceptions
Type
How to recognize
Okay for program
to catch?
Is program required
to handle or declare?
Runtime exceptionSubclass of
YesNo
Checked exceptionSubclass of
but not subclass of
YesYes
ErrorSubclass of
NoNo
Using a
try
Statement
Now that you know what exceptions are, let’s explore how to handle them. Java uses a
try
statement
to separate the logic that might throw an exception from the logic to handle that
exception. Figure 6.2 shows the syntax of a
statement.
FIGURE 6.2
The syntax of a
try
statement
try {
//The try block is also referred to
The try keyword
If an exception is thrown in a try
you are trying to catch
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 306
block is run normally. If any of the statements throw an exception
block, the
statement. If none of the statements in the
throw an exception that can be caught, the
catch clause
You probably noticed the word猠贀blockŽ an搠贀clause踀 used interchangeably. The
exam does this as well, so we are getting you used to it. Both are correct.₍BlockŽ is
correct because there are braces present.₍Clause踀 is correct because they are part of a
statement.
There aren’t a ton of syntax rules here. The curly braces are required for the
and
blocks.
In our example, the little girl gets up by herself th攠■
rst time she falls. He牥’s what this
looks like:
c06.indd 1봀
4/2014 Page 307
Using a
try
Statement
307
statements are like methods in that the curly braces are required even if there is only
one statement inside the code blocks.
statements and loops are special in this respect as
they allow you to omit the curly braces.
What about this one?
This code doesn’t compile because the
block doesn’t have anything after it.
Remember, the point of a
statement is for something to happen if an exception is
thrown. Without another clause, the
statement is lonely.
try {
of a try statement.
There are two paths through code with both a
and a
. If an exception
is thrown, the
block is run after the
block. If no exception is thrown, the
block is run after the
block completes.
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 308
Let’s go back to our young girl example, this time with
c06.indd 1봀
4/2014 Page 309
Using a
try
Statement
310
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 310
Creating your own exceptions is not on the OCA exam, but it is on the OCP exam.
However, the OCA exam can de■
ne basic exceptions to show you the hierarchy. You only
need to do two things with this information. First, you must be able to recognize if the
exception is a checked or an unchecked exception. Second, you need to determine if any of
the exceptions are subclasses of the others.
In this example, there are three custom exceptions. All are unchecked exceptions
because they directly or indirectly extend
. Now we catch both types of
exceptions and handle them by printing out the appropriate message:
There are three possibilities for when this code is run. If
doesn’t throw an
exception, nothing is printed out. If the animal is out for a walk, only th攠■
rst
block
runs. If the exhibit is closed, only the second
block runs.
blocks. Java looks at them in the order they
appear. If it is impossible for one of the
blocks to be executed, a compiler error
about unreachable code occurs. This happens when a superclass is caught before a subclass.
Remember, we warned you to pay attention to any subclass exceptions.
In the porcupine example, the order of the
blocks could be reversed because the
exceptions don’t inherit from each other. And yes, we have seen a porcupine be taken for a
walk on a leash.
The following example shows exception types that do inherit from each other:
c06.indd 1봀
4/2014 Page 311
Using a
try
Statement
311
If the more speci■
exception is thrown, th攠■
rst
block runs. If not, Java checks if the superclass
exception is thrown
and catches it. This time, the order of the
blocks does matter. The reverse does
not work.
This time, if the more speci■
c
exception is thrown, the
block for
runs—which means there is no way for the second
block to
ever run. Java correctly tells us there is an unreachable
block.
Let’s try this one more time. Do you see why this code doesn’t compile?
䥴’s the same problem.
. If it is thrown, the 
312
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 312
Even though the topic of reading files is on the OCP exam, the OCA exam
may ask you about exception handling with those classes. This is actually a
gift. When you see such a question, you know the problem has to be about
basic Java syntax or exception handling!
The following code tries to read a 
le:
)17: FileReader reader = null;18: try {19: reader = read();20: } catch (IOException e) {21: try {22: if (reader != null) reader.close();23: } catch (IOException inner) {24: }25: }26: }27: private static FileReader read() throws IOException {28: // CODE GOES HERE29: }The easiest case is if line 28 doesnt throw an exception. Then the entire
lines 20…25 is skipped. Next, consider if line 28 throws a
. That isnt
, so the
, the
Recognizing Common Exception Types
313
c06.indd 1봀
4/2014 Page 313
be thrown. However, the
block. Since the
314
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 314
Runtime Exceptions
Runtime exceptions extend
. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM. Common runtime exceptions
include the following:
Recognizing Common Exception Types
315
c06.indd 1봀
4/2014 Page 315
for (int i = 0; i = countsOfMoose.length; i++) total += countsOfMoose[i]; The problem is that the
loop should have
instead of
. On th攠■
nal iteration of
the loop, Java tries to call
, which is invalid. The array includes only
three elements, making 2 the largest possible index. The output looks like this:
ClassCastException
Java tries to protect you from impossible casts. This code doesn’t compile because
is not a subclass of
More complicated code thwarts Java’s attempts to protect you. When the cast fails at
runtime, Java will throw a
The compiler sees a cast from
. This could be okay. The compiler
doesn’t realize theres a
in that
. When the code runs, it yields the following
output:
Java tells us both types that were involved in the problem, making it apparent what’s
wrong.
IllegalArgumentException
is a way for your program to protect itself. We 
rst saw the
following setter method in the
class in Chapter 4,₍Methods and Encapsulation.踀
316
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 316
ple, which checks whether you remember instance variable references default to
Running this code results in this output:
NumberFormatException
Java provides methods to convert strings to numbers. When these are passed
an invalid value, they throw a
. The idea is similar to
. Since this is a common problem, Java gives it a separate class.
In fact,
is a subclass of
. He牥’s an
example of trying to convert something non-numeric into an
The output looks like this:
Recognizing Common Exception Types
317
c06.indd 1봀
4/2014 Page 317
Checked Exceptions
Checked exceptions have
in their hierarchy but not
. They
must be handled or declared. They can be thrown by the programmer or by the JVM.
Common runtime exceptions include the following:
Thrown programmatically when code tries to reference a 
le
that does not exist
Thrown programmatically when theres a problem reading or writing a 
le
For the OCA exam, you only need to know that these are checked exceptions. Also keep
in mind that
is a subclass of
, although the exam will
remind you of that fact if it comes up. You’ll see these two exceptions in more detail on the
OCP exam.
Errors
Errors extend the
class. They are thrown by the JVM and should not be handled or
declared. Errors are rare, but you might see these:
Thrown by the JVM when a static initializer throws
an exception and doesn’t handle it
Thrown by the JVM when a method calls itself too many times
⠀this is called
in■
nite recursion
because the method typically calls itself without end⤀
Thrown by the JVM when a class that the code uses is available
at compile time but not runtime
ExceptionInInitializerError
Java runs
initializers th攠■
rst time a class is used. If one of the
initializers
throws an exception, Java can’t start using the class. It declares defeat by throwing an
. This code shows an
in a
initializer:
318
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 318
This code yields information about two exceptions:
We get the
because the error happened in a
initial-
izer. That information alone wouldn’t be particularly useful in 
xing the problem. Therefore,
Java also tells us the original cause of the problem: the
that
we need to 
x.
The
is an error because Java failed to load the whole
class. This failure prevents Java from continuing.
StackOverflowError
When Java calls methods, it puts parameters and local variables on the stack. After doing
this a very large number of times, the stack runs out of room and over.
ows. This is called a
. Most of the time, this error occurs when a method calls itself.
Calling Methods That Throw Exceptions
319
c06.indd 1봀
4/2014 Page 319
The problem is that
is a checked exception. Checked excep-
tions must be handled or declared. The code would compile if we changed the
method to either of these:
) throws NoMoreCarrotsException {// declare exception eatCarrot();}public static void main(String[] args) { try { eatCarrot(); } catch (NoMoreCarrotsException e ) {// handle exception System.out.print("sad rabbit"); }}You might have noticed that
didn’t actually throw an exception; it just
declared that it could. This is enough for the compiler to require the caller to handle or
declare the exception.
The compiler is still on the lookout for unreachable code. Declaring an unused exception
isn’t considered unreachable code. It gives the method the option to change the implementa-
tion to throw that exception in the future. Do you see the issue here?
Java knows that
can’t throw a checked exception—which means theres no
way for the
block in
to be reached. In comparison,
is free to declare
other exceptions.
Subclasses
Now that you have a deeper understanding of exceptions, let’s look at overriding meth-
ods with exceptions in the method declaration. When a class overrides a method from a
320
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 320
superclass or implements a method from an interface, it’s not allowed to add new checked
exceptions to the method signature. For example, this code isn’t allowed:
Java knows
isn’t allowed to throw any checked exceptions because the superclass
doesn’t declare any. Imagine what would happen if subclasses could add checked
exceptions—you could write code that calls

method and not handle any
exceptions. Then if
was used in its place, the code wouldn’t know to handle or
declare
A subclass is allowed to declare fewer exceptions than the superclass or interface. This is
legal because callers are already handling them.
A subclass not declaring an exception is similar to a method declaring it throws an
exception that it never actually throws. This is perfectly legal.
Similarly, a class is allowed to declare a subclass of an exception type. The idea is the
same. The superclass or interface has already taken care of a broader type. He牥’s an
example:
could declare that it throws
directly, or it could declare that it throws a
more speci■
c type of
. It could even declare that it throws nothing at all.
This rule applies only to checked exceptions. The following code is legal because it has a
runtime exception in the subclass’s version:
Calling Methods That Throw Exceptions
321
c06.indd 1봀
4/2014 Page 321
The reason that it’s okay to declare new runtime exceptions in a subclass method is that
the declaration is redundant. Methods are free to throw any runtime exceptions they want
without mentioning them in the method declaration.
Printing an Exception
There are three ways to print an exception. You can let Java print it out, print just the mes-
sage, or print where the stack trace comes from. This example shows all three approaches:
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 322
FIGURE 6.4
A method stack
Why Swallowing Exception Is Bad
Because checked exceptions require you to handle or declare them, there is a temptation
to catch them so they₍go away.踀 But doing so can cause problems. In the following code,
there’s a problem reading in th攠fi
le:
) String textInFile = null; try { readInFile(); } catch (IOException e) { // ignore exception } // imagine many lines of code here System.out.println(textInFile.replace(" ", ""));}private static void readInFile() throws IOException { throw new IOException();}The code results in a
. Java doesn’t tell you anything about the
original
because it was handled. Granted, it was handled poorly, but it
was
handled.
When writing your own code, print out a stack trace or at least a message when catching
an exception. Also, consider whether continuing is the best course of action. In our exam-
ple, the program can’t do anything after it fails to read in th攠fi
le. It might as well have just
thrown the
Summary
c06.indd 1봀
4/2014 Page 323
Summary
An exception indicates something unexpected happened. A method can handle an excep-
tion by catching it or declaring it for the caller to deal with. Many exceptions are thrown
by Java libraries. You can throw your own exception with code such as
Subclasses of
are exceptions that a programmer should not attempt to
handle. Subclasses of
are runtime (unchecked) exceptions.
Subclasses of
, but not
are checked
exceptions. Java requires checked exceptions to be handled or declared.
If a
statement has multiple
blocks, at most one
block can run. Java
looks for an exception that can be caught by each
block in the order they appear, and
th攠■
rst match is run. Then execution continues after the
statement. If both
and
throw an exception, the one from
gets thrown.
Common runtime exceptions include:
324
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 324
Exam Essentials
Differentiate between checked and unchecked exceptions.
Unchecked exceptions are also
known as runtime exceptions and are subclasses of
. All
other subclasses of
are checked exceptions.
Understand the flow of a
statement.
A
statement must have a
block. Multiple
blocks are also allowed, provided no superclass exception type
appears in an earlier
block than its subclass. The
block runs last regardless
of whether an exception is thrown.
Identify whether an exception is thrown by the programmer or the JVM.
and
are commonly thrown by the program-
mer. Most of the other runtime exceptions are typically thrown by the JVM.
Declare methods that declare exceptions.
The
keyword is used in a method decla-
ration to indicate an exception might be thrown. When overriding a method, the method is
allowed to throw fewer exceptions than the original version.
Recognize when to use throw versus throws.
The
keyword is used when you actu-
ally want to throw an exception—for example
The
keyword is used in a method declaration.
Review Questions
c06.indd 1봀
4/2014 Page 325
Review Questions
Which of the following statements are true? (Choose all that apply⤀
Runtime exceptions are the same thing as checked exceptions.
Runtime exceptions are the same thing as unchecked exceptions.
You can declare only checked exceptions.
You can declare only unchecked exceptions.
You can handle only
subclasses.
Which of the following pairs fill in the blanks to make this code compile? (Choose all that
apply⤀
On line 7, fill in
On line 7, fill in
On line 8, fill in
On line 8, fill in
On line 8, fill in
On line 8, fill in
When are you required to use a
block in a regular
statement (not a
Never.
When the program code doesn’t terminate on its own.
When there are no
blocks in a
statement.
When there is exactly one
block in a
statement.
When there are two or more
blocks in a
statement.
Which exception will the following throw?
None of the above.
326
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 326
Which of the following exceptions are thrown by the JVM? (Choose all that apply⤀
What will happen if you add the statement
to a working
method?
It will not compile.
It will not run.
It will run and throw an
Review Questions
327
c06.indd 1봀
4/2014 Page 327
No output appears other than the stack trace.
What is the output of the following snippet, assuming a and b are both 0?
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 328
The code does not compile.
An uncaught exception is thrown.
10.
What is the output of the following program?
)14: Dog leroy = new Dog();15: leroy.name = "Leroy";16: leroy.parseName();17: System.out.print("5");18: } }A. 12B. 1234C. 1235D. 124E. 1245F. The code does not compile.
An uncaught exception is thrown.
11.
What is the output of the following program?
Review Questions
c06.indd 1봀
4/2014 Page 329
)15: Cat leo = new Cat();16: leo.name = "Leo";17: leo.parseName();18: System.out.print("6");19: }20: }A. 12, followed by a stack trace for a
, followed by a stack trace for a
, followed by a stack trace for a
The code does not compile.
An uncaught exception is thrown.
12.
What is printed by the following? (Choose all that apply⤀
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 330
The stack trace for a
13.
Which of the following statements are true? (Choose all that apply⤀
You can declare a method with
as the return type.
You can declare any subclass of
in the
part of a method declaration.
You can declare any subclass of
in the
part of a method
declaration.
You can declare any subclass of
in the
part of a method declaration.
You can declare any subclass of
in the
part of a method
declaration.
14.
Which of the following can be inserted on line 8 to make this code compile? (Choose all
that apply⤀
out
15.
Which of the following are unchecked exceptions? (Choose all that apply⤀
Any exception that extends
Any exception that extends
16.
Which scenario is the best use of an exception?
An element is not found when searching a list.
An unexpected parameter is passed into a method.
Review Questions
331
c06.indd 1봀
4/2014 Page 331
The computer caught fire.
You want to loop through a list.
You don’t know how to code a method.
17.
Which of the following can be inserted into
to make this code compile? (Choose all
that apply⤀
Chapter 6
Exceptions
c06.indd 1봀
4/2014 Page 332
None of the above.
20.
What does the output of the following contain? (Choose all that apply⤀
)13: System.out.print("a");14: try {15: System.out.print("b");16: throw new IllegalArgumentException();17: } catch (IllegalArgumentException e) {18: System.out.print("c");19: throw new RuntimeException("1");20: } catch (RuntimeException e) {21: System.out.print("d");22: throw new RuntimeException("2");23: } finally {24: System.out.print("e");25: throw new RuntimeException("3");26: }27: }A. abceB. abdeC. An exception with the message set to
An exception with the message set to
An exception with the message set to
Nothing; the code does not compile.
bapp01.indd 1봀
4/2014 Page 333
Answers to Review
Questions
Appendix
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 334
Chapter 1: Java Building Blocks
A, B, E. Option A is valid because you can use the dollar sign in identifiers. Option B is
valid because you can use an underscore in identifiers. Option C is not a valid identifier
because
is a Java reserved word. Option D is not valid because the dot (.⤀ is not
allowed in identifiers. Option E is valid because Java is case sensitive, so
is not
a reserved word and therefore a valid identifier. Option F is not valid because the first
character is not a letter, $, or _.
D. Boolean fields initialize to
and references initialize to
, so
is
and
is
is output.
B, D, E. Option A (line 4⤀ compiles because
is an integral type. Option B (line
5⤀ generates a compiler error because
is an integral type, but 5.6 is a floating-point
type. Option C (line 6) compiles because it is assigned a
. Options D and E (lines
7 and 8⤀ do not compile because
and
are primitives. Primitives do not allow
methods to be called on them. Option F (line 9⤀ compiles because
is defined
A, B. Adding the variable at line 2 makes
an instance variable. Since instance
variables are in scope for the entire life of the object, option A is correct. Option B is
correct because adding the variable at line 4 makes
a local variable with a scope
of the whole method. Adding the variable at line 6 makes
a local variable with
a scope of lines 6–7. Since it is out of scope on line 8, the
does not compile and
option C is incorrect. Adding the variable at line 9 makes
a local variable with
a scope of lines 9 and 10. Since line 8 is before the declaration, it does not compile and
option D is incorrect. Finally, option E is incorrect because the code can be made to
compile.
C, D. Option C is correct because it imports
by classname. Option D is cor-
rect because it imports all the classes in the
package, which includes
Option A is incorrect because it only imports classes in the
package—
in this case—and not those in lower-level packages. Option B is incorrect because you
cannot use wildcards anyplace other than the end of an import statement. Option E is
incorrect because you cannot import parts of a class with a regular import statement.
Option F is incorrect because options C and D do make the code compile.
E. The first two imports can be removed because
is automatically imported.
The second two imports can be removed because
and
are in the same pack-
age, making the correct answer E. If
and
were in different packages, one of
these two imports could be removed. In that case, the answer would be option D.
A, B, C. Option A is correct because it imports all the classes in the
package
including
. Options B and C are correct because they import
classname. Since importing by classname takes precedence over wildcards, these com-
pile. Option D is incorrect because Java doesn’t know which of the two wildcard
Chapter 1: Java Building Blocks
335
bapp01.indd 1봀
4/2014 Page 335
classes to use. Option E is incorrect because you cannot specify the same classname in
two imports.
B. Option B is correct because arrays start counting from zero and strings with spaces
must be in quotes. Option A is incorrect because it outputs
. C is incorrect because
it outputs
. Option D is incorrect because it outputs
. Options E and F are
incorrect because they output
A, C, D, E. Option A is correct because it is the traditional
method signature
and variables may begin with underscores. Options C and D are correct because the
array operator may appear after the variable name. Option E is correct because
varargs are allowed in place of an array. Option B is incorrect because variables are
not allowed to begin with a digit. Option F is incorrect because the argument must be
an array or varargs. Option F is a perfectly good method. However, it is not one that
can be run from the command line because it has the wrong parameter type.
10.
E. Option E is the canonical
method signature. You need to memorize it.
Option A is incorrect because the
method must be public. Options B and F
are incorrect because the
method must have a
return type. Option C is
incorrect because the
method must be static. Option D is incorrect because the
method must be named
11.
C, D. Option C is correct because all non-primitive values default to
. Option D is
correct because float and double primitives default to
. Options B and E are incor-
rect because
primitives default to
12.
G. Option G is correct because local variables do not get assigned default values. The
code fails to compile if a local variable is not explicitly initialized. If this question
were about instance variables, options D and F would be correct. A
primitive
defaults to
and a
primitive defaults to
13.
A, D. Options A and D are correct because
primitives default to
and
primitives default to
14.
D. The package name represents any folders underneath the current path, which is
in this case. Option B is incorrect because package names are case sensitive,
just like variable names and other identifiers.
15.
A, E. Underscores are allowed as long as they are directly between two other digits.
This means options A and E are correct. Options B and C are incorrect because the
underscore is adjacent to the decimal point. Option D is incorrect because the under-
score is the last character.
16.
B, C, D.
is the prefix for a binary value and is correct.
is the prefix for a hexa-
decimal value. This value can be assigned to many primitive types, including
and
, making options C and D correct. Option A is incorrect because
is a long
value.
would be allowed. Option E is incorrect because the under-
score is immediately before the decimal. Option F is incorrect because the underscore is
the very last character.
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 336
17.
A, E.
is a class, which can be seen from the declaration: public class
is a reference to an object.
is a method.
18.
C, D, E.
and
are both optional. If both are present, the order must
be
, then
, then
. Option A is incorrect because
is before
and
. Option B is incorrect because
is before
. Option
F is incorrect because
is before
. Option G is incorrect because
is
before
19.
B, D. The
object from line 3 has two references to it:
and
. The ref-
erences are nulled out on lines 6 and 8, respectively. Option B is correct because this
makes the object eligible for garbage collection after line 8. Line 7 sets the reference
to the now null
, which means it has no effect on garbage collection. The
object from line 4 only has a single reference to it:
. Option D is correct because
this single reference becomes
on line 9. The
object declared on line 10
becomes eligible for garbage collection at the end of the method on line 12. Calling
has no effect on eligibility for garbage collection.
20.
B, E. Calling
suggests that Java might wish to run the garbage collector.
Java is free to ignore the request, making option E correct.
runs if an object
attempts to be garbage collected, making option B correct.
21.
A. While the code on line 3 does compile, it is not a constructor because it has a return
type. It is a method that happens to have the same name as the class. When the code
runs, the default constructor is called and count has the default value (0) for an
22.
B, E. C++ has operator overloading and pointers. Java made a point of not having
either. Java does have references to objects, but these are pointing to an object that can
move around in memory. Option B is correct because Java is platform independent.
Option E is correct because Java is object oriented. While it does support some parts of
functional programming, these occur within a class.
23.
C, D. Java puts source code in
files and bytecode in
files. It does not use
file. When running a Java program, you pass just the name of the class
without the
extension.
Chapter 2: Operators and Statements
A, D. Option A is the equality operator and can be used on numeric primitives,
values, and object references. Options B and C are both arithmetic operators and
cannot be applied to a
value. Option D is the logical complement operator
and is used exclusively with
values. Option E is the modulus operator, which
can only be used with numeric primitives. Finally, option F is a relational operator that
compares the values of two numbers.
Chapter 2: Operators and Statements
337
bapp01.indd 1봀
4/2014 Page 337
A, B, D. The value
is automatically promoted to
, so
and data types that
can be promoted automatically from
will work. Options A, B, D are such data
types. Option C will not work because
is not a numeric data type. Options E
and F will not work without an explicit cast to a smaller data type.
F. In this example, the ternary operator has two expressions, one of them a
and
the other a
value. The ternary operator is permitted to have expressions that
don’t have matching types, but the key here is the assignment to the
reference.
The compiler knows how to assign the first expression value as a
, but the sec-
expression cannot be set as a
; therefore, this line will not compile.
B, C, D, F. The code will not compile as is, so option A is not correct. The value
is automatically promoted to
and cannot be automatically stored in
, which is
in an
value. Options B, C, and D solve this problem by reducing the
value to
. Option E does not solve the problem and actually makes it worse by attempting
to place the value in a smaller data type. Option F solves the problem by increasing the
data type of the assignment so that
is allowed.
C. This code does not contain any compilation errors or an infinite loop, so options D,
E, and F are incorrect. The
statement on line 8 causes the loop to execute once
and finish, so option C is the correct answer.
F. The code does not compile because two
statements cannot be chained together
without additional
statements, so the correct answer is option F. Option E is
incorrect as Line 6 by itself does not cause a problem, only when it is paired with Line
7. One way to fix this code so it compiles would be to add an
statement on
line 6. The other solution would be to remove line 7.
D. As you learned in the sectio渠贀Ternary Operator,踀 although parentheses are not
required, they do greatly increase code readability, such as the following equivalent
statement:
We apply the outside ternary operator 
rst, as it is possible the inner ternary expression
may never be evaluated. Since
is
, this reduces the problem to:
Since
is greater than
, the answer is
, or option D in this case.
B. This example is tricky because of the second assignment operator embedded in line
5. The expression
assigns the value
and returns
for the
entire expression. Since
does not equal
, the left-hand side returns
; therefore,
the exclusive or (
) of the entire expression assigned to
is
. The output reflects
these assignments, with no change to
, so option B is the only correct answer. The
code compiles and runs without issue, so option F is not correct.
F. In this example, the update statement of the
loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop incre-
ments
but then assigns
the old value. Therefore,
ends the loop with the same value
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 338
that it starts with:
. The loop will repeat infinitely, outputting the same statement over
and over again because
remains
after every iteration of the loop.
10.
D. Line 4 generates a possible loss of precision compiler error. The
operator has
the highest precedence, so it is evaluated first, casting
to a byte. Then, the addition is
evaluated, causing both
and
to be promoted to
values. The value
is an
and cannot be assigned to the
without an explicit cast, so the code does not
compile. The code could be corrected with parentheses around
, in which case
option C would be the correct answer.
11.
A. The
and
have the same operator precedence, so the expression is evaluated
from left-to-right. The result of
is
, and
is
divided by
is
, the
remainder is
⤀. The output is
and option A is the correct answer.
12.
D. The variable
is an
and
is a reference to a
object. The two data types
are incomparable because neither variable can be converted to the other variab汥’s type.
The compiler error occurs on line 5 when the comparison is attempted, so the answer
is option D.
13.
A. The code compiles successfully, so options C and D are incorrect. The value of
after line 4 is
. However, the
statement on line 5 contains an assignment,
not a comparison. The variable
is assigned
on line 3, and the assignment opera-
tor returns
, so line 5 executes and displays
, so the answer is option A.
14.
C. The code compiles successfully, so option F is incorrect. On line 5, the pre-incre-
ment operator is used, so
is incremented to
and the new value is returned to the
expression. The value of
is computed by adding
to the original value of
resulting in a new value of
, which is output on line 6. Therefore, option C is the
correct answer.
15.
E. This is actually a much simpler problem than it appears to be. The
statement
on line 4 is missing parentheses, so the code will not compile, and option E is the cor-
rect answer. If the parentheses were added, though, option F would be the correct
answer since the loop does not use curly braces to include
and the
expres-
sion never changes. Finally, if curly braces were added around both expressions, the
output would be
and option B would be correct.
16.
D. The variable
is declared within the body of the
statement, so it is out of
scope on line 6. Line 6 generates a compiler error, so option D is the correct answer.
17.
D. The code compiles without issue, so option F is incorrect. After the first execu-
tion of the loop,
is decremented to
and
. Since
is not 8,
is
, and the loop continues. On the next iteration,
is decremented to
and
. On the second execution,
does equal
, so
is set to
. At the
conclusion of the loop, the loop terminates since
is no longer
. The
value of
is
, and the correct answer is option D.
18.
A. The expression on line 5 is
is an even number. On the first
iteration,
and
, so the expression on line 6 is
, the
is
skipped, and
is incremented to
. On the second iteration,
and
Chapter 3: Core Java APIs
339
bapp01.indd 1봀
4/2014 Page 339
, so the expression on line 6 is
and the
ends the outer loop with
still at
. On the third iteration,
and
, so the expression on line
6 is
and the
ends the outer loop with
still at
. On the fourth
iteration,
and
, so the expression on line 6 is
, the
is
skipped, and
is incremented to
. Finally, on the fifth and final iteration,
and
, so the expression on line 6 is
and the
ends the outer
loop with
still at
. The result of
is displayed, so the answer is option B.
19.
D. Prior to the first iteration,
, and
. After the iteration of the first
loop,
is updated to
, and
to the sum of the new values for
. After the iteration of the second loop,
is updated to
, and
to the sum
of the new values for
. After the iteration of the third loop,
is
updated to
, and
to the sum of the new values for
. On
the fourth iteration of the loop,
evaluates to
, as
is not
. The
loop ends and the most recent value of
, is output, so the correct answer is option
20.
B. The code compiles and runs without issue, so options C, D, and E are not correct. The
value of
is
and there is a matching
statement that will cause
to
be printed. There is no
statement after the
, though, so the next
state-
ment will be reached, and
will be printed. There is a
after this
state-
ment, though, so the
statement will end. The correct answer is thus option B.
Chapter 3: Core Java APIs
G. Line 5 does not compile. This question is checking to see if you are paying attention
to the types.
is an
and
is an
. Therefore, we use numeric addition and
get 5. The problem is that we can’t store an
in a
variable. Supposing line 5
said
. In that case, the answer would be
options A and D. The variable defined on line 5 would be the string
, and both out-
put statements would use concatenation.
A, C, D. The code compiles fine. Line 3 points to the
in the string pool. Line 4
calls the
constructor explicitly and is therefore a different object than
. Lines 5
and 7 check for object equality, which is true, and so print
and
. Line 6 uses
object reference equality, which is not true since we have different objects. Line 7 also
compares references but is true since both references point to the object from the string
pool. Finally, line 8 compares one object from the string pool with one that was explic-
itly constructed and returns
B, C, E. Immutable means the state of an object cannot change once it is created.
Immutable objects can be garbage collected just like mutable objects.
is immu-
table.
can be mutated with methods like
. Although
340
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 340
isn’t on the exam, you should know about it anyway in case older ques-
tions haven’t been removed.
B. This example uses method chaining. After the call to
contains
That result is passed to the first
call, which inserts at index 1. At this point
contains
. That result is passed to the final
, which inserts at index
4, resulting in
F. The question is trying to distract you into paying attention to logical equality versus
object reference equality. It is hoping you will miss the fact that line 4 does not com-
pile. Java does not allow you to compare
and
using
B. A
is immutable. Calling
returns a new
but does not change
the original. A
is mutable. Calling
adds characters to the
existing character sequence along with returning a reference to the same object.
B, D, E.
is simply a count of the number of characters in a
. In this
case, there are six characters.
returns the character at that index. Remember
that indexes are zero based, which means that index 3 corresponds to
and index 6
corresponds to 1 past the end of the array. A
is
thrown for the last line.
A, D, E.
has two forms. The first takes the index to start with and the
index to stop immediately before. The second takes just the index to start with and
goes to the end of the
. Remember that indexes are zero based. The first call
starts at index 1 and ends with index 2 since it needs to stop before index 3. The sec-
ond call starts at index 7 and ends in the same place, resulting in an empty
This prints out a blank line. The final call starts at index 7 and goes to the end of the
C. This question is trying to see if you know that
objects are immutable. Line
4 returns
but the result is ignored and not stored in
. Line 5 returns
since there is no whitespace present but the result is again ignored. Line 6 returns
because it starts with index 1 and ends before index 3 using zero-based indexes. The
result is ignored again. Finally, on line 6 something happens. We concatenate four new
characters to
and now have a
of length 8.
10.
F.
expands to
concatenated with any other type gives
. Lines 14, 15, and 16 all append to
, giving a result of
. The
statement on line 18 returns
because the values of the two
objects are the
same using object equality. The
statement on line 17 returns
because the two
objects are not the same in memory. One comes directly from the string pool
and the other comes from building using
operations.
11.
E. Line 6 adds 1 to
because
includes the starting index but not
the ending index. Line 7 adds 0 to
. Line 8 is a problem: Java does not allow the
indexes to be specified in reverse order and the code throws a
Chapter 3: Core Java APIs
341
bapp01.indd 1봀
4/2014 Page 341
12.
A. First, we delete the characters at index 2 until the character one before index 8. At
this point, 0189 is in
. The following line uses method chaining. It appends a
dash to the end of the characters sequence, resulting in
, and then inserts a plus
sign at index 2, resulting in
13.
F. This is a trick question. The first line does not compile because you cannot
assign a
. If that line were
, the code would compile and print
. Watch out for this
sort of trick on the exam. You could easily spend a minute working out the character
positions for no reason at all.
14.
A, C. The
method is the easiest way of reversing the characters in a
; therefore, option A is correct. Option B is a nice distraction—it does in fact
return
. However,
returns a
, which is not stored anywhere.
Option C uses method chaining. First it creates the value
. Then it removes
the first three characters, resulting in
. Finally, it removes the last character,
resulting in
. Option D throws an exception because you cannot delete the char-
acter after the last index. Remember that
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 342
23.
A. Line 4 creates a fixed size array of size 4. Line 5 sorts it. Line 6 converts it back to
an array. The brackets aren’t in the traditional place, but they are still legal. Line 7
prints the first element, which is no眠–1.
C. Converting from an array to an
uses
. There is
no
method on an array instance. If this code were corrected to compile, the
answer would be option A.
25.
D. After sorting,
contains
. Remember that numbers sort before
letters and strings sort alphabetically. This makes 30 come before 8. A binary search
correctly finds 8 at index 2 and 3A at index 1. It cannot find 4F but notices it should
be at index 2. The rule when an item isn’t found is to negate that index and subtract 1.
Therefore, we ge琠–2–1, which is₅3.
A, B, D. Lines 5 and 7 use autoboxing to convert an
to an
. Line 6 does
not because
returns an
. Line 8 does not because
is not an
The code does not compile. However, when the
loop tries to unbox
into an
, it fails and throws a
27.
B. The first
statement is false because the variables do not point to the same object.
The second
statement is true because
implements equality to mean the
same elements in the same order.
D, F. Options A and B are incorrect because
does not have a public con-
structor. Option C is incorrect because months start counting with 1 rather than 0.
Option E is incorrect because it uses the old pre–Java 8 way of counting months, again
beginning with 0. Options D and F are both correct ways of specifying the desired
date.
29.
D. A
does not have a time element. Therefore, it has no method to add
hours and the code does not compile.
30.
F. Java throws an exception if invalid date values are passed. There is no 40th day in
April—or any other month for that matter.
B. The date starts out as April 30, 2018. Since dates are immutable and the plus meth-
ods have their return values ignored, the result is unchanged. Therefore, option B is
correct.
32.
E. Even though
has both date and time, the formatter only outputs time.
33.
B.
does not allow chaining. Only the last
method called counts, so only
the two years are subtracted.
Chapter 4: Methods and Encapsulation
B, C.
is a return type. Only the access modifier or optional specifiers are allowed
before the return type. Option C is correct, creating a method with private access.
Option B is correct, creating a method with default access and the optional specifier
. Since default access does not require a modifier, we get to jump right to
Chapter 4: Methods and Encapsulation
343
bapp01.indd 1봀
4/2014 Page 343
Option A is incorrect because default access omits the access modifier rather than spec-
ifying default. Option D is incorrect because Java is case sensitive. It would have been
correct if
were the choice. Option E is incorrect because the method already has
return type. Option F is incorrect because labels are not allowed for methods.
A, D. Options A and D are correct because the optional specifiers are allowed in any
order. Options B and C are incorrect because they each have two return types. Options
E and F are incorrect because the return type is before the optional specifier and access
modifier, respectively.
A, C, D. Options A and C are correct because a
method is allowed to have a
return statement as long as it doesn’t try to return a value. Options B and G do not
compile because
requires a reference object as the return type.
is not a refer-
ence object since it is a marker for no return type.
is not a reference object since it
is a primitive. Option D is correct because it returns an
value. Option E does not
compile because it tries to return a
when the return type is
. Since a
cannot be assigned to an
, it cannot be returned as one either. Option F does not
compile because no value is actually returned.
A, B, G. Options A and B are correct because the single vararg parameter is the last
parameter declared. Option G is correct because it doesn’t use any vararg parameters
at all. Options C and F are incorrect because the vararg parameter is not last. Option
D is incorrect because two vararg parameters are not allowed in the same method.
Option E is incorrect because the
for a vararg must be after the type, not before it.
D, G. Option D passes the initial parameter plus two more to turn into a vararg array
of size 2. Option G passes the initial parameter plus an array of size 2. Option A does
not compile because it does not pass the initial parameter. Options E and F do not
compile because they do not declare an array properly. It should be
{true}. Option B creates a vararg array of size 0 and option C creates a vararg array of
size 1.
D. Option D is correct. This is the common implementation for encapsulation by set-
ting all fields to be private and all methods to be public. Option A is incorrect because
protected access allows everything that package private access allows and additionally
allows subclasses access. Option B is incorrect because the class is public. This means
that other classes can see the class. However, they cannot call any of the methods or
read any of the fields. It is essentially a useless class. Option C is incorrect because
package private access applies to the whole package. Option E is incorrect because Java
has no such capability.
B, C, D, F. The two classes are in different packages, which means private access and
default (package private⤀ access will not compile. Additionally, protected access will
not compile since
does not inherit from
. Therefore, only line 8 will
compile because it uses public access.
B, C, E. Encapsulation requires using methods to get and set instance variables so
other classes are not directly using them. Instance variables must be private for this
to work. Immutability takes this a step further, allowing only getters, so the instance
variables do not change state.
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 344
C, E. Option A is incorrect because the property is of type
and getters must
begin with
s. Options B and D are incorrect because they don’t follow
the naming convention of beginning with
Chapter 4: Methods and Encapsulation
bapp01.indd 1봀
4/2014 Page 345
caller have a reference to the same object. Finally, returning a value does pass the refer-
ence to the caller for assignment to
18.
C, G. Since the
method is in the same class, it can call
methods in the
class.
may only be called as the first line of a constructor.
can be called from any instance method to refer to an instance variable. It cannot be
called from a static method because there is no instance of the class to refer to. Option
F is tricky. The default constructor is only written by the compiler if no user-defined
constructors were provided.
can only be called from a constructor in the same
class. Since there can be no user-defined constructors in the class if a default construc-
tor was created, it is impossible for option F to be true.
19.
A, G. Options B and C don’t compile because the constructor name must match the
classname. Since Java is case sensitive, these don’t match. Options D, E, and F all com-
pile and provide one user-defined constructor. Since a constructor is coded, a default
constructor isn’t supplied. Option G defines a method, but not a constructor. Option A
does not define a constructor, either. Since no constructor is coded, a default construc-
tor is provided for options A and G.
20.
E. Options A and B will not compile because constructors cannot be called without
. Options C and D will compile but will create a new object rather than setting the
fields in this one. Option F will not compile because
must be the first line of a
constructor. Option E is correct.
21.
C. Within the constructor
numSpots
refers to the constructor parameter. The instance
variable is hidden because they have the same name.
this.numSpots
tells Java to use
the instance variable. In the
method,
numSpots
refers to the instance variable.
Option A sets the constructor parameter to itself, leaving the instance variable as 0.
Option B sets the constructor parameter to the value of the instance variable, making
them both 0. Option C is correct, setting the instance variable to the value of the con-
structor parameter. Options D and E do not compile.
22.
E. On line 3 of
for the first time. At this point the stat-
ics in
get initialized. In this case, the statics are the
declaration of
result
and the
initializer.
result
is
at this point. On line 4,
result
is the same
because the
initialization is only run once. On line 5, we create a new
which triggers the instance initializers in the order they appear in the file. Now
result
is
. Line 6 creates another
, triggering another set of initializers. Now
result
is
. Notice how the
is on a different line than the initialization code in
lines 4–5 of
. The exam may try to trick you by formatting the code like this to
confuse you.
23.
A. Line 4 instantiates an
. Java runs the declarations and instance initializers first
in the order they appear. This sets
value
. Line 5 creates another
and
initializes
value
. The object on line 5 is stored in the same variable line 4 used.
This makes the object created on line 4 unreachable. When
value
is printed, it is the
instance variable in the object created on line 5.
346
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 346
B, C, E.
value1
is a
instance variable. It can only be set once: in the variable dec-
laration, an instance initializer, or a constructor. Option A does not compile because
the
variable was already set in the declaration.
value2
is a
variable. Both
instance and static initializers are able to access
variables, making options B
and E correct.
value3
is an instance variable. Options D and F do not compile because
initializer does not have access to instance variables.
25.
A, E. The
parameter is an
and so calls the matching
constructor. When
this constructor is removed, Java looks for the next most specific constructor. Java pre-
fers autoboxing to varargs, and so chooses the
constructor. The
param-
eter is a
. Since it can’t be converted into a smaller type, it is autoboxed into a
and then the constructor for
is called.
A. This code is correct. Line 8 creates a lambda expression that checks if the age is less
than 5. Since there is only one parameter and it does not specify a type, the parentheses
around the type parameter are optional. Line 10 uses the
interface, which
declares a
method.
27.
C. The interface takes two
parameters. The code on line 7 attempts to use them as
if one is a
. It is tricky to use types in a lambda when they are implicitly
specified. Remember to check the interface for the real type.
A, D, F.
expects a
, which takes a parameter list of one param-
eter using the specified type. Options B and C are incorrect because they do not use the
Chapter 5: Class Design
347
bapp01.indd 1봀
4/2014 Page 347
A, B, D, E. The blank can be filled with any class or interface that is a supertype of
. Option A is a superclass of
, and option B is the same class,
so both are correct.
is not a superclass of
, so option
C is incorrect.
inherits the
interface, so option D is correct. All
classes inherit
, so option E is correct. Finally,
is an unrelated class that is
not a superclass of
, and is therefore incorrect.
C, E. The code doesn’t compile, so option A is incorrect. Option B is also not correct
because the rules for overriding a method allow a subclass to define a method with an
exception that is a subclass of the exception in the parent method. Option C is cor-
rect because the return types are not covariant; in particular,
is not a subclass
of
. Option D is incorrect because the subclass defines a method that is more
accessible than the method in the parent class, which is allowed. Finally, option E is
correct because the method is declared as
in the parent class and not so in the
child class. For nonprivate methods in the parent class, both methods must use
(hide⤀ or neither should use
(override⤀.
A, D, E, F. First off, options B and C are incorrect because protected and public meth-
ods may be overridden, not hidden. Option A is correct because private methods are
always hidden in a subclass. Option D is also correct because static methods cannot
be overridden, only hidden. Options E and F are correct because variables may only be
hidden, regardless of the access modifier.
D. The code fails to compile because
348
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 348
A. Although the definition of methods on lines 2 and 5 vary, both will be converted to
by the compiler. Line 4 is fine, because an interface can have
or default access. Finally, the class
doesn’t need to implement the interface
methods because it is marked as
. Therefore, the code will compile without
issue.
10.
B, C, E, F. Option A is wrong, because an abstract class may contain concrete meth-
ods. Since Java 8, interfaces may also contain concrete methods in form of static or
default methods. Although all variables in interfaces are assumed to be
, abstract classes may contain them as well, so option B is correct. Both abstract
classes and interfaces can be extended with the
keyword, so option C is cor-
rect. Only interfaces can contain default methods, so option D is incorrect. Both
abstract classes and interfaces can contain static methods, so option E is correct. Both
structures require a concrete subclass to be instantiated, so option F is correct. Finally,
though an instance of an object that implements an interface inherits
, the interface itself doesn’t; otherwise, Java would support multiple inheritance
for objects, which it doesn’t. Therefore, option G is incorrect.
11.
A, D, E. Interface variables are assumed to be
; therefore, options
A, D, and E are correct. Options B and C are incorrect because interface variables must
be public—interfaces are implemented by classes, not inherited by interfaces. Option F
is incorrect because variables can never be abstract.
12.
B. This code compiles and runs without issue, outputting
, so option B is the
correct answer. The first declaration of
is as a default interface method,
assumed
. The second declaration of
correctly overrides the default
interface method. Finally, the newly created
instance may be automatically cast to
reference without an explicit cast, although adding it doesn’t break the
13.
A. The code compiles and runs without issue, so options E and F are incorrect. The
method is an overload in
, not an override, so both methods may
be called. The call on line 8 references the version that takes an
as input defined
in the
class, and the call on line 9 references the version in the
class
that takes a
. Therefore,
is output and option A is the correct
answer.
14.
C. The code compiles without issue, so option A is wrong. Option B is incorrect, since
an abstract class could implement
without the need to override the
method. Option C is correct; any class that implements
auto-
matically inherits its methods, as well as any inherited methods defined in the parent
interface. Because option C is correct, it follows that option D is incorrect. Finally, an
interface can extend multiple interfaces, so option E is incorrect.
15.
B. Concrete classes are, by definition, not abstract, so option A is incorrect. A concrete
class must implement all inherited abstract methods, so option B is correct. Option C
is incorrect; a superclass may have already implemented an inherited interface, so the
concrete subclass would not need to implement the method. Concrete classes can be
both
and not
, so option D is incorrect. Finally, abstract methods must be
overridden by a concrete subclass, so option E is incorrect.
Chapter 6: Exceptions
bapp01.indd 1봀
4/2014 Page 349
16.
E. The code doesn’t compile, so options A and B are incorrect. The issue with line 9 is
that
is marked as
in the superclass
, which means it cannot be
overridden. There are no errors on any other lines, so options C and D are incorrect.
17.
B. This may look like a complex question, but it is actually quite easy. Line 2 contains
an invalid definition of an abstract method. Abstract methods cannot contain a body,
so the code will not compile and option B is the correct answer. If the body
was
removed from line 2, the code would still not compile, although it would be line 8 that
would throw the compilation error. Since
in
is abstract and
extends
, then it must implement an overridden version of
. The method on line
9 is an overloaded version of
, not an overridden version, so
is an invalid
subclass and will not compile.
18.
E. The code doesn’t compile because line 6 contains an incompatible override of the
350
Appendix A
Answers to Review Questions
bapp01.indd 1봀
4/2014 Page 350
B. The second line tries to cast an
. Since
does not extend
, this is not allowed and a
is thrown.
A, B, D.
is thrown by many methods in the
package,
but it is always thrown programmatically. The same is true for
; it is thrown programmatically by the wrapper classes of
. The other
three exceptions are all thrown by the JVM when the corresponding problem arises.
C. The compiler tests the operation for a valid type but not a valid result, so the code
will still compile and run. At runtime, evaluation of the parameter takes place before
passing it to the
method, so an
Chapter 6: Exceptions
351
bapp01.indd 1봀
4/2014 Page 351
13.
A, B, C, E. Classes listed in the
part of a method declaration must extend
. This includes
, and
. Arbi-
trary classes such as
can’t go there. Any Java type, including
, can
be declared as the return type. However, this will simply return the object rather than
throw an exception.
14.
A, C, D, E. A method that declares an exception isn’t required to throw one, making
option A correct. Runtime exceptions can be thrown in any method, making options
C and E correct. Option D matches the exception type declared and so is also correct.
Option B is incorrect because a broader exception is not allowed.
15.
A, B, D, E.
, and
are runtime exceptions. Sorry, you have to memorize them. Any
class that extends
is a runtime (unchecked) exception. Classes that
extend
but not
are checked exceptions.
16.
B.
is used when an unexpected parameter is passed into a
method. Option A is incorrect because returning
is a common return value
for this scenario. Option D is incorrect because a
loop is typically used for this
scenario. Option E is incorrect because you should find out how to code the method
and not leave it for the unsuspecting programmer who calls your method. Option C is
incorrect because you should run!
17.
A, C, D, E. The method is allowed to throw no exceptions at all, making option A cor-
rect. It is also allowed to throw runtime exceptions, making options D and E correct.
Option C is also correct since it matches the signature in the interface.
18.
A, B, C, E. Checked exceptions are required to be handled or declared. Runtime
exceptions are allowed to be handled or declared. Errors are allowed to be handled or
declared, but this is bad practice.
19.
C, E. Option C is allowed because it is a more specific type than
Option E is allowed because it isn’t in the same inheritance tree as
. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the
block doesn’t declare an
to be thrown. The
compiler realizes that
would be an unreachable
block. Option D
is not allowed because the same exception can’t be specified in two different
blocks. Finally, option A is not allowed because it’s more general than
and would make that block unreachable.
20.
A, E.
The code begins normally and prints
on line 13, followed by
on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most spe-
cific matching
is run. Line 18 prints
, and then line 19 throws another excep-
tion. Regardless, the
block runs, printing
. Since the
block also
throws an exception, that’s the one printed.
bapp02.indd 1봀
4/2014 Page 353
Study Tips
Appendix
bapp02.indd 1봀
4/2014 Page 354bapp02.indd 1봀
4/2014 Page 354
This appendix covers suggestions and recommendations for
how you should prepare for the certi■
cation exam. If you’re
an experienced test taker, or you’ve taken a certi■
cation test
before, most of this should be common knowledge. For those who are taking the exam for
th攠■
rst time, don’t panic! We’ll present a number of tips and strategies in this appendix to
help you prepare for the exam.
Studying for the Test
Before you even sign up and take the test, you need to study the material. Studying includes
the following tasks:
Create a study plan.
Read the Study Guide material.
Create and run sample applications.
Solve the Review Questions at the end of each chapter.
Create flashcards and/or use the ones weve provided.
Take the three practice exams.
The book is divided into chapters with corresponding exam objectives, to make it easier
to assimilate. The earlier chapters on syntax and operators are especially important since
they are used throughout the code samples on the exam. Unless we explicitly stated some-
thing was out of scope for the exam, you will be required to have a strong understanding of
all the information in this book.
Creating a Study Plan
Rome wasn’t built in a day, so you shouldn’t attempt to study for only one day. Even if you
have been certi■
ed with a previous version of Java, the new test includes features and com-
ponents unique to Java 8 that are covered in this text.
Once you have decided to take the test, which we assume you have already since you’re
reading this book, you should construct a study plan that 
ts with your schedule. We rec-
ommend you set aside some amount of time each day, even if it’s just a few minutes during
lunch, to read or practice for the exam. The idea is to keep your momentum going through-
out the exam preparation process. The more consistent you are in how you study, the better
prepared you will be for the exam. Try to avoid taking a few days or weeks off from study-
ing, or you’re likely to spend a lot of time relearning existing material instead of moving on
to new material.
Studying for the Test
bapp02.indd 1봀
4/2014 Page 355
Let’s say you begin studying on January 1. Assuming you allot two weeks per chapter,
we constructed a study plan in Table B.1 that you can use as a schedule throughout the
study process. Of course, if you’re new to Java, two weeks per chapter may not be enough;
if you’re an experienced Java developer, you may only need a few days per chapter.
TABLE B.1
Sample study plan
Date
Task
January 1…January 11Read Introduction, Appendix B, and Chapter 1
January 12–January 14Answer Chapter 1 Review Questions
January 15–January 25Read Chapter 2
January 26–January 28Answer Chapter 2 Review Questions
January 29–February 8Read Chapter 3
February 9–February 11Answer Chapter 3 Review Questions
February 12–February 22Read Chapter 4
February 23–February 25Answer Chapter 4 Review Questions
February 26–March 8Read Chapter 5
March 9–March 11Answer Chapter 5 Review Questions
March 12–March 22Read Chapter 6
March 23–March 25Answer Chapter 6 Review Questions
March 26–April 2Take practice exams and practice with flashcards
April 3Take exam
Your own study plan will vary based on your familiarity with Java, your personal and
work schedule, and your learning abilities. The idea is to create a plan early on that has
self-imposed deadlines that you can follow throughout the studying process. When some-
one asks how you’re doing preparing for the exam, you should have a strong sense of what
you’ve learned so far, what you’re currently studying, and how many weeks you need to be
prepared to the take the exam.
Creating and Running Sample Applications
Although some people can learn Java just by reading a textbook, that’s not how we recom-
mend you study for a certi■
cation exam. We want you to be writing your own Java sample
356
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 356
applications throughout this book so that you don’t just learn the material but you also
understand the material. For example, it may not be obvious why the following line of code
does not compile, but if you try to compile it yourself, the Java compiler will tell you the
problem.
float value = 102.0; // DOES NOT COMPILE
In this section, we will discuss how to test Java code and the tools available to assist you
in this process.
A lot of people post on the CodeRanch.com forum askingⰠ贀Why does this
code not compile?踠and we encourage you to post the compiler error mes-
sage anytime you need help. We recommend you also read the compiler
message when posting, since it may provide meaningful information about
why the code failed to compile.
In the previous example, the compiler failed to compile with the message
. This mes-
sage indicates that we are trying to convert a
value,
, to a
variable reference using an implicit cast. If we add an explicit cast
to
or change the value to
, the code will compile without
issue.
Sample Test Class
Throughout this book, we present numerous code snippets and ask you whether they’ll
compile and what their output will be. These snippets are designed to be placed inside
a simple Java application that starts, executes the code, and terminates. As described in
Chapter 1,₍Java Building Blocks,踀 you can accomplish this by compiling and running a
public class containing a
) method, such as the
following:
) // Add test code here // Add any print statements here System.out.println("Hello World!"); }}This application isn’t particularly interesting—it just output猠贀
踠and exits.
That said, we can insert many of the code snippets present in this book in the
method to determine if the code compiles, as well as what the code outputs when it does
compile. We strongly recommend you become familiar with this sample application, so
much so that you could write it from memory, without the comments.
Studying for the Test
357
bapp02.indd 1봀
4/2014 Page 357
We recommend that while reading this book you make note of any sections that you
do not fully understand and revisit them when in front of a computer screen with a Java
compiler and Java runtime. You should start by copying the code snippet into your test
class, and then try experimenting with the code as much as possible. For example, we indi-
cated the previous sample line of code would not compile, but would any of the following
compile?
Try out these samples on your computer and see if the result matches your expectation.
He牥’s a hint: Two of thes攠■
ves lines will not compile.
IDE Software
While studying for the exam, you should develop code using a text editor and command-
line Java compiler. Some of you may have existing experience with Integrated Develop-
ment Environments (IDEs⤀ such as Eclipse or IntelliJ. An IDE is a software application that
facilitates software development for computer programmers.
Although such tools are extremely valuable in developing software, they can interfere
with your ability to readily spot problems on the exam. For example, when a line code
does not compile, the IDE will often underline it in red, whereas on the exam, you’ll have
toₓ
nd the line that does not compile, if there is one, on your own.
If you do choose to study with an IDE, make sure you understand everything it is doing in
the background for you. For the exam, you’ll need to know how to manually compile code
from the command line, and this experience is rarely learned using an IDE. You’ll also
need to understand why the code does not compile without relying on the tips and sug-
gestions provided by the IDE.
Identifying Your Weakest Link
The best advice we can give you to do well on the exam is to practice writing sample appli-
cations that push the limits of what you already know, as much and as often as possible.
For example, if the previous samples with
values were too dif■
cult for you, then you
should spend even more time studying numeric promotion and casting expressions.
Prior to taking the OCA exam, you may already be an experienced Java developer,
but there is a difference between being able to write Java code and being a certi■
ed Java
358
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 358
developer. For example, you might go years without writing a ternary expression or using
an abstract class, but that does not mean they are not important features of the Java lan-
guage. You may also be unaware of some of the more complex features that exist within
the Java language. On top of that, there are new features to Java 8, such as lambda expres-
sions and default interface methods, which as of this writing very few professional software
developers are using.
The Review Questions in each chapter are designed to help you hone in on those fea-
tures of the Java language that you may be weak in and that are required knowledge for the
exam. For each chapter, you should note which questions you got wrong, understand why
you got them wrong, and study those areas even more.
Often, the reason you got a question wrong on the exam is that you did not fully under-
stand the concept. Many topics in Java have subtle rules that you often need to see for
yourself to truly understand. For example, you cannot write a class that implements two
interfaces that de■
ne the same default method unless you override the default method in the
class. Writing and attempting to compile your own sample interfaces and classes that refer-
ence the default method may illuminate this concept far better than we could ever explain it.
Finally, we 
nd developers who practice writing code while studying for the Java certi-
cation tend to write better Java code in their professional career. Anyone can write a Java
class that can compile, but just because a class compiles does not mean it is well designed.
For example, imagine a class where all class methods and variables were declared
simply because the developer did not understand the other access modi■
ers, such as
and
. Studying for the certi■
cation helps you to learn those features that
may be applicable in your daily coding experience but that you never knew existed within
the Java language.
贀Overstudying踀 Practice Exams
Although we recommend reading this book and writing your own sample applications
multiple times, redoing practice exams over and over can have a negative impact in the
long run. For example, some individuals study the practice exam questions so much that
they end up memorizing them. In this scenario, they can easily become overconfi
dent—
they can achieve perfect scores on the practice exams but may fail on the actual exam.
If you get a practice exam question correct, you should move on, and if you get it incor-
rect you should review the part of the chapter that covers it until you can answer it cor-
rectly. Remember that for legal reasons the practice exam questions are not real exam
questions, so it is important you learn the material the questions are based on.
On the other hand, we recommend you repeat Review Questions as often as you like to
master a chapter. Review Questions are designed to teach you important concepts in the
chapter, and you should understand them completely before leaving a section. Further-
more, they help improve your ability to recognize certain types of problems present in
many code snippets.
Taking the Test
bapp02.indd 1봀
4/2014 Page 359
Taking the Test
Studying how to take a test can be just as important as the studying the material itself. For
example, you could answer every question correctly, but only make it halfway through the
exam, resulting in a failing score! If you’re not historically a good test taker, or you’ve never
taken a certi■
cation exam before, we recommend you read this section because it contains
notes that are relevant to many software certi■
cation exams.
Understanding the Question
The majority of questions on the exam will contain code snippets and ask you to answer
questions about them. For those containing code snippets, the number one question we rec-
ommend you answer before attempting to solve the question is:
Does the code compile?
It sounds simple but many people dive into answering the question without checking
whether or not the code actually compiles. If you can determine whether or not a particular
set of code compiles, and what line or lines cause it to not compile, answering the question
often becomes easy.
Checking the Answers
To determine whether the code will compile, you should brie.
y review the answer choices
to see what options are available. If there are no choices of the form₍Code does not com-
pile,踀 then you can be reasonably assured all the lines of the code will compile and you do
not need to spend time checking syntax. These questions are often, but not always, among
the easiest questions because you can skip determining whether the code compiles and
instead focus on what it does.
If the answer choices do include some answers of the form₍Does not compile due to line
5,踠you should immediately focus on those lines and determine whether they compile. For
example, take a look at the answer choices for the following question:
18.
What is the output of the following code?
- Code Omitted -
The code does not compile due to line 4.
The code does not compile due to line 6.
The answer choices act as a guide instructing you to focus on line 4 or 6 for compila-
tion errors. If the question indicates only one answer choice is allowed, it also tells you at
most only one line of code contains a compilation problem and the other line is correct.
Although the reason line 4 or 6 may not compile could be related to other lines of code, the
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 360
key is that those other lines do not throw compiler errors themselves. By quickly browsing
the list of answers, you can save time by focusing only on those lines of code that are pos-
sible candidates for not compiling.
If you are able to identify a line of code that does not compile, you will be able to 
nish
the question a lot quicker. Often, the most dif■
cult questions are the ones where the code
does in fact compile, but one of the answer choices is₍Does not compile踀 without indicat-
ing any line numbers. In these situations, you will have to spend extra time verifying that
each and every line compiles. If they are taking too much time, we recommend marking
these for ReviewŽ and coming back to them later.
Determining What the Question Is Asking
A lot of times, a question may appear to be asking one thing but will actually be asking
another. For example, the following question may appear to be asking about method over-
loading and abstract classes:
12.
What is the output of the following code?
Taking the Test
361
bapp02.indd 1봀
4/2014 Page 361
Use a similar strategy when a question asks which single line will not compile. If you’re
able to determine the line that does not compile with some degree of con■
dence, you
can use the remaining code that you know does compile as a guide to help answer other
questions.
By using context clues of other questions on the exam, you may be able to more easily
solve questions that you are unsure about.
Reviewing Common Compiler Issues
The following is a brief list of common things to look for when trying to determine whether
code compiles. Bear in mind that this is only a partial list. We recommend you review each
chapter for a comprehensive list of reasons that code will not compile. Also, if you have not
nished reading the book, you should set aside this list and return to it when you are pre-
paring to take the exam.
Common Tips to Determine if Code Compiles:
Keep an eye out for all reserved words. [Chapter 1]
Verify brackets—
葡nd parenthese玄
—are being used correctly. [Chapter 1]
Verify
is used appropriately for creating objects. [Chapter 1]
Ignore all line indentation especially with
statements that do not use brackets
. [Chapter 2]
Make sure operators use compatible data types, such as the logical complement opera-
) only applied to
values, and arithmetic operators (
) only
applied to numeric values. [Chapter 2]
For any numeric operators, check for automatic numeric promotion and order or oper-
ation when evaluating an expression. [Chapter 2]
Verify
statements use acceptable data types. [Chapter 2]
Remember
is not the same as
. [Chapter 3]
values are immutable. [Chapter 3]
Non-
methods must return a value that matches or is a subclass of the return type
of the method. [Chapter 4]
If two classes are involved, make sure access modifiers allow proper access of variables
and methods. [Chapter 4]
Nonstatic methods and variables require an object instance to access. [Chapter 4]
If a class is missing a default no-argument constructor or the provided constructors do
not explicitly call
, assume the compiler will automatically insert them.
[Chapter 5]
Make sure abstract methods do not define an implementation, and likewise concrete
methods always define an implementation. [Chapter 5]
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 362
You implement an interface and extend a class. [Chapter 5]
A class can be cast to a reference of any superclass it inherits from or interface it imple-
ments. [Chapter 5]
Checked exceptions must be caught; unchecked exceptions may be caught but do not
need to be. [Chapter 6]
blocks require a
and/or
block for the OCA exam. [Chapter 6]
We have listed the chapter each tip is found in so that you can go back and review any
that you do not fully understand. Once you’ve determined that the code does in fact com-
pile, proceed with tracing the application logic and trying to determine what the code actu-
ally does.
Applying Process of Elimination
Although you might not immediately know the correct answer to a question, if you can
reduce the question from 
ve answers down to three, your odds of guessing the correct
answer will be markedly improved. For example, if you can reduce a question from four
answers to two answers, you double your chances of guessing the correct answer. In this
section, we will discuss how to apply the process of elimination to help improve your score.
Using the Provided Writing Material
Depending on your particular testing center, you may be provided with a stack of blank
paper or a whiteboard to use to help you answer questions. If you sit down and are not pro-
vided with anything, please make sure to ask for such materials.
After determining whether a question compiles and what it is asking for, you should
then jot down a list of all the answers. You should then proceed to cross out the ones you
know are not correct. We provided a sample of what this might look like in Figure B.1.
FIGURE B.1
Eliminating answer choices
If you’re using paper and you decide to come back to this question, be sure to write
down the question number and save it for later. If you’re using a whiteboard and decide to
come back to a question later, you may have to redo some of the work, given the limited
space on a whiteboard. For those questions you want to come back to later, we suggest jot-
ting down the remaining answer choices on the side of the whiteboard. Some test-taking
Taking the Test
bapp02.indd 1봀
4/2014 Page 363
software allows you to mark and save which answer choices you’ve eliminated, although in
our experience this does not always work reliably in practice.
Although you aren’t allowed to bring any written notes with you into the
exam, you’re allowed to write things down you remember at the start of
the exam on the provided writing material. If there’s a particular facet of
the Java language that you have difficulty remembering, try memorizing
it before the exam and write it down as soon as the exam starts. You can
then use it as a guide for the rest of the exam. Of course, this strategy only
works for a handful of topics, since there’s a limit to what you’re likely to
remember in a short time.
For example, you may have trouble remembering the list of acceptable
data types in
statements. If so, we recommend you memorize that
information before the exam and write it down as soon as the exam starts
for use in various questions.
Understanding Relationships Between Answers
The exam writers, as well as the writers of this book, are fond of answers that are related
to each other. We can apply the process of elimination to remove entire sets of answers
from selection, not just a single answer. For example, take a look at the following question:
22.
What is the output of the following application?
In this question, notice that half of the answers output
, whereas the other
half output
. Based on the code, as well as the answers available, the question
cannot output both values. That means if you can determine what the ternary expression
on line 5 evaluates to, you can eliminate half the answers!
You might also notice that this particular question does not include any Does not com-
pile踠潲₍Code throws an exception at runtime踀 answers, meaning you can be assured this
snippet of code does compile and run without issue. If you have a question similar to this,
you can compare the syntax and use this as a guide for solving other related questions.
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 364
Guessing the Correct Answer
Unlike with some other standardized tests, theres no penalty for answering a question
incorrectly versus leaving it blank. If you’re nearly out of time, or you just can’t decide on
an answer, select a random answer and move on. If you’ve been able to eliminate even one
answer, then your guess will be better than blind luck.
Answer All Questions!
You should set a hard stop of 5 minutes of time remaining on the exam to ensure that
you’ve answered each and every question. Remember, if you fail to answer a question
you’ll defi
nitely get it wrong and lose points, but if you guess, there’s at least a chance
you’ll be correct. There’s no harm in guessing!
When in doubt, we generally recommend picking a random answer that includes₍Does
not compile踀 if available, although which choice you select is not nearly as important as
making sure to not leave any unanswered questions on the exam!
Optimizing Your Time
One of the most dif■
cult test-taking skills to master is balancing your time on the exam.
Although Oracle often varies the precise number of questions on the exam and the amount
of time you have to answer them, the general rule of thumb is that you have about one and
half minutes per question.
Of course, it can be stressful to frequently look at the time remaining while taking the
exam, so the key is pacing yourself. Some questions will take you longer than two minutes
to solve, but hopefully others will only take less than a minute. The more time you save on
the easier questions, the more time you’ll have for the harder questions.
Checking the Time Remaining
The exam software includes a clock that tells you the amount of time you have left on
the exam. We don’t recommend checking the clock after each and every question to deter-
mine your pace. After all, doing such a calculation will waste time and probably make you
nervous and stressed out. We do recommend you check the time remaining at certain points
while taking the exam to determine whether you should try to increase your pace.
For example, if the exam lasts two hours and is 90 questions long, the following would
be a good pace to try to keep.
120 Minutes Remaining: Start exam.
90 Minutes Remaining: One third of the exam finished.
Taking the Test
bapp02.indd 1봀
4/2014 Page 365
60 Minutes Remaining: Two thirds of the exam finished.
30 Minutes Remaining: First pass of all questions complete.
5 Minutes Remaining: Finished reviewing all questions marked for Review.踠Select
answers to all questions left blank.
As you’re taking the exam you may realize you’re falling behind. In this scenario, you
need to start allotting less time per question, which may involve more guessing, or you’ll
end up with some questions that you never even answered. As discussed in the previous sec-
tion, guessing an answer to a question is better than not answering the question at all.
Skipping Hard Questions
If you do 
nd you are having dif■
culty with a particular set of questions, just skip them.
The exam provides a feature to mark questions for ReviewŽ that you can later come back
to. Remember that all questions on the exam, easy or dif■
cult, are weighted the same. It is
a far better use of your time to spen搠■
ve minutes answering ten easy questions than the
same amount of time answering one dif■
cult question.
You might come to a question that looks dif■
cult and immediately realize it is going to
take a lot of time. In this case, skip it before even starting on it. You can save the most dif-
cult problems for the end so that you can get all the easy ones solved early on. Of course,
you shouldn’t mark every question for Review,踠so use that sparingly. For example, if you
only need 30 more seconds to solve a speci■
c question, it is better to 
nish it so you do not
have to come back to it later. The trick is to not get stuck on a dif■
cult question for a long
period of time.
Improving Your Test-Taking Speed
Answering certi■
cation exam questions quickly does not come naturally to most people.
It takes a bit of practice and skill to look at a question, a code sample, and 4–6 answers,
and be able to answer it within a minute or two. The best way to practice is to keep solving
the review questions at the end of each chapter until you can read, understand, and answer
them in under a minute.
Once you’ve completed all of the material and practiced with the review questions
enough that you can answer them quickly and correctly, you should try one of the three
60-question practice exams that come with this Study Guide. You should treat it like the
real exam, setting aside two hours an搠■
nishing it in one sitting.
Although we recommend you try to avoid taking the practice exams so much that you
memorize the questions and answers, we do recommend you keep taking them until you
ca渠■
nish each practice exam in under two hours. Remember not to move on to the next
one until you can pass the previous exam in the allotted time. If not, study more and go
back to drilling on the Review Questions. The idea is that you want to be good at quickly
reading through the question, honing in on the key concept the question is asking, and
being able to select the answer that best represents it.
Appendix B
Study Tips
bapp02.indd 1봀
4/2014 Page 366
Getting a Good Night’s Rest
Although a lot of people are inclined to cram as much material as they can in the hours
leading up to the exam, most studies have shown that this is a poor test-taking strategy.
The best thing we can recommend you do before the exam is to get a good night’s rest!
Given the length of the exam and number of questions, the exam can be quite draining,
especially if this is your 
rst time taking a certi■
cation exam. You might come in expect-
ing to be done 30 minutes early, only to discover you are only a quarter of the way through
the exam with half the time remaining. At some point, you may begin to panic, and it is
in these moments that these test-taking skills are most important. Just remember to take
a deep breath, stay calm, eliminate as many wrong answers as you can, and make sure to
answer each and every question. It is for stressful moments like these that being well rested
with a good night’s sleep will be most bene■
cial!
bindex.indd 1봀
4/2014 Page 367
Index
bindex.indd 1봀
4/2014 Page 369
Note to the Reader:
Throughout this index
boldfaced
page numbers indicate primary discus-
sions of a topic.
Italicized
page numbers indicate illustrations.
abstract classes
concrete classes from,
262
263
creating,
259
defining,
262
extending,
263
265
abstract specifiers
interfaces, 267–269
methods, 168,
271
273
access modifiers,
173
default,
175
description, 7
inheritance,
237
methods, 166–167
private,
173
protected,
public,
180
181
static,
181
188
add() method,
130
131
addition
dates, 142–143
precedence, 53–54
ampersands (&) for logical operators, 64,
ancestors in inheritance, 234
贀andŽ logical operator, 64,
anonymous arrays, 120
append(⤀ method,
115
args parameters in main⠀⤀, 7–8
arithmetic operators,
ArithmeticException class,
314
ArrayIndexOutOfBoundsException class, 123,
314
315
ArrayLists,
arrays from,
136
137
autoboxing,
136
creating,
methods,
130
134
sorting,
wrapper classes,
134
135
arrays,
119
ArrayLists,
declaring, 121
indexes, 7, 120,
120
multidimensional,
126
128
parameters, 7
primitives,
119
121
119
120
reference variables,
121
122
searching,
126
sorting,
varargs,
126
working with,
arrow operator (-�⤀ for lambda expressions,
211–212,
212
asList⠀⤀ method, 187–188
assignment operators
compound,
overview,
precedence, 53
assumed keywords in interfaces, 268
asterisks (*⤀
comments, 4–5
packages, 10
asymmetric arrays, 128,
128
autoboxing
overloading methods,
193
type conversions,
136
B prefix for binary, 22
backed lists, 137
base 10 numbering system,
Beginning Java forum, 6
binary number format, 22–23
binary operators
arithmetic,
assignment,
casting,
compound assignment operators,
equality,
logical,
numeric promotion,
relational,
binary searches,
126
bitwise operators, 64,
bindex.indd 1봀
4/2014 Page 370
blocks … commas ⠀
blocks
description, 67
initialization order,
instance initializer,
scope in,
bodies
lambda expressions, 212,
212
methods,
171
172
boolean type
default initialization, 31
if statements, 70
logical operators, 57–58
size and range, 21
ternary operators, 71…72
while statements, 77
wrapper classes, 134–135
braces ({})
blocks, 18–19, 32–33
if-then statements,
lambda expressions, 212,
212
methods, 171
try statements, 306–307
brackets ([]⤀ for arrays, 7, 119–122
break statements
in loops,
in switch,
byte type
default initialization, 31
promotion rules, 56
size and range, 21
switch statements, 72–73
wrapper classes, 134–135
bytecode, 6
calling
constructors,
243
244
inherited class members,
244
245
static variables and methods,
182
183
CamelCase names, 28–29
capacity vs. size,
113
114
114
carets (^) for logical operators, 64,
case sensitivity of names, 27
case statements in switch,
casting
objects,
284
operators,
catch blocks, 305–309,
305
chaining
constructors,
201
methods,
110
StringBuilder,
112
113
char type
default initialization, 31
promotion rules, 56
size and range, 21
switch statements, 72–73
wrapper classes, 134–135
charAt⠀⤀ method,
106
114
, 135
checked exceptions,
303
, 305,
child classes in inheritance, 234
child packages, 10
.class extension, 6
class variables in default initialization,
ClassCastException class,
315
classes
abstract,
259
265
concrete,
262
263
description,
element ordering,
extending,
235
236
235
fields and methods,
vs. files,
immutable,
207
208
inheritance.
See
inheritance
interfaces.
See
interfaces
packages, 9
paths, 15
subclasses,
319
321
wrapper,
134
136
clear⠀) method,
133
closures.
See
lambda expressions
blocks, 18–19
compiling, 6,
exam formatting,
colons (:⤀
dates and times, 150
labels, 88
paths, 15
ternary operators,
commas (,⤀
dates and times, 150
exception lists, 171
interface implementation, 267
parameter lists, 171
variable declarations, 26
comments₅ do-while statements
371
bindex.indd 1봀
4/2014 Page 371
comments,
comparators in arrays, 125
compile-time constant values in switch
statements,
compiling code
extensions for, 6
and inheritance,
241
242
with packages,
compound assignment operators,
concatenating strings,
102
104
concrete classes,
262
263
conflicts in names,
consistency of names, 28
constant values in switch statements,
constructors
calling,
243
244
chaining,
201
creating,
196
date and time, 141
default,
197
199
defining,
238
definition rules,
242
243
final fields,
initialization order,
204
objects,
overloading,
199
200
wrapper classes, 134–135
contains⠀⤀ method
ArrayLists,
133
strings,
109
110
continue statements,
control flow statements
break,
continue,
do-while,
for,
for-each,
if-then,
if-then-else,
labels,
nested loops,
switch,
while,
converting
ArrayLists to arrays,
136
137
number systems,
objects to wrapper classes,
135
136
covariant return types, 248, 252
curly braces ({})
blocks, 18–19, 32–33
if-then statements,
lambda expressions, 212,
212
methods, 171
try statements, 306–307
data types
in for statements, 82
promotion rules,
switch statements,
Date class, 12–13
dates
creating,
142
earlier versions,
141
142
144
150
formatting,
148
150
manipulating,
142
145
parsing,
151
periods,
145
147
DateTimeFormatter class, 148–150
dd format for dates and times,
decimal numbering system, 22
declare rules for exceptions, 303
declaring
arrays, 121
methods,
166
166
variables,
decrement operators,
default statements in switch, 72,
defaults
access modifiers, 167,
175
constructors, 17,
197
199
interface methods,
274
278
packages, 13
variable initialization,
defining
abstract classes,
262
interfaces,
267
269
delete⠀⤀ method,
deleteCharAt⠀⤀ method,
descedents in inheritance, 234
destroying objects
finalize⠀⤀,
garbage collection,
diamond operator (&#x-16.;P⤀, 130
division
modulus operation, 54–55
precedence, 53–54
do-while statements,
dollar signs ($) for names 蔠free store
bindex.indd 1봀
4/2014 Page 372
dollar signs ($) for names, 27, 29
double quotes ("⤀
for spaces, 8
strings, 102–103
double type
default initialization, 31
size and range, 21
wrapper classes, 134–135
else operators,
encapsulation
description, 39
immutable classes,
207
208
overview,
205
206
endsWith⠀⤀ method,
109
enum type
dates, 140
support for, 72–73
switch statements, 72
equal signs (=⤀
assignment operators, 60
compound assignment operators, 62–63
equality, 117–118
equality operators, 65–66
precedence, 53
relational operators, 63
unary operator, 57
variable declarations, 25
equality
operators,
overview,
119
equals(⤀ method
ArrayLists,
133
134
arrays, 121
strings,
109
, 118–119
equalsIgnoreCase⠀⤀ method,
109
Error class, 302,
, 305,
318
exams, code formatting in,
exception lists for methods,
171
ExceptionInInitializerError class,
exceptions
checked,
Error,
318
finally blocks,
309
307
ignoring, 322
methods,
318
322
multiple,
313
printing,
321
322
reasons,
300
vs. return codes,
301
roles,
300
301
runtime,
314
subclasses,
319
321
throwing,
304
305
try statements,
305
305
types,
303
309
exclamation points (!⤀
equality operators, 65–66
logical operator, 57–58
unary operator, 57
贀exclusive orŽ operator, 64,
exit⠀⤀ method, 309
extending
abstract classes,
263
265
classes,
235
236
235
interfaces, 269
false value in logical operators, 57
fields
in classes, 35, 41
final,
initialization order, 19–20
overview,
reading and writing,
static,
181
182
FileNotFoundException class, 317
files vs. classes,
final specifiers
abstract classes, 261
constants, 74
constructor fields,
interfaces, 267, 273–274
methods, 168,
256
finalize⠀⤀ method,
finally blocks,
309
307
float type
default initialization, 31
promotion rules, 55
size and range, 21
wrapper classes, 134–135
for statements,
for-each statements,
format⠀⤀ method, 148
formatting dates and times,
148
150
free store, 36
functional interfaces with lambda expressions 蔠interfaces
bindex.indd 1봀
4/2014 Page 373
functional interfaces with lambda expressions,
214
functional programming, 208–209
functions.
See
methods
garbage collection,
gc⠀⤀ method, 36
generics, 130
getter methods in JavaBeans, 206
getting variables, 18
GMT (Greenwich Mean Time), 146
greater than signs (�⤀
diamond operator, 130
lambda expressions, 211–212,
212
relational operators, 63
Greenwich Mean Time (GMT), 146
handle rules for exceptions,
303
heap, 36
hexadecimal number format, 22–23
hh format for dates and times, 150
hiding
vs. overriding,
254
255
374
intValue⠀⤀ method … methods
bindex.indd 1봀
4/2014 Page 374
lambda expressions, 214
multiple inheritance,
277
switch statements, 73–75
local variables,
LocalDate, 138–141, 146
LocalDateTime, 139–141, 146
LocalTime, 139–140
logical operators,
complement,
overview,
precedence, 53
long type
dates and times,
146
default initialization, 31
size and range, 21–22
wrapper classes, 134–135
loops
arrays, 123
break statements,
continue statements,
do-while,
for,
for-each,
infinite,
labels,
nested,
while,
main⠀⤀ method,
MAX_VALUE constant, 22
MEDIUM format for dates and times, 149
members in classes, 2
memory
object destruction,
reference types, 24,
methods
abstract, 259,
271
273
access modifiers.
See
access modifiers
ArrayLists,
130
134
bodies,
171
172
chaining,
110
constructors.
See
constructors
dates and times,
144
declaring,
166
166
defining, 3
designing,
166
166
exception lists,
171
exceptions thrown by,
318
322
final,
256
hiding,
252
254
interfaces,
271
279
minus signs (-) 蔠order
bindex.indd 1봀
4/2014 Page 375
main⠀⤀,
names,
170
optional specifiers,
168
169
overloading,
overriding,
319
321
overriding vs. hiding,
254
255
overview,
parameter lists,
171
passing data,
188
190
polymorphism,
287
288
redeclaring,
251
252
return types,
169
170
signatures, 3, 7, 166,
166
static,
181
182
StringBuilder class,
114
strings,
105
109
varargs,
172
173
virtual,
284
285
minus signs (-⤀
compound assignment operators, 62
increment operators, 58–59
lambda expressions, 211–212,
212
negation operator, 57–58
unary operator, 57
mm format for dates and times, 150
MMMM format for dates and times, 150
modulus operator (%⤀
overview, 54–55
precedence, 53–54
multidimensional arrays,
126
128
multiple exceptions,
313
multiple inheritance
description, 234–235,
235
interfaces,
271
273
277
multiple-line comments, 4–5
multiple variables, declaring,
multiplication, 53蔵4
mutability of StringBuilder,
112
113
names
conflicts,
constructors, 17
identifiers,
JavaBeans,
205
206
methods,
170
packages, 10,
native specifiers, 168
negation operator,
nested loops,
new keyword for constructors, 17
no-argument constructors, 198
NoClassDefFoundError class, 318
not equals operators,
now⠀) method, 139
null values
autoboxing, 136
reference types, 24
NullPointerException class, 303,
NumberFormatException class,
numbering systems, 22–23
numeric promotion,
object-oriented languages,
objects
casting,
284
comparing, 66
constructors,
creating,
237
238
238
description, 2
destroying,
initialization order,
instance initializer blocks,
polymorphism,
281
primitive types,
reading and writing fields,
vs. references,
octal number format, 22
ofLocalized methods, 149
operators
arithmetic,
assignment,
casting,
equality,
logical,
numeric promotion,
order,
overview,
relational,
ternary,
unary,
optional specifiers,
168
169
贀orŽ operator, 64,
order
class elements,
constructor initialization,
204
field initialization,
operators,
overflow … public access modifiers
bindex.indd 1봀
4/2014 Page 376
overflow,
overloading methods,
autoboxing,
193
constructors,
199
200
vs. overriding,
248
overview,
194
196
primitive types,
194
reference types,
193
194
varargs,
192
193
overriding
vs. hiding,
254
255
methods,
319
321
vs. overloading,
248
polymorphism,
287
288
package private access modifiers, 167,
175
packages
compiling code with,
creating,
element ordering, 35
names, 10,
overview,
redundant imports,
wildcards,
parameters
main⠀⤀, 7
methods, 3,
171
overloading methods,
192
193
, 199
polymorphic,
285
286
parent classes in inheritance, 234
parentheses (⤀
lambda expressions, 212–213,
212
methods, 167
precedence, 54
parse⠀) method, 151
question marks (?) for ternary operators 蔠sorting
bindex.indd 1봀
4/2014 Page 377
question marks (?) for ternary operators,
quotes ("⤀
for spaces, 8
strings, 102–103
ranges of primitive types, 21
readability
if-then statements,
literal values, 23
names, 28
polymorphic parameters,
286
reading fields,
recursion, infinite, 317
recursive functions, 247
redeclaring private methods,
251
252
redundant package imports,
references
in arrays,
121
122
comparing, 66
methods, 189–191,
190
vs. objects,
overloading methods,
194
overview,
polymorphism,
281
vs. primitive,
relational operators
overview,
precedence, 53
remainder operator (%⤀
overview, 54–55
precedence, 53–54
remove⠀⤀ method,
131
132
replace⠀) method,
110
reserved words,
return codes vs. exceptions,
301
return statement in methods, 169
return types and values
constructors, 17
covariant, 248, 252
description, 7
ignored, 191
immutable classes,
207
208
methods,
169
170
reverse⠀) method,
robustness, 40
runtime exceptions,
314
RuntimeException class, 302–303,
, 305
scope
in for statements, 81
variables,
searching arrays,
126
security, 40
semicolons (;⤀
class paths, 15
in for statements, 81
lambda expressions, 212–213,
212
variable declarations, 27
set⠀) method,
132
setter methods in JavaBeans, 206
setting variables, 18
shift operators, 53
short-circuit logical operators
description, 64–65
precedence, 53
SHORT format for dates and times, 149
short type
default initialization, 31
promotion rules, 56
size and range, 21
switch statements, 72–73
wrapper classes, 134–135
signatures in methods, 3, 7, 166,
166
simplicity, 40
single inheritance, 234,
235
single-line comments, 4
size
vs. capacity,
113
114
114
primitive types, 21
size⠀⤀ method,
132
133
slashes (/⤀
comments, 4–5
division, 53
precedence, 54
sorting
ArrayLists,
spaces in arguments 蔠update statements in for statements
bindex.indd 1봀
4/2014 Page 378
arrays,
spaces in arguments, 8
square brackets ([]⤀ for arrays, 7,
119–122
StackOverflowError class,
318
startsWith⠀⤀ method,
109
statements
do-while,
for,
for-each,
if-then,
if-then-else,
overview,
switch,
while,
static keyword, 7
static methods, hiding,
252
254
static specifiers
calling variables and methods,
182
183
designing,
181
182
imports,
187
188
initialization,
186
187
vs. instance,
183
185
interfaces, 273–274,
278
methods, 168
variables,
185
strictfp specifiers, 168
String class, 102
StringBuffer class vs,
StringBuilder class,
112
creating,
113
114
methods,
114
mutability and chaining,
112
113
vs. StringBuffer class,
strings
as arrays, 119
concatenating,
102
104
description, 3,
102
immutability,
104
105
methods,
105
109
pools,
105
StringBuilder class,
switch statements, 73
subclasses with exceptions,
319
321
substring⠀⤀ method,
107
108
114
subtraction
days, 145
precedence, 53–54
super⠀) keyword, 239–243,
super keyword,
247
switch statements,
compile-time constant values,
data types,
synchronized specifiers, 168
System.gc⠀) method, 36
ternary operators
overview,
precedence, 53
this⠀⤀ keyword, 238
Throwable class, 302,
throwing exceptions,
304
305
times
creating,
142
formatting,
148
150
manipulating,
142
145
parsing,
151
periods,
145
147
toEpochDay⠀⤀ method, 146
toEpochTime⠀) method, 146
toLowerCase⠀) method,
108
toString⠀⤀ method, 105,
toUpperCase⠀) method,
108
trim⠀⤀ method,
110
true value in logical operators, 57
truth tables, 64,
try statements,
305
305
two-multidimensional arrays,
127
unary operators
increment and decrement,
logical complement and negation,
precedence, 53
promotion rules, 56
working with,
unchecked exceptions,
underflow,
underscores (_⤀
in literal values, 23
names, 27
Unicode character set, 29
update statements in for statements, 80–82,
valueOf⠀) method … ZonedDateTime
bindex.indd 1봀
4/2014 Page 379
valueOf⠀) method, 135
variable argument (varargs⤀ lists, 7–8
ArrayLists, 137
arrays,
126
methods,
172
173
overloading methods,
192
193
variables
assignment operators,
declaring,
default initialization,
defining, 3
description, 2
in for statements, 81–83
for-each statements, 83
hiding,
257
inheriting,
257
interfaces,
273
274
lambda expression access, 213
reading and writing, 18
scope,
static,
185
vertical bars (|) for logical operators, 64,
virtual methods,
284
285
void type, 7
description, 3
methods, 169
while statements,
wildcards
JAR files, 15
packages,
wrapper classes
ArrayLists,
134
135
converting to,
135
136
switch statements, 73
贀write once, run everywhere踀,
writing fields,
X for hexadecimal, 22
ZonedDateTime, 139
badvert.indd 1봀
4/2014 Page 388
Register on Sybex.com to gain access to the free online interactive
learning environment and test bank to help you study for your OCA Java
SE 8 Programmer I certi■
cation.
The online test bank includes:
耠Assessment Test to help you focus your study to speci■
c objectives
耠Chapter Tests to reinforce what you learned
耠Practice Exams to test your knowledge of the material
耠Electronic Flashcards to reinforce your learning and provide last-minute
test prep before the exam
耠Searchable Glossary gives you instant access to the key terms you’ll need
to know for the exam
Go to
to register and gain access to this
comprehensive study tool package.
Go to www.wiley.com/go/eula to access Wiley’s ebook EULA.
378

spaces in arguments update statements in for statements
bindex.indd 1
4/2014 Page378
arrays,
124

125
spaces in arguments, 8
square brackets ([]) for arrays, 7,
119122
StackOverflowError class,
318
startsWith() method,
109
statements
do-while,
78

80
,
78
for,
80

83
,
80
,
85
for-each,
83

86
,
83
if-then,
67

68
,
67
if-then-else,
68

70
,
69
overview,
66
switch,
72

76
,
73
while,
76

77
,
77
,
79
static keyword, 7
static methods, hiding,
252

254
static specifiers
calling variables and methods,
182

183
designing,
181

182
imports,
187

188
initialization,
186

187
vs. instance,
183

185
interfaces, 273274,
278
methods, 168
variables,
185
strictfp specifiers, 168
String class, 102
StringBuffer class vs,
117
StringBuilder class,
111

112
creating,
113

114
methods,
114

117
mutability and chaining,
112

113
vs. StringBuffer class,
117
strings
as arrays, 119
concatenating,
102

104
description, 3,
102
immutability,
104

105
methods,
105

109
pools,
105
StringBuilder class,
111

117
switch statements, 73
subclasses with exceptions,
319

321
substring() method,
107

108
,
114
subtraction
days, 145
precedence, 5354
super() keyword, 239243,
246
super keyword,
246

247
switch statements,
72
compile-time constant values,
73

76
data types,
72

73
,
73
synchronized specifiers, 168
System.gc() method, 36
T
ternary operators
overview,
71
precedence, 53
this() keyword, 238
Throwable class, 302,
302
throwing exceptions,
304

305
times
creating,
138

142
formatting,
148

150
manipulating,
142

145
parsing,
151
periods,
145

147
toEpochDay() method, 146
toEpochTime() method, 146
toLowerCase() method,
108
toString() method, 105,
116

117
toUpperCase() method,
108
trim() method,
110
true value in logical operators, 57
truth tables, 64,
64
try statements,
305

307
,
305
two-multidimensional arrays,
127
U
unary operators
increment and decrement,
58

59
logical complement and negation,
57

58
precedence, 53
promotion rules, 56
working with,
57
unchecked exceptions,
302
underflow,
61
underscores (_)
in literal values, 23
names, 27
Unicode character set, 29
update statements in for statements, 8082,
80

Приложенные файлы

  • pdf 10879118
    Размер файла: 3 MB Загрузок: 0

Добавить комментарий