Introduction▲
"He gave man speech, and speech created thought, Which is the measure of the Universe"-Prometheus Unbound, Shelley
Human beings ... are very much at the mercy of the particular language which has become the medium of expression for their society. It is quite an illusion to imagine that one adjusts to reality essentially without the use of language and that language is merely an incidental means of solving specific problems of communication and reflection. The fact of the matter is that the "real world" is to a large extent unconsciously built up on the language habits of the group.
The Status Of Linguistics As A Science, 1929, Edward Sapir
Like any human language, Java provides a way to express concepts. If successful, this medium of expression will be significantly easier and more flexible than the alternatives as problems grow larger and more complex.
You can't look at Java as just a collection of features-some of the features make no sense in isolation. You can use the sum of the parts only if you are thinking about design, not simply coding. And to understand Java in this way, you must understand the problems with it and with programming in general. This book discusses programming problems, why they are problems, and the approach Java has taken to solve them. Thus, the set of features that I explain in each chapter are based on the way I see a particular type of problem being solved with the language. In this way I hope to move you, a little at a time, to the point where the Java mindset becomes your native tongue.
Throughout, I'll be taking the attitude that you want to build a model in your head that allows you to develop a deep understanding of the language; if you encounter a puzzle, you'll be able to feed it to your model and deduce the answer.
Prerequisites▲
This book assumes that you have some programming familiarity: you understand that a program is a collection of statements, the idea of a subroutine/function/macro, control statements such as "if" and looping constructs such as "while," etc. However, you might have learned this in many places, such as programming with a macro language or working with a tool like Perl. As long as you've programmed to the point where you feel comfortable with the basic ideas of programming, you'll be able to work through this book. Of course, the book will be easier for the C programmers and more so for the C++ programmers, so don't count yourself out if you're not experienced with those languages-but come willing to work hard (also, the multimedia CD that accompanies this book will bring you up to speed in the fundamentals necessary to learn Java). However, I will be introducing the concepts of object-oriented programming (OOP) and Java's basic control mechanisms.
Although references will often be made to C and C++ language features, these are not intended to be insider comments, but instead to help all programmers put Java in perspective with those languages, from which, after all, Java is descended. I will attempt to make these references simple and to explain anything that I think a non- C/C++ programmer would not be familiar with.
Learning Java▲
At about the same time that my first book Using C++ (Osborne/McGraw-Hill, 1989) came out, I began teaching that language. Teaching programming languages has become my profession; I've seen nodding heads, blank faces, and puzzled expressions in audiences all over the world since 1987. As I began giving in-house training with smaller groups of people, I discovered something during the exercises. Even those people who were smiling and nodding were confused about many issues. I found out, by creating and chairing the C++ track at the Software Development Conference for a number of years (and later creating and chairing the Java track), that I and other speakers tended to give the typical audience too many topics too quickly. So eventually, through both variety in the audience level and the way that I presented the material, I would end up losing some portion of the audience. Maybe it's asking too much, but because I am one of those people resistant to traditional lecturing (and for most people, I believe, such resistance results from boredom), I wanted to try to keep everyone up to speed.
For a time, I was creating a number of different presentations in fairly short order. Thus, I ended up learning by experiment and iteration (a technique that also works well in Java program design). Eventually, I developed a course using everything I had learned from my teaching experience. It tackles the learning problem in discrete, easy-to-digest steps, and in a hands-on seminar (the ideal learning situation), there are exercises following each of the short lessons. My company MindView, Inc. now gives this as the public and in-house Thinking in Java seminar; this is our main introductory seminar that provides the foundation for our more advanced seminars. You can find details at www.MindView.net. (The introductory seminar is also available as the Hands-On Java CD ROM. Information is available at the same Web site.)
The feedback that I get from each seminar helps me change and refocus the material until I think it works well as a teaching medium. But this book isn't just seminar notes; I tried to pack as much information as I could within these pages, and structured it to draw you through onto the next subject. More than anything, the book is designed to serve the solitary reader who is struggling with a new programming language.
Goals▲
Like my previous book Thinking in C++, this book has come to be structured around the process of teaching the language. In particular, my motivation is to create something that provides me with a way to teach the language in my own seminars. When I think of a chapter in the book, I think in terms of what makes a good lesson during a seminar. My goal is to get bite-sized pieces that can be taught in a reasonable amount of time, followed by exercises that are feasible to accomplish in a classroom situation.
My goals in this book are to:
- Present the material one simple step at a time so that you can easily digest each concept before moving on.
- Use examples that are as simple and short as possible. This sometimes prevents me from tackling "real world" problems, but I've found that beginners are usually happier when they can understand every detail of an example rather than being impressed by the scope of the problem it solves. Also, there's a severe limit to the amount of code that can be absorbed in a classroom situation. For this I will no doubt receive criticism for using "toy examples," but I'm willing to accept that in favor of producing something pedagogically useful.
- Carefully sequence the presentation of features so that you're exposed to a topic before you see it in use. Of course, this isn't always possible; in those situations, a brief introductory description is given.
- Give you what I think is important for you to understand about the language, rather than everything I know. I believe there is an information importance hierarchy, and that there are some facts that 95 percent of programmers will never need to know-details that just confuse people and increase their perception of the complexity of the language. To take an example from C, if you memorize the operator precedence table (I never did), you can write clever code. But if you need to think about it, it will also confuse the reader/maintainer of that code. So forget about precedence, and use parentheses when things aren't clear.
- Keep each section focused enough so that the lecture time-and the time between exercise periods-is small. Not only does this keep the audience's minds more active and involved during a hands-on seminar, but it gives the reader a greater sense of accomplishment.
- Provide you with a solid foundation so that you can understand the issues well enough to move on to more difficult coursework and books.
JDK HTML documentation▲
The Java language and libraries from Sun Microsystems (a free download from java.sun.com) come with documentation in electronic form, readable using a Web browser, and virtually every third-party implementation of Java has this or an equivalent documentation system. Almost all the books published on Java have duplicated this documentation. So you either already have it or you can download it, and unless necessary, this book will not repeat that documentation, because it's usually much faster if you find the class descriptions with your Web browser than if you look them up in a book (and the on-line documentation is probably more up-to-date). You'll simply be referred to "the JDK documentation." This book will provide extra descriptions of the classes only when it's necessary to supplement that documentation so you can understand a particular example.
Chapters▲
This book was designed with one thing in mind: the way people learn the Java language. Seminar audience feedback helped me understand the difficult parts that needed illumination. In the areas where I got ambitious and included too many features all at once, I came to know-through the process of presenting the material-that if you include a lot of new features, you need to explain them all, and this easily compounds the student's confusion. As a result, I've taken a great deal of trouble to introduce the features as few at a time as possible.
The goal, then, is for each chapter to teach a single feature, or a small group of associated features, without relying on features that haven't been introduced yet. That way you can digest each piece in the context of your current knowledge before moving on.
Here is a brief description of the chapters contained in the book, that correspond to lectures and exercise periods in the Thinking in Java seminar.
Chapter 1: Introduction to Objects
(Corresponding lecture on the CD ROM). This chapter is an overview of what object-oriented programming is all about, including the answer to the basic question "What is an object?" It looks at interface versus implementation, abstraction and encapsulation, messages and methods, inheritance and composition, and the subtle concept of polymorphism. You'll also get an overview of issues of object creation such as constructors, where the objects live, where to put them once they're created, and the magical garbage collector that cleans up the objects that are no longer needed. Other issues will be introduced, including error handling with exceptions, multithreading for responsive user interfaces, and networking and the Internet. You'll learn what makes Java special and why it's been so successful.
Chapter 2: Everything is an Object
(Corresponding lecture on the CD ROM). This chapter moves you to the point where you can write your first Java program. It begins with an overview of the essentials: the concept of a reference to an object; how to create an object; an introduction to primitive types and arrays; scoping and the way objects are destroyed by the garbage collector; how everything in Java is a new data type (class); the basics of creating your own classes; methods, arguments, and return values; name visibility and using components from other libraries; the static keyword; and comments and embedded documentation.
Chapter 3: Controlling Program Flow
(Corresponding set of lectures on the CD ROM: Thinking in C). This chapter begins with all of the operators that come to Java from C and C++. In addition, you'll discover common operator pitfalls, casting, promotion, and precedence. This is followed by the basic control-flow and selection operations that you get with virtually any programming language: choice with if-else, looping with for and while, quitting a loop with break and continue as well as Java's labeled break and labeled continue (which account for the "missing goto" in Java), and selection using switch. Although much of this material has common threads with C and C++ code, there are some differences.
Chapter 4: Initialization & Cleanup
(Corresponding lecture on the CD ROM). This chapter begins by introducing the constructor, which guarantees proper initialization. The definition of the constructor leads into the concept of method overloading (since you might want several constructors). This is followed by a discussion of the process of cleanup, which is not always as simple as it seems. Normally, you just drop an object when you're done with it, and the garbage collector eventually comes along and releases the memory. This portion explores the garbage collector and some of its idiosyncrasies. The chapter concludes with a closer look at how things are initialized: automatic member initialization, specifying member initialization, the order of initialization, static initialization, and array initialization.
Chapter 5: Hiding the Implementation
(Corresponding lecture on the CD ROM). This chapter covers the way that code is packaged together, and why some parts of a library are exposed while other parts are hidden. It begins by looking at the package and import keywords, that perform file-level packaging and allow you to build libraries of classes. It then examines the subject of directory paths and file names. The remainder of the chapter looks at the public, private, and protected keywords, the concept of package access, and what the different levels of access control mean when used in various contexts.
Chapter 6: Reusing Classes
(Corresponding lecture on the CD ROM). The simplest way to reuse a class is to embed an object inside your new class with composition. However, composition isn't the only way to make new classes from existing ones. The concept of inheritance is standard in virtually all OOP languages. It's a way to take an existing class and add to its functionality (as well as change it-the subject of Chapter 7). Inheritance is often a way to reuse code by leaving the "base class" the same and just patching things here and there to produce what you want. In this chapter you'll learn how composition and inheritance reuse code in Java, and how to apply them.
Chapter 7: Polymorphism
(Corresponding lecture on the CD ROM). On your own, you might take nine months to discover and understand polymorphism, a cornerstone of OOP. Through small, simple examples, you'll see how to create a family of types with inheritance and manipulate objects in that family through their common base class. Java's polymorphism allows you to treat all objects in this family generically, which means that the bulk of your code doesn't rely on specific type information. This makes your code more flexible, so building programs and code maintenance is easier and cheaper.
Chapter 8: Interfaces & Inner Classes
Java provides special tool to set up design and reuse relationships: the interface, which is a pure abstraction of the interface of an object. The interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation on C++'s "multiple inheritance" by creating a class that can be upcast to more than one base type.
At first, inner classes look like a simple code-hiding mechanism; you place classes inside other classes. You'll learn, however, that the inner class does more than that; it knows about and can communicate with the surrounding class. The kind of code you can write with inner classes is more elegant and clear. However, it is a new concept to most, and it takes some time to become comfortable with design using inner classes.
Chapter 9: Error Handling with Exceptions
The basic philosophy of Java is that badly-formed code will not be run. As much as possible, the compiler catches problems, but sometimes a problem-either a programmer error or a natural error condition that occurs as part of the normal execution of the program-can be detected and dealt with only at run time. Java has exception handling to deal with any problems that arise while the program is running. This chapter examines how the keywords try, catch, throw, throws, and finally work in Java, when you should throw exceptions, and what to do when you catch them. In addition, you'll see Java's standard exceptions, how to create your own, what happens with exceptions in constructors, and how exception handlers are discovered during an exception.
Chapter 10: Detecting Types
Java run-time type identification (RTTI) lets you find the exact type of an object when you have a reference to only the base type. Normally, you'll want to intentionally ignore the exact type and let Java's dynamic binding mechanism (polymorphism) implement the correct behavior for that type. But occasionally, it is very helpful to know the exact type of an object for which you have only a base reference. Often this information allows you to perform a special-case operation more efficiently. This chapter also introduces the Java reflection mechanism. You'll learn what RTTI and reflection are for and how to use them, and also how to get rid of RTTI when it doesn't belong there.
Chapter 11: Collections of Objects
It's a fairly simple program that has only a fixed quantity of objects with known lifetimes. In general, your programs will always be creating new objects at a variety of times that will be known only while the program is running. In addition, you won't know until run time the quantity or even the exact type of the objects you need. To solve the general programming problem, you need to create any number of objects anywhere, at any time. This chapter explores in depth the collections library that Java supplies to hold objects while you're working with them: the simple arrays and more sophisticated containers (data structures) such as ArrayList and HashMap.
Chapter 12: The Java I/O System
Theoretically, you can divide any program into three parts: input, process, and output. This implies that I/O (input/output) is an important part of the equation. In this chapter you'll learn about the different classes that Java provides for reading and writing files, blocks of memory, and the console. The evolution of the Java I/O framework and the JDK 1.4 "new" I/O (nio) will be examined. In addition, this chapter shows how you can take an object, "stream" it (so that it can be placed on disk or sent across a network), and then reconstruct it, which is handled for you with Java's object serialization. Java's compression libraries, which are used in the Java ARchive (JAR) file format, are examined. Finally, the new preferences application program interface (API) and regular expressions are explained.
Chapter 13: Concurrency
Java provides a built-in facility to support multiple concurrent subtasks, called threads, running within a single program. (Unless you have multiple processors on your machine, this is only the appearance of multiple subtasks.) Although these can be used anywhere, threads are most apparent when trying to create a responsive user interface so, for example, a user isn't prevented from pressing a button or entering data while some processing is going on. This chapter gives you a solid grounding in the fundamentals of concurrent programming.
Chapter 14: Creating Windows and Applets
Java comes with the Swing GUI library, which is a set of classes that handle windowing in a portable fashion. These windowed programs can either be World Wide Web applets or standalone applications. This chapter is an introduction to the creation of programs using Swing. Applet signing and Java Web Start are demonstrated. Also, the important JavaBeans technology is introduced, which is fundamental for the creation of Rapid Application Development (RAD) program-building tools.
Chapter 15: Discovering Problems
Language-checking mechanisms can take us only so far in our quest to develop a correctly-working program. This chapter presents tools to solve the problems that the compiler doesn't. One of the biggest steps forward is the incorporation of automated unit testing. For this book, a custom testing system was developed to ensure the correctness of the program output, but the defacto standard JUnit testing system is also introduced. Automatic building is implemented with the open-source standard Ant tool, and for teamwork, the basics of CVS are explained. For problem reporting at run time, this chapter introduces the Java assertion mechanism (shown here used with Design by Contract), the logging API, debuggers, profilers, and even doclets (which can help discover problems in source code).
Chapter 16: Analysis & Design
The object-oriented paradigm is a new and different way of thinking about programming, and many people have trouble at first knowing how to approach an OOP project. Once you understand the concept of an object, and as you learn to think more in an object-oriented style, you can begin to create "good" designs that take advantage of all the benefits that OOP has to offer. This chapter introduces the ideas of analysis, design, and some ways to approach the problems of developing good object-oriented programs in a reasonable amount of time. Topics include Unified Modeling Language (UML) diagrams and associated methodology, use cases, Class-Responsibility-Collaboration (CRC) cards, iterative development, Extreme Programming (XP), ways to develop and evolve reusable code, and strategies for transition to object-oriented programming.
Appendix A: Passing & Returning Objects
Since the only way you talk to objects in Java is through references, the concepts of passing an object into a method and returning an object from a method have some interesting consequences. This appendix explains what you need to know to manage objects when you're moving in and out of methods, and also shows the String class, which uses a different approach to the problem.
Appendix B: Java Programming Guidelines
This appendix contains suggestions that I have discovered and collected over the years to help guide you while performing low-level program design and writing code.
Appendix C: Supplements
Descriptions of additional learning material available from MindView:
1. The CD ROM that's in the back of this book, which contains the Foundations for Java seminar-on-CD,
to prepare you for this book.
2. The Hands-On Java CD ROM, 3rd Edition, available at www.MindView.net.
A seminar-on-CD that's based on the material in this book.
3. The Thinking in Java Seminar. The MindView, Inc., main introductory seminar based on the material in this book.
Schedule and registration pages can be found at www.MindView.net.
4. Thinking in Enterprise Java, a book that covers more advanced Java topics appropriate to enterprise programming.
Available at www.MindView.net.
5. The J2EE Seminar.
Introduces you to the practical development of real-world, Web-enabled, distributed applications with Java.
See www.MindView.net.
6. Designing Objects & Systems Seminar.
Object-oriented analysis, design, and implementation techniques. See www.MindView.net.
7. Thinking in Patterns (with Java),
which covers more advanced Java topics on design patterns and problem-solving techniques. Available at www.MindView.net.
8. Thinking in Patterns Seminar. A live seminar based on the above book.
Schedule and registration pages can be found at www.MindView.net.
9. Design Consulting and Reviews. Assistance to help keep your project in good shape.
Appendix D: Resources
A list of some of the Java books I've found particularly useful.
Exercises▲
I've discovered that simple exercises are exceptionally useful to complete a student's understanding during a seminar, so you'll find a set at the end of each chapter.
Most exercises are designed to be easy enough that they can be finished in a reasonable amount of time in a classroom situation while the instructor observes, making sure that all the students are absorbing the material. Some are more challenging, but none present major challenges. (Presumably, you'll find those on your own-or more likely, they'll find you).
Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from www.BruceEckel.com.
The CD ROM▲
Another bonus with this edition is the CD ROM that is packaged in the back of the book. I've resisted putting CDs in the back of my books in the past because I felt the extra charge for a few kilobytes of source code on an enormous CD was not justified, preferring instead to allow people to download such things from my Web site. However, you'll soon see that this CD is different.
The CD doesn't contain the source code from the book, but instead has a link to the code at www.MindView.net (you don't need the link on the CD to get to the source code. You can just go to the site and find it that way). There are two reasons for this: the code was not complete at the time the CD had to be sent to the printer, and this approach allows the code to evolve and be corrected as any issues arise.
Because the book has changed significantly over the three editions, the CD contains the first and second editions of the book in HTML format, including sections that for aforementioned reasons were removed from later editions but which may in some cases be useful to you. In addition, you can download the HTML version of the current (third edition) book from www.MindView.net, and this will include corrections as they are discovered and fixed. One benefit of the HTML version is that the index is hyperlinked so navigating it is much simpler.
The bulk of the 400+ Megabytes of the CD, however, is a full multimedia course called Foundations for Java. This includes the Thinking in C seminar that gives you an introduction to the C syntax, operators, and functions that Java syntax is based upon. In addition, it includes the first seven lectures from the second edition of the Hands-On Java seminar-on-CD that I created and narrate. Although historically the entire Hands-On Java CD is only available for sale separately (this is also the case with the third edition of the Hands-On Java CD that may be available when you read this-see www.MindView.net), I decided to include the first seven lectures from the second edition because they will not have changed too much in relationship to the third edition of the book, so it will not only provide you (along with Thinking in C)with a foundation for this book, but in addition I hope it will give you a taste for the quality and value of the Hands-On Java CD, 3rd Edition.
I originally commissioned Chuck Allison to create the Thinking in C part of this seminar-on-CD ROM as a standalone product, but decided to include it with the second editions of both Thinking in C++ and Thinking in Java because of the consistent experience of having people come to seminars without an adequate background in basic C syntax. The thinking apparently goes "I'm a smart programmer and I don't want to learn C, but rather C++ or Java, so I'll just skip C and go directly to C++/Java." After arriving at the seminar, it slowly dawns on folks that the prerequisite of understanding C syntax is there for a very good reason. By including the CD ROM with the book, we can ensure that everyone attends a seminar with adequate preparation.
The CD also allows the book to appeal to a wider audience. Even though Chapter 3 (Controlling Program Flow) does cover the fundamentals of the parts of Java that come from C, the CD is a gentler introduction, and assumes even less about the student's programming background than does the book. And being walked through the material in the first seven chapters via the corresponding lectures in the second edition of the Hands-On Java CD should help you get an even better foothold into Java. It is my hope that by including the CD, more people will be able to be brought into the fold of Java programming. The Hands-On Java CD ROM 3rd Edition is available only by ordering directly from the Web site www.BruceEckel.com.
Source code▲
All the source code for this book is available as copyrighted freeware, distributed as a single package, by visiting the Web site www.BruceEckel.com. To make sure that you get the most current version, this is the official site for distribution of the code and the electronic version of the book. You can find mirrored versions of the electronic book and the code on other sites (some of these sites are found at www.BruceEckel.com), but you should check the official site to ensure that the mirrored version is actually the most recent edition. You may distribute the code in classroom and other educational situations.
The primary goal of the copyright is to ensure that the source of the code is properly cited, and to prevent you from republishing the code in print media without permission. (As long as the source is cited, using examples from the book in most media is generally not a problem.)
In each source code file you will find a reference to the following copyright notice:
This computer source code is Copyright ©2003 MindView, Inc.
All Rights Reserved.
Permission to use, copy, modify, and distribute <b>this</b>
computer source code (Source Code) and its documentation
without fee and without a written agreement <b>for</b> the
purposes set forth below is hereby granted, provided that
the above copyright notice, <b>this</b> paragraph and the
following five numbered paragraphs appear in all copies.
1. Permission is granted to compile the Source Code and to
include the compiled code, in executable format only, in
personal and commercial software programs.
2. Permission is granted to use the Source Code without
modification in classroom situations, including in
presentation materials, provided that the book "Thinking in
Java" is cited as the origin.
3. Permission to incorporate the Source Code into printed
media may be obtained by contacting
MindView, Inc. 5343 Valle Vista La Mesa, California 91941
Wayne@MindView.net
4. The Source Code and documentation are copyrighted by
MindView, Inc. The Source code is provided without express
or implied warranty of any kind, including any implied
warranty of merchantability, fitness <b>for</b> a particular
purpose or non-infringement. MindView, Inc. does not
warrant that the operation of any program that includes the
Source Code will be uninterrupted or error- free. MindView,
Inc. makes no representation about the suitability of the
Source Code or of any software that includes the Source
Code <b>for</b> any purpose. The entire risk as to the quality
and performance of any program that includes the Source
code is with the user of the Source Code. The user
understands that the Source Code was developed <b>for</b> research
and instructional purposes and is advised not to rely
exclusively <b>for</b> any reason on the Source Code or any
program that includes the Source Code. Should the Source
Code or any resulting software prove defective, the user
assumes the cost of all necessary servicing, repair, or
correction.
5. IN NO EVENT SHALL MINDVIEW, INC., OR ITS PUBLISHER BE
LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF
BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR
PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE
CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY
TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW, INC., OR
ITS PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. MINDVIEW, INC. SPECIFICALLY DISCLAIMS ANY
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED
HEREUNDER IS ON AN <b>"AS IS"</b> BASIS, WITHOUT ANY ACCOMPANYING
SERVICES FROM MINDVIEW, INC., AND MINDVIEW, INC. HAS NO
OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
Please note that MindView, Inc. maintains a web site which
is the sole distribution point <b>for</b> electronic copies of the
Source Code, http:<b><i>//www.BruceEckel.com (and official mirror</i></b>
sites), where it is freely available under the terms stated
above.
If you think you've found an error in the Source Code,
please submit a correction using the URL marked <i>"feedback"</i>
in the electronic version of the book, nearest the error
you've found.
You may use the code in your projects and in the classroom (including your presentation materials) as long as the copyright notice that appears in each source file is retained.
Coding standards▲
In the text of this book, identifiers (method, variable, and class names) are set in bold. Most keywords are also set in bold, except for those keywords that are used so much that the bolding can become tedious, such as "class."
I use a particular coding style for the examples in this book. This style follows the style that Sun itself uses in virtually all of the code you will find at its site (see java.sun.com/docs/codeconv/index.html), and seems to be supported by most Java development environments. If you've read my other works, you'll also notice that Sun's coding style coincides with mine-this pleases me, although I had nothing to do with it. The subject of formatting style is good for hours of hot debate, so I'll just say I'm not trying to dictate correct style via my examples; I have my own motivation for using the style that I do. Because Java is a free-form programming language, you can continue to use whatever style you're comfortable with.
The programs in this book are files that are included by the word processor in the text, directly from compiled files. Thus, the code files printed in the book should all work without compiler errors. The errors that should cause compile-time error messages are commented out with the comment //! so they can be easily discovered and tested using automatic means. Errors discovered and reported to the author will appear first in the distributed source code and later in updates of the book (which will also appear on the Web site www.BruceEckel.com).
Java versions▲
I generally rely on the Sun implementation of Java as a reference when determining whether behavior is correct.
This book focuses on and is tested with Java 2, JDK 1.4. If you need to learn about earlier releases of the language that are not covered in this edition, the first edition and second editions of the book are freely downloadable at www.BruceEckel.com and are also contained on the CD that is bound in with this book.
Errors▲
No matter how many tricks a writer uses to detect errors, some always creep in and these often leap off the page for a fresh reader.
Because the feedback provided by astute readers has been so valuable to me, I've developed several versions of a feedback system called BackTalk (conceived with the aid of Bill Venners, and implemented with the help of numerous others, using several different technologies). In the electronic version of this book, freely downloadable from www.BruceEckel.com,each paragraph in the text has its own unique URL that will produce an email that will register your comment in the BackTalk system, for that particular paragraph. This way it's very easy to track and update corrections. If you discover anything you believe to be an error, please use the BackTalk system to submit the error along with your suggested correction. Your help is appreciated.
Note on the cover design▲
The cover of Thinking in Java is inspired by the American Arts & Crafts Movement that began near the turn of the century and reached its zenith between 1900 and 1920. It began in England as a reaction to both the machine production of the Industrial Revolution and the highly ornamental style of the Victorian era. Arts & Crafts emphasized spare design, the forms of nature as seen in the art nouveau movement, hand-crafting, and the importance of the individual craftsperson, and yet it did not eschew the use of modern tools. There are many echoes with the situation we have today: the turn of the century, the evolution from the raw beginnings of the computer revolution to something more refined and meaningful to individual persons, and the emphasis on software craftsmanship rather than just manufacturing code.
I see Java in this same way: as an attempt to elevate the programmer away from an operating-system mechanic and toward being a "software craftsman."
Both the author and the book/cover designer (who have been friends since childhood) find inspiration in this movement, and both own furniture, lamps, and other pieces that are either original or inspired by this period.
The other theme in this cover suggests a collection box that a naturalist might use to display the insect specimens that he or she has preserved. These insects are objects that are placed within the box objects. The box objects are themselves placed within the "cover object," which illustrates the fundamental concept of aggregation in object-oriented programming. Of course, a programmer cannot help but make the association with "bugs," and here the bugs have been captured and presumably killed in a specimen jar, and finally confined within a small display box, as if to imply Java's ability to find, display, and subdue bugs (which is truly one of its most powerful attributes).
Acknowledgements▲
First, thanks to associates who have worked with me to give seminars, provide consulting, and develop teaching projects: Andrea Provaglio, Dave Bartlett, Bill Venners, Chuck Allison, Jeremy Meyer, and Larry O'Brien. I appreciate your patience as I continue to try to develop the best model for independent folks like us to work together.
Recently, no doubt because of the Internet, I have become associated with a surprisingly large number of people who assist me in my endeavors, usually working from their own home offices. In the past, I would have had to pay for a pretty big office space to accommodate all these folks, but because of the net and Fedex and occasionally the telephone, I'm able to benefit from their help without the extra costs. In my attempts to learn to better "play well with others," you have all been very helpful, and I hope to continue learning how to make my own work better through the efforts of others. Paula Steuer has been invaluable in taking over my haphazard business practices and making them sane (thanks for prodding me when I don't want to do something, Paula). Jonathan Wilcox, Esq., has sifted through my corporate structure and turned over every possible rock that might hide scorpions, and frog-marched us through the process of putting everything straight, legally. Thanks for your care and persistence. Sharlynn Cobaugh (who discovered Paula) has made herself an expert in sound processing and an essential part of creating the multimedia training CD ROMs, as well as tackling other problems. Thanks for your perseverance when faced with intractable computer problems. Evan Cofsky (Evan@TheUnixMan.com) has become an essential part of my development process, taking to the Python programming language like a duck (Hmm. Such a mixed metaphor could produce a fat Python) and solving all kinds of difficult problems, including the (final?) re-architecting of BackTalk into an email-driven XML database. The folks at Amaio in Prague have helped me out with several projects. Daniel Will-Harris was the original work-by-Internet inspiration, and he is of course fundamental to all my design solutions.
For this project, I took another step that had been fermenting in the back of my mind for awhile. For the summer of 2002, I created an internship program in Crested Butte, Colorado, initially looking for two interns and ending up with 5 (two volunteers). Not only did they contribute to the book but they helped keep me focused on the project. Thanks to JJ Badri, Ben Hindman, Mihajlo Jovanovic, Mark Welsh. Chintan Thakker was able to stay for a second internship through the end of the book process and beyond, and since I had to rent the intern condo in Mount Crested Butte anyway, we advertised for volunteers and got Mike Levin, Mike Shea, and Ian Phillips, who all made contributions. Someday I may do another internship program; visit www.MindView.net for news.
Thanks to the Doyle Street Cohousing Community for putting up with me for the two years that it took me to write the first edition of this book (and for putting up with me at all). Thanks very much to Kevin and Sonda Donovan for subletting their great place in gorgeous Crested Butte, Colorado for the summer while I worked on the first edition of the book (and to Kevin for all the great remodeling on my place in CB). Also thanks to the friendly residents of Crested Butte and the Rocky Mountain Biological Laboratory who make me feel so welcome. My yoga teachers in CB, Maria and Brenda, were instrumental in keeping me sane during the development of the 3rd edition.
Camp4 Coffee in Crested Butte, Colorado has become the standard hangout when teachers have come up to give seminars, and during seminar breaks it is the best and cheapest catering I've ever had. Thanks to my buddy Al Smith for creating it and making it such a great place, and for being such an interesting and entertaining part of the Crested Butte experience.
Thanks to Claudette Moore at Moore Literary Agency for her tremendous patience and perseverance in getting me exactly what I wanted. Thanks to Paul Petralia at Prentice Hall for continuing to give me what I want, and for going out of his way to make things run smoothly for me (and for putting up with all my special requirements).
My first two books were published with Jeff Pepper as editor at Osborne/McGraw-Hill. Jeff appeared at the right place and the right time at Prentice Hall to lay the original groundwork for these books, before passing the responsibility on to Paul. Thanks, Jeff.
Thanks to Rolf André Klaedtke (Switzerland); Martin Vlcek, Vlada & Pavel Lahoda, (Prague); and Marco Cantu (Italy) for hosting me on my first self-organized European seminar tour.
Thanks to Gen Kiyooka and his company Digigami, who graciously provided my Web server for the first several years of my presence on the Web. This was an invaluable learning aid.
Special thanks to Larry and Tina O'Brien, who helped turn my seminar into the first edition of the Hands-On Java CD ROM. (You can find out more at www.BruceEckel.com.)
Certain open-source tools have proved invaluable during my development process and I am very grateful to the creators every time I use these. Cygwin (http://www.cygwin.com) has solved innumerable problems for me that Windows can't/won't and I become more attached to it each day (if I only had this 15 years ago when my brain was still hard-wired with Gnu Emacs). CVS and Ant have become essential to my Java development process and I couldn't go back now. I've even become fond of JUnit (http://www.junit.org) now that they've actually made it "the simplest thing that could possibly work." IBM's Eclipse (http://www.eclipse.org) is a truly wonderful contribution to the development community, and I expect to see great things from it as it continues to evolve (how did IBM become hip? I must have missed a memo). Linux was used daily during the development process, especially by the interns. And of course, if I don't say it enough everywhere else, I use Python (www.Python.org) constantly to solve problems, the brainchild of my buddy Guido Van Rossum and the goofy geniuses at PythonLabs with whom I spent a few great days doing XP on Zope 3 (Tim, I've now framed that mouse you borrowed, officially named the "TimMouse"). You guys need to find healthier places to eat lunch. (Also, thanks to the entire Python community, an amazing bunch of people).
Lots of people sent in corrections and I am indebted to them all, but particular thanks go to (for the first edition): Kevin Raulerson (found tons of great bugs), Bob Resendes (simply incredible), John Pinto, Joe Dante, Joe Sharp (all three were fabulous), David Combs (many grammar and clarification corrections), Dr. Robert Stephenson, John Cook, Franklin Chen, Zev Griner, David Karr, Leander A. Stroschein, Steve Clark, Charles A. Lee, Austin Maher, Dennis P. Roth, Roque Oliveira, Douglas Dunn, Dejan Ristic, Neil Galarneau, David B. Malkovsky, Steve Wilkinson, and a host of others. Prof. Ir. Marc Meurrens put in a great deal of effort to publicize and make the electronic version of the first edition of the book available in Europe.
Thanks to those who helped me rewrite the examples to use the Swing library (for the 2nd edition), and for other assistance: Jon Shvarts, Thomas Kirsch, Rahim Adatia, Rajesh Jain, Ravi Manthena, Banu Rajamani, Jens Brandt, Nitin Shivaram, Malcolm Davis, and everyone who expressed support.
There have been a spate of smart technical people in my life who have become friends and have also been both influential and unusual in that they do yoga and practice other forms of spiritual enhancement, which I find quite inspirational and instructional. They are Kraig Brockschmidt, Gen Kiyooka, and Andrea Provaglio (who helps in the understanding of Java and programming in general in Italy, and now in the United States as an associate of the MindView team).
It's not that much of a surprise to me that understanding Delphi helped me understand Java, since there are many concepts and language design decisions in common. My Delphi friends provided assistance by helping me gain insight into that marvelous programming environment. They are Marco Cantu (another Italian-perhaps being steeped in Latin gives one aptitude for programming languages?), Neil Rubenking (who used to do the yoga/vegetarian/Zen thing until he discovered computers), and of course Zack Urlocker (Delphi product manager), a long-time pal whom I've traveled the world with.
My friend Richard Hale Shaw's insights and support have been very helpful (and Kim's, too). Richard and I spent many months giving seminars together and trying to work out the perfect learning experience for the attendees.
The book design, cover design, and cover photo were created by my friend Daniel Will-Harris, noted author and designer (www.Will-Harris.com), who used to play with rub-on letters in junior high school while he awaited the invention of computers and desktop publishing, and complained of me mumbling over my algebra problems. However, I produced the camera-ready pages myself, so the typesetting errors are mine. Microsoft® Word XP for Windows was used to write the book and to create camera-ready pages in Adobe Acrobat; the book was created directly from the Acrobat PDF files. As a tribute to the electronic age, I happened to be overseas when the final version of the first and second editions of the book was produced-the first edition was sent from Capetown, South Africa and the second edition was posted from Prague. The third was from Crested Butte, Colorado. The body typeface is Georgia and the headlines are in Verdana. The cover typeface is ITC Rennie Mackintosh.
A special thanks to all my teachers and all my students (who are my teachers as well). The most fun writing teacher was Gabrielle Rico (author of Writing the Natural Way, Putnam, 1983). I'll always treasure the terrific week at Esalen.
My sweetie Dawn McGee took the back cover photo, and makes me smile that way.
The supporting cast of friends includes, but is not limited to: Andrew Binstock, Steve Sinofsky, JD Hildebrandt, Tom Keffer, Brian McElhinney, Brinkley Barr, Bill Gates at Midnight Engineering Magazine, Larry Constantine and Lucy Lockwood, Greg Perry, Dan Putterman, Christi Westphal, Gene Wang, Dave Mayer, David Intersimone, Andrea Rosenfield, Claire Sawyers, more Italians (Laura Fallai, Corrado, Ilsa, and Cristina Giustozzi), Chris and Laura Strand, the Almquists, Brad Jerbic, Marilyn Cvitanic, the Mabrys, the Haflingers, the Pollocks, Peter Vinci, the Robbins Families, the Moelter Families (and the McMillans), Michael Wilk, Dave Stoner, Laurie Adams, the Cranstons, Larry Fogg, Mike and Karen Sequeira, Gary Entsminger and Allison Brody, Kevin Donovan and Sonda Eastlack, Chester and Shannon Andersen, Joe Lordi, Dave and Brenda Bartlett, Patti Gast, the Rentschlers, the Sudeks, Dick, Patty, and Lee Eckel, Lynn and Todd, and their families. And of course, Mom and Dad.