Register your product to gain access to bonus material or receive a coupon.
You will find in-depth and progressively advanced coverage of classes and objects, interfaces, exception-handling, threads and multitasking, and packages. In addition, the book describes the Java core library packages, including I/O, standard utilities, language types, and system classes.
Thoroughly revised from start to finish, this second edition fully integrates Java 1.1 into both text and examples. This edition includes the changes introduced in Java 1.1, such as nested classes (including anonymous classes), threading issues, character-based streams, object-serialization, documentation comments, new utility classes, plus internationalization and localization.
The book lets you in on the rationale behind Java's design, direct from the language's creator, as well as the tradeoffs involved in using specific features. With these insights, you will have the understanding you need to begin developing Java applications and applets.
Third Edition now available! |
Co-authored by the creator of the Java technology and an experienced object-oriented developer, The JavaTM Programming Language, Second Edition, is the definitive resource for all serious Java programmers. This book will give you a solid foundation in Java programming language strategies and techniques. It features a concise introduction to the language; detailed descriptions of Java's commands, constructs, and libraries; and numerous real-world examples that show you how to exploit the language's power, portability, and flexibility.
You will find in-depth and progressively advanced coverage of classes and objects, interfaces, exception-handling, threads and multitasking, and packages. In addition, the book describes the Java core library packages, including I/O, standard utilities, language types, and system classes.
Thoroughly revised from start to finish, this second edition fully integrates Java 1.1 into both text and examples. This edition includes the changes introduced in Java 1.1, such as nested classes (including anonymous classes), threading issues, character-based streams, object-serialization, documentation comments, new utility classes, plus internationalization and localization.
The book lets you in on the rationale behind Java's design, direct from the language's creator, as well as the tradeoffs involved in using specific features. With these insights, you will have the understanding you need to begin developing Java applications and applets.
1. A Quick Tour of Java.
Getting Started.
Variables.
Comments in Code.
Named Constants.
Unicode Characters.
Flow of Control.
Classes and Objects.
Creating Objects.
Static or Class Fields.
The Garbage Collector.
Methods and Parameters.
Invoking a Method.
The this Reference.
Static or Class Methods.
Arrays.
String Objects.
Extending a Class.
Invoking Methods from the Superclass.
The Object Class.
Interfaces.
Exceptions.
Packages.
The Java Platform.
Other Topics Briefly Noted.
2. Classes and Objects.
A Simple Class.
Fields.
Access Control and Inheritance.
Creating Objects.
Constructors.
Methods.
Parameter Values.
Using Methods to Control Access.
this.
Overloading Methods.
Static Members.
Initialization Blocks.
Garbage Collection and finalize.
finalize.
Resurrecting Objects During finalize.
Nested Classes and Interfaces.
Local Inner Classes.
main.
The to String Method.
Native Methods.
3. Extending Classes.
An Extended Class.
What protected Really Means.
Constructors in Extended Classes.
Constructor Order Dependencies.
Overriding Methods, Hiding Fields and Nested Classes.
The super Keyword.
Marking Methods and Classes final.
The Object Class.
Anonymous Classes.
Abstract Classes and Methods.
Cloning Objects.
Extending Classes: How and When.
Designing a Class to Be Extended.
4. Interfaces.
An Example Interface.
Single Inheritance versus Multiple Inheritance.
Extending Interfaces.
Name Conflicts.
Implementing Interfaces.
Using an Implementation.
Marker Interfaces.
When to Use Interfaces.
5. Tokens, Operators, and Expressions.
Character Set.
Comments.
Tokens.
Identifiers.
Java Keywords.
Primitive Types.
Literals.
Object References.
Boolean.
Integers.
Floating-Point Numbers.
Characters.
Strings.
Class Literals.
Declarations of Variables.
Using final for Variables.
The Meanings of Names.
Array Variables.
Arrays of Arrays.
Initial Values.
Array Initializers.
Operator Precedence and Associativity.
Order of Evaluation.
Expression Type.
Type Conversions.
Implicit Conversion.
Explicit Casts and instance of.
String Conversions.
Member Access.
Arithmetic Operators.
Integer Arithmetic.
Floating-Point Arithmetic.
Java Floating-Point Arithmetic and IEEE-754.
String Concatenation.
Increment and Decrement Operators.
Relational, Equality, and Logical Operators.
Bitwise Operators.
The Conditional Operator?
Assignment Operators.
Package Names.
6. Control Flow.
Statements and Blocks.
if-else.
switch.
while and do-while.
for.
Labels.
break.
continue.
return.
What, No go to?
7. Exceptions.
Creating Exception Types.
throw.
The throws Clause.
try, catch, and finally.
finally.
When to Use Exceptions.
8. Strings.
Basic String Operations.
String Comparisons.
Utility Methods.
Making Related Strings.
String Conversions.
Strings and char Arrays.
Strings and byte Arrays.
The String Buffer Class.
Modifying the Buffer.
Getting Data Out.
Capacity Management.
9. Threads.
Creating Threads.
Synchronization.
synchronized Methods.
synchronized Statements.
wait and notify.
Details of wait and notify.
Thread Scheduling.
Deadlocks.
Ending Thread Execution.
The End of a Thread's Life.
Waiting For a Thread to Complete.
Don't stop.
Suspending Threads.
Ending Application Execution.
Using Runnable.
volatile.
Thread Security and Thread Group.
Debugging Threads.
10. Packages.
Package Naming.
Package Access.
Package Contents.
11. Documentation Comments.
Paragraphs.
@see.
@param.
@return.
@exception.
@deprecated.
@author.
@version.
@since.
An Example.
Notes on Usage.
12. The I/O Package.
Byte Streams.
Input Stream.
Output Stream.
Character Streams.
Character Streams and the Standard Streams.
Reader.
Writer.
Summary of I/O Types.
Input Stream Reader and Output Stream Writer.
Filter Streams.
Print Streams.
Buffered Streams.
Byte Array Byte Streams.
Char Array Character Streams.
String Character Streams.
File Streams and File Descriptor.
Piped Streams.
Sequence Input Stream.
Line Number Reader.
Pushback Streams.
Stream Tokenizer.
Data Byte Streams.
The Data Stream Classes.
Random Access File.
The Object Byte Streams.
Making Your Classes Serializable.
Serialization and Deserialization Order.
Customized Serialization and Externalizable.
Object Versioning.
The Externalizable Interface.
The File Class.
Filename Filter.
The IO Exception Classes.
13. Standard Utilities.
Bit Set.
Enumeration.
Implementing an Enumeration Interface.
Vector.
Stack.
Dictionary.
Hashtable.
Properties.
Observer/Observable.
Random.
String Tokenizer.
14. Programming with Types.
Wrapper Classes: An Overview.
Void.
Boolean.
Character.
Number.
The Integer Wrapper Classes.
The Floating-Point Wrapper Classes.
Reflection.
Class.
Examining Classes.
Field.
Method.
Creating New Objects and Constructor.
Arrays.
Loading Classes.
Loading Related Resources.
15. System Programming.
Standard I/O Streams.
Memory Management.
System Properties.
Creating Processes.
Runtime.
Miscellaneous.
Security.
Math.
16. Internationalization and Localization.
Locale.
Resource Bundles.
List Resource Bundle.
Property Resource Bundle.
Subclassing Resource Bundle.
Time, Dates, and Calendars.
Calendars.
Time Zones.
Gregorian Calendar and Simple Time Zone.
Formatting and Parsing Dates and Times.
17. Standard Packages.
java.text - Internationalization and Localization for Text.
Collation.
Formatting and Parsing.
Text Boundaries.
java.awt-The Abstract Window Toolkit.
java.applet-Applets.
java.rmi-Remote Method Invocation.
java.beans-Java Components.
java.net-The Network.
java.math-Mathematics.
java.sql - Relational Database Access.
java.security - Security Tools.
Appendix A. Runtime Exceptions.
Runtime Exception Classes.
Error Classes.
Appendix B. Useful Tables.
Table 1: Keywords.
Table 2: Operator Precedence.
Table 3: Unicode Digits.
Table 4: Unicode Letters and Digits.
Table 5: Special Characters Using \.
Table 6: Documentation Comment Tags.
Further Reading. 0201310066T04062001
Preface
Beautiful buildings are more than scientific. They are true organisms, spiritually conceived; works of art, using the best technology by inspiration rather than the idiosyncrasies of mere taste or any averaging by the committee mind.-Frank Lloyd Wright
THE Java programming language (hereafter called simply Java) has been warmly received by the world community of software developers and Internet content providers. Users of the Internet and World Wide Web benefit from access to secure, platform-independent applications that can come from anywhere on the Internet. Software developers who create applications in Java benefit by develop- ing code only once, with no need to "port" their applications to every software and hardware platform.
For many, Java was known first as a tool to create applets for the World Wide Web. Applet is the term Java uses for a mini-application that runs inside a web page. An applet can perform tasks and interact with users on their browser pages without using resources from the Web server after being downloaded. Some applets may, of course, interact with the server for their own purposes, but that's their business.
Java is indeed valuable for distributed network environments like the Web. However, Java goes well beyond this domain to provide a powerful general-pur- pose programming language suitable for building a variety of applications that either do not depend on network features, or want them for different reasons. Java's ability to execute downloaded code on remote hosts in a secure manner is a critical requirement for many organizations.
Other groups use Java as a general-purpose programming language for projects in which machine independence is less important. Java's ease of pro- gramming and safety features help you quickly produce working code. Some common programming errors never occur because of features like garbage collec- tion and type-safe references. Java's support for multithreading caters to modern network-based and graphical user interface-based applications that must attend to multiple tasks simultaneously, and the mechanisms of exception handling ease the task of dealing with error conditions. While its built-in tools are powerful, the Java language is a simple language in which programmers can quickly become profi- cient.
Java is designed for maximum portability with as few implementation depen- dencies as possible. An int, for example, is a 32-bit signed two's-complement integer in all Java implementations, irrespective of the CPU architecture on which the Java program executes. Defining everything possible about the language and its runtime environment enables users to run compiled code anywhere and share code with anyone who has a Java environment.
About This Book
This book teaches Java programming to people who are familiar with basic pro- gramming concepts. It explains Java without being arduously formal or complete. This book is not an introduction to object-oriented programming, although some issues are covered to establish a common terminology. Other books in this series, and much online documentation, focus on Java applets, databases, components, and other specific kinds of programming tasks. For other references, see "Further Reading" on page 381.
This second edition includes the changes introduced in Java 1.1, such as nested classes (including anonymous classes), threading issues, character-based streams, object serialization, documentation comments, new utility classes, and internationalization/localization. You will also find brief coverage of the other core Java packages. If you have already read the first edition, this edition will give you new information, but since most of the language is unchanged, and almost all core packages types are still usable, you will want to pay most attention to the newer areas. The first chapter (the "quick tour") is largely unchanged because it covers the elemental parts of Java, which have changed little.
Java shares many language features common to most programming languages in use today. Java should look familiar to C and C++ programmers, because Java was designed with C and C++ constructs where the languages are similar. That said, this book is neither a comparative analysis nor a "bridge" tutorial-no knowledge of C or C++ is assumed. C++ programmers, especially, may be as hin- dered by what they must unlearn as they are helped by their knowledge.
Chapter 1-A Quick Tour of Java-gives a quick overview of Java. Program- mers who are unfamiliar with object-oriented programming notions should read the quick tour, while programmers who are already familiar with object-oriented programming paradigms will find the quick tour a useful introduction to the object-oriented features of Java.
Chapters 2, 3, and 4 cover the object-oriented core features of Java, namely, class declarations that define components of a program, and objects manufactured according to class definitions. Chapter 2-Classes and Objects-describes the basis of the Java language: classes. Chapter 3-Extending Classes-describes how an existing class can be extended, or subclassed, to create a new class with additional data and behavior. Chapter 4-Interfaces-describes how to declare interface types which are abstract descriptions of behavior that provide maximum flexibility for class designers and implementers.
Chapters 5 and 6 cover standard constructs common to most languages. Chap- ter 5-Tokens, Operators, and Expressions-describes the tokens of the language from which statements are constructed, how the tokens and operators are used to build expressions, and how expressions are evaluated. Chapter 6-Control Flow-describes how control statements direct the order of statement execution.
Chapter 7-Exceptions-describes Java's powerful error-handling capabili- ties. Chapter 8-Strings-describes the built-in language and runtime support for String objects.
Chapter 9-Threads-explains Java's implementation of multithreading. Many applications, such as graphical interface-based software, must attend to multiple tasks simultaneously. These tasks must cooperate to behave correctly, and threads meet the needs of cooperative multitasking.
Chapter 10-Packages-describes Java's mechanism for grouping collections of Java classes into separate packages. Chapter 11-Documentation Comments- shows how to write reference documentation in comments.
Chapters 12 through 15 cover the main body of the core Java class library packages. Chapter 12-The I/O Package-describes the Java input/output system, which is based on streams. Chapter 13-Standard Utilities-covers Java utility classes such as vectors and hashtables. Chapter 14-Programming with Types- describes Java's type-related classes: individual objects that describe each class and interface, and classes that wrap primitive data types such as integers and float- ing-point values into their own object types. Chapter 15-System Programming- leads you through the system classes that provide access to features of the under- lying platform.
Chapter 16- Internationalization and Localization-covers some of the tools used to create programs that can run in many linguistic and cultural environ- ments. Chapter 17-Standard Packages-briefly explores the packages that are part of the Java platform, giving overviews of those packages not covered in more detail in this book.
Appendix A-Runtime Exceptions-lists all the runtime exceptions and errors that the Java system itself can throw.
Appendix B-Useful Tables-has tables of information that you may find useful for quick reference.
Finally, Further Reading lists works that may be interesting for further read- ing on Java details, object orientation, programming with threads, software design, and other topics.
Examples and Documentation
All the code examples in the text have been compiled and run on the latest version of the language available at the time the book was written, which was version 1.1.4. Only Java 1.14 features are covered-deprecated types, methods, and fields are ignored except where unavoidable. We have also covered issues beyond writ- ing programs that simply compile. Part of learning a language is to learn to use it well. For this reason, we have tried to show principles of good programming style and design.
In a few places we refer to online documentation. Java development environ- ments provide a way to automatically generate documentation (usually HTML documents) from a compiled class using the documentation comments. This docu- mentation is normally viewed using a Web browser.
Acknowledgments (First Edition)
No technical book-writing endeavor is an island unto itself, and ours was more like a continent. Many people contributed technical help, excellent reviews, useful information, and book-writing advice.
Contributing Editor Henry McGilton of Trilithon Software played the role of "Chief Editorial Firefighter" to help make this book possible. Series Editor Lisa Friendly contributed dogged perseverance and support.
A veritable multitude of reviewers took time out of their otherwise busy lives to read, edit, advise, revise, and delete material, all in the name of making this a better book. Kevin Coyle performed one of the most detailed editorial reviews at all levels. Karen Bennet, Mike Burati, Patricia Giencke, Steve Gilliard, Bill Joy, Rosanna Lee, Jon Madison, Brian O'Neill, Sue Palmer, Stephen Perelgut, R. Anders Schneiderman, Susan Sim, Bob Sproull, Guy Steele, Arthur van Hoff, Jim Waldo, Greg Wilson, and Ann Wollrath provided in-depth review. Geoff Arnold, Tom Cargill, Chris Darke, Pat Finnegan, Mick Jordan, Doug Lea, Randall Murray, Roger Riggs, Jimmy Torres, Arthur van Hoff, and Frank Yellin contributed useful comments and technical information at critical junctures.
Alka Deshpande, Sharon Flank, Nassim Fotouhi, Betsy Halstead, Kee Hinck- ley, Dr. K. Kalyanasundaram, Patrick Martin, Paul Romagna, Susan Snyder, and Nicole Yankelovich collaborated to make possible the five words of non-ISO- Latin-1 text on pages 106 and 260. Jim Arnold provided research help on the proper spelling, usage, and etymology of "smoog" and "moorge." Ed Mooney helped with the document preparation. Herb and Joy Kaiser were our Croatian language consultants. Cookie Callahan, Robert E. Pierce, and Rita Tavilla pro- vided the support necessary to keep this project going at many moments when it would otherwise have stalled with a sputtering whimper.
Thanks to Kim Polese for supplying us the capsule summary of why Java is important to computer users as well as programmers.
Support and advice were provided at critical moments by Susan Jones, Bob Sproull, Jim Waldo, and Ann Wollrath. And we thank our families, who, besides their loving support, would at times drag us out to play when we should have been working, for which we are deeply grateful.
And thanks to the folks at Peet's Coffee and Tea, who kept us buzzed on the best Java on the planet.
Acknowledgments (Second Edition)
The cast of characters for this second edition is much like the first.
Series Editor Lisa Friendly continued to be doggedly supportive and attentive.
The set of reviewers was smaller, overlapping, and certainly as helpful and thorough. Overall reviews by Steve Byrne, Tom Cargill, Mary Dageforde, Tim Lindholm, and Rob Murray were critical to clarity. Brian Beck, Peter Jones, Doug Lea, Bryan O'Sullivan, Rosanna Lee, Lori Park, Mark Reinhold, Roger Riggs, Ann Wollrath, and Ken Zadek contributed focused reviews of important parts. Guy Steele's support was ongoing, and warm. Rosemary Simpson's extensive and intensive efforts to make a useful index are deeply appreciated. Carla Carlson gave critical logistic support that kept all the wheels on the tracks instead of in the ditch. All who submitted errata and suggestions from the first edition were help- ful.
For some inexplicable reason we left the friendly folks of Addison-Wesley off the original acknowledgments-luckily, most of them were present again for this edition. A merged list for both editions includes Kate Duffy, Rosa Gonzales, Mike Hendrickson, Marina Lang, Shannon Patti, Marty Rabinowitz, Sarah Weaver, and Pamela Yee. Others did much that we are blissfully unaware of, but for which we are nonetheless abidingly grateful.
Gerry Wiener provided the Tibetan word on page 260, and we also had help on this from Craig Preston and Takao Miyatani.
And Peet's Coffee and Tea continued its supporting role as purveyor to the caffeine-consuming connoisseur.
Any errors or shortcomings that remain in this book-despite the combined efforts of these myriads-are completely the responsibility of the authors.
Results! Why, man, I have gotten a lot of results. I know several thousand things that won't work.
-Thomas Edison
0201310066P04062001