图书简介:
Contents
Chapter 1 Introduction to Computers and Java 1
1.1 Introduction 2
1.2 Computers: Hardware and Software 4
1.3 Data Hierarchy 5
1.4 Computer Organization 6
1.5 Machine Languages, Assembly Languages and High-Level Languages 7
1.6 Introduction to Object Technology 8
1.7 Operating Systems 10
1.8 Programming Languages 12
1.9 Java and a Typical Java Development Environment 14
1.10 Test-Driving a Java Application 17
1.11 Web 2.0: Going Social 21
1.12 Software Technologies 23
1.13 Keeping Up-to-Date with Information Technologies 24
1.14 Wrap-Up 24
Chapter 2 Introduction to Java Applications 29
2.1 Introduction 29
2.2 Your First Program in Java: Printing a Line of Text 30
2.3 Modifying Your First Java Program 35
2.4 Displaying Text with printf 36
2.5 Another Application: Adding Integers 37
2.6 Memory Concepts 41
2.7 Arithmetic 42
2.8 Decision Making: Equality and Relational Operators 45
2.9 Wrap-Up 48
Chapter 3 Introduction to Classes, Objects, Methods and Strings 58
3.1 Introduction 58
3.2 Declaring a Class with a Method and Instantiating an Object of a Class 59
3.3 Declaring a Method with a Parameter 62
3.4 Instance Variables, set Methods and get Methods 64
3.5 Primitive Types vs. Reference Types 68
3.6 Initializing Objects with Constructors 69
3.7 Floating-Point Numbers and Type double 71
3.8 (Optional) GUI and Graphics Case Study: Using Dialog Boxes 75
3.9 Wrap-Up 77
Chapter 4 Control Statements: Part 1 84
4.1 Introduction 85
4.2 Algorithms 85
4.3 Pseudocode 85
4.4 Control Structures 86
4.5 if Single-Selection Statement 88
4.6 if…else Double-Selection Statement 89
4.7 while Repetition Statement 92
4.8 Formulating Algorithms: Counter-Controlled Repetition 93
4.9 Formulating Algorithms: Sentinel-Controlled Repetition 97
4.10 Formulating Algorithms: Nested Control Statements 103
4.11 Compound Assignment Operators 107
4.12 Increment and Decrement Operators 107
4.13 Primitive Types 110
4.14 (Optional) GUI and Graphics Case Study: Creating Simple Drawings 110
4.15 Wrap-Up 113
Chapter 5 Control Statements: Part 2 126
5.1 Introduction 126
5.2 Essentials of Counter-Controlled Repetition 127
5.3 for Repetition Statement 128
5.4 Examples Using the for Statement 131
5.5 do…while Repetition Statement 135
5.6 switch Multiple-Selection Statement 136
5.7 break and continue Statements 142
5.8 Logical Operators 144
5.9 Structured Programming Summary 148
5.10 (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals 152
5.11 Wrap-Up 154
Chapter 6 Methods: A Deeper Look 164
6.1 Introduction 165
6.2 Program Modules in Java 165
6.3 static Methods, static Fields and Class Math 166
6.4 Declaring Methods with Multiple Parameters 168
6.5 Notes on Declaring and Using Methods 171
6.6 Method-Call Stack and Activation Records 172
6.7 Argument Promotion and Casting 172
6.8 Java API Packages 173
6.9 Case Study: Random-Number Generation 175
6.10 Case Study: A Game of Chance; Introducing Enumerations 179
6.11 Scope of Declarations 182
6.12 Method Overloading 184
6.13 (Optional) GUI and Graphics Case Study: Colors and Filled Shapes 186
6.14 Wrap-Up 188
Chapter 7 Arrays and ArrayLists 201
7.1 Introduction 202
7.2 Arrays 202
7.3 Declaring and Creating Arrays 203
7.4 Examples Using Arrays 204
7.5 Case Study: Card Shuffling and Dealing Simulation 212
7.6 Enhanced for Statement 215
7.7 Passing Arrays to Methods 216
7.8 Case Study: Class GradeBook Using an Array to Store Grades 219
7.9 Multidimensional Arrays 223
7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 226
7.11 Variable-Length Argument Lists 230
7.12 Using Command-Line Arguments 232
7.13 Class Arrays 233
7.14 Introduction to Collections and Class ArrayList 235
7.15 (Optional) GUI and Graphics Case Study: Drawing Arcs 237
7.16 Wrap-Up 240
Chapter 8 Classes and Objects: A Deeper Look 259
8.1 Introduction 260
8.2 Time Class Case Study 260
8.3 Controlling Access to Members 263
8.4 Referring to the Current Object’s Members with the this Reference 264
8.5 Time Class Case Study: Overloaded Constructors 266
8.6 Default and No-Argument Constructors 270
8.7 Notes on Set and Get Methods 271
8.8 Composition 272
8.9 Enumerations 274
8.10 Garbage Collection and Method finalize 276
8.11 static Class Members 277
8.12 static Import 280
8.13 final Instance Variables 281
8.14 Time Class Case Study: Creating Packages 282
8.15 Package Access 286
8.16 (Optional) GUI and Graphics Case Study: Using Objects with Graphics 287
8.17 Wrap-Up 290
Chapter 9 Object-Oriented Programming: Inheritance 298
9.1 Introduction 298
9.2 Superclasses and Subclasses 299
9.3 protected Members 301
9.4 Relationship between Superclasses and Subclasses 302
9.5 Constructors in Subclasses 318
9.6 Software Engineering with Inheritance 319
9.7 Class Object 320
9.8 (Optional) GUI and Graphics Case Study: Displaying Text and Images Using Labels 320
9.9 Wrap-Up 322
Chapter 10 Object-Oriented Programming: Polymorphism 326
10.1 Introduction 327
10.2 Polymorphism Examples 328
10.3 Demonstrating Polymorphic Behavior 329
10.4 Abstract Classes and Methods 331
10.5 Case Study: Payroll System Using Polymorphism 333
10.6 final Methods and Classes 346
10.7 Case Study: Creating and Using Interfaces 346
10.8 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 356
10.9 Wrap-Up 357
Chapter 11 Exception Handling: A Deeper Look 362
11.1 Introduction 363
11.2 Example: Divide by Zero without Exception Handling 363
11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 365
11.4 When to Use Exception Handling 369
11.5 Java Exception Hierarchy 369
11.6 finally Block 372
11.7 Stack Unwinding and Obtaining Information from an Exception Object 375
11.8 Chained Exceptions 378
11.9 Declaring New Exception Types 379
11.10 Preconditions and Postconditions 380
11.11 Assertions 381
11.12 (New in Java SE 7) Multi-catch: Handling Multiple Exceptions in One catch 382
11.13 (New in Java SE 7) try-with-Resources: Automatic Resource Deallocation 382
11.14 Wrap-Up 383
Chapter 12 ATM Case Study, Part 1: Object-Oriented Design with the UML 388
12.1 Case Study Introduction 388
12.2 Examining the Requirements Document 389
12.3 Identifying the Classes in a Requirements Document 395
12.4 Identifying Class Attributes 400
12.5 Identifying Objects’ States and Activities 404
12.6 Identifying Class Operations 407
12.7 Indicating Collaboration Among Objects 412
12.8 Wrap-Up 418
Chapter 13 ATM Case Study Part 2: Implementing an Object-Oriented Design 421
13.1 Introduction 422
13.2 Starting to Program the Classes of the ATM System 422
13.3 Incorporating Inheritance and Polymorphism into the ATM System 425
13.4 ATM Case Study Implementation 431
13.5 Wrap-Up 449
Chapter 14 GUI Components: Part 1 451
14.1 Introduction 452
14.2 Java’s New Nimbus Look-and-Feel 453
14.3 Simple GUI-Based Input/Output with JOptionPane 454
14.4 Overview of Swing Components 456
14.5 Displaying Text and Images in a Window 457
14.6 Text Fields and an Introduction to Event Handling with Nested Classes 461
14.7 Common GUI Event Types and Listener Interfaces 466
14.8 How Event Handling Works 467
14.9 JButton 468
14.10 Buttons That Maintain State 471
14.11 JComboBox; Using an Anonymous Inner Class for Event Handling 476
14.12 JList 479
14.13 Multiple-Selection Lists 480
14.14 Mouse Event Handling 482
14.15 Adapter Classes 486
14.16 JPanel Subclass for Drawing with the Mouse 488
14.17 Key Event Handling 491
14.18 Introduction to Layout Managers 493
14.19 Using Panels to Manage More Complex Layouts 501
14.20 JTextArea 502
14.21 Wrap-Up 504
Chapter 15 Graphics and Java 2D 517
15.1 Introduction 517
15.2 Graphics Contexts and Graphics Objects 519
15.3 Color Control 520
15.4 Manipulating Fonts 525
15.5 Drawing Lines, Rectangles and Ovals 529
15.6 Drawing Arcs 531
15.7 Drawing Polygons and Polylines 533
15.8 Java 2D API 535
15.9 Wrap-Up 541
Chapter 16 Strings, Characters and Regular Expressions 549
16.1 Introduction 550
16.2 Fundamentals of Characters and Strings 550
16.3 Class String 551
16.4 Class StringBuilder 561
16.5 Class Character 566
16.6 Tokenizing Strings 570
16.7 Regular Expressions, Class Pattern and Class Matcher 571
16.8 Wrap-Up 577
Chapter 17 Files, Streams and Object Serialization 588
17.1 Introduction 589
17.2 Files and Streams 589
17.3 Class File 590
17.4 Sequential-Access Text Files 593
17.5 Object Serialization 605
17.6 Additional java.io Classes 612
17.7 Opening Files with JFileChooser 614
17.8 Wrap-Up 617
Chapter 18 Recursion 625
18.1 Introduction 625
18.2 Recursion Concepts 626
18.3 Example Using Recursion: Factorials 627
18.4 Example Using Recursion: Fibonacci Series 630
18.5 Recursion and the Method-Call Stack 632
18.6 Recursion vs. Iteration 633
18.7 Towers of Hanoi 635
18.8 Fractals 636
18.9 Recursive Backtracking 644
18.10 Wrap-Up 645
Chapter 19 Searching, Sorting and Big O 652
19.1 Introduction 652
19.2 Searching Algorithms 653
19.3 Sorting Algorithms 660
19.4 Wrap-Up 671
Chapter 20 Generic Collections 676
20.1 Introduction 677
20.2 Collections Overview 677
20.3 Type-Wrapper Classes for Primitive Types 678
20.4 Autoboxing and Auto-Unboxing 678
20.5 Interface Collection and Class Collections 679
20.6 Lists 679
20.7 Collections Methods 686
20.8 Stack Class of Package java.util 694
20.9 Class PriorityQueue and Interface Queue 696
20.10 Sets 697
20.11 Maps 699
20.12 Properties Class 702
20.13 Synchronized Collections 704
20.14 Unmodifiable Collections 705
20.15 Abstract Implementations 706
20.16 Wrap-Up 706
Chapter 21 Generic Classes and Methods 712
21.1 Introduction 712
21.2 Motivation for Generic Methods 713
21.3 Generic Methods: Implementation and Compile-Time Translation 715
21.4 Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as
the Return Type 717
21.5 Overloading Generic Methods 720
21.6 Generic Classes 720
21.7 Raw Types 726
21.8 Wildcards in Methods That Accept Type Parameters 729
21.9 Generics and Inheritance: Notes 732
21.10 Wrap-Up 733
Chapter 22 Custom Generic Data Structures 737
22.1 Introduction 737
22.2 Self-Referential Classes 738
22.3 Dynamic Memory Allocation 739
22.4 Linked Lists 739
22.5 Stacks 747
22.6 Queues 750
22.7 Trees 752
22.8 Wrap-Up 757
Chapter 23 Applets and Java Web Start 767
23.1 Introduction 767
23.2 Sample Applets Provided with the JDK 768
23.3 Simple Java Applet: Drawing a String 772
23.4 Applet Life-Cycle Methods 775
23.5 Initialization with Method init 776
23.6 Sandbox Security Model 777
23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 778
23.8 Wrap-Up 783
Chapter 24 Multimedia: Applets and Applications 788
24.1 Introduction 788
24.2 Loading, Displaying and Scaling Images 789
24.3 Animating a Series of Images 794
24.4 Image Maps 799
24.5 Loading and Playing Audio Clips 801
24.6 Playing Video and Other Media with Java Media Framework 804
24.7 Wrap-Up 807
24.8 Web Resources 807
Chapter 25 GUI Components: Part 2 815
25.1 Introduction 815
25.2 JSlider 816
25.3 Windows: Additional Notes 819
25.4 Using Menus with Frames 820
25.5 JPopupMenu 826
25.6 Pluggable Look-and-Feel 828
25.7 JDesktopPane and JInternalFrame 831
25.8 JTabbedPane 834
25.9 Layout Managers: BoxLayout and GridBagLayout 836
25.10 Wrap-Up 845
Chapter 26 Multithreading 850
26.1 Introduction 851
26.2 Thread States: Life Cycle of a Thread 852
26.3 Creating and Executing Threads with Executor Framework 855
26.4 Thread Synchronization 858
26.5 Producer/Consumer Relationship without Synchronization 864
26.6 Producer/Consumer Relationship: ArrayBlockingQueue 870
26.7 Producer/Consumer Relationship with Synchronization 872
26.8 Producer/Consumer Relationship: Bounded Buffers 877
26.9 Producer/Consumer Relationship: The Lock and Condition Interfaces 883
26.10 Concurrent Collections Overview 888
26.11 Multithreading with GUI 889
26.12 Interfaces Callable and Future 899
26.13 Java SE 7: Fork/Join Framework 900
26.14 Wrap-Up 900
Chapter 27 Networking 908
27.1 Introduction 908
27.2 Manipulating URLs 909
27.3 Reading a File on a Web Server 913
27.4 Establishing a Simple Server Using Stream Sockets 915
27.5 Establishing a Simple Client Using Stream Sockets 917
27.6 Client/Server Interaction with Stream Socket Connections 918
27.7 Datagrams: Connectionless Client/Server Interaction 927
27.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server 932
27.9 [Web Bonus] Case Study: DeitelMessenger 943
27.10 Wrap-Up 943
Chapter 28 Accessing Databases with JDBC 949
28.1 Introduction 950
28.2 Relational Databases 951
28.3 Relational Database Overview: The books Database 951
28.4 SQL 954
28.5 Instructions for Installing MySQL and MySQL Connector/J 960
28.6 Instructions for Setting Up a MySQL User Account 961
28.7 Creating Database books in MySQL 962
28.8 Manipulating Databases with JDBC 963
28.9 RowSet Interface 976
28.10 Java DB/Apache Derby 978
28.11 PreparedStatements 979
28.12 Stored Procedures 991
28.13 Transaction Processing 991
28.14 Wrap-Up 992
28.15 Web Resources 992
Chapter 29 JavaServer Faces Web Apps: Part 1 999
29.1 Introduction 1000
29.2 HyperText Transfer Protocol (HTTP) Transactions 1000
29.3 Multitier Application Architecture 1004
29.4 Your First JSF Web App 1004
29.5 Model-View-Controller Architecture of JSF Apps 1011
29.6 Common JSF Components 1011
29.7 Validation Using JSF Standard Validators 1014
29.8 Session Tracking 1019
29.9 Wrap-Up 1025
Chapter 30 JavaServer Faces Web Apps: Part 2 1032
30.1 Introduction 1032
30.2 Accessing Databases in Web Apps 1033
30.3 Ajax 1042
30.4 Adding Ajax Functionality to the Validation App 1044
30.5 Wrap-Up 1046
Chapter 31 Web Services 1050
31.1 Introduction 1051
31.2 Web Service Basics 1052
31.3 Simple Object Access Protocol (SOAP) 1052
31.4 Representational State Transfer (REST) 1053
31.5 JavaScript Object Notation (JSON) 1053
31.6 Publishing and Consuming SOAP-Based Web Services 1054
31.7 Publishing and Consuming REST-Based XML Web Services 1063
31.8 Publishing and Consuming REST-Based JSON Web Services 1067
31.9 Session Tracking in a SOAP Web Service 1070
31.10 Consuming a Database-Driven SOAP Web Service 1082
31.11 Equation Generator: Returning User-Defined Types 1087
31.12 Wrap-Up 1095
Appendix A Operator Precedence Chart 1103
Appendix B ASCII Character Set 1104
Appendix C Keywords and Reserved Words 1105
Appendix D Primitive Types 1106
Index 1107
附录E~附录L请登录华信教育资源网(www.hxedu.com.cn)注册下载。
Appendix E Using the Java API Documentation
Appendix F Using the Debugger
Appendix G Formatted Output
Appendix H Number Systems
Appendix I GroupLayout
Appendix J Java Desktop Integration Components
Appendix K Mashups
Appendix L Unicode?
展开
Preface
Live in fragments no longer, only connect.
—Edgar Morgan Foster
Welcome to Java and Java How to Program, Ninth Edition! This book presents leadingedge computing technologies for students, instructors and software developers.
The new Chapter 1 engages students with intriguing facts and figures to get them excited about studying computers and programming. The chapter includes a table of some of the research made possible by computers; current technology trends and hardware discussion; the data hierarchy; a table of mobile and Internet app platforms; a new section on social networking; an introduction to Android; a table of popular web services; a table of business and technology publications and websites that will help you stay up to date with the latest technology news and trends; and updated exercises.
The book is appropriate for introductory course sequences based on the ACM/IEEE curriculum recommendations and for AP Computer Science exam preparation.
We focus on software engineering best practices. At the heart of the book is the Deitel signature “live-code approach”—concepts are presented in the context of complete working programs, rather than in code snippets. Each complete code example is accompanied by live sample executions. All the source code is available at www.deitel.com/books/ jhtp9/.
As you read the book, if you have questions, send an e-mail to deitel@deitel.com; we’ll respond promptly. For updates on this book, visit www.deitel.com/books/jhtp9/, follow us on Facebook (www.deitel.com/deitelfan) and Twitter (@deitel), and subscribe to the Deitel Buzz Online newsletter (www.deitel.com/newsletter/ subscribe.html).
New and Updated Features
Here are the updates we’ve made for Java How to Program, 9/e:
Java Standard Edition (SE) 7
l Easy to use as a Java SE 6 or Java SE 7 book. There are a few Java Standard Edition (SE) 7 features that affect CS 1 and CS 2 courses. We cover those features in optional modular sections that are easy to include or omit. Here’s some of the new functionality: Strings in switch statements, the try-with-resources statement for managing AutoClosable objects, multi-catch for defining a single exception handler to replace multiple exception handlers that perform the same task, the NIO filesystem APIs and inferring the types of generic objects from the variable they’re assigned to by using the <> notation. We also overview the new concurrency API features.
l Java SE 7 filesystem APIs. We provide an alternate online version of Chapter 17, Files, Streams and Object Serialization, that’s reimplemented with the new filesystem APIs from Java SE 7.
l Java SE 7’s AutoClosable versions of Connection, Statement and ResultSet. With the source code for Chapter 28, Accessing Databases with JDBC, we provide a version of the chapter’s first example that’s implemented using Java SE 7’s AutoClosable versions of Connection, Statement and ResultSet. AutoClosable objects reduce the likelihood of resource leaks when you use them with Java SE 7’s try-with-resources statement, which automatically closes the AutoClosable objects allocated in the parentheses following the try keyword.
Pedagogic Features
l Enhanced Making a Difference exercises set. We encourage you to use computers and the Internet to research and solve significant social problems. These exercises are meant to increase awareness and discussion of important issues the world is facing. We hope you’ll approach them with your own values, politics and beliefs. Check out our new Making a Difference Resource Center at www.deitel.com/ MakingADifference for additional ideas you may want to investigate further.
l Page numbers for key terms in chapter summaries. For key terms that appear in the chapter summaries, we include the page number of the key term’s defining occurrence.
Object Technology
l Object-oriented programming and design. We introduce the basic concepts and terminology of object technology in Chapter 1. Students develop their first customized classes and objects in Chapter 3. Presenting objects and classes early gets students “thinking about objects” immediately and mastering these concepts more thoroughly. [For courses that require a late-objects approach, consider Java How to Program, Late Objects Version, 8/e, which begins with six chapters on programming fundamentals (including two on control statements) and continues with seven chapters that gradually introduce object-oriented programming concepts.]
l Exception handling. We integrate basic exception handling earlier in the book and instructors can easily pull more material forward from Chapter 11, Exception Handling: A Deeper Look.
l Class Arrays and ArrayList. Chapter 7 covers class Arrays—which contains methods for performing common array manipulations—and class ArrayList— which implements a dynamically resizable array-like data structure. This follows our philosophy of getting lots of practice using existing classes while learning how to define your own classes.
l OO case studies. 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.
l Optional Case Study: Using the UML to Develop an Object-Oriented Design and Java Implementation of an ATM. The UML (Unified Modeling Language) is the industry-standard graphical language for modeling object-oriented systems. Chapters 12–13 include an optional case study on object-oriented design using the UML. We design and implement the software for a simple automated teller machine (ATM). We analyze a typical requirements document that specifies the system to be built. We determine the classes needed to implement that system, the attributes the classes need to have, the behaviors the classes need to exhibit and specify how the classes must interact with one another to meet the system requirements. From the design we produce a complete Java implementation. Students often report having a “light-bulb moment”—the case study helps them “tie it all together” and really understand object orientation.
l Reordered data structures presentation. We begin with generic class ArrayList in Chapter 7. Because students will understand basic generics concepts early in the book, our later data structures discussions provide a deeper treatment of generic collections—showing how to use the built-in collections of the Java API. We then show how to implement generic methods and classes. Finally, we show how to build custom generic data structures.
Database and Web Development
l JDBC 4. Chapter 28, Accessing Databases with JDBC, covers JDBC 4 and uses the Java DB/Apache Derby and MySQL database management systems. The chapter features an OO case study on developing a database-driven address book that demonstrates prepared statements and JDBC 4’s automatic driver discovery.
l Java Server Faces (JSF) 2.0. Chapters 29–30 have been updated to introduce JavaServer Faces (JSF) 2.0 technology, which greatly simplifies building JSF web applications. Chapter 29 includes examples on building web application GUIs, validating forms and session tracking. Chapter 30 discusses data-driven and Ajaxenabled JSF applications. The chapter features a database-driven multitier web address book that allows users to add and search for contacts. This Ajax-enabled application gives the reader a nice sense of Web 2.0 software development.
l Web services. Chapter 31, Web Services, demonstrates creating and consuming SOAP-and REST-based web services. Case studies include developing blackjack and airline reservation web services.
l Java Web Start and the Java Network Launch Protocol (JNLP). We introduce Java Web Start and JNLP, which enable applets and applications to be launched via a web browser. Users can install locally for later execution. Programs can also request the user’s permission to access local system resources such as files—enabling you to develop more robust applets and applications that execute safely using Java’s sandbox security model, which applies to downloaded code.
Multithreading
l Multithreading. We completely reworked Chapter 26, Multithreading [special thanks to the guidance of Brian Goetz and Joseph Bowbeer—two of the co-authors of Java Concurrency in Practice, Addison-Wesley, 2006].
l SwingWorker class. We use class SwingWorker to create multithreaded user interfaces.
GUI and Graphics
l Scalable GUI and graphics presentation. Instructors teaching introductory courses have a broad choice of the amount of GUI and graphics to cover—from none, to an optional 10-brief-sections introductory sequence woven in with the early chapters, to a deep treatment in Chapters 14, 15 and 25, and Appendix I.
l GroupLayout layout manager. We discuss the GroupLayout layout manager in the context of the GUI design tool in the NetBeans IDE.
l JTable sorting and filtering capabilities. Chapter 28 uses these capabilities to resort the data in a JTable and filter it by regular expressions.
Other Features
l Android. Because of the tremendous interest in Android-based smartphones and tablets, we’ve included a three-chapter introduction to Android app development on the Companion Website. These chapters are from our new Deitel Developer Series book Android for Programmers: An App-Driven Approach. After you learn Java, you’ll find it straightforward to develop and run Android apps on the free Android emulator that you can download from developer.android.com.
l Software engineering community concepts. We discuss agile software development, refactoring, design patterns, LAMP, SaaS (Software as a Service), PaaS (Platform as a Service), cloud computing, open-source software and more.
Dependency Chart
The chart on the next page shows the dependencies among the chapters to help instructors plan their syllabi. Java How to Program, 9/e, is appropriate for a variety of programming courses at various levels, most notably CS 1 and CS 2 courses and introductory course sequences in related disciplines. The book has a clearly delineated, modular organization. Chapters 1–11 and 14–17 form an accessible elementary programming sequence with a solid introduction to object-oriented programming. Optional Chapters 12–13 form an accessible introduction to object-oriented design with the UML. The GUI and Graphics Track and Chapters 14, 15, 23, 24 and 25 form a substantial GUI, graphics and multimedia sequence. Chapters 18–22 form a nice data-structures sequence. Chapters 26–27 form a solid introduction to multithreading and Internet networking. Chapters 28–31 form a rich database-intensive web application development sequence.
Teaching Approach
Java How to Program, 9/e, contains hundreds of complete working examples. We stress program clarity and concentrate on building well-engineered software.
Code Highlighting. We place yellow rectangles around key code segments.
Using Fonts for Emphasis. We place the key terms and the index’s page reference for each defining occurrence in bold maroon 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 can be downloaded from:
Objectives. The opening quotes are followed by a list of chapter objectives.
Illustrations/Figures. Abundant tables, line drawings, UML diagrams, programs and program outputs are included.
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 them.
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 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.
Summary Bullets. We present a section-by-section bullet-list summary of the chapter.
Self-Review Exercises and Answers. Extensive self-review exercises and answers are included for self study. All of the exercises in the optional ATM case study are fully solved.
Exercises. The chapter exercises include:
l simple recall of important terminology and concepts
l What’s wrong with this code?
l What does this code do?
l writing individual statements and small portions of methods and classes
l writing complete methods, classes and programs
l major projects
l in many chapters, Making a Difference exercises.
Index. We’ve included an extensive index.
Software Used in Java How to Program, 9/e
All the software you’ll need for this book is available free for download from the web. See the Before You Begin section that follows this Preface for links to each download.
We wrote most of the examples in Java How to Program, 9/e, using the free Java Standard Edition Development Kit (JDK) 6. For the optional Java SE 7 modules, we used the OpenJDK’s early access version of JDK 7. In Chapters 29–31, we also used the Netbeans IDE, and in Chapter 28, we used MySQL and MySQL Connector/J. You can find additional resources and software downloads in our Java Resource Centers at:
Discounts on Deitel Developer Series Books
If you’d like to receive information on professional Deitel Developer Series titles, including Android for Programmers: An App-Driven Approach, please register your copy of Java How to Program, 9/e at informit.com/register. You’ll receive information on how to purchase Android for Programmers at a discount.
Instructor Supplements
The following supplements are available to qualified instructors only through www.pearsoninternationaleditions. com/deitel:
l PowerPoint? slides containing all the code and figures in the text, plus bulleted items that summarize key points.
l Test Item File of multiple-choice questions (approximately two per book section).
l Solutions Manual with solutions to the vast majority of the end-of-chapter exercises.
Please do not write to us requesting access to the Pearson Instructor’s Resource Center which contains the book’s instructor supplements, including the exercise solutions. Access is limited strictly to college instructors teaching from the book. Instructors may obtain access only through their Pearson representatives. Solutions are not provided for “project” exercises. Check out our Programming Projects Resource Center for lots of additional exercise and project possibilities (www.deitel.com/ProgrammingProjects/).
If you’re not a registered faculty member, contact your Pearson representative.
Acknowledgments
We’d like to thank Abbey Deitel and Barbara Deitel for long hours devoted to this project. We’re fortunate to have worked on this project with the dedicated team of publishing professionals at Pearson. We appreciate the guidance, savvy and energy of Michael Hirsch, Editor-in-Chief of Computer Science. Carole Snyder recruited the book’s reviewers and managed the review process. Bob Engelhardt managed the book’s production.
Reviewers
We wish to acknowledge the efforts of our eighth and ninth edition reviewers. They scrutinized the text and the programs and provided countless suggestions for improving the presentation: Lance Andersen (Oracle), Soundararajan Angusamy (Sun Microsystems), Joseph Bowbeer (Consultant), William E. Duncan (Louisiana State University), Diana Franklin (University of California, Santa Barbara), Edward F. Gehringer (North Carolina State University), Huiwei Guan (Northshore Community College), Ric Heishman (George Mason University), Dr. Heinz Kabutz (JavaSpecialists.eu), Patty Kraft (San Diego State University), Lawrence Premkumar (Sun Microsystems), Tim Margush (University of Akron), Sue McFarland Metzger (Villanova University), Shyamal Mitra (The University of Texas at Austin), Peter Pilgrim (Consultant), Manjeet Rege, Ph.D. (Rochester Institute of Technology), Manfred Riem (Java Champion, Consultant, Robert Half), Simon Ritter (Oracle), Susan Rodger (Duke University), Amr Sabry (Indiana University), José Antonio González Seco (Parliament of Andalusia), Sang Shin (Sun Microsystems), S. Sivakumar (Astra Infotech Private Limited), Raghavan “Rags” Srinivas (Intuit), Monica Sweat (Georgia Tech), Vinod Varma (Astra Infotech Private Limited) and Alexander Zuev (Sun Microsystems).
Well, there you have it! As you read the book, we’d appreciate your comments, criticisms, corrections and suggestions for improvement. Please address all correspondence to:
We’ll respond promptly. We hope you enjoy working with Java How to Program, 9/e. Good luck!
Paul and Harvey Deitel
About the Authors
Paul J. Deitel, CEO and Chief Technical Officer of Deitel & Associates, Inc., is a graduate of MIT, where he studied Information Technology. Through Deitel & Associates, Inc., he has delivered hundreds of Java, C++, C, C#, Visual Basic and Internet programming courses to industry clients, including Cisco, IBM, Siemens, 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, SunGard Higher Education, Stratus, Cambridge Technology Partners, One Wave, Hyperion Software, Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, Invensys and many more. 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 50 years of experience in the computer field. Dr. Deitel earned B.S. and M.S. degrees from MIT and a Ph.D. from Boston University. He has extensive 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 dozens of books and LiveLessons multimedia packages and they are writing many more. The Deitels’ texts have earned international recognition, with translations published in Japanese, German, Russian, Chinese, Spanish, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. Dr. Deitel has delivered hundreds of professional programming seminars to major corporations, academic institutions, government organizations and the military.
Corporate Training from Deitel & Associates, Inc.
Deitel & Associates, Inc., is an internationally recognized corporate training and authoring organization. The company provides instructor-led courses delivered at client sites worldwide on major programming languages and platforms, such as Java, C++, Visual C++?, C, Visual C#?, Visual Basic?, XML?, Python?, object technology, Internet and web programming, Android? and iPhone? app development, and a growing list of additional programming and software-development 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 35-year publishing partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., publishes leading-edge programming textbooks, professional books and LiveLessons DVD-based and web-based video courses. Deitel & Associates, Inc., and the authors can be reached via e-mail at:
To learn more about Deitel & Associates, Inc., its publications and its Dive Into Series Corporate Training curriculum delivered at client locations worldwide, visit:
and subscribe to the free Deitel Buzz Online e-mail newsletter at:
and follow the authors on Facebook (www.deitel.com/deitelfan) and Twitter (@deitel).
Individuals wishing to purchase Deitel books, and LiveLessons DVD and web-based training courses can do so through www.deitel.com. Bulk orders by corporations, the government, the military and academic institutions should be placed directly with Pearson.
Before You Begin
This section contains information you should review before using this book and instructions to ensure that your computer is set up properly for use with this book. We’ll post updates (if any) to the Before You Begin section on the book’s website:
Font and Naming Conventions
We use fonts to distinguish between on-screen components (such as menu names and menu items) and Java code or commands. Our convention is to emphasize on-screen components in a sans-serif bold Helvetica font (for example, File menu) and to emphasize Java code and commands in a sans-serif Lucida font (for example, System.out.println()).
Software Used in the Book
All the software you’ll need for this book is available free for download from the web.
Java SE Software Development Kit (JDK) 6 and 7
We wrote most of the examples in Java How to Program, 9/e, using the free Java Standard Edition Development Kit (JDK) 6, which is available from:
For the optional Java SE 7 modules, we used the OpenJDK’s early access version of JDK 7, which is available from:
Java DB, MySQL and MySQL Connector/J
In Chapter 28, we use the Java DB and MySQL Community Edition database management systems. Java DB is part of the JDK installation. At the time of this writing, the JDK’s 64-bit installer was not properly installing Java DB. If you are using the 64-bit version of Java, you may need to install Java DB separately. You can download Java DB from:
At the time of this writing, the latest release of MySQL Community Edition was 5.5.8. To install MySQL Community Edition on Windows, Linux or Mac OS X, see the installation overview for your platform at:
l Windows: dev.mysql.com/doc/refman/5.5/en/windows-installation.html
l Linux: dev.mysql.com/doc/refman/5.5/en/linux-installation-rpm.html
l Mac OS X: dev.mysql.com/doc/refman/5.5/en/macosx-installation.html
Carefully follow the instructions for downloading and installing the software on your platform. The downloads are available from:
You also need to install MySQL Connector/J (the J stands for Java), which allows programs to use JDBC to interact with MySQL. MySQL Connector/J can be downloaded from
At the time of this writing, the current generally available release of MySQL Connector/J is 5.1.14. The documentation for Connector/J is located at
To install MySQL Connector/J, carefully follow the installation instructions at:
We do not recommend modifying your system’s CLASSPATH environment variable, which is discussed in the installation instructions. Instead, we’ll show you how use MySQL Connector/J by specifying it as a command-line option when you execute your applications.
Free versions of Java IDEs can be downloaded from the web at the following sites:
l JDK 6: www.oracle.com/technetwork/java/javase/downloads/
l Eclipse IDE: eclipse.org/downloads/
l NetBeans IDE: netbeans.org/downloads/
l jGRASP IDE: spider.eng.auburn.edu/user-cgi/grasp/grasp.pl?;dl=download_jgrasp.html
l DrJava IDE: drjava.org
l BlueJ IDE: www.bluej.org/download/download.html
l TextPad Text Editor (evaluation version): www.textpad.com/download/
Obtaining the Code Examples
The examples for Java How to Program, 9/e are available for download at
If you’re not already registered at our website, go to www.deitel.com and click the Register link below our logo in the upper-left corner of the page. Fill in your information. There’s no charge to register, and we do not share your information with anyone. We send you only account-management e-mails unless you register separately for our free Deitel Buzz Online e-mail newsletter at www.deitel.com/newsletter/subscribe.html. After registering for the site, you’ll receive a confirmation e-mail with your verification code. Click the link in the confirmation e-mail to complete your registration. Configure your e-mail client to allow e-mails from deitel.com to ensure that the confirmation email is not filtered as junk mail.
Next, go to www.deitel.com and sign in using the Login link below our logo in the upper-left corner of the page. Go to www.deitel.com/books/jhtp9/. You’ll find the link to download the examples under the heading Download Code Examples and Other Premium Content for Registered Users. Write down the location where you choose to save the ZIP file on your computer.
We assume the examples are located at C:\Examples on your computer. Extract the contents of Examples.zip using a tool such as WinZip (www.winzip.com) or the built-in capabilities of your operating system.
Setting the PATH Environment Variable
The PATH environment variable on your computer designates which directories the computer searches when looking for applications, such as the applications that enable you to compile and run your Java applications (called javac and java, respectively). Carefully follow the installation instructions for Java on your platform to ensure that you set the PATH environment variable correctly.
If you do not set the PATH variable correctly, when you use the JDK’s tools, you’ll receive a message like:
In this case, go back to the installation instructions for setting the PATH and recheck your steps. If you’ve downloaded a newer version of the JDK, you may need to change the name of the JDK’s installation directory in the PATH variable.
Setting the CLASSPATH Environment Variable
If you attempt to run a Java program and receive a message like
then your system has a CLASSPATH environment variable that must be modified. To fix the preceding error, follow the steps in setting the PATH environment variable, to locate the CLASSPATH variable, then edit the variable’s value to include the local directory—typically represented as a dot (.). On Windows add
.;
at the beginning of the CLASSPATH’s value (with no spaces before or after these characters). On other platforms, replace the semicolon with the appropriate path separator characters—often a colon (:).
Java’s Nimbus Look-and-Feel
Java comes bundled with an elegant, cross-platform look-and-feel known as Nimbus. For programs with graphical user interfaces, we’ve configured our systems to use Nimbus as the default look-and-feel.
To set Nimbus as the default for all Java applications, you must create a text file named swing.properties in the lib folder of both your JDK installation folder and your JRE installation folder. Place the following line of code in the file:
For more information on locating these installation folders visit java.sun.com/javase/6/webnotes/install/ index.html. [Note: In addition to the standalone JRE, there’s a JRE nested in your JDK’s installation folder. If you’re using an IDE that depends on the JDK (e.g., NetBeans), you may also need to place the swing.properties file in the nested jre folder’s lib folder.]
You’re now ready to begin your Java studies with Java How to Program, 9/e. We hope you enjoy the book!
展开