A programmer's guide to Java SCJP certification a comprehensive primer [3rd ed] 0321556054, 9780321556059, 9780321585738, 0321585739

This book will help you prepare for and pass the Sun Certified Programmer for the Java Platform SE 6 (CX-310-065) Exam.

238 35 6MB

English Pages 1039 [1089] Year 2008;2009

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover......Page 1
Contents......Page 10
List of Figures......Page 24
List of Tables......Page 28
List of Examples......Page 30
Foreword......Page 36
Preface......Page 38
1 Basics of Java Programming......Page 48
1.2 Classes......Page 49
Declaring Members: Fields and Methods......Page 50
Class Instantiation, Reference Values, and References......Page 51
1.4 Instance Members......Page 53
1.5 Static Members......Page 54
1.6 Inheritance......Page 57
1.7 Aggregation......Page 59
Review Questions......Page 60
Essential Elements of a Java Application......Page 62
Compiling and Running an Application......Page 63
Review Questions......Page 64
Programming Exercise......Page 65
2 Language Fundamentals......Page 66
Keywords......Page 67
Literals......Page 68
Floating-Point Literals......Page 69
Character Literals......Page 70
White Spaces......Page 72
Comments......Page 73
Review Questions......Page 74
Integer Types......Page 75
The Floating-Point Types......Page 76
The boolean Type......Page 77
Declaring and Initializing Variables......Page 78
Reference Variables......Page 79
Default Values for Fields......Page 80
Initializing Local Variables of Primitive Data Types......Page 81
Lifetime of Variables......Page 82
Review Questions......Page 83
Programming Exercise......Page 84
3 Declarations......Page 86
3.1 Class Declarations......Page 87
Naming Patterns for Properties......Page 88
Naming Patterns for the Event Model......Page 89
3.3 Method Declarations......Page 91
Instance Methods and the Object Reference this......Page 92
Method Overloading......Page 94
3.4 Constructors......Page 95
The Default Constructor......Page 96
Overloaded Constructors......Page 98
Review Questions......Page 99
Using Typesafe Enums......Page 101
Declaring Enum Constructors and Members......Page 102
Implicit Static Methods for Enum Types......Page 104
Inherited Methods from the Enum Class......Page 105
Extending Enum Types: Constant-Specific Class Bodies......Page 106
Declaring Typesafe Enums Revisited......Page 109
Review Questions......Page 110
3.6 Arrays......Page 116
Constructing an Array......Page 117
Initializing an Array......Page 118
Using an Array......Page 119
Anonymous Arrays......Page 121
Multidimensional Arrays......Page 122
Review Questions......Page 126
3.7 Parameter Passing......Page 128
Passing Primitive Data Values......Page 129
Passing Reference Values......Page 131
Passing Arrays......Page 133
Array Elements as Actual Parameters......Page 134
final Parameters......Page 136
3.8 Variable Arity Methods......Page 137
Calling a Varargs Method......Page 138
Varargs and Non-Varargs Method Calls......Page 140
3.9 The main() Method......Page 141
Program Arguments......Page 142
Review Questions......Page 143
Chapter Summary......Page 147
Programming Exercises......Page 148
4 Access Control......Page 150
4.1 Java Source File Structure......Page 151
4.2 Packages......Page 152
Defining Packages......Page 153
Using Packages......Page 154
Compiling Code into Packages......Page 162
4.3 Searching for Classes......Page 164
4.4 The JAR Utility......Page 167
4.5 System Properties......Page 169
Review Questions......Page 170
Class Scope for Members......Page 176
Block Scope for Local Variables......Page 178
4.7 Accessibility Modifiers for Top-Level Type Declarations......Page 179
abstract Classes......Page 182
final Classes......Page 183
4.9 Member Accessibility Modifiers......Page 185
public Members......Page 186
protected Members......Page 188
Default Accessibility for Members......Page 189
private Members......Page 190
Review Questions......Page 191
4.10 Other Modifiers for Members......Page 193
static Members......Page 194
final Members......Page 195
synchronized Methods......Page 197
native Methods......Page 198
transient Fields......Page 199
volatile Fields......Page 200
Review Questions......Page 201
Programming Exercise......Page 204
5 Operators and Expressions......Page 206
Widening and Narrowing Primitive Conversions......Page 207
Widening and Narrowing Reference Conversions......Page 208
Other Conversions......Page 209
5.2 Type Conversion Contexts......Page 210
Casting Context of the Unary Type Cast Operator: (type)......Page 211
Numeric Promotion Context......Page 212
5.3 Precedence and Associativity Rules for Operators......Page 213
Operand Evaluation before Operation Execution......Page 215
Assigning References......Page 216
Multiple Assignments......Page 217
Type Conversions in Assignment Context......Page 218
Review Questions......Page 220
Evaluation Order in Arithmetic Expressions......Page 221
Range of Numeric Values......Page 222
Unary Arithmetic Operators: -, +......Page 224
Multiplicative Binary Operators: *, /, %......Page 225
Numeric Promotions in Arithmetic Expressions......Page 227
Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -=......Page 229
Review Questions......Page 231
5.7 The Binary String Concatenation Operator +......Page 232
5.8 Variable Increment and Decrement Operators: ++, --......Page 233
The Decrement Operator --......Page 234
Review Questions......Page 235
5.10 Relational Operators: =......Page 237
Primitive Data Value Equality: ==, !=......Page 238
Object Reference Equality: ==, !=......Page 239
Object Value Equality......Page 240
5.12 Boolean Logical Operators: !, ^, &, |......Page 241
Boolean Logical Compound Assignment Operators: &=, ^=, |=......Page 242
5.13 Conditional Operators: &&, ||......Page 243
Short-Circuit Evaluation......Page 244
Review Questions......Page 246
5.15 Other Operators: new, [], instanceof......Page 248
Programming Exercise......Page 249
6 Control Flow......Page 250
The Simple if Statement......Page 251
The if-else Statement......Page 252
The switch Statement......Page 254
Review Questions......Page 259
6.3 Iteration Statements......Page 263
The do-while Statement......Page 264
The for(;;) Statement......Page 265
The for(:) Statement......Page 267
Labeled Statements......Page 270
The break Statement......Page 271
The continue Statement......Page 273
The return Statement......Page 275
Review Questions......Page 276
6.5 Stack-Based Execution and Exception Propagation......Page 282
6.6 Exception Types......Page 286
The RuntimeException Class......Page 288
The Error Class......Page 289
Checked and Unchecked Exceptions......Page 290
Defining New Exceptions......Page 291
The try Block......Page 292
The catch Block......Page 293
The finally Block......Page 298
6.8 The throw Statement......Page 302
6.9 The throws Clause......Page 304
Review Questions......Page 307
The assert Statement and the AssertionError Class......Page 312
Compiling Assertions......Page 314
Runtime Enabling and Disabling of Assertions......Page 316
Using Assertions......Page 319
Review Questions......Page 323
Programming Exercises......Page 326
7 Object-Oriented Programming......Page 330
7.1 Single Implementation Inheritance......Page 331
Relationships: is-a and has-a......Page 333
The Supertype-Subtype Relationship......Page 334
Instance Method Overriding......Page 335
Covariant return in Overriding Methods......Page 337
Overriding vs. Overloading......Page 339
Static Method Hiding......Page 341
7.4 The Object Reference super......Page 342
Review Questions......Page 344
The this() Constructor Call......Page 349
The super() Constructor Call......Page 352
Review Questions......Page 355
7.6 Interfaces......Page 356
Abstract Method Declarations......Page 357
Implementing Interfaces......Page 359
Extending Interfaces......Page 360
Constants in Interfaces......Page 361
Review Questions......Page 362
Arrays and Subtype Covariance......Page 364
7.8 Reference Values and Conversions......Page 366
7.9 Reference Value Assignment Conversions......Page 367
7.10 Method Invocation Conversions Involving References......Page 370
Overloaded Method Resolution......Page 371
The Cast Operator......Page 374
The instanceof Operator......Page 375
Review Questions......Page 379
7.12 Polymorphism and Dynamic Method Lookup......Page 387
7.13 Inheritance Versus Aggregation......Page 389
Encapsulation......Page 392
Coupling......Page 393
Review Questions......Page 394
Programming Exercises......Page 396
8 Nested Type Declarations......Page 398
8.1 Overview of Nested Type Declarations......Page 399
Declaring and Using Static Member Types......Page 402
Accessing Members in Enclosing Context......Page 404
8.3 Non-Static Member Classes......Page 406
Instantiating Non-Static Member Classes......Page 407
Accessing Members in Enclosing Context......Page 409
Review Questions......Page 414
8.4 Local Classes......Page 418
Accessing Declarations in Enclosing Context......Page 419
Instantiating Local Classes......Page 421
Extending an Existing Class......Page 424
Implementing an Interface......Page 426
Accessing Declarations in Enclosing Context......Page 427
Review Questions......Page 429
Programming Exercise......Page 433
9 Object Lifetime......Page 436
9.2 Reachable Objects......Page 437
9.3 Facilitating Garbage Collection......Page 439
9.4 Object Finalization......Page 443
9.5 Finalizer Chaining......Page 444
9.6 Invoking Garbage Collection Programmatically......Page 445
Review Questions......Page 448
9.8 Field Initializer Expressions......Page 453
9.9 Static Initializer Blocks......Page 457
9.10 Instance Initializer Blocks......Page 460
9.11 Constructing Initial Object State......Page 463
Review Questions......Page 467
Chapter Summary......Page 469
10 Fundamental Classes......Page 470
10.2 The Object Class......Page 471
10.3 The Wrapper Classes......Page 475
Common Wrapper Class Constructors......Page 476
Common Wrapper Class Utility Methods......Page 477
Numeric Wrapper Classes......Page 480
The Character Class......Page 483
Review Questions......Page 484
Creating and Initializing Strings......Page 486
The CharSequence Interface......Page 489
Reading Characters from a String......Page 490
Comparing Strings......Page 492
Concatenation of Strings......Page 493
Searching for Characters and Substrings......Page 495
Extracting Substrings......Page 496
Formatting Values......Page 497
Pattern Matching......Page 498
Review Questions......Page 499
Mutability......Page 503
Reading and Changing Characters in String Builders......Page 504
Appending, Inserting, and Deleting Characters in String Builders......Page 505
Controlling String Builder Capacity......Page 507
Review Questions......Page 508
Chapter Summary......Page 511
Programming Exercises......Page 512
11 Files and Streams......Page 514
11.2 The File Class......Page 515
Querying the File System......Page 517
File and Directory Permissions......Page 519
Creating New Files and Directories......Page 520
Deleting Files and Directories......Page 521
11.3 Byte Streams: Input Streams and Output Streams......Page 522
File Streams......Page 524
Reading and Writing Binary Values......Page 526
Review Questions......Page 531
11.4 Character Streams: Readers and Writers......Page 535
Print Writers......Page 537
Writing Text Files......Page 539
Reading Text Files......Page 541
Using Buffered Writers......Page 542
Using Buffered Readers......Page 543
The Standard Input, Output, and Error Streams......Page 546
11.5 The Console class......Page 547
Review Questions......Page 553
11.6 Object Serialization......Page 557
The ObjectOutputStream Class......Page 558
The ObjectInputStream Class......Page 559
Customizing Object Serialization......Page 564
Serialization and Inheritance......Page 566
Review Questions......Page 569
Chapter Summary......Page 576
Programming Exercise......Page 577
12 Localization, Pattern Matching, and Formatting......Page 578
12.1 The java.util.Locale Class......Page 579
12.2 The java.util.Date Class......Page 582
12.3 The java.util.Calendar Class......Page 583
Selected get and set Methods......Page 584
Manipulating a Calendar......Page 586
Comparing Calendars......Page 587
Static Factory Methods to Create a Date/Time Formatter......Page 588
Formatting Dates......Page 589
Parsing Strings to Date/Time......Page 590
Managing the Calendar and the Number Formatter......Page 592
Formatting Numbers and Currency......Page 593
Specifying the Number of Digits......Page 594
Review Questions......Page 598
Regular Expression Fundamentals......Page 601
Escaping Metacharacters......Page 608
The java.util.regex.Pattern Class......Page 609
The java.util.regex.Matcher Class......Page 613
The java.util.Scanner Class......Page 618
Review Questions......Page 629
Overview......Page 640
Defining Format Specifiers......Page 642
Conversion Categories and Formatting Conversions......Page 644
Selected Format Exceptions......Page 648
Using the format() Method......Page 649
Review Questions......Page 651
Programming Exercises......Page 657
13 Threads......Page 660
13.2 Overview of Threads......Page 661
13.4 Thread Creation......Page 662
Implementing the Runnable Interface......Page 663
Extending the Thread Class......Page 666
Review Questions......Page 669
Locks......Page 673
Synchronized Methods......Page 674
Synchronized Blocks......Page 676
Review Questions......Page 678
Thread States......Page 681
Thread Scheduler......Page 685
Running and Yielding......Page 686
Waiting and Notifying......Page 687
Joining......Page 694
Blocking for I/O......Page 696
Thread Termination......Page 697
Deadlocks......Page 698
Review Questions......Page 700
Chapter Summary......Page 705
Programming Exercises......Page 706
14 Generics......Page 708
14.1 Introducing Generics......Page 709
Generic Types......Page 710
Parameterized Types......Page 712
Generic Interfaces......Page 713
Extending Generic Types......Page 715
Raw Types and Unchecked Warnings......Page 717
14.3 Collections and Generics......Page 719
The Subtype Covariance Problem with Parameterized Types......Page 720
Subtype Covariance: ? extends Type......Page 722
Subtype Contravariance: ? super Type......Page 723
Some Restrictions on Wildcard Types......Page 724
14.5 Using References of Wildcard Parameterized Types......Page 725
Generic Reference Assignment......Page 726
Using Parameterized References to Call Set and Get Methods......Page 727
14.6 Bounded Type Parameters......Page 731
Review Questions......Page 733
14.7 Implementing a Simplified Generic Stack......Page 742
14.8 Generic Methods and Constructors......Page 744
Generic Method Declaration......Page 746
Calling Generic Methods......Page 747
14.9 Wildcard Capture......Page 750
Nested Wildcards......Page 752
Wildcard Parameterized Types as Formal Parameters......Page 754
Flexible Comparisons with Wildcards......Page 756
Recursive Bounds......Page 759
14.11 Type Erasure......Page 761
Method Signature......Page 763
Implications for Overloading......Page 764
Implications for Overriding......Page 765
Reifiable Types......Page 769
Implications for instanceof operator......Page 770
Implications for Casting......Page 771
Implications for Arrays......Page 773
Implications for Varargs......Page 776
Implications for Exception Handling......Page 777
Implications for Nested Classes......Page 778
Other Implications......Page 780
Review Questions......Page 781
Chapter Summary......Page 791
Programming Exercises......Page 792
15 Collections and Maps......Page 794
15.1 Comparing Objects......Page 795
The equals() Method......Page 798
The hashCode() Method......Page 807
The Comparable Interface......Page 812
The Comparator Interface......Page 818
Review Questions......Page 822
15.2 The Java Collections Framework......Page 824
Core Interfaces......Page 825
Implementations......Page 827
Basic Operations......Page 831
Iterators......Page 832
Array Operations......Page 837
Review Questions......Page 838
The HashSet and LinkedHashSet Classes......Page 843
The SortedSet Interface......Page 847
The NavigableSet Interface......Page 848
The TreeSet Class......Page 849
15.6 Lists......Page 851
The ArrayList, LinkedList, and Vector Classes......Page 853
The Queue Interface......Page 856
The PriorityQueue and LinkedList Classes......Page 857
The Deque Interface......Page 860
The ArrayDeque and LinkedList Class......Page 862
Review Questions......Page 863
Basic Operations......Page 868
Collection Views......Page 869
The HashMap, LinkedHashMap, and Hashtable Classes......Page 870
The SortedMap Interface......Page 873
The NavigableMap Interface......Page 874
The TreeMap Class......Page 875
Review Questions......Page 880
Ordering Elements in Lists......Page 885
Searching in Collections......Page 887
Changing Elements in Collections......Page 888
Sorting Arrays......Page 889
Searching in Arrays......Page 890
Creating List Views of Arrays......Page 892
Review Questions......Page 893
Chapter Summary......Page 896
Programming Exercises......Page 897
A.1 Preparing for the Programmer Exam......Page 898
Contact Information......Page 899
Utilizing the Allotted Time......Page 900
Types of Questions Asked......Page 901
Topics Covered by the Questions......Page 902
A.5 Moving on to Other Java Technology Exams......Page 903
B: Objectives for the SCJP 1.6 Exam......Page 904
C: Objectives for the SCJP 1.6 Upgrade Exam......Page 910
D: Annotated Answers to Review Questions......Page 916
E: Solutions to Programming Exercises......Page 982
F: Mock Exam......Page 1006
Binary, Octal, and Hexadecimal Number System......Page 1052
Converting Binary Numbers to Decimals......Page 1053
G.2 Relationship between Binary, Octal, and Hexadecimal Numbers......Page 1054
Converting Decimals to Binary Numbers......Page 1055
Converting Decimals to Octal and Hexadecimal Numbers......Page 1056
G.4 Representing Integers......Page 1057
Calculating 2’s Complement......Page 1058
A......Page 1060
C......Page 1062
D......Page 1066
E......Page 1067
F......Page 1068
G......Page 1069
I......Page 1070
J......Page 1071
L......Page 1072
M......Page 1074
N......Page 1075
O......Page 1076
P......Page 1078
R......Page 1079
S......Page 1080
T......Page 1083
V......Page 1085
Z......Page 1086
Recommend Papers

A programmer's guide to Java SCJP certification a comprehensive primer [3rd ed]
 0321556054, 9780321556059, 9780321585738, 0321585739

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

A Programmer’s Guide to Java™ SCJP Certification Third Edition

This page intentionally left blank

A Programmer’s Guide to Java™ SCJP Certification A Comprehensive Primer Third Edition

Khalid A. Mughal Rolf W. Rasmussen

Upper Saddle River, New Jersey • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sidney • Tokyo • Singapore • Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the United States please contact: International Sales [email protected] Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Mughal, Khalid Azim. A programmer's guide to Java SCJP certification : a comprehensive primer / Khalid A. Mughal, Rolf W. Rasmussen.—3rd ed. p. cm. Previously published under title: A programmer’s guide to Java certification. Includes bibliographical references and index. ISBN 0-321-55605-4 (pbk. : alk. paper) 1. Electronic data processing personnel--Certification. 2. Operating systems (Computers)—Examinations--Study guides. 3. Java (Computer program language)--Examinations-Study guides. I. Rasmussen, Rolf (Rolf W.) II. Mughal, Khalid Azim. Programmer’s guide to Java certification. III. Title. QA76.3.M846 2008 005.2'762--dc22

2008048822

Copyright © 2009 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: ISBN-13: 978-0-321-55605-9 ISBN-10: 0-321-55605-4 Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts. First printing, December 2008

To the loving memory of my mother, Zubaida Begum, and my father, Mohammed Azim. —K.A.M.

For Olivia E. Rasmussen and Louise J. Dahlmo. —R.W.R.

This page intentionally left blank

Contents Overview

Foreword Preface 1 Basics of Java Programming

xxxv xxxvii 1

2 Language Fundamentals

19

3 Declarations

39

4 Access Control

103

5 Operators and Expressions

159

6 Control Flow

203

7 Object-Oriented Programming

283

8 Nested Type Declarations

351

9 Object Lifetime

389

10 Fundamental Classes

423

11 Files and Streams

467

12 Localization, Pattern Matching and Formatting

531

13 Threads

613

14 Generics

661 vii

viii

CONTENTS

15 Collections and Maps

747

A Taking the SCJP 1.6 Exam

851

B Objectives for the SCJP 1.6 Exam

857

C Objectives for the SCJP 1.6 Upgrade Exam

863

D Annotated Answers to Review Questions

869

E Solutions to Programming Exercises

935

F Mock Exam

959

G Number Systems and Number Representation Index

1005 1013

Contents

List of Figures

xxiii

List of Tables

xxvii

List of Examples

xxix

Foreword

xxxv

Preface 1 Basics of Java Programming 1.1 1.2 1.3

1.4 1.5 1.6 1.7 1.8 1.9 1.10

Introduction Classes Declaring Members: Fields and Methods Objects Class Instantiation, Reference Values, and References Object Aliases Instance Members Invoking Methods Static Members Inheritance Aggregation Tenets of Java Review Questions Java Programs Sample Java Application Essential Elements of a Java Application Compiling and Running an Application Review Questions Chapter Summary Programming Exercise

xxxvii 1 2 2 3 4 4 6 6 7 7 10 12 13 13 15 15 15 16 17 18 18

ix

x

CONTENTS

2

Language Fundamentals 2.1

2.2

2.3

2.4

3

Basic Language Elements Lexical Tokens Identifiers Keywords Literals Integer Literals Floating-Point Literals Boolean Literals Character Literals String Literals White Spaces Comments Review Questions Primitive Data Types Integer Types The char Type The Floating-Point Types The boolean Type Review Questions Variable Declarations Declaring and Initializing Variables Reference Variables Initial Values for Variables Default Values for Fields Initializing Local Variables of Primitive Data Types Initializing Local Reference Variables Lifetime of Variables Review Questions Chapter Summary Programming Exercise

Declarations 3.1 3.2

3.3

3.4

Class Declarations JavaBeans Standard Naming Patterns for Properties Naming Patterns for the Event Model Method Declarations Statements Instance Methods and the Object Reference this Method Overloading Constructors The Default Constructor Overloaded Constructors Review Questions

19 20 20 20 20 21 22 22 23 23 25 25 26 27 28 28 29 29 30 31 31 31 32 33 33 34 35 35 36 37 37

39 40 41 41 42 44 45 45

47 48 49 51 52

CONTENTS

xi

3.5

3.6

3.7

3.8

3.9

Enumerated Types Declaring Typesafe Enums Using Typesafe Enums Declaring Enum Constructors and Members Implicit Static Methods for Enum Types Inherited Methods from the Enum Class Extending Enum Types: Constant-Specific Class Bodies Declaring Typesafe Enums Revisited Review Questions Arrays Declaring Array Variables Constructing an Array Initializing an Array Using an Array Anonymous Arrays Multidimensional Arrays Review Questions Parameter Passing Passing Primitive Data Values Passing Reference Values Passing Arrays Array Elements as Actual Parameters final Parameters Variable Arity Methods Calling a Varargs Method Varargs and Non-Varargs Method Calls The main() Method Program Arguments Review Questions Chapter Summary Programming Exercises

4 Access Control 4.1 4.2

4.3 4.4 4.5 4.6

Java Source File Structure Packages Defining Packages Using Packages Compiling Code into Packages Running Code from Packages Searching for Classes The JAR Utility System Properties Review Questions Scope Rules Class Scope for Members

54 54 54 55 57 58 59 62 63 69 70 70 71 72 74 75 79 81 82 84 86 87 89 90 91 93 94 95 96 100 101

103 104 105 106 107 115 117 117 120 122 123 129 129

xii

CONTENTS

4.7 4.8

4.9

4.10

5

Block Scope for Local Variables Accessibility Modifiers for Top-Level Type Declarations Other Modifiers for Classes abstract Classes final Classes Review Questions Member Accessibility Modifiers public Members protected Members Default Accessibility for Members private Members Review Questions Other Modifiers for Members static Members final Members abstract Methods synchronized Methods native Methods transient Fields volatile Fields Review Questions Chapter Summary Programming Exercise

Operators and Expressions 5.1

5.2

5.3 5.4

5.5

Conversions Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Boxing and Unboxing Conversions Other Conversions Type Conversion Contexts Assignment Context Method Invocation Context Casting Context of the Unary Type Cast Operator: (type) Numeric Promotion Context Precedence and Associativity Rules for Operators Evaluation Order of Operands Left-Hand Operand Evaluation First Operand Evaluation before Operation Execution Left to Right Evaluation of Argument Lists The Simple Assignment Operator = Assigning Primitive Values Assigning References Multiple Assignments Type Conversions in Assignment Context

131 132 135 135 136 138 138 139 141 142 143 144 146 147 148 150 150 151 152 153 154 157 157

159 160 160 161 162 162 163 164 164 164 165 166 168 168 168 169 169 169 169 170 171

CONTENTS

xiii

5.6

5.7 5.8

5.9 5.10 5.11

5.12

5.13

5.14 5.15

Review Questions Arithmetic Operators: *, /, %, +, Arithmetic Operator Precedence and Associativity Evaluation Order in Arithmetic Expressions Range of Numeric Values Unary Arithmetic Operators: -, + Multiplicative Binary Operators: *, /, % Additive Binary Operators: +, Numeric Promotions in Arithmetic Expressions Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -= Review Questions The Binary String Concatenation Operator + Variable Increment and Decrement Operators: ++, -The Increment Operator ++ The Decrement Operator -Review Questions Boolean Expressions Relational Operators: = Equality Primitive Data Value Equality: ==, != Object Reference Equality: ==, != Object Value Equality Boolean Logical Operators: !, ^, &, | Operand Evaluation for Boolean Logical Operators Boolean Logical Compound Assignment Operators: &=, ^=, |= Conditional Operators: &&, || Short-Circuit Evaluation Review Questions The Conditional Operator: ?: Other Operators: new, [], instanceof Chapter Summary Programming Exercise

6 Control Flow 6.1 6.2

6.3

Overview of Control Flow Statements Selection Statements The Simple if Statement The if-else Statement The switch Statement Review Questions Iteration Statements The while Statement The do-while Statement The for(;;) Statement The for(:) Statement

173 174 174 174 175 177 178 180 180 182 184 185 186 187 187 188 190 190 191 191 192 193 194 195 195 196 197 199 201 201 202 202

203 204 204 204 205 207 212 216 217 217 218 220

xiv

CONTENTS

6.4

6.5 6.6

6.7

6.8 6.9 6.10

7

Transfer Statements Labeled Statements The break Statement The continue Statement The return Statement Review Questions Stack-Based Execution and Exception Propagation Exception Types The Exception Class The RuntimeException Class The Error Class Checked and Unchecked Exceptions Defining New Exceptions Exception Handling: try, catch, and finally The try Block The catch Block The finally Block The throw Statement The throws Clause Review Questions Assertions The assert Statement and the AssertionError Class Compiling Assertions Runtime Enabling and Disabling of Assertions Using Assertions Review Questions Chapter Summary Programming Exercises

Object-Oriented Programming 7.1

7.2

7.3

7.4 7.5

Single Implementation Inheritance Inheritance Hierarchy Relationships: is-a and has-a The Supertype-Subtype Relationship Overriding Methods Instance Method Overriding Covariant return in Overriding Methods Overriding vs. Overloading Hiding Members Field Hiding Static Method Hiding The Object Reference super Review Questions Chaining Constructors Using this() and super() The this() Constructor Call

223 223 224 226 228 229 235 239 241 241 242 243 244 245 245 246 251 255 257 260 265 265 267 269 272 276 279 279

283 284 286 286 287 288 288 290 292 294 294 294 295 297 302 302

CONTENTS

xv

7.6

7.7

7.8 7.9 7.10 7.11

7.12 7.13 7.14

The super() Constructor Call Review Questions Interfaces Defining Interfaces Abstract Method Declarations Implementing Interfaces Extending Interfaces Interface References Constants in Interfaces Review Questions Arrays and Subtyping Arrays and Subtype Covariance Array Store Check Reference Values and Conversions Reference Value Assignment Conversions Method Invocation Conversions Involving References Overloaded Method Resolution Reference Casting and the instanceof Operator The Cast Operator The instanceof Operator Review Questions Polymorphism and Dynamic Method Lookup Inheritance Versus Aggregation Basic Concepts in Object-Oriented Design Encapsulation Cohesion Coupling Review Questions Chapter Summary Programming Exercises

8 Nested Type Declarations 8.1 8.2

8.3

8.4

8.5

Overview of Nested Type Declarations Static Member Types Declaring and Using Static Member Types Accessing Members in Enclosing Context Non-Static Member Classes Instantiating Non-Static Member Classes Accessing Members in Enclosing Context Review Questions Local Classes Accessing Declarations in Enclosing Context Instantiating Local Classes Anonymous Classes Extending an Existing Class

305 308 309 310 310 312 313 314 314 315 317 317 319 319 320 323 324 327 327 328 332 340 342 345 345 346 346 347 349 349

351 352 355 355 357 359 360 362 367 371 372 374 377 377

xvi

CONTENTS

Implementing an Interface Instantiating Anonymous Classes Accessing Declarations in Enclosing Context Review Questions Chapter Summary Programming Exercise

9

Object Lifetime 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11

Garbage Collection Reachable Objects Facilitating Garbage Collection Object Finalization Finalizer Chaining Invoking Garbage Collection Programmatically Review Questions Initializers Field Initializer Expressions Static Initializer Blocks Instance Initializer Blocks Constructing Initial Object State Review Questions Chapter Summary

10 Fundamental Classes 10.1 10.2 10.3

10.4

Overview of the java.lang Package The Object Class Review Questions The Wrapper Classes Common Wrapper Class Constructors Common Wrapper Class Utility Methods Numeric Wrapper Classes The Character Class The Boolean Class Review Questions The String Class Immutability Creating and Initializing Strings The CharSequence Interface Reading Characters from a String Comparing Strings Character Case in a String Concatenation of Strings Searching for Characters and Substrings Extracting Substrings Converting Primitive Values and Objects to Strings

379 380 380 382 386 386

389 390 390 392 396 397 398 401 406 406 410 413 416 420 422

423 424 424 428 428 429 430 433 436 437 437 439 439 439 442 443 445 446 446 448 449 450

CONTENTS

xvii

10.5

Formatting Values Pattern Matching Review Questions The StringBuilder and the StringBuffer Classes Thread-Safety Mutability Constructing String Builders Reading and Changing Characters in String Builders Constructing Strings from String Builders Appending, Inserting, and Deleting Characters in String Builders Controlling String Builder Capacity Review Questions Chapter Summary Programming Exercises

11 Files and Streams 11.1 11.2

11.3

11.4

11.5 11.6

Input and Output The File Class Querying the File System File or Directory Existence File and Directory Permissions Listing Directory Entries Creating New Files and Directories Renaming Files and Directories Deleting Files and Directories Byte Streams: Input Streams and Output Streams File Streams Filter Streams Reading and Writing Binary Values Review Questions Character Streams: Readers and Writers Print Writers Writing Text Files Reading Text Files Using Buffered Writers Using Buffered Readers The Standard Input, Output, and Error Streams Comparison of Byte Streams and Character Streams The Console class Review Questions Object Serialization The ObjectOutputStream Class The ObjectInputStream Class Customizing Object Serialization Serialization and Inheritance

450 452 452 456 456 456 457 457 458 458 460 461 464 465

467 468 468 470 472 472 473 473 474 474 475 477 479 479 484 488 490 492 494 495 496 499 500 500 506 510 511 512 517 519

xviii

CONTENTS

Review Questions Chapter Summary Programming Exercise

12 Localization, Pattern Matching, and Formatting 12.1 12.2 12.3

12.4

12.5

12.6

12.7

The java.util.Locale Class The java.util.Date Class The java.util.Calendar Class Static Factory Methods to Create a Calendar Interoperability with the Date Class Selected get and set Methods Manipulating a Calendar Comparing Calendars The java.text.DateFormat Class Static Factory Methods to Create a Date/Time Formatter Formatting Dates Parsing Strings to Date/Time Managing the Calendar and the Number Formatter The java.text.NumberFormat Class Static Factory Methods to Create a Number Formatter Formatting Numbers and Currency Parsing Strings to Numbers Specifying the Number of Digits Review Questions String Pattern Matching Using Regular Expressions Regular Expression Fundamentals Escaping Metacharacters The java.util.regex.Pattern Class The java.util.regex.Matcher Class The java.util.Scanner Class Review Questions Formatting Values Overview Defining Format Specifiers Conversion Categories and Formatting Conversions Selected Format Exceptions Using the format() Method Review Questions Chapter Summary Programming Exercises

522 529 530

531 532 535 536 537 537 537 539 540 541 541 542 543 545 546 546 546 547 547 551 554 554 561 562 566 571 582 593 593 595 597 601 602 604 610 610

13 Threads

613

13.1 13.2 13.3

614 614 615

Multitasking Overview of Threads The Main Thread

CONTENTS

xix

13.4

13.5

13.6

Thread Creation Implementing the Runnable Interface Extending the Thread Class Review Questions Synchronization Locks Synchronized Methods Synchronized Blocks Review Questions Thread Transitions Thread States Thread Priorities Thread Scheduler Running and Yielding Sleeping and Waking Up Waiting and Notifying Joining Blocking for I/O Thread Termination Deadlocks Review Questions Chapter Summary Programming Exercises

14 Generics 14.1 14.2

14.3 14.4

14.5

14.6

Introducing Generics Generic Types and Parameterized Types Generic Types Parameterized Types Generic Interfaces Extending Generic Types Raw Types and Unchecked Warnings Collections and Generics Wildcards The Subtype Covariance Problem with Parameterized Types Wildcard Types Subtype Covariance: ? extends Type Subtype Contravariance: ? super Type Subtype Bivariance: ? Subtype Invariance: Type Some Restrictions on Wildcard Types Using References of Wildcard Parameterized Types Generic Reference Assignment Using Parameterized References to Call Set and Get Methods Bounded Type Parameters Multiple Bounds

615 616 619 622 626 626 627 629 631 634 634 638 638 639 640 640 647 649 650 651 653 658 659

661 662 663 663 665 666 668 670 672 673 673 675 675 676 677 677 677 678 679 680 684 686

xx

CONTENTS

14.7 14.8

14.9 14.10

14.11 14.12

14.13

Review Questions Implementing a Simplified Generic Stack Generic Methods and Constructors Generic Method Declaration Calling Generic Methods Wildcard Capture Capture Conversion Flexibility with Wildcard Parameterized Types Nested Wildcards Wildcard Parameterized Types as Formal Parameters Flexible Comparisons with Wildcards Recursive Bounds Type Erasure Bridge Methods Implications for Overloading and Overriding Method Signature Implications for Overloading Implications for Overriding Limitations and Restrictions on Generic Types Reifiable Types Implications for instanceof operator Implications for Casting Implications for Arrays Implications for Varargs Implications for Exception Handling Implications for Nested Classes Other Implications Review Questions Chapter Summary Programming Exercises

15 Collections and Maps 15.1

15.2

15.3

Comparing Objects The equals() Method The hashCode() Method The Comparable Interface The Comparator Interface Review Questions The Java Collections Framework Core Interfaces Implementations Collections Basic Operations Bulk Operations Iterators

686 695 697 699 700 703 705 705 705 707 709 712 714 716 716 716 717 718 722 722 723 724 726 729 730 731 733 734 744 745

747 748 751 760 765 771 775 777 778 780 784 784 785 785

CONTENTS

xxi

Array Operations Review Questions 15.4 Sets The HashSet and LinkedHashSet Classes 15.5 The SortedSet and NavigableSet Interfaces The SortedSet Interface The NavigableSet Interface The TreeSet Class 15.6 Lists The ArrayList, LinkedList, and Vector Classes 15.7 Queues The Queue Interface The PriorityQueue and LinkedList Classes The Deque Interface The ArrayDeque and LinkedList Class Review Questions 15.8 Maps Basic Operations Bulk Operations Collection Views 15.9 Map Implementations The HashMap, LinkedHashMap, and Hashtable Classes 15.10 The SortedMap and NavigableMap Interfaces The SortedMap Interface The NavigableMap Interface The TreeMap Class Review Questions 15.11 Working with Collections Ordering Elements in Lists Searching in Collections Changing Elements in Collections Sorting Arrays Searching in Arrays Creating List Views of Arrays Miscellaneous Utility Methods in the Arrays Class Review Questions Chapter Summary Programming Exercises

A

Taking the SCJP 1.6 Exam A.1 A.2

Preparing for the Programmer Exam Registering for the Exam Obtaining an Exam Voucher Signing Up for the Test Contact Information

790 791 796 796 800 800 801 802 804 806 809 809 810 813 815 816 821 821 822 822 823 823 826 826 827 828 833 838 838 840 841 842 843 845 846 846 849 850

851 851 852 852 852 852

xxii

CONTENTS

A.3

A.4

A.5

B

After Taking the Exam How the Examination Is Conducted The Testing Locations Utilizing the Allotted Time The Exam Program The Questions Types of Questions Asked Types of Answers Expected Topics Covered by the Questions Moving on to Other Java Technology Exams

Objectives for the SCJP 1.6 Exam

853 853 853 853 854 854 854 855 855 856

857

C Objectives for the SCJP 1.6 Upgrade Exam

863

D Annotated Answers to Review Questions

869

E Solutions to Programming Exercises

935

F Mock Exam

959

G

Number Systems and Number Representation G.1

G.2 G.3

G.4

Number Systems Binary, Octal, and Hexadecimal Number System Converting Binary Numbers to Decimals Converting Octal and Hexadecimal Numbers to Decimals Relationship between Binary, Octal, and Hexadecimal Numbers Converting Decimals Converting Decimals to Binary Numbers Converting Decimals to Octal and Hexadecimal Numbers Representing Integers Calculating 2’s Complement

Index

1005 1005 1005 1006 1007 1007 1008 1008 1009 1010 1011

1013

List of Figures

1.1 UML Notation for Classes Chapter 11 1.2 UML Notation for Objects 1.3 Aliases 1.4 Class Diagram Showing Static Members of a Class 1.5 Members of a Class 1.6 Class Diagram Depicting Inheritance Relationship 1.7 Class Diagram Depicting Aggregation 2.1 Primitive Chapter 2 19Data Types in Java 3.1 The Event Chapter 3 39Model 3.2 Array of Arrays 3.3 Parameter Passing: Primitive Data Values 3.4 Parameter Passing: Reference Values 3.5 Parameter Passing: Arrays 4.1 Java Source Chapter 4 103File Structure 4.2 Package Hierarchy 4.3 File Hierarchy 4.4 Searching for Classes 4.5 Searching in JAR files 4.6 Block Scope 4.7 Public Accessibility 4.8 Protected Accessibility 4.9 Default Accessibility 4.10 Private Accessibility 5.1 Widening Primitive Conversions Chapter 5 159 5.2 Overflow and Underflow in Floating-point Arithmetic 5.3 Numeric Promotion in Arithmetic Expressions 6.1 Activity Diagram for if Statements Chapter 6 203 6.2 Activity Diagram for a switch Statement 6.3 Activity Diagram for the while Statement 6.4 Activity Diagram for the do-while Statement 6.5 Activity Diagram for the for Statement 6.6 Enhanced for Statement 6.7 Method Execution

3 5 6 8 9 10 12 28 43 78 84 85 87 104 105 116 118 121 132 141 142 143 144 160 176 181 205 208 217 218 219 221 237

xxiii

xxiv

LIST OF FIGURES

6.8 Exception Propagation 6.9 Partial Exception Inheritance Hierarchy 6.10 The try-catch-finally Construct 6.11 Exception Handling (Scenario 1) 6.12 Exception Handling (Scenario 2) 6.13 Exception Handling (Scenario 3) 6.14 Execution of the Simple assert Statement (with Assertions Enabled) 6.15 Package Hierarchy 7.1 Inheritance Chapter 7 283Hierarchy 7.2 Inheritance Relations 7.3 Reference Type Hierarchy: Arrays and Subtype Covariance 7.4 Type Hierarchy to Illustrate Polymorphism 7.5 Implementing Data Structures by Inheritance and Aggregation 8.1 Static Member Chapter 8 351 Classes and Interfaces 8.2 Outer Object with Associated Inner Objects 8.3 Nested Classes and Inheritance 8.4 Local Classes and Inheritance Hierarchy 9.1 Memory Organization at Runtime Chapter 9 389 10.1 Partial10 Inheritance Hierarchy in the java.lang Package Chapter 423 10.2 Converting Values Between Primitive, Wrapper, and String Types 11.1 Partial11 Byte Stream Inheritance Hierarchies Chapter 467 11.2 Stream Chaining for Reading and Writing Binary Values to a File 11.3 Partial Character Stream Inheritance Hierarchies 11.4 Setting up a PrintWriter to Write to a File 11.5 Setting up Readers to read Characters 11.6 Buffered Writers 11.7 Buffered Readers 11.8 Keyboard and Display as Console 11.9 Object Stream Chaining 13.1 Spawning Threads Using a Runnable Object Chapter 12 613 13 531 13.2 Spawning Threads—Extending the Thread Class 13.3 Thread States 13.4 Running and Yielding 13.5 Sleeping and Waking up 13.6 Waiting and Notifying 13.7 Thread Communication 13.8 Stack Users 13.9 Joining of Threads 13.10 Deadlock 14.1 Extending Generic Types Chapter 14 661 14.2 No Subtype Covariance for Parameterized Types 14.4 Partial Type Hierarchy for Node