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.
|Using This Book|
|Conventions Used in This Book|
|How to Contact Us|
|Chapter 1. Yet Another Language?|
|Section 1.1. Enter Java|
|Section 1.2. A Virtual Machine|
|Section 1.3. Java Compared with Other Languages|
|Section 1.4. Safety of Design|
|Section 1.5. Safety of Implementation|
|Section 1.6. Application and User-Level Security|
|Section 1.7. Java and the Web|
|Section 1.8. Java as a General Application Language|
|Section 1.9. A Java Road Map|
|Chapter 2. A First Application|
|Section 2.1. HelloJava|
|Section 2.2. HelloJava2: The Sequel|
|Section 2.3. HelloJava3: The Button Strikes!|
|Section 2.4. HelloJava4: Netscape's Revenge|
|Chapter 3. Tools of the Trade|
|Section 3.1. The Java Interpreter|
|Section 3.2. The Classpath|
|Section 3.3. Policy Files|
|Section 3.4. The Java Compiler|
|Section 3.5. Java Archive (JAR) Files|
|Chapter 4. The Java Language|
|Section 4.1. Text Encoding|
|Section 4.2. Comments|
|Section 4.3. Types|
|Section 4.4. Statements and Expressions|
|Section 4.5. Exceptions|
|Section 4.6. Assertions|
|Section 4.7. Arrays|
|Chapter 5. Objects in Java|
|Section 5.1. Classes|
|Section 5.2. Methods|
|Section 5.3. Object Creation|
|Section 5.4. Object Destruction|
|Chapter 6. Relationships Among Classes|
|Section 6.1. Subclassing and Inheritance|
|Section 6.2. Interfaces|
|Section 6.3. Packages and Compilation Units|
|Section 6.4. Visibility of Variables and Methods|
|Section 6.5. Arrays and the Class Hierarchy|
|Section 6.6. Inner Classes|
|Chapter 7. Working with Objects and Classes|
|Section 7.1. The Object Class|
|Section 7.2. The Class Class|
|Section 7.3. Reflection|
|Chapter 8. Threads|
|Section 8.1. Introducing Threads|
|Section 8.2. Threading an Applet|
|Section 8.3. Synchronization|
|Section 8.4. Scheduling and Priority|
|Section 8.5. Thread Groups|
|Section 8.6. Thread Performance|
|Chapter 9. Working with Text|
|Section 9.1. Other Text-Related APIs|
|Section 9.2. Strings|
|Section 9.3. Parsing and Formatting Text|
|Section 9.4. Internationalization|
|Section 9.5. The java.text Package|
|Section 9.6. Regular Expressions|
|Chapter 10. Core Utilities|
|Section 10.1. Math Utilities|
|Section 10.2. Dates|
|Section 10.3. Timers|
|Section 10.4. Collections|
|Section 10.5. Properties|
|Section 10.6. The Preferences API|
|Section 10.7. The Logging API|
|Section 10.8. Observers and Observables|
|Chapter 11. Input/Output Facilities|
|Section 11.1. Streams|
|Section 11.2. Files|
|Section 11.3. Serialization|
|Section 11.4. Data Compression|
|Section 11.5. The NIO Package|
|Chapter 12. Network Programming|
|Section 12.1. Sockets|
|Section 12.2. Datagram Sockets|
|Section 12.3. Simple Serialized Object Protocols|
|Section 12.4. Remote Method Invocation|
|Section 12.5. Scaleable I/O with NIO|
|Chapter 13. Programming for the Web|
|Section 13.1. Uniform Resource Locators (URLs)|
|Section 13.2. The URL Class|
|Section 13.3. Handlers in Practice|
|Chapter 14. Servlets and Web Applications|
|Section 14.1. Servlets: Powerful Tools|
|Section 14.2. Web Applications|
|Section 14.3. The Servlet Life Cycle|
|Section 14.4. Web Servlets|
|Section 14.5. The HelloClient Servlet|
|Section 14.6. The Servlet Response|
|Section 14.7. Servlet Parameters|
|Section 14.8. The ShowParameters Servlet|
|Section 14.9. User Session Management|
|Section 14.10. The ServletContext API|
|Section 14.11. WAR Files and Deployment|
|Section 14.12. Reloading WebApps|
|Section 14.13. Error and Index Pages|
|Section 14.14. Security and Authentication|
|Section 14.15. Servlet Filters|
|Section 14.16. Building WAR Files with Ant|
|Chapter 15. Swing|
|Section 15.1. Components|
|Section 15.2. Containers|
|Section 15.3. Events|
|Section 15.4. Event Summary|
|Section 15.5. The AWT Robot!|
|Section 15.6. Multithreading in Swing|
|Chapter 16. Using Swing Components|
|Section 16.1. Buttons and Labels|
|Section 16.2. Checkboxes and Radio Buttons|
|Section 16.3. Lists and Combo Boxes|
|Section 16.4. The Spinner|
|Section 16.5. Borders|
|Section 16.6. Menus|
|Section 16.7. The PopupMenu Class|
|Section 16.8. The JScrollPane Class|
|Section 16.9. The JSplitPane Class|
|Section 16.10. The JTabbedPane Class|
|Section 16.11. Scrollbars and Sliders|
|Section 16.12. Dialogs|
|Chapter 17. More Swing Components|
|Section 17.1. Text Components|
|Section 17.2. Focus Navigation|
|Section 17.3. Trees|
|Section 17.4. Tables|
|Section 17.5. Desktops|
|Section 17.6. Pluggable Look-and-Feel|
|Section 17.7. Creating Custom Components|
|Chapter 18. Layout Managers|
|Section 18.1. FlowLayout|
|Section 18.2. GridLayout|
|Section 18.3. BorderLayout|
|Section 18.4. BoxLayout|
|Section 18.5. CardLayout|
|Section 18.6. GridBagLayout|
|Section 18.7. Nonstandard Layout Managers|
|Section 18.8. Absolute Positioning|
|Section 18.9. SpringLayout|
|Chapter 19. Drawing with the 2D API|
|Section 19.1. The Big Picture|
|Section 19.2. The Rendering Pipeline|
|Section 19.3. A Quick Tour of Java 2D|
|Section 19.4. Filling Shapes|
|Section 19.5. Stroking Shape Outlines|
|Section 19.6. Using Fonts|
|Section 19.7. Displaying Images|
|Section 19.8. Drawing Techniques|
|Section 19.9. Printing|
|Chapter 20. Working with Images and Other Media|
|Section 20.1. ImageObserver|
|Section 20.2. MediaTracker|
|Section 20.3. Producing Image Data|
|Section 20.4. Filtering Image Data|
|Section 20.5. Simple Audio|
|Section 20.6. Java Media Framework|
|Chapter 21. JavaBeans|
|Section 21.1. What's a Bean?|
|Section 21.2. The NetBeans IDE|
|Section 21.3. Properties and Customizers|
|Section 21.4. Event Hookups and Adapters|
|Section 21.5. Binding Properties|
|Section 21.6. Building Beans|
|Section 21.7. Limitations of Visual Design|
|Section 21.8. Serialization Versus Code Generation|
|Section 21.9. Customizing with BeanInfo|
|Section 21.10. Hand-Coding with Beans|
|Section 21.11. BeanContext and BeanContextServices|
|Section 21.12. The Java Activation Framework|
|Section 21.13. Enterprise JavaBeans|
|Chapter 22. Applets|
|Section 22.1. The Politics of Applets|
|Section 22.2. The JApplet Class|
|Section 22.3. The <APPLET> Tag|
|Section 22.4. Using the Java Plug-in|
|Section 22.5. Java Web Start|
|Section 22.6. Using Digital Signatures|
|Chapter 23. XML|
|Section 23.1. A Bit of Background|
|Section 23.2. XML Basics|
|Section 23.3. SAX|
|Section 23.4. DOM|
|Section 23.5. Validating Documents|
|Section 23.6. XSL/XSLT|
|Section 23.7. Web Services|
|Appendix A. Content and Protocol Handlers|
|Section A.1. Writing a Content Handler|
|Section A.2. Writing a Protocol Handler|
|Appendix B. BeanShell: Simple Java Scripting|
|Section B.1. Running BeanShell|
|Section B.2. Java Statements and Expressions|
|Section B.3. BeanShell Commands|
|Section B.4. Scripted Methods and Objects|
|Section B.5. Changing the Classpath|
|Section B.6. Learning More ...|
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 email@example.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.