1089

Khalid mughal scjp 1.6

Embed Size (px)

DESCRIPTION

SCJP 1.6

Citation preview

  • 1. A Programmers Guide toJava SCJP CertificationThird Edition

2. This page intentionally left blank 3. A Programmers Guide toJava SCJP CertificationA Comprehensive PrimerThird EditionKhalid A. MughalRolf W. RasmussenUpper Saddle River, New Jersey Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sidney Tokyo Singapore Mexico City 4. Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and the publisherwas aware of a trademark claim, the designations have been printed with initial capital let-ters or in all capitals.The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors or omis-sions. No liability is assumed for incidental or consequential damages in connection with orarising 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 pur-chases or special sales, which may include electronic versions and/or custom covers andcontent particular to your business, training goals, marketing focus, and branding interests.For more information, please contact:U.S. Corporate and Government Sales(800) [email protected] sales outside the United States please contact:International [email protected] us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication DataMughal, Khalid Azim.A programmers guide to Java SCJP certification : a comprehensive primer / Khalid A.Mughal, Rolf W. Rasmussen.3rd ed.p. cm.Previously published under title: A programmers 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 (Comput-ers)Examinations--Study guides. 3. Java (Computer program language)--Examinations--Study guides. I. Rasmussen, Rolf (Rolf W.) II. Mughal, Khalid Azim. Programmers guideto Java certification. III. Title.QA76.3.M846 2008005.2762--dc22 2008048822Copyright 2009 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibitedreproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. For information regardingpermissions, write to:ISBN-13: 978-0-321-55605-9ISBN-10: 0-321-55605-4Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts.First printing, December 2008 5. To the loving memory of my mother, Zubaida Begum,and my father, Mohammed Azim.K.A.M.For Olivia E. Rasmussen andLouise J. Dahlmo.R.W.R. 6. This page intentionally left blank 7. viiContents OverviewForeword xxxvPreface xxxvii1 Basics of Java Programming 12 Language Fundamentals 193 Declarations 394 Access Control 1035 Operators and Expressions 1596 Control Flow 2037 Object-Oriented Programming 2838 Nested Type Declarations 3519 Object Lifetime 38910 Fundamental Classes 42311 Files and Streams 46712 Localization, Pattern Matching and Formatting 53113 Threads 61314 Generics 661 8. viii CONTENTS15 Collections and Maps 747A Taking the SCJP 1.6 Exam 851B Objectives for the SCJP 1.6 Exam 857C Objectives for the SCJP 1.6 Upgrade Exam 863D Annotated Answers to Review Questions 869E Solutions to Programming Exercises 935F Mock Exam 959G Number Systems and Number Representation 1005Index 1013 9. ixContentsList of Figures xxiiiList of Tables xxviiList of Examples xxixForeword xxxvPreface xxxvii1 Basics of Java Programming 11.1 Introduction 21.2 Classes 2Declaring Members: Fields and Methods 31.3 Objects 4Class Instantiation, Reference Values, and References 4Object Aliases 61.4 Instance Members 6Invoking Methods 71.5 Static Members 71.6 Inheritance 101.7 Aggregation 121.8 Tenets of Java 13Review Questions 131.9 Java Programs 151.10 Sample Java Application 15Essential Elements of a Java Application 15Compiling and Running an Application 16Review Questions 17Chapter Summary 18Programming Exercise 18 10. x CONTENTS2 Language Fundamentals 192.1 Basic Language Elements 20Lexical Tokens 20Identifiers 20Keywords 20Literals 21Integer Literals 22Floating-Point Literals 22Boolean Literals 23Character Literals 23String Literals 25White Spaces 25Comments 26Review Questions 272.2 Primitive Data Types 28Integer Types 28The char Type 29The Floating-Point Types 29The boolean Type 30Review Questions 312.3 Variable Declarations 31Declaring and Initializing Variables 31Reference Variables 322.4 Initial Values for Variables 33Default Values for Fields 33Initializing Local Variables of Primitive Data Types 34Initializing Local Reference Variables 35Lifetime of Variables 35Review Questions 36Chapter Summary 37Programming Exercise 373 Declarations 393.1 Class Declarations 403.2 JavaBeans Standard 41Naming Patterns for Properties 41Naming Patterns for the Event Model 423.3 Method Declarations 44Statements 45Instance Methods and the Object Reference this 45Method Overloading 473.4 Constructors 48The Default Constructor 49Overloaded Constructors 51Review Questions 52 11. CONTENTS xi3.5 Enumerated Types 54Declaring Typesafe Enums 54Using Typesafe Enums 54Declaring Enum Constructors and Members 55Implicit Static Methods for Enum Types 57Inherited Methods from the Enum Class 58Extending Enum Types: Constant-Specific Class Bodies 59Declaring Typesafe Enums Revisited 62Review Questions 633.6 Arrays 69Declaring Array Variables 70Constructing an Array 70Initializing an Array 71Using an Array 72Anonymous Arrays 74Multidimensional Arrays 75Review Questions 793.7 Parameter Passing 81Passing Primitive Data Values 82Passing Reference Values 84Passing Arrays 86Array Elements as Actual Parameters 87final Parameters 893.8 Variable Arity Methods 90Calling a Varargs Method 91Varargs and Non-Varargs Method Calls 933.9 The main() Method 94Program Arguments 95Review Questions 96Chapter Summary 100Programming Exercises 1014 Access Control 1034.1 Java Source File Structure 1044.2 Packages 105Defining Packages 106Using Packages 107Compiling Code into Packages 115Running Code from Packages 1174.3 Searching for Classes 1174.4 The JAR Utility 1204.5 System Properties 122Review Questions 1234.6 Scope Rules 129Class Scope for Members 129 12. xii CONTENTSBlock Scope for Local Variables 1314.7 Accessibility Modifiers for Top-Level Type Declarations 1324.8 Other Modifiers for Classes 135abstract Classes 135final Classes 136Review Questions 1384.9 Member Accessibility Modifiers 138public Members 139protected Members 141Default Accessibility for Members 142private Members 143Review Questions 1444.10 Other Modifiers for Members 146static Members 147final Members 148abstract Methods 150synchronized Methods 150native Methods 151transient Fields 152volatile Fields 153Review Questions 154Chapter Summary 157Programming Exercise 1575 Operators and Expressions 1595.1 Conversions 160Widening and Narrowing Primitive Conversions 160Widening and Narrowing Reference Conversions 161Boxing and Unboxing Conversions 162Other Conversions 1625.2 Type Conversion Contexts 163Assignment Context 164Method Invocation Context 164Casting Context of the Unary Type Cast Operator: (type) 164Numeric Promotion Context 1655.3 Precedence and Associativity Rules for Operators 1665.4 Evaluation Order of Operands 168Left-Hand Operand Evaluation First 168Operand Evaluation before Operation Execution 168Left to Right Evaluation of Argument Lists 1695.5 The Simple Assignment Operator = 169Assigning Primitive Values 169Assigning References 169Multiple Assignments 170Type Conversions in Assignment Context 171 13. CONTENTS xiiiReview Questions 1735.6 Arithmetic Operators: *, /, %, +, - 174Arithmetic Operator Precedence and Associativity 174Evaluation Order in Arithmetic Expressions 174Range of Numeric Values 175Unary Arithmetic Operators: -, + 177Multiplicative Binary Operators: *, /, % 178Additive Binary Operators: +, - 180Numeric Promotions in Arithmetic Expressions 180Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -= 182Review Questions 1845.7 The Binary String Concatenation Operator + 1855.8 Variable Increment and Decrement Operators: ++, -- 186The Increment Operator ++ 187The Decrement Operator -- 187Review Questions 1885.9 Boolean Expressions 1905.10 Relational Operators: = 1905.11 Equality 191Primitive Data Value Equality: ==, != 191Object Reference Equality: ==, != 192Object Value Equality 1935.12 Boolean Logical Operators: !, ^, &, | 194Operand Evaluation for Boolean Logical Operators 195Boolean Logical Compound Assignment Operators: &=, ^=, |= 1955.13 Conditional Operators: &&, || 196Short-Circuit Evaluation 197Review Questions 1995.14 The Conditional Operator: ?: 2015.15 Other Operators: new, [], instanceof 201Chapter Summary 202Programming Exercise 2026 Control Flow 2036.1 Overview of Control Flow Statements 2046.2 Selection Statements 204The Simple if Statement 204The if-else Statement 205The switch Statement 207Review Questions 2126.3 Iteration Statements 216The while Statement 217The do-while Statement 217The for(;;) Statement 218The for(:) Statement 220 14. xiv CONTENTS6.4 Transfer Statements 223Labeled Statements 223The break Statement 224The continue Statement 226The return Statement 228Review Questions 2296.5 Stack-Based Execution and Exception Propagation 2356.6 Exception Types 239The Exception Class 241The RuntimeException Class 241The Error Class 242Checked and Unchecked Exceptions 243Defining New Exceptions 2446.7 Exception Handling: try, catch, and finally 245The try Block 245The catch Block 246The finally Block 2516.8 The throw Statement 2556.9 The throws Clause 257Review Questions 2606.10 Assertions 265The assert Statement and the AssertionError Class 265Compiling Assertions 267Runtime Enabling and Disabling of Assertions 269Using Assertions 272Review Questions 276Chapter Summary 279Programming Exercises 2797 Object-Oriented Programming 2837.1 Single Implementation Inheritance 284Inheritance Hierarchy 286Relationships: is-a and has-a 286The Supertype-Subtype Relationship 2877.2 Overriding Methods 288Instance Method Overriding 288Covariant return in Overriding Methods 290Overriding vs. Overloading 2927.3 Hiding Members 294Field Hiding 294Static Method Hiding 2947.4 The Object Reference super 295Review Questions 2977.5 Chaining Constructors Using this() and super() 302The this() Constructor Call 302 15. CONTENTS xvThe super() Constructor Call 305Review Questions 3087.6 Interfaces 309Defining Interfaces 310Abstract Method Declarations 310Implementing Interfaces 312Extending Interfaces 313Interface References 314Constants in Interfaces 314Review Questions 3157.7 Arrays and Subtyping 317Arrays and Subtype Covariance 317Array Store Check 3197.8 Reference Values and Conversions 3197.9 Reference Value Assignment Conversions 3207.10 Method Invocation Conversions Involving References 323Overloaded Method Resolution 3247.11 Reference Casting and the instanceof Operator 327The Cast Operator 327The instanceof Operator 328Review Questions 3327.12 Polymorphism and Dynamic Method Lookup 3407.13 Inheritance Versus Aggregation 3427.14 Basic Concepts in Object-Oriented Design 345Encapsulation 345Cohesion 346Coupling 346Review Questions 347Chapter Summary 349Programming Exercises 3498 Nested Type Declarations 3518.1 Overview of Nested Type Declarations 3528.2 Static Member Types 355Declaring and Using Static Member Types 355Accessing Members in Enclosing Context 3578.3 Non-Static Member Classes 359Instantiating Non-Static Member Classes 360Accessing Members in Enclosing Context 362Review Questions 3678.4 Local Classes 371Accessing Declarations in Enclosing Context 372Instantiating Local Classes 3748.5 Anonymous Classes 377Extending an Existing Class 377 16. xvi CONTENTSImplementing an Interface 379Instantiating Anonymous Classes 380Accessing Declarations in Enclosing Context 380Review Questions 382Chapter Summary 386Programming Exercise 3869 Object Lifetime 3899.1 Garbage Collection 3909.2 Reachable Objects 3909.3 Facilitating Garbage Collection 3929.4 Object Finalization 3969.5 Finalizer Chaining 3979.6 Invoking Garbage Collection Programmatically 398Review Questions 4019.7 Initializers 4069.8 Field Initializer Expressions 4069.9 Static Initializer Blocks 4109.10 Instance Initializer Blocks 4139.11 Constructing Initial Object State 416Review Questions 420Chapter Summary 42210 Fundamental Classes 42310.1 Overview of the java.lang Package 42410.2 The Object Class 424Review Questions 42810.3 The Wrapper Classes 428Common Wrapper Class Constructors 429Common Wrapper Class Utility Methods 430Numeric Wrapper Classes 433The Character Class 436The Boolean Class 437Review Questions 43710.4 The String Class 439Immutability 439Creating and Initializing Strings 439The CharSequence Interface 442Reading Characters from a String 443Comparing Strings 445Character Case in a String 446Concatenation of Strings 446Searching for Characters and Substrings 448Extracting Substrings 449Converting Primitive Values and Objects to Strings 450 17. CONTENTS xviiFormatting Values 450Pattern Matching 452Review Questions 45210.5 The StringBuilder and the StringBuffer Classes 456Thread-Safety 456Mutability 456Constructing String Builders 457Reading and Changing Characters in String Builders 457Constructing Strings from String Builders 458Appending, Inserting, and Deleting Characters in String Builders 458Controlling String Builder Capacity 460Review Questions 461Chapter Summary 464Programming Exercises 46511 Files and Streams 46711.1 Input and Output 46811.2 The File Class 468Querying the File System 470File or Directory Existence 472File and Directory Permissions 472Listing Directory Entries 473Creating New Files and Directories 473Renaming Files and Directories 474Deleting Files and Directories 47411.3 Byte Streams: Input Streams and Output Streams 475File Streams 477Filter Streams 479Reading and Writing Binary Values 479Review Questions 48411.4 Character Streams: Readers and Writers 488Print Writers 490Writing Text Files 492Reading Text Files 494Using Buffered Writers 495Using Buffered Readers 496The Standard Input, Output, and Error Streams 499Comparison of Byte Streams and Character Streams 50011.5 The Console class 500Review Questions 50611.6 Object Serialization 510The ObjectOutputStream Class 511The ObjectInputStream Class 512Customizing Object Serialization 517Serialization and Inheritance 519 18. xviii CONTENTSReview Questions 522Chapter Summary 529Programming Exercise 53012 Localization, Pattern Matching, and Formatting 53112.1 The java.util.Locale Class 53212.2 The java.util.Date Class 53512.3 The java.util.Calendar Class 536Static Factory Methods to Create a Calendar 537Interoperability with the Date Class 537Selected get and set Methods 537Manipulating a Calendar 539Comparing Calendars 54012.4 The java.text.DateFormat Class 541Static Factory Methods to Create a Date/Time Formatter 541Formatting Dates 542Parsing Strings to Date/Time 543Managing the Calendar and the Number Formatter 54512.5 The java.text.NumberFormat Class 546Static Factory Methods to Create a Number Formatter 546Formatting Numbers and Currency 546Parsing Strings to Numbers 547Specifying the Number of Digits 547Review Questions 55112.6 String Pattern Matching Using Regular Expressions 554Regular Expression Fundamentals 554Escaping Metacharacters 561The java.util.regex.Pattern Class 562The java.util.regex.Matcher Class 566The java.util.Scanner Class 571Review Questions 58212.7 Formatting Values 593Overview 593Defining Format Specifiers 595Conversion Categories and Formatting Conversions 597Selected Format Exceptions 601Using the format() Method 602Review Questions 604Chapter Summary 610Programming Exercises 61013 Threads 61313.1 Multitasking 61413.2 Overview of Threads 61413.3 The Main Thread 615 19. CONTENTS xix13.4 Thread Creation 615Implementing the Runnable Interface 616Extending the Thread Class 619Review Questions 62213.5 Synchronization 626Locks 626Synchronized Methods 627Synchronized Blocks 629Review Questions 63113.6 Thread Transitions 634Thread States 634Thread Priorities 638Thread Scheduler 638Running and Yielding 639Sleeping and Waking Up 640Waiting and Notifying 640Joining 647Blocking for I/O 649Thread Termination 650Deadlocks 651Review Questions 653Chapter Summary 658Programming Exercises 65914 Generics 66114.1 Introducing Generics 66214.2 Generic Types and Parameterized Types 663Generic Types 663Parameterized Types 665Generic Interfaces 666Extending Generic Types 668Raw Types and Unchecked Warnings 67014.3 Collections and Generics 67214.4 Wildcards 673The Subtype Covariance Problem with Parameterized Types 673Wildcard Types 675Subtype Covariance: ? extends Type 675Subtype Contravariance: ? super Type 676Subtype Bivariance: ? 677Subtype Invariance: Type 677Some Restrictions on Wildcard Types 67714.5 Using References of Wildcard Parameterized Types 678Generic Reference Assignment 679Using Parameterized References to Call Set and Get Methods 68014.6 Bounded Type Parameters 684Multiple Bounds 686 20. xx CONTENTSReview Questions 68614.7 Implementing a Simplified Generic Stack 69514.8 Generic Methods and Constructors 697Generic Method Declaration 699Calling Generic Methods 70014.9 Wildcard Capture 703Capture Conversion 70514.10 Flexibility with Wildcard Parameterized Types 705Nested Wildcards 705Wildcard Parameterized Types as Formal Parameters 707Flexible Comparisons with Wildcards 709Recursive Bounds 71214.11 Type Erasure 714Bridge Methods 71614.12 Implications for Overloading and Overriding 716Method Signature 716Implications for Overloading 717Implications for Overriding 71814.13 Limitations and Restrictions on Generic Types 722Reifiable Types 722Implications for instanceof operator 723Implications for Casting 724Implications for Arrays 726Implications for Varargs 729Implications for Exception Handling 730Implications for Nested Classes 731Other Implications 733Review Questions 734Chapter Summary 744Programming Exercises 74515 Collections and Maps 74715.1 Comparing Objects 748The equals() Method 751The hashCode() Method 760The Comparable Interface 765The Comparator Interface 771Review Questions 77515.2 The Java Collections Framework 777Core Interfaces 778Implementations 78015.3 Collections 784Basic Operations 784Bulk Operations 785Iterators 785 21. CONTENTS xxiArray Operations 790Review Questions 79115.4 Sets 796The HashSet and LinkedHashSet Classes 79615.5 The SortedSet and NavigableSet Interfaces 800The SortedSet Interface 800The NavigableSet Interface 801The TreeSet Class 80215.6 Lists 804The ArrayList, LinkedList, and Vector Classes 80615.7 Queues 809The Queue Interface 809The PriorityQueue and LinkedList Classes 810The Deque Interface 813The ArrayDeque and LinkedList Class 815Review Questions 81615.8 Maps 821Basic Operations 821Bulk Operations 822Collection Views 82215.9 Map Implementations 823The HashMap, LinkedHashMap, and Hashtable Classes 82315.10 The SortedMap and NavigableMap Interfaces 826The SortedMap Interface 826The NavigableMap Interface 827The TreeMap Class 828Review Questions 83315.11 Working with Collections 838Ordering Elements in Lists 838Searching in Collections 840Changing Elements in Collections 841Sorting Arrays 842Searching in Arrays 843Creating List Views of Arrays 845Miscellaneous Utility Methods in the Arrays Class 846Review Questions 846Chapter Summary 849Programming Exercises 850A Taking the SCJP 1.6 Exam 851A.1 Preparing for the Programmer Exam 851A.2 Registering for the Exam 852Obtaining an Exam Voucher 852Signing Up for the Test 852Contact Information 852 22. xxii CONTENTSAfter Taking the Exam 853A.3 How the Examination Is Conducted 853The Testing Locations 853Utilizing the Allotted Time 853The Exam Program 854A.4 The Questions 854Types of Questions Asked 854Types of Answers Expected 855Topics Covered by the Questions 855A.5 Moving on to Other Java Technology Exams 856B Objectives for the SCJP 1.6 Exam 857C Objectives for the SCJP 1.6 Upgrade Exam 863D Annotated Answers to Review Questions 869E Solutions to Programming Exercises 935F Mock Exam 959G Number Systems and Number Representation 1005G.1 Number Systems 1005Binary, Octal, and Hexadecimal Number System 1005Converting Binary Numbers to Decimals 1006Converting Octal and Hexadecimal Numbers to Decimals 1007G.2 Relationship between Binary, Octal, and Hexadecimal Numbers 1007G.3 Converting Decimals 1008Converting Decimals to Binary Numbers 1008Converting Decimals to Octal and Hexadecimal Numbers 1009G.4 Representing Integers 1010Calculating 2s Complement 1011Index 1013 23. xxiiiList of FiguresChapter 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 Aggregation 12Chapter 2 192.1 Primitive Data Types in Java 28Chapter 3 393.1 The Event Model 433.2 Array of Arrays 783.3 Parameter Passing: Primitive Data Values 843.4 Parameter Passing: Reference Values 853.5 Parameter Passing: Arrays 87Chapter 4 1034.1 Java Source File Structure 1044.2 Package Hierarchy 1054.3 File Hierarchy 1164.4 Searching for Classes 1184.5 Searching in JAR files 1214.6 Block Scope 1324.7 Public Accessibility 1414.8 Protected Accessibility 1424.9 Default Accessibility 1434.10 Private Accessibility 144Chapter 5 1595.1 Widening Primitive Conversions 1605.2 Overflow and Underflow in Floating-point Arithmetic 1765.3 Numeric Promotion in Arithmetic Expressions 181Chapter 6 2036.1 Activity Diagram for if Statements 2056.2 Activity Diagram for a switch Statement 2086.3 Activity Diagram for the while Statement 2176.4 Activity Diagram for the do-while Statement 2186.5 Activity Diagram for the for Statement 2196.6 Enhanced for Statement 2216.7 Method Execution 237 24. xxiv LIST OF FIGURES6.8 Exception Propagation 2386.9 Partial Exception Inheritance Hierarchy 2406.10 The try-catch-finally Construct 2466.11 Exception Handling (Scenario 1) 2486.12 Exception Handling (Scenario 2) 2496.13 Exception Handling (Scenario 3) 2506.14 Execution of the Simple assert Statement (with Assertions Enabled) 2666.15 Package Hierarchy 271Chapter 7 2837.1 Inheritance Hierarchy 2877.2 Inheritance Relations 3147.3 Reference Type Hierarchy: Arrays and Subtype Covariance 3187.4 Type Hierarchy to Illustrate Polymorphism 3407.5 Implementing Data Structures by Inheritance and Aggregation 342Chapter 8 3518.1 Static Member Classes and Interfaces 3588.2 Outer Object with Associated Inner Objects 3628.3 Nested Classes and Inheritance 3668.4 Local Classes and Inheritance Hierarchy 374Chapter 9 3899.1 Memory Organization at Runtime 392Chapter 10 42310.1 Partial Inheritance Hierarchy in the java.lang Package 42410.2 Converting Values Between Primitive, Wrapper, and String Types 429Chapter 11 46711.1 Partial Byte Stream Inheritance Hierarchies 47611.2 Stream Chaining for Reading and Writing Binary Values to a File 48111.3 Partial Character Stream Inheritance Hierarchies 48911.4 Setting up a PrintWriter to Write to a File 49311.5 Setting up Readers to read Characters 49411.6 Buffered Writers 49611.7 Buffered Readers 49711.8 Keyboard and Display as Console 50111.9 Object Stream Chaining 511Chapter 12 531Chapter 13 61313.1 Spawning Threads Using a Runnable Object 61613.2 Spawning ThreadsExtending the Thread Class 62013.3 Thread States 63513.4 Running and Yielding 63913.5 Sleeping and Waking up 64013.6 Waiting and Notifying 64113.7 Thread Communication 64213.8 Stack Users 64313.9 Joining of Threads 64813.10 Deadlock 652Chapter 14 66114.1 Extending Generic Types 66814.2 No Subtype Covariance for Parameterized Types 67414.4 Partial Type Hierarchy for Node