Tải bản đầy đủ (.pdf) (1,535 trang)

Java how to program

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.1 MB, 1,535 trang )


DEITEL® HOW TO PROGRAM SERIES Cover Theme
The cover theme for the DEITEL® HOW TO PROGRAM SERIES emphasizes social consciousness issues such as
going green, clean energy, recycling, sustainability and more. Within the text, in addition to conventional programming exercises, we’ve included our Making a Difference exercise set to raise awareness of issues such as global
warming, population growth, affordable healthcare, accessibility, privacy of electronic records and more. In this
book, you’ll use Java to program applications that relate to these issues. We hope that what you learn in
Java How to Program, 9/e will help you to make a difference.

Night at the Niagara Falls—Ontario and New York
The Niagara Falls waterfalls straddle the border between Ontario, Canada and upstate
New York in the United States. Horseshoe Falls is located on the Canadian side, and
American Falls and Bridal Veil Falls are on the U.S. side.
The Niagara Falls are an awe-inspiring, world-class tourist attraction, and a
significant source of hydroelectric power. On average, nearly four million cubic feet
of water falls over the crest line each minute. The U.S. and Canada harness the natural energy from Niagara Falls to generate clean, inexpensive electricity. The first
hydroelectric generating station on the Niagara River was built in 1881. Its electricity
powered local mills and street lights. The Niagara Redevelopment Act, passed by
the U.S. Congress in 1957, gave the New York Power Authority the right to develop
the U.S. Niagara River hydroelectric power plants. The Niagara Falls hydroelectric project began operating in 1961.
Up to 375,000 gallons of water per second is diverted from the river through conduits to the power plants. The
water spins turbines that power generators that convert the mechanical energy into electrical energy. Today,
the project generates 2.4 million kilowatts, which can power 24 million 100-watt light bulbs simultaneously. For
further information visit:
en.wikipedia.org/wiki/Niagra_falls
www.nypa.gov/facilities/niagara.htm
www.niagarafrontier.com/power.html

About Deitel & Associates, Inc.
Deitel & Associates, Inc., is an internationally recognized authoring and corporate training organization. The company offers instructor-led courses delivered at client sites worldwide on programming languages and other software
topics such as Java™, C#®, Visual Basic®, Visual C++®, C++, C, Objective-C®, XML®, Python®, JavaScript, object
technology, Internet and web programming, and Android and iPhone app development. The company’s clients include many of the world’s largest companies, as well as government agencies, branches of the military and academic


institutions. To learn more about Deitel Pearson Higher Education publications and Dive Into® Series corporate
training, e-mail or visit www.deitel.com/training/. Follow Deitel on Facebook® at
www.deitel.com/deitelfan/ and on Twitter® @deitel.



Deitel® Series Page
How To Program Series
Java™ How to Program, 9/E
Java™ How to Program, Late Objects Version, 8/E
C++ How to Program, 8/E
C How to Program, 6/E
Internet & World Wide Web How to Program, 4/E
Visual Basic® 2010 How to Program
Visual C#® 2010 How to Program, 3/E
Visual C++® 2008 How to Program, 2/E
Small Java™ How to Program, 6/E
Small C++ How to Program, 5/E

Simply Series
Simply C++: An App-Driven Tutorial Approach
Simply Java™ Programming: An App-Driven
Tutorial Approach
Simply C#: An App-Driven Tutorial Approach
Simply Visual Basic® 2008, 3/E: An App-Driven
Tutorial Approach

CourseSmart Web Books
www.deitel.com/books/CourseSmart/


C++ How to Program, 5/E, 6/E, 7/E & 8/E
Java™ How to Program, 6/E, 7/E, 8/E & 9/E
Simply C++: An App-Driven Tutorial Approach
(continued next column)

(continued)
Simply Visual Basic 2008: An App-Driven
Tutorial Approach, 3/E
Visual Basic® 2010 How to Program
Visual Basic ®2008 How to Program
Visual C#® 2010 How to Program, 4/E
Visual C#® 2008 How to Program, 3/E

Deitel® Developer Series
AJAX, Rich Internet Applications and Web
Development for Programmers
Android for Programmers: An App-Driven
Approach
C++ for Programmers
C# 2010 for Programmers, 3/E
iPhone for Programmers: An App-Driven Approach
Java™ for Programmers
JavaScript for Programmers

LiveLessons Video Learning Products
www.deitel.com/books/LiveLessons/

Java™ Fundamentals
C# Fundamentals
C++ Fundamentals

iPhone® App Development Fundamentals
JavaScript Fundamentals
Visual Basic Fundamentals

To receive updates on Deitel publications, Resource Centers, training courses, partner offers and more,
please register for the free Deitel® Buzz Online e-mail newsletter at:
www.deitel.com/newsletter/subscribe.html

follow us on Twitter®
@deitel

and become a Deitel & Associates fan on Facebook®
www.deitel.com/deitelfan/

To communicate with the authors, send e-mail to:


For information on government and corporate Dive-Into® Series on-site seminars offered by Deitel &
Associates, Inc. worldwide, visit:
www.deitel.com/training/

or write to


For continuing updates on Prentice Hall/Deitel publications visit:
www.deitel.com
www.pearsonhighered.com/deitel/

Check out our Resource Centers for valuable web resources that will help you master Java, other important programming languages, software and, Internet- and web-related topics:
www.deitel.com/ResourceCenters.html



Paul Deitel
Deitel & Associates, Inc.

Harvey Deitel
Deitel & Associates, Inc.


Vice President and Editorial Director: Marcia J. Horton
Editor-in-Chief: Michael Hirsch
Associate Editor: Carole Snyder
Vice President, Marketing: Patrice Jones
Marketing Manager: Yezan Alayan
Senior Marketing Coordinator: Kathryn Ferranti
Vice President, Production: Vince O’Brien
Managing Editor: Jeff Holcomb
Associate Managing Editor: Robert Engelhardt
Operations Specialist: Lisa McDowell
Art Director: Linda Knowle
Cover Design: Abbey S. Deitel, Harvey M. Deitel, Marta Samsel
Cover Photo Credit: © Gonzalo E. Brea/Flickr/Getty Images
Media Editor: Daniel Sandin
Media Project Manager: Wanda Rockwell
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear
on page vi.
The authors and publisher of this book have used their best efforts in preparing this book. These efforts include the
development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation
contained in this book. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.
Copyright © 2012, 2009, 2007, 2005, 2003 Pearson Education, Inc., publishing as Prentice Hall. All rights reserved.

Manufactured in the United States of America. This publication is protected by Copyright, and permission should be
obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any
form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use
material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 501
Boylston Street, Suite 900, Boston, Massachusetts 02116.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where
those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been
printed in initial caps or all caps.
Library of Congress Cataloging-in-Publication Data
Deitel, Paul J.
Java : how to program / P.J. Deitel, H.M. Deitel. -- 9th ed.
p. cm.
H.M. Deitel's name appears on the earlier editions.
Includes index.
ISBN 978-0-13-257566-9
1. Java (Computer program language) I. Deitel, Paul J. II. Deitel, Harvey M. III. Title.
QA76.73.J38D45 2012
005.13'3--dc22
2011000244

10 9 8 7 6 5 4 3 2 1
ISBN-10: 0-13-257566-3
ISBN-13: 978-0-13-257566-9


In memory of Sargent Shriver,
The first director of the Peace Corps and
founder of numerous social organizations:
For a lifetime of making a difference.
Paul and Harvey Deitel



Trademarks
DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates,
Inc.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks
of their respective owners.
Microsoft, Internet Explorer and the Windows logo are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries.
UNIX is a registered trademark of The Open Group.
Apache is a trademark of The Apache Software Foundation.
CSS, XHTML and XML are registered trademarks of the World Wide Web Consortium.
Firefox is a registered trademark of the Mozilla Foundation.
Google is a trademark of Google, Inc.
Web 2.0 is a service mark of CMP Media.

Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of
a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit
of the trademark owner, with no intention of infringement of the trademark.


Contents
Appendices M–Q are PDF documents posted online at the book’s Companion Website
(www.pearsonhighered.com/deitel/).

Preface
Before You Begin

xxiii
xxxiii


1

Introduction to Computers and Java

1

1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11
1.12
1.13
1.14

Introduction
Computers: Hardware and Software
Data Hierarchy
Computer Organization
Machine Languages, Assembly Languages and High-Level Languages
Introduction to Object Technology
Operating Systems
Programming Languages

Java and a Typical Java Development Environment
Test-Driving a Java Application
Web 2.0: Going Social
Software Technologies
Keeping Up-to-Date with Information Technologies
Wrap-Up

2
5
6
8
10
11
13
16
18
22
26
29
31
32

2

Introduction to Java Applications

37

2.1
2.2

2.3
2.4
2.5
2.6

Introduction
Your First Program in Java: Printing a Line of Text
Modifying Your First Java Program
Displaying Text with printf
Another Application: Adding Integers
Memory Concepts

38
38
44
46
47
52


viii

Contents

2.7
2.8
2.9

Arithmetic
Decision Making: Equality and Relational Operators

Wrap-Up

3

Introduction to Classes, Objects, Methods
and Strings

3.1
3.2
3.3
3.4
3.5
3.6
3.7
3.8
3.9

Introduction
Declaring a Class with a Method and Instantiating an Object of a Class
Declaring a Method with a Parameter
Instance Variables, set Methods and get Methods
Primitive Types vs. Reference Types
Initializing Objects with Constructors
Floating-Point Numbers and Type double
(Optional) GUI and Graphics Case Study: Using Dialog Boxes
Wrap-Up

4

Control Statements: Part 1


4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
4.10
4.11
4.12
4.13
4.14
4.15

Introduction
Algorithms
Pseudocode
Control Structures
if Single-Selection Statement
if…else Double-Selection Statement
while Repetition Statement
Formulating Algorithms: Counter-Controlled Repetition
Formulating Algorithms: Sentinel-Controlled Repetition
Formulating Algorithms: Nested Control Statements
Compound Assignment Operators
Increment and Decrement Operators
Primitive Types

(Optional) GUI and Graphics Case Study: Creating Simple Drawings
Wrap-Up

5

Control Statements: Part 2

5.1
5.2
5.3
5.4
5.5
5.6
5.7
5.8
5.9

Introduction
Essentials of Counter-Controlled Repetition
for Repetition Statement
Examples Using the for Statement
do…while Repetition Statement
switch Multiple-Selection Statement
break and continue Statements
Logical Operators
Structured Programming Summary

53
56
60


71
72
72
76
79
84
85
88
92
95

102
103
103
104
104
107
107
112
113
118
125
130
130
134
134
138

151

152
152
154
158
162
164
172
173
179


Contents

ix

5.10
5.11

(Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals
Wrap-Up

184
187

6

Methods: A Deeper Look

6.1
6.2

6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12
6.13
6.14

Introduction
Program Modules in Java
static Methods, static Fields and Class Math
Declaring Methods with Multiple Parameters
Notes on Declaring and Using Methods
Method-Call Stack and Activation Records
Argument Promotion and Casting
Java API Packages
Case Study: Random-Number Generation
6.9.1
Generalized Scaling and Shifting of Random Numbers
6.9.2
Random-Number Repeatability for Testing and Debugging
Case Study: A Game of Chance; Introducing Enumerations
Scope of Declarations
Method Overloading
(Optional) GUI and Graphics Case Study: Colors and Filled Shapes

Wrap-Up

7

Arrays and ArrayLists

7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8
7.9
7.10
7.11
7.12
7.13
7.14
7.15
7.16

Introduction
Arrays
Declaring and Creating Arrays
Examples Using Arrays
Case Study: Card Shuffling and Dealing Simulation
Enhanced for Statement
Passing Arrays to Methods

Case Study: Class GradeBook Using an Array to Store Grades
Multidimensional Arrays
Case Study: Class GradeBook Using a Two-Dimensional Array
Variable-Length Argument Lists
Using Command-Line Arguments
Class Arrays
Introduction to Collections and Class ArrayList
(Optional) GUI and Graphics Case Study: Drawing Arcs
Wrap-Up

8

Classes and Objects: A Deeper Look

8.1
8.2
8.3
8.4
8.5

Introduction
Class Case Study
Controlling Access to Members
Referring to the Current Object’s Members with the this Reference
Time Class Case Study: Overloaded Constructors
Time

197
198
198

200
202
205
206
207
208
210
214
214
215
219
222
224
227

240
241
242
243
244
254
258
259
262
268
271
278
279
281
284

286
289

311
312
312
316
317
320


x

Contents

8.6
8.7
8.8
8.9
8.10
8.11
8.12
8.13
8.14
8.15
8.16
8.17

Default and No-Argument Constructors
Notes on Set and Get Methods

Composition
Enumerations
Garbage Collection and Method finalize
static Class Members
static Import
final Instance Variables
Time Class Case Study: Creating Packages
Package Access
(Optional) GUI and Graphics Case Study: Using Objects with Graphics
Wrap-Up

9

Object-Oriented Programming: Inheritance

9.1
9.2
9.3
9.4

9.9

Introduction
Superclasses and Subclasses
protected Members
Relationship between Superclasses and Subclasses
9.4.1
Creating and Using a CommissionEmployee Class
9.4.2
Creating and Using a BasePlusCommissionEmployee Class

9.4.3
Creating a CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy
CommissionEmployee–BasePlusCommissionEmployee Inheritance
9.4.4
Hierarchy Using protected Instance Variables
CommissionEmployee–BasePlusCommissionEmployee Inheritance
9.4.5
Hierarchy Using private Instance Variables
Constructors in Subclasses
Software Engineering with Inheritance
Class Object
(Optional) GUI and Graphics Case Study: Displaying Text and
Images Using Labels
Wrap-Up

10

Object-Oriented Programming: Polymorphism 394

10.1
10.2
10.3
10.4
10.5

Introduction
Polymorphism Examples
Demonstrating Polymorphic Behavior
Abstract Classes and Methods

Case Study: Payroll System Using Polymorphism
10.5.1 Abstract Superclass Employee
10.5.2 Concrete Subclass SalariedEmployee
10.5.3 Concrete Subclass HourlyEmployee
10.5.4 Concrete Subclass CommissionEmployee
10.5.5 Indirect Concrete Subclass BasePlusCommissionEmployee
10.5.6 Polymorphic Processing, Operator instanceof and Downcasting

9.5
9.6
9.7
9.8

326
326
328
331
333
334
338
339
340
345
347
351

359
360
361
363

364
364
370
375
377
380
385
386
387
388
391

395
397
398
400
403
404
407
408
410
412
413


Contents

xi

10.5.7


10.8
10.9

Summary of the Allowed Assignments Between Superclass and
Subclass Variables
final Methods and Classes
Case Study: Creating and Using Interfaces
10.7.1 Developing a Payable Hierarchy
10.7.2 Interface Payable
10.7.3 Class Invoice
10.7.4 Modifying Class Employee to Implement Interface Payable
10.7.5 Modifying Class SalariedEmployee for Use in the Payable
Hierarchy
10.7.6 Using Interface Payable to Process Invoices and Employees
Polymorphically
10.7.7 Common Interfaces of the Java API
(Optional) GUI and Graphics Case Study: Drawing with Polymorphism
Wrap-Up

11

Exception Handling: A Deeper Look

11.1
11.2
11.3

Introduction
Example: Divide by Zero without Exception Handling

Example: Handling ArithmeticExceptions and

439
439

InputMismatchExceptions

442
447
447
450
454
457
459
460
461

10.6
10.7

11.4
11.5
11.6
11.7
11.8
11.9
11.10
11.11
11.12


When to Use Exception Handling
Java Exception Hierarchy
finally Block
Stack Unwinding and Obtaining Information from an Exception Object
Chained Exceptions
Declaring New Exception Types
Preconditions and Postconditions
Assertions
(New in Java SE 7) Multi-catch: Handling Multiple Exceptions
in One catch
11.13 (New in Java SE 7) try-with-Resources: Automatic Resource Deallocation
11.14 Wrap-Up

12
12.1
12.2
12.3
12.4
12.5
12.6
12.7
12.8

ATM Case Study, Part 1: Object-Oriented
Design with the UML
Case Study Introduction
Examining the Requirements Document
Identifying the Classes in a Requirements Document
Identifying Class Attributes
Identifying Objects’ States and Activities

Identifying Class Operations
Indicating Collaboration Among Objects
Wrap-Up

418
418
419
421
422
422
425
427
428
430
431
433

438

462
463
463

469
470
470
478
484
489
493

499
506


xii

13
13.1
13.2
13.3
13.4

Contents

ATM Case Study Part 2: Implementing an
Object-Oriented Design

13.5

Introduction
Starting to Program the Classes of the ATM System
Incorporating Inheritance and Polymorphism into the ATM System
ATM Case Study Implementation
13.4.1 Class ATM
13.4.2 Class Screen
13.4.3 Class Keypad
13.4.4 Class CashDispenser
13.4.5 Class DepositSlot
13.4.6 Class Account
13.4.7 Class BankDatabase

13.4.8 Class Transaction
13.4.9 Class BalanceInquiry
13.4.10 Class Withdrawal
13.4.11 Class Deposit
13.4.12 Class ATMCaseStudy
Wrap-Up

14

GUI Components: Part 1

14.1
14.2
14.3
14.4
14.5
14.6
14.7
14.8
14.9
14.10

Introduction
Java’s New Nimbus Look-and-Feel
Simple GUI-Based Input/Output with JOptionPane
Overview of Swing Components
Displaying Text and Images in a Window
Text Fields and an Introduction to Event Handling with Nested Classes
Common GUI Event Types and Listener Interfaces
How Event Handling Works

JButton

Buttons That Maintain State
14.10.1 JCheckBox
14.10.2 JRadioButton
14.11 JComboBox; Using an Anonymous Inner Class for Event Handling
14.12 JList
14.13 Multiple-Selection Lists
14.14 Mouse Event Handling
14.15 Adapter Classes
14.16 JPanel Subclass for Drawing with the Mouse
14.17 Key Event Handling
14.18 Introduction to Layout Managers
14.18.1 FlowLayout
14.18.2 BorderLayout
14.18.3 GridLayout
14.19 Using Panels to Manage More Complex Layouts

510
511
511
516
522
523
528
529
530
531
532
534

537
538
539
543
546
546

549
550
551
552
555
557
561
567
569
571
574
574
577
580
584
586
589
594
597
601
604
605
608

611
613


Contents

615
618

14.20 JTextArea
14.21 Wrap-Up

15

Graphics and Java 2D

15.1
15.2
15.3
15.4
15.5
15.6
15.7
15.8
15.9

Introduction
Graphics Contexts and Graphics Objects
Color Control
Manipulating Fonts

Drawing Lines, Rectangles and Ovals
Drawing Arcs
Drawing Polygons and Polylines
Java 2D API
Wrap-Up

16

Strings, Characters and Regular Expressions

16.1
16.2
16.3

Introduction
Fundamentals of Characters and Strings
Class String
16.3.1 String Constructors
16.3.2 String Methods length, charAt and getChars
16.3.3 Comparing Strings
16.3.4 Locating Characters and Substrings in Strings
16.3.5 Extracting Substrings from Strings
16.3.6 Concatenating Strings
16.3.7 Miscellaneous String Methods
16.3.8 String Method valueOf
Class StringBuilder
16.4.1 StringBuilder Constructors
16.4.2 StringBuilder Methods length, capacity, setLength and

16.4


ensureCapacity

16.4.3

StringBuilder

xiii

631
632
634
635
642
647
651
654
657
664

672
673
673
674
674
675
676
681
683
684

684
686
687
688
688

Methods charAt, setCharAt, getChars

16.5
16.6
16.7
16.8

and reverse
16.4.4 StringBuilder append Methods
16.4.5 StringBuilder Insertion and Deletion Methods
Class Character
Tokenizing Strings
Regular Expressions, Class Pattern and Class Matcher
Wrap-Up

17

Files, Streams and Object Serialization

17.1
17.2
17.3
17.4


Introduction
Files and Streams
Class File
Sequential-Access Text Files
17.4.1 Creating a Sequential-Access Text File

690
691
693
694
699
700
708

719
720
720
722
726
726


xiv

Contents

17.7
17.8

17.4.2 Reading Data from a Sequential-Access Text File

17.4.3 Case Study: A Credit-Inquiry Program
17.4.4 Updating Sequential-Access Files
Object Serialization
17.5.1 Creating a Sequential-Access File Using Object Serialization
17.5.2 Reading and Deserializing Data from a Sequential-Access File
Additional java.io Classes
17.6.1 Interfaces and Classes for Byte-Based Input and Output
17.6.2 Interfaces and Classes for Character-Based Input and Output
Opening Files with JFileChooser
Wrap-Up

18

Recursion

18.1
18.2
18.3
18.4
18.5
18.6
18.7
18.8
18.9
18.10

Introduction
Recursion Concepts
Example Using Recursion: Factorials
Example Using Recursion: Fibonacci Series

Recursion and the Method-Call Stack
Recursion vs. Iteration
Towers of Hanoi
Fractals
Recursive Backtracking
Wrap-Up

19

Searching, Sorting and Big O

19.1
19.2

19.4

Introduction
Searching Algorithms
19.2.1 Linear Search
19.2.2 Binary Search
Sorting Algorithms
19.3.1 Selection Sort
19.3.2 Insertion Sort
19.3.3 Merge Sort
Wrap-Up

20

Generic Collections


20.1
20.2
20.3
20.4
20.5
20.6

Introduction
Collections Overview
Type-Wrapper Classes for Primitive Types
Autoboxing and Auto-Unboxing
Interface Collection and Class Collections
Lists
20.6.1 ArrayList and Iterator
20.6.2 LinkedList

17.5
17.6

19.3

733
736
741
742
743
749
751
751
753

754
757

765
766
767
768
771
774
776
777
779
790
790

798
799
800
800
804
809
810
814
817
824

829
830
830
831

832
832
833
834
836


Contents
20.7

20.8
20.9
20.10
20.11
20.12
20.13
20.14
20.15
20.16

Collections Methods
20.7.1 Method sort
20.7.2 Method shuffle
20.7.3 Methods reverse, fill, copy, max and min
20.7.4 Method binarySearch
20.7.5 Methods addAll, frequency and disjoint
Stack Class of Package java.util
Class PriorityQueue and Interface Queue
Sets
Maps

Properties Class
Synchronized Collections
Unmodifiable Collections
Abstract Implementations
Wrap-Up

21

Generic Classes and Methods

21.1
21.2
21.3
21.4

Introduction
Motivation for Generic Methods
Generic Methods: Implementation and Compile-Time Translation
Additional Compile-Time Translation Issues: Methods That Use a
Type Parameter as the Return Type
21.5 Overloading Generic Methods
21.6 Generic Classes
21.7 Raw Types
21.8 Wildcards in Methods That Accept Type Parameters
21.9 Generics and Inheritance: Notes
21.10 Wrap-Up

22

Custom Generic Data Structures


22.1
22.2
22.3
22.4
22.5
22.6
22.7
22.8

Introduction
Self-Referential Classes
Dynamic Memory Allocation
Linked Lists
Stacks
Queues
Trees
Wrap-Up

23

Applets and Java Web Start

23.1
23.2
23.3

Introduction
Sample Applets Provided with the JDK
Simple Java Applet: Drawing a String

23.3.1 Executing WelcomeApplet in the appletviewer
23.3.2 Executing an Applet in a Web Browser

xv
841
842
845
847
849
851
853
855
856
859
863
866
866
867
867

873
874
874
877
880
883
883
891
895
899

900

904
905
905
906
907
917
921
924
930

941
942
943
947
949
951


xvi
23.4
23.5
23.6
23.7

Contents

23.8


Applet Life-Cycle Methods
Initialization with Method init
Sandbox Security Model
Java Web Start and the Java Network Launch Protocol (JNLP)
23.7.1 Packaging the DrawTest Applet for Use with Java Web Start
23.7.2 JNLP Document for the DrawTest Applet
Wrap-Up

24

Multimedia: Applets and Applications

24.1
24.2
24.3
24.4
24.5
24.6
24.7
24.8

Introduction
Loading, Displaying and Scaling Images
Animating a Series of Images
Image Maps
Loading and Playing Audio Clips
Playing Video and Other Media with Java Media Framework
Wrap-Up
Web Resources


25

GUI Components: Part 2

25.1
25.2
25.3
25.4
25.5
25.6
25.7
25.8
25.9
25.10

Introduction

26
26.1
26.2
26.3
26.4

JSlider

Windows: Additional Notes
Using Menus with Frames
JPopupMenu

Pluggable Look-and-Feel

JDesktopPane and JInternalFrame
JTabbedPane

Layout Managers: BoxLayout and GridBagLayout
Wrap-Up

Multithreading

Introduction
Thread States: Life Cycle of a Thread
Creating and Executing Threads with Executor Framework
Thread Synchronization
26.4.1 Unsynchronized Data Sharing
26.4.2 Synchronized Data Sharing—Making Operations Atomic
26.5 Producer/Consumer Relationship without Synchronization
26.6 Producer/Consumer Relationship: ArrayBlockingQueue
26.7 Producer/Consumer Relationship with Synchronization
26.8 Producer/Consumer Relationship: Bounded Buffers
26.9 Producer/Consumer Relationship: The Lock and Condition Interfaces
26.10 Concurrent Collections Overview
26.11 Multithreading with GUI

951
952
954
956
956
957
961


967
968
969
975
982
985
988
992
992

1000
1001
1001
1005
1006
1014
1017
1022
1026
1028
1040

1045
1046
1048
1051
1054
1055
1059
1062

1070
1073
1079
1086
1093
1095


Contents
26.11.1 Performing Computations in a Worker Thread
26.11.2 Processing Intermediate Results with SwingWorker
26.12 Interfaces Callable and Future
26.13 Java SE 7: Fork/Join Framework
26.14 Wrap-Up

27

Networking

27.1
27.2
27.3
27.4
27.5
27.6
27.7
27.8
27.9
27.10


Introduction
Manipulating URLs
Reading a File on a Web Server
Establishing a Simple Server Using Stream Sockets
Establishing a Simple Client Using Stream Sockets
Client/Server Interaction with Stream Socket Connections
Datagrams: Connectionless Client/Server Interaction
Client/Server Tic-Tac-Toe Using a Multithreaded Server
[Web Bonus] Case Study: DeitelMessenger
Wrap-Up

28

Accessing Databases with JDBC

28.1
28.2
28.3
28.4

Introduction
Relational Databases
Relational Database Overview: The books Database
SQL
28.4.1 Basic SELECT Query
28.4.2 WHERE Clause
28.4.3 ORDER BY Clause
28.4.4 Merging Data from Multiple Tables: INNER JOIN
28.4.5 INSERT Statement
28.4.6 UPDATE Statement

28.4.7 DELETE Statement
Instructions for Installing MySQL and MySQL Connector/J
Instructions for Setting Up a MySQL User Account
Creating Database books in MySQL
Manipulating Databases with JDBC
28.8.1 Connecting to and Querying a Database
28.8.2 Querying the books Database
RowSet Interface
Java DB/Apache Derby
PreparedStatements
Stored Procedures
Transaction Processing
Wrap-Up
Web Resources

28.5
28.6
28.7
28.8

28.9
28.10
28.11
28.12
28.13
28.14
28.15

xvii
1096

1102
1109
1109
1110

1118
1119
1120
1125
1128
1130
1130
1142
1150
1165
1165

1171
1172
1173
1174
1177
1178
1179
1181
1182
1184
1185
1186
1186

1187
1188
1189
1189
1194
1207
1209
1211
1226
1227
1227
1228


xviii

Contents

29

JavaServer™ Faces Web Apps: Part 1

29.1
29.2
29.3
29.4

29.9

Introduction

HyperText Transfer Protocol (HTTP) Transactions
Multitier Application Architecture
Your First JSF Web App
29.4.1 The Default index.xhtml Document: Introducing Facelets
29.4.2 Examining the WebTimeBean Class
29.4.3 Building the WebTime JSF Web App in NetBeans
Model-View-Controller Architecture of JSF Apps
Common JSF Components
Validation Using JSF Standard Validators
Session Tracking
29.8.1 Cookies
29.8.2 Session Tracking with @SessionScoped Beans
Wrap-Up

30

JavaServer™ Faces Web Apps: Part 2

30.1
30.2

30.3
30.4
30.5

Introduction
Accessing Databases in Web Apps
30.2.1 Setting Up the Database
30.2.2 @ManagedBean Class AddressBean
30.2.3 index.xhtml Facelets Page

30.2.4 addentry.xhtml Facelets Page
Ajax
Adding Ajax Functionality to the Validation App
Wrap-Up

31

Web Services

31.1
31.2
31.3
31.4
31.5
31.6

Introduction
Web Service Basics
Simple Object Access Protocol (SOAP)
Representational State Transfer (REST)
JavaScript Object Notation (JSON)
Publishing and Consuming SOAP-Based Web Services
31.6.1 Creating a Web Application Project and Adding a Web
Service Class in NetBeans
31.6.2 Defining the WelcomeSOAP Web Service in NetBeans
31.6.3 Publishing the WelcomeSOAP Web Service from NetBeans
31.6.4 Testing the WelcomeSOAP Web Service with GlassFish
Application Server’s Tester Web Page
31.6.5 Describing a Web Service with the Web Service Description
Language (WSDL)

31.6.6 Creating a Client to Consume the WelcomeSOAP Web Service
31.6.7 Consuming the WelcomeSOAP Web Service

29.5
29.6
29.7
29.8

1235
1236
1237
1240
1241
1242
1244
1246
1250
1250
1254
1261
1262
1263
1269

1276
1277
1277
1279
1282
1286

1288
1290
1292
1295

1299
1300
1302
1302
1302
1303
1303
1303
1304
1307
1308
1309
1310
1312


Contents
31.7

Publishing and Consuming REST-Based XML Web Services
31.7.1 Creating a REST-Based XML Web Service
31.7.2 Consuming a REST-Based XML Web Service
31.8 Publishing and Consuming REST-Based JSON Web Services
31.8.1 Creating a REST-Based JSON Web Service
31.8.2 Consuming a REST-Based JSON Web Service

31.9 Session Tracking in a SOAP Web Service
31.9.1 Creating a Blackjack Web Service
31.9.2 Consuming the Blackjack Web Service
31.10 Consuming a Database-Driven SOAP Web Service
31.10.1 Creating the Reservation Database
31.10.2 Creating a Web Application to Interact with the
Reservation Service
31.11 Equation Generator: Returning User-Defined Types
31.11.1 Creating the EquationGeneratorXML Web Service
31.11.2 Consuming the EquationGeneratorXML Web Service
31.11.3 Creating the EquationGeneratorJSON Web Service
31.11.4 Consuming the EquationGeneratorJSON Web Service
31.12 Wrap-Up

xix
1315
1315
1318
1320
1320
1322
1324
1325
1328
1339
1340
1343
1346
1349
1350

1354
1354
1357

A
B
C
D
E

Operator Precedence Chart

1365

ASCII Character Set

1367

Keywords and Reserved Words

1368

Primitive Types

1369

Using the Java API Documentation

1370


E.1
E.2

Introduction
Navigating the Java API

F

Using the Debugger

F.1
F.2
F.3
F.4
F.5
F.6
F.7

Introduction
Breakpoints and the run, stop, cont and print Commands
The print and set Commands
Controlling Execution Using the step, step up and next Commands
The watch Command
The clear Command
Wrap-Up

G

Formatted Output


G.1

Introduction

1370
1370

1378
1379
1379
1383
1385
1388
1391
1393

1395
1396


xx

Contents

G.2
G.3
G.4
G.5
G.6
G.7

G.8
G.9
G.10
G.11
G.12
G.13
G.14

Streams
Formatting Output with printf
Printing Integers
Printing Floating-Point Numbers
Printing Strings and Characters
Printing Dates and Times
Other Conversion Characters
Printing with Field Widths and Precisions
Using Flags in the printf Format String
Printing with Argument Indices
Printing Literals and Escape Sequences
Formatting Output with Class Formatter
Wrap-Up

1396
1396
1397
1398
1400
1401
1403
1405

1407
1411
1411
1412
1413

H

Number Systems

H.1
H.2
H.3
H.4
H.5
H.6

Introduction
Abbreviating Binary Numbers as Octal and Hexadecimal Numbers
Converting Octal and Hexadecimal Numbers to Binary Numbers
Converting from Binary, Octal or Hexadecimal to Decimal
Converting from Decimal to Binary, Octal or Hexadecimal
Negative Binary Numbers: Two’s Complement Notation

I

GroupLayout

I.1
I.2

I.3
I.4

Introduction
GroupLayout Basics
Building a ColorChooser
GroupLayout Web Resources

J

Java Desktop Integration Components

J.1
J.2
J.3
J.4

Introduction
Splash Screens
Desktop Class
Tray Icons

1443
1443
1445
1447

K

Mashups


1449

K.1
K.2
K.3
K.4
K.5
K.6

Introduction
Popular Mashups
APIs Commonly Used in Mashups
Deitel Mashups Resource Center
Deitel RSS Resource Center
Mashup Performance and Reliability Issues

L

Unicode®

L.1

Introduction

1418
1419
1422
1423
1423

1424
1426

1431
1431
1431
1432
1442

1443

1449
1449
1450
1450
1451
1451

1452
1452


Contents
L.2
L.3
L.4
L.5
L.6

Unicode Transformation Formats

Characters and Glyphs
Advantages/Disadvantages of Unicode
Using Unicode
Character Ranges

xxi
1453
1454
1454
1455
1457

Appendices on the Web

1459

Index

1461

Appendices M–Q are PDF documents posted online at the book’s Companion Website
(www.pearsonhighered.com/deitel/).

M

Creating Documentation with javadoc

M.1
M.2
M.3

M.4
M.5

Introduction
Documentation Comments
Documenting Java Source Code

M-1

Files Produced by javadoc

M-1
M-1
M-1
M-8
M-9

N

Bit Manipulation

N-1

N.1
N.2
N.3

Introduction
Bit Manipulation and the Bitwise Operators
BitSet Class


N-1
N-1
N-11

O

Labeled break and continue Statements

O-1

O.1
O.2
O.3

Introduction
Labeled break Statement
Labeled continue Statement

P

UML 2: Additional Diagram Types

P.1
P.2

Introduction
Additional Diagram Types

Q


Design Patterns

Q.1
Q.2

Introduction
Creational, Structural and Behavioral Design Patterns
Q.2.1 Creational Design Patterns
Q.2.2 Structural Design Patterns

javadoc

O-1
O-1
O-2

P-1
P-1
P-1

Q-1
Q-1
Q-2
Q-3
Q-5


xxii


Q.3

Q.4
Q.5

Q.6
Q.7

Contents
Q.2.3 Behavioral Design Patterns
Q.2.4 Conclusion
Design Patterns in Packages java.awt and javax.swing
Q.3.1 Creational Design Patterns
Q.3.2 Structural Design Patterns
Q.3.3 Behavioral Design Patterns
Q.3.4 Conclusion
Concurrency Design Patterns
Design Patterns Used in Packages java.io and java.net
Q.5.1 Creational Design Patterns
Q.5.2 Structural Design Patterns
Q.5.3 Architectural Patterns
Q.5.4 Conclusion
Design Patterns Used in Package java.util
Q.6.1 Creational Design Patterns
Q.6.2 Behavioral Design Patterns
Wrap-Up

Q-6
Q-7
Q-7

Q-7
Q-8
Q-10
Q-13
Q-14
Q-15
Q-15
Q-15
Q-16
Q-19
Q-19
Q-19
Q-19
Q-20


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/ and at the book’s Companion Website www.pearsonhighered.com/deitel/.
As you read the book, if you have questions, send an e-mail to ;
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
• 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.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×