1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu ABSOLUTE JAVA pptx

1,3K 1,2K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Absolute Java 5th Edition
Tác giả Walter Savitch, Kenrick Mock
Trường học University of California, San Diego
Thể loại Sách giáo trình
Năm xuất bản N/A
Thành phố San Diego
Định dạng
Số trang 1.306
Dung lượng 6,9 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 1 Getting Started 1 1.1 INTRODUCTION TO JAVA 2 Origins of the Java Language ★ 2 Objects and Methods 3 Applets ★ 4 A Sample Java Application Program 5 Byte-Code and t

Trang 3

ABSOLUTE

5 th Edition

Trang 5

University of Alaska Anchorage

Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montréal Toronto

Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Trang 6

Editor in Chief: Michael Hirsch

Executive Editor: Matt Goldstein

Editorial Assistant: Emma Snider

Vice President Marketing: Patrice Jones

Marketing Manager: Yez Alayan

Marketing Coordinator: Kathryn Ferranti

Vice President and Director of

Production: Vince O’Brien

Managing Editor: Jeff Holcomb

Senior Production Project Manager: Marilyn Lloyd

Manufacturing Manager: Nick Skilitis

Cover Designer: Anthony Gemmellaro Cover Image: B0NGR1 Alamy Media Editor: Dan Sandin Text Permissions—assessment: Dana Weightman Text Permissions—clearance: Jenn Kennett/Creative

Compliance

Full-Service Vendor: GEX Publishing Services Project Management: GEX Publishing Services Printer/Binder: Edwards Brothers

Cover Printer: Lehigh-Phoenix Color

This book was composed in InDesign Basal font is Adobe Garamond 10/12 Display font is Optima LT Std Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text.

Copyright © 2013, 2010, 2008, 2006, 2004 by Pearson Education, Inc., publishing as Addison-Wesley 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, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to 201-236-3290.

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 designa- tions have been printed in initial caps or all caps.

CIP data available upon request

10 9 8 7 6 5 4 3 2 1

ISBN 10: 0-13-283031-0 ISBN 13: 978-0-13-283031-7

Trang 7

This book is designed to serve as a textbook and reference for programming in the Java language Although it does include programming techniques, it is organized around the features of the Java language rather than any particular curriculum of programming techniques The main audience I had in mind when writing this book was undergraduate students who have not had extensive programming experience with the Java language As such, it would be a suitable Java text or reference for either a first programming course or a later computer science course that uses Java This book is designed to accommodate a wide range of users The introductory chapters are written

at a level that is accessible to beginners, while the boxed sections of those chapters serve to quickly introduce more experienced programmers to basic Java syntax Later chapters are still designed to be accessible, but are written at a level suitable for students who have progressed to these more advanced topics

CHANGES IN THIS EDITION

This fifth edition presents the same programming philosophy as the fourth edition

For instructors, you can teach the same course, presenting the same topics in the same

order with no changes in the material covered or the chapters assigned The changes to

this edition consist almost exclusively of supplementary material added to the chapters

of the previous edition, namely:

■ Updates have been made for language changes in Java 7, such as allowing strings in switch statements

■ Twenty-five new programming projects have been added By request, some of these are longer and less prescriptive projects to give the student more practice designing programming solutions

■ 15 new video notes have been created for a total of 46 video notes These videos cover specific topics and offer solutions to the programming projects; they have been added to the book’s website The solutions walk students through the process of problem solving and coding to reinforce key programming concepts An icon appears in the margin of the book when a video is available regarding the corresponding topic in the text

■ Chapter 2 now describes how to use the Scanner class to read from a text file so based programming projects can be explored prior to detailed coverage of File I/O in Chapter 10

data-■ A brief introduction to the Random class has been added to Chapter 3

■ Chapter 9 on exception handling begins with a new introduction of try/catch for handling input mismatch exceptions before discussing how to throw custom exceptions

■ A recursive algorithm to search the file system has been added to Chapter 11

■ Material on race conditions and thread synchronization has been added to Chapter 19

■ Ten new self-test exercises have been added along with the new material

v

Trang 8

This book gives extensive coverage of encapsulation, inheritance, and polymorphism

as realized in the Java language The chapters on Swing GUIs provide coverage of and extensive practice with event driven programming A chapter on UML and patterns gives additional coverage of OOP-related material

FLEXIBILITY IN TOPIC ORDERING

This book allows instructors wide latitude in reordering the material This is important

if a book is to serve as a reference It is also in keeping with my philosophy of writing books that accommodate themselves to an instructor’s style rather than tying the instructor to an author’s personal preference of topic ordering With this in mind, each chapter has a prerequisite section at the beginning; this section explains what material must be covered before doing each section of the chapter Starred sections, which are explained next, further add to flexibility

STARRED SECTIONS

Each chapter has a number of starred (★) sections, which can be considered optional These sections contain material that beginners might find difficult and that can be omitted or delayed without hurting the continuity of the text It is hoped that eventually the reader would return and cover this material For more advanced students, the starred sections should not be viewed as optional

ACCESSIBLE TO STUDENTS

It is not enough for a book to present the right topics in the right order It is not even enough for it to be clear and correct when read by an instructor or other expert The material needs to be presented in a way that is accessible to the person who does not yet know the content Like my other textbooks that have proven to be very popular, this book was written to be friendly and accessible to the student

SUMMARY BOXES

Each major point is summarized in a short boxed section These boxed sections are spread throughout each chapter They serve as summaries of the material, as a quick reference source, and as a way to quickly learn the Java syntax for features the reader knows about in general but for which he or she needs to know the Java particulars

Trang 9

SELF-TEST EXERCISES

Each chapter contains numerous Self-Test Exercises at strategic points in the chapter Complete answers for all the Self-Test Exercises are given at the end of each chapter

VIDEO NOTES

VideoNotes are step-by-step videos that guide readers through the solution to an

end-of-chapter problem or further illuminate a concept presented in the text Icons in the text indicate where a VideoNote enhances a topic Fully navigable problems allow for self-paced instruction VideoNotes are located at www.pearsonhighered.com/savitch

OTHER FEATURES

Pitfall sections, programming tip sections, and examples of complete programs with sample I/O are given throughout each chapter Each chapter ends with a summary section and a collection of programming projects suitable to assign to students

ONLINE PRACTICE AND ASSESSMENT WITH

MyProgrammingLab

MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of programming Through practice exercises and immediate, personalized feedback, MyProgrammingLab improves the programming competence of beginning students who often struggle with the basic concepts and paradigms of popular high-level programming languages

A self-study and homework tool, a MyProgrammingLab course consists of hundreds

of small practice problems organized around the structure of this textbook For students, the system automatically detects errors in the logic and syntax of their code submissions and offers targeted hints that enable students to figure out what went wrong—and why For instructors, a comprehensive gradebook tracks correct and incorrect answers and stores the code inputted by students for review

MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the makers of the CodeLab interactive programming exercise system For a full demonstration, to see feedback from instructors and students, or to get started using MyProgrammingLab in your course, visit www.myprogramminglab.com

SUPPORT MATERIAL

The following support materials are available to all users of this book at www

pearsonhighered.com/cssupport:

■ Source code from the book

The following resources are available to qualifi ed instructors only at www pearsonhighered

com/irc Please contact your local sales representative for access information:

■ Instructor’s Manual with Solutions

■ PowerPoint® slides

VideoNote

Trang 10

Integrated Development Environment Resource Kits

Professors who adopt this text can order it for students with a kit containing seven popular Java IDEs (the most recent JDK from Oracle, Eclipse, NetBeans, jGRASP, DrJava, BlueJ, and TextPad) The kit also includes access to a website containing written and video tutorials for getting started in each IDE For ordering information, please contact your campus Pearson Education representative or visit www.pearsonhighered.com

edi-fi nal typeset book

The following reviewers provided corrections and suggestions for this book Their contributions were a great help I thank them all In alphabetical order they are: Jim Adams Chandler-Gilbert Community College Gerald W Adkins Georgia College & State University

Prof Richard G Baldwin Austin Community College Kevin Bierre Rochester Institute of Technology

Janet Brown-Sederberg Massasoit Community College

Charlotte Busch Texas A&M University, Corpus Christi Stephen Chandler NW Shoals Community College

Adrienne Decker University of Buffalo

Ahmad Ghafarian North Georgia College & State University

Massoud Ghyam University of Southern California

Judy Hankins Middle Tennessee State University

Trang 11

Sterling Hough NHTI

Eliot Jacobson University of California, Santa Barbara

Balaji Janamanchi Texas Tech University

Dr Clifford R Kettemborough IT Consultant and Professor

Mark M Meysenburg Doane College

Sridhar P Nerur The University of Texas at Arlington

Prof Bryson R Payne North Georgia College & State University

David Primeaux Virginia Commonwealth University

Neil Rhodes University of California, San Diego

W Brent Seales University of Kentucky

Riyaz Sikora The University of Texas at Arlington

Donald J Smith Community College of Allegheny County

Xueqing (Clare) Tang Governors State University

Ronald F Taylor Wright State University

Shon Vick University of Maryland, Baltimore County

Natalie S Wear University of South Florida

David A Wheeler

Special thanks goes to Kenrick Mock (University of Alaska Anchorage) who executed the updating of this edition He once again had the difficult job of satisfying

me, the editor, and himself I thank him for a truly excellent job

Trang 12

www.pearsonhighered.com/savitch

Chapter 1 Compiling a Java Program, page 10

Solution to Programming Project 1.7, page 56

Chapter 2 Pitfalls Involving nextLine() , page 83

Solution to Programming Project 2.11, page 97

Solution to Programming Project 2.12, page 98

Chapter 3 Nested Loop Example, page 145

Debugging Walkthrough, page 152

Solution to Programming Project 3.9, page 170

Solution to Programming Project 3.13, page 171

Chapter 4 Information Hiding Example, page 207

Example Using the StringTokenizer Class on a CSV File, page 247 Solution to Programming Project 4.9, page 255

Chapter 5 Deep Copy vs Shallow Copy Example, page 321

Solution to Programming Project 5.9, page 344

Chapter 6 Arrays of Objects, page 358

Solution to Programming Project 6.8, page 422

Solution to Programming Project 6.15, page 424

Chapter 7 Inheritance Walkthrough, page 432

Solution to Programming Project 7.3, page 477

Solution to Programming Project 7.5, page 479

Chapter 8 Late Binding Example, page 486

Solution to Programming Project 8.1, page 518

Solution to Programming Project 8.9, page 521

Chapter 9 Solution to Programming Project 9.1, page 574

Solution to Programming Project 9.7, page 576

Chapter 10 Reading a Text File, page 589

Solution to Programming Project 10.1, page 643

Solution to Programming Project 10.8, page 645

Chapter 11 Recursion and the Stack, page 660

Solution to Programming Project 11.3, page 684

Chapter 12 Solution to Programming Project 12.9, page 710

Chapter 13 Solution to Programming Project 13.1, page 754

Solution to Programming Project 13.11, page 757

Chapter 14 Solution to Programming Project 14.7, page 801

Chapter 15 Walkthrough of the Hash Table Class, page 868

Solution to Programming Project 15.1, page 893

Trang 13

Solution to Programming Project 16.5, page 938

Chapter 17 GUI Layout Using an IDE, page 969

Solution to Programming Project 17.1, page 1013

Chapter 18 Walkthrough of a Simple Drawing Program, page 1042

Solution to Programming Project 18.7, page 1077

Chapter 19 Walkthrough of a Program with Race Conditions, page 1094

Solution to Programming Project 19.3, page 1135

Solution to Programming Project 19.11, page 1136

Chapter 20 No video notes (Chapter on website)

Trang 15

Chapter 1 GETTING STARTED 1

Chapter 2 CONSOLE INPUT AND OUTPUT 57

Chapter 3 FLOW OF CONTROL 99

Chapter 4 DEFINING CLASSES I 173

Chapter 5 DEFINING CLASSES II 259

Chapter 6 ARRAYS 345

Chapter 7 INHERITANCE 427

Chapter 8 POLYMORPHISM AND ABSTRACT CLASSES 483

Chapter 9 EXCEPTION HANDLING 523

Chapter 10 FILE I/O 577

Chapter 11 RECURSION 647

Chapter 12 UML AND PATTERNS 689

Chapter 13 INTERFACES AND INNER CLASSES 711

Chapter 14 GENERICS AND THE ArrayList CLASS 759

Chapter 15 LINKED DATA STRUCTURES 801

Chapter 16 COLLECTIONS, MAPS AND ITERATORS 897

Chapter 17 SWING I 941

Chapter 18 SWING II 1017

Chapter 19 JAVA NEVER ENDS 1079

Chapter 20 APPLETS AND HTML 1137

Appendix 1 KEYWORDS 1139

Appendix 2 PRECEDENCE AND ASSOCIATIVITY RULES 1141

Appendix 3 ASCII CHARACTER SET 1143

Appendix 4 FORMAT SPECIFICATIONS FOR printf 1145

Appendix 5 SUMMARY OF CLASSES AND INTERFACES 1147

INDEX 1215

xiii

Trang 17

Chapter 1 Getting Started 1

1.1 INTRODUCTION TO JAVA 2

Origins of the Java Language ★ 2

Objects and Methods 3

Applets ★ 4

A Sample Java Application Program 5

Byte-Code and the Java Virtual Machine 8

Class Loader ★ 10

Compiling a Java Program or Class 10

Running a Java Program 11

TIP: Error Messages 12

1.2 EXPRESSIONS AND ASSIGNMENT STATEMENTS 13

Identifi ers 13

Variables 15

Assignment Statements 16

TIP: Initialize Variables 18

More Assignment Statements ★ 19

Assignment Compatibility 20

Constants 21

Arithmetic Operators and Expressions 23

Parentheses and Precedence Rules ★ 24

Integer and Floating-Point Division 26

PITFALL: Round-Off Errors in Floating-Point Numbers 27

PITFALL: Division with Whole Numbers 28

Type Casting 29

Increment and Decrement Operators 30

1.3 THE CLASS String 33

String Constants and Variables 33

Trang 18

1.4 PROGRAM STYLE 46

Naming Constants 46 Java Spelling Conventions 48 Comments 49

Indenting 50 Chapter Summary 51 Answers to Self-Test Exercises 52 Programming Projects 54

Chapter 2 Console Input and Output 57

2.1 SCREEN OUTPUT 58

System.out.println 58 TIP: Different Approaches to Formatting Output 61 Formatting Output with printf 61

TIP: Formatting Monetary Amounts with printf 65 TIP: Legacy Code 66

Money Formats Using NumberFormat ★ 67 Importing Packages and Classes 70 The DecimalFormat Class ★ 72

2.2 CONSOLE INPUT USING THE Scanner CLASS 76

The Scanner Class 76 PITFALL: Dealing with the Line Terminator, '\n' 83 The Empty String 84

TIP: Prompt for Input 84 TIP: Echo Input 84 EXAMPLE: Self-Service Checkout 86 Other Input Delimiters 87

2.3 INTRODUCTION TO FILE INPUT 89

The Scanner Class for Text File Input 89 Chapter Summary 92

Answers to Self-Test Exercises 92 Programming Projects 95

Chapter 3 Flow of Control 99

3.1 BRANCHING MECHANISM 100

if-else Statements 100 Omitting the else 101 Compound Statements 102 TIP: Placing of Braces 103 Nested Statements 104

Trang 19

Multiway if-else Statement 104

EXAMPLE: State Income Tax 105

The switch Statement 107

PITFALL: Forgetting a break in a switch Statement 111

The Conditional Operator ★ 112

3.2 BOOLEAN EXPRESSIONS 113

Simple Boolean Expressions 113

PITFALL: Using = in Place of == 114

PITFALL: Using == with Strings 115

Lexicographic and Alphabetical Order 116

Building Boolean Expressions 119

PITFALL: Strings of Inequalities 120

Evaluating Boolean Expressions 120

TIP: Naming Boolean Variables 123

Short-Circuit and Complete Evaluation 124

Precedence and Associativity Rules 125

3.3 LOOPS 132

while Statement and do-while Statement 132

Algorithms and Pseudocode 134

EXAMPLE: Averaging a List of Scores 137

The for Statement 138

The Comma in for Statements 141

TIP: Repeat N Times Loops 143

PITFALL: Extra Semicolon in a for Statement 143

PITFALL: Infi nite Loops 144

Nested Loops 145

The break and continue Statements ★ 148

The exit Statement 149

3.4 DEBUGGING 150

Loop Bugs 150

Tracing Variables 150

General Debugging Techniques 151

EXAMPLE: Debugging an Input Validation Loop 152

Preventive Coding 156

Assertion Checks ★ 157

3.5 RANDOM NUMBER GENERATION 159

The Random Object 160

The Math.random() Method 161

Chapter Summary 162

Answers to Self-Test Exercises 162

Programming Projects 168

Trang 20

Chapter 4 Defi ning Classes I 173

PITFALL: Use of the Terms “Parameter” and “Argument” 195 Simple Cases with Class Parameters 197

The this Parameter 197 Methods That Return a Boolean Value 199 The Methods equals and toString 202 Recursive Methods 205

TIP: Testing Methods 205

4.2 INFORMATION HIDING AND ENCAPSULATION 207

public and private Modifi ers 208 EXAMPLE: Yet Another Date Class 209 Accessor and Mutator Methods 210 TIP: A Class Has Access to Private Members of All Objects of the Class 215 TIP: Mutator Methods Can Return a Boolean Value ★ 216

Preconditions and Postconditions 217

4.3 OVERLOADING 218

Rules for Overloading 218 PITFALL: Overloading and Automatic Type Conversion 222 PITFALL: You Cannot Overload Based on the Type Returned 224

4.4 CONSTRUCTORS 226

Constructor Defi nitions 226 TIP: You Can Invoke Another Method in a Constructor 234 TIP: A Constructor Has a this Parameter 234

TIP: Include a No-Argument Constructor 235 EXAMPLE: The Final Date Class 236

Default Variable Initializations 237

An Alternative Way to Initialize Instance Variables 237 EXAMPLE: A Pet Record Class 238

The StringTokenizer Class ★ 242 Chapter Summary 247

Answers to Self-Test Exercises 248 Programming Projects 253

Trang 21

Chapter 5 Defi ning Classes II 259

5.1 STATIC METHODS AND STATIC VARIABLES 261

Static Methods 261

PITFALL: Invoking a Nonstatic Method Within a Static Method 263

TIP: You Can Put a main in Any Class 264

Static Variables 268

The Math Class 273

Wrapper Classes 277

Automatic Boxing and Unboxing 278

Static Methods in Wrapper Classes 280

PITFALL: A Wrapper Class Does Not Have a No-Argument Constructor 283

5.2 REFERENCES AND CLASS PARAMETERS 284

Variables and Memory 285

References 286

Class Parameters 291

PITFALL: Use of = and == with Variables of a Class Type 295

The Constant null 297

PITFALL: Null Pointer Exception 298

The new Operator and Anonymous Objects 298

EXAMPLE: Another Approach to Keyboard Input ★ 299

TIP: Use Static Imports ★ 301

5.3 USING AND MISUSING REFERENCES 303

EXAMPLE: A Person Class 304

PITFALL: null Can Be an Argument to a Method 309

Copy Constructors 313

PITFALL: Privacy Leaks 315

Mutable and Immutable Classes 319

TIP: Deep Copy versus Shallow Copy 321

TIP: Assume Your Coworkers Are Malicious 322

5.4 PACKAGES AND javadoc 322

Packages and import Statements 323

The Package java.lang 324

Package Names and Directories 324

PITFALL: Subdirectories Are Not Automatically Imported 327

The Default Package 327

PITFALL: Not Including the Current Directory in Your Class Path 328

Specifying a Class Path When You Compile ★ 328

Name Clashes ★ 329

Introduction to javadoc★ 330

Commenting Classes for javadoc★ 330

Running javadoc★ 332

Trang 22

Chapter Summary 334 Answers to Self-Test Exercises 335 Programming Projects 339

Chapter 6 Arrays 345

6.1 INTRODUCTION TO ARRAYS 346

Creating and Accessing Arrays 347 The length Instance Variable 350 TIP: Use for Loops with Arrays 352 PITFALL: Array Indices Always Start with Zero 352 PITFALL: Array Index Out of Bounds 352

Initializing Arrays 353 PITFALL: An Array of Characters Is Not a String 355

6.2 ARRAYS AND REFERENCES 356

Arrays Are Objects 356 PITFALL: Arrays with a Class Base Type 358 Array Parameters 358

PITFALL: Use of = and == with Arrays 360 Arguments for the Method main★ 365 Methods that Return an Array 367

6.3 PROGRAMMING WITH ARRAYS 368

Partially Filled Arrays 369 EXAMPLE: A Class for Partially Filled Arrays 372 TIP: Accessor Methods Need Not Simply Return Instance Variables 376 The “for-each” Loop ★ 376

Methods with a Variable Number of Parameters ★ 380 EXAMPLE: A String Processing Example ★ 383 Privacy Leaks with Array Instance Variables 384 Enumerated Types ★ 386

EXAMPLE: Sorting an Array 388 TIP: Enumerated Types in switch Statements ★ 397

6.4 MULTIDIMENSIONAL ARRAYS 399

Multidimensional Array Basics 399 Using the length Instance Variable 402 Ragged Arrays ★ 403

Multidimensional Array Parameters and Returned Values 403 EXAMPLE: A Grade Book Class 404

Chapter Summary 410 Answers to Self-Test Exercises 411 Programming Projects 418

Trang 23

Chapter 7 Inheritance 427

7.1 INHERITANCE BASICS 428

Derived Classes 429

Overriding a Method Defi nition 439

Changing the Return Type of an Overridden Method 439

Changing the Access Permission of an Overridden Method 440

PITFALL: Overriding versus Overloading 441

The super Constructor 442

The this Constructor 444

TIP: An Object of a Derived Class Has More than One Type 445

PITFALL: The Terms Subclass and Superclass 448

EXAMPLE: An Enhanced StringTokenizer Class ★ 449

7.2 ENCAPSULATION AND INHERITANCE 452

PITFALL: Use of Private Instance Variables from the Base Class 453

PITFALL: Private Methods Are Effectively Not Inherited 454

Protected and Package Access 455

PITFALL: Forgetting about the Default Package 458

PITFALL: A Restriction on Protected Access ★ 458

7.3 PROGRAMMING WITH INHERITANCE 461

TIP: Static Variables Are Inherited 461

TIP: “is a” versus “has a” 461

Access to a Redefi ned Base Method 461

PITFALL: You Cannot Use Multiple super s 463

The Class Object 464

The Right Way to Defi ne equals 465

TIP: getClass versus instanceof★ 467

The final Modifi er 487

EXAMPLE: Sales Records 488

Late Binding with toString 495

PITFALL: No Late Binding for Static Methods 496

Downcasting and Upcasting 497

PITFALL: Downcasting 501

Trang 24

TIP: Checking to See Whether Downcasting Is Legitimate ★ 501

A First Look at the clone Method 504 PITFALL: Sometimes the clone Method Return Type Is Object 505 PITFALL: Limitations of Copy Constructors ★ 506

8.2 ABSTRACT CLASSES 509

Abstract Classes 510 PITFALL: You Cannot Create Instances of an Abstract Class 514 TIP: An Abstract Class Is a Type 515

Chapter Summary 516 Answers to Self-Test Exercises 516 Programming Projects 518

Chapter 9 Exception Handling 523

9.1 EXCEPTION HANDLING BASICS 525

try-catch Mechanism 525 Exception Handling with the Scanner Class 527 TIP: Exception Controlled Loops 528

Throwing Exceptions 530 EXAMPLE: A Toy Example of Exception Handling 532 Exception Classes 537

Exception Classes from Standard Packages 538 Defi ning Exception Classes 540

TIP: Preserve getMessage 544 TIP: An Exception Class Can Carry a Message of Any Type 546 Multiple catch Blocks 551

PITFALL: Catch the More Specifi c Exception First 553

9.2 THROWING EXCEPTIONS IN METHODS 556

Throwing an Exception in a Method 556 Declaring Exceptions in a throws Clause 558 Exceptions to the Catch or Declare Rule 561

throws Clause in Derived Classes 562 When to Use Exceptions 563

ArrayIndexOutOfBoundsException 569

Trang 25

Chapter Summary 569

Answers to Self-Test Exercises 570

Programming Projects 574

Chapter 10 File I/O 577

10.1 INTRODUCTION TO FILE I/O 578

Streams 578

Text Files and Binary Files 579

10.2 TEXT FILES 580

Writing to a Text File 580

PITFALL: A try Block Is a Block 586

PITFALL: Overwriting an Output File 586

Appending to a Text File 587

TIP: toString Helps with Text File Output 588

Reading from a Text File 589

Reading a Text File Using Scanner 589

Testing for the End of a Text File with Scanner 592

Reading a Text File Using BufferedReader 599

TIP: Reading Numbers with BufferedReader 603

Testing for the End of a Text File with BufferedReader 603

Path Names 605

Nested Constructor Invocations 606

System.in, System.out, and System.err 607

10.3 THE File CLASS 609

Programming with the File Class 609

10.4 BINARY FILES 613

Writing Simple Data to a Binary File 614

UTF and writeUTF 618

Reading Simple Data from a Binary File 619

Checking for the End of a Binary File 624

PITFALL: Checking for the End of a File in the Wrong Way 625

Binary I/O of Objects 626

The Serializable Interface 627

PITFALL: Mixing Class Types in the Same File 630

Array Objects in Binary Files 630

10.5 RANDOM ACCESS TO BINARY FILES 632

Reading and Writing to the Same File 632

PITFALL: RandomAccessFile Need Not Start Empty 638

Trang 26

Chapter Summary 638 Answers to Self-Test Exercises 639 Programming Projects 643

Chapter 11 Recursion 647

11.1 RECURSIVE Void METHODS 649

EXAMPLE: Vertical Numbers 649 Tracing a Recursive Call 652

A Closer Look at Recursion 655 PITFALL: Infi nite Recursion 657 Stacks for Recursion ★ 658 PITFALL: Stack Overfl ow ★ 660 Recursion versus Iteration 660

11.2 RECURSIVE METHODS THAT RETURN A VALUE 661

General Form for a Recursive Method That Returns a Value 662 EXAMPLE: Another Powers Method 662

Chapter 12 UML and Patterns 689

12.1 UML 690

History of UML 691 UML Class Diagrams 691 Class Interactions 692 Inheritance Diagrams 692 More UML 694

12.2 PATTERNS 695

Adaptor Pattern ★ 695 The Model-View-Controller Pattern ★ 696 EXAMPLE: A Sorting Pattern 697

Restrictions on the Sorting Pattern 703 Effi ciency of the Sorting Pattern ★ 703

Trang 27

TIP: Pragmatics and Patterns 704

PITFALL: Interface Semantics Are Not Enforced 717

The Comparable Interface 719

EXAMPLE: Using the Comparable Interface 720

Defi ned Constants in Interfaces 725

PITFALL: Inconsistent Interfaces 726

The Serializable Interface ★ 729

The Cloneable Interface 729

13.2 SIMPLE USES OF INNER CLASSES 734

Helping Classes 734

TIP: Inner and Outer Classes Have Access to Each Other’s Private Members 735 EXAMPLE: A Bank Account Class 735

The class File for an Inner Class 739

PITFALL: Other Uses of Inner Classes 740

13.3 MORE ABOUT INNER CLASSES 740

Static Inner Classes 740

Public Inner Classes 741

TIP: Referring to a Method of the Outer Class 743

Nesting Inner Classes 745

Inner Classes and Inheritance 745

Chapter 14 Generics and the ArrayList Class 759

14.1 THE ArrayList CLASS 761

Using the ArrayList Class 762

TIP: Summary of Adding to an ArrayList 766

Trang 28

Methods in the Class ArrayList 767 The “for-each” Loop 770

EXAMPLE: Golf Scores 773 TIP: Use trimToSize to Save Memory 776 PITFALL: The clone Method Makes a Shallow Copy ★ 776 The Vector Class 777

Parameterized Classes and Generics 778 PITFALL: Nonparameterized ArrayList and Vector Classes 778

14.2 GENERICS 778

Generic Basics 779 TIP: Compile with the -Xlint Option 781 EXAMPLE: A Generic Class for Ordered Pairs 781 PITFALL: A Generic Constructor Name Has No Type Parameter 784 PITFALL: You Cannot Plug in a Primitive Type for a Type Parameter 785 PITFALL: A Type Parameter Cannot Be Used Everywhere a Type Name

Can Be Used 785 PITFALL: An Instantiation of a Generic Class Cannot be an 

Array Base Type 786 TIP: A Class Defi nition Can Have More Than One Type Parameter 787 PITFALL: A Generic Class Cannot Be an Exception Class 788

Bounds for Type Parameters 789 TIP: Generic Interfaces 792 Generic Methods ★ 792 Inheritance with Generic Classes ★ 794 Chapter Summary 796

Answers to Self-Test Exercises 796 Programming Projects 799

Chapter 15 Linked Data Structures 801

15.1 JAVA LINKED LISTS 804

EXAMPLE: A Simple Linked List Class 804 Working with Linked Lists 808

PITFALL: Privacy Leaks 813 Node Inner Classes 814 EXAMPLE: A Generic Linked List 817 PITFALL: Using Node Instead of Node<T> 822 The equals Method for Linked Lists 822

15.2 COPY CONSTRUCTORS AND THE clone METHOD 824

Simple Copy Constructors and clone Methods ★ 824 Exceptions ★ 825

Trang 29

PITFALL: The clone Method Is Protected in object★ 827

TIP: Use a Type Parameter Bound for a Better clone★ 828

EXAMPLE: A Linked List with a Deep Copy clone Method ★ 832

TIP: Cloning Is an “All or Nothing” Affair 835

15.3 ITERATORS 835

Defi ning an Iterator Class 836

Adding and Deleting Nodes 841

15.4 VARIATIONS ON A LINKED LIST 846

Doubly Linked List 846

The Stack Data Structure 855

The Queue Data Structure 857

Running Times and Big- O Notation 860

Effi ciency of Linked Lists 865

15.5 HASH TABLES WITH CHAINING 866

A Hash Function for Strings 867

Effi ciency of Hash Tables 870

15.6 SETS 871

Fundamental Set Operations 872

Effi ciency of Sets Using Linked Lists 877

15.7 TREES 878

Tree Properties 878

EXAMPLE: A Binary Search Tree Class ★ 881

Effi ciency of Binary Search Trees ★ 886

The Collection Framework 900

PITFALL: Optional Operations 906

TIP: Dealing with All Those Exceptions 907

Concrete Collection Classes 908

Differences between ArrayList<T> and Vector<T> 918

Nonparameterized Version of the Collection Framework ★ 918

PITFALL: Omitting the 919

Trang 30

PITFALL: next Can Return a Reference 932 TIP: Defi ning Your Own Iterator Classes 934 Chapter Summary 935

Answers to Self-Test Exercises 935 Programming Projects 936

Chapter 17 Swing I 941

17.1 EVENT-DRIVEN PROGRAMMING 943

Events and Listeners 943

17.2 BUTTONS, EVENTS, AND OTHER SWING BASICS 944

EXAMPLE: A Simple Window 945 PITFALL: Forgetting to Program the Close-Window Button 950 Buttons 951

Action Listeners and Action Events 952 PITFALL: Changing the Heading for actionPerformed 954 TIP: Ending a Swing Program 954

EXAMPLE: A Better Version of Our First Swing GUI 955 Labels 958

Color 959 EXAMPLE: A GUI with a Label and Color 960

17.3 CONTAINERS AND LAYOUT MANAGERS 962

Border Layout Managers 963 Flow Layout Managers 966 Grid Layout Managers 967 Panels 971

EXAMPLE: A Tricolor Built with Panels 972 The Container Class 976

TIP: Code a GUI’s Look and Actions Separately 979 The Model-View-Controller Pattern ★ 980

Trang 31

17.4 MENUS AND BUTTONS 981

EXAMPLE: A GUI with a Menu 981

Menu Bars, Menus, and Menu Items 981

Nested Menus ★ 986

The AbstractButton Class 986

The setActionCommand Method 989

Listeners as Inner Classes ★ 990

17.5 TEXT FIELDS AND TEXT AREAS 993

Text Areas and Text Fields 994

TIP: Labeling a Text Field 1000

TIP: Inputting and Outputting Numbers 1000

EXAMPLE: A Window Listener Inner Class 1020

The dispose Method 1023

PITFALL: Forgetting to Invoke setDefaultCloseOperation 1024

The WindowAdapter Class 1024

18.2 ICONS AND SCROLL BARS 1026

Icons 1026

Scroll Bars 1032

EXAMPLE: Components with Changing Visibility 1037

18.3 THE Graphics CLASS 1041

Coordinate System for Graphics Objects 1041

The Method paint and the Class Graphics 1042

Drawing Ovals 1047

Drawing Arcs 1047

Rounded Rectangles ★ 1051

paintComponent for Panels 1052

Action Drawings and repaint 1052

Some More Details on Updating a GUI ★ 1058

Trang 32

18.5 FONTS AND THE drawString METHOD 1065

The drawString Method 1065 Fonts 1068

Chapter Summary 1071 Answers to Self-Test Exercises 1071 Programming Projects 1075

Chapter 19 Java Never Ends 1079

19.1 MULTITHREADING 1080

EXAMPLE: A Nonresponsive GUI 1081

Thread.sleep 1081 The getGraphics Method 1085 Fixing a Nonresponsive Program Using Threads 1086 EXAMPLE: A Multithreaded Program 1086

The Class Thread 1087 The Runnable Interface ★ 1090 Race Conditions and Thread Synchronization ★ 1093

19.2 NETWORKING WITH STREAM SOCKETS 1098

Sockets 1098 Sockets and Threading 1102

19.5 WEB PROGRAMMING WITH JAVA SERVER PAGES 1118

Applets, Servlets, and Java Server Pages 1118 Oracle GlassFish Enterprise Server 1120 HTML Forms—the Common Gateway Interface 1121 JSP Declarations, Expressions, Scriptlets, and Directives 1123

Trang 33

Appendix 2 Precedence and Associativity Rules 1141

Appendix 3 ASCII Character Set 1143

Appendix 4 Format Specifi cations for printf 1145

Appendix 5 Summary of Classes and Interfaces 1147

Trang 35

1.3 THE CLASS String 33

String Constants and Variables 33 Concatenation of Strings 34 Classes 35

String Methods 37 Escape Sequences 42 String Processing 43 The Unicode Character Set ★ 43

1.4 PROGRAM STYLE 46

Naming Constants 46 Java Spelling Conventions 48 Comments 49

Indenting 50

1.1 INTRODUCTION TO JAVA 2

Origins of the Java Language ★ 2

Objects and Methods 3

Applets ★ 4

A Sample Java Application Program 5

Byte-Code and the Java Virtual Machine 8

Class Loader ★ 10

Compiling a Java Program or Class 10

Running a Java Program 11

1.2 EXPRESSIONS AND ASSIGNMENT

Arithmetic Operators and Expressions 23

Parentheses and Precedence Rules ★ 24

Integer and Floating-Point Division 26

Trang 36

She starts—she moves—she seems to feel The thrill of life along her keel

HENRY WADSWORTH LONGFELLOW, The Building of the Ship

Introduction

This chapter introduces you to the Java language and gives you enough details to allow you to write simple programs involving expressions, assignments, and console output The details about assignments and expressions are similar to that of most other high-level languages Every language has its own way of handling strings and console output,

so even the experienced programmer should look at that material Even if you are already an experienced programmer in some language other than Java, you should read

at least the subsection entitled “A Sample Java Application Program” in Section 1.1 and preferably all of Section 1.2 You should also read all of Section 1.3 (on strings) and at least skim Section 1.4 to find out about Java defined constants and comments

Prerequisites

This book is self-contained and requires no preparation other than some simple high school algebra

1.1 Introduction to Java

Eliminating the middle man is not necessarily a good idea

Found in my old economics class notes

In this section, we give you an overview of the Java programming language

Origins of the Java Language

Java is well-known as a programming language for Internet applications However, this book , and many other books and programmers, consider Java a general-purpose programming language that is suitable for most any application, whether it involves the Internet or not The first version of Java was neither of these things, but it evolved into both

In 1991, James Gosling led a team at Sun Microsystems that developed the first

version of Java (which was not yet called Java ) This first version of the language was

Trang 37

designed for programming home appliances, such as washing machines and television sets Although that may not be a very glamorous application area, it is no easy task to design such a language Home appliances are controlled by a wide variety of computer processors (chips) The language that Gosling was designing needed to work on all these different processors Moreover, a home appliance is typically an inexpensive item, so the manufacturer would be unwilling to invest large amounts of money into

developing complicated compilers (A compiler translates a program into a language

the processor can understand.) To simplify the tasks of writing compilers (translation programs) for each class of appliances, the team used a two-step translation process

The programs are first translated into an intermediate language that is the same

for all appliances (or all computers), and then a small, easy-to-write—and hence, inexpensive—program translates this intermediate language into the machine language

for a particular appliance or computer This intermediate language is called Java

byte-code , or simply, byte-byte-code Since there is only one intermediate language, the hardest

step of the two-step translation from program to intermediate language to machine language is the same for all appliances (or all computers); hence, most of the cost of translating to multiple machine languages was saved The language for programming appliances never caught on with appliance manufacturers, but the Java language into which it evolved has become a widely used programming language Today, Java is owned by Oracle Corporation, which purchased Sun Microsystems in 2010

Why call it byte-code ? The word code is commonly used to mean a program or part

of a program A byte is a small unit of storage (eight bits to be precise)

Computer-readable information is typically organized into bytes So the term byte-code suggests a

program that is readable by a computer as opposed to a person

In 1994, Patrick Naughton and Jonathan Payne at Sun Microsystems developed

a Web browser that could run (Java) programs over the Internet, which has evolved into the browser known as HotJava This was the start of Java’s connection to the Internet In the fall of 1995, Netscape Incorporated made its Web browser capable of running Java programs Other companies followed suit and have developed software that accommodates Java programs

Objects and Methods

Java is an object-oriented programming (OOP) language What is OOP? The world

around us is made up of objects, such as people, automobiles, buildings, streets, adding machines, papers, and so forth Each of these objects has the ability to perform certain actions, and each of these actions has some effect on some of the other objects

in the world OOP is a programming methodology that views a program as similarly consisting of objects that interact with each other by means of actions

Object-oriented programming has its own specialized terminology The objects are

called, appropriately enough, objects The actions that an object can take are called

methods Objects of the same kind are said to have the same type or, more often, are

said to be in the same class For example, in an airport simulation program, all the

Trang 38

Why Is the Language Named “Java”?

The current custom is to name programming languages according to the whims of their designers Java is no exception There are conflicting explanations of the origin of the name

“Java.” Despite these differing stories, one thing is clear: The word “Java” does not refer

to any property or serious history of the Java language One believable story about where the name came from is that it was thought of when, after a fruitless meeting trying to come

up with a new name for the language, the development team went out for coffee Hence, the inspiration for the name “Java.”

simulated airplanes might belong to the same class, probably called the Airplane

class All objects within a class have the same methods Thus, in a simulation program, all airplanes have the same methods (or possible actions), such as taking off, flying

to a specific location, landing, and so forth However, all simulated airplanes are not identical They can have different characteristics, which are indicated in the program

by associating different data (that is, some different information) with each particular airplane object For example, the data associated with an airplane object might be two numbers for its speed and altitude

If you have used some other programming language, it might help to explain Java terminology in terms of the vocabulary used in other languages Things that are

called procedures , methods , functions , or subprograms in other languages are all called

methods in Java In Java, all methods (and for that matter, any programming constructs

whatsoever) are part of a class As we will see, a Java application program is a class

with a method named main ; when you run the Java program, the run-time system automatically invokes the method named main (that is, it automatically initiates the

main action) An application program is a “regular” Java program, and, as we are

about to see, there is another kind of Java program known as an applet Other Java

terminology is pretty much the same as the terminology in most other programming languages and, in any case, will be explained when each concept is introduced

Applets

There are two kinds of Java programs, applets and applications An application, or

application program, is just a regular program Although the name applet may sound like it has something to do with apples, it really means a little Java application , not

a little apple Applets and applications are almost identical The difference is that applications are meant to be run on your computer like any other program, whereas an

applet is meant to be run from a Web browser, and so can be sent to another location

on the Internet and run there Applets always use a windowing interface, but not all programs with a windowing interface are applets , as you will see in Chapters 16 – 18 Although applets were designed to be run from a Web browser, they can also be

run with a program known as an applet viewer The applet viewer is really meant

Trang 39

as a debugging aid and not as the final environment to allow users to run applets Nonetheless, applets are now often run as stand-alone programs using an applet viewer 1

We find this to be a somewhat unfortunate accident of history Java has multiple libraries of software for designing windowing interfaces that run without a connection

to a browser We prefer to use these libraries, rather than applets, to write windowing programs that will not be run from a Web browser In this book , we show you how

to do windowing interfaces as applets and as programs with no connection to a Web browser In fact, the two approaches have a large overlap of both techniques and the Java libraries that they use Once you know how to design and write either applets or applications, it is easy to learn to write the other of these two kinds of programs

An applet always has a windowing interface An application program may have a windowing interface or use simple console I/O So as not to detract from the code being studied, most of our example programs, particularly early in this book , use simple console I/O (that is, simple text I/O)

A Sample Java Application Program

Display 1.1 contains a simple Java program and the screen displays produced when it is run A Java program is really a class definition (whatever that is) with a method named

main When the program is run, the method named main is invoked; that is, the action specified bymain is carried out The body of the method main is enclosed in braces,

{} , so that when the program is run, the statements in the braces are executed (If you

are not even vaguely familiar with the words class and method, they will be explained

Read on.)

The following line says that this program is a class called FirstProgram :

public class FirstProgram

{

The next two lines, shown below, begin the definition of the main method:

public static void main(String[] args)

{

The details of exactly what a Java class is and what words such as public , static ,

void , and so forth mean will be explained in the next few chapters Until then, think

of these opening lines, repeated below, as being a rather wordy way of saying “Begin the program namedFirstProgram ”

public class FirstProgram

{

public static void main(String[] args)

{

1 An applet viewer does indeed use a browser to run an applet, but the look and feel is that of a

stand-alone program with no interaction with a browser

Trang 40

The next two lines, shown in what follows, are the first actions the program performs:

to be written to the screen The output produced by the next line that begins with

System.out.println will go on the following line Thus, these two lines cause the following output:

Hello reader

Welcome to Java

These lines that begin with System.out.println are a way of saying “output what

is shown in parentheses,” and the details of why the instruction is written this way need not concern us yet However, we can tell you a little about what is going on here

println

System.out.

println

Display 1.1 A Sample Java Program

1 public class FirstProgram

Ngày đăng: 16/02/2014, 00:20

TỪ KHÓA LIÊN QUAN

w