pgjc4 jse8 oca - universitetet i bergen › ~khalid › ocajp8 › pgj8-oca-toc.pdf1.8 tenets of...
TRANSCRIPT
ix
Contents
Figures xix
Tables xxi
Examples xxiii
Foreword xxvii
Preface xxix
1 Basics of Java Programming 11.1 Introduction 21.2 Classes 2
Declaring Members: Fields and Methods 31.3 Objects 4
Class Instantiation, Reference Values, and References 4Object Aliases 6
1.4 Instance Members 6Invoking Methods 7
1.5 Static Members 71.6 Inheritance 101.7 Associations: Aggregation and Composition 121.8 Tenets of Java 13
Review Questions 131.9 Java Programs 151.10 Sample Java Application 16
Essential Elements of a Java Application 16Compiling and Running an Application 17
1.11 Program Output 18Formatted Output 18
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM
x CONTENTS
1.12 The Java Ecosystem 21Object-Oriented Paradigm 22Interpreted: The JVM 23Architecture-Neutral and Portable Bytecode 23Simplicity 23Dynamic and Distributed 23Robust and Secure 24High Performance and Multithreaded 24
Review Questions 25Chapter Summary 25Programming Exercise 26
2 Language Fundamentals 272.1 Basic Language Elements 28
Lexical Tokens 28Identifiers 28Keywords 29Separators 29Literals 30Integer Literals 30Floating-Point Literals 31Underscores in Numerical Literals 32Boolean Literals 32Character Literals 32String Literals 34Whitespace 35Comments 35
Review Questions 362.2 Primitive Data Types 37
The Integer Types 38The char Type 38The Floating-Point Types 38The boolean Type 39
Review Questions 402.3 Variable Declarations 40
Declaring and Initializing Variables 41Reference Variables 41
2.4 Initial Values for Variables 42Default Values for Fields 42Initializing Local Variables of Primitive Data Types 43Initializing Local Reference Variables 43Lifetime of Variables 44
Review Questions 45Chapter Summary 46Programming Exercise 46
PGJC4_JSE8_OCA.book Page x Monday, June 20, 2016 2:31 PM
CONTENTS xi
3 Declarations 473.1 Class Declarations 483.2 Method Declarations 49
Statements 50Instance Methods and the Object Reference this 50Method Overloading 52
3.3 Constructors 53The Default Constructor 54Overloaded Constructors 56
Review Questions 563.4 Arrays 58
Declaring Array Variables 59Constructing an Array 59Initializing an Array 60Using an Array 61Anonymous Arrays 63Multidimensional Arrays 64Sorting Arrays 68Searching Arrays 69
Review Questions 703.5 Parameter Passing 72
Passing Primitive Data Values 73Passing Reference Values 75Passing Arrays 77Array Elements as Actual Parameters 78final Parameters 80
3.6 Variable Arity Methods 81Calling a Variable Arity Method 82Variable Arity and Fixed Arity Method Calls 84
3.7 The main() Method 85Program Arguments 86
3.8 Enumerated Types 87Declaring Type-safe Enums 87Using Type-safe Enums 88Selected Methods for Enum Types 89
Review Questions 90Chapter Summary 92Programming Exercise 93
4 Access Control 954.1 Java Source File Structure 964.2 Packages 97
Defining Packages 98Using Packages 99Compiling Code into Packages 105
PGJC4_JSE8_OCA.book Page xi Monday, June 20, 2016 2:31 PM
xii CONTENTS
Running Code from Packages 106
4.3 Searching for Classes 107
Review Questions 110
4.4 Scope Rules 114
Class Scope for Members 114
Block Scope for Local Variables 117
4.5 Accessibility Modifiers for Top-Level Type Declarations 118
4.6 Non-Accessibility Modifiers for Classes 120
abstract Classes 120
final Classes 122
Review Questions 123
4.7 Member Accessibility Modifiers 123
public Members 124
protected Members 126
Default Accessibility for Members 127
private Members 128
Review Questions 129
4.8 Non-Accessibility Modifiers for Members 131
static Members 132
final Members 133
abstract Methods 136
synchronized Methods 136
native Methods 137
transient Fields 138
volatile Fields 139
Review Questions 140
Chapter Summary 142
Programming Exercise 142
5 Operators and Expressions 143
5.1 Conversions 144
Widening and Narrowing Primitive Conversions 144
Widening and Narrowing Reference Conversions 145
Boxing and Unboxing Conversions 145
Other Conversions 146
5.2 Type Conversion Contexts 147
Assignment Context 147
Method Invocation Context 148
Casting Context of the Unary Type Cast Operator: (type) 148
Numeric Promotion Context 149
5.3 Precedence and Associativity Rules for Operators 150
5.4 Evaluation Order of Operands 152
Left-Hand Operand Evaluation First 152
Operand Evaluation before Operation Execution 153
Left-to-Right Evaluation of Argument Lists 154
PGJC4_JSE8_OCA.book Page xii Monday, June 20, 2016 2:31 PM
CONTENTS xiii
5.5 Representing Integers 154Calculating Two’s Complement 155Converting Binary Numbers to Decimals 157Converting Decimals to Binary Numbers 157Relationships among Binary, Octal, and Hexadecimal Numbers 157
5.6 The Simple Assignment Operator = 158Assigning Primitive Values 159Assigning References 159Multiple Assignments 159Type Conversions in an Assignment Context 160
Review Questions 1625.7 Arithmetic Operators: *, /, %, +, - 163
Arithmetic Operator Precedence and Associativity 164Evaluation Order in Arithmetic Expressions 164Range of Numeric Values 164Unary Arithmetic Operators: -, + 167Multiplicative Binary Operators: *, /, % 167Additive Binary Operators: +, - 169Numeric Promotions in Arithmetic Expressions 170Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -= 172
Review Questions 1735.8 The Binary String Concatenation Operator + 1745.9 Variable Increment and Decrement Operators: ++, -- 176
The Increment Operator ++ 176The Decrement Operator -- 176
Review Questions 1785.10 Boolean Expressions 1805.11 Relational Operators: <, <=, >, >= 1805.12 Equality 181
Primitive Data Value Equality: ==, != 181Object Reference Equality: ==, != 182Object Value Equality 183
5.13 Boolean Logical Operators: !, ^, &, | 184Operand Evaluation for Boolean Logical Operators 185Boolean Logical Compound Assignment Operators: &=, ^=, |= 185
5.14 Conditional Operators: &&, || 186Short-Circuit Evaluation 187
5.15 Integer Bitwise Operators: ~, &, |, ^ 189Bitwise Compound Assignment Operators: &=, ^=, |= 192
Review Questions 1925.16 The Conditional Operator: ?: 1945.17 Other Operators: new, [], instanceof, -> 195
Review Questions 196Chapter Summary 197Programming Exercise 197
PGJC4_JSE8_OCA.book Page xiii Monday, June 20, 2016 2:31 PM
xiv CONTENTS
6 Control Flow 1996.1 Overview of Control Flow Statements 2006.2 Selection Statements 200
The Simple if Statement 200The if-else Statement 201The switch Statement 203
Review Questions 2106.3 Iteration Statements 213
The while Statement 213The do-while Statement 214The for(;;) Statement 215The for(:) Statement 217
6.4 Transfer Statements 219Labeled Statements 220The break Statement 221The continue Statement 223The return Statement 224
Review Questions 2266.5 Stack-Based Execution and Exception Propagation 2306.6 Exception Types 233
The Exception Class 235The RuntimeException Class 236The Error Class 237Checked and Unchecked Exceptions 237Defining Customized Exceptions 238
6.7 Exception Handling: try, catch, and finally 238The try Block 240The catch Clause 240The finally Clause 245
6.8 The throw Statement 2496.9 The throws Clause 251
Overriding the throws Clause 2536.10 Advantages of Exception Handling 254
Review Questions 255Chapter Summary 258Programming Exercises 258
7 Object-Oriented Programming 2637.1 Single Implementation Inheritance 264
Relationships: is-a and has-a 266The Supertype–Subtype Relationship 267
7.2 Overriding Methods 268Instance Method Overriding 268Covariant return in Overriding Methods 273Overriding versus Overloading 273
PGJC4_JSE8_OCA.book Page xiv Monday, June 20, 2016 2:31 PM
CONTENTS xv
7.3 Hiding Members 275Field Hiding 275Static Method Hiding 275
7.4 The Object Reference super 276Review Questions 279
7.5 Chaining Constructors Using this() and super() 282The this() Constructor Call 282The super() Constructor Call 285
Review Questions 2887.6 Interfaces 290
Defining Interfaces 290Abstract Methods in Interfaces 291Implementing Interfaces 291Extending Interfaces 294Interface References 296Default Methods in Interfaces 297Static Methods in Interfaces 300Constants in Interfaces 302
Review Questions 3047.7 Arrays and Subtyping 309
Arrays and Subtype Covariance 309Array Store Check 311
7.8 Reference Values and Conversions 3117.9 Reference Value Assignment Conversions 3127.10 Method Invocation Conversions Involving References 315
Overloaded Method Resolution 3167.11 Reference Casting and the instanceof Operator 320
The Cast Operator 320The instanceof Operator 321
Review Questions 3257.12 Polymorphism and Dynamic Method Lookup 3297.13 Inheritance versus Aggregation 3317.14 Basic Concepts in Object-Oriented Design 334
Encapsulation 335Cohesion 335Coupling 336
Review Questions 336Chapter Summary 338Programming Exercises 339
8 Fundamental Classes 341
8.1 Overview of the java.lang Package 3428.2 The Object Class 342
Review Questions 346
PGJC4_JSE8_OCA.book Page xv Monday, June 20, 2016 2:31 PM
xvi CONTENTS
8.3 The Wrapper Classes 346Common Wrapper Class Constructors 347Common Wrapper Class Utility Methods 348Numeric Wrapper Classes 351The Character Class 354The Boolean Class 355
Review Questions 3558.4 The String Class 357
Immutability 357Creating and Initializing Strings 357The CharSequence Interface 360Reading Characters from a String 361Comparing Strings 363Character Case in a String 364Concatenation of Strings 364Joining of CharSequence Objects 365Searching for Characters and Substrings 367Extracting Substrings 369Converting Primitive Values and Objects to Strings 369Formatted Strings 370
Review Questions 3718.5 The StringBuilder and StringBuffer Classes 374
Thread-Safety 374Mutability 374Constructing String Builders 374Reading and Changing Characters in String Builders 375Constructing Strings from String Builders 375Appending, Inserting, and Deleting Characters in String Builders 376Controlling String Builder Capacity 378
Review Questions 379Chapter Summary 382Programming Exercises 382
9 Object Lifetime 3839.1 Garbage Collection 3849.2 Reachable Objects 3849.3 Facilitating Garbage Collection 3869.4 Object Finalization 3909.5 Finalizer Chaining 3919.6 Invoking Garbage Collection Programmatically 393
Review Questions 3969.7 Initializers 3999.8 Field Initializer Expressions 400
Declaration Order of Initializer Expressions 4019.9 Static Initializer Blocks 402
PGJC4_JSE8_OCA.book Page xvi Monday, June 20, 2016 2:31 PM
CONTENTS xvii
Declaration Order of Static Initializers 4039.10 Instance Initializer Blocks 404
Declaration Order of Instance Initializers 4059.11 Constructing Initial Object State 406
Review Questions 409Chapter Summary 411
10 The ArrayList<E> Class and Lambda Expressions 41310.1 The ArrayList<E> Class 414
Lists 414Declaring References and Constructing ArrayLists 415Modifying an ArrayList 419Querying an ArrayList 422Traversing an ArrayList 423Converting an ArrayList to an Array 424Sorting an ArrayList 425Arrays versus ArrayList 425
Review Questions 43010.2 Lambda Expressions 433
Behavior Parameterization 434Functional Interfaces 442Defining Lambda Expressions 444Type Checking and Execution of Lambda Expressions 450Filtering Revisited: The Predicate<T> Functional Interface 451
Review Questions 455Chapter Summary 458Programming Exercise 458
11 Date and Time 46111.1 Basic Date and Time Concepts 46211.2 Working with Temporal Classes 462
Creating Temporal Objects 464Querying Temporal Objects 468Comparing Temporal Objects 470Creating Modified Copies of Temporal Objects 470Temporal Arithmetic 474
11.3 Working with Periods 476Creating Periods 476Querying Periods 478Creating Modified Copies of Periods 479More Temporal Arithmetic 479
Review Questions 48311.4 Formatting and Parsing 486
Default Formatters 487
PGJC4_JSE8_OCA.book Page xvii Monday, June 20, 2016 2:31 PM
xviii CONTENTS
Predefined Formatters 488Localized Formatters 490Customized Formatters 495
Review Questions 500Chapter Summary 502Programming Exercise 503
A Taking the Java SE 8 Programmer I Exam 507
A.1 Preparing for the Exam 507A.2 Registering for the Exam 508
Contact Information 509Obtaining an Exam Voucher 509Signing Up for the Test 509After Taking the Exam 509
A.3 How the Exam Is Conducted 510The Testing Locations 510Utilizing the Allotted Time 510The Exam Program 510The Exam Result 511
A.4 The Questions 511Assumptions about the Exam Questions 511Types of Questions Asked 512Types of Answers Expected 512Topics Covered by the Questions 513
B Exam Topics: Java SE 8 Programmer I 515
C Annotated Answers to Review Questions 519
D Solutions to Programming Exercises 553
E Mock Exam: Java SE 8 Programmer I 571
F Annotated Answers to Mock Exam I 605
Index 619
PGJC4_JSE8_OCA.book Page xviii Monday, June 20, 2016 2:31 PM
xix
Figures
Chapter 1 11.1 UML Notation for Classes 31.2 UML Notation for Objects 51.3 Aliases 61.4 Class Diagram Showing Static Members of a Class 81.5 Members of a Class 91.6 Class Diagram Depicting Inheritance Relationship 101.7 Class Diagram Depicting Associations 121.8 Class Diagram Depicting Composition 13
Chapter 2 272.1 Primitive Data Types in Java 37Chapter 3 473.1 Array of Arrays 67
3.2 Parameter Passing: Primitive Data Values 753.3 Parameter Passing: Reference Values 763.4 Parameter Passing: Arrays 78
Chapter 4 954.1 Java Source File Structure 964.2 Package Hierarchy 974.3 File Hierarchy 1074.4 Searching for Classes 1084.5 Block Scope 1174.6 Public Accessibility for Members 1244.7 Protected Accessibility for Members 1274.8 Default Accessibility for Members 1284.9 Private Accessibility for Members 129
Chapter 5 1435.1 Widening Primitive Conversions 1445.2 Converting among Binary, Octal, and Hexadecimal Numbers 1585.3 Overflow and Underflow in Floating-Point Arithmetic 1665.4 Numeric Promotion in Arithmetic Expressions 170
Chapter 6 1996.1 Activity Diagram for if Statements 2016.2 Activity Diagram for a switch Statement 2046.3 Activity Diagram for the while Statement 2136.4 Activity Diagram for the do-while Statement 2146.5 Activity Diagram for the for Statement 2156.6 Enhanced for Statement 2176.7 Method Execution 231
PGJC4_JSE8_OCA.book Page xix Monday, June 20, 2016 2:31 PM
xx FIGURES
6.8 Exception Propagation 2336.9 Partial Exception Inheritance Hierarchy 234
6.10 The try-catch-finally Construct 2396.11 Exception Handling (Scenario 1) 2416.12 Exception Handling (Scenario 2) 2436.13 Exception Handling (Scenario 3) 245
Chapter 7 2637.1 Inheritance Hierarchy 2677.2 Inheritance Hierarchy for Example 7.2 and Example 7.3 2697.3 Inheritance Hierarchies 2957.4 Inheritance Relationships for Interface Constants 3037.5 Reference Type Hierarchy: Arrays and Subtype Covariance 3107.6 Type Hierarchy That Illustrates Polymorphism 3307.7 Implementing Data Structures by Inheritance and Aggregation 332
Chapter 8 3418.1 Partial Inheritance Hierarchy in the java.lang Package 3428.2 Converting Values among Primitive, Wrapper, and String Types 347
Chapter 9 3839.1 Memory Organization at Runtime 386Chapter 10 41310.1 Partial ArrayList Inheritance Hierarchy 415Chapter 11 461
PGJC4_JSE8_OCA.book Page xx Monday, June 20, 2016 2:31 PM
xxi
Tables
Chapter 1 11.1 Terminology for Class Members 91.2 Format Specifier Examples 20
Chapter 2 272.1 Keywords in Java 292.2 Reserved Literals in Java 292.3 Reserved Keywords Not Currently in Use 292.4 Separators in Java 292.5 Examples of Literals 302.6 Examples of Decimal, Binary, Octal, and Hexadecimal Literals 302.7 Examples of Character Literals 332.8 Escape Sequences 332.9 Examples of Escape Sequence \ddd 34
2.10 Range of Integer Values 382.11 Range of Character Values 382.12 Range of Floating-Point Values 392.13 Boolean Values 392.14 Summary of Primitive Data Types 392.15 Default Values 42
Chapter 3 473.1 Parameter Passing by Value 73Chapter 4 954.1 Accessing Members within a Class 115
4.2 Summary of Accessibility Modifiers for Top-Level Types 1204.3 Summary of Non-Accessibility Modifiers for Classes 1224.4 Summary of Accessibility Modifiers for Members 1294.5 Summary of Non-Accessibility Modifiers for Members 139
Chapter 5 1435.1 Selected Conversion Contexts and Conversion Categories 1475.2 Operator Summary 1515.3 Representing Signed byte Values Using Two’s Complement 1555.4 Examples of Truncated Values 1625.5 Arithmetic Operators 1645.6 Examples of Arithmetic Expression Evaluation 1695.7 Arithmetic Compound Assignment Operators 1725.8 Relational Operators 1805.9 Primitive Data Value Equality Operators 181
5.10 Reference Equality Operators 182
PGJC4_JSE8_OCA.book Page xxi Monday, June 20, 2016 2:31 PM
xxii TABLES
5.11 Truth Values for Boolean Logical Operators 1845.12 Boolean Logical Compound Assignment Operators 1855.13 Conditional Operators 1865.14 Truth Values for Conditional Operators 1865.15 Integer Bitwise Operators 1895.16 Result Table for Bitwise Operators 1905.17 Examples of Bitwise Operations 1905.18 Bitwise Compound Assignment Operators 192
Chapter 6 1996.1 The return Statement 225Chapter 7 2637.1 Overriding versus Overloading 274
7.2 Same Signature for Subclass and Superclass Method 2767.3 Types and Values 309
Chapter 8 341Chapter 9 383Chapter 10 41310.1 Summary of Arrays versus ArrayLists 42610.2 Selected Functional Interfaces from the java.util.function Package 444
Chapter 11 46111.1 Selected Common Method Prefix of the Temporal Classes 46311.2 Selected ISO-Based Predefined Formatters for Date and Time 48911.3 Format Styles for Date and Time 49011.4 Combination of Format Styles and Localized Formatters 49111.5 Selected Date/Time Pattern Letters 496
PGJC4_JSE8_OCA.book Page xxii Monday, June 20, 2016 2:31 PM
xxiii
Examples
Chapter 1 11.1 Basic Elements of a Class Declaration 41.2 Static Members in Class Declaration 81.3 Defining a Subclass 111.4 An Application 161.5 Formatted Output 21
Chapter 2 272.1 Default Values for Fields 422.2 Flagging Uninitialized Local Variables of Primitive Data Types 432.3 Flagging Uninitialized Local Reference Variables 44
Chapter 3 473.1 Using the this Reference 513.2 Namespaces 543.3 Using Arrays 623.4 Using Anonymous Arrays 643.5 Using Multidimensional Arrays 673.6 Passing Primitive Values 743.7 Passing Reference Values 753.8 Passing Arrays 773.9 Array Elements as Primitive Data Values 79
3.10 Array Elements as Reference Values 793.11 Calling a Variable Arity Method 833.12 Passing Program Arguments 863.13 Using Enums 88
Chapter 4 954.1 Defining Packages and Using Type Import 994.2 Single Static Import 1024.3 Avoiding the Interface Constant Antipattern 1024.4 Importing Enum Constants 1034.5 Shadowing Static Import 1044.6 Conflict in Importing Static Method with the Same Signature 1054.7 Class Scope 1164.8 Accessibility Modifiers for Classes and Interfaces 1184.9 Abstract Classes 121
4.10 Public Accessibility of Members 1254.11 Accessing Static Members 1324.12 Using final Modifier 134
PGJC4_JSE8_OCA.book Page xxiii Monday, June 20, 2016 2:31 PM
xxiv EXAMPLES
4.13 Synchronized Methods 137Chapter 5 1435.1 Evaluation Order of Operands and Arguments 153
5.2 Numeric Promotion in Arithmetic Expressions 1715.3 Short-Circuit Evaluation Involving Conditional Operators 1875.4 Bitwise Operations 191
Chapter 6 1996.1 Fall-Through in a switch Statement 2056.2 Using break in a switch Statement 2066.3 Nested switch Statement 2076.4 Strings in switch Statement 2086.5 Enums in switch Statement 2096.6 The break Statement 2216.7 Labeled break Statement 2226.8 continue Statement 2236.9 Labeled continue Statement 224
6.10 The return Statement 2256.11 Method Execution 2306.12 The try-catch Construct 2416.13 Exception Propagation 2436.14 The try-catch-finally Construct 2466.15 The try-finally Construct 2476.16 The finally Clause and the return Statement 2486.17 Throwing Exceptions 2506.18 The throws Clause 252
Chapter 7 2637.1 Extending Classes: Inheritance and Accessibility 2657.2 Overriding, Overloading, and Hiding 2707.3 Using the super Keyword 2777.4 Constructor Overloading 2827.5 The this() Constructor Call 2847.6 The super() Constructor Call 2857.7 Implementing Interfaces 2927.8 Default Methods in Interfaces 2977.9 Default Methods and Multiple Inheritance 299
7.10 Static Methods in Interfaces 3017.11 Constants in Interfaces 3027.12 Inheriting Constants in Interfaces 3047.13 Assigning and Passing Reference Values 3127.14 Choosing the Most Specific Method (Simple Case) 3177.15 Overloaded Method Resolution 3187.16 The instanceof and Cast Operators 3227.17 Using the instanceof Operator 3237.18 Polymorphism and Dynamic Method Lookup 3307.19 Implementing Data Structures by Inheritance and Aggregation 332
Chapter 8 3418.1 Methods in the Object Class 3448.2 String Representation of Integers 3538.3 String Construction and Equality 3598.4 Reading Characters from a String 362
PGJC4_JSE8_OCA.book Page xxiv Monday, June 20, 2016 2:31 PM
EXAMPLES xxv
Chapter 9 3839.1 Garbage Collection Eligibility 3889.2 Using Finalizers 3929.3 Invoking Garbage Collection 3949.4 Initializer Expression Order and Method Calls 4029.5 Static Initializers and Forward References 4039.6 Instance Initializers and Forward References 4059.7 Object State Construction 4069.8 Initialization Anomaly under Object State Construction 408
Chapter 10 41310.1 Using an ArrayList 42710.2 Implementing Customized Methods for Filtering an ArrayList 43410.3 Implementing an Interface for Filtering an ArrayList 43610.4 User-Defined Functional Interface for Filtering an ArrayList 43910.5 Using the Predicate<T> Functional Interface for Filtering an ArrayList 44110.6 Accessing Members in an Enclosing Object 44710.7 Accessing Local Variables in an Enclosing Method 44910.8 Filtering an ArrayList 452
Chapter 11 46111.1 Creating Temporal Objects 46711.2 Using Temporal Objects 47211.3 Temporal Arithmetic 47511.4 Period-Based Loop 48111.5 More Temporal Arithmetic 48211.6 Using Default Date and Time Formatters 48811.7 Using Predefined Format Styles with Time-Based Values 49211.8 Using Predefined Format Styles with Date-Based Values 49311.9 Using Predefined Format Styles with Date and Time-Based Values 494
11.10 Formatting and Parsing with Letter Patterns 49711.11 Formatting with Date/Time Letter Patterns 499
PGJC4_JSE8_OCA.book Page xxv Monday, June 20, 2016 2:31 PM