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 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 the Java programming language benefit by developing code only once, with no need to “port” their applications to every software and hardware platform.

For many, the language was known first as a tool to create applets for the World Wide Web. An applet is 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, talk with the server to do their job, but that's their business.

The Java programming language is indeed valuable for distributed network environments like the Web. However, it goes well beyond this domain to provide a powerful general-purpose programming language suitable for building a variety of applications that either do not depend on network features or want them for different reasons. The ability to execute downloaded code on remote hosts in a secure manner is a critical requirement for many organizations.

Other groups use it as a general-purpose programming language for projects in which machine independence is less important. Ease of programming and safety features help you quickly produce working code. Some common programming errors never occur because of features like garbage collection and type-safe references. 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 the built-in tools are powerful, it is a simple language in which programmers can quickly become proficient.

The Java programming language is designed for maximum portability with as few implementation dependencies as possible. An int, for example, is a 32-bit signed two's-complement integer in all implementations, irrespective of the CPU architecture on which the 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 runtime environment.

About This Book

This book teaches the Java programming language to people who are familiar with basic programming concepts. It explains the language 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 applets, graphical interfaces, Web sites, databases, components, and other specific kinds of programming tasks. For other references, see “Further Reading” on page 755.

This fourth edition provides integrated coverage of the Java programming language as provided by the Java 2 Platform Standard Edition 5.0 and specified by the Java Language Specification, Third Edition. It also covers most of the classes in the main packages (java.lang, java.util, java.io) as implemented in the J2SE Development Kit 5.0 (more commonly known as JDK 5.0, or in the older nomenclature JDK 1.5.0).

If you have already read the third edition of this book, you will find some major changes, both in the language and the book, since the 1.3 release that the third edition covered. There are new chapters on generics, enums, and annotations—the major new language features introduced in the 5.0 release—and major new sections on assertions and regular expressions. Some existing material has been restructured to accommodate other changes and to improve the general flow of the text—such as introducing the new boxing and unboxing conversions. But every single chapter has been updated in some way, whether it is a new language feature like variable argument methods; the new enhanced for loop construct; a new class such as Formatter for formatting text output; or changes to classes and methods caused by the addition of generics (such as the collections utilities and the reflection classes)—change permeates this entire fourth edition.

The Java programming language shares many features common to most programming languages in use today. The language should look familiar to C and C++ programmers because it 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 hindered by what they must unlearn as they are helped by their knowledge.

Chapter 1A Quick Tour—gives a quick overview of the language. Programmers 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 the language. The quick tour introduces some of the basic language features on which examples through the rest of the book are built.

Chapters 2 through 6 cover the object-oriented core features of the language, namely, class declarations that define components of a program, and objects manufactured according to class definitions. Chapter 2Classes and Objects—describes the basis of the language: classes. Chapter 3Extending Classes—describes how an existing class can be extended, or subclassed, to create a new class with additional data and behavior. Chapter 4Interfaces—describes how to declare interface types that are abstract descriptions of behavior that provide maximum flexibility for class designers and implementors. Chapter 5Nested Classes and Interfaces—describes how classes and interfaces can be declared inside other classes and interfaces, and the benefits that provides. Finally, Chapter 6Enumeration Types—covers the definition and use of type-safe enumeration constants.

Chapters 7 through 10 cover standard constructs common to most languages. Chapter 7Tokens, Values, and Variables—describes the tokens of the language from which statements are constructed, the types defined by the language and their allowed values, and the variables that store data in objects, arrays, or locally within methods. Chapter 8Primitives as Types—explores the relationship between the primitive types and objects of their corresponding wrapper classes, and how boxing and unboxing can transparently convert between them. Chapter 9Operators and Expressions—describes the basic operators of the language, how these operators are used to build expressions, and how expressions are evaluated. Chapter 10Control Flow—describes how control statements direct the order of statement execution.

Chapter 11Generic Types—describes generic types: how they are written and used, their power, and their limitations.

Chapter 12Exceptions and Assertions—describes the language's powerful error-handling capabilities, and the use of assertions to validate the expected behavior of code.

Chapter 13Strings and Regular Expressions—describes the built-in language and runtime support for String objects, the underlying character set support, and the powerful utilities for regular expression matching.

Chapter 14Threads—explains the language's view 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 15Annotations—describes the annotation types used to document some of the extra-linguistic properties of classes and method.

Chapter 16Reflection—describes the runtime type introspection mechanism and how you can construct and manipulate objects of unknown type dynamically at runtime.

Chapter 17Garbage Collection and Memory—talks about garbage collection, finalization, and lower-strength reference objects.

Chapter 18Packages—describes how you can group collections of classes and interfaces into separate packages.

Chapter 19Documentation Comments—shows how to write reference documentation in comments.

Chapters 20 through 24 cover the main packages. Chapter 20The I/O Package—describes the input/output system, which is based on streams. Chapter 21Collections—covers the collection or container classes such as sets and lists. Chapter 22Miscellaneous Utilities—covers the rest of the utility classes such as bit sets, formatted output, text scanning, and random number generation. Chapter 23System Programming—leads you through the system classes that provide access to features of the underlying platform. Chapter 24Internationalization and Localization—covers some of the tools used to create programs that can run in many linguistic and cultural environments.

Chapter 25Standard Packages—briefly explores the packages that are part of the standard platform, giving overviews of those packages not covered in more detail in this book.

Appendix AApplication Evolution—looks at some of the issues involved in dealing with the evolution of applications and the Java platform, and the impact this has on some of the new language features.

Appendix BUseful Tables—has tables of information that you may find useful for quick reference.

Finally, Further Reading lists works that may be interesting for further reading on complete 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 the JDK 1.5.0_02 product version. Only supported features are covered—deprecated types, methods, and fields are ignored except when unavoidable or when knowledge of the past is necessary to understand the present. We have also covered issues beyond writing 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. Development environments provide a way to automatically generate documentation (usually HTML documents) for a compiled class from its documentation comments. This documentation is normally viewed with a Web browser.

Acknowledgments (Fourth Edition)

Once again we are indebted to a group of people who took time out from their hectic schedules (and even their own books!) to give us the benefit of their experiences in making this the best edition yet. Of course, some of those people were also responsible for the huge volume of work required for us to catch up with all the new language and library features, but we won't hold that against them. Much.

On the reviewing side our thanks go first to Yoshiki Shibata. Yoshiki produced the Japanese translation of the third edition and in the process single-handedly discovered at least 85% of the errata. To get the fourth edition as errata free as possible we knew we needed Yoshiki onboard as a reviewer very early on. Yoshiki became our front-line reviewer and nothing went out for general review without his nod of approval. Not only did he provide valuable corrections and feedback on the new material, he also pointed out several areas where there had been language changes that we hadn't been aware of!

Brian Goetz also rates special thanks not only for reviewing the entire edition, but also for re-reviewing various sections that took several iterations to get right. The turnaround times for these re-reviews were very tight and we much appreciate Brian's time at that critical stage.

The remainder of the core reviewing team consisted of Beth Stearns and Kevin Davis, who were able to stay for the long haul, while Bob Withers, Herb Jellinek, Ken Louden, Rich Wardwell, and Kevin Hammond provided valuable feedback on the earlier portions of the text. Thank you all very much.

We'd also like to thank Tim Peierls for supplying the chess example used in the enum chapter; and Keith Lea and Martin Buchholz for valuable reviews of the generics material—thanks!

It will come as no surprise to most that writing the generics chapter (and the related part of the appendix) was the hardest part of this edition. Armed initially only with a draft of the third edition of the Java Language Specification, it was never going to be easy to fathom the depths of the new type system, so we brought in the big guns: Neal Gafter, Josh Bloch, Gilad Bracha, and Peter von der Ahé were all instrumental in educating us about generics, and for that we thank them. Peter's in-depth review of the generics chapter was especially valuable and warrants an additional thank you. Of course, the teachers cannot be blamed for the shortcomings of the student, so any errors or omissions in the description of generics are the sole responsibility of the authors. (We'd like to thank Phil Wadler for catching two such omissions in the generics coverage just prior to publication.)

We'd also like to thank the following technical experts for their assistance in specific areas: Doug Lea for reviewing the Java memory model material and providing assistance with concurrent collections; Brian Goetz for checking the overview of the concurrent collections (in addition to everything else); Mike “MadBot” McCloskey for the review of, and assistance with, the use of the Scanner class and the associated regular expression usage; and Jeremy Manson for trying to explain the unfathomable relationship between finalization and the memory model.

Rosemary Simpson seems to always manage to be around when we need her. It's starting to get difficult to find a creative way to say how much we appreciate her indexing, but I'm sure we'll have one by the fifth edition.

On the production side, the path to the fourth edition was a somewhat changeable one. Mike Hendrickson held the reins when the fourth edition was conceived, then handed the reins to Ann Sellers. Ann, with assistance from Ebony Haight, saw the fourth edition through its early gestation, then handed the reins to Greg Doench. Greg, with assistance from Noreen Regina, Stephane Nakib, Tyrrell Albaugh, Elizabeth Ryan, and Mary Lou Nohr saw us through to the ultimate delivery. Thank you all, and to all those behind the scenes.

And thanks as well to Kathy Kerby, Ben Littauer, and Ariana Littauer for being a valuable source of borrowed computrons. It's always nice to have neighbors from whom you can borrow a cup of cycles.

Last, but by no means least, thank you to our families for putting up with the trials and tribulations of authorship once again.

Acknowledgments (Third Edition)

The third edition required yet more reviews and work, and the helper list is equally critical. Lisa Friendly continued her attempts to keep the project in line; someday we will cooperate better. The set of reviewers included new faces and old friends, all helpful: Joshua Bloch, Joseph Bowbeer, Gilad Bracha, Keith Edwards, Joshua Engel, Rich Gillam, Peter Haggar, Cay Horstmann, Alexander Kuzmin, Doug Lea, Keith Lea, Tim Lindholm, David Mendenhall, Andrew M. Morgan, Ray Ortigas, Brian Preston, Mark Schuldenfrei, Peter Sparago, Guy Steele, Antoine Trux, and our Russian compatriots Leonid Arbouzov, Valery Shakurov, Viatcheslav Rybalov, Eugene Latkin, Dmitri Khukhro, Konstantin Anisimov, Alexei Kaigorodov, Oleg Oleinik, and Maxim Sokolnikov. Several people let us bend their ears to figure out how to approach things better: Peter Jones, Robert W. Scheifler, Susan Snyder, Guy Steele, Jimmy Torres, and Ann Wollrath. Helen Leary made the logistics work smoothly, as always.

Material support is always provided by the Addison-Wesley team: Julie DiNicola, Mike Hendrickson, and Tracy Russ.

And since the last edition, Peet's Coffee and Tea has opened up on the East Coast, so the eastern part of this writing team can enjoy it regularly. The world continues to improve apace.

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, Sue Palmer, 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 and Helen Leary gave logistic support that kept all the wheels on the tracks instead of in the ditch. Gerry Wiener provided the Tibetan word on page 550, and we also had help on this from Craig Preston and Takao Miyatani. All who submitted errata and suggestions from the first edition were helpful.

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.

The revision was additionally aided by Josh Bloch, Joe Fialli, Jimmy Torres, Benjamin Renaud, Mark Reinhold, Jen Volpe, and Ann Wollrath.

And Peet's Coffee and Tea continued its supporting role as purveyor to the caffeine-consuming connoisseur.

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 Hinckley, 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 164 and 550. 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 provided 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 the Java programming language 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.

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

Calvin and Hobbes quote (page 39) reprinted by permission of Universal Press Syndicate.

“Mail Myself to You,” (page 183) words and music by Woody Guthrie. TRO 1962 (renewed), 1963 (renewed) by Ludlow Music, Inc. New York, NY. Used by permission.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.190.182