|
This new edition of Learning Java has been expanded and updated for Java 2 Standard Edition SDK 1.4. It comprehensively addresses important topics such as web applications, servlets, and XML that are increasingly driving enterprise applications. This edition provides full coverage of all Java 1.4 language features including assertions and exception chaining as well as new APIs such as regular expressions and NIO, the new I/O package. New Swing features and components are described along with updated coverage of the JavaBeans component architecture using the open source NetBeans IDE the latest information about Applets and the Java Plug-in for all major web browsers. 777 |
Copyright
Copyright © 2002, 2000 O'Reilly & Associates, Inc. All rights reserved.
Printed in the United States of America.
Published by O'Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O'Reilly & Associates books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safari.oreilly.com). For more information contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, 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 & Associates, 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 & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. The association between a Bengal tigress and cubs and the topic of learning Java is a trademark of O'Reilly & Associates, Inc.
While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
This book is about the Java™ language and programming environment. Whether you are a software developer or just someone who's been active on the Internet in the past few years, you've undoubtedly heard a lot about Java. Its introduction was one of the most exciting developments in the history of the Internet. Java became the darling of the Internet programming community as soon as the alpha version was released in 1995. Immediately, thousands of people were writing Java applets to add to their web pages. Since then Java has grown up and traveled far from its browser-based roots. Java is now, arguably, the most popular programming language in the world, used by millions. In recent years Java has surpassed languages such as C++ and Visual Basic in terms of developer demand and become the de facto language for new development—especially for web-based applications and services. Most universities are now using Java in their introductory courses, alongside the other important modern languages. Perhaps you are using this text in one of your classes right now!
What, then, is Java? Java is a new kind of programming language that was developed by Sun Microsystems to work on myriads of computing devices and to thrive in networked applications. It's widely used to create interactive web pages and web services. However, we have still seen only the start. The Java language and environment are rich enough to support new kinds of applications, such as dynamically extensible web browsers and mobile agents. Entirely new kinds of computer platforms have been and are being developed around Java; these include handheld devices and network computers that download all their software dynamically over the network. In the coming years, we'll see even more of what Java can do. Fancy web pages are fun and interesting, but they certainly aren't the end of the story. The success of Java is changing the way we think about computing in fundamental ways.
This book gives you a thorough grounding in Java fundamentals. Learning Java, Second Edition, attempts to live up to its name by mapping out the Java language, its class libraries, programming techniques, and idioms. We'll dig deep into interesting areas and at least scratch the surface of the rest. Other titles from O'Reilly & Associates pick up where we leave off and provide more comprehensive information on specific areas and applications of Java.
Whenever possible, we provide compelling, realistic and examples and avoid merely cataloging features. The examples are simple but hint at what can be done. We won't be developing the next great "killer app" in these pages, but we hope to give you a starting point for many hours of experimentation and inspired tinkering that will lead you to learn more on your own.
This book, Learning Java, is actually the fourth edition—reworked and retitled—of our original popular Exploring Java. With each edition we've taken great care not only to add new material covering additional features, but to thoroughly revise and update the existing content to synthesize the coverage and add years of real world perspective and experience to these pages.
One noticeable change in recent editions is that we've deemphasized the use of applets, reflecting their somewhat static role over the past couple of years in creating interactive web pages. And in this edition we've greatly expanded our coverage of web applications and services, which are now mature technologies. We've also included a chapter on working with XML and XSL, which are important new technologies.
We cover the most interesting features of Sun's newest release of Java, officially called Java 2 Standard Edition SDK Version 1.4 . (In the old days, it would have been called JDK for Java Development Kit; Sun now uses the term SDK for Software Development Kit.) Sun coined the term "Java 2" to cover the major new features introduced in Java Version 1.2. When it's necessary to mention versions, we'll simply refer to them as Java 1.x.
New features in Java 1.4 include important improvements for servlets and web applications, regular expressions, Swing enhancements, new language features such as assertions and chained exceptions, logging and preferences APIs and a completely new I/O facility.
Another important change in recent Java history (Version 1.2) was the ascendancy of Java Swing as the main API for graphical user interface programming. All the material in this book relating to AWT, Java's original GUI programming interface, has been recast and updated in terms of the Swing facilities.
This edition of the book has been significantly reworked to be as complete and up to date as possible. New topics in this edition include:
Language assertions and exception chaining (Chapter 4)
Regular expressions (Chapter 9)
The new preferences and logging APIs (Chapter 10)
The NIO package for scaleable I/O (Chapter 11 and Chapter 12)
Full coverage of the servlet and web applications API (Chapter 14)
Swing updates including formatted text and the new focus system (Chapters Chapter 15 through Chapter 17)
JavaBeans examples using the NetBeans IDE (Chapter 21)
Information on the Java Plug-in and applet signing (Chapter 22)
Full coverage of XML including SAX, DOM, DTDs, XSL/XSLT, and the new JavaBeans XMLEncoder (Chapter 23)
This book is for computer professionals, students, technical people, and Finnish hackers. It's for everyone who has a need for hands-on experience with the Java language with an eye toward building real applications. This book could also be considered a crash course in object-oriented programming; as you learn about Java, you'll also learn a powerful and practical approach to object-oriented software development.
Superficially, Java looks like C or C++, so you'll have a head start in using this book if you have some experience with one of these languages. If you do not however, don't worry. Don't make too much of the syntactic similarities between Java and C or C++. In many respects, Java acts like more dynamic languages such as Smalltalk and Lisp. Knowledge of another object-oriented programming language should certainly help, although you may have to change some ideas and unlearn a few habits. Java is considerably simpler than languages like C++ and Smalltalk. If you learn well from good, concise examples and personal experimentation, we think you'll like this book.
Although we encourage you to take a broad view, you would have every right to be disappointed if we ignored the Web. A substantial part of this book does discuss Java in the context of web applications, so you should be familiar with the basic ideas behind web browsers, servers, and documents.
This book is organized roughly as follows:
Chapter 1 and Chapter 2 provide a basic introduction to Java concepts and a tutorial to give you a jump start on Java programming.
Chapter 3 discusses tools for developing with Java (the compiler, the interpreter, and the JAR file package). It also covers important concepts such as embedding Java code in HTML support and object signing.
Chapter 4 through Chapter 8 describe the Java language itself. Chapter 8 covers the language's thread facilities, which should be of particular interest to advanced programmers.
Chapter 9 covers basic string utilities and the powerful Regular Expressions API.
Chapter 10 and Chapter 11 cover much of the core API. Chapter 10 describes basic utilities, and Chapter 11 covers I/O facilities.
Chapter 12 and Chapter 13 cover Java networking including sockets and NIO, URLs, and remote method invocation (RMI).
Chapter 14 covers web applications using servlets, servlet filters, and WAR files.
Chapter 15 through Chapter 20 cover the Abstract Window Toolkit (AWT) and Swing, which provide graphical user interface (GUI) and image support.
Chapter 21 covers the JavaBeans™ component architecture.
Chapter 22 covers applets, the area in which Java saw its initial success.
Chapter 23 covers the Java APIs for working with XML and XSLT.
If you're like us, you don't read books from front to back. If you're really like us, you usually don't read the Preface at all. However, on the off chance that you will see this in time, here are a few suggestions:
If you are an experienced programmer who has to learn Java in the next five minutes, you are probably looking for the examples. You might want to start by glancing at the tutorial in Chapter 2. If that doesn't float your boat, you should at least look at the information in Chapter 3, which tells how to use the compiler and interpreter, and gives the basics of a standalone Java application. This should get you started.
Chapter 12 through Chapter 14 are essential if you are interested in writing advanced networked or web-based applications. This is one of the more interesting and important parts of Java.
Chapter 15 though Chapter 21 discuss Java's graphics features and component architecture. You should read this if you are interested in writing graphical Java applications or applets.
Chapter 22 covers the Applet API, including the Java Plug-in for guaranteed browser compatibility and signed applets for advanced applications.
Chapter 23 covers the Java APIs for working with XML, including SAX, DOM, DTDs, and using XSL to render output for the Web. XML technology is becoming key to cross-platform development.
The accompanying CD-ROM provides all you need to start working with Java immediately (view CD content online at http://examples.oreilly.com/learnjava2/CD-ROM/). Open source software on the CD-ROM includes:
Java 2 Standard Edition SDK (Version 1.4.0)
NetBeans (Version 3.3.1), a visual IDE for working with JavaBeans
Ant (Version 1.4.1), a Java servlet engine from the Jakarta Project
Tomcat (Version 4.0.3), a Java servlet engine from the Jakarta Project
BeanShell (Version 1.2), a simple Java scripting language
There are many online sources for information about Java. Sun Microsystems's official web site for Java topics is http://java.sun.com; look here for the latest news, updates, and Java releases. This is where you'll find the Java SDK, which includes the compiler, the interpreter, and other tools (the SDK is also on the CD-ROM that comes with this book; view CD content online at http://examples.oreilly.com/learnjava2/CD-ROM/).
You should also visit O'Reilly & Associates' Java site at http://java.oreilly.com. There you'll find information about other O'Reilly Java books, and a pointer to the home page for Learning Java, http://www.oreilly.com/catalog/learnjava2/, where you'll find the source code examples for this book.
The comp.lang.java newsgroup can be a good source of information and announcements, and a place to ask intelligent questions.
The font conventions used in this book are quite simple.
Italic is used for:
Unix pathnames, filenames, and program names
Internet addresses, such as domain names and URLs
New terms where they are defined
GUI buttons and menus, and threads
Program names, compilers, interpreters, utilities, and commands
Constant width is used for:
Anything that might appear in a Java program, including method names, variable names, and class names
Command lines and options that should be typed verbatim on the screen
Tags that might appear in an HTML or XML document
Keywords, objects, and environment variables
Constant width bold is used for:
Text that is typed by the user in code examples
Constant width italic is used for:
Replaceable items in code
|
|
In the main body of text, we always use a pair of empty parentheses after a method name to distinguish methods from variables and other creatures.
In the Java source listings, we follow the coding conventions most frequently used in the Java community. Class names begin with capital letters; variable and method names begin with lowercase. All the letters in the names of constants are capitalized. We don't use underscores to separate words in a long name; following common practice, we capitalize individual words (after the first) and run the words together. For example: thisIsAVariable, thisIsAMethod(), ThisIsAClass, and THISISACONSTANT. Also, note that we differentiate between static and nonstatic methods when we refer to them. Unlike some books, we never write Foo.bar() to mean the bar() method of Foo unless bar() is actually static.
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, or any additional information. You can access this page at:
To comment or ask technical questions about this book, send email to:
For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at:
Many people have contributed to putting this book together, both in its Exploring Java incarnation and in its current form as Learning Java. Foremost we would like to thank Tim O'Reilly for giving us the opportunity to write this book. Special thanks to Mike Loukides, the series editor, whose endless patience and experience got us through the difficult parts. Paula Ferguson and John Posner contributed their organizational and editing abilities to get the material into final form. We could not have asked for a more skillful or responsive team of people with whom to work.
Speaking of borrowings, the original version of the glossary came from David Flanagan's book, Java in a Nutshell. We also borrowed the class hierarchy diagrams from David's book. These diagrams were based on similar diagrams by Charles L. Perkins. His original diagrams are available at http://rendezvous.com/java/.
Thanks also to Marc Wallace and Steven Burkett for reading the original work in progress and for the support of our friends at Washington University. A big thanks to Deb Cameron who edited this edition of the book and kept me from getting too far behind schedule (thanks for all the hard work Deb!). Thanks to all those who reviewed or answered questions for the latest edition: Jim Elliott and Brian Cole for Swing, Jack Shirazi for NIO, Tim Boudreau for NetBeans, Ed Howland for XML, and Ian Darwin for regular expressions. (Check out Ian's O'Reilly Java Cookbook for more examples.) Thanks also to Ray O'Leary, Mario Aquino, and Mark Volkmann for their reviews. Finally, special thanks to Song Fang for putting up with me through all this work.