Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL



“Live in fragments no longer, only connect.”

—Edgar Morgan Foster

Welcome to Java and Java for Programmers! At Deitel & Associates, we write programming language professional books and textbooks for Prentice Hall, deliver corporate training worldwide and develop Internet businesses. This book was a joy to create. It reflects recent changes to the Java language and to the preferred ways of teaching and learning programming.


Here’s some key features of Java for Programmers:

  • The book uses Java Standard Edition 6; we carefully audited the manuscript against the Java Language Specification.

  • The book is object-oriented throughout and the treatment of OOP is clear and accessible.

  • The early classes and objects presentation features Time, Employee and GradeBook class case studies that weave their way through multiple sections and chapters, gradually introducing deeper OO concepts.

  • The book contains a rich treatment of GUI and graphics.

  • We tuned our object-oriented presentation to use the latest version of the UML™ (Unified Modeling Language™)—the UML™ 2—the industry-standard graphical language for modeling object-oriented systems.

  • We include an optional OOD/UML 2 automated teller machine (ATM) case study in Chapters 18 and 10. An appendix contains the complete code implementation. Check out the back cover testimonials.

  • We include several substantial object-oriented web programming case studies.

  • Chapter 20, Accessing Databases with JDBC, includes JDBC 4 and uses the Java DB/Apache Derby and MySQL database management systems. The chapter features a database-driven address book case study that demonstrates prepared (pre-compiled) statements and JDBC 4’s automatic driver discovery.

  • Chapter 21, JavaServer Faces™ Web Applications, and Chapter 22, Ajax-Enabled JavaServer™ Faces Web Applications, introduce web application development with JavaServer Faces (JSF) technology and use it with the Netbeans IDE to build web applications quickly and easily. Chapter 21 includes examples on building web application GUIs, handling events, validating forms and session tracking. Chapter 22 discusses developing Ajax-enabled web applications. The chapter features a database-driven multitier web address book application that allows users to add contacts and search for contacts. The application uses Ajax-enabled JSF components to suggest contact names while the user types a name to locate.

  • Chapter 23, JAX-WS Web Services, uses a tools-based approach to creating and consuming web services—a signature Web 2.0 capability. Case studies include developing blackjack and airline reservation web services.

  • We use a tools-based approach for rapid web applications development; all the tools are available free for download.

  • We discuss key software engineering community concepts, such as Web 2.0, Ajax, SOA, web services, open source software, design patterns, refactoring, extreme programming, agile software development, rapid prototyping and more.

  • Chapter 18, Multithreading, benefitted from the guidance of Brian Goetz and Joseph Bowbeer—co-authors of Java Concurrency in Practice, Addison-Wesley, 2006.

  • We discuss the SwingWorker class for developing multithreaded user interfaces.

  • We discuss the Java Desktop Integration Components (JDIC), such as splash screens and interactions with the system tray.

  • We use the GroupLayout layout manager in the context of the GUI design tools provided by the NetBeans IDE to create portable GUIs that adhere to the underlying platform’s GUI design guidelines.

  • We present the JTable sorting and filtering capabilities which allow the user to re-sort the data in a JTable and filter it by regular expressions.

  • We present an in-depth treatment of generics and generic collections.

  • We discuss the StringBuilder class, which performs better than StringBuffer in non-threaded applications.

  • We present annotations, which reduce the amount of code you have to write to build applications.

Other recent Java features discussed in Java for Programmers include

  • Obtaining formatted input with class Scanner

  • Displaying formatted output with the System.out object’s printf method

  • Enhanced for statements to process array elements and collections

  • Declaring methods with variable-length argument lists

  • Using enum classes that declare sets of constants

  • Importing the static members of one class for use in another

  • Converting primitive-type values to type-wrapper objects and vice versa, using autoboxing and auto-unboxing, respectively

  • Using generics to create general models of methods and classes that can be declared once, but used with many different data types

  • Using the generics-enhanced data structures of the Collections API

  • Using the Concurrency API to implement multithreaded applications

  • Using JDBC RowSets to access data in a database

All of this has been carefully reviewed by distinguished industry developers and academics who worked with us on Java How to Program, 6/e and Java How to Program, 7/e—the book on which Java for Programmers is based.

As you read this book, if you have questions, send an e-mail to; we’ll respond promptly. For updates on this book and the status of all supporting Java software, and for the latest news on all Deitel publications and services, visit Sign up at for the free Deitel® Buzz Online e-mail newsletter and check out for our growing list of Resource Centers on key Java and related topics.

Using the UML 2 to Develop an Object-Oriented Design of an ATM

UML 2 has become the preferred graphical modeling language for designing object-oriented systems. All the UML diagrams in the book comply with the UML 2 specification. We use UML activity diagrams to demonstrate the flow of control in each of Java’s control statements, and we use UML class diagrams to visually represent classes and their inheritance relationships.

We include an optional (but highly recommended) case study on object-oriented design using the UML. The case study was reviewed by a distinguished team of OOD/UML industry professionals and academics, including leaders in the field from Rational (the creators of the UML) and the Object Management Group (responsible for evolving the UML). In the case study, we design and fully implement the software for a simple automated teller machine (ATM). The Software Engineering Case Study sections at the ends of Chapters 18 and 10 present a carefully paced introduction to object-oriented design using the UML. We introduce a concise, simplified subset of the UML 2, then guide you through a design experience. The case study is not an exercise—it’s an end-to-end learning experience that concludes with a detailed walkthrough of the complete Java code. In the first of the case study sections at the end of Chapter 1, we introduce basic concepts and terminology of OOD. In the optional Software Engineering Case Study sections at the ends of Chapters 25, we consider more substantial issues, as we undertake a challenging problem with the techniques of OOD. We analyze a typical requirements document that specifies a system to be built, determine the objects needed to implement that system, determine the attributes these objects need to have, determine the behaviors these objects need to exhibit, and specify how the objects must interact with one another to meet the system requirements. In an appendix, we include a complete Java code implementation of the object-oriented system that we designed in the earlier chapters. We employ a carefully developed, incremental object-oriented design process to produce a UML 2 model for our ATM system. From this design, we produce a substantial working Java implementation using key object-oriented programming notions, including classes, objects, encapsulation, visibility, composition, inheritance and polymorphism.

Dependency Chart

The chart on the next page shows the dependencies among the chapters. Chapters 114 form an accessible introduction to object-oriented programming. Chapters 11, 12 and 17 form a substantial GUI and graphics sequence. Chapters 2023 form a clear database-intensive web development sequence.

  1. Chapter 20 is dependent on Chapter 11 for GUI used in one example.

  2. The large case study at the end of Chapter 19 depends on Chapter 17 for GUI and Chapter 18 for multithreading.

  3. Chapter 23 is dependent on Chapter 11 for GUI used in one example, and Chapters 1516 for one example.

Teaching Approach

Java for Programmers contains a rich collection of examples. The book concentrates on the principles of good software engineering and stresses program clarity. We teach by example. We are educators who teach leading-edge topics in government, industry, military and academic classrooms worldwide.

Live-Code Approach. Java for Programmers is loaded with “live-code” examples—by this we mean that each new concept is presented in the context of a complete working Java application that is immediately followed by one or more actual executions showing the program’s inputs and outputs.

Syntax Shading. We syntax shade all the Java code, similar to the way Java integrated-development environments and code editors syntax color code. This improves code read-ability—an important goal, given that this book contains over 18,000 lines of code in complete, working Java programs. Our syntax-shading conventions are as follows:

comments appear in italic
keywords appear in bold italic
errors and ASP.NET script delimiters appear in bold black
constants and literal values appear in bold gray
all other code appears in plain black

Code Highlighting. We place white rectangles around each program’s key code segments.

Using Fonts for Emphasis. We place the key terms and the index’s page reference for each defining occurrence in bold italic text for easier reference. We emphasize on-screen components in the bold Helvetica font (e.g., the File menu) and emphasize Java program text in the Lucida font (for example, int x = 5).

Web Access. All of the source-code examples for Java for Programmers are available for download from:

Objectives. Each chapter begins with a statement of objectives.

Quotations. The learning objectives are followed by quotations. We hope that you enjoy relating these to the chapter material.

Illustrations/Figures. Abundant charts, tables, line drawings, programs and program output are included. We model the flow of control in control statements with UML activity diagrams. UML class diagrams model the fields, constructors and methods of classes. We make extensive use of six major UML diagram types in the optional OOD/UML 2 ATM case study.

Programming Tips. We include programming tips to help you focus on important aspects of program development. These tips and practices represent the best we’ve gleaned from a combined seven decades of programming and teaching experience.

Good Programming Practice

The Good Programming Practices call attention to techniques that will help you produce programs that are clearer, more understandable and more maintainable.

Common Programming Error

Pointing out these Common Programming Errors reduces the likelihood that you’ll make the same mistakes.

Error-Prevention Tip

These tips contain suggestions for exposing bugs and removing them from your programs; many describe aspects of Java that prevent bugs from getting into programs in the first place.

Performance Tip

These tips highlight opportunities for making your programs run faster or minimizing the amount of memory that they occupy.

Portability Tip

The Portability Tips to help you write code that will run on a variety of platforms.

Software Engineering Observation

The Software Engineering Observations highlight architectural and design issues that affect the construction of software systems, especially large-scale systems.

Look-and-Feel Observation

The Look-and-Feel Observations highlight graphical-user-interface conventions. These observations help you design attractive, user-friendly graphical user interfaces that conform to industry norms.

Wrap-Up Section. Each of the chapters ends with a “wrap-up” section that recaps the chapter content and transitions to the next chapter.

Thousands of Index Entries. We have included an extensive index which is especially useful when you use the book as a reference.

Software Used with Java for Programmers

Many Java development tools are available for purchase, but you do not need any of these to get started with Java. We wrote most of the examples in Java for Programmers using the free Java Standard Edition Development Kit (JDK) 6. The current JDK version (and separately its documentation) can be downloaded from Sun’s Java website We also used the Netbeans IDE in several chapters. Net-beans is available as a bundle with the JDK from the preceding website or you can download it separately from You can find additional resources and software downloads in our Java SE 6 Resource Center at:

Deitel® Buzz Online Free E-mail Newsletter

Each week, the Deitel® Buzz Online announces our latest Resource Center(s) and includes commentary on industry trends and developments, links to free articles and resources from our published books and upcoming publications, product-release schedules, errata, challenges, anecdotes, information on our corporate instructor-led training courses and more. It’s also a good way for you to keep posted about issues related to Java for Programmers. To subscribe, visit

The Deitel Online Resource Centers

Our website provides more than 100 Resource Centers on various topics including programming languages, software development, Web 2.0, Internet business and open-source projects—see the list of Resource Centers in the first few pages of this book or visit The Resource Centers evolve out of the research we do to support our books and business endeavors. We’ve found many exceptional resources online, including tutorials, documentation, software downloads, articles, blogs, podcasts, videos, code samples, books, e-books and more—most of them are free. Each week we announce our latest Resource Centers in our newsletter, the Deitel® Buzz Online ( Some of the Resource Centers you might find helpful while studying this book are Java SE 6, Java, Java Assessment and Certification, Java Design Patterns, Java EE 5, Code Search Engines and Code Sites, Game programming, Programming Projects and many more.


It is a great pleasure to acknowledge the efforts of many people whose names may not appear on the cover, but whose hard work, cooperation, friendship and understanding were crucial to the production of the book. Many people at Deitel & Associates, Inc. devoted long hours to this project—thanks especially to Abbey Deitel and Barbara Deitel.

We’d also like to thank two participants of our Honors Internship program who contributed to this publication—Megan Schuster, a computer science major at Swarthmore College, and Henry Klementowicz, a computer science major at Columbia University.

We are fortunate to have worked on this project with the talented and dedicated team of publishing professionals at Prentice Hall. We appreciate the extraordinary efforts of Mark Taub, Editor-in-Chief of Prentice Hall Professional; John Fuller, Managing Editor of Prentice Hall Professional; and Marcia Horton, Editorial Director of Prentice Hall’s Engineering and Computer Science Division. Sandra Schroeder did a wonderful job designing the book’s cover. Scott Disanno and Robert Engelhardt did a marvelous job managing the book’s production.

This book was adapted from our book Java How to Program, 7/e. We wish to acknowledge the efforts of our reviewers on that book. Adhering to a tight time schedule, they scrutinized the text and the programs, providing countless suggestions for improving the accuracy and completeness of the presentation.

Java How to Program, 7/e Reviewers (including 6/e Post-Publication Reviewers)

Sun Microsystems Reviewers: Lance Andersen (JDBC/Rowset Specification Lead, Java SE Engineering), Ed Burns, Ludovic Champenois (Sun’s Application Server for Java EE programmers with Sun Application Server and tools—NetBeans, Studio Enterprise and Studio Creator), James Davidson, Vadiraj Deshpande (Java Enterprise System Integration Group, Sun Microsystems India), Sanjay Dhamankar (Core Developer Platform Group), Jesse Glick (NetBeans Group), Brian Goetz (author of Java Concurrency in Practice, Addison-Wesley, 2006), Doug Kohlert (Web Technologies and Standards Group), Sandeep Konchady (Java Software Engineering Organization), John Morrison (Sun Java System Portal Server Product Group), Winston Prakash, Brandon Taylor (SysNet group within the Software Division), and Jayashri Visvanathan (Sun Microsystems Java Studio Creator Team). Academic and Industry Reviewers: Akram Al-Rawi (King Faisal University), Mark Biamonte (DataDirect), Ayad Boudiab (International School of Choueifat, Lebanon), Joe Bowbeer (Mobile App Consulting), Harlan Brewer (Select Engineering Services), Marita Ellixson (Eglin AFB, Indiana Wesleyan University, Lead Facilitator), John Goodson (DataDirect), Anne Horton (Lockheed Martin), Terrell Regis Hull (Logicalis Integration Solutions), Clark Richey (RABA Technologies, LLC, Java Sun Champion), Manfred Riem (Utah Interactive, LLC, Java Sun Champion), Karen Tegtmeyer (Model Technologies, Inc.), David Wolff (Pacific Lutheran University), and Hua Yan (Borough of Manhattan Community College, City University of New York). Java How to Program, 6/e Post-Publication Reviewers: Anne Horton (Lockheed Martin), William Martz (University of Colorado at Colorado Springs), Bill O’Farrell (IBM), Jeffry Babb (Virginia Commonwealth University), Jeffrey Six (University of Delaware, Adjunct Faculty), Jesse Glick (Sun Microsystems), Karen Tegtmeyer (Model Technologies, Inc.), Kyle Gabhart (L-3 Communications), Marita Ellixson (Eglin AFB, Indiana Wesleyan University, Lead Facilitator), and Sean Santry (Independent Consultant).

These reviewers scrutinized every aspect of the text and made countless suggestions for improving the accuracy and completeness of the presentation.

Well, there you have it! Java is a powerful programming language that will help you write programs quickly and effectively. It scales nicely into the realm of enterprise systems development to help organizations build their critical information systems. As you read the book, we would sincerely appreciate your comments, criticisms, corrections and suggestions for improving the text. Please address all correspondence to:

We’ll respond promptly, and post corrections and clarifications on:

We hope you find Java for Programmers helpful in your professional endeavors.

Paul J. Deitel

Dr. Harvey M. Deitel

About the Authors

Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate of MIT’s Sloan School of Management, where he studied Information Technology. He holds the Java Certified Programmer and Java Certified Developer certifications, and has been designated by Sun Microsystems as a Java Champion. Through Deitel & Associates, Inc., he has delivered Java, C, C++, C#, Visual Basic and Internet programming courses to industry clients, including Cisco, IBM, Sun Microsystems, Dell, Lucent Technologies, Fidelity, NASA at the Kennedy Space Center, the National Severe Storm Laboratory, White Sands Missile Range, Rogue Wave Software, Boeing, Stratus, Cambridge Technology Partners, Open Environment Corporation, One Wave, Hyperion Software, Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, Invensys and many more. He has also lectured on Java and C++ for the Boston Chapter of the Association for Computing Machinery. He and his co-author, Dr. Harvey M. Deitel, are the world’s bestselling programming language textbook authors.

Dr. Harvey M. Deitel, Chairman and Chief Strategy Officer of Deitel & Associates, Inc., has 47 years of academic and industry experience in the computer field. Dr. Deitel earned B.S. and M.S. degrees from the MIT and a Ph.D. from Boston University. He has 20 years of college teaching experience, including earning tenure and serving as the Chairman of the Computer Science Department at Boston College before founding Deitel & Associates, Inc., with his son, Paul J. Deitel. He and Paul are the co-authors of several dozen books and multimedia packages and they are writing many more. With translations published in Japanese, German, Russian, Spanish, Traditional Chinese, Simplified Chinese, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish, the Deitels’ texts have earned international recognition. Dr. Deitel has delivered hundreds of professional seminars to major corporations, academic institutions, government organizations and the military.

About Deitel & Associates, Inc.

Deitel & Associates, Inc., is an internationally recognized corporate training and authoring organization specializing in computer programming languages, Internet and web software technology, object-technology education and Internet business development through its Web 2.0 Internet Business Initiative. The company provides instructor-led courses on major programming languages and platforms, such as Java, C++, C, Visual C#, Visual Basic, Visual C++, XML, object technology, Internet and web programming, and a growing list of additional programming and software-development related courses. The founders of Deitel & Associates, Inc., are Paul J. Deitel and Dr. Harvey M. Deitel. The company’s clients include many of the world’s largest companies, government agencies, branches of the military, and academic institutions. Through its 33-year publishing partnership with Prentice Hall, Deitel & Associates, Inc., publishes leading-edge programming textbooks, professional books, interactive multimedia Cyber Classrooms, LiveLessons DVD-based and web-based video courses, and e-content for popular course-management systems. Deitel & Associates, Inc., and the authors can be reached via e-mail at:

To learn more about Deitel & Associates, Inc., its publications and its worldwide Dive Into® Series Corporate Training curriculum, visit:

and subscribe to the free Deitel® Buzz Online e-mail newsletter at:

Individuals wishing to purchase Deitel books, and LiveLessons DVD and web-based training courses can do so through Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Prentice Hall. For more information, visit

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint