• Tidak ada hasil yang ditemukan

Empowering Developers with Programming Expertise

N/A
N/A
Albert

Academic year: 2024

Membagikan " Empowering Developers with Programming Expertise"

Copied!
1535
0
0

Teks penuh

(1)
(2)

About Deitel & Associates, Inc.

Deitel & Associates, Inc., is an internationally recognized authoring and corporate training organization. The com- pany 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 in- clude 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[email protected]or visitwww.deitel.com/training/.Follow Deitel on Facebook®at

www.deitel.com/deitelfan/and on Twitter®@deitel.

going green, clean energy, recycling, sustainability and more. Within the text, in addition to conventional program- ming 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 natu- ral 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

(3)
(4)

D e i t e l ® S e r i e s P a g e

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 JavaHow to Program, 6/E Small C++ How to Program, 5/E

Simply Series

Simply C++: An App-Driven Tutorial Approach Simply JavaProgramming: 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 freeDeitel®Buzz Onlinee-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:

[email protected]

For information on government and corporateDive-Into®Serieson-site seminars offered by Deitel &

Associates, Inc. worldwide, visit:

www.deitel.com/training/

or write to

[email protected]

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 impor- tant programming languages, software and, Internet- and web-related topics:

www.deitel.com/ResourceCenters.html

(5)

Paul Deitel

Deitel & Associates, Inc.

Harvey Deitel

Deitel & Associates, Inc.

(6)

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 pub- lisher 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 dam- ages 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

(7)

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

(8)

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.

(9)

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

Preface xxiii

Before You Begin xxxiii

1 Introduction to Computers and Java 1

1.1 Introduction 2

1.2 Computers: Hardware and Software 5

1.3 Data Hierarchy 6

1.4 Computer Organization 8

1.5 Machine Languages, Assembly Languages and High-Level Languages 10

1.6 Introduction to Object Technology 11

1.7 Operating Systems 13

1.8 Programming Languages 16

1.9 Java and a Typical Java Development Environment 18

1.10 Test-Driving a Java Application 22

1.11 Web 2.0: Going Social 26

1.12 Software Technologies 29

1.13 Keeping Up-to-Date with Information Technologies 31

1.14 Wrap-Up 32

2 Introduction to Java Applications 37

2.1 Introduction 38

2.2 Your First Program in Java: Printing a Line of Text 38

2.3 Modifying Your First Java Program 44

2.4 Displaying Text withprintf 46

2.5 Another Application: Adding Integers 47

2.6 Memory Concepts 52

Contents

(10)

2.7 Arithmetic 53 2.8 Decision Making: Equality and Relational Operators 56

2.9 Wrap-Up 60

3 Introduction to Classes, Objects, Methods

and Strings 71

3.1 Introduction 72

3.2 Declaring a Class with a Method and Instantiating an Object of a Class 72

3.3 Declaring a Method with a Parameter 76

3.4 Instance Variables,setMethods andgetMethods 79

3.5 Primitive Types vs. Reference Types 84

3.6 Initializing Objects with Constructors 85

3.7 Floating-Point Numbers and Typedouble 88

3.8 (Optional) GUI and Graphics Case Study: Using Dialog Boxes 92

3.9 Wrap-Up 95

4 Control Statements: Part 1 102

4.1 Introduction 103

4.2 Algorithms 103

4.3 Pseudocode 104

4.4 Control Structures 104

4.5 ifSingle-Selection Statement 107

4.6 ifelseDouble-Selection Statement 107

4.7 whileRepetition Statement 112

4.8 Formulating Algorithms: Counter-Controlled Repetition 113 4.9 Formulating Algorithms: Sentinel-Controlled Repetition 118 4.10 Formulating Algorithms: Nested Control Statements 125

4.11 Compound Assignment Operators 130

4.12 Increment and Decrement Operators 130

4.13 Primitive Types 134

4.14 (Optional) GUI and Graphics Case Study: Creating Simple Drawings 134

4.15 Wrap-Up 138

5 Control Statements: Part 2 151

5.1 Introduction 152

5.2 Essentials of Counter-Controlled Repetition 152

5.3 forRepetition Statement 154

5.4 Examples Using theforStatement 158

5.5 dowhileRepetition Statement 162

5.6 switchMultiple-Selection Statement 164

5.7 breakandcontinueStatements 172

5.8 Logical Operators 173

5.9 Structured Programming Summary 179

(11)

Contents ix

5.10 (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals 184

5.11 Wrap-Up 187

6 Methods: A Deeper Look 197

6.1 Introduction 198

6.2 Program Modules in Java 198

6.3 staticMethods,staticFields and ClassMath 200

6.4 Declaring Methods with Multiple Parameters 202

6.5 Notes on Declaring and Using Methods 205

6.6 Method-Call Stack and Activation Records 206

6.7 Argument Promotion and Casting 207

6.8 Java API Packages 208

6.9 Case Study: Random-Number Generation 210

6.9.1 Generalized Scaling and Shifting of Random Numbers 214 6.9.2 Random-Number Repeatability for Testing and Debugging 214 6.10 Case Study: A Game of Chance; Introducing Enumerations 215

6.11 Scope of Declarations 219

6.12 Method Overloading 222

6.13 (Optional) GUI and Graphics Case Study: Colors and Filled Shapes 224

6.14 Wrap-Up 227

7 Arrays and ArrayLists 240

7.1 Introduction 241

7.2 Arrays 242

7.3 Declaring and Creating Arrays 243

7.4 Examples Using Arrays 244

7.5 Case Study: Card Shuffling and Dealing Simulation 254

7.6 EnhancedforStatement 258

7.7 Passing Arrays to Methods 259

7.8 Case Study: ClassGradeBookUsing an Array to Store Grades 262

7.9 Multidimensional Arrays 268

7.10 Case Study: ClassGradeBookUsing a Two-Dimensional Array 271

7.11 Variable-Length Argument Lists 278

7.12 Using Command-Line Arguments 279

7.13 ClassArrays 281

7.14 Introduction to Collections and ClassArrayList 284

7.15 (Optional) GUI and Graphics Case Study: Drawing Arcs 286

7.16 Wrap-Up 289

8 Classes and Objects: A Deeper Look 311

8.1 Introduction 312

8.2 TimeClass Case Study 312

8.3 Controlling Access to Members 316

8.4 Referring to the Current Object’s Members with thethisReference 317

8.5 TimeClass Case Study: Overloaded Constructors 320

(12)

8.6 Default and No-Argument Constructors 326

8.7 Notes onSetandGetMethods 326

8.8 Composition 328

8.9 Enumerations 331

8.10 Garbage Collection and Methodfinalize 333

8.11 staticClass Members 334

8.12 staticImport 338

8.13 finalInstance Variables 339

8.14 TimeClass Case Study: Creating Packages 340

8.15 Package Access 345

8.16 (Optional) GUI and Graphics Case Study: Using Objects with Graphics 347

8.17 Wrap-Up 351

9 Object-Oriented Programming: Inheritance 359

9.1 Introduction 360

9.2 Superclasses and Subclasses 361

9.3 protectedMembers 363

9.4 Relationship between Superclasses and Subclasses 364

9.4.1 Creating and Using aCommissionEmployeeClass 364 9.4.2 Creating and Using aBasePlusCommissionEmployeeClass 370 9.4.3 Creating aCommissionEmployeeBasePlusCommissionEmployee

Inheritance Hierarchy 375

9.4.4 CommissionEmployeeBasePlusCommissionEmployeeInheritance Hierarchy UsingprotectedInstance Variables 377 9.4.5 CommissionEmployeeBasePlusCommissionEmployeeInheritance

Hierarchy UsingprivateInstance Variables 380

9.5 Constructors in Subclasses 385

9.6 Software Engineering with Inheritance 386

9.7 ClassObject 387

9.8 (Optional) GUI and Graphics Case Study: Displaying Text and

Images Using Labels 388

9.9 Wrap-Up 391

10 Object-Oriented Programming: Polymorphism 394

10.1 Introduction 395

10.2 Polymorphism Examples 397

10.3 Demonstrating Polymorphic Behavior 398

10.4 Abstract Classes and Methods 400

10.5 Case Study: Payroll System Using Polymorphism 403

10.5.1 Abstract SuperclassEmployee 404

10.5.2 Concrete SubclassSalariedEmployee 407

10.5.3 Concrete SubclassHourlyEmployee 408

10.5.4 Concrete SubclassCommissionEmployee 410

10.5.5 Indirect Concrete SubclassBasePlusCommissionEmployee 412 10.5.6 Polymorphic Processing, Operatorinstanceofand Downcasting 413

(13)

Contents xi

10.5.7 Summary of the Allowed Assignments Between Superclass and

Subclass Variables 418

10.6 finalMethods and Classes 418

10.7 Case Study: Creating and Using Interfaces 419

10.7.1 Developing aPayableHierarchy 421

10.7.2 InterfacePayable 422

10.7.3 ClassInvoice 422

10.7.4 Modifying ClassEmployeeto Implement InterfacePayable 425 10.7.5 Modifying ClassSalariedEmployeefor Use in thePayable

Hierarchy 427

10.7.6 Using InterfacePayableto ProcessInvoices andEmployees

Polymorphically 428

10.7.7 Common Interfaces of the Java API 430

10.8 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 431

10.9 Wrap-Up 433

11 Exception Handling: A Deeper Look 438

11.1 Introduction 439

11.2 Example: Divide by Zero without Exception Handling 439 11.3 Example: HandlingArithmeticExceptions and

InputMismatchExceptions 442

11.4 When to Use Exception Handling 447

11.5 Java Exception Hierarchy 447

11.6 finallyBlock 450

11.7 Stack Unwinding and Obtaining Information from an Exception Object 454

11.8 Chained Exceptions 457

11.9 Declaring New Exception Types 459

11.10 Preconditions and Postconditions 460

11.11 Assertions 461

11.12 (New in Java SE 7) Multi-catch: Handling Multiple Exceptions

in Onecatch 462

11.13 (New in Java SE 7)try-with-Resources: Automatic Resource Deallocation 463

11.14 Wrap-Up 463

12 ATM Case Study, Part 1: Object-Oriented

Design with the UML 469

12.1 Case Study Introduction 470

12.2 Examining the Requirements Document 470

12.3 Identifying the Classes in a Requirements Document 478

12.4 Identifying Class Attributes 484

12.5 Identifying Objects’ States and Activities 489

12.6 Identifying Class Operations 493

12.7 Indicating Collaboration Among Objects 499

12.8 Wrap-Up 506

(14)

13 ATM Case Study Part 2: Implementing an

Object-Oriented Design 510

13.1 Introduction 511

13.2 Starting to Program the Classes of the ATM System 511 13.3 Incorporating Inheritance and Polymorphism into the ATM System 516

13.4 ATM Case Study Implementation 522

13.4.1 ClassATM 523

13.4.2 ClassScreen 528

13.4.3 ClassKeypad 529

13.4.4 ClassCashDispenser 530

13.4.5 ClassDepositSlot 531

13.4.6 ClassAccount 532

13.4.7 ClassBankDatabase 534

13.4.8 ClassTransaction 537

13.4.9 ClassBalanceInquiry 538

13.4.10 ClassWithdrawal 539

13.4.11 ClassDeposit 543

13.4.12 ClassATMCaseStudy 546

13.5 Wrap-Up 546

14 GUI Components: Part 1 549

14.1 Introduction 550

14.2 Java’s New Nimbus Look-and-Feel 551

14.3 Simple GUI-Based Input/Output withJOptionPane 552

14.4 Overview of Swing Components 555

14.5 Displaying Text and Images in a Window 557

14.6 Text Fields and an Introduction to Event Handling with Nested Classes 561

14.7 Common GUI Event Types and Listener Interfaces 567

14.8 How Event Handling Works 569

14.9 JButton 571

14.10 Buttons That Maintain State 574

14.10.1 JCheckBox 574

14.10.2 JRadioButton 577

14.11 JComboBox; Using an Anonymous Inner Class for Event Handling 580

14.12 JList 584

14.13 Multiple-Selection Lists 586

14.14 Mouse Event Handling 589

14.15 Adapter Classes 594

14.16 JPanelSubclass for Drawing with the Mouse 597

14.17 Key Event Handling 601

14.18 Introduction to Layout Managers 604

14.18.1 FlowLayout 605

14.18.2 BorderLayout 608

14.18.3 GridLayout 611

14.19 Using Panels to Manage More Complex Layouts 613

(15)

Contents xiii

14.20 JTextArea 615

14.21 Wrap-Up 618

15 Graphics and Java 2D 631

15.1 Introduction 632

15.2 Graphics Contexts and Graphics Objects 634

15.3 Color Control 635

15.4 Manipulating Fonts 642

15.5 Drawing Lines, Rectangles and Ovals 647

15.6 Drawing Arcs 651

15.7 Drawing Polygons and Polylines 654

15.8 Java 2D API 657

15.9 Wrap-Up 664

16 Strings, Characters and Regular Expressions 672

16.1 Introduction 673

16.2 Fundamentals of Characters and Strings 673

16.3 ClassString 674

16.3.1 StringConstructors 674

16.3.2 StringMethodslength,charAtandgetChars 675

16.3.3 Comparing Strings 676

16.3.4 Locating Characters and Substrings in Strings 681

16.3.5 Extracting Substrings from Strings 683

16.3.6 Concatenating Strings 684

16.3.7 MiscellaneousStringMethods 684

16.3.8 StringMethodvalueOf 686

16.4 ClassStringBuilder 687

16.4.1 StringBuilderConstructors 688

16.4.2 StringBuilderMethodslength,capacity,setLengthand

ensureCapacity 688

16.4.3 StringBuilderMethodscharAt,setCharAt,getChars

andreverse 690

16.4.4 StringBuilder appendMethods 691

16.4.5 StringBuilderInsertion and Deletion Methods 693

16.5 ClassCharacter 694

16.6 TokenizingStrings 699

16.7 Regular Expressions, ClassPatternand ClassMatcher 700

16.8 Wrap-Up 708

17 Files, Streams and Object Serialization 719

17.1 Introduction 720

17.2 Files and Streams 720

17.3 ClassFile 722

17.4 Sequential-Access Text Files 726

17.4.1 Creating a Sequential-Access Text File 726

(16)

17.4.2 Reading Data from a Sequential-Access Text File 733

17.4.3 Case Study: A Credit-Inquiry Program 736

17.4.4 Updating Sequential-Access Files 741

17.5 Object Serialization 742

17.5.1 Creating a Sequential-Access File Using Object Serialization 743 17.5.2 Reading and Deserializing Data from a Sequential-Access File 749

17.6 Additionaljava.ioClasses 751

17.6.1 Interfaces and Classes for Byte-Based Input and Output 751 17.6.2 Interfaces and Classes for Character-Based Input and Output 753

17.7 Opening Files withJFileChooser 754

17.8 Wrap-Up 757

18 Recursion 765

18.1 Introduction 766

18.2 Recursion Concepts 767

18.3 Example Using Recursion: Factorials 768

18.4 Example Using Recursion: Fibonacci Series 771

18.5 Recursion and the Method-Call Stack 774

18.6 Recursion vs. Iteration 776

18.7 Towers of Hanoi 777

18.8 Fractals 779

18.9 Recursive Backtracking 790

18.10 Wrap-Up 790

19 Searching, Sorting and Big O 798

19.1 Introduction 799

19.2 Searching Algorithms 800

19.2.1 Linear Search 800

19.2.2 Binary Search 804

19.3 Sorting Algorithms 809

19.3.1 Selection Sort 810

19.3.2 Insertion Sort 814

19.3.3 Merge Sort 817

19.4 Wrap-Up 824

20 Generic Collections 829

20.1 Introduction 830

20.2 Collections Overview 830

20.3 Type-Wrapper Classes for Primitive Types 831

20.4 Autoboxing and Auto-Unboxing 832

20.5 InterfaceCollectionand ClassCollections 832

20.6 Lists 833

20.6.1 ArrayListandIterator 834

20.6.2 LinkedList 836

(17)

Contents xv

20.7 Collections Methods 841

20.7.1 Methodsort 842

20.7.2 Methodshuffle 845

20.7.3 Methodsreverse,fill,copy,maxandmin 847

20.7.4 MethodbinarySearch 849

20.7.5 MethodsaddAll,frequencyanddisjoint 851

20.8 StackClass of Packagejava.util 853

20.9 ClassPriorityQueueand InterfaceQueue 855

20.10 Sets 856

20.11 Maps 859

20.12 PropertiesClass 863

20.13 Synchronized Collections 866

20.14 Unmodifiable Collections 866

20.15 Abstract Implementations 867

20.16 Wrap-Up 867

21 Generic Classes and Methods 873

21.1 Introduction 874

21.2 Motivation for Generic Methods 874

21.3 Generic Methods: Implementation and Compile-Time Translation 877 21.4 Additional Compile-Time Translation Issues: Methods That Use a

Type Parameter as the Return Type 880

21.5 Overloading Generic Methods 883

21.6 Generic Classes 883

21.7 Raw Types 891

21.8 Wildcards in Methods That Accept Type Parameters 895

21.9 Generics and Inheritance: Notes 899

21.10 Wrap-Up 900

22 Custom Generic Data Structures 904

22.1 Introduction 905

22.2 Self-Referential Classes 905

22.3 Dynamic Memory Allocation 906

22.4 Linked Lists 907

22.5 Stacks 917

22.6 Queues 921

22.7 Trees 924

22.8 Wrap-Up 930

23 Applets and Java Web Start 941

23.1 Introduction 942

23.2 Sample Applets Provided with the JDK 943

23.3 Simple Java Applet: Drawing a String 947

23.3.1 ExecutingWelcomeAppletin theappletviewer 949

23.3.2 Executing an Applet in a Web Browser 951

(18)

23.4 Applet Life-Cycle Methods 951

23.5 Initialization with Methodinit 952

23.6 Sandbox Security Model 954

23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 956 23.7.1 Packaging theDrawTestApplet for Use with Java Web Start 956

23.7.2 JNLP Document for theDrawTestApplet 957

23.8 Wrap-Up 961

24 Multimedia: Applets and Applications 967

24.1 Introduction 968

24.2 Loading, Displaying and Scaling Images 969

24.3 Animating a Series of Images 975

24.4 Image Maps 982

24.5 Loading and Playing Audio Clips 985

24.6 Playing Video and Other Media with Java Media Framework 988

24.7 Wrap-Up 992

24.8 Web Resources 992

25 GUI Components: Part 2 1000

25.1 Introduction 1001

25.2 JSlider 1001

25.3 Windows: Additional Notes 1005

25.4 Using Menus with Frames 1006

25.5 JPopupMenu 1014

25.6 Pluggable Look-and-Feel 1017

25.7 JDesktopPaneandJInternalFrame 1022

25.8 JTabbedPane 1026

25.9 Layout Managers:BoxLayoutandGridBagLayout 1028

25.10 Wrap-Up 1040

26 Multithreading 1045

26.1 Introduction 1046

26.2 Thread States: Life Cycle of a Thread 1048

26.3 Creating and Executing Threads withExecutorFramework 1051

26.4 Thread Synchronization 1054

26.4.1 Unsynchronized Data Sharing 1055

26.4.2 Synchronized Data Sharing—Making Operations Atomic 1059 26.5 Producer/Consumer Relationship without Synchronization 1062 26.6 Producer/Consumer Relationship:ArrayBlockingQueue 1070 26.7 Producer/Consumer Relationship with Synchronization 1073 26.8 Producer/Consumer Relationship: Bounded Buffers 1079 26.9 Producer/Consumer Relationship: TheLockandConditionInterfaces 1086

26.10 Concurrent Collections Overview 1093

26.11 Multithreading with GUI 1095

(19)

Contents xvii

26.11.1 Performing Computations in a Worker Thread 1096 26.11.2 Processing Intermediate Results withSwingWorker 1102

26.12 InterfacesCallableandFuture 1109

26.13 Java SE 7: Fork/Join Framework 1109

26.14 Wrap-Up 1110

27 Networking 1118

27.1 Introduction 1119

27.2 Manipulating URLs 1120

27.3 Reading a File on a Web Server 1125

27.4 Establishing a Simple Server Using Stream Sockets 1128 27.5 Establishing a Simple Client Using Stream Sockets 1130 27.6 Client/Server Interaction with Stream Socket Connections 1130 27.7 Datagrams: Connectionless Client/Server Interaction 1142 27.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server 1150

27.9 [Web Bonus] Case Study:DeitelMessenger 1165

27.10 Wrap-Up 1165

28 Accessing Databases with JDBC 1171

28.1 Introduction 1172

28.2 Relational Databases 1173

28.3 Relational Database Overview: ThebooksDatabase 1174

28.4 SQL 1177

28.4.1 BasicSELECTQuery 1178

28.4.2 WHEREClause 1179

28.4.3 ORDER BYClause 1181

28.4.4 Merging Data from Multiple Tables:INNER JOIN 1182

28.4.5 INSERTStatement 1184

28.4.6 UPDATEStatement 1185

28.4.7 DELETEStatement 1186

28.5 Instructions for Installing MySQL and MySQL Connector/J 1186 28.6 Instructions for Setting Up a MySQL User Account 1187

28.7 Creating Databasebooksin MySQL 1188

28.8 Manipulating Databases with JDBC 1189

28.8.1 Connecting to and Querying a Database 1189

28.8.2 Querying thebooksDatabase 1194

28.9 RowSetInterface 1207

28.10 Java DB/Apache Derby 1209

28.11 PreparedStatements 1211

28.12 Stored Procedures 1226

28.13 Transaction Processing 1227

28.14 Wrap-Up 1227

28.15 Web Resources 1228

(20)

29 JavaServer™ Faces Web Apps: Part 1 1235

29.1 Introduction 1236

29.2 HyperText Transfer Protocol (HTTP) Transactions 1237

29.3 Multitier Application Architecture 1240

29.4 Your First JSF Web App 1241

29.4.1 The Defaultindex.xhtmlDocument: Introducing Facelets 1242

29.4.2 Examining theWebTimeBeanClass 1244

29.4.3 Building theWebTimeJSF Web App in NetBeans 1246

29.5 Model-View-Controller Architecture of JSF Apps 1250

29.6 Common JSF Components 1250

29.7 Validation Using JSF Standard Validators 1254

29.8 Session Tracking 1261

29.8.1 Cookies 1262

29.8.2 Session Tracking with@SessionScopedBeans 1263

29.9 Wrap-Up 1269

30 JavaServer™ Faces Web Apps: Part 2 1276

30.1 Introduction 1277

30.2 Accessing Databases in Web Apps 1277

30.2.1 Setting Up the Database 1279

30.2.2 @ManagedBeanClassAddressBean 1282

30.2.3 index.xhtmlFacelets Page 1286

30.2.4 addentry.xhtmlFacelets Page 1288

30.3 Ajax 1290

30.4 Adding Ajax Functionality to the Validation App 1292

30.5 Wrap-Up 1295

31 Web Services 1299

31.1 Introduction 1300

31.2 Web Service Basics 1302

31.3 Simple Object Access Protocol (SOAP) 1302

31.4 Representational State Transfer (REST) 1302

31.5 JavaScript Object Notation (JSON) 1303

31.6 Publishing and Consuming SOAP-Based Web Services 1303 31.6.1 Creating a Web Application Project and Adding a Web

Service Class in NetBeans 1303

31.6.2 Defining theWelcomeSOAPWeb Service in NetBeans 1304 31.6.3 Publishing theWelcomeSOAPWeb Service from NetBeans 1307 31.6.4 Testing theWelcomeSOAPWeb Service with GlassFish

Application Server’sTesterWeb Page 1308

31.6.5 Describing a Web Service with the Web Service Description

Language (WSDL) 1309

31.6.6 Creating a Client to Consume theWelcomeSOAPWeb Service 1310

31.6.7 Consuming theWelcomeSOAPWeb Service 1312

(21)

Contents xix

31.7 Publishing and Consuming REST-Based XML Web Services 1315

31.7.1 Creating a REST-Based XML Web Service 1315

31.7.2 Consuming a REST-Based XML Web Service 1318

31.8 Publishing and Consuming REST-Based JSON Web Services 1320

31.8.1 Creating a REST-Based JSON Web Service 1320

31.8.2 Consuming a REST-Based JSON Web Service 1322

31.9 Session Tracking in a SOAP Web Service 1324

31.9.1 Creating aBlackjackWeb Service 1325

31.9.2 Consuming theBlackjackWeb Service 1328

31.10 Consuming a Database-Driven SOAP Web Service 1339

31.10.1 Creating theReservationDatabase 1340

31.10.2 Creating a Web Application to Interact with the

ReservationService 1343

31.11 Equation Generator: Returning User-Defined Types 1346 31.11.1 Creating theEquationGeneratorXMLWeb Service 1349 31.11.2 Consuming theEquationGeneratorXMLWeb Service 1350 31.11.3 Creating theEquationGeneratorJSONWeb Service 1354 31.11.4 Consuming theEquationGeneratorJSONWeb Service 1354

31.12 Wrap-Up 1357

A Operator Precedence Chart 1365

B ASCII Character Set 1367

C Keywords and Reserved Words 1368

D Primitive Types 1369

E Using the Java API Documentation 1370

E.1 Introduction 1370

E.2 Navigating the Java API 1370

F Using the Debugger 1378

F.1 Introduction 1379

F.2 Breakpoints and therun,stop,contandprintCommands 1379

F.3 TheprintandsetCommands 1383

F.4 Controlling Execution Using thestep,step upandnextCommands 1385

F.5 ThewatchCommand 1388

F.6 TheclearCommand 1391

F.7 Wrap-Up 1393

G Formatted Output 1395

G.1 Introduction 1396

(22)

G.2 Streams 1396

G.3 Formatting Output withprintf 1396

G.4 Printing Integers 1397

G.5 Printing Floating-Point Numbers 1398

G.6 Printing Strings and Characters 1400

G.7 Printing Dates and Times 1401

G.8 Other Conversion Characters 1403

G.9 Printing with Field Widths and Precisions 1405

G.10 Using Flags in theprintfFormat String 1407

G.11 Printing with Argument Indices 1411

G.12 Printing Literals and Escape Sequences 1411

G.13 Formatting Output with ClassFormatter 1412

G.14 Wrap-Up 1413

H Number Systems 1418

H.1 Introduction 1419

H.2 Abbreviating Binary Numbers as Octal and Hexadecimal Numbers 1422 H.3 Converting Octal and Hexadecimal Numbers to Binary Numbers 1423 H.4 Converting from Binary, Octal or Hexadecimal to Decimal 1423 H.5 Converting from Decimal to Binary, Octal or Hexadecimal 1424 H.6 Negative Binary Numbers: Two’s Complement Notation 1426

I GroupLayout 1431

I.1 Introduction 1431

I.2 GroupLayout Basics 1431

I.3 Building aColorChooser 1432

I.4 GroupLayoutWeb Resources 1442

J Java Desktop Integration Components 1443

J.1 Introduction 1443

J.2 Splash Screens 1443

J.3 DesktopClass 1445

J.4 Tray Icons 1447

K Mashups 1449

K.1 Introduction 1449

K.2 Popular Mashups 1449

K.3 APIs Commonly Used in Mashups 1450

K.4 Deitel Mashups Resource Center 1450

K.5 Deitel RSS Resource Center 1451

K.6 Mashup Performance and Reliability Issues 1451

L Unicode® 1452

L.1 Introduction 1452

(23)

Contents xxi

L.2 Unicode Transformation Formats 1453

L.3 Characters and Glyphs 1454

L.4 Advantages/Disadvantages of Unicode 1454

L.5 Using Unicode 1455

L.6 Character Ranges 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.1 Introduction M-1

M.2 Documentation Comments M-1

M.3 Documenting Java Source Code M-1

M.4 javadoc M-8

M.5 Files Produced byjavadoc M-9

N Bit Manipulation N-1

N.1 Introduction N-1

N.2 Bit Manipulation and the Bitwise Operators N-1

N.3 BitSetClass N-11

O Labeled break and continue Statements O-1

O.1 Introduction O-1

O.2 LabeledbreakStatement O-1

O.3 LabeledcontinueStatement O-2

P UML 2: Additional Diagram Types P-1

P.1 Introduction P-1

P.2 Additional Diagram Types P-1

Q Design Patterns Q-1

Q.1 Introduction Q-1

Q.2 Creational, Structural and Behavioral Design Patterns Q-2

Q.2.1 Creational Design Patterns Q-3

Q.2.2 Structural Design Patterns Q-5

(24)

Q.2.3 Behavioral Design Patterns Q-6

Q.2.4 Conclusion Q-7

Q.3 Design Patterns in Packagesjava.awtandjavax.swing Q-7

Q.3.1 Creational Design Patterns Q-7

Q.3.2 Structural Design Patterns Q-8

Q.3.3 Behavioral Design Patterns Q-10

Q.3.4 Conclusion Q-13

Q.4 Concurrency Design Patterns Q-14

Q.5 Design Patterns Used in Packagesjava.ioandjava.net Q-15

Q.5.1 Creational Design Patterns Q-15

Q.5.2 Structural Design Patterns Q-15

Q.5.3 Architectural Patterns Q-16

Q.5.4 Conclusion Q-19

Q.6 Design Patterns Used in Packagejava.util Q-19

Q.6.1 Creational Design Patterns Q-19

Q.6.2 Behavioral Design Patterns Q-19

Q.7 Wrap-Up Q-20

(25)

Live in fragments no longer, only connect.

Edgar Morgan Foster

Welcome to Java andJava How to Program, Ninth Edition! This book presents leading- edge 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 dis- cussion; 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 accompa- nied by live sample executions. All the source code is available atwww.deitel.com/books/

jhtp9/and at the book’s Companion Websitewww.pearsonhighered.com/deitel/. As you read the book, if you have questions, send an e-mail to [email protected]; 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 theDeitel®Buzz Onlinenewsletter (www.deitel.com/newsletter/subscribe.html).

New and Updated Features

Here are the updates we’ve made forJava 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 Edi- tion (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 inswitch statements, thetry-with-resources state- ment for managingAutoClosableobjects, multi-catchfor defining a single ex- ception 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.

Preface

(26)

Java SE 7 filesystem APIs.We provide analternateonline version of Chapter 17, Files, Streams and Object Serialization, that’s reimplemented with the new file- system APIs from Java SE 7.

Java SE 7’sAutoClosableversions ofConnection,StatementandResultSet. With the source code for Chapter 28, Accessing Databases with JDBC, we pro- vide a version of the chapter’s first example that’s implemented using Java SE 7’s

AutoClosable versions ofConnection, Statement andResultSet. AutoClos-

ableobjects reduce the likelihood of resource leaks when you use them with Java SE 7’stry-with-resources statement, which automatically closes theAutoClos-

ableobjects allocated in the parentheses following thetrykeyword.

Pedagogic Features

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 atwww.deitel.com/

MakingADifferencefor additional ideas you may want to investigate further.

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.

VideoNotes.The Companion Website includes extensive VideoNotes in which co-author Paul Deitel explains in detail most of the programs in the core chapters.

Instructors have told us that their students find the VideoNotes valuable.

Object Technology

Object-oriented programming and design.We introduce the basic concepts and terminology of object technology in Chapter 1. Students develop their first cus- tomized 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, considerJava How to Program, Late Objects Version, 8/e,which begins with six chapters on program- ming fundamentals (including two on control statements) and continues with sev- en chapters that gradually introduce object-oriented programming concepts.]

Exception handling. We integrate basic exception handling earlier in the book and instructors can easily pull more material forward from Chapter 11, Excep- tion Handling: A Deeper Look.

Class Arrays andArrayList. Chapter 7 covers class Arrays—which contains methods for performing common array manipulations—and classArrayList— which implements a dynamically resizable array-like data structure. This follows our philosophy of getting lots of practiceusing existing classes while learning how to define your own classes.

OO case studies.The early classes and objects presentation featuresTime,Employ-

eeandGradeBookclass case studies that weave their way through multiple sec- tions and chapters, gradually introducing deeper OO concepts.

(27)

New and Updated Features xxv

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 anoptional 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 re- quirements. From the design we produce acompleteJava implementation. Stu- dents often report having a “light-bulb moment”—the case study helps them “tie it all together” and really understand object orientation.

Reordered data structures presentation.We begin with generic classArrayList in Chapter 7. Becausestudents 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

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.

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 Ajax- enabled 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.

Web services.Chapter 31, Web Services, demonstrates creating and consuming SOAP-andREST-based web services. Case studies include developing blackjack and airline reservation web services.

Java Web Start and the Java Network Launch Protocol (JNLP).We introduce Java Web Start and JNLP, which enable appletsandapplications 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—en- abling you to develop more robust applets and applications that execute safely us- ing Java’s sandbox security model, which applies to downloaded code.

Multithreading

Multithreading. We completely reworked Chapter 26, Multithreading [special thanks to the guidance of Brian Goetz and Joseph Bowbeer—two of the co-au- thors ofJava Concurrency in Practice,Addison-Wesley, 2006].

SwingWorkerclass.We use classSwingWorkerto createmultithreaded user interfaces.

(28)

GUI and Graphics

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.

GroupLayout layout manager.We discuss the GroupLayoutlayout manager in the context of the GUI design tool in the NetBeans IDE.

JTablesorting and filtering capabilities.Chapter 28 uses these capabilities to re- sort the data in aJTableand filter it by regular expressions.

Other Features

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 bookAndroid 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 fromdeveloper.android.com.

Software engineering community concepts. We discuss agile software develop- ment, 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 multime- dia 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.

Syntax Coloring.For readability, we syntax color all the Java code, similar to the way most Java integrated-development environments and code editors syntax color code. Our syn- tax-coloring conventions are as follows:

comments appear in green keywords appear in dark blue errors appear in red

constants and literal values appear in light blue all other code appears in black

(29)

Teaching Approach xxvii

Introduction

1 Introduction to Computers and Java

Intro to Programming, Classes and Objects

2 Intro to Java Applications 3 Intro to Classes and Objects

Control Statements, Methods and Arrays

4 Control Statements: Part 1 5 Control Statements: Part 2 6 Methods: A Deeper Look 7 Arrays andArrayLists

Object-Oriented Programming

Object-Oriented Design with the UML

10 Object-Oriented Programming:

Polymorphism 8 Classes and Objects:

A Deeper Look 9 Object-Oriented Programming:

Inheritance

11 Exception Handling

13 (Optional) Implementing an Object-Oriented Design 12 (Optional) Object-Oriented

Design with the UML

14 GUI Components: Part 1 15 Graphics and Java2D

24 Multimedia: Applets and Applications 25 GUI Components:

Part 2 23 Applets and Java Web Start5 3.9 Using Dialog Boxes 4.14 Creating Simple Drawings

5.10 Drawing Rectangles and Ovals 6.13 Colors and Filled Shapes

7.15 Drawing Arcs 8.16 Using Objects with Graphics 9.8 Displaying Text and

Images Using Labels 10.8 Drawing with

Polymorphism

(Optional) GUI & Graphics Track

GUI, Graphics, Applets and Multimedia

18 Recursion1

21 Generic Classes and Methods 19 Searching, Sorting and Big O 20 Generic Collections

22 Custom Generic Data Structures

Data Structures

Multithreading and Networking

Database-Driven Desktop and Web Development

Strings and Files

16 Strings, Characters and Regular Expressions 17 Files, Streams and Object

Serialization

27 Networking3 26 Multithreading2

28 JDBC4 29 JSF Web Apps: Part 1 30 JSF Web Apps: Part 2

31 Web Services

Modules and Chapter Dependency Chart

2.Chapter 26is dependent onChapter 14for GUI used in one example and onChapters 20–21for one example.

3.Chapter 27is dependent onChapter 23for one example that uses an applet. The large case study (on the web) depends onChapter 25for GUI andChapter 26for multithreading.

4.Chapter 28is dependent onChapter 14for GUI used in one example.

5. More applets are covered inChapters 24and27.

[Note:Arrows pointing into a chapter indicate that chapter’s dependencies. Some chapters have multiple dependencies.]

1.Chapter 18is dependent onChapters 14and15for GUI and graphics used in one example.

(30)

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 inbold maroon text for easier reference. We emphasize on-screen components in thebold Helveticafont (e.g., theFilemenu) and emphasize Java program text in theLucidafont (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 pro- gram 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.

www.deitel.com/books/jhtp9 www.pearsonhighered.com/deitel

Good Programming Practices

TheGood Programming Practicescall attention to techniques that will help you pro- duce programs that are clearer, more understandable and more maintainable. 3.0

Common Programming Errors

Pointing out theseCommon Programming Errors reduces the likelihood that you’ll

make them. 3.0

Error-Prevention Tips

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. 3.0

Performance Tips

These tips highlight opportunities for making your programs run faster or minimizing the

amount of memory that they occupy. 3.0

Portability Tips

ThePortability Tipshelp you write code that will run on a variety of platforms. 3.0

Software Engineering Observations

TheSoftware Engineering Observationshighlight architectural and design issues that affect the construction of software systems, especially large-scale systems. 3.0

Look-and-Feel Observations

TheLook-and-Feel Observationshighlight graphical-user-interface conventions. These observations help you design attractive, user-friendly graphical user interfaces that con-

form to industry norms. 3.0

(31)

Software Used in Java How to Program, 9/e xxix

Summary Bullets.We present a section-by-section bullet-list summary of the chapter. For ease of reference, we include the page number of each key term’s defining occurrence in the text.

Self-Review Exercises and Answers.Extensive self-review exercisesandanswers are includ- ed for self study. All of the exercises in the optional ATM case study are fully solved.

Exercises.The chapter exercises include:

• simple recall of important terminology and concepts

• What’s wrong with this code?

• What does this code do?

• writing individual statements and small portions of methods and classes

• writing complete methods, classes and programs

• major projects

• in many chapters, Making a Difference exercises.

Index.We’ve included an extensive index. Defining occurrences of key terms are high- lighted with abold maroonpage number.

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 inJava How to Program, 9/e, using the free Java Stan- dard 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 addi- tional resources and software downloads in our Java Resource Centers at:

Java IDE Resource Kit

Your instructor may have ordered through your college bookstore a Value Pack edition of Java How to Program, 9/ethat comes bundled with the Java IDE Resource Kit. This kit contains CD or DVD versions of Java™ SE Development Kit 6 for Windows®, Eclipse™

IDE for Windows®, NetBeans™ IDE, jGRASP™ IDE, DrJava IDE, BlueJ IDE and the TextPad®Text Editor for Windows®. Free versions of these IDEs also can be downloaded from the web. The Java IDE Resource Kit also includes access to a Companion Website containing step-by-step VideoNotes and written instructions to help you get started with each development environment. If your book did not come with the Java IDE Resource Kit, you can purchase access to the Resource Kit’s Companion Website fromwww.pear-

sonhighered.com/javaidekit/. You’ll still need to download the free software separately.

Discounts on Deitel Developer Series Books

If you’d like to receive information on professionalDeitel Developer Seriestitles, including Android for Programmers: An App-Driven Approach, please register your copy ofJava How

www.deitel.com/ResourceCenters.html

(32)

to Program, 9/eatinformit.com/register. You’ll receive information on how to purchase Android for Programmersat a discount.

CourseSmart Web Books

Today’s students and instructors have increasing demands on their time and money. Pear- son has responded to that need by offering digital texts and course materials online through CourseSmart. CourseSmart allows faculty to review course materials online, sav- ing time and costs. It offers students a high-quality digital version of the text for less than the cost of a print copy of the text. Students receive the same content offered in the print textbook enhanced by search, note-taking, and printing tools. For more information, visit

www.coursesmart.com.

Instructor Supplements

The following supplements are available to qualified instructors only through Pearson Education’s Instructor Resource Center (www.pearsonhighered.com/irc):

PowerPoint®slidescontaining all the code and figures in the text, plus bulleted items that summarize key points.

Test Item Fileof multiple-choice questions (approximately two per book section).

Solutions Manualwith solutions to the vast majority of the end-of-chapter exer- cises.

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. Ac- cess is limited strictly to college instructors teaching from the book. Instructors may ob- tain access only through their Pearson representatives. Solutions arenotprovided for

“project” exercises.Check out our Programming Projects Resource Center for lots of ad- ditional exercise and project possibilities (www.deitel.com/ProgrammingProjects/).

If you’re not a registered faculty member, contact your Pearson representative or visit

www.pearsonhighered.com/educator/replocator/.

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 pro- fessionals 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 scru- tinized 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 Di- ego State University), Lawrence Premkumar (Sun Microsystems), Tim Margush (Univer-

(33)

About the Authors xxxi

sity of Akron), Sue McFarland Metzger (Villanova University), Shyamal Mitra (The University of Texas at Austin), Peter Pilgrim (Consultant), Manjeet Rege, Ph.D. (Roch- ester 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, criti- cisms, corrections and suggestions for improvement. Please address all correspondence to:

We’ll respond promptly. We hope you enjoy working withJava 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, Lu- cent 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 Soft- ware, Adra Systems, Entergy, CableData Systems, Nortel Networks, Puma, iRobot, In- vensys and many more. He and his co-author, Dr. Harvey M. Deitel, are the world’s best- selling 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 Sci- ence 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, Chi- nese, Spanish, Korean, French, Polish, Italian, Portuguese, Greek, Urdu and Turkish. Dr.

Deitel has delivered hundreds of professional programming seminars to major corpora- tions, 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 world- wide on major programming languages and platforms, such as Java™, C++, Visual C++®, C, Visual C#®, Visual Basic®, XML®, Python®

Gambar

Fig. 1.3 | Levels of the data hierarchy. (Part 1 of 2.)
Fig. 1.8 | Typical Java development environment—loading phase.
Fig. 1.10 | Typical Java development environment—execution phase.
Fig. 1.14 | Entering a valid PIN number and displaying the ATM application’s main menu.
+7

Referensi

Dokumen terkait