This book is about the JavaTM language and programming environment. Whether you are a software developer or just someone who uses the Internet in your daily life, you’ve undoubtedly heard about Java. Its introduction was one of the most exciting developments in the history of the Web and it hasn’t slowed down much since. Java is now, arguably, the most popular programming language in the world, used by millions of developers on almost every kind of computer imaginable. 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!
This book gives you a thorough grounding in Java fundamentals and APIs. Learning Java, Third 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 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 fun 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 edition of Learning Java is actually the fifth edition—updated 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. In contrast, we’ve greatly expanded our coverage of server-side web applications and XML, which are now mature technologies.
We cover all of the important features of the latest release of Java, officially called Java 2 Standard Edition 5.0, JDK 1.5. Sun has changed the naming scheme many times over the years and this is the most confusing release ever! Sun coined the term “Java 2” to cover the major new features introduced in Java Version 1.2 and dropped the term JDK in favor of SDK. With this release Sun has skipped from Java Version 1.4 to the Java 5.0, but reprieved the term JDK and kept its numbering convention there. We’ve had no choice but to accept the term Java 5.0 into our vocabulary. You can’t fight marketing.
This release of Java is targeted at developers and has the biggest set of language changes since Java’s birth. We’ve tried to capture these new features and update every example in this book to reflect not only the current Java practice, but style.
A full chapter on generics and parameterized types (Chapter 8)
Full coverage of the new Java concurrency package, including details on executors, thread pools, read/write locks, and more (Chapter 9)
Printf-style text formatting and the new Scanner text-parsing API (Chapter 10)
New Collections classes, including Queue and Concurrent collections (Chapter 11)
Enhanced RMI (Chapter 13)
Coverage of NetBeans 4.x (Chapter 22)
Major XML enhancements, including XML schema and validation, JAXB XML binding, XPath Expressions, and XInclude document processing (Chapter 24)
Introduction to the Eclipse IDE 3.x (Appendix A) and Audience
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, networking, GUIs, and XML. As you learn about Java, you’ll also learn a powerful and practical approach to software development beginning with a deep understanding of the fundamentals of Java and its APIs.
Superficially, Java looks like C or C++, so you’ll have a tiny head start in using this book if you have some experience with one of these languages. If you do not, 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 such as C++ and Smalltalk. If you learn well from good, concise examples and personal experimentation, we think you’ll like this book.
The last part of this book branches out to discuss Java in the context of web applications, web services, and XML processing, so you should be familiar with the basic ideas behind web browsers, servers, and documents.
This book is organized roughly as follows:
Chapter 3 discusses fundamental tools for developing with Java (the compiler, the interpreter, and the JAR file package).
Chapter 8 covers generics and parameterized types in Java.
Chapter 9 covers the language’s built-in thread facilities and the Java Concurrency package, which should be of particular interest to advanced programmers.
Chapter 10 covers text processing, formatting, scanning, string utilities, and the powerful regular expressions API.
Chapter 11 covers much of the core API including utilities and collections.
Chapter 12 covers Java I/O, streams, files, and the NIO package.
Chapter 15 covers web applications using servlets, servlet filters, and WAR files, as well as web services.
Chapter 22 covers the JavaBeans? component architecture and introduces the NetBeans IDE.
Chapter 23 covers applets, the Java Plug-In, and JAR signing.
Chapter 24 covers the Java APIs for working with XML and XSLT, including XML Schema, validation, XPath, and XInclude, as well as XML binding with JAXB.
Appendix A covers using the Eclipse IDE with the examples in this book.
Appendix B describes BeanShell, a lightweight scripting language for Java that I developed.
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 explains how to use the compiler and interpreter, or Appendix A, which shows how to run the examples in the Eclipse IDE. This should get you started.
Chapter 23 covers the Applet API, including the Java plug-in for guaranteed browser compatibility and signed applets for advanced applications.
Chapter 24 covers the Java APIs for working with XML, including SAX, DOM, DTDs, XML Schema, and using XSL to render output for the Web. XML technology is becoming key to cross-platform development. Read this chapter!
Examples are available online at http://examples.oreilly.com/learnjava3/CD-ROM/.
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 software, updates, and Java releases. This is where you’ll find the JDK, which includes the compiler, the interpreter, and other tools.
You should also visit O’Reilly Media’s 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/learnjava3/, where you’ll find the source code examples for this book.
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
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
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 on the command line
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:
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() is actually static.
This book is here to help you get your job done. Generally, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Learning Java, Third Edition by Patrick Niemeyer and Jonathan Knudsen. Copyright 2005 O’Reilly Media, Inc., 0-596-00873-2.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at email@example.com.
When you see a Safari® Enabled icon on the cover of your favorite technology book, it 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 technology books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.
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-0104 (fax)|
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. Thanks to Mike Loukides, the series editor, whose patience and experience helped us get started on this journey. Thanks to Paula Ferguson and John Posner, who contributed their organizational and editing abilities at various times. And a special thanks to Deb Cameron, the tireless editor of this book, without whom the last two editions might never have been finished and certainly wouldn’t have resembled English. 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 (O’Reilly). We also borrowed several class hierarchy diagrams from David’s book. These diagrams were based on similar diagrams by Charles L. Perkins.
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: Bryan O’Connor and Brian Gottlieb. Thanks also to Josh Peck, coauthor of the original book, Exploring Java. Thanks to all those who reviewed or answered questions: David Flanagan for generics; Henry Wong for the concurrency utilities; Jim Elliott, Marc Loy, and Brian Cole for Swing; Jack Shirazi for NIO; Tim Boudreau for NetBeans; Martin Aeschlimann, Jim Farley, and John Norman for Eclipse; Ed Howland for XML; and Ian Darwin for regular expressions. (Check out Ian’s Java Cookbook [O’Reilly] for more examples.) Thanks also to Ray O’Leary, Mario Aquino, and Mark Volkmann for their reviews. And finally, thanks to my beautiful wife, Song Fang for putting up with me through all this work.