Tải bản đầy đủ (.pdf) (706 trang)

Manning OCA java SE 8 programmer i certification guide

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.79 MB, 706 trang )

MANNING

Mala Gupta


OCA Java SE 8 Programmer I Certification Guide



OCA Java SE 8
Programmer I
Certification Guide
MALA GUPTA

MANNING
SHELTER ISLAND


For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email:
©2017 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.


Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.

Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964

Development editor:
Technical development editor:
Copy editor:
Proofreader:
Technical proofreader:
Typesetter:
Cover designer:

ISBN: 9781617293252
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16

Cynthia Kane
Francesco Bianchi
Linda Recktenwald

Katie Tennant
Jean-François Morin
Dennis Dalinnik
Marija Tudor


To Dheeraj, my pillar of strength



brief contents
Introduction 1
1



Java basics

22

2



Working with Java data types 92

3




Methods and encapsulation

4



Selected classes from the Java API and arrays

5



Flow control

6



Working with inheritance 384

7



Exception handling 469

8




Full mock exam 539

147

322

vii

221



contents
preface xvii
acknowledgments xix
about this book xxi
about the author xxix
about the cover illustration

xxx

Introduction 1
1
2
3
4
5
6
7


Disclaimer 2
Introduction to OCA Java SE 8 Programmer I
Certification 2
The importance of OCA Java SE 8 Programmer I
Certification 2
Comparing OCA Java exam versions 4
Next step: OCP Java SE 8 Programmer II (1Z0-809)
exam 8
Complete exam objectives, mapped to book chapters, and
readiness checklist 8
FAQs 10
FAQs on exam preparation

8

10



FAQs on taking the exam

The testing engine used in the exam

ix

20

18



CONTENTS

x

1

Java basics 22
1.1

The structures of a Java class and a source code file
Structure of a Java class 24
a Java source code file 32

1.2



23

Structure and components of

Executable Java applications

36

Executable Java classes versus non-executable Java classes
The main method 37 Run a Java program from the
command line 39

36




1.3

Java packages

41

The need for packages 42 Defining classes in a package using
the package statement 42 Using simple names with import
statements 45 Using packaged classes without using the
import statement 47 Importing a single member versus all
members of a package 48 The import statement doesn’t import
the whole package tree 49 Importing classes from the default
package 50 Static imports 50















1.4

Java access modifiers

51

Access modifiers 52 Public access modifier 53 Protected
access modifier 54 Default access (package access) 57
private access modifier 61 Access modifiers and
Java entities 62








1.5

Nonaccess modifiers
abstract modifier

1.6

65

64



final modifier

Features and components of Java

66

2

Summary 74
Review notes 75
Sample exam questions 79
Answers to sample exam questions

static modifier

Irrelevant features



84

Working with Java data types 92
2.1

Primitive variables

93

Category: Boolean 95 Category: signed numeric 96
Category: character (unsigned integer) 102 Confusion with

the names of the primitive data types 104




2.2

Identifiers

105

Valid and invalid identifiers 105

67

72

Valid features and components of Java 72
and components of Java 74

1.7
1.8
1.9
1.10




CONTENTS


2.3

xi

Object reference variables

106

What are object reference variables? 107 Differentiating between
object reference variables and primitive variables 109


2.4

Operators

111

Assignment operators 112 Arithmetic operators 115
Relational operators 119 Logical operators 121
Operator precedence 123




2.5

Wrapper classes 125
Class hierarchy of wrapper classes 125 Creating objects of the
wrapper classes 125 Retrieving primitive values from the

wrapper classes 126 Parsing a string value to a
primitive type 127 Difference between using the valueOf
method and constructors of wrapper classes 128 Comparing
objects of wrapper classes 128 Autoboxing and unboxing 130











2.6
2.7
2.8
2.9

3

Summary 132
Review notes 132
Sample exam questions 136
Answers to sample exam questions 140

Methods and encapsulation 147
3.1


Scope of variables

149

Local variables 149 Method parameters 151
Instance variables 152 Class variables 153
Overlapping variable scopes 155




3.2

Object’s life cycle

158

An object is born 159 Object is accessible 160
Object is inaccessible 161 Garbage collection 163




3.3

Create methods with arguments and return values
Return type of a method
Return statement 172

3.4




Accessing object fields

177



Access level

177

178

User-defined constructors 178
Overloaded constructors 185

3.6

174

Return type

Constructors of a class

166

Method parameters 169


Create an overloaded method
Argument list 175

3.5

168





Default constructor 183

188

What is an object field? 188 Read and write object fields
Calling methods on objects 192


189


CONTENTS

xii

3.7

Apply encapsulation principles to a class
Need for encapsulation 195


3.8



Apply encapsulation 195

Passing objects and primitives to methods
Passing primitives to methods 198
to methods 199

3.9
3.10
3.11
3.12

4

194
197

Passing object references



Summary 202
Review notes 203
Sample exam questions 207
Answers to sample exam questions


212

Selected classes from the Java API and arrays 221
4.1

Welcome to the world of the String class

223

Creating String objects 223 The class String is immutable
Methods of the class String 230 String objects and
operators 235 Determining equality of Strings 236


227





4.2

Mutable strings: StringBuilder

239

The StringBuilder class is mutable 239 Creating StringBuilder
objects 240 Methods of class StringBuilder 241 A quick
note on the class StringBuffer 247





4.3

Arrays



247

What is an array? 248 Array declaration 249
Array allocation 250 Array initialization 252
Combining array declaration, allocation, and initialization 254
Asymmetrical multidimensional arrays 255 Arrays of type
interface, abstract class, and class Object 256 Members of
an array 258








4.4

ArrayList

258


Creating an ArrayList 259 Adding elements to an
ArrayList 261 Accessing elements of an ArrayList 263
Modifying the elements of an ArrayList 265 Deleting the
elements of an ArrayList 266 Other methods of ArrayList








4.5

Comparing objects for equality

273

The method equals in the class java.lang.Object 273
Comparing objects of a user-defined class 273 Incorrect
method signature of the equals method 275 Contract of the
equals method 276




4.6

Working with calendar data


278

LocalDate 279 LocalTime 282 LocalDateTime 285
Period 286 DateTimeFormatter 291






267


CONTENTS

4.7
4.8
4.9
4.10

5

Summary 297
Review notes 299
Sample exam questions 309
Answers to sample exam questions

Flow control
5.1


xiii

313

322

The if, if-else, and ternary constructs

324

The if construct and its flavors 324 Missing else blocks 328
Implications of the presence and absence of {} in if-else
constructs 328 Appropriate versus inappropriate expressions
passed as arguments to an if statement 331 Nested if
constructs 332 Ternary construct 334








5.2

The switch statement 338
Create and use a switch statement 339 Comparing a switch
statement with multiple if-else constructs 339 Arguments
passed to a switch statement 341 Values passed to the label

case of a switch statement 343 Use of break statements within
a switch statement 345








5.3

The for loop

346

Initialization block 348 Termination condition 349
The update clause 349 Optional parts of a for statement
Nested for loop 351




5.4

The enhanced for loop

350

352


Iteration with enhanced for loop 352 Limitations of the
enhanced for loop 355 Nested enhanced for loop 356




5.5

The while and do-while loops

358

The while loop 358 The do-while loop 360
while and do-while block, expression, and nesting rules 362


5.6

Comparing loop constructs

362

Comparing do-while and while loops 362 Comparing for and
enhanced for loops 363 Comparing for and while loops 364




5.7


Loop statements: break and continue 364
The break statement 364
Labeled statements 367

5.8
5.9
5.10
5.11



The continue statement 366

Summary 368
Review notes 369
Sample exam questions 372
Answers to sample exam questions

377


CONTENTS

xiv

6

Working with inheritance 384
6.1


Inheritance with classes

385

The need to inherit classes 385 Benefits 387 A derived class
contains within it an object of its base class 390 Which base class
members are inherited by a derived class? 391 Which base class
members aren’t inherited by a derived class? 391 Derived classes
can define additional properties and behaviors 391 Abstract base
class versus concrete base class 392












6.2

Use interfaces 394
Need for using interfaces 396 Defining interfaces 398
Types of methods in an interface 401 Implementing a single
interface 405 A class can’t extend multiple classes 407
A class can implement multiple interfaces 408 Extending

interfaces 411 Modifying existing methods of an interface 414
Properties of members of an interface 417










6.3

Reference variable and object types

418

Using a variable of the derived class to access its own object 418
Using a variable of a superclass to access an object of a derived
class 419 Using a variable of an implemented interface to access
a derived class object 420 The need for accessing an object using
the variables of its base class or implemented interfaces 421




6.4

Casting


424

How to cast a variable to another type
Need for casting 426

6.5

Use this and super to access objects and constructors
Object reference: this

6.6

424

Polymorphism

427



Object reference: super

427

430

434

Polymorphism with classes 434 Binding of variables and

methods at compile time and runtime 439 Polymorphism
with interfaces 441




6.7

Simple lambda expressions

446

Comparing passing values with passing code to methods 446
Syntax of lambda expressions 449 Interface Predicate 450


6.8
6.9
6.10
6.11

Summary 452
Review notes 453
Sample exam questions 456
Answers to sample exam questions

461


CONTENTS


7

xv

Exception handling 469
7.1

Exceptions in Java

470

A taste of exceptions 470 Why handle exceptions
separately? 473 Does exception handling offer any
other benefits? 474




7.2

Categories of exceptions

475

Identifying exception categories 476 Class hierarchy of
exception classes 476 Checked exceptions 477
Runtime exceptions 478 Errors 478







7.3

Creating a method that throws an exception 479
Create a method that throws a checked exception 480
Handle-or-declare rule 481 Creating a method that throws
runtime exceptions or errors 481 A method can declare to throw
all types of exceptions, even if it doesn’t 482




7.4

What happens when an exception is thrown?

483

Creating try-catch-finally blocks 485 Using a method that throws
a checked exception 490 Using a method that throws a runtime
exception 491 Using a method that throws an error 493
Will a finally block execute even if the catch block defines a return
statement? 493 What happens if both a catch and a finally block
define return statements? 494 What happens if a finally block
modifies the value returned from a catch block? 495 Can a try
block be followed only by a finally block? 496 Does the order of the
exceptions caught in the catch blocks matter? 497 Can I rethrow

an exception or the error I catch? 499 Can I declare my methods
to throw a checked exception instead of handling it? 500 I can
create nested loops, so can I create nested try-catch blocks too? 500
Should I handle errors? 502




















7.5

Common exception classes and categories

503


ArrayIndexOutOfBoundsException and
IndexOutOfBoundsException 504 ClassCastException 505
IllegalArgumentException 507 NullPointerException 508
ArithmeticException 511 NumberFormatException 514
ExceptionInInitializerError 516 StackOverflowError 518
NoClassDefFoundError 519 OutOfMemoryError 519










7.6
7.7
7.8
7.9

Summary 520
Review notes 520
Sample exam questions 526
Answers to sample exam questions 530


CONTENTS

xvi


8

Full mock exam 539
8.1
8.2

Mock exam 539
Answers to mock exam questions 574

appendix

Answers to Twist in the Tale exercises 641
index

659


preface
Java programmer certifications are designed to tell would-be employers whether you
really know your stuff, and cracking the OCA Java SE 8 Programmer Certification is
not an easy task. Thorough preparation is crucial if you want to pass the exam the first
time with a score that you can be proud of. You need to know Java inside-out, and you
need to understand the certification process so that you’re ready for the challenging
questions you’ll face in the exam.
This book is a comprehensive guide to the 1Z0-808 exam. You’ll explore a wide
range of important Java topics as you systematically learn how to pass the certification
exam. Each chapter starts with a list of the exam objectives covered in that chapter.
Throughout the book you’ll find sample questions and exercises designed to reinforce
key concepts and prepare you for what you’ll see in the real exam, along with numerous

tips, notes, and visual aids.
Unlike many other exam guides, this book provides multiple ways to digest important techniques and concepts, including comic conversations, analogies, pictorial representations, flowcharts, UML diagrams, and, naturally, lots of well-commented code.
The book also gives insight into common mistakes people make when taking the
exam, and guides you in avoiding traps and pitfalls. It provides



Complete coverage of exam topics, all mapped to chapter and section numbers
Hands-on coding exercises, including particularly challenging ones that throw
in a twist

xvii


PREFACE

xviii




Instruction on what’s happening behind the scenes using the actual code from
the Java API source
Mastery of both the concepts and the exam

This book is written for developers with a working knowledge of Java. My hope is that
the book will deepen your knowledge and prepare you well for the exam and that you
will pass it with flying colors!



acknowledgments
First and foremost, I thank Dheeraj—my pillar of strength, my best friend, and my
husband. His constant guidance, encouragement, and love kept me going. He helped
me to get started with this book and got me over the goal line.
My sincere gratitude goes to Marjan Bace, publisher at Manning, for giving me the
opportunity to author this book. The Manning team has been wonderful—Michael
Stephens ensured that it was worth it for Manning to have a book on this subject.
Cynthia Kane, my development editor, is like sunshine. Not only did she help me with
the organization of individual chapters and the overall book, but she pulled me through
whenever the task of writing a book became overwhelming. It’s always a pleasure to
work with her. Copyeditor Linda Recktenwald not only applied her magic to sentence
and language constructions but also supplemented her editing with valuable suggestions on technical content.
Technical development editor Francesco Bianchi suggested multiple additions and
modifications, improving the content of this book. Technical proofreader Jean-François
Morin was outstanding in his review. He not only pointed out existing errors but also
suggested multiple improvements to the organization of the contents. Proofreader
Katie Tennant was extremely capable and talented. She reviewed the final manuscript
with great precision.
The technical reviewers on this book did an awesome job of reviewing the contents and sharing their valuable feedback and comments: Andrea Barisone, Andrea
Consentino, Anutosh Ghosh, David Blau, Marty Henderson, Mirsad Vojnikovic, Nicola
Pedot, Sanjiv Kumar, Simona Russo, Travis Nelson, and Ursin Stauss. I would also like

xix


xx

ACKNOWLEDGMENTS

to thank Nicole Butterfield and Donna Clements, review editors, for managing the

whole review process and meticulously funneling the feedback to make this book better.
Dennis Dalinnik did an outstanding job of converting the black-and-white handdrawn illustrations into glorious images. It was amazing to scrutinize the page proofs.
I also thank Dennis for adjusting the images in the final page proofs, which was a lot
of work. Janet Vail and Mary Piergies were awesome in their expertise at turning all
text, code, and images into publishable form. I am also grateful to Candace Gillhoolley
for her efforts in promoting the book.
I thank the MEAP readers for buying the book while it was being developed and
for their suggestions, corrections, and encouragement.
I would also like to thank my former colleagues Harry Mantheakis, Paul Rosenthal,
and Selvan Rajan, whose names I use in coding examples throughout the book. I have
always looked up to them.
I thank my daughters, Shreya and Pavni, who often advised me on the images that
I created for the book. I thank my family for their unconditional support. The book
would have been not been possible without their love and encouragement.


about this book
This book is written for developers with a working knowledge of Java who want to earn
the OCA Java SE 8 Programmer Certification. It uses powerful tools and features to
make reaching your goal of certification a quick, smooth, and enjoyable experience.
This section explains the features used in the book and tells you how to use the book
to get the most out of it as you prepare for the certification exam. More information
on the exam and on how the book is organized is available in the Introduction.

Start your preparation with the chapter-based exam
objective map
I strongly recommend a structured approach to preparing for this exam. To help you
with this task, I developed a chapter-based exam objective map, as shown in figure 1.
The full version is in the Introduction (table I.3).


Exam objectives

Covered in chapter/
section

1

Java basics

Chapters 1 and 3

1.1

Define the scope of variables

Section 3.1

1.2

Define the structure of a Java class

Section 1.1

1.3

Create executable Java applications with a main method; run a Java program from

Section 1.2

Figure 1 The Introduction to this book provides a list of all exam objectives and the corresponding

chapter and section numbers where they are covered. See the full table in the Introduction (table I.3).

xxi


ABOUT THIS BOOK

xxii

The map in the Introduction shows the complete exam objective list mapped to the
relevant chapter and section numbers. You can jump to the relevant section number
to work on a particular exam topic.

Chapter-based objectives
Each chapter starts with a list of the exam objectives covered in that chapter, as shown
in figure 2. This list is followed by a quick comparison of the major concepts and topics covered in the chapter with real-world objects and scenarios.
Exam objectives covered in this chapter

What you need to know

[1.2] Define the structure of a Java class.

Structure of a Java class, with its components:
package and import statements, class declarations, comments, variables, and methods.
Difference between the components of a Java
class and that of a Java source code file.

[1.3] Create executable Java applications with a

The right method signature for the main method

to create an executable Java application.
The arguments that are passed to the main
method.

main method; run a Java program from the
command line; including console output.

Figure 2
chapter

An example of the list of exam objectives and brief explanations at the beginning of each

Section-based objectives
Each main section in a chapter starts by identifying the exam objective(s) that it covers. Each listed exam topic starts with the exam objective and its subobjective number.
In figure 3, the number “4.4” refers to section 4.4 in chapter 4 (the complete list of
chapters and sections can be found in the table of contents). The number “9.4” preceding the exam objective refers to the objective’s numbering in the list of exam
objectives on Oracle’s website (the complete numbered list of exam objectives is given
in table I.3 in the Introduction).

4.4

ArrayList
[9.4] Declare and use an ArrayList of a given type
In this section, I’ll cover how to use ArrayList, its commonly used methods, and the
advantages it offers over an array.
The OCA Java SE 8 Programmer I exam covers only one class from the Java Collection API: ArrayList. The rest of the classes from the Java Collection API are covered
in the OCP Java SE 8 Programmer II exam (exam number 1Z0-809). One of the reasons

Figure 3 An example of the beginning of a section, identifying the exam objective that it covers



ABOUT THIS BOOK

xxiii

Exam tips
Each chapter provides multiple exam tips to reemphasize the points that are the most
confusing, overlooked, or frequently answered incorrectly by candidates and that
therefore require special attention for the exam. Figure 4 shows an example.
An ArrayList preserves the order of insertion of its elements.
Iterator, ListIterator, and the enhanced for loop will return the elements in the order in which they were added to the ArrayList. An iterator
(Iterator or ListIterator) lets you remove elements as you iterate an
ArrayList. It’s not possible to remove elements from an ArrayList while
iterating it using a for loop.
EXAM TIP

Figure 4 Example of an exam tip; they occur multiple times in a chapter

Notes
All chapters also include multiple notes that draw your attention to points that should
be noted while you’re preparing for the exam. Figure 5 shows an example.
NOTE Although the terms method parameters and method arguments are not the
same, you may have noticed that many programmers use them interchangeably. Method parameters are the variables that appear in the definition of a
method. Method arguments are the actual values that are passed to a method
while executing it. In figure 3.15, the variables phNum and msg are method
parameters. If you execute this method as sendMsg("123456", "Hello"),
then the String values "123456" and "Hello" are method arguments. As you
know, you can pass literal values or variables to a method. Thus, method arguments can be literal values or variables.

Figure 5


Example note

Sidebars
Sidebars contain information that may not be directly relevant to the exam but that is
related to it. Figure 6 shows an example.

static classes and interfaces
Certification aspirants frequently ask questions about static classes and interfaces, so I’ll quickly cover these in this section to ward off any confusion related to
them. But note that static classes and interfaces are types of nested classes and
interfaces that aren’t covered by the OCA Java 8 Programmer I exam.
You can’t prefix the definition of a top-level class or an interface with the keyword
static. A top-level class or interface is one that isn’t defined within another class or
interface. The following code will fail to compile:
static class Person {}
Figure 6

Example sidebar


ABOUT THIS BOOK

xxiv

Images
I use a lot of images in the chapters for an immersive learning experience. I believe
that a simple image can help you understand a concept quickly, and a little humor can
help you to retain information longer.
Simple images are used to draw your attention to a particular line of code (as shown
in figure 7).

public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
// code to create a new char array and
// replace the desired char with the new char
return new String(0, len, buf);
}
replace creates and
returns a new String
object. It doesn’t modify
the existing array value.

return this;
}

Figure 7 An example image that draws your attention to a particular line of code

I use pictorial representation of data in arrays (figure 8) and other data types to aid
visualization and understanding.

multiStrArr

0

0

1

1
null


2

0
1
2

A
B

Jan
Feb
Mar

Figure 8 An example pictorial representation
of data in an array

To reinforce important points and help you retain them longer, a little humor has been
added using comic strips (as in figure 9).

Figure 9 An example of a little humor to help you remember that the finally block always executes


×