1,046 142 7MB
Pages 1089 Page size 252 x 334.08 pts Year 2009
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