1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu A Programmer’s Guide to Java™ SCJP Certification doc

1,1K 7,4K 2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.090
Dung lượng 6,95 MB

Nội dung

xxiv LIST OF FIGURES6.10 The try-catch-finally Construct 246 6.14 Execution of the Simple assert Statement with Assertions Enabled 266 Chapter 7 283 7.3 Reference Type Hierarchy: Arrays

Trang 2

A Programmer’s Guide to

Third Edition

Trang 3

This page intentionally left blank

Trang 4

Upper Saddle River, New Jersey • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Capetown • Sidney • Tokyo • Singapore • Mexico City

Trang 5

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 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:

pur-U.S Corporate and Government Sales

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 ers)—Examinations Study guides 3 Java (Computer program language) Examinations Study guides I Rasmussen, Rolf (Rolf W.) II Mughal, Khalid Azim Programmer’s guide

(Comput-to Java certification III Title

QA76.3.M846 2008

005.2'762 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-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

Trang 6

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.

Trang 7

This page intentionally left blank

Trang 8

Contents Overview

Foreword xxxv Preface xxxvii

Trang 9

viii CONTENTS

Trang 10

Contents

Foreword xxxv Preface xxxvii

Trang 11

Initializing Local Variables of Primitive Data Types 34

Trang 12

CONTENTS xi

Extending Enum Types: Constant-Specific Class Bodies 59

Trang 13

xii CONTENTS

4.7 Accessibility Modifiers for Top-Level Type Declarations 132

Casting Context of the Unary Type Cast Operator: (type) 164

5.3 Precedence and Associativity Rules for Operators 166

Operand Evaluation before Operation Execution 168

Trang 14

CONTENTS xiii

Arithmetic Operator Precedence and Associativity 174

Multiplicative Binary Operators: *,/,% 178

Numeric Promotions in Arithmetic Expressions 180Arithmetic Compound Assignment Operators: *=,/=,%=,+=,-= 182

5.8 Variable Increment and Decrement Operators: ++, 186

5.10 Relational Operators: <,<=,>,>= 190

5.12 Boolean Logical Operators: !,^,&,| 194

Operand Evaluation for Boolean Logical Operators 195Boolean Logical Compound Assignment Operators: &=,^=, |= 195

Trang 15

xiv CONTENTS

6.5 Stack-Based Execution and Exception Propagation 235

6.7 Exception Handling: try,catch, and finally 245

7.5 Chaining Constructors Using this() and super() 302

Trang 16

7.10 Method Invocation Conversions Involving References 323

7.11 Reference Casting and the instanceof Operator 327

Accessing Declarations in Enclosing Context 372

Trang 17

xvi CONTENTS

Accessing Declarations in Enclosing Context 380

Trang 18

Reading and Changing Characters in String Builders 457

Appending, Inserting, and Deleting Characters in String Builders 458

11.3 Byte Streams: Input Streams and Output Streams 475

The Standard Input, Output, and Error Streams 499Comparison of Byte Streams and Character Streams 500

TheObjectOutputStream Class 511

Trang 19

xviii CONTENTS

12.1 The java.util.Locale Class 532

12.3 The java.util.Calendar Class 536

Static Factory Methods to Create a Calendar 537

12.4 The java.text.DateFormat Class 541

Static Factory Methods to Create a Date/Time Formatter 541

Managing the Calendar and the Number Formatter 54512.5 The java.text.NumberFormat Class 546

Static Factory Methods to Create a Number Formatter 546

12.6 String Pattern Matching Using Regular Expressions 554

Conversion Categories and Formatting Conversions 597

Trang 20

CONTENTS xix

The Subtype Covariance Problem with Parameterized Types 673

14.5 Using References of Wildcard Parameterized Types 678

Using Parameterized References to Call Set and Get Methods 680

Trang 21

xx CONTENTS

14.10 Flexibility with Wildcard Parameterized Types 705

Wildcard Parameterized Types as Formal Parameters 707

14.13 Limitations and Restrictions on Generic Types 722

TheComparable<E> Interface 765TheComparator<E> Interface 771

Trang 22

Miscellaneous Utility Methods in the Arrays Class 846

Trang 23

xxii CONTENTS

Binary, Octal, and Hexadecimal Number System 1005

Converting Octal and Hexadecimal Numbers to Decimals 1007G.2 Relationship between Binary, Octal, and Hexadecimal Numbers 1007

Converting Decimals to Octal and Hexadecimal Numbers 1009

Trang 24

List of Figures

Chapter 1 1

1.4 Class Diagram Showing Static Members of a Class 8

1.6 Class Diagram Depicting Inheritance Relationship 10

Chapter 4 103

5.2 Overflow and Underflow in Floating-point Arithmetic 176

Chapter 6 203

6.4 Activity Diagram for the do-while Statement 218

Trang 25

xxiv LIST OF FIGURES

6.10 The try-catch-finally Construct 246

6.14 Execution of the Simple assert Statement (with Assertions Enabled) 266

Chapter 7 283

7.3 Reference Type Hierarchy: Arrays and Subtype Covariance 318

7.5 Implementing Data Structures by Inheritance and Aggregation 342

Chapter 8 351

Chapter 12 531

13.2 Spawning Threads—Extending the Thread Class 620

14.2 No Subtype Covariance for Parameterized Types 67414.4 Partial Type Hierarchy for Node<? super Integer> 67614.3 Partial Type Hierarchy for Node<? extends Number> 67614.5 Partial Type Hierarchy for Selected Parameterized Types of Node<E> 678

Chapter 15 747

Trang 26

LIST OF FIGURES XXV

15.2 The Core Collection Interfaces and Their Implementations 78115.3 The Core Map Interfaces and Their Implementations 782

G.1 Converting between Binary, Octal, and Hexadecimal 1008

Trang 27

This page intentionally left blank

Trang 28

List of Tables

2.5 Examples of Decimal, Octal, and Hexadecimal Literals 22

4.2 Summary of Accessibility Modifiers for Top-Level Types 135

4.4 Summary of Accessibility Modifiers for Members 144

5.5 Examples of Arithmetic Expression Evaluation 180

5.11 Boolean Logical Compound Assignment Operators 196

Trang 29

xxviii LIST OF TABLES

6.2 Granularities for Enabling and Disabling Assertions at Runtime 2696.3 Enabling and Disabling Assertions in All System Classes at Runtime 272

Chapter 9 389

11.3 The DataInput and DataOutput Interfaces 480

11.7 Correspondence Between Selected Byte and Character Streams 500

12.5 Selected Field Numbers to Indicate Information in a Calendar 53712.6 Selected Constants that Represent Values in a Calendar 538

14.2 Get and Set Operations Using Parameterized References 68214.3 Summary of Get and Set Operations using Parameterized References 684

15.2 Summary of Collection and Map Implementations 782

G.2 Representing Signed byte Values Using 2’s Complement 1010

Trang 30

List of Examples

Chapter 1 1

Chapter 2 19

2.2 Flagging Uninitialized Local Variables of Primitive Data Types 342.3 Flagging Uninitialized Local Reference Variables 35

Chapter 4 103

4.6 Conflict in Importing Static Method with the Same Signature 113

4.10 Accessibility Modifiers for Classes and Interfaces 133

Trang 31

xxx LIST OF EXAMPLES

Chapter 5 159

5.3 Short-Circuit Evaluation Involving Conditional Operators 198

Chapter 6 203

6.13 The try-catch-finally Construct 253

6.15 The finally Block and the return Statement 255

Chapter 7 283

7.1 Extending Classes: Inheritance and Accessibility 285

7.10 Choosing the Most Specific Method (Simple Case) 325

7.12 The instanceof and Cast Operators 329

7.15 Implementing Data Structures by Inheritance and Aggregation 342

Chapter 8 351

8.4 Accessing Members in Enclosing Context (Static Member Classes) 3588.5 Defining and Instantiating Non-static Member Classes 360

Trang 32

LIST OF EXAMPLES xxxi

8.6 Special Form of this and new Constructs in Non-static

8.13 Accessing Declarations in Enclosing Context (Anonymous Classes) 381

Chapter 9 389

9.4 Initializer Expression Order and Method Calls 408

9.8 Instance Initializers and Forward References 4149.9 Instance Initializer Block in Anonymous Class 4149.10 Exception Handling in Instance Initializer Blocks 415

9.12 Initialization under Object State Construction 419

Chapter 10 423

Chapter 11 467

11.4 Demonstrating Readers and Writers, and Character Encoding 498

12.12 Using Delimiters and Patterns with a Scanner 580

Trang 33

xxxii LIST OF EXAMPLES

Chapter 13 613

14.6 Illustrating Get and Set Operations Using Parameterized References 681

14.15 Genericity Cannot Be Added to Inherited Methods 722

Chapter 15 747

15.2 Not Overriding the equals() and the hashCode() Methods 75215.3 Testing the equals() and the hashCode() Methods 752

15.5 Implications of Overriding the equals() Method 759

15.7 Implications of Overriding the hashCode() Method 76515.8 Implementing the compareTo() Method of the Comparable Interface 76715.9 Implications of Implementing the compareTo() Method 769

15.13 Using a for(:) Loop to Iterate Over a Collection 789

Trang 34

LIST OF EXAMPLES xxxiii

Trang 35

This page intentionally left blank

Trang 36

Foreword

Consider the following observations:

• Software continues to become ever more pervasive, ever more ubiquitous inour lives

• Incompetence seems to be the only thing we can count on in today’s worldand, especially, in the domain of software

• The Java programming language has become a lingua franca for programmersall over the world

One can draw varied conclusions from these comments One of them is that it is ofgreat importance that programmers working with the Java programming lan-guage should be as competent as possible

The Java certification program is an important effort aimed at precisely this goal.Practitioners looking to obtain such certification need good quality training mate-rials, which brings us to this book

Programming is still more of an art than a science, and will continue to be so forthe foreseeable future Mastering the intricacies of a large and complex program-ming language is a challenging task that requires time and effort, and above allexperience

Real programming requires more than just mastery of a programming language Itrequires mastery of a computing platform, with a rich set of libraries These librar-ies are designed to simplify the task of building realistic applications, and they do.Again, the practitioner is faced with a daunting task

To address the clear need for professional training material, a plethora of bookshave been written purporting to tutor programmers in the programming languageand platform skills they require

The choice is as mind boggling as the material within the books themselves

Should one try Java for Frontally Lobotomized Simians or Postmodern Java Dialectics?

The readership for these books is largely self selecting I trust that if you, the reader,

Trang 37

xxxvi FOREWORD

have gotten this far, you are looking for something that is intelligent, yet practical.This book is one of the finest efforts in this crowded arena It brings a necessarylevel of academic rigor to an area much in need of it, while retaining an essentiallypragmatic flavor

The material in this book is probably all you need to pass the Java certificationexam It certainly isn’t all you need to be a good software engineer You must con-tinue learning about new technologies The hardest part of this is dealing withthings that are completely different from what you are familiar with Yet this iswhat distinguishes the top flight engineer from the mediocre one Keep an openmind; it pays

Gilad Bracha

Computational Theologist

Sun Java Software

http://java.sun.com/people/gbracha/

Trang 38

Preface

Writing the Third Edition

The exam for the Sun Certified Programmer for Java Platform, Standard Edition 6,has changed considerably since the second edition of this book was published Themost noticeable change in the current version of the Sun Certified Java Program-mer (SCJP) 1.6 exam is the inclusion of the features of Java 5, and the shifting ofemphasis towards analyzing code scenarios, rather than individual language con-structs In our opinion, the new exam demands an even greater understanding andactual experience of the language, rather than mere recitation of facts Proficiency

in the language is the key to success

Since the emphasis of the SCJP 1.6 exam is on the core features of Java, the thirdedition provides even greater in-depth coverage of the relevant topics The bookcovers not just the exam objectives, but also supplementary topics that aid in mas-tering the exam topics

The third edition is still a one-source guide for the SCJP 1.6 exam: it provides a ture of theory and practice for the exam Use the book to learn Java, pass the SCJP1.6 exam, and afterwards, use it as a handy language guide The book also has anappendix devoted to the SCJP 1.6 Upgrade exam

mix-We have taken into consideration the feedback we have received from readers Themany hours spent in handling the deluge of e-mail have not been in vain Everysingle e-mail is appreciated and is hereby acknowledged

Preparing the third edition dispelled our illusions about newer editions being, toput it colloquially, a piece of cake Every sentence from the second edition has beenweighed carefully, and not many paragraphs have escaped rewriting UML (Uni-fied Modeling Language) is also extensively employed in this edition Numerousnew review questions have been added In covering the new topics and expandingthe existing ones, new examples, figures, and tables were also specifically createdfor the third edition

Trang 39

xxxviii PREFACE

About This Book

This book provides extensive coverage of the Java programming language and itscore Application Programming Interfaces (APIs), with particular emphasis on itssyntax and usage The book is primarily intended for professionals who want toprepare for the SCJP 1.6 exam, but it is readily accessible to any programmer whowants to master the language For both purposes, it provides in-depth coverage ofessential features of the language and its core APIs

There is a great and increasing demand for certified Java programmers SunMicrosystems has defined the SCJP 1.6 exam as one that professionals can take tovalidate their skills The certification provides the IT industry with a standard touse for hiring such professionals, and allows the professionals to turn their Javaskills into credentials that are important for career advancement

The book provides extensive coverage of all the objectives defined for the exam bySun But the exam objectives are selective and do not include many of the essentialfeatures of Java This book covers many additional topics that every Java program-mer should master in order to be proficient In this regard, the book is a compre-hensive primer for learning the Java programming language After mastering thelanguage by working through this book, the reader can confidently sit for theexam

This book is not a complete reference for Java, as it does not attempt to list every

member of every class from the Java Development Kit (JDK) API documentation.The purpose is not to document the JDK APIs This book does not teachprogramming techniques The emphasis is on the Java programming languagefeatures, their syntax and correct usage through code examples

The book assumes little background in programming We believe the exam isaccessible to any programmer who works through the book A Java programmercan easily skip over material that is well understood and concentrate on parts thatneed reinforcing, whereas a programmer new to Java will find the conceptsexplained from basic principles

Each topic is explained and discussed thoroughly with examples, and backed byreview questions and exercises to reinforce the concepts The book is not biasedtoward any particular platform, but provides platform-specific details wherenecessary

Using the Book

The reader can choose a linear or a non-linear route through the book, depending

on her programming background Non-Java programmers wishing to migrate toJava can read Chapter 1, which provides a short introduction to object-orientedprogramming concepts, and the procedure for compiling and running Java appli-

Trang 40

rein-in a separate appendix.

Example 0.1 Example Source Code

We encourage experimenting with the code examples in order to reinforce thematerial from the book These can be downloaded from the book Web site (see

p xli)

Java code is written in a mono-spaced font Lines of code in the examples or in codesnippets are referenced in the text by a number, which is specified by using asingle-line comment in the code For example, in the following code snippet, thecall to the method doSomethingInteresting() hopefully does something interesting

at (1)

Exam Objectives

0.1 Exam objectives are stated clearly at the start of every chapter

0.2 The number in front of the objective identfies the objective as defined by Sun

0.3 The objectives are organized into major sections, detailing the curriculum for the exam

0.4 The exam objectives are reproduced in Appendix B where, for each section

of the syllabus, references are included to point the reader to relevant topics for the exam

Supplementary Objectives

• Supplementary objectives cover topics that are not on the exam, but which

we believe are important for mastering the topics that are on the exam.

• Any supplementary objectives are listed as bullets at the beginning of a chapter

Ngày đăng: 14/02/2014, 12:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w