Home > Store

Core Java 2, Volume I--Fundamentals, 6th Edition

Register your product to gain access to bonus material or receive a coupon.

Core Java 2, Volume I--Fundamentals, 6th Edition


  • Sorry, this book is no longer in print.
Not for Sale



  • NEW - Fully updated for the latest enhancements in Java 2, Standard Edition, Version 1.4—Including regular expressions, New I/O, chained exceptions, logging, Preference Classes, the new Swing focus architecture, and much more.
    • Helps students rapidly master the most valuable features incorporated in the latest version of Java.

  • NEW - Extensive library of complete, robust program code, updated for the latest JDK 1.4 features and techniques.
    • Helps students learn how to build production-quality software with Java 1.4.

  • NEW - Review questions and practice exercises.
    • Helps students master the latest Java 1.4 features.

  • Definitive coverage of object-oriented Java programming and the Java event model.
    • Gives students a deeper understanding of foundational aspects of Java programming that will translate into better software design and more reliable programs.

  • All code downloadable from companion Web site—Provides a single source for the latest versions of all code associated with the book, including any fixes or updates. URL: www.prenhall.com/horstmann.
    • Gives students easy access to the book's code wherever and whenever they need it.

  • First volume of a 2-Volume Set—Complemented by Core Java, Volume II, Fifth Edition, which focuses on JDK 1.4 enterprise features and advanced user interface development.
    • Gives students comprehensive understanding of contemporary Java development.


  • Copyright 2002
  • Edition: 6th
  • Book
  • ISBN-10: 0-13-047177-1
  • ISBN-13: 978-0-13-047177-2

The best-selling guide for serious programmers of Java technology—fully updated for the Java 1.4 SDK!

  • The experienced developer's guide to the Java program environment-now fully updated for the Java(tm) 1.4 SDK.
  • New coverage: regular expressions, New I/O, assertions, Preferences, Swing enhancements, logging, and more
  • Even more of the robust code examples professional programmers need

Ask any experienced Java technology programmer: Core Java delivers the real-world guidance you need to accomplish even the most challenging tasks. That's why it's been an international best seller for seven straight years. Core Java II, Volume 1 covers the fundamentals of Java 2, Standard Edition, Version 1.4, including major enhancements ranging from regular expressions to high-performance I/O. You'll find state-of-the-art discussions of object-oriented Java platform development, updated coverage of Swing user interface development, and much more. Best of all, this new Sixth Edition delivers even more of the robust, real-world programs previous editions are famous for—updated to reflect the latest SDK features and improvements!

State-of-the-art information for Java platform developers, including:

  • Swing GUI development—including input validation and other enhancements
  • Building reliable code—including chained exceptions, stack frames, assertions, and logging
  • The high-performance New I/O API: memory-mapped files, file locking, and character set encoders/decoders
  • Regular expressions using the powerful new java.util.regex package
  • Java 1.4 platform Preference Class: the new cross-platform repository for configuration information
  • Dynamic proxy classes, inner classes, the Java platform event model, streams, file management, and more


Source Code

Untitled Document Download the source code related to this title.

Sample Content

Online Sample Chapters

Fundamental Programming Structures in Java

Inside Java Interfaces and Inner Classes

Downloadable Sample Chapter

Click here for a sample chapter for this book: 0130471771.pdf

Table of Contents


To the Reader. About This Book. Conventions. Sample Code.


1. An Introduction to Java.

Java as a Programming Tool. Advantages of Java. The Java “White Paper” Buzzwords. Java and the Internet. A Short History of Java. Common Misconceptions About Java.

2. The Java Programming Environment.

Installing the Java Software Development Kit. Development Environments. Using the Command Line Tools. Using an Integrated Development Environment. Compiling and Running Programs from a Text Editor. Graphical Applications. Applets.

3. Fundamental Programming Structures in Java.

A Simple Java Program. Comments. Data Types. Variables. Assignments and Initializations. Operators. Strings. Control Flow. Arrays.

4. Objects and Classes.

Introduction to Object-Oriented Programming. Using Existing Classes. Building Your Own Classes. Static Fields and Methods. Method Parameters. Object Construction. Packages. Documentation Comments. Class Design Hints.

5. Inheritance.

Extending Classes. Object: The Cosmic Superclass. The Class Class. Reflection. Design Hints for Inheritance.

6. Interfaces and Inner Classes.

Interfaces. Object Cloning. Inner Classes. Proxies.

7. Graphics Programming.

Introduction to Swing. Creating a Frame. Frame Positioning. Displaying Information in a Panel. 2D Shapes. Colors. Text and Fonts. Images.

8. Event Handling.

Basics of Event Handling. The AWT Event Hierarchy. Semantic and Low-Level Events in the AWT. Low-Level Event Types. Actions. Multicasting. The Event Queue.

9. User Interface Components with Swing.

The Model-View-Controller Design Pattern. An Introduction to Layout Management. Text Input. Making Choices. Menus. Sophisticated Layout Management. Dialog Boxes.

10. Deploying Applets and Applications.

Applet Basics. The Applet HTML Tags and Attributes. Multimedia. The Applet Context. JAR Files. Packaging Applications. Java Web Start. Storing Application Preferences.

11. Exceptions and Debugging.

Dealing with Errors. Catching Exceptions. Some Tips on Using Exceptions. Logging. Assertions. Debugging Techniques. Using a Debugger.

12. Streams and Files.

Streams. The Complete Stream Zoo. ZIP File Streams. Putting Streams to Use. Object Streams. File Management. New I/O. Regular Expressions.





To the Reader

In late 1995, the Java programming language burst onto the Internet scene and gainedinstant celebrity status. The promise of Java technology was that it would become theuniversal glue that connects users with information, whether that information comes fromWeb 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 engineeredlanguage that has gained acceptance by all major vendors, except for Microsoft. Its built-insecurity and safety features are reassuring both to programmers and to the users of Javaprograms. Java even has built-in support that makes advanced programming tasks, such asnetwork programming, database connectivity, and multithreading, straightforward.

Since 1995, Sun Microsystems has released five major revisions of the Java SoftwareDevelopment Kit. Over the course of the last 7 years, the Application ProgrammingInterface (API) has grown from about 200 to just over 3,000 classes. The API now spanssuch diverse areas as user interface construction, database management, internationalization,security, and XML processing.

The book you have in your hand is the first volume of the sixth edition of the Core Java book.With the publishing of each edition, the book followed the release of the Java Software DevelopmentKit as quickly as possible, and each time, we rewrote the book to take advantage of thenewest Java features.

As with the previous editions of this book, we still target serious programmers who want to putJava to work on real projects. We still guarantee no nervous text or dancing tooth-shaped characters.We think of you, our reader, as a programmer with a solid background in a programming language.But you do not need to know C++ or object-oriented programming. Based on the responseswe have received to the earlier editions of this book, we remain confident that experienced VisualBasic, C, or COBOL programmers will have no trouble with this book. (You don't even need anyexperience in building graphical user interfaces for Windows, Unix, or the Macintosh.)

What we do is assume you want to:

  • Write real code to solve real problems;


  • Don't like books filled with toy examples (such as kitchen appliances or fruit trees).

In this book you will find lots of sample code that demonstrates almost every language andlibrary feature that we discuss. We kept the sample programs purposefully simple to focuson 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 Javaputs 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
  • Stream input/output and object serialization

We still don't spend much time on the fun but less serious kind of Java programs whosesole purpose is to liven up your Web page. There are quite a few sources for this kindof material already—we recommend John Pew's book Instant Java, also published bySun Microsystems Press.

Finally, with the explosive growth of the Java class library, a one-volume treatment of allthe features of Java that serious programmers need to know is no longer possible. Hence,we decided to break the book up into two volumes. The first volume, which you hold inyour hands, concentrates on the fundamental concepts of the Java language, along with thebasics of user-interface programming. The second volume goes further into the enterprisefeatures and advanced user-interface programming. It includes detailed discussions of:

  • Multithreading
  • Network programming
  • Distributed objects
  • Collection classes
  • Databases
  • Advanced graphics
  • Advanced GUI components
  • Internationalization
  • Native methods
  • JavaBeans
  • XML Processing

When writing a book, errors and inaccuracies are inevitable. We'd very much like to knowabout them. But, of course, we'd prefer to learn about each of them only once. We have putup a list of frequently asked questions, bugs fixes, and workarounds in a Web page athttp://www.horstmann.com/corejava.html. Strategically placed at the end of the FAQ(to encourage you to read through it first) is a form you can use to report bugs and suggestimprovements. Please don't be disappointed if we don't answer every query or if we don'tget back to you immediately. We do read all e-mail and appreciate your input to makefuture editions of this book clearer and more informative.

We hope that you find this book enjoyable and helpful in your Java programming.

About This Book

Chapter 1 gives an overview of the capabilities of Java that set it apart from other pro-gramminglanguages. We explain what the designers of the language set out to do andto what extent they succeeded. Then, we give a short history of how Java came intobeing and how it has evolved.

In Chapter 2, we tell you how to download and install the Java SDK from http://java.sun.com/j2se. We also describe how to download and install the Core Java program examples forthis book from www.phptr.com/corejava. Then we guide you through compiling and runningthree typical Java programs, a console application, a graphical application, and an applet.

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 becausethe syntax for these language features is essentially the same as in C. If you come from a non-Cbackground such as Visual Basic or COBOL, you will want to read this chapter carefully.

Object-oriented programming (OOP) is now in the mainstream of programming practice, andJava is completely object-oriented. Chapter 4 introduces encapsulation, the first of two fundamentalbuilding blocks of object orientation, and the Java language mechanism to implement it,that is, classes and methods. In addition to the rules of the Java language, we also give advice onsound OOP design. Finally, we cover the marvelous javadoc tool that formats your code commentsas a set of hyperlinked web pages. If you are familiar with C++, then you can browsethrough this chapter quickly. Programmers coming from a non-object-oriented backgroundshould expect to spend some time mastering OOP 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 yourneeds. This is a fundamental technique for programming in Java. The inheritance mechanism inJava is quite similar to that in C++. Once again, C++ programmers can focus on the differencesbetween the languages.

Chapter 6 shows you how to use Java's notion of an interface. Interfaces let you go beyond thesimple inheritance model of Chapter 5. Mastering interfaces allows you to have full access tothe power of Java's completely object-oriented approach to programming. We also cover auseful technical feature of Java called inner classes. Inner classes help make your code cleanerand more concise.

In Chapter 7, we begin application programming in earnest. We show how you can makewindows, how to paint on them, how to draw with geometric shapes, how to format text inmultiple fonts, and how to display images.

Chapter 8 is a detailed discussion of the event model of the AWT, the abstract windows toolkit.(We discuss the event model that was added to Java 1.1, not the obsolete and simplistic 1.0event model.) You'll see how to write the code that responds to events like mouse clicks or keypresses. Along the way you'll see how to handle basic GUI elements like buttons and panels.

Chapter 9 discusses the Swing GUI toolkit in great detail. The Swing toolkit allows you to builda cross-platform graphical user interface. You'll learn all about the various kinds of buttons, textcomponents, borders, sliders, list boxes, menus, and dialog boxes. However, some of the moreadvanced components are discussed in Volume 2.

After you finish Chapter 9, you finally have all mechanisms in place to write applets, those mini-programsthat can live inside a Web page, and so applets are the topic of Chapter 10. We showyou a number of useful and fun applets, but more importantly, we look at applets as a method ofprogram deployment. We then describe how to package applications in JAR files, and how todeliver applications over the internet with the Java Web Start mechanism. Finally, we explain howJava 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 thatbad things can happen to good programs. For example, a network connection can becomeunavailable in the middle of a file download, a disk can fill up, and so on. Exceptions giveyou 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 stillmight fail to work as expected. In the second half of this chapter, we give you a large numberof useful debugging tips. Finally, we guide you through sample sessions with varioustools: the JDB debugger, the debugger of an integrated development environment, aprofiler, a code coverage testing tool, and the AWT robot.

We finish the book with input and output handling. In Java, all I/O is handled through so-calledstreams. Streams let you deal in a uniform manner with communicating with any source of data,such as files, network connections, or memory blocks. We include detailed coverage of the readerand writer classes, which make it easy to deal with Unicode. We show you what goes on underthe hood when you use the object serialization mechanism, which makes saving and loadingobjects easy and convenient. Finally, we cover several libraries that have been added to SDK 1.4:the "new I/O" classes that contain support for advanced and more efficient file operations, andthe regular expression library.

An appendix lists the Java language keywords.

Sample Code

The web site for this book at http://www.phptr.com/corejava contains all sample codefrom the book, in compressed form. You can expand the file either with one of the fam-iliarunzipping programs or simply with the jar utility that is part of the Java SoftwareDevelopment Kit. See Chapter 2 for more information about installing the SoftwareDevelopment Kit and the sample code.



Page 144
The code for the Card class is misaligned. It should be
public class Card
   public Card(int aValue, int aSuit) { . . . }
   public int getValue() { . . . }
   public int getSuit() { . . . }

   private int value;
   private int suit;

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020