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

java in a nutshell a5th edition

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 (47.59 MB, 1,256 trang )

www.traintelco.com
www.traintelco.com
JAVA
TM
IN A NUTSHELL
Downloa d f r o m W o w ! e B o o k < w w w.woweb o o k . c o m >
www.traintelco.com
Other Java

resources from O’Reilly
Related titles
Learning Java

Java

Cookbook
Java

Threads
Java

5.0 Tiger:
A Developer’s Notebook
Better, Faster, Lighter
Java

Enterprise JavaBeans

Head First Java

Java



Network
Programming
Java Books
Resource Center
java.oreilly.com is a complete catalog of O’Reilly’s books
on Java and related technologies, including sample chap-
ters and code examples.
OnJava.com is a one-stop resource for enterprise Java de-
velopers, featuring news, code recipes, interviews,
weblogs, and more.
Conferences
O’Reilly Media brings diverse innovators together to nur-
ture the ideas that spark revolutionary industries. We
specialize in documenting the latest tools and systems,
translating the innovator’s knowledge into useful skills
for those in the trenches. Visit conferences.oreilly.com for
our upcoming events.
Safari Bookshelf (safari.oreilly.com) is the premier online
reference library for programmers and IT professionals.
Conduct searches across more than 1,000 books. Sub-
scribers can zero in on answers to time-critical questions
in a matter of seconds. Read the books on your Book-
shelf from cover to cover or simply flip to the page you
need. Try it today with a free trial.
www.traintelco.com
Fifth Edition
JAVA
TM
IN A NUTSHELL

David Flanagan
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
www.traintelco.com
Java

in a Nutshell, Fifth Edition
by David Flanagan
Copyright © 2005, 2002, 1999, 1997, 1996 O’Reilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online
editions are also available for most titles (safari.oreilly.com). For more information, contact
our corporate/institutional sales department: (800) 998-9938 or
Editors:
Debra Cameron and Mike Loukides
Production Editor:
Jamie Peppard
Cover Designer:
Edie Freedman
Interior Designer:
David Futato
Printing History:
February 1996: First Edition.
May 1997: Second Edition.
November 1999: Third Edition.
March 2002: Fourth Edition.
March 2005: Fifth Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarks of O’Reilly Media, Inc. The In a Nutshell series designations, Java in a Nutshell,
the image of the Javan tiger, and related trade dress are trademarks of O’Reilly Media, Inc.

Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of
Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is
independent of Sun Microsystems.
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 O’Reilly Media,
Inc. was aware of a trademark claim, the designations have been printed in caps or initial
caps.
While every precaution has been taken in the preparation of this book, the publisher and
author assume no responsibility for errors or omissions, or for damages resulting from the use
of the information contained herein.
ISBN: 978-0-596-00773-7
[TG] [2011-07-22]
www.traintelco.com
This book is dedicated to all
who teach peace and resist violence.
www.traintelco.com
www.traintelco.com
vii
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Table of Contents
Preface
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xvii
Part I. Introducing Java
1. Introduction
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
What Is Java? 1
The Java Programming Language 1

The Java Virtual Machine 2
The Java Platform 2
Versions of Java 3
Key Benefits of Java 4
Write Once, Run Anywhere 4
Security 5
Network-Centric Programming 5
Dynamic, Extensible Programs 5
Internationalization 6
Performance 6
Programmer Efficiency and Time-to-Market 6
An Example Program 7
Compiling and Running the Program 7
Analyzing the Program 9
Exceptions 15
2. Java Syntax from the Ground Up
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
Java Programs from the Top Down 18
www.traintelco.com
viii
|
Table of Contents
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Lexical Structure 18
The Unicode Character Set 18
Case-Sensitivity and Whitespace 19
Comments 19
Reserved Words 20

Identifiers 20
Literals 21
Punctuation 21
Primitive Data Types 21
The boolean Type 22
The char Type 22
Strings 24
Integer Types 24
Floating-Point Types 25
Primitive Type Conversions 26
Expressions and Operators 28
Operator Summary 28
Arithmetic Operators 32
String Concatenation Operator 33
Increment and Decrement Operators 34
Comparison Operators 34
Boolean Operators 35
Bitwise and Shift Operators 37
Assignment Operators 39
The Conditional Operator 39
The instanceof Operator 40
Special Operators 40
Statements 42
Expression Statements 42
Compound Statements 43
The Empty Statement 43
Labeled Statements 43
Local Variable Declaration Statements 43
The if/else Statement 44
The switch Statement 46

The while Statement 48
The do Statement 49
The for Statement 49
The for/in Statement 50
The break Statement 54
The continue Statement 54
The return Statement 55
The synchronized Statement 55
The throw Statement 56
The try/catch/finally Statement 58
The assert Statement 60
www.traintelco.com
Table of Contents | ix
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Methods 64
Defining Methods 64
Method Modifiers 66
Declaring Checked Exceptions 68
Variable-Length Argument Lists 69
Covariant Return Types 70
Classes and Objects Introduced 71
Defining a Class 72
Creating an Object 72
Using an Object 73
Object Literals 73
Arrays 74
Array Types 75
Creating and Initializing Arrays 76
Using Arrays 77

Multidimensional Arrays 80
Reference Types 81
Reference vs. Primitive Types 82
Copying Objects 83
Comparing Objects 85
Terminology: Pass by Value 86
Memory Allocation and Garbage Collection 86
Reference Type Conversions 86
Boxing and Unboxing Conversions 88
Packages and the Java Namespace 89
Package Declaration 90
Globally Unique Package Names 90
Importing Types 90
Importing Static Members 92
Java File Structure 93
Defining and Running Java Programs 94
Differences Between C and Java 95
3. Object-Oriented Programming in Java
. . . . . . . . . . . . . . . . . . . . . . . .
98
Class Definition Syntax 99
Fields and Methods 100
Field Declaration Syntax 101
Class Fields 102
Class Methods 102
Instance Fields 103
Instance Methods 104
Case Study: System.out.println( ) 106
Creating and Initializing Objects 106
Defining a Constructor 107

www.traintelco.com
x
|
Table of Contents
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Defining Multiple Constructors 108
Invoking One Constructor from Another 108
Field Defaults and Initializers 109
Destroying and Finalizing Objects 111
Garbage Collection 111
Memory Leaks in Java 112
Object Finalization 113
Subclasses and Inheritance 114
Extending a Class 114
Superclasses, Object, and the Class Hierarchy 116
Subclass Constructors 116
Constructor Chaining and the Default Constructor 117
Hiding Superclass Fields 119
Overriding Superclass Methods 120
Data Hiding and Encapsulation 123
Access Control 124
Data Accessor Methods 127
Abstract Classes and Methods 128
Important Methods of java.lang.Object 130
toString() 132
equals( ) 132
hashCode( ) 133
Comparable.compareTo( ) 133
clone() 134

Interfaces 135
Defining an Interface 135
Implementing an Interface 136
Interfaces vs. Abstract Classes 138
Marker Interfaces 139
Interfaces and Constants 139
Nested Types 140
Static Member Types 141
Nonstatic Member Classes 143
Local Classes 147
Anonymous Classes 151
How Nested Types Work 154
Modifier Summary 156
C++ Features Not Found in Java 157
4. Java 5.0 Language Features
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
159
Generic Types 160
Typesafe Collections 160
Understanding Generic Types 163
Type Parameter Wildcards 166
www.traintelco.com
Table of Contents | xi
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Writing Generic Types and Methods 169
Generics Case Study: Comparable and Enum 176
Enumerated Types 178
Enumerated Types Basics 179
Using Enumerated Types 181

Advanced Enum Syntax 185
The Typesafe Enum Pattern 190
Annotations 191
Annotation Concepts and Terminology 192
Using Standard Annotations 194
Annotation Syntax 196
Annotations and Reflection 198
Defining Annotation Types 199
Meta-Annotations 201
5. The Java Platform
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
203
Java Platform Overview 203
Text 205
The String Class 205
The Character Class 206
The StringBuffer Class 206
The CharSequence Interface 207
The Appendable Interface 207
String Concatenation 208
String Comparison 208
Supplementary Characters 209
Formatting Text with printf() and format( ) 210
Logging 211
Pattern Matching with Regular Expressions 212
Tokenizing Text 215
StringTokenizer 216
Numbers and Math 217
Mathematical Functions 217
Random Numbers 218

Big Numbers 218
Converting Numbers from and to Strings 219
Formatting Numbers 220
Dates and Times 221
Milliseconds and Nanoseconds 221
The Date Class 222
The Calendar Class 222
Formatting Dates and Times 223
Arrays 224
Collections 225
www.traintelco.com
xii
|
Table of Contents
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
The Collection Interface 225
The Set Interface 227
The List Interface 229
The Map Interface 231
The Queue and BlockingQueue Interfaces 234
Collection Wrappers 236
Special-Case Collections 236
Converting to and from Arrays 237
Collections Utility Methods 237
Implementing Collections 238
Threads and Concurrency 238
Creating, Running, and Manipulating Threads 238
Making a Thread Sleep 241
Running and Scheduling Tasks 241

Exclusion and Locks 245
Coordinating Threads 247
Thread Interruption 250
Blocking Queues 251
Atomic Variables 252
Files and Directories 252
RandomAccessFile 253
Input/Output with java.io 254
Reading Console Input 254
Reading Lines from a Text File 254
Writing Text to a File 255
Reading a Binary File 255
Compressing Data 255
Reading ZIP Files 256
Computing Message Digests 256
Streaming Data to and from Arrays 257
Thread Communication with Pipes 257
Networking with java.net 258
Networking with the URL Class 258
Working with Sockets 258
Secure Sockets with SSL 259
Servers 261
Datagrams 262
Testing the Reachability of a Host 263
I/O and Networking with java.nio 263
Basic Buffer Operations 264
Basic Channel Operations 265
Encoding and Decoding Text with Charsets 267
Working with Files 268
Client-Side Networking 271

Server-Side Networking 272
Nonblocking I/O 273
www.traintelco.com
Table of Contents | xiii
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
XML 276
Parsing XML with SAX 277
Parsing XML with DOM 278
Transforming XML Documents 280
Validating XML Documents 281
Evaluating XPath Expressions 283
Types, Reflection, and Dynamic Loading 283
Class Objects 284
Reflecting on a Class 284
Dynamic Class Loading 285
Dynamic Proxies 286
Object Persistence 286
Serialization 286
JavaBeans Persistence 287
Security 288
Message Digests 288
Digital Signatures 289
Signed Objects 290
Cryptography 290
Secret Keys 290
Encryption and Decryption with Cipher 291
Encrypting and Decrypting Streams 292
Encrypted Objects 292
Miscellaneous Platform Features 292

Properties 293
Preferences 294
Processes 295
Management and Instrumentation 296
6. Java Security
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
299
Security Risks 300
Java VM Security and Class File Verification 300
Authentication and Cryptography 301
Access Control 301
Java 1.0: The Sandbox 301
Java 1.1: Digitally Signed Classes 302
Java 1.2: Permissions and Policies 303
Security for Everyone 304
Security for System Programmers 304
Security for Application Programmers 304
Security for System Administrators 305
Security for End Users 305
Permission Classes 306
www.traintelco.com
xiv
|
Table of Contents
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
7. Programming and Documentation Conventions
. . . . . . . . . . . . . . .
308
Naming and Capitalization Conventions 308

Portability Conventions and Pure Java Rules 310
Java Documentation Comments 312
Structure of a Doc Comment 313
Doc-Comment Tags 314
Inline Doc Comment Tags 316
Cross-References in Doc Comments 318
Doc Comments for Packages 319
JavaBeans Conventions 320
Bean Basics 320
Bean Classes 321
Properties 322
Indexed Properties 322
Bound Properties 322
Constrained Properties 323
Events 324
8. Java Development Tools
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
326
apt 326
extcheck 327
jarsigner 328
jar 329
java 332
javac 338
javadoc 342
javah 348
javap 349
javaws 351
jconsole 352
jdb 353

jinfo 357
jmap 358
jps 358
jsadebugd 359
jstack 359
jstat 360
jstatd 362
keytool 362
native2ascii 366
pack200 366
policytool 368
www.traintelco.com
Table of Contents | xv
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
serialver 370
unpack200 370
Part II. API Quick Reference
How to Use This Quick Reference
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
375
9. java.io
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
385
10. java.lang and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
439
11. java.math
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
543

12. java.net
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
549
13. java.nio and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
586
14. java.security and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
638
15. java.text
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
724
16. java.util and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
750
17. javax.crypto and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
921
18. javax.net and javax.net.ssl
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
946
19. javax.security.auth and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . .
970
20. javax.xml and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
994
21. org.w3c.dom
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1032

22. org.xml.sax and Subpackages
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1051
Class, Method, and Field Index
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1077
Index
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1147
www.traintelco.com
www.traintelco.com
xvii
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Chapter 1
Preface
This book is a desktop Java™ quick reference, designed to sit faithfully by your
keyboard while you program. Part I of the book is a fast-paced, “no-fluff” intro-
duction to the Java programming language and the core APIs of the Java platform.
Part II is a quick reference section that succinctly details most classes and inter-
faces of those core APIs. The book covers Java 1.0, 1.1, 1.2, 1.3, 1.4, and 5.0.
Changes in the Fifth Edition
The fifth edition of this book covers Java 5.0. As its incremented version number
attests, this new version of Java has a lot of new features. The three most signifi-
cant new language features are generic types, enumerated types, and annotations,
which are covered in a new chapter of their own. Experienced Java programmers
who just want to learn about these new features can jump straight to Chapter 4.
Other new language features of Java 5.0 are:
• The for/in statement for easily iterating through arrays and collections (this
statement is sometimes called “foreach”).

• Autoboxing and autounboxing conversions to automatically convert back
and forth between primitive values and their corresponding wrapper objects
(such as
int values and Integer objects) as needed.
• Varargs methods to define and invoke methods that accept an arbitrary num-
ber of arguments.
• Covariant returns to allow a subclass to override a superclass method and
narrow the return type of the method.
• The
import static declaration to import the static members of a type into
the namespace.
Although each of these features is new in Java 5.0, none of them is large enough to
merit a chapter of its own. Coverage of these features is integrated into Chapter 2.
www.traintelco.com
xviii
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
In addition to these language changes, Java 5.0 also includes changes to the Java
platform. Important enhancements include the following:
• The
java.util collections classes have been converted to be generic types,
providing support for typesafe collections. This is covered in Chapter 4.
• The
java.util package also includes the new Formatter class. This class
enables C-style formatted text output with
printf( ) and format( ) methods.
Examples are included in Chapter 5. The
java.util.Formatter entry in the

quick reference includes a detailed table of formatting options.
• The new package
java.util.concurrent includes important utilities for
threadsafe concurrent programming. Chapter 5 provides examples.

java.lang has three new subpackages:

java.lang.annotation
• java.lang.instrument
• java.lang.management
These packages support Java 5.0 annotations and the instrumentation, man-
agement, and monitoring of a running Java interpreter. Although their posi-
tion in the
java.lang hierarchy marks these packages as very important, they
are not commonly used. Annotation examples are provided in Chapter 4, and
a simple instrumentation and management example is found in Chapter 5.
• New packages have been added to the
javax.xml hierarchy. javax.xml.
validation
supports document validation with schemas. javax.xml.xpath
supports the XPath query language. And javax.xml.namespace provides sim-
ple support for XML namespaces. Validation and XPath examples are in
Chapter 5.
In a mostly futile attempt to make room for this new material, I’ve had to make
some cuts. I’ve removed coverage of the packages
java.beans, java.beans.
beancontext
, java.security.acl, and org.ietf.jgss from the quick reference.
JavaBeans standards have not caught on in core Java APIs and now appear to be
relevant only for Swing and related graphical APIs. As such, they are no longer

relevant in this book. The
java.security.acl package has been deprecated since
Java 1.2 and I’ve taken this opportunity to remove it. And the
org.ietf.jgss
package is of interest to only a very narrow subset of readers.
Along with removing coverage of
java.beans from the quick reference section, I’ve
also cut the chapter on JavaBeans from Part I of this book. The material on Java-
Beans naming conventions from that chapter remains useful, however, and has
been moved into Chapter 7.
Contents of This Book
The first eight chapters of this book document the Java language, the Java plat-
form, and the Java development tools that are supplied with Sun’s Java
Development Kit (JDK). The first five chapters are essential; the next three cover
topics of interest to some, but not all, Java programmers.
www.traintelco.com
Preface | xix
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Chapter 1: Introduction
This chapter is an overview of the Java language and the Java platform that
explains the important features and benefits of Java. It concludes with an
example Java program and walks the new Java programmer through it line
by line.
Chapter 2: Java Syntax from the Ground Up
This chapter explains the details of the Java programming language,
including some of the Java 5.0 language changes. It is a long and detailed
chapter that does not assume substantial programming experience. Experi-
enced Java programmers can use it as a language reference. Programmers
with substantial experience with languages such as C and C++ should be able

to pick up Java syntax quickly by reading this chapter; beginning program-
mers with only a modest amount of experience should be able to learn Java
programming by studying this chapter carefully.
Chapter 3: Object-Oriented Programming in Java
This chapter describes how the basic Java syntax documented in Chapter 2 is
used to write object-oriented programs in Java. The chapter assumes no prior
experience with OO programming. It can be used as a tutorial by new
programmers or as a reference by experienced Java programmers.
Chapter 4: Java 5.0 Language Features
This chapter documents the three biggest new features of Java 5.0: generic
types, enumerated types, and annotations. If you read previous editions of
this book, you might want to skip directly to this chapter.
Chapter 5: The Java Platform
This chapter is an overview of the essential Java APIs covered in this book. It
contains numerous short examples that demonstrate how to perform
common tasks with the classes and interfaces that comprise the Java plat-
form. Programmers who are new to Java (and especially those who learn best
by example) should find this a valuable chapter.
Chapter 6: Java Security
This chapter explains the Java security architecture that allows untrusted
code to run in a secure environment from which it cannot do any malicious
damage to the host system. It is important for all Java programmers to have
at least a passing familiarity with Java security mechanisms.
Chapter 7: Programming and Documentation Conventions
This chapter documents important and widely adopted Java programming
conventions, including JavaBeans naming conventions. It also explains how
you can make your Java code self-documenting by including specially
formatted documentation comments.
Chapter 8: Java Development Tools
Sun’s JDK includes a number of useful Java development tools, most notably

the Java interpreter and the Java compiler. This chapter documents those tools.
These first eight chapters teach you the Java language and get you up and running
with the Java APIs. Part II of the book is a succinct but detailed API reference
formatted for optimum ease of use. Please be sure to read How to Use This Quick
www.traintelco.com
xx
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Reference in Part II; it explains how to get the most out of the quick reference
section. Also, please note that the quick reference chapters are followed by one
final chapter called “Class, Method, and Field Index.” This special index allows
you to look up the name of a type and find the package in which it is defined or to
look up the name of a method or field and find the type in which it it is defined.
Related Books
O’Reilly publishes an entire series of books on Java programming, including
several companion books to this one. The companion books are:
Java Examples in a Nutshell
This book contains hundreds of complete, working examples illustrating
many common Java programming tasks using the core, enterprise, and
desktop APIs. Java Examples in a Nutshell is like Chapter 4 of this book, but
greatly expanded in breadth and depth, and with all the code snippets fully
fleshed out into working examples. This is a particularly valuable book for
readers who learn well by experimenting with existing code.
Java Enterprise in a Nutshell
This book is a succinct tutorial for the Java “Enterprise” APIs such as JDBC,
RMI, JNDI, and CORBA. It also cover enterprise tools such as Hibernate,
Struts, Ant, JUnit, and XDoclet.
J2ME in a Nutshell

This book is a tutorial and quick reference for the graphics, networking, and
database APIs of the Java 2 Micro Edition (J2ME) platform.
You can find a complete list of Java books from O’Reilly at />Books that focus on the core Java APIs, as this one does, include:
Learning Java, by Pat Niemeyer and Jonathan Knudsen
This book is a comprehensive tutorial introduction to Java, with an emphasis
on client-side Java programming.
Java Swing, by Marc Loy, Robert Eckstein, Dave Wood, James Elliott, and Brian Cole
This book provides excellent coverage of the Swing APIs and is a must-read
for GUI developers.
Java Threads, by Scott Oaks and Henry Wong
Java makes multithreaded programming easy, but doing it right can still be
tricky. This book explains everything you need to know.
Java I/O, by Elliotte Rusty Harold
Java’s stream-based input/output architecture is a thing of beauty. This book
covers it in the detail it deserves.
Java Network Programming, by Elliotte Rusty Harold
This book documents the Java networking APIs in detail.
Java Security, by Scott Oaks
This book explains the Java access-control mechanisms in detail and also
documents the authentication mechanisms of digital signatures and message
digests.
www.traintelco.com
Preface | xxi
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Java Cryptography, by Jonathan Knudsen
This book provides thorough coverage of the Java Cryptography Extension,
the
javax.crypto.* packages, and cryptography in Java.
Examples Online

The examples in this book are available online and can be downloaded from the
home page for the book at You may
also want to visit this site for any important notes or errata that have been
published there.
Conventions Used in This Book
We use the following formatting conventions in this book:
Italic
Used for emphasis and to signify the first use of a term. Italic is also used for
commands, email addresses, web sites, FTP sites, and file and directory
names.
Bold
Occasionally used to refer to particular keys on a computer keyboard or to
portions of a user interface, such as the Back button or the Options menu.
Constant Width
Used for all Java code as well as for anything that you would type literally
when programming, including keywords, data types, constants, method
names, variables, class names, and interface names.
Constant Width Italic
Used for the names of function arguments and generally as a placeholder to
indicate an item that should be replaced with an actual value in your
program. Sometimes used to refer to a conceptual section or line of code as in
statement.
Franklin Gothic Book Condensed
Used for the Java class synopses in the quick reference section. This very
narrow font allows us to fit a lot of information on the page without a lot of
distracting line breaks. This font is also used for code entities in the descrip-
tions in the quick reference section.
Franklin Gothic Demi Condensed
Used for highlighting class, method, field, property, and constructor names in
the quick reference section, which makes it easier to scan the class synopses.

Franklin Gothic Book Condensed Italic
Used for method parameter names and comments in the quick reference
section.
www.traintelco.com
xxii
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
Request for Comments
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-1014 (fax)
There is a web page for this book, which lists errata, examples, and any addi-
tional information. You can access this page at:
/>To ask technical questions or comment on this book, send email to:

For more information about books, conferences, Resource Centers, and the
O’Reilly Network, see the O’Reilly web site at:

How the Quick Reference Is Generated
For the curious reader, this section explains a bit about how the quick reference
material in Java in a Nutshell and related books is created.
As Java has evolved, so has my system for generating Java quick reference mate-
rial. The current system is part of a larger commercial documentation browser
system I’m developing (visit for more informa-

tion about it). The program works in two passes: the first pass collects and
organizes the API information, and the second pass outputs that information in
the form of quick reference chapters.
The first pass begins by reading the class files for all of the classes and interfaces to
be documented. Almost all of the API information in the quick reference is avail-
able in these class files. The notable exception is the names of method arguments,
which are not stored in class files. These argument names are obtained by parsing
the Java source file for each class and interface. Where source files are not available,
I obtain method argument names by parsing the API documentation generated by
javadoc. The parsers I use to extract API information from the source files and
javadoc files are created using the Antlr parser generator developed by Terence Parr.
(See for details on this very powerful programming tool.)
Once the API information has been obtained by reading class files, source files,
and javadoc files, the program spends some time sorting and cross-referencing
everything. Then it stores all the API information into a single large data file.
The second pass reads API information from that data file and outputs quick
reference chapters using a custom XML doctype. Once I’ve generated the XML
output, I hand it off to the production team at O’Reilly. In the past, these XML
www.traintelco.com
Preface | xxiii
This is the Title of the Book, eMatter Edition
Copyright © 2011 O’Reilly & Associates, Inc. All rights reserved.
documents were converted to troff and formatted with GNU groff using a highly
customized macro package. In this edition, the chapters were converted from
XML to Framemaker instead, using in-house production tools.
When you see a Safari®-enabled icon on the cover of your favorite
technology book, that means the book is available online through
the O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-Books. It’s a virtual
library that lets you easily search thousands of top tech books, cut and paste code

samples, download chapters, and find quick answers when you need the most
accurate, current information. Try it free at .
Acknowledgments
Many people helped in the creation of this book, and I am grateful to them all. I
am indebted to the many, many readers of the first four editions who wrote in
with comments, suggestions, bug reports, and praise. Their many small contribu-
tions are scattered throughout the book. Also, my apologies to those who made
many good suggestions that could not be incorporated into this edition.
Deb Cameron was the editor for the fifth edition. Deb edited not only the mate-
rial that was new in this edition but also made the time to carefully read over the
old material, giving it a much-needed updating. Deb was patient when my work
on this book veered off in an unexpected direction and provided steady guidance
to help get me back on track. The fourth edition was edited by Bob Eckstein, a
careful editor with a great sense of humor. Paula Ferguson, a friend and colleague,
was the editor of the first three editions of this book. Her careful reading and
practical suggestions made the book stronger, clearer, and more useful.
As usual, I’ve had a crack team of technical reviewers for this edition of the book.
Gilad Bracha of Sun reviewed the material on generic types. Josh Bloch, a former
Sun employee who is now at Google, reviewed the material on enumerated types
and annotations. Josh was also a reviewer for the third and fourth editions of the
book, and his helpful input has been an invaluable resource for me. Josh’s book
Effective Java Programming Guide (Addison Wesley) is highly recommended. Neal
Gafter, who, like Josh, left Sun for Google, answered many questions about anno-
tations and generics. David Biesack of SAS, Changshin Lee of the Korean
company Tmax Soft, and Tim Peierls were colleagues of mine on the JSR-201
expert group that was responsible for a number of language changes in Java 5.0.
They reviewed the generics and enumerated type material. Joseph Bowbeer, Brian
Goetz, and Bill Pugh were members of the JSR-166 or JSR-133 expert groups and
helped me to understand threading and concurrency issues behind the
java.util.

concurrency
package. Iris Garcia of Sun answered my questions about the new
java.util.Formatter class that she authored. My sincere thanks go to each of
these engineers. Any mistakes that remain in the book are, of course, my own.
The fourth edition was also reviewed by a number of engineers from Sun and else-
where. Josh Bloch reviewed material on assertions and the Preferences API. Bob
Eckstein reviewed XML material. Graham Hamilton reviewed the Logging API
material. Ron Hitchens reviewed the New I/O material. Jonathan Knudsen (who
www.traintelco.com

×