Tải bản đầy đủ (.pdf) (1,501 trang)

Wrox beginning java 2 JDK 5 edition dec 2004 ISBN 0764568744 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (20.78 MB, 1,501 trang )

TeAM
YYePG

Digitally signed by TeAM YYePG
DN: cn=TeAM YYePG, c=US,
o=TeAM YYePG, ou=TeAM
YYePG, email=
Reason: I attest to the accuracy
and integrity of this document
Date: 2005.02.24 07:33:04 +08'00'


Ivor Horton’s Beginning Java™ 2,
JDK™ 5 Edition



Ivor Horton’s Beginning Java™ 2,
JDK™ 5 Edition
Ivor Horton


Ivor Horton’s Beginning Java™ 2, JDK™ 5 Edition
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2005 by Ivor Horton
Published by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
ISBN: 0-7645-6874-4
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
5B/RU/RS/QU/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections
107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood
Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be
addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)
572-3447, fax (317) 572-4355, e-mail:
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED
OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED
HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT
PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE
LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS
REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE
ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR
DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be
available in electronic books.
Library of Congress Cataloging-in-Publication Data
Horton, Ivor.
Ivor Horton’s Beginning Java 2, JDK 5 Edition / Ivor Horton.
p. cm.
Includes index.

ISBN 0-7645-6874-4 (paper/website)
1. Java (Computer program language) I. Title: Ivor Horton’s Beginning Java 2, JDK 5 Edition. II. Title.
QA76.73.J38H6758 2004
005.13’3—dc22
2004017036
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United
States and other countries, and may not be used without written permission. Java and JDK are trademarks of Sun
Microsystems, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not
associated with any product or vendor mentioned in this book.


About the Author
Ivor Horton started out as a mathematician, but shortly after graduating, he was lured into messing
about with computers by a well-known manufacturer. He has spent many happy years programming
occasionally useful applications in a variety of languages as well as teaching mainly scientists and engineers to do likewise. He has extensive experience in applying computers to problems in engineering
design and to manufacturing operations in a wide range of industries. He is the author of a number of
tutorial books on programming in C, C++, and Java. When not writing programming books or providing advice to others, he leads a life of leisure.



Credits
Executive Editor

Project Coordinator

Robert Elliott

Erin Smith


Senior Development Editor

Graphics and Production Specialists

Kevin Kent

William A. Barton

Karl Brandt
Jonelle Burns
Kelly Emkow
Carrie Foster
Lauren Goddard
Denny Hager
Joyce Haughey
Jennifer Heleine
Ron Terry

Copy Editor

Quality Control Technicians

Luann Rouff

Joe Niesen
Susan Moritz
Brian H. Walls

Technical Editors
Calvin Austin, J2SE 5.0 Specification Lead, Sun

Microsystems
Wiley-Dreamtech India Pvt Ltd

Production Editor

Editorial Manager
Mary Beth Wakefield

Media Development Specialist
Vice President & Executive Group Publisher

Travis Silvers

Richard Swadley

Proofreading and Indexing
Vice President and Publisher

TECHBOOKS Production Services

Joseph B. Wikert

Cover Photograph
© Ian Capener



Foreword
You are probably reading this foreword with one of several things in mind. First, is this the right book
for me, is the material current, and does the text reflect the final API? Second, what should I expect to

learn and where should I start reading a book of this length?
Many of the forewords I have seen will lead you through an amusing anecdote or story and then mention a little about the author, but then fail to leave you any wiser about the answer to those questions. So,
to get straight to the point and to answer the second question first, this is a book that you can start from
page one and read right through to the end. If you haven’t read any of Ivor Horton’s books before, you
are in for a pleasant surprise. Ivor’s style is very accessible, which makes the content easy to follow and
understand. I know, because I have read this book from cover to cover.
This edition of Ivor Horton’s Beginning Java 2, JDK 5 Edition is based on the J2SE 5.0 platform. The J2SE 5.0
release is one of the most significant updates to the Java platform in many years and has been three
years in the making. The release involved 160 experts worldwide, all working through the Java
Community Process and focused on making the platform better for all developers. I have been involved
with the project since day one as the Specification Lead for JSR 176, which defines the contents of J2SE
5.0. As such, I had a great interest in making sure that this book is accurate and matches the final API set.
I’ve even compiled and run every code example twice, and there are a lot of great examples, as you will
find out.
So what can you expect to learn from this new edition? First, Ivor covers the basic programming blocks
and gets you started with your first Java program. Ivor then introduces the Java language changes step
by step, including the new generic types, the enhanced for loop, enumerated types, and many others.
You will also get to use the new language changes in later chapters and learn some of the other nonlanguage features, such as XML DOM3 updates. So whether you are a new developer or already have
some Java programming experience, you will gain the skills needed to work with the latest Java release.
In closing, I encourage you to read and enjoy what JDK 5.0 has to offer and find out how easy using J2SE
5.0 really is.
Calvin Austin
J2SE 5.0 Specification Lead
Sun Microsystems



Acknowledgments
While a book is usually attributed to the author, a book — particularly a large book such as this — is
always the result of the efforts of a sizeable team of people. I’d therefore like to thank all the editorial

and production staff at Wiley who worked so hard to produce this fifth edition of my Java tutorial from
my initial draft.
I’d especially like to thank Calvin Austin of Sun Microsystems for his extensive technical input. He
somehow found the time to go through the complete text and try out all the examples — twice — in spite
of the considerable demands of his day job. Calvin’s suggestions for improvements were invaluable, as
was his ability to spot my mistakes, and I’m particularly grateful for his indications of where I’d missed
some of the inevitable changes arising from the evolution of the J2SE 5.0 API during the beta phases.
Any errors that remain are, of course, my own, but there are surely fewer of them as a consequence of
Calvin’s efforts.
I’d also like to thank readers of past editions of Ivor Horton’s Beginning Java for their numerous suggestions for corrections and improvements. In addition to the many changes that I made in response to
these, I also updated and reintroduced the chapters on using JDBC that were omitted from the previous
edition, in response to requests from a number of readers. The greatly increased page count of this edition over the previous edition is only in part a consequence of restoring the JDBC tutorial. The bulk of
the additional page count is attributable to new material relating to the features introduced by J2SE 5.0
that deliver exciting new capabilities for every Java programmer. The J2SE 5.0 release is truly a major
step forward that encompasses important extensions to the Java language as well as major additions to
the class libraries.
Finally I’d like to thank my wife, Eve, who provides unstinting support for whatever I happen to be
doing and cheerfully accepts my complaints about the workload that I freely elected to undertake. She
always manages to be on hand whenever I need sustenance or sympathy, or both, and undoubtedly I
would never have finished this book without her.
Ivor Horton



Contents
About the Author
Foreword
Acknowledgments
Introduction


Chapter 1: Introducing Java
What Is Java All About?
Features of the Java Language
Learning Java
Java Programs
Learning Java — The Road Ahead

The Java Environment
Java Program Development
Installing the JDK
Compiling a Java Program
Executing a Java Application
Executing an Applet

Object-Oriented Programming in Java
So What Are Objects?
What Defines a Class of Objects?
Operating on Objects
Java Program Statements
Encapsulation
Classes and Data Types
Classes and Subclasses
Advantages of Using Objects

Java Program Structure
Java’s Class Library
Java Applications

Java and Unicode
Summary

Resources

v
ix
xi
xxxvii

1
1
2
3
3
3

4
5
6
8
9
10

12
13
14
17
19
20
20
21
21


21
22
24

27
27
28


Contents
Chapter 2: Programs, Data, Variables, and Calculation
Data and Variables
Naming Your Variables
Variable Names and Unicode
Variables and Types

Integer Data Types

29
29
30
31
31

31

Integer Literals
Declaring Integer Variables


33
34

Floating-Point Data Types

36

Floating-Point Literals
Declaring Floating-Point Variables

Fixing the Value of a Variable
Arithmetic Calculations

37
38

Integer Calculations

39

Producing Output

44

Integer Division and Remainders
The Increment and Decrement Operators
Computation with Shorter Integer Types
Errors in Integer Arithmetic
Floating-Point Calculations
Other Floating-Point Arithmetic Operators

Error Conditions in Floating-Point Arithmetic

Mixed Arithmetic Expressions
Explicit Casting
Automatic Type Conversions in Assignments

The op= Operators
Mathematical Functions and Constants
Importing the Math Class Methods

Storing Characters
Character Escape Sequences
Character Arithmetic

Bitwise Operations
Using the AND and OR Operators
Using the Exclusive OR Operator
Shift Operations
Methods for Bitwise Operations

Variables with a Fixed Set of Integer Values
Boolean Variables
Operator Precedence
Program Comments
Documentation Comments

xiv

36
37


45
46
48
49
49
50
51

51
52
52

53
54
59

60
60
61

63
65
68
70
74

77
79
80

81
82


Contents
Summary
Exercises

Chapter 3: Loops and Logic
Making Decisions

83
84

85
85

Making Comparisons
The if Statement

86
87

Statement Blocks
The else Clause

88
90

Nested if Statements

Comparing Enumeration Values

Logical Operators
Logical AND Operations
&& versus &
Logical OR Operations
Boolean NOT Operations
Character Testing Using Standard Library Methods

The Conditional Operator
The switch Statement
The General Case of the switch Statement

Variable Scope
Loops
Varieties of Loop
Counting Using Floating-Point Values

Nested Loops
The continue Statement
The Labeled continue Statement

Using the break Statement in a Loop
Breaking Indefinite Loops
The Labeled break Statement

Assertions
More Complex Assertions

Summary

Exercises

Chapter 4: Arrays and Strings
Arrays
Array Variables
Defining an Array
The Length of an Array

91
94

95
95
97
98
98
99

100
102
104

108
111
112
117

121
123
123


124
127
128

130
132

133
134

135
135
136
136
137

xv


Contents
Accessing Array Elements
Reusing Array Variables
Initializing Arrays
Using a Utility Method to Initialize an Array
Initializing an Array Variable

Using Arrays
Using the Collection-Based for Loop with an Array


Arrays of Arrays
Arrays of Arrays of Varying Length
Multidimensional Arrays

Arrays of Characters

Strings
String Literals
Creating String Objects
Arrays of Strings

138
138
139
140
141

142
143

145
149
151

152

152
153
153
155


Operations on Strings

157

Joining Strings
Comparing Strings

157
161

Comparing Strings for Equality
String Interning
Checking the Start and End of a String

Sequencing Strings
Accessing String Characters
Extracting String Characters

Searching Strings for Characters
Searching for Substrings
Extracting Substrings
Tokenizing a String

Modified Versions of String Objects
Creating Character Arrays from String Objects
Using the Collection-Based for Loop with a String
Obtaining the Characters in a String as an Array of Bytes
Creating String Objects from Character Arrays


Mutable Strings
Creating StringBuffer Objects
The Capacity of a StringBuffer Object
Changing the String Length for a StringBuffer Object
Adding to a StringBuffer Object
Appending a Substring
Appending Basic Types

Finding the Position of a Substring
Replacing a Substring in the Buffer
Inserting Strings

xvi

163
166
167

167
169
170

172
173
177
179

182
182
183

183
184

184
185
186
188
189
189
190

191
192
192


Contents
Extracting Characters from a Mutable String
Other Mutable String Operations
Creating a String Object from a StringBuffer Object

Summary
Exercises

Chapter 5: Defining Classes
What Is a Class?
Fields in a Class Definition
Methods in a Class Definition
Accessing Variables and Methods


Defining Classes
Defining Methods
Returning from a Method
The Parameter List

193
193
194

196
197

199
200
200
202
203

204
205
206
206

How Argument Values Are Passed to a Method
Final Parameters

208
209

Defining Class Methods

Accessing Class Data Members in a Method
The Variable this
Initializing Data Members

209
209
210
211

Using Initialization Blocks

Constructors
The Default Constructor
Creating Objects of a Class
Passing Objects to a Method
The Lifetime of an Object

Defining and Using a Class
Method Overloading
Multiple Constructors
Calling a Constructor from a Constructor

Duplicating Objects Using a Constructor

Using Objects
Creating a Point from Two Lines

Recursion
Understanding Packages
Packaging Up Your Classes

Packages and the Directory Structure
Compiling a Package
Accessing a Package
Using Extensions

Adding Classes from a Package to Your Program

212

215
216
217
218
219

220
222
223
225

226

227
230

233
236
237
237
238

239
240

241

xvii


Contents
Packages and Names in Your Programs
Importing Static Class Members
Standard Packages
Standard Classes Encapsulating the Primitive Data Types

Controlling Access to Class Members
Using Access Attributes
Specifying Access Attributes
Choosing Access Attributes
Using Package and Access Attributes

Nested Classes
Static Nested Classes
Using a Non-Static Nested Class
Using a Nested Class Outside the Top-Level Class
Local Nested Classes

The finalize() Method
Native Methods
Summary
Exercises


Chapter 6: Extending Classes and Inheritance
Using Existing Classes
Class Inheritance
Inheriting Data Members
Hidden Data Members

Inherited Methods
Objects of a Derived Class
Deriving a Class
Derived Class Constructors
Calling the Base Class Constructor

Overriding a Base Class Method

Choosing Base Class Access Attributes
Polymorphism
Using Polymorphism

Multiple Levels of Inheritance
Abstract Classes
The Universal Superclass
The toString() Method
Determining the Type of an Object
Copying Objects

Methods Accepting a Variable Number of Arguments
Limiting the Types in a Variable Argument List

xviii


241
242
243
244

246
246
248
250
251

256
257
262
263
264

265
266
266
267

269
269
271
272
273

273

274
275
275
276

277

279
279
282

286
287
288
289
289
291

295
297


Contents
Casting Objects
When to Cast Objects
Identifying Objects

More on Enumerations
Adding Members to an Enumeration Class


298
300
301

302
303

Designing Classes

307

A Classy Example

307

Designing the PolyLine Class
A General-Purpose Linked List

Using the final Modifier
Interfaces
Encapsulating Constants in a Program

309
313

317
318
319

Constants in an Interface

Constants Defined in a Class

320
321

Interfaces Declaring Methods

323

A Partial Interface Implementation

Extending Interfaces
Interfaces and Multiple Inheritance

Using Interfaces
Interfaces and Polymorphism
Using Multiple Interfaces

Method Parameters of Interface Types
Nesting Classes in an Interface Definition
Interfaces and the Real World

324

325
326

326
327
333


333
334
334

Anonymous Classes
Summary
Exercises

335
335
337

Chapter 7: Exceptions

339

The Idea Behind Exceptions
Types of Exceptions
Error Exceptions
RuntimeException Exceptions
Other Subclasses of Exception

Dealing with Exceptions
Specifying the Exceptions a Method Can Throw
Handling Exceptions
The try Block
The catch Block
try catch Bonding
Multiple catch Blocks


The finally Block

339
340
341
342
343

344
344
345
345
345
347
349

350

xix


Contents
Structuring a Method
Execution Sequence
Normal Execution of a Method
Execution When an Exception Is Thrown
Execution When an Exception Is Not Caught

Nested try Blocks

Rethrowing Exceptions

Exception Objects
The Throwable Class
Standard Exceptions

355
356
357

358
359

359
359
362

Defining Your Own Exceptions

362

Defining an Exception Class
Throwing Your Own Exception
An Exception Handling Strategy

363
363
364

An Example of an Exception Class


Summary
Exercises

Chapter 8: Understanding Streams
Streams and the New I/O Capability
Understanding Streams
Input and Output Streams
Binary and Character Streams

364

368
368

371
371
372
373
374

The Classes for Input and Output

375

Basic Input Stream Operations
Basic Output Stream Operations
Stream Readers and Writers

375

379
379

Using Readers
Using Writers

381
382

The Standard Streams

384

Getting Data from the Keyboard

384

Tokenizing a Stream
Customizing a Stream Tokenizer

385
387

Writing to the Command Line
The printf() Method
Formatting Numerical Data
Specifying the Width and Precision
Formatting Characters and Strings
The Locale Class


Formatting Data into a String

Summary
Exercises

xx

351
352

392
392
394
395
396
397

398

399
399


Contents
Chapter 9: Accessing Files and Directories
Working with File Objects
Creating File Objects

401
401

402

Portable Path Considerations
Absolute and Relative Paths

404
404

Accessing System Properties

405

Setting System Properties

407

Testing and Checking File Objects
Querying Files and Directories

Filtering a File List
Creating and Modifying Files and Directories

Creating File Output Streams
Ensuring a File Exists
Avoiding Overwriting a File
FileDescriptor Objects

Summary
Exercises


Chapter 10: Writing Files

408
409

414
417

419
421
423
424

425
425

427

File I/O Basics
File Input and Output
Channels

427
429
430

Channel Operations
File Channels

431

433

Buffers
Buffer Capacity
Buffer Position and Limit
Setting the Position and Limit
Creating Buffers

434
434
435
437
438

View Buffers
Duplicating and Slicing Buffers
Creating Buffers by Wrapping Arrays
Wrapping Strings

439
441
443
445

Marking a Buffer
Buffer Data Transfers
Transferring Data into a Buffer
Using View Buffers
Preparing a Buffer for Output to a File


446
446
447
449
449

Writing to a File

451

File Position

453

Using a View Buffer to Load Data into a Byte Buffer

458

xxi


Contents
Writing Varying Length Strings to a File
Using a Formatter Object to Load a Buffer

Direct and Indirect Buffers
Writing Numerical Data to a File
Writing Mixed Data to a File
Gathering-Write Operations


Summary
Exercises

Chapter 11: Reading Files
File Read Operations

460
462

466
467
471
477

481
482

483
483

Creating File Input Streams

484

File Channel Read Operations
Reading a Text File

485
488


Getting Data from the Buffer

489

Reading Binary Data
Reading Mixed Data
Compacting a Buffer

Copying Files
Random Access to a File
Read/Write Operations with a Single File Channel
Memory-Mapped Files
Locking a File
Locking Part of a File
Practical File Locking Considerations

Summary
Exercises

Chapter 12: Serializing Objects
Storing Objects in a File
Writing an Object to a File
Writing Basic Data Types to an Object Stream
Implementing the Serializable Interface
Conditions for Serialization
Transient Data Members of a Class

Reading an Object from a File
Determining the Class of a Deserialized Object
Reading Basic Data from an Object Stream


Using Object Serialization
Serializing Classes Yourself

xxii

491
496
499

502
507
512
513
517
519
519

523
524

525
525
526
528
529
532
533

533

537
538

538
541


Contents
Serialization Problems and Complications
Resetting an Object Output Stream

Summary
Exercises

542
544

545
546

Chapter 13: Generic Class Types

547

What Are Generic Types?
Defining a Generic Class Type

547
548


Implementing a Generic Type
Instantiating a Generic Type

550
551

Using Primitive Type Wrapper Class Types as Arguments

The Runtime Type of Generic Type Instances
Relationships between Generic Type Instances
Multiple Type Parameters
Type Parameter Scope
Static Fields in a Generic Type
Type Parameter Bounds

Generic Types and Generic Interfaces
Enabling the Collection-Based for Loop
Implementing an Iterator Capability
A Parameterized Type for Binary Trees
Defining the Generic Type
Hidden Constraints in the BinaryTree<> Type

Variables of a Raw Type
Using Wildcards as Type Parameter Arguments
Constraints on a Wildcard
More on the Class Class

Arrays and Parameterized Types
Parameterized Methods
Generic Constructors


Parameterized Types and Inheritance
Summary
Exercises

Chapter 14: The Collections Framework
Understanding the Collections Framework
Collections of Objects
Sets
Sequences
Maps
Hashing

555

557
559
559
560
560
561

565
565
567
569
571
579

580

582
584
587

588
592
595

598
599
600

601
601
602
603
604
605
606

xxiii


Contents
Iterators
List Iterators

Collection Classes
Collection Interfaces


Using Vectors
Creating a Vector
The Capacity and Size of a Vector

Storing Objects in a Vector
Retrieving Objects from a Vector
Accessing Elements in a Vector through a List Iterator
Extracting All the Elements from a Vector

Removing Objects from a Vector
Searching a Vector
Applying Vectors
Sorting a Collection
Stack Storage

Linked Lists
Using Maps
The Hashing Process
Using Your Own Class Objects as Keys
Generating Hashcodes

Creating a HashMap Container
Storing, Retrieving, and Removing Objects
Processing all the Elements in a Map

Summary
Exercises

Chapter 15: A Collection of Useful Classes
Utility Methods for Arrays

Filling an Array
Comparing Arrays
Sorting Arrays
Searching Arrays

Observable and Observer Objects
Defining Classes of Observable Objects
Observable Class Methods

Generating Random Numbers
Random Operations

Dates and Times
The Date Class
Interpreting Date Objects
Obtaining a Date Object from a String

xxiv

606
608

610
614

615
616
618

620

621
621
622

623
625
626
630
632

638
640
640
642
642

643
644
646

657
658

659
659
660
661
662
666


670
671
671

675
676

678
679
679
684


×