Core.Java.Volume-I.Fundamentals.(2007),.8Ed.pdf
Document Details
Full Transcript
VOLUME I-FUNDAMENTALS EIGHTH EDITION CAY S. HORSTMANN GARY CORNELL Sun Microsystems Press Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid Capetown Sydney Tokyo Singapore Mexico City Many of the...
VOLUME I-FUNDAMENTALS EIGHTH EDITION CAY S. HORSTMANN GARY CORNELL Sun Microsystems Press Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid Capetown Sydney Tokyo Singapore Mexico City 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 the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. Sun Microsystems, Inc., has intellectual property rights relating to implementations of the technology described in this publication. In particular, and without limitation, these intellectual property rights may include one or more VS. patents, foreign patents, or pending applications. Sun, Sun Microsystems, the Sum logo, J2ME. Solaris, Java, Javadoc. Net Beans, and all Sun and Java based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed lor incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE. OR NON-INFRINGEMENT. THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPO- GRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC., MAY MAKE IMPROVE- MENTS AND/OR CHANGES IN THE PRODUCTS) AND/OR THE PROCRAM(S) DESCRIBED IN THIS PUBLICATION AT ANYTIME The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact U 5. Corporate and Government Sales, (800) 382-3419, corpsales@pear- sontechgroup.com. For sales outside the United States please contact: International Sales, [email protected]. Visit us on the Web: www.prenhaIlprofessional.com Library of Congress Cataloging-in-Publication Data Horstmann. CayS.,1959- Core Java. Volume I, Fundamentals / Cay S. Horstmann, Gary Cornell. — 8th ed. p. cm. Includes index. ISBN 978-0-13-235476-9 (pbk.: alk. paper) I. lava (Computer program language) I. Cornell, Gary. II. Title. III. Title: Fundamentals. IV. Title: Core-Java fundamentals. QA76.73.I3SH6753 2008 005.133-dc22 2007028843 Copyright© 2008 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054 U.S.A. All rights reserved.. Printed in the United States of America. This publication is protected by copyright, and permission must he obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likeivi.se. For information regardling permissions, write to: Pearson Education, Inc.. Rights and Contracts Department. One Like Street, Upper Saddle River, NJ 07458. ISBN-13: 978-0-13-235476-9 ISBN-10: 0-13-235476-4 Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts. First printing, September 2007 Table of Contents Preface xix Acknowledgments xxv Chapter 1: An Introduction to Java 1 Java As a Programming Platform 2 The Java “White Paper” Buzzwords 2 Java Applets and the Internet 7 A Short History of Java 9 Common Misconceptions about Java 11 Chapter 2: The Java Programming Environment 15 Installing the Java Development Kit 16 Choosing a Development Environment 21 Using the Command-Line Tools 22 Using an Integrated Development Environment 25 Running a Graphical Application 28 Building and Running Applets 31 Chapter 3: Fundamental Programming Structures in Java 35 A Simple Java Program 36 Comments 39 Data Types 40 Variables 44 Operators 46 Strings 53 Input and Output 63 Control Flow 71 Big Numbers 88 Arrays 90 Chapter 4: Objects and Classes 105 Introduction to Object-Oriented Programming 106 Using Predefined Classes 111 Defining Your Own Classes 122 Static Fields and Methods 132 Method Parameters 138 Object Construction 144 Packages 15 The Class Path 160 Documentation Comments 162 Class Design Hints 167 Chapter 5: Inheritance 171 Classes, Superclasses, and Subclasses 172 Object: The Cosmic Superclass 192 Generic Array Lists 204 Object Wrappers and Autoboxing 211 Methods with a Variable Number of Parameters 214 Enumeration Classes 215 Reflection 217 Design Hints for Inheritance 238 Chapter 6: Interfaces and Inner Classes 241 Interfaces 242 Object Cloning 249 Interfaces and Callbacks 255 Inner Classes 258 Proxies 275 Chapter 7: Graphics Programming 281 Introducing Swing 282 Creating a Frame 285 Positioning a Frame 288 Displaying Information in a Component 294 Working with 2D Shapes 299 Using Color 307 Using Special Fonts for Text 310 Displaying Images 318 Chapter 8: Event Handling 323 Basics of Event Handling 324 Actions 342 Mouse Events 349 The AWT Event Hierarchy 357 Chapter 9: User Interface Components with Swing 361 Swing and the Model-View-Controller Design Pattern 362 Introduction to Layout Management 368 Text Input 377 Choice Components 385 Menus 406 Sophisticated Layout Management 424 Dialog Boxes 452 Chapter 10: Deploying Applications and Applets 493 JAR Files 494 Java Web Start 501 Applets 516 Storage of Application Preferences 539 Chapter 11: Exceptions, Logging, Assertions, and Debugging 551 Dealing with Errors 552 Catching Exceptions 559 Tips for Using Exceptions 568 Using Assertions 571 Logging 575 Debugging Tips 591 Using a Debugger 607 Chapter 12: Generic Programming 613 Why Generic Programming? 614 Definition of a Simple Generic Class 616 Generic Methods 618 Bounds for Type Variables 619 Generic Code and the Virtual Machine 621 Restrictions and Limitations 626 Inheritance Rules for Generic Types 630 Wildcard Types 632 Reflection and Generics 640 Chapter 13: Collections 649 Collection Interfaces 650 Concrete Collections 658 The Collections Framework 689 Algorithms 700 Legacy Collections 707 Chapter 14: Multithreading 715 What Are Threads? 716 Interrupting Threads 728 Thread States 730 Thread Properties 733 Synchronization 736 Blocking Queues 764 Thread-Safe Collections 771 Callables and Futures 774 Executors 778 Synchronizers 785 Threads and Swing 794 Appendix 809 To t h e Reader In late 1995, the Java programming language buret onto the Internet scene and gained instant celebrity status. The promise of Java technology was that it would become the universal glue that connects users with information, whether that information comes from web servers, databases, information providers, or any other imaginable source. Indeed, Java is in a unique position to fulfill this promise. It is an extremely solidly engi- neered language that has gained acceptance by all major vendors, except for Microsoft. Its built-in security and safety features are reassuring both to programmers and to the users of Java programs. Java even has built-in support that makes advanced program- ming tasks, such as network programming, database connectivity, and multithreading, straightforward. Since 1995, Sun Microsystems has released seven major revisions of the Java Develop- ment Kit. Over the course of the last eleven years, the Application Programming Inter- face (API) has grown from about 200 to over 3,000 classes. The API now spans such diverse areas as user interface constaiction, database management, internationaliza- tion, security, and XML processing. The book you have in your hands is the first volume of the eighth edition of Core Java™. With the publishing of each edition, the book followed the release of the Java Development Kit as quickly as possible, and each time, we rewrote the book to take advantage of the newest Java features. This edition has been updated to reflect the features of Java Standard Edition (SE) 6. As with the previous editions of this book, we still target serious programmers who want to put jam to work on real projects. We think of you, our reader, as a programmer with a solid back- ground in a programming language other than Java, and we assume that you don't like books filled with toy examples (such as toasters, zoo animals, or "nervous text"). You won't find any xix Preface of these in this book. Our goal is to enable you to fully understand the Java language and library, not to give you an illusion of understanding. In this book you will find lots of sample code that demonstrates almost every' language and library feature that we discuss. We keep the sample programs purposefully simple to focus on the major points, but, for the most part, they aren't fake and they don't cut corners. They should make good starting points for your own code. We assume you are willing, even eager, to learn about all the advanced features that Java puts at your disposal. For example, we give you a detailed treatment of: Object-oriented programming Reflection and proxies Interfaces and inner classes The event listener model Graphical user interface design with the Swing UI toolkit Exception handling Generic programming The collections framework Concurrency With the explosive growth of the Java class library, a one-volume treatment of all the features of Java that serious programmers need to know is no longer possible. Hence, we decided to break up the book into two volumes. The first volume, which you hold in your hands, concentrates on the fundamental concepts of the Java language, along with the basics of user-interface programming. The second volume, Core Java, Volume II— Advanced Features (forthcoming, ISBN: 978-0-13-235479-0), goes further into the enterprise features and advanced user-interface programming. It includes detailed discussions of: Files and streams Distributed objects Databases Advanced GUI components Native methods XML processing Network programming Advanced graphics Internationalization lavaBeans Annotations In this edition, we reshuffled the contents of the two volumes. In particular, multi- threading is now covered in Volume I because it has become so important, with Moore's law coming to an end. When writing a book, errors and inaccuracies are inevitable. We'd very much like to know about them. But, of course, we'd prefer to learn about each of them only once. We have put up a list of frequently asked questions, bugs fixes, and workarounds in a web page at http://horstmann.coni/corejava. Strategically placed at the end of the errata page Preface (to encourage you to read through it first) is a form you can use to report bugs and sug- gest improvements. Please don't be disappointed if we don't answer every query or if we don't got back to you immediately. We do read all e-mail and appreciate your input to make future editions of this book clearer and more informative. A Tour of T h i s B o o k Chapter 1 gives an overview of the capabilities of Java that set it apart from other p r o g r a m m i n g languages. We explain w h a t the designers of the language set out to do and to what extent they succeeded. Then, we give a short history of how Java came into being and how it has evolved. In Chapter 2, we tell you how to download and install the JDK and the program exam- ples for this book. Then we guide you through compiling and running three typical Java programs, a console application, a graphical application, and an applet, using the plain JDK, a Java-enabled text editor, and a Java IDE. Chapter 3 starts the discussion of the Java language. In this chapter, we cover the basics: variables, loops, and simple functions. If you are a C or C++ programmer, this is smooth sailing because the syntax for these language features is essentially the same as in C. If you come from a non-C background such as Visual Basic, you will want to read this chapter carefully. Object-oriented programming (OOP) is now in the mainstream of programming prac- tice, and Java is completely object oriented. Chapter 4 introduces encapsulation, the first of two fundamental building blocks of object orientation, and the Java language mecha- nism to implement it, that is, classes and methods. In addition to the rules of the Java language, we also give advice on sound OOP design. Finally, we cover the marvelous javadoc tool that formats your code comments as a set of hyperlinked web pages. If you are familiar with C++, then you can browse through this chapter quickly. Programmers coming from a non-object-oriented background should expect to spend some time mas- tering O O P concepts before going further with Java. Classes and encapsulation are only one part of the OOP story, and Chapter 5 introduces the other, namely, inheritance. Inheritance lets you take an existing class and modify it according to your needs. This is a fundamental technique for programming in Java. The inheritance mechanism in Java is quite similar to that in C++. Once again, C++ pro- grammers can focus on the differences between the languages. Chapter 6 shows you how to use Java's notion of an interface. Interfaces let you go beyond the simple inheritance model of Chapter 5. Mastering interfaces allows you to have full access to the power of Java's completely object-oriented approach to program- ming. We also cover a useful technical feature of Java called inner classes. Inner classes help make your code cleaner and more concise. In Chapter 7, we begin application programming in earnest. Every Java programmer should know a bit about GUI programming, and this volume contains the basics. We show how you can make windows, how to paint on them, how to draw with geometric shapes, how to format text in multiple fonts, and how to display images. Chapter 8 is a detailed discussion of the event model of the AWT, the abstract window toolkit You'll see how to write the code that responds to events like mouse clicks or key presses. Along the way you'll see how to handle basic GUI elements like buttons and panels. Prefaсe Chapter 9 discusses the Swing GUI toolkit in great detail. The Swing toolkit allows you to build a cross-platform graphical user interface. You'll learn all about the various kinds of buttons, text components, borders, sliders, list boxes, menus, and dialog boxes. However, some of the more advanced components are discussed in Volume II. Chapter 10 shows you how to deploy your programs, either as applications or applets. We describe how to package programs in JAR files, and how to deliver applications over the Internet with the Java Web Start and applet mechanisms. Finally, we explain how Java programs can store and retrieve configuration information once they have been deployed. Chapter 11 discusses exception handling, Java's robust mechanism to deal with the fact that bad things can happen to good programs. Exceptions give you an efficient way of separating the normal processing code from the error handling. Of course, even after hardening your program by handling all exceptional conditions, it still might fail to work as expected. In the second half of this chapter, we give you a large number of use ful debugging tips. Finally, we guide you through a sample debugging session. Chapter 12 gives an overview of generic programming, a major advance of Java SE 5.0. Generic programming makes your programs easier to read and safer. We show you how you can use strong typing and remove unsightly and unsafe casts, and how you can deal with the complexities that arise from the need to stav compatible with older ver sions of Java. The topic of Chapter 13 is the collections framework of the Java platform. Whenever you want to collect multiple objects and retrieve them later, you will want to use a collection that is best suited for your circumstances, instead of just tossing the elements into an array. This chapter shows you how to take advantage of the standard collections that are prebuilt for your use. Chapter 14 finishes the book, with a discussion on multithreading, which enables you to program tasks to be done in parallel. (A thread is a flow of control within a program.) We show you how to set up threads and how to deal with thread synchronization. Mul tithreading has changed a great deal in Java SE 5.0, and we tell you all about the new mechanisms. The Appendix lists the reserved words of the Java language. Conventions As is common in many computer books, we use monospace type to represent computer code. NOTE: Notes are tagged with "note" icons that look like this. TIP: Tips are tagged with the 'lip" icon that look like this. CAUTION: When there is danger ahead, we warn you with a "caution" icon. Preface C++ NOTE: There are many C++ notes that explain the difference between Java and C++. You can skip over them if you don't have a background in C++ or if you consider your experi- ence with that language a bad dream of which you'd rather not be reminded. Java comes with a large programming library or Application Programming Interface (API). When using an API call for the first time, we add a short summary description tagged with an API icon at the end of the section. These descriptions are a bit more inform.il but, we hope, also a little more informative than those in the official on-line API documentation. We now tag each API note with the version number in which the feature was introduced, to help the readers who don't use the "bleeding edge" version of Java. Programs whose source code is on the Web are listed as examples, for instance Sample Code The web site for this book at http://horstmann.con1/core3ava contains all sample code from the book, in compressed form. You can expand the file either with one of the familiar unzipping programs or simply with the jar utility that is part of the Java Development Kit. See Chapter 2 for more information about installing the Java Development Kit and the sample code. Writing a book is always a monumental effort, and rewriting doesn't seem to be much easier, especially with continuous change in Java technology. Making a book a reality takes many dedicated people, and it is my great pleasure to acknowledge the contri- butions of the entire Core Java team. A large number of individuals at Prentice Hall and Sun Microsystems Press provided valu- able assistance, but they managed to stay behind the scenes. I'd like them all to know how much I appreciate their efforts. As always, my warm thanks go to my editor, Greg Doench of Prentice Hall, for steering the book through the writing and production process, and for allowing me to be blissfully unaware of the existence of all those folks behind the scenes. I am grateful to Vanessa Moore for the excellent production support. My thanks also to my coauthor of earlier editions, Gary Cornell, who has since moved on to other ventures. Thanks to the many readers of earlier editions who reported embarrassing errors and made lots of thoughtful suggestions for improvement. I am particularly grateful to the excellent reviewing team that went over the manuscript with an amazing eye for detail and saved me from many more embarrassing errors. Reviewers of this and earlier editions include Chuck Allison (Contributing Editor, C/C++ Users journal), Alec Beaton (PointBase, Inc.), Cliff Berg (iSavvix Corporation), Joshua Bloch (Sun Microsystems), David Brown, Corky Cartwright, Frank Cohen (PushToTest), Chris Crane (devXsolution), Dr. Nicholas J. De Lillo (Manhattan College), Rakesh Dhoopar (Ora- cle), David Geary (Sabrewaro), Brian Goetz (Principal Consultant, Quiotix Corp.), Angela Gordon (Sun Microsystems), Dan Gordon (Sun Microsystems), Rob Gordon, John Gray (University of Hartford), Cameron Gregory (olabs.com), Marty Hall (The Johns Hopkins University Applied Physics Lab), Vincent Hardy (Sun Microsystems), Dan Harkey (San Jose State University), William Higgins(IBM), Vladimir Ivanovic (PointBase),Jerry Jackson (ChannelPoint Software), Tim Kimmet (Preview Systems), Chris Laffra, Charlie Lai (Sun XXV Acknowledgments Microsystems), Angelika Langer, Doug Langston, Hang Liu (McGill University), Mark Lawrence, Doug Lea (SUNY Oswego), Gregory Longshore, Bob Lynch (Lynch Associates), Philip Milne (consultant), Mark Morrissoy (The Oregon Graduate Institute), Mahesh Neelakanta (Florida Atlantic University), Hao Pham, Paul Philion, Blake Ragsdell, Stuart Reges (University of Arizona), Rich Rosen (Interactive Data Corporation), Peter Sanders (ESSI University, Nice, France), Dr. Paul Sanghera (San Jose State University and Brooks College), Paul Sevinc (Teamup AG), Devang Shah (Sun Microsystems), Bradley A. Smith, Steven Stelting (Sun Microsystems), Christopher Taylor, Luke Taylor (Valtech), George Thiruvathukal, Kim Topley (author of Core JFC), Janet Traub, Paul Tyma (consultant), Peter van der Linden (Sun Microsystems), and Burt Walsh. Cay Horsttnann San Francisco, 2007 Chapter 1. An Introduction to Java Chapter AN INTRODUCTION TO JAVA ▼ JAVA AS A PROGRAMMING PLATFORM ▼ THE JAVA “WHITE PAPER” BUZZWORDS ▼ JAVA APPLETS AND THE INTERNET ▼ A SHORT HISTORY OF JAVA ▼ COMMON MISCONCEPTIONS ABOUT JAVA 1 Chapter 1. An Introduction to Java 2 Chapter 1 An Introduction to Java T he first release of Java in 1996 generated an incredible amount of excitement, not just in the computer press, but in mainstream media such as The New York Times, The Washington Post, and Business Week. Java has the distinction of being the first and only programming language that had a ten-minute story on National Public Radio. A $100,000,000 venture capital fund was set up solely for products produced by use of a specific computer language. It is rather amusing to revisit those heady times, and we give you a brief history of Java in this chapter. Java As a Programming Platform In the first edition of this book, we had this to write about Java: “As a computer language, Java’s hype is overdone: Java is certainly a good program- ming language. There is no doubt that it is one of the better languages available to serious programmers. We think it could potentially have been a great programming language, but it is probably too late for that. Once a language is out in the field, the ugly reality of compatibility with existing code sets in.” Our editor got a lot of flack for this paragraph from someone very high up at Sun Micro- systems who shall remain unnamed. But, in hindsight, our prognosis seems accurate. Java has a lot of nice language features—we examine them in detail later in this chapter. It has its share of warts, and newer additions to the language are not as elegant as the original ones because of the ugly reality of compatibility. But, as we already said in the first edition, Java was never just a language. There are lots of programming languages out there, and few of them make much of a splash. Java is a whole platform, with a huge library, containing lots of reusable code, and an execution environment that provides services such as security, portability across operating sys- tems, and automatic garbage collection. As a programmer, you will want a language with a pleasant syntax and comprehensible semantics (i.e., not C++). Java fits the bill, as do dozens of other fine languages. Some languages give you portability, garbage collection, and the like, but they don’t have much of a library, forcing you to roll your own if you want fancy graphics or network- ing or database access. Well, Java has everything—a good language, a high-quality exe- cution environment, and a vast library. That combination is what makes Java an irresistible proposition to so many programmers. The Java “White Paper” Buzzwords The authors of Java have written an influential White Paper that explains their design goals and accomplishments. They also published a shorter summary that is organized along the following 11 buzzwords: Simple Portable Object Oriented Interpreted Network-Savvy High Performance Robust Multithreaded Secure Dynamic Architecture Neutral Chapter 1. An Introduction to Java The Java “White Paper” Buzzwords 3 In this section, we will Summarize, with excerpts from the White Paper, what the Java designers say about each buzzword; and Tell you what we think of each buzzword, based on our experiences with the cur- rent version of Java. NOTE: As we write this, the White Paper can be found at http://java.sun.com/docs/white/ langenv/. The summary with the 11 buzzwords is at http://java.sun.com/docs/overviews/java/ java-overview-1.html. Simple We wanted to build a system that could be programmed easily without a lot of eso- teric training and which leveraged today’s standard practice. So even though we found that C++ was unsuitable, we designed Java as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that, in our experience, bring more grief than benefit. The syntax for Java is, indeed, a cleaned-up version of the syntax for C++. There is no need for header files, pointer arithmetic (or even a pointer syntax), structures, unions, operator overloading, virtual base classes, and so on. (See the C++ notes interspersed throughout the text for more on the differences between Java and C++.) The designers did not, however, attempt to fix all of the clumsy features of C++. For example, the syn- tax of the switch statement is unchanged in Java. If you know C++, you will find the tran- sition to the Java syntax easy. If you are used to a visual programming environment (such as Visual Basic), you will not find Java simple. There is much strange syntax (though it does not take long to get the hang of it). More important, you must do a lot more programming in Java. The beauty of Visual Basic is that its visual design environment almost automatically pro- vides a lot of the infrastructure for an application. The equivalent functionality must be programmed manually, usually with a fair bit of code, in Java. There are, however, third-party development environments that provide “drag-and-drop”-style program development. Another aspect of being simple is being small. One of the goals of Java is to enable the construction of software that can run stand-alone in small machines. The size of the basic interpreter and class support is about 40K bytes; adding the basic stan- dard libraries and thread support (essentially a self-contained microkernel) adds an additional 175K. This was a great achievement at the time. Of course, the library has since grown to huge proportions. There is now a separate Java Micro Edition with a smaller library, suitable for embedded devices. Object Oriented Simply stated, object-oriented design is a technique for programming that focuses on the data (= objects) and on the interfaces to that object. To make an analogy with carpentry, an “object-oriented” carpenter would be mostly concerned with the chair Chapter 1. An Introduction to Java 4 Chapter 1 An Introduction to Java he was building, and secondarily with the tools used to make it; a “non-object- oriented” carpenter would think primarily of his tools. The object-oriented facilities of Java are essentially those of C++. Object orientation has proven its worth in the last 30 years, and it is inconceivable that a modern programming language would not use it. Indeed, the object-oriented features of Java are comparable to those of C++. The major difference between Java and C++ lies in multiple inheritance, which Java has replaced with the simpler concept of interfaces, and in the Java metaclass model (which we discuss in Chapter 5). NOTE: If you have no experience with object-oriented programming languages, you will want to carefully read Chapters 4 through 6. These chapters explain what object-oriented programming is and why it is more useful for programming sophisticated projects than are traditional, procedure-oriented languages like C or Basic. Network-Savvy Java has an extensive library of routines for coping with TCP/IP protocols like HTTP and FTP. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file system. We have found the networking capabilities of Java to be both strong and easy to use. Anyone who has tried to do Internet programming using another language will revel in how simple Java makes onerous tasks like opening a socket connection. (We cover net- working in Volume II of this book.) The remote method invocation mechanism enables communication between distributed objects (also covered in Volume II). Robust Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error-prone.... The single biggest difference between Java and C/C++ is that Java has a pointer model that elim- inates the possibility of overwriting memory and corrupting data. This feature is also very useful. The Java compiler detects many problems that, in other languages, would show up only at runtime. As for the second point, anyone who has spent hours chasing memory corruption caused by a pointer bug will be very happy with this feature of Java. If you are coming from a language like Visual Basic that doesn’t explicitly use pointers, you are probably wondering why this is so important. C programmers are not so lucky. They need pointers to access strings, arrays, objects, and even files. In Visual Basic, you do not use pointers for any of these entities, nor do you need to worry about memory allocation for them. On the other hand, many data structures are difficult to implement in a pointerless language. Java gives you the best of both worlds. You do not need point- ers for everyday constructs like strings and arrays. You have the power of pointers if you need it, for example, for linked lists. And you always have complete safety, because you can never access a bad pointer, make memory allocation errors, or have to protect against memory leaking away. Chapter 1. An Introduction to Java The Java “White Paper” Buzzwords 5 Secure Java is intended to be used in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems. In the first edition of Core Java we said: “Well, one should ‘never say never again,’” and we turned out to be right. Not long after the first version of the Java Development Kit was shipped, a group of security experts at Princeton University found subtle bugs in the security features of Java 1.0. Sun Microsystems has encouraged research into Java security, making publicly available the specification and implementation of the virtual machine and the security libraries. They have fixed all known security bugs quickly. In any case, Java makes it extremely difficult to outwit its security mechanisms. The bugs found so far have been very technical and few in number. From the beginning, Java was designed to make certain kinds of attacks impossible, among them: Overrunning the runtime stack—a common attack of worms and viruses Corrupting memory outside its own process space Reading or writing files without permission A number of security features have been added to Java over time. Since version 1.1, Java has the notion of digitally signed classes (see Volume II). With a signed class, you can be sure who wrote it. Any time you trust the author of the class, the class can be allowed more privileges on your machine. NOTE: A competing code delivery mechanism from Microsoft based on its ActiveX technol- ogy relies on digital signatures alone for security. Clearly this is not sufficient—as any user of Microsoft’s own products can confirm, programs from well-known vendors do crash and create damage. Java has a far stronger security model than that of ActiveX because it con- trols the application as it runs and stops it from wreaking havoc. Architecture Neutral The compiler generates an architecture-neutral object file format—the compiled code is executable on many processors, given the presence of the Java runtime sys- tem. The Java compiler does this by generating bytecode instructions which have nothing to do with a particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly. This is not a new idea. More than 30 years ago, both Niklaus Wirth’s original implemen- tation of Pascal and the UCSD Pascal system used the same technique. Of course, interpreting bytecodes is necessarily slower than running machine instruc- tions at full speed, so it isn’t clear that this is even a good idea. However, virtual machines have the option of translating the most frequently executed bytecode sequences into machine code, a process called just-in-time compilation. This strategy has proven so effective that even Microsoft’s.NET platform relies on a virtual machine. Chapter 1. An Introduction to Java 6 Chapter 1 An Introduction to Java The virtual machine has other advantages. It increases security because the virtual machine can check the behavior of instruction sequences. Some programs even produce bytecodes on the fly, dynamically enhancing the capabilities of a running program. Portable Unlike C and C++, there are no “implementation-dependent” aspects of the specifi- cation. The sizes of the primitive data types are specified, as is the behavior of arith- metic on them. For example, an int in Java is always a 32-bit integer. In C/C++, int can mean a 16-bit integer, a 32-bit integer, or any other size that the compiler vendor likes. The only restriction is that the int type must have at least as many bytes as a short int and cannot have more bytes than a long int. Having a fixed size for number types eliminates a major porting headache. Binary data is stored and transmitted in a fixed format, eliminating confusion about byte ordering. Strings are saved in a standard Unicode format. The libraries that are a part of the system define portable interfaces. For example, there is an abstract Window class and implementations of it for UNIX, Windows, and the Macintosh. As anyone who has ever tried knows, it is an effort of heroic proportions to write a pro- gram that looks good on Windows, the Macintosh, and ten flavors of UNIX. Java 1.0 made the heroic effort, delivering a simple toolkit that mapped common user interface elements to a number of platforms. Unfortunately, the result was a library that, with a lot of work, could give barely acceptable results on different systems. (And there were often different bugs on the different platform graphics implementations.) But it was a start. There are many applications in which portability is more important than user interface slickness, and these applications did benefit from early versions of Java. By now, the user interface toolkit has been completely rewritten so that it no longer relies on the host user interface. The result is far more consistent and, we think, more attrac- tive than in earlier versions of Java. Interpreted The Java interpreter can execute Java bytecodes directly on any machine to which the interpreter has been ported. Since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory. Incremental linking has advantages, but its benefit for the development process is clearly overstated. Early Java development tools were, in fact, quite slow. Today, the bytecodes are translated into machine code by the just-in-time compiler. High Performance While the performance of interpreted bytecodes is usually more than adequate, there are situations where higher performance is required. The bytecodes can be translated on the fly (at runtime) into machine code for the particular CPU the application is running on. In the early years of Java, many users disagreed with the statement that the perfor- mance was “more than adequate.” Today, however, the just-in-time compilers have become so good that they are competitive with traditional compilers and, in some cases, even outperform them because they have more information available. For example, a just-in-time compiler can monitor which code is executed frequently and optimize just Chapter 1. An Introduction to Java Java Applets and the Internet 7 that code for speed. A more sophisticated optimization is the elimination (or “inlining”) of function calls. The just-in-time compiler knows which classes have been loaded. It can use inlining when, based upon the currently loaded collection of classes, a particu- lar function is never overridden, and it can undo that optimization later if necessary. Multithreaded [The] benefits of multithreading are better interactive responsiveness and real-time behavior. If you have ever tried to do multithreading in another language, you will be pleasantly surprised at how easy it is in Java. Threads in Java also can take advantage of multi- processor systems if the base operating system does so. On the downside, thread imple- mentations on the major platforms differ widely, and Java makes no effort to be platform independent in this regard. Only the code for calling multithreading remains the same across machines; Java offloads the implementation of multithreading to the underlying operating system or a thread library. Nonetheless, the ease of multithread- ing is one of the main reasons why Java is such an appealing language for server-side development. Dynamic In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment. Libraries can freely add new meth- ods and instance variables without any effect on their clients. In Java, finding out runtime type information is straightforward. This is an important feature in those situations in which code needs to be added to a running program. A prime example is code that is downloaded from the Internet to run in a browser. In Java 1.0, finding out runtime type information was anything but straightforward, but current versions of Java give the programmer full insight into both the structure and behavior of its objects. This is extremely useful for systems that need to analyze objects at runtime, such as Java GUI builders, smart debuggers, pluggable components, and object databases. NOTE: Shortly after the initial success of Java, Microsoft released a product called J++ with a programming language and virtual machine that was almost identical to Java. At this point, Microsoft is no longer supporting J++ and has instead introduced another language called C# that also has many similarities with Java but runs on a different virtual machine. There is even a J# for migrating J++ applications to the virtual machine used by C#. We do not cover J++, C#, or J# in this book. Java Applets and the Internet The idea here is simple: Users will download Java bytecodes from the Internet and run them on their own machines. Java programs that work on web pages are called applets. To use an applet, you only need a Java-enabled web browser, which will execute the bytecodes for you. You need not install any software. Because Sun licenses the Java source code and insists that there be no changes in the language and standard library, a Java applet should run on any browser that is advertised as Java-enabled. You get the latest version of the program whenever you visit the web page containing the applet. Chapter 1. An Introduction to Java 8 Chapter 1 An Introduction to Java Most important, thanks to the security of the virtual machine, you need never worry about attacks from hostile code. When the user downloads an applet, it works much like embedding an image in a web page. The applet becomes a part of the page, and the text flows around the space used for the applet. The point is, the image is alive. It reacts to user commands, changes its appearance, and sends data between the computer presenting the applet and the com- puter serving it. Figure 1–1 shows a good example of a dynamic web page that carries out sophisticated calculations. The Jmol applet displays molecular structures. By using the mouse, you can rotate and zoom each molecule to better understand its structure. This kind of direct manipulation is not achievable with static web pages, but applets make it possible. (You can find this applet at http://jmol.sourceforge.net.) When applets first appeared, they created a huge amount of excitement. Many people believe that the lure of applets was responsible for the astonishing popularity of Java. However, the initial excitement soon turned into frustration. Various versions of Netscape and Internet Explorer ran different versions of Java, some of which were seri- ously outdated. This sorry situation made it increasingly difficult to develop applets that took advantage of the most current Java version. Today, most web pages simply use JavaScript or Flash when dynamic effects are desired in the browser. Java, on the other hand, has become the most popular language for developing the server-side applica- tions that produce web pages and carry out the backend logic. Figure 1–1 The Jmol applet Chapter 1. An Introduction to Java A Short History of Java 9 A Short History of Java This section gives a short history of Java’s evolution. It is based on various published sources (most important, on an interview with Java’s creators in the July 1995 issue of SunWorld’s on-line magazine). Java goes back to 1991, when a group of Sun engineers, led by Patrick Naughton and Sun Fellow (and all-around computer wizard) James Gosling, wanted to design a small computer language that could be used for consumer devices like cable TV switchboxes. Because these devices do not have a lot of power or memory, the language had to be small and generate very tight code. Also, because different manufacturers may choose different central processing units (CPUs), it was important that the language not be tied to any single architecture. The project was code-named “Green.” The requirements for small, tight, and platform-neutral code led the team to resurrect the model that some Pascal implementations tried in the early days of PCs. Niklaus Wirth, the inventor of Pascal, had pioneered the design of a portable language that gen- erated intermediate code for a hypothetical machine. (These are often called virtual machines—hence, the Java virtual machine or JVM.) This intermediate code could then be used on any machine that had the correct interpreter. The Green project engineers used a virtual machine as well, so this solved their main problem. The Sun people, however, come from a UNIX background, so they based their language on C++ rather than Pascal. In particular, they made the language object oriented rather than procedure oriented. But, as Gosling says in the interview, “All along, the language was a tool, not the end.” Gosling decided to call his language “Oak” (presumably because he liked the look of an oak tree that was right outside his window at Sun). The people at Sun later realized that Oak was the name of an existing computer language, so they changed the name to Java. This turned out to be an inspired choice. In 1992, the Green project delivered its first product, called “* 7.” It was an extremely intelligent remote control. (It had the power of a SPARCstation in a box that was 6 inches by 4 inches by 4 inches.) Unfortunately, no one was interested in producing this at Sun, and the Green people had to find other ways to market their technology. How- ever, none of the standard consumer electronics companies were interested. The group then bid on a project to design a cable TV box that could deal with new cable services such as video on demand. They did not get the contract. (Amusingly, the company that did was led by the same Jim Clark who started Netscape—a company that did much to make Java successful.) The Green project (with a new name of “First Person, Inc.”) spent all of 1993 and half of 1994 looking for people to buy its technology—no one was found. (Patrick Naughton, one of the founders of the group and the person who ended up doing most of the mar- keting, claims to have accumulated 300,000 air miles in trying to sell the technology.) First Person was dissolved in 1994. While all of this was going on at Sun, the World Wide Web part of the Internet was growing bigger and bigger. The key to the Web is the browser that translates the hypertext page to the screen. In 1994, most people were using Mosaic, a noncommer- cial web browser that came out of the supercomputing center at the University of Illi- nois in 1993. (Mosaic was partially written by Marc Andreessen for $6.85 an hour as Chapter 1. An Introduction to Java 10 Chapter 1 An Introduction to Java an undergraduate student on a work-study project. He moved on to fame and fortune as one of the cofounders and the chief of technology at Netscape.) In the SunWorld interview, Gosling says that in mid-1994, the language developers real- ized that “We could build a real cool browser. It was one of the few things in the client/ server mainstream that needed some of the weird things we’d done: architecture neu- tral, real-time, reliable, secure—issues that weren’t terribly important in the workstation world. So we built a browser.” The actual browser was built by Patrick Naughton and Jonathan Payne and evolved into the HotJava browser. The HotJava browser was written in Java to show off the power of Java. But the builders also had in mind the power of what are now called applets, so they made the browser capable of executing code inside web pages. This “proof of technology” was shown at SunWorld ‘95 on May 23, 1995, and inspired the Java craze that continues today. Sun released the first version of Java in early 1996. People quickly realized that Java 1.0 was not going to cut it for serious application development. Sure, you could use Java 1.0 to make a nervous text applet that moved text randomly around in a canvas. But you couldn’t even print in Java 1.0. To be blunt, Java 1.0 was not ready for prime time. Its successor, version 1.1, filled in the most obvious gaps, greatly improved the reflection capability, and added a new event model for GUI programming. It was still rather limited, though. The big news of the 1998 JavaOne conference was the upcoming release of Java 1.2, which replaced the early toylike GUI and graphics toolkits with sophisticated and scal- able versions that come a lot closer to the promise of “Write Once, Run Anywhere”™ than its predecessors. Three days after (!) its release in December 1998, Sun’s marketing department changed the name to the catchy Java 2 Standard Edition Software Development Kit Version 1.2. Besides the Standard Edition, two other editions were introduced: the Micro Edition for embedded devices such as cell phones, and the Enterprise Edition for server-side pro- cessing. This book focuses on the Standard Edition. Versions 1.3 and 1.4 of the Standard Edition are incremental improvements over the ini- tial Java 2 release, with an ever-growing standard library, increased performance, and, of course, quite a few bug fixes. During this time, much of the initial hype about Java applets and client-side applications abated, but Java became the platform of choice for server-side applications. Version 5.0 is the first release since version 1.1 that updates the Java language in signifi- cant ways. (This version was originally numbered 1.5, but the version number jumped to 5.0 at the 2004 JavaOne conference.) After many years of research, generic types (which are roughly comparable to C++ templates) have been added—the challenge was to add this feature without requiring changes in the virtual machine. Several other use- ful language features were inspired by C#: a “for each” loop, autoboxing, and metadata. Language changes are always a source of compatibility pain, but several of these new lan- guage features are so seductive that we think that programmers will embrace them eagerly. Chapter 1. An Introduction to Java Common Misconceptions about Java 11 Version 6 (without the.0 suffix) was released at the end of 2006. Again, there are no lan- guage changes but additional performance improvements and library enhancements. Table 1–1 shows the evolution of the Java language and library. As you can see, the size of the application programming interface (API) has grown tremendously. Table 1–1 Evolution of the Java Language Number of Classes Version Year New Language Features and Interfaces 1.0 1996 The language itself 211 1.1 1997 Inner classes 477 1.2 1998 None 1,524 1.3 2000 None 1,840 1.4 2004 Assertions 2,723 5.0 2004 Generic classes, “for each” loop, 3,279 varargs, autoboxing, metadata, enumerations, static import 6 2006 None 3,777 Common Misconceptions about Java We close this chapter with a list of some common misconceptions about Java, along with commentary. Java is an extension of HTML. Java is a programming language; HTML is a way to describe the structure of a web page. They have nothing in common except that there are HTML extensions for placing Java applets on a web page. I use XML, so I don’t need Java. Java is a programming language; XML is a way to describe data. You can process XML data with any programming language, but the Java API contains excellent support for XML processing. In addition, many important third-party XML tools are implemented in Java. See Volume II for more information. Java is an easy programming language to learn. No programming language as powerful as Java is easy. You always have to distinguish between how easy it is to write toy programs and how hard it is to do serious work. Also, consider that only four chapters in this book discuss the Java language. The remaining chapters of both volumes show how to put the language to work, using the Java libraries. The Java libraries contain thousands of classes and interfaces, and tens of thousands of functions. Luckily, you do not need to know every one of them, but you do need to know surprisingly many to use Java for anything realistic. Chapter 1. An Introduction to Java 12 Chapter 1 An Introduction to Java Java will become a universal programming language for all platforms. This is possible, in theory, and it is certainly the case that every vendor but Microsoft seems to want this to happen. However, many applications, already working perfectly well on desktops, would not work well on other devices or inside a browser. Also, these applications have been written to take advantage of the speed of the processor and the native user interface library and have been ported to all the important platforms any- way. Among these kinds of applications are word processors, photo editors, and web browsers. They are typically written in C or C++, and we see no benefit to the end user in rewriting them in Java. Java is just another programming language. Java is a nice programming language; most programmers prefer it over C, C++, or C#. But there have been hundreds of nice programming languages that never gained wide- spread popularity, whereas languages with obvious flaws, such as C++ and Visual Basic, have been wildly successful. Why? The success of a programming language is determined far more by the utility of the support system surrounding it than by the elegance of its syntax. Are there useful, convenient, and standard libraries for the features that you need to implement? Are there tool vendors that build great programming and debugging environments? Does the language and the toolset integrate with the rest of the computing infrastructure? Java is successful because its class libraries let you easily do things that were hard before, such as networking and multithreading. The fact that Java reduces pointer errors is a bonus and so programmers seem to be more productive with Java, but these factors are not the source of its success. Now that C# is available, Java is obsolete. C# took many good ideas from Java, such as a clean programming language, a virtual machine, and garbage collection. But for whatever reasons, C# also left some good stuff behind, in particular security and platform independence. If you are tied to Windows, C# makes a lot of sense. But judging by the job ads, Java is still the language of choice for a majority of developers. Java is proprietary, and it should therefore be avoided. Sun Microsystems licenses Java to distributors and end users. Although Sun has ulti- mate control over Java through the “Java Community Process,” they have involved many other companies in the development of language revisions and the design of new libraries. Source code for the virtual machine and the libraries has always been freely available, but only for inspection, not for modification and redistribution. Up to this point, Java has been “closed source, but playing nice.” This situation changed dramatically in 2007, when Sun announced that future versions of Java will be available under the General Public License, the same open source license that is used by Linux. It remains to be seen how Sun will manage the governance of Java in the future, but there is no question that the open sourcing of Java has been a very cou- rageous move that will extend the life of Java by many years. Java is interpreted, so it is too slow for serious applications. In the early days of Java, the language was interpreted. Nowadays, except on “micro” platforms such as cell phones, the Java virtual machine uses a just-in-time compiler. The Chapter 1. An Introduction to Java Common Misconceptions about Java 13 “hot spots” of your code will run just as fast in Java as they would in C++, and in some cases, they will run faster. Java does have some additional overhead over C++. Virtual machine startup time is slow, and Java GUIs are slower than their native counterparts because they are painted in a platform-independent manner. People have complained for years that Java applications are too slow. However, today’s computers are much faster than they were when these complaints started. A slow Java program will still run quite a bit better than those blazingly fast C++ programs did a few years ago. At this point, these complaints sound like sour grapes, and some detrac- tors have instead started to complain that Java user interfaces are ugly rather than slow. All Java programs run inside a web page. All Java applets run inside a web browser. That is the definition of an applet—a Java pro- gram running inside a browser. But most Java programs are stand-alone applications that run outside of a web browser. In fact, many Java programs run on web servers and produce the code for web pages. Most of the programs in this book are stand-alone programs. Sure, applets can be fun. But stand-alone Java programs are more important and more useful in practice. Java programs are a major security risk. In the early days of Java, there were some well-publicized reports of failures in the Java security system. Most failures were in the implementation of Java in a specific browser. Researchers viewed it as a challenge to try to find chinks in the Java armor and to defy the strength and sophistication of the applet security model. The technical failures that they found have all been quickly corrected, and to our knowledge, no actual systems were ever compromised. To keep this in perspective, consider the literally millions of virus attacks in Windows executable files and Word macros that cause real grief but sur- prisingly little criticism of the weaknesses of the attacked platform. Also, the ActiveX mechanism in Internet Explorer would be a fertile ground for abuse, but it is so boringly obvious how to circumvent it that few researchers have bothered to publicize their findings. Some system administrators have even deactivated Java in company browsers, while continuing to permit their users to download executable files, ActiveX controls, and Word documents. That is pretty ridiculous—currently, the risk of being attacked by hos- tile Java applets is perhaps comparable to the risk of dying from a plane crash; the risk of being infected by opening Word documents is comparable to the risk of dying while crossing a busy freeway on foot. JavaScript is a simpler version of Java. JavaScript, a scripting language that can be used inside web pages, was invented by Netscape and originally called LiveScript. JavaScript has a syntax that is reminiscent of Java, but otherwise there are no relationships (except for the name, of course). A subset of JavaScript is standardized as ECMA-262. JavaScript is more tightly integrated with browsers than Java applets are. In particular, a JavaScript program can modify the docu- ment that is being displayed, whereas an applet can only control the appearance of a limited area. Chapter 1. An Introduction to Java 14 Chapter 1 An Introduction to Java With Java, I can replace my computer with a $500 “Internet appliance.” When Java was first released, some people bet big that this was going to happen. Ever since the first edition of this book, we have believed it is absurd to think that home users are going to give up a powerful and convenient desktop for a limited machine with no local storage. We found the Java-powered network computer a plausible option for a “zero administration initiative” to cut the costs of computer ownership in a business, but even that has not happened in a big way. On the other hand, Java has become widely distributed on cell phones. We must confess that we haven’t yet seen a must-have Java application running on cell phones, but the usual fare of games and screen savers seems to be selling well in many markets. TIP: For answers to common Java questions, turn to one of the Java FAQ (frequently asked question) lists on the Web—see http://www.apl.jhu.edu/~hall/java/FAQs-and-Tutorials.html. Chapter 2. The Java Programming Environment Chapter THE JAVA PROGRAMMING ENVIRONMENT ▼ INSTALLING THE JAVA DEVELOPMENT KIT ▼ CHOOSING A DEVELOPMENT ENVIRONMENT ▼ USING THE COMMAND-LINE TOOLS ▼ USING AN INTEGRATED DEVELOPMENT ENVIRONMENT ▼ RUNNING A GRAPHICAL APPLICATION ▼ BUILDING AND RUNNING APPLETS 15 Chapter 2. The Java Programming Environment 16 Chapter 2 The Java Programming Environment I n this chapter, you will learn how to install the Java Development Kit (JDK) and how to compile and run various types of programs: console programs, graphical appli- cations, and applets. You run the JDK tools by typing commands in a shell window. However, many programmers prefer the comfort of an integrated development envi- ronment. We show you how to use a freely available development environment to compile and run Java programs. Although easier to learn, integrated development envi- ronments can be resource-hungry and tedious to use for small programs. As a middle ground, we show you how to use a text editor that can call the Java compiler and run Java programs. Once you have mastered the techniques in this chapter and picked your development tools, you are ready to move on to Chapter 3, where you will begin explor- ing the Java programming language. Installing the Java Development Kit The most complete and up-to-date versions of the Java Development Kit (JDK) are available from Sun Microsystems for Solaris, Linux, and Windows. Versions in various states of development exist for the Macintosh and many other platforms, but those ver- sions are licensed and distributed by the vendors of those platforms. NOTE: Some Linux distributions have prepackaged versions of the JDK. For example, on Ubuntu, you can install the JDK by simply installing the sun-java6-jdk package with apt-get or the Synaptic GUI. Downloading the JDK To download the Java Development Kit, you will need to navigate the Sun web site and decipher an amazing amount of jargon before you can get the software that you need. See Table 2–1 for a summary. You already saw the abbreviation JDK for Java Development Kit. Somewhat confus- ingly, versions 1.2 through 1.4 of the kit were known as the Java SDK (Software Devel- opment Kit). You will still find occasional references to the old term. There is also a Java Runtime Environment (JRE) that contains the virtual machine but not the compiler. That is not what you want as a developer. It is intended for end users who have no need for the compiler. Next, you’ll see the term Java SE everywhere. That is the Java Standard Edition, in con- trast to Java EE (Enterprise Edition) and Java ME (Micro Edition). You will occasionally run into the term Java 2 that was coined in 1998 when the market- ing folks at Sun felt that a fractional version number increment did not properly com- municate the momentous advances of JDK 1.2. However, because they had that insight only after the release, they decided to keep the version number 1.2 for the development kit. Subsequent releases were numbered 1.3, 1.4, and 5.0. The platform, however, was renamed from Java to Java 2. Thus, we had Java 2 Standard Edition Software Develop- ment Kit Version 5.0, or J2SE SDK 5.0. For engineers, all of this was a bit confusing, but that’s why we never made it into mar- keting. Mercifully, in 2006, sanity prevailed. The useless Java 2 moniker was dropped and the current version of the Java Standard Edition was called Java SE 6. You will still see occasional references to versions 1.5 and 1.6—these are just synonyms for versions 5.0 and 6. Chapter 2. The Java Programming Environment Installing the Java Development Kit 17 Finally, when Sun makes a minor version change to fix urgent issues, it refers to the change as an update. For example, the first update of the development kit for Java SE 6 is officially called JDK 6u1 and has the internal version number 1.6.0_01. If you use Solaris, Linux, or Windows, point your browser to http://java.sun.com/javase to download the JDK. Look for version 6 or later and pick your platform. Don’t worry if the software is called an “update.” The update bundles contain the most current version of the whole JDK. Sometimes, Sun makes available bundles that contain both the Java Development Kit and an integrated development environment. That integrated environment has, at dif- ferent times of its life, been named Forte, Sun ONE Studio, Sun Java Studio, and Net- beans. We do not know what the eager beavers in marketing will call it when you approach the Sun web site. We suggest that you install only the Java Development Kit at this time. If you later decide to use Sun’s integrated development environment, simply download it from http://netbeans.org. Table 2–1 Java Jargon Name Acronym Explanation Java Development Kit JDK The software for programmers who want to write Java programs Java Runtime Environment JRE The software for consumers who want to run Java programs Standard Edition SE The Java platform for use on desktops and simple server applications Enterprise Edition EE The Java platform for complex server applications Micro Edition ME The Java platform for use on cell phones and other small devices Java 2 J2 An outdated term that described Java versions from 1998 until 2006 Software Development Kit SDK An outdated term that described the JDK from 1998 until 2006 Update u Sun’s term for a bug fix release NetBeans — Sun’s integrated development environment After downloading the JDK, follow the platform-dependent installation directions. At the time of this writing, they are available at http://java.sun.com/javase/6/webnotes/install/ index.html. Only the installation and compilation instructions for Java are system dependent. Once you get Java up and running, everything else in this book should apply to you. System independence is a major benefit of Java. Chapter 2. The Java Programming Environment 18 Chapter 2 The Java Programming Environment NOTE: The setup procedure offers a default for the installation directory that contains the JDK version number, such as jdk1.6.0. This sounds like a bother, but we have come to appreciate the version number—it makes it easier to install a new JDK release for testing. Under Windows, we strongly recommend that you do not accept a default location with spaces in the path name, such as c:\Program Files\jdk1.6.0. Just take out the Program Files part of the path name. In this book, we refer to the installation directory as jdk. For example, when we refer to the jdk/bin directory, we mean the directory with a name such as /usr/local/jdk1.6.0/bin or c:\jdk1.6.0\bin. Setting the Execution Path After you are done installing the JDK, you need to carry out one additional step: Add the jdk/bin directory to the execution path, the list of directories that the operating sys- tem traverses to locate executable files. Directions for this step also vary among operat- ing systems. In UNIX (including Solaris and Linux), the procedure for editing the execution path depends on the shell that you are using. If you use the C shell (which is the Solaris default), then add a line such as the following to the end of your ~/.cshrc file: set path=(/usr/local/jdk/bin $path) If you use the Bourne Again shell (which is the Linux default), then add a line such as the following to the end of your ~/.bashrc or ~/.bash_profile file: export PATH=/usr/local/jdk/bin:$PATH Under Windows, log in as administrator. Start the Control Panel, switch to Classic View, and select the System icon. In Windows NT/2000/XP, you immediately get the system properties dialog. In Vista, you need to select Advanced System Settings (see Figure 2–1). In the system properties dialog, click the Advanced tab, then click on the Environment button. Scroll through the System Variables window until you find a variable named Path. Click the Edit button (see Figure 2–2). Add the jdk\bin directory to the beginning of the path, using a semicolon to separate the new entry, like this: c:\jdk\bin;other stuff Save your settings. Any new console windows that you start have the correct path. Here is how you test whether you did it right: Start a shell window. Type the line java -version and press the ENTER key. You should get a display such as this one: java version "1.6.0_01" Java(TM) SE Runtime Environment (build 1.6.0_01-b06) Java HotSpot(TM) Client VM (build 1.6.0_01-b06, mixed mode, sharing) If instead you get a message such as “java: command not found” or “The name specified is not recognized as an internal or external command, operable program or batch file”, then you need to go back and double-check your installation. Chapter 2. The Java Programming Environment Installing the Java Development Kit 19 Figure 2–1 Launching the system properties dialog in Windows Vista Figure 2–2 Setting the Path environment variable in Windows Vista Chapter 2. The Java Programming Environment 20 Chapter 2 The Java Programming Environment NOTE: In Windows, follow these instructions to open a shell window. If you use Windows NT/ 2000/XP, select the “Run” option from the Start menu and type cmd. In Vista, simply type cmd into the “Start Search” field in the Start menu. Press ENTER, and a shell window appears. If you’ve never seen one of these, we suggest that you work through a tutorial that teaches the basics about the command line. Many computer science departments have tutorials on the Web, such as http://www.cs.sjsu.edu/faculty/horstman/CS46A/windows/tutorial.html. Installing the Library Source and Documentation The library source files are delivered in the JDK as a compressed file src.zip, and you must unpack that file to get access to the source code. We highly recommend that you do that. Simply do the following: 1. Make sure the JDK is installed and that the jdk/bin directory is on the execution path. 2. Open a shell window. 3. Change to the jdk directory (e.g., cd /usr/local/jdk1.6.0 or cd c:\jdk1.6.0). 4. Make a subdirectory src mkdir src cd src 5. Execute the command jar xvf../src.zip (or jar xvf..\src.zip on Windows) TIP: The src.zip file contains the source code for all public libraries. To obtain even more source (for the compiler, the virtual machine, the native methods, and the private helper classes), go to http://download.java.net/jdk6. The documentation is contained in a compressed file that is separate from the JDK. You can download the documentation from http://java.sun.com/javase/downloads. Simply follow these steps: 1. Make sure the JDK is installed and that the jdk/bin directory is on the execution path. 2. Download the documentation zip file and move it into the jdk directory. The file is called jdk-version-doc.zip, where version is something like 6. 3. Open a shell window. 4. Change to the jdk directory. 5. Execute the command jar xvf jdk-version-doc.zip where version is the appropriate version number. Installing the Core Java Program Examples You should also install the Core Java program examples. You can download them from http://horstmann.com/corejava. The programs are packaged into a zip file corejava.zip. You should unzip them into a separate directory—we recommend you call it CoreJavaBook. Here are the steps: Chapter 2. The Java Programming Environment Choosing a Development Environment 21 1. Make sure the JDK is installed and the jdk/bin directory is on the execution path. 2. Make a directory CoreJavaBook. 3. Download the corejava.zip file to that directory. 4. Open a shell window. 5. Change to the CoreJavaBook directory. 6. Execute the command jar xvf corejava.zip Navigating the Java Directories In your explorations of Java, you will occasionally want to peek inside the Java source files. And, of course, you will need to work extensively with the library documentation. Table 2–2 shows the JDK directory tree. Table 2–2 Java Directory Tree Directory Structure Description jdk (The name may be different, for example, jdk5.0) bin The compiler and tools demo Look here for demos docs Library documentation in HTML format (after expansion of j2sdkversion-doc.zip) include Files for compiling native methods (see Volume II) jre Java runtime environment files lib Library files src The library source (after expanding src.zip) The two most useful subdirectories for learning Java are docs and src. The docs directory contains the Java library documentation in HTML format. You can view it with any web browser, such as Netscape. TIP: Set a bookmark in your browser to the file docs/api/index.html. You will be referring to this page a lot as you explore the Java platform. The src directory contains the source code for the public part of the Java libraries. As you become more comfortable with Java, you may find yourself in situations for which this book and the on-line information do not provide what you need to know. At this point, the source code for Java is a good place to begin digging. It is reassuring to know that you can always dig into the source to find out what a library function really does. For example, if you are curious about the inner workings of the System class, you can look inside src/java/lang/System.java. Choosing a Development Environment If your programming experience comes from using Microsoft Visual Studio, you are accustomed to a development environment with a built-in text editor and menus to Chapter 2. The Java Programming Environment 22 Chapter 2 The Java Programming Environment compile and launch a program along with an integrated debugger. The basic JDK con- tains nothing even remotely similar. You do everything by typing in commands in a shell window. This sounds cumbersome, but it is nevertheless an essential skill. When you first install Java, you will want to troubleshoot your installation before you install a development environment. Moreover, by executing the basic steps yourself, you gain a better understanding of what the development environment does behind your back. However, after you have mastered the basic steps of compiling and running Java pro- grams, you will want to use a professional development environment. In the last decade, these environments have become so powerful and convenient that it simply doesn’t make much sense to labor on without them. Two excellent choices are the freely available Eclipse and NetBeans programs. In this chapter, we show you how to get started with Eclipse since it is still a bit slicker than NetBeans, although NetBeans is catching up fast. Of course, if you prefer a different development environment, you can certainly use it with this book. In the past, we recommended the use of a text editor such as Emacs, JEdit, or TextPad for simple programs. We no longer make this recommendation because the integrated devlopment environments are now so fast and convenient. In sum, we think that you should know how to use the basic JDK tools, and then you should become comfortable with an integrated development environment. Using the Command-Line Tools Let us get started the hard way: compiling and launching a Java program from the command line. 1. Open a shell window. 2. Go to the CoreJavaBook/v1ch02/Welcome directory. (The CoreJavaBook directory is the direc- tory into which you installed the source code for the book examples, as explained in the section “Installing the Core Java Program Examples” on page 20.) 3. Enter the following commands: javac Welcome.java java Welcome You should see the output shown in Figure 2–3 in the shell window. Congratulations! You have just compiled and run your first Java program. What happened? The javac program is the Java compiler. It compiles the file Welcome.java into the file Welcome.class. The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in the class file. NOTE: If you got an error message complaining about the line for (String g : greeting) then you probably use an older version of the Java compiler. Java SE 5.0 introduced a num- ber of very desirable features to the Java programming language, and we take advantage of them in this book. If you are using an older version of Java, you need to rewrite the loop as follows: for (int i = 0; i < greeting.length; i++) System.out.println(greeting[i]); Chapter 2. The Java Programming Environment Using the Command-Line Tools 23 Figure 2–3 Compiling and running Welcome.java The Welcome program is extremely simple. It merely prints a message to the console. You may enjoy looking inside the program shown in Listing 2–1 (we explain how it works in the next chapter). Listing 2–1 Welcome.java 1. 6. public class Welcome 7. { 8. public static void main(String[] args) 9. { 10. String[] greeting = new String; 11. greeting = "Welcome to Core Java"; 12. greeting = "by Cay Horstmann"; 13. greeting = "and Gary Cornell"; 14. 15. for (String g : greeting) 16. System.out.println(g); 17. } 18. } Chapter 2. The Java Programming Environment 24 Chapter 2 The Java Programming Environment Troubleshooting Hints In the age of visual development environments, many programmers are unfamiliar with running programs in a shell window. Any number of things can go wrong, leading to frustrating results. Pay attention to the following points: If you type in the program by hand, make sure you pay attention to uppercase and lowercase letters. In particular, the class name is Welcome and not welcome or WELCOME. The compiler requires a file name ( Welcome.java). When you run the program, you specify a class name ( Welcome) without a.java or.class extension. If you get a message such as “Bad command or file name” or “javac: command not found”, then go back and double-check your installation, in particular the execution path setting. If javac reports an error “cannot read: Welcome.java”, then you should check whether that file is present in the directory. Under UNIX, check that you used the correct capitalization for Welcome.java. Under Windows, use the dir shell command, not the graphical Explorer tool. Some text editors (in particular Notepad) insist on adding an extension.txt after every file. If you use Notepad to edit Welcome.java, then it actually saves it as Welcome.java.txt. Under the default Windows settings, Explorer conspires with Notepad and hides the.txt extension because it belongs to a “known file type.” In that case, you need to rename the file, using the ren shell command, or save it again, placing quotes around the file name: "Welcome.java". If you launch your program and get an error message complaining about a java.lang.NoClassDefFoundError, then carefully check the name of the offending class. If you get a complaint about welcome (with a lowercase w), then you should reissue the java Welcome command with an uppercase W. As always, case matters in Java. If you get a complaint about Welcome/java, then you accidentally typed java Welcome.java. Reissue the command as java Welcome. If you typed java Welcome and the virtual machine can’t find the Welcome class, then check if someone has set the CLASSPATH environment variable on your system. (It is usually not a good idea to set this variable globally, but some poorly written soft- ware installers in Windows do just that.) You can temporarily unset the CLASSPATH environment variable in the current shell window by typing set CLASSPATH= This command works on Windows and UNIX/Linux with the C shell. On UNIX/ Linux with the Bourne/bash shell, use export CLASSPATH= If you get an error message about a new language construct, make sure that your compiler supports Java SE 5.0. If you have too many errors in your program, then all the error messages fly by very quickly. The compiler sends the error messages to the standard error stream, so it’s a bit tricky to capture them if they fill more than the window can display. Use the 2> shell operator to redirect the errors to a file: javac MyProg.java 2> errors.txt Chapter 2. The Java Programming Environment Using an Integrated Development Environment 25 TIP: The excellent tutorial at http://java.sun.com/docs/books/tutorial/getStarted/cupojava/ goes into much greater detail about the “gotchas” that beginners can run into. Using an Integrated Development Environment In this section, we show you how to compile a program with Eclipse, an integrated development environment that is freely available from http://eclipse.org. Eclipse is written in Java, but because it uses a nonstandard windowing library, it is not quite as portable as Java itself. Nevertheless, versions exist for Linux, Mac OS X, Solaris, and Windows. There are other popular IDEs, but currently, Eclipse is the most commonly used. Here are the steps to get started: 1. After starting Eclipse, select File -> New Project from the menu. 2. Select “Java Project” from the wizard dialog (see Figure 2–4). These screen shots were taken with Eclipse 3.2. Don’t worry if your version of Eclipse looks slightly different. Figure 2–4 New Project dialog in Eclipse 3. Click the “Next” button. Supply the project name “Welcome” and type in the full path name of the directory that contains Welcome.java (see Figure 2–5). 4. Be sure to uncheck the option labeled “Create project in workspace”. 5. Click the “Finish” button. The project is now created. Chapter 2. The Java Programming Environment 26 Chapter 2 The Java Programming Environment Figure 2–5 Configuring an Eclipse project 6. Click on the triangle in the left pane next to the project window to open it, and then click on the triangle next to “Default package”. Double-click on Welcome.java. You should now see a window with the program code (see Figure 2–6). Figure 2–6 Editing a source file with Eclipse Chapter 2. The Java Programming Environment Using an Integrated Development Environment 27 7. With the right mouse button, click on the project name (Welcome) in the leftmost pane. Select Run -> Run As -> Java Application. An output window appears at the bottom of the window. The program output is displayed in the output window (see Figure 2–7). Figure 2–7 Running a program in Eclipse Locating Compilation Errors Presumably, this program did not have typos or bugs. (It was only a few lines of code, after all.) Let us suppose, for the sake of argument, that your code occasionally contains a typo (perhaps even a syntax error). Try it out—ruin our file, for example, by changing the capitalization of String as follows: public static void main(string[] args) Now, run the compiler again. You will get an error message that complains about an unknown string type (see Figure 2–8). Simply click on the error message. The cursor moves to the matching line in the edit window, where you can correct your error. This behavior allows you to fix your errors quickly. TIP: Often, an Eclipse error report is accompanied by a lightbulb icon. Click on the lightbulb to get a list of suggested fixes. Chapter 2. The Java Programming Environment 28 Chapter 2 The Java Programming Environment Figure 2–8 Error messages in Eclipse These instructions should give you a taste of working in an integrated environment. We discuss the Eclipse debugger in Chapter 11. Running a Graphical Application The Welcome program was not terribly exciting. Next, we will demonstrate a graphical application. This program is a simple image file viewer that just loads and displays an image. Again, let us first compile and run it from the command line. 1. Open a shell window. 2. Change to the directory CoreJavaBook/v1ch02/ImageViewer. 3. Enter the following: javac ImageViewer.java java ImageViewer A new program window pops up with our ImageViewer application (see Figure 2–9). Now, select File -> Open and look for an image file to open. (We supplied a couple of sample files in the same directory.) To close the program, click on the Close box in the title bar or pull down the system menu and close the program. (To compile and run this program inside a text editor or an integrated development environment, do the same as before. For example, for Emacs, choose JDE -> Compile, then choose JDE -> Run App.) Chapter 2. The Java Programming Environment Running a Graphical Application 29 Figure 2–9 Running the ImageViewer application We hope that you find this program interesting and useful. Have a quick look at the source code. The program is substantially longer than the first program, but it is not ter- ribly complex if you consider how much code it would take in C or C++ to write a simi- lar application. In Visual Basic, of course, it is easy to write or, rather, drag and drop, such a program. The JDK does not have a visual interface builder, so you need to write code for everything, as shown in Listing 2–2. You learn how to write graphical pro- grams like this in Chapters 7 through 9. Listin