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

Tài liệu introduction to java progamming comprehesive 9th pdf

1,9K 2,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 đề Introduction to Java Programming Comprehensive Version Ninth Edition
Tác giả Y. Daniel Liang
Người hướng dẫn Marcia Horton, Editorial Director, Michael Hirsch, Editor in Chief, Tracy Dunkelberger, Executive Editor, Carole Snyder, Associate Editor, Patrice Jones, Director of Marketing, Yez Alayan, Marketing Manager, Kathryn Ferranti, Marketing Coordinator, Emma Snider, Marketing Assistant, Vince O’Brien, Director of Production, Jeff Holcomb, Managing Editor, Kayla Smith-Tarbox, Production Project Manager, Alan Fischer, Operations Supervisor, Lisa McDowell, Manufacturing Buyer, Anthony Gemmellaro, Art Director and Cover Designer, Karen Sanatar, Manager, Visual Research, Mike Joyce, Manager, Rights and Permissions, Danielle Simon, Text Permission Coordinator, Jenn Kennett, Text Permission Coordinator, Jason Consalvo, Cover Illustration, Daniel Sandin, Lead Media Project Manager, Gillian Hall, Project Management, Laserwords, Composition and Art, Edwards Brothers, Printer/Binder, Lehigh-Phoenix Color/Hagerstown, Cover Printer
Trường học Armstrong Atlantic State University
Chuyên ngành Computer Science
Thể loại Sách giáo trình
Năm xuất bản 2013
Thành phố Upper Saddle River
Định dạng
Số trang 1.947
Dung lượng 28,41 MB

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

Nội dung

We have: ■ Reorganized sections and chapters to present the subjects in a more logical order ■ Included many new interesting examples and exercises to stimulate interests ■ Updated to Ja

Trang 2

ALWAYS LEARNING

PEARSON Learn more at www.myprogramminglab.com

MyProgrammingLab™

Through the power of practice and immediate personalized

feedback, MyProgrammingLab improves your performance.

get with the programming

Trang 4

Armstrong Atlantic State University

Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Trang 5

Executive Editor: Tracy Dunkelberger

Associate Editor: Carole Snyder

Director of Marketing: Patrice Jones

Marketing Manager: Yez Alayan

Marketing Coordinator: Kathryn Ferranti

Marketing Assistant: Emma Snider

Director of Production: Vince O’Brien

Managing Editor: Jeff Holcomb

Production Project Manager: Kayla Smith-Tarbox

Operations Supervisor: Alan Fischer

Manufacturing Buyer: Lisa McDowell

Manager, Visual Research: Karen Sanatar Manager, Rights and Permissions: Mike Joyce Text Permission Coordinator: Danielle Simon and Jenn Kennett

Cover Illustration: Jason Consalvo Lead Media Project Manager: Daniel Sandin Project Management: Gillian Hall

Composition and Art: Laserwords Printer/Binder: Edwards Brothers Cover Printer: Lehigh-Phoenix Color/Hagerstown Text Font: Times 10/12

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

Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on the appropriate page within text and as follows: Table 3.2 and 10.1: Data from IRS Figures 8.1, 8.12, 12.3, 12.5, 12.7, 12.9, 12.10, 12.12–12.21, 12.26–12.30, 13.1, 13.4, 13.9, 13.11, 13.15, 13.17, 13.19, 13.21, 13.23, 13.25–13.35, 14.10, 14.14,15.9–15.11, 16.1, 16.2, 16.8, 16.11, 16.14, 16.17, 16.19–16.35, 17.1, 17.3, 17.6, 17.9, 17.12, 17.13, 17.15, 17.17–17.32, 18.6–18.8, 18.10, 18.15–18.35, 19.19, 19.20, 19.22, 20.1, 20.9, 20.12–20.14, 20.16–20.20, 22.8, 22.17–22.21, 24.4, 24.6, 24.8, 24.11–24.17, 25.18–25.20, 27.17, 27.23-–27.25, 30.10, 30.14, 30.22, 30.23, 30.25, 31.24–31.26, 32.6, 32.7, 32.31–32.34, 33.5, 33.9–33.11, 33.16–33.22, 34.23, 34.27–34.30: Screenshots © 2011 by Oracle Corporation Reprinted with permission.

Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A and other tries Screen shots and icons reprinted with permission from the Microsoft Corporation This book is not sponsored

coun-or endcoun-orsed by coun-or affiliated with the Microsoft Ccoun-orpcoun-oration.

Copyright © 2013, 2011, 2009, 2007, 2004 by Pearson Education, Inc., publishing as Prentice Hall All rights

reserved Manufactured in the United States of America This publication is protected by Copyright, and sion 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.,

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

Library of Congress Cataloging-in-Publication Data available upon request.

Trang 6

used this book in CS1, CS2, and CS3 at Lamar University and provided invaluable suggestions for improving the book Sadly, Myers passed away after he completed the review

of this edition.

To Samantha, Michael, and Michelle

Trang 8

Dear Reader,

Many of you have provided feedback on earlier editions of this book, and your comments and

suggestions have greatly improved the book This edition has been substantially enhanced in

presentation, organization, examples, exercises, and supplements We have:

■ Reorganized sections and chapters to present the subjects in a more logical order

■ Included many new interesting examples and exercises to stimulate interests

■ Updated to Java 7

■ Created animations for algorithms and data structures to visually demonstrate the

concepts

■ Redesigned the support Website to make it easier to navigate

This book teaches programming in a problem-driven way that focuses on problem solving

rather than syntax We make introductory programming interesting by using thought-provoking

problems in a broad context The central thread of early chapters is on problem solving

Appropriate syntax and library are introduced to enable readers to write programs for solving the

problems To support the teaching of programming in a problem-driven way, the book provides

a wide variety of problems at various levels of difficulty to motivate students To appeal to

stu-dents in all majors, the problems cover many application areas, including math, science, business,

financial, gaming, animation, and multimedia

The book focuses on fundamentals first by introducing basic programming concepts and

techniques before designing custom classes The fundamental concepts and techniques of loops,

methods, and arrays are the foundation for programming Building this strong foundation

prepares students to learn object-oriented programming and advanced Java programming

This comprehensive version covers fundamentals of programming, object-oriented

program-ming, GUI programprogram-ming, algorithms and data structures, concurrency, networking,

internation-alization, advanced GUI, database, and Web programming It is designed to prepare students to

become proficient Java programmers A brief version (Introduction to Java Programming, Brief

Version, Ninth Edition) is available for a first course on programming, commonly known as

CS1 The brief version contains the first 20 chapters of the comprehensive version

The best way to teach programming is by example, and the only way to learn programming

is by doing Basic concepts are explained by example, and a large number of exercises with

various levels of difficulty are provided for students to practice For our programming courses,

we assign programming exercises after each lecture

Our goal is to produce a text that teaches problem solving and programming in a broad

context using a wide variety of interesting examples If you have any comments on and

suggestions for improving the book, please email me

examples and exercises

Trang 9

What’s New in This Edition?

This edition substantially improves Introduction to Java Programming, Eighth Edition The

major improvements are as follows:

■ This edition is completely revised in every detail to enhance clarity, presentation, content,examples, and exercises

■ New examples and exercises are provided to motivate and stimulate student interest inprogramming

■ Each section starts with a Key Point that highlights the important concepts covered in thesection

■ Check Points provide review questions to help students track their progress and evaluatetheir learning after a major concept or example is covered

■ Each chapter provides test questions online They are grouped by sections for students to

do self-test The questions are graded online

■ New VideoNotes provide short video tutorials designed to reinforce code

■ The Java GUI API is an excellent example of how the object-oriented principle is applied.Students learn better with concrete and visual examples So basic GUI/Graphics is movedbefore introducing abstract classes and interfaces You can however still choose to coverabstract classes and interfaces before GUI or skip GUI

■ The numeric wrapper classes, BigInteger, and BigDecimal are now introduced in

Chapter 10 to enable students to write code using these classes early

■ Exception handling is covered before abstract classes and interfaces so that studentscan build robust programs early The instructor can still choose to cover exceptionhandling later Text I/O is now combined with exception handling to form a newchapter

■ Simple use of generics is introduced along with ArrayListin Chapter 11 and with

Comparable in Chapter 15 while the complex detail on generics is still kept inChapter 21

■ Chapter 22 is split into two chapters (Chapter 22 and Chapter 23) to make room for porating three new case studies to demonstrate effective use of data structures

incor-■ Chapter 24 is expanded to introduce algorithmic techniques: dynamic programming,divide-and-conquer, backtracking, and greedy algorithm with new examples to designefficient algorithms

■ Visual animations are created to show how data structures and algorithms work

■ A common problem with a data structures course is lack of good examples and exercises.This edition added many new interesting examples and exercises

■ Parallel programming techniques are introduced in Chapter 32, Multithreading andParallel Programming

■ Chapter 44 is completely new to introduce the latest standard on JSF

■ Chapter 50 is completely new to introduce testing using JUnit

Please visit www.cs.armstrong.edu/liang/intro9e/newfeatures.html for a complete list of newfeatures as well as correlations to the previous edition

new JUnit chapter

new JSF chapter

parallel programming

new data structures materials

data structures and algorithm

animation

developing efficient

algorithms

splitting Chapter 22

simple generics early

exception handling earlier

numeric classes covered early

basic GUI and graphics early

Trang 10

Pedagogical Features

The book uses the following elements to help students get the most from the material:

The Objectives at the beginning of each chapter list what students should learn from the

chapter This will help them determine whether they have met the objectives after

com-pleting the chapter

The Introduction opens the discussion with representative problems to give the reader an

overview of what to expect from the chapter

Key Points highlight the important concepts covered in each section.

Check Points provide review questions to help students track their progress as they read

through the chapter and evaluate their learning

Problems and Case Studies, carefully chosen and presented in an easy-to-follow style,

teach problem solving and programming concepts The book uses many small, simple,

and stimulating examples to demonstrate important ideas

The Chapter Summary reviews the important subjects that students should understand

and remember It helps them reinforce the key concepts they have learned in the chapter

Test Questions are accessible online, grouped by sections, for students to do self-test on

programming concepts and techniques

Programming Exercises are grouped by sections to provide students with opportunities to

apply the new skills they have learned on their own The level of difficulty is rated as easy (no

asterisk), moderate (*), hard (**), or challenging (***) The trick of learning programming

is practice, practice, and practice To that end, the book provides a great many exercises

Notes, Tips, Cautions, and Design Guides are inserted throughout the text to offer

valu-able advice and insight on important aspects of program development

Provides guidelines for designing programs.

Flexible Chapter Orderings

The book is designed to provide flexible chapter orderings to enable GUI, exception handling,

recursion, generics, and the Java Collections Framework to be covered earlier or later The

diagram on the next page shows the chapter dependencies

Organization of the Book

The chapters can be grouped into five parts that, taken together, form a comprehensive

intro-duction to Java programming, data structures and algorithms, and database and Web

pro-gramming Because knowledge is cumulative, the early chapters provide the conceptual basis

Trang 11

Chapter 45 Web Services Chapter 44 Java Server Faces

Chapter 46 Remote Method Invocation

Chapter 27 Binary Search Trees Chapter 28 Hashing

Chapter 29 AVL Trees

Chapter 31 Weighted Graphs and Applications

Chapter 30 Graphs and Applications

Chapter 23 Sets and Maps

Chapter 24 Developping Efficient Algorithms

Chapter 8 Objects and Classes

Chapter 19 Binary I/O

Note: Chapters 1–20 are in the

brief version of this book

Note: Chapters 1–34 are in the

comprehensive version

Note: Chapters 35–50 are bonus

chapters available from the Companion Website.

Chapter 9 Strings Chapter 10 Thinking in Objects

Chapter 11 Inheritance and Polymorphism Chapter 14 Exception Handling and Text I/O Chapter 15 Abstract Classes and Interfaces

Chapter 41 Advanced Database Programming

Chapter 43 Java Server Pages

Part V: Advanced Java Programming

Chapter 12 GUI Basics Chapter 13 Graphics Chapter 16 Event-Driven Programming

Chapter 22 Lists, Stacks, Queues, and Priority Queues

Chapter 17 GUI Components

Chapter 18 Applets and Multimedia

Chapter 36 JavaBeans and Bean Events

Chapter 37 Containers, Layout Managers, and Borders Chapter 38 Menus, Toolbars, and Dialogs

Chapter 39 MVC and Swing Models

Chapter 40 JTable and JTree Chapter 49 Java 2D

Chapter 50 Testing Using JUnit

Part III: GUI Programming

Part IV: Data Structures and Algorithms

Trang 12

for understanding programming and guide students through simple examples and exercises;

subsequent chapters progressively present Java programming in detail, culminating with the

development of comprehensive Java applications The appendixes contain a mixed bag of

top-ics, including an introduction to number systems and bitwise operations

Part I: Fundamentals of Programming (Chapters 1–7)

The first part of the book is a stepping stone, preparing you to embark on the journey of

learning Java You will begin to learn about Java (Chapter 1) and fundamental programming

techniques with primitive data types, variables, constants, assignments, expressions, and

operators (Chapter 2), control statements (Chapters 3–4), methods (Chapter 5), and arrays

(Chapters 6–7) After Chapter 6, you can jump to Chapter 20 to learn how to write recursive

methods for solving inherently recursive problems

Part II: Object-Oriented Programming (Chapters 8–11, 14–15, and 19)

This part introduces object-oriented programming Java is an object-oriented programming

language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great

flexibility, modularity, and reusability in developing software You will learn programming

with objects and classes (Chapters 8–10), class inheritance (Chapter 11), polymorphism

(Chapter 11), exception handling and text I/O (Chapter 14), abstract classes (Chapter 15), and

interfaces (Chapter 15) Processing strings is introduced in Chapter 9, and binary I/O is

dis-cussed in Chapter 19

Part III: GUI Programming (Chapters 12–13, 16–18, and Bonus Chapters 36–40 and 49)

This part introduces elementary Java GUI programming in Chapters 12–13 and 16–18 and

advanced Java GUI programming in Chapters 36–40 and 49 Major topics include GUI basics

(Chapter 12), drawing shapes (Chapter 13), event-driven programming (Chapter 16), using GUI

components (Chapter 17), and writing applets (Chapter 18) You will learn the architecture of

Java GUI programming and use the GUI components to develop applications and applets from

these elementary GUI chapters The advanced GUI chapters discuss Java GUI programming in

more depth and breadth You will delve into JavaBeans and learn how to develop custom events

and source components in Chapter 36, review and explore new containers, layout managers,

and borders in Chapter 37, learn how to create GUI with menus, popup menus, toolbars,

dialogs, and internal frames in Chapter 38, develop components using the MVC approach and

explore the advanced Swing components JSpinner,JList, and JComboBoxin Chapter 39,

andJTableandJTreein Chapter 40 Chapter 49 introduces Java 2D.

Part IV: Data Structures and Algorithms (Chapters 20–31 and Bonus Chapters 47–48)

This part covers the main subjects in a typical data structures course Chapter 20 introduces

recursion to write methods for solving inherently recursive problems Chapter 21 presents

how generics can improve software reliability Chapters 22 and 23 introduce the Java

Collection Framework, which defines a set of useful API for data structures Chapter 24

dis-cusses measuring algorithm efficiency in order to choose an appropriate algorithm for

appli-cations Chapter 25 describes classic sorting algorithms You will learn how to implement

several classic data structures lists, queues, and priority queues in Chapter 26 Chapters 27

and 29 introduce binary search trees and AVL trees Chapter 28 presents hashing and

imple-menting maps and sets using hashing Chapters 30 and 31 introduce graph applications The

2-4 trees, B-trees, and red-black trees are covered in Chapters 47–48

Part V: Advanced Java Programming (Chapters 32–33 and Bonus Chapters 35, 41–46,

and 50)

This part of the book is devoted to advanced Java programming Chapter 32 treats the use

of multithreading to make programs more responsive and interactive and introduces

par-allel programming Chapter 33 discusses how to write programs that talk with each other

Trang 13

over the Internet Chapter 34 introduces the use of Java to develop database projects, andChapter 35 covers the use of internationalization support to develop projects for interna-tional audiences Chapter 41 delves into advanced Java database programming BonusChapters 42, 43 and 44 introduce how to use Java servlets, JavaServer Pages, andJavaServer Faces to generate dynamic content from Web servers Chapter 45 discussesWeb services, and Chapter 46 introduces remote method invocation Chapter 50 introducestesting Java programs using JUnit.

Appendixes

This part of the book covers a mixed bag of topics Appendix A lists Java keywords.Appendix B gives tables of ASCII characters and their associated codes in decimal and inhex Appendix C shows the operator precedence Appendix D summarizes Java modifiers andtheir usage Appendix E discusses special floating-point values Appendix F introduces num-ber systems and conversions among binary, decimal, and hex numbers Finally, Appendix Gintroduces bitwise operations

Java Development Tools

You can use a text editor, such as the Windows Notepad or WordPad, to create Java programsand to compile and run the programs from the command window You can also use a Javadevelopment tool, such as TextPad, NetBeans, or Eclipse These tools support an integrateddevelopment environment (IDE) for developing Java programs quickly Editing, compiling,building, executing, and debugging programs are integrated in one graphical user interface.Using these tools effectively can greatly increase your programming productivity TextPad is

a primitive IDE tool NetBeans and Eclipse are more sophisticated, but they are easy to use ifyou follow the tutorials Tutorials on TextPad, NetBeans, and Eclipse can be found in the sup-plements on the Companion Website www.cs.armstrong.edu/liang/intro9e

Online Practice and Assessment with MyProgrammingLab

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

program-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, thesystem automatically detects errors in the logic and syntax of their code submissions andoffers targeted hints that enable students to figure out what went wrong—and why Forinstructors, a comprehensive gradebook tracks correct and incorrect answers and stores thecode inputted by students for review

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

VideoNotes

We are excited about the new VideoNotes feature that is found in this new edition These videosprovide additional help by presenting examples of key topics and showing how to solve problemscompletely, from design through coding VideoNotes are free to first time users and can beaccessed by redeeming the access code in the front of this book at www.pearsonhighered.com/liang

IDE tutorials

VideoNote

Trang 14

This book is accompanied by a complementary Web-based course assessment and

manage-ment system for instructors The system has four main components:

The Automatic Grading System can automatically grade programs.

The Quiz Creation/Submission/Grading System enables instructors to create and

modify quizzes that students can take and be graded upon automatically

The Peer Evaluation System enables peer evaluations.

Tracking grades, attendance, etc., lets students track their grades, and enables

instruc-tors to view the grades of all students and to track students’ attendance

The main features of the Automatic Grading System include:

■ Students can run and submit exercises (The system checks whether their program runs

correctly—students can continue to run and resubmit the program before the due date.)

■ Instructors can review submissions, run programs with instructor test cases, correct them,

provide feedback to students, and check plagiarism

■ Instructors can create/modify their own exercises, create public and secret test cases,

assign exercises, and set due dates for the whole class or for individuals

■ Instructors can assign all the exercises in the text to students Additionally, LiveLab

provides extra exercises that are not printed in the text

■ Instructors can sort and filter all exercises and check grades (by time frame, student,

and/or exercise)

■ Instructors can delete students from the system

■ Students and instructors can track grades on exercises

The main features of the Quiz System are:

■ Instructors can create/modify quizzes from the test bank or a text file or create completely

new tests online

■ Instructors can assign the quizzes to students and set a due date and test time limit for the

whole class or for individuals

■ Students and instructors can review submitted quizzes

■ Instructors can analyze quizzes and identify students’ weaknesses

■ Students and instructors can track grades on quizzes

The main features of the Peer Evaluation System include:

■ Instructors can assign peer evaluation for programming exercises

■ Instructors can view peer evaluation reports

Student Resource Website

The Student Resource Website (www.cs.armstrong.edu/liang/intro9e) contains the following

resources:

■ Access to VideoNotes (www.pearsonhighered.com/liang)

■ Answers to check point questions

Trang 15

■ Solutions to even-numbered programming exercises

■ Source code for the examples in the book

■ Interactive self-testing (organized by sections for each chapter)

■ Data structures and algorithm animations

■ Errata

Instructor Resource Website

The Instructor Resource Website, accessible from www.cs.armstrong.edu/liang/intro9e, containsthe following resources:

■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlightedsource code and to run programs without leaving the slides

■ Solutions to all programming exercises Students will have access to the solutions of numbered programming exercises

even-■ Web-based quiz generator (Instructors can choose chapters to generate quizzes from alarge database of more than two thousand questions.)

■ Sample exams Most exams have four parts:

■ Multiple-choice questions or short-answer questions

■ Correct programming errors

We have provided numerous animations for algorithms These are valuable pedagogical tools

to demonstrate how algorithms work Algorithm animations can be accessed from theCompanion Website

Acknowledgments

I would like to thank Armstrong Atlantic State University for enabling me to teach what Iwrite and for supporting me in writing what I teach Teaching is the source of inspiration forcontinuing to improve the book I am grateful to the instructors and students who have offeredcomments, suggestions, bug reports, and praise

This book has been greatly enhanced thanks to outstanding reviews for this and previous tions The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed (NorthGeorgia College and State University), Omar Aldawud (Illinois Institute of Technology), YangAng (University of Wollongong, Australia), Kevin Bierre (Rochester Institute of Technology),David Champion (DeVry Institute), James Chegwidden (Tarrant County College), Anup Dargar(University of North Dakota), Charles Dierbach (Towson University), Frank Ducrest(University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at Parkside), Deena

Trang 16

edi-Engel (New York University), Henry A Etlinger (Rochester Institute of Technology), James

Ten Eyck (Marist College), Myers Foreman (Lamar University), Olac Fuentes (University of

Texas at El Paso), Edward F Gehringer (North Carolina State University), Harold Grossman

(Clemson University), Barbara Guillot (Louisiana State University), Stuart Hansen (University

of Wisconsin, Parkside), Dan Harvey (Southern Oregon University), Ron Hofman (Red River

College, Canada), Stephen Hughes (Roanoke College), Vladan Jovanovic (Georgia Southern

University), Edwin Kay (Lehigh University), Larry King (University of Texas at Dallas), Nana

Kofi (Langara College, Canada), George Koutsogiannakis (Illinois Institute of Technology),

Roger Kraft (Purdue University at Calumet), Norman Krumpe (Miami University), Hong Lin

(DeVry Institute), Dan Lipsa (Armstrong Atlantic State University), James Madison

(Rensselaer Polytechnic Institute), Frank Malinowski (Darton College), Tim Margush

(University of Akron), Debbie Masada (Sun Microsystems), Blayne Mayfield (Oklahoma

State University), John McGrath (J.P McGrath Consulting), Hugh McGuire (Grand Valley

State), Shyamal Mitra (University of Texas at Austin), Michel Mitri (James Madison

University), Kenrick Mock (University of Alaska Anchorage), Frank Murgolo (California State

University, Long Beach), Jun Ni (University of Iowa), Benjamin Nystuen (University of

Colorado at Colorado Springs), Maureen Opkins (CA State University, Long Beach), Gavin

Osborne (University of Saskatchewan), Kevin Parker (Idaho State University), Dale Parson

(Kutztown University), Mark Pendergast (Florida Gulf Coast University), Richard Povinelli

(Marquette University), Roger Priebe (University of Texas at Austin), Mary Ann Pumphrey (De

Anza Junior College), Pat Roth (Southern Polytechnic State University), Amr Sabry (Indiana

University), Carolyn Schauble (Colorado State University), David Scuse (University of

Manitoba), Ashraf Shirani (San Jose State University), Daniel Spiegel (Kutztown University),

Joslyn A Smith (Florida Atlantic University) , Lixin Tao (Pace University), Ronald F Taylor

(Wright State University), Russ Tront (Simon Fraser University), Deborah Trytten (University

of Oklahoma), Kent Vidrine (George Washington University), and Bahram Zartoshty

(California State University at Northridge)

It is a great pleasure, honor, and privilege to work with Pearson I would like to thank

Tracy Dunkelberger and her colleagues Marcia Horton, Michael Hirsch, Matt Goldstein,

Carole Snyder, Tim Huddleston, Yez Alayan, Jeff Holcomb, Kayla Smith-Tarbox, Gillian

Hall, Rebecca Greenberg, and their colleagues for organizing, producing, and promoting this

project

As always, I am indebted to my wife, Samantha, for her love, support, and encouragement

Trang 17

14 Exception Handling and Text I/O 517

15 Abstract Classes and Interfaces 559

24 Developing Efficient Algorithms 853

26 Implementing Lists, Stacks, Queues,

30 Graphs and Applications 1047

31 Weighted Graphs and Applications 1093

32 Multithreading and Parallel

34 Java Database Programming 1211

Chapters 35–50 are bonus Web chapters

37 Containers, Layout Managers,

38 Menus, Toolbars, and Dialogs 38-1

41 Advanced Database Programming 41-1

46 Remote Method Invocation 46-1

B The ASCII Character Set 1254

C Operator Precedence Chart 1256

Trang 18

1.5 Java, the World Wide Web, and Beyond 13

1.6 The Java Language Specification, API, JDK, and IDE 16

1.7 A Simple Java Program 16

1.8 Creating, Compiling, and Executing a Java Program 19

1.9 Displaying Text in a Message Dialog Box 22

1.10 Programming Style and Documentation 24

2.2 Writing a Simple Program 34

2.3 Reading Input from the Console 37

2.11 Evaluating Expressions and Operator Precedence 50

2.12 Case Study: Displaying the Current Time 51

2.13 Augmented Assignment Operators 53

2.14 Increment and Decrement Operators 54

2.15 Numeric Type Conversions 56

2.16 Software Development Process 58

2.17 Character Data Type and Operations 62

2.19 Getting Input from Input Dialogs 70

xvii

Trang 19

3.3 ifStatements 843.4 Case Study: Guessing Birthdays 863.5 Two-Way if-elseStatements 893.6 Nested ifand Multi-Way if-elseStatements 913.7 Common Errors in Selection Statements 933.8 Generating Random Numbers 963.9 Case Study: Computing Body Mass Index 973.10 Case Study: Computing Taxes 99

5.5 Passing Parameters by Values 186

5.7 Case Study: Converting Decimals to Hexadecimals 191

5.9 The Scope of Variables 196

Trang 20

5.11 Case Study: Generating Random Characters 201

5.12 Method Abstraction and Stepwise Refinement 203

6.3 Case Study: Lotto Numbers 231

6.4 Case Study: Deck of Cards 234

6.6 Passing Arrays to Methods 237

6.7 Returning an Array from a Method 240

6.8 Case Study: Counting the Occurrences of Each Letter 241

6.9 Variable-Length Argument Lists 244

7.2 Two-Dimensional Array Basics 264

7.3 Processing Two-Dimensional Arrays 267

7.4 Passing Two-Dimensional Arrays to Methods 269

7.5 Case Study: Grading a Multiple-Choice Test 270

7.6 Case Study: Finding the Closest Pair 272

7.8 Multidimensional Arrays 277

8.2 Defining Classes for Objects 296

8.3 Example: Defining Classes and Creating Objects 298

8.4 Constructing Objects Using Constructors 303

8.5 Accessing Objects via Reference Variables 304

8.6 Using Classes from the Java Library 308

8.7 Static Variables, Constants, and Methods 312

8.8 Visibility Modifiers 317

8.9 Data Field Encapsulation 319

8.10 Passing Objects to Methods 322

Trang 21

9.3 Case Study: Checking Palindromes 3479.4 Case Study: Converting Hexadecimals to Decimals 348

10.8 Case Study: Designing the CourseClass 38410.9 Case Study: Designing a Class for Stacks 38610.10 Case Study: Designing the GuessDateClass 38810.11 Class Design Guidelines 39110.12 Processing Primitive Data Type Values as Objects 39310.13 Automatic Conversion between Primitive Types

and Wrapper Class Types 39610.14 The BigIntegerandBigDecimal 397

11.9 Casting Objects and the instanceofOperator 42511.10 The Object’s equalsmethod 42911.11 The ArrayListClass 43011.12 Case Study: A Custom Stack Class 43611.13 The protectedData and Methods 43711.14 Preventing Extending and Overriding 439

Trang 22

12.3 The Java GUI API 446

12.6 Using Panels as Subcontainers 458

12.9 Common Features of Swing GUI Components 462

13.3 Drawing Strings, Lines, Rectangles, and Ovals 483

13.4 Case Study: The FigurePanelClass 485

13.6 Drawing Polygons and Polylines 490

13.7 Centering a String Using the FontMetricsClass 493

13.8 Case Study: The MessagePanelClass 495

13.9 Case Study: The StillClockClass 500

13.11 Case Study: The ImageViewerClass 506

14.2 Exception-Handling Overview 518

14.4 More on Exception Handling 526

14.6 When to Use Exceptions 535

14.7 Rethrowing Exceptions 536

14.9 Defining Custom Exception Classes 538

14.11 File Input and Output 544

14.13 Reading Data from the Web 551

Trang 23

Chapter 15 Abstract Classes and Interfaces 559

15.7 The Cloneable Interface 57715.8 Interfaces vs Abstract Classes 58115.9 Case Study: The RationalClass 584

16.9 Listener Interface Adapters 620

16.11 Animation Using the TimerClass 625

17.8 Creating Multiple Windows 660

18.3 The HTML File and the <applet>Tag 67318.4 Applet Security Restrictions 675

Trang 24

18.5 Enabling Applets to Run as Applications 676

18.6 Applet Life-Cycle Methods 677

18.7 Passing Strings to Applets 679

18.8 Case Study: Bouncing Ball 683

18.9 Case Study: Developing a Tic-Tac-Toe Game 686

18.10 Locating Resources Using the URLClass 691

18.11 Playing Audio in Any Java Program 693

18.12 Case Study: National Flags and Anthems 695

19.2 How Is Text I/O Handled in Java? 710

19.3 Text I/O vs Binary I/O 711

19.5 Case Study: Copying Files 722

19.7 Random-Access Files 729

20.2 Case Study: Computing Factorials 738

20.3 Case Study: Computing Fibonacci Numbers 741

20.4 Problem Solving Using Recursion 744

20.5 Recursive Helper Methods 746

20.6 Case Study: Finding the Directory Size 749

20.7 Case Study: Towers of Hanoi 750

20.8 Case Study: Fractals 754

20.9 Recursion vs Iteration 757

21.2 Motivations and Benefits 770

21.3 Defining Generic Classes and Interfaces 772

21.5 Case Study: Sorting an Array of Objects 776

21.6 Raw Types and Backward Compatibility 778

21.7 Wildcard Generic Types 779

21.8 Erasure and Restrictions on Generics 782

21.9 Case Study: Generic Matrix Class 784

Trang 25

Chapter 22 Lists, Stacks, Queues, and

22.6 Static Methods for Lists and Collections 80522.7 Case Study: Bouncing Balls 809

22.9 Queues and Priority Queues 81422.10 Case Study: Evaluating Expressions 817

Trang 26

Chapter 26 Implementing Lists, Stacks, Queues,

27.2 Binary Search Trees 962

27.3 Deleting Elements from a BST 975

28.3 Hash Functions and Hash Codes 999

28.4 Handling Collisions Using Open Addressing 1001

28.5 Handling Collisions Using Separate Chaining 1005

28.6 Load Factor and Rehashing 1005

28.7 Implementing a Map Using Hashing 1007

28.8 Implementing Set Using Hashing 1016

29.3 Designing Classes for AVL Trees 1031

29.4 Overriding the insertMethod 1032

29.5 Implementing Rotations 1033

29.6 Implementing the deleteMethod 1034

29.8 Testing the AVLTreeClass 1040

29.9 AVL Tree Time Complexity Analysis 1043

30.2 Basic Graph Terminologies 1049

Trang 27

31.2 Representing Weighted Graphs 1095

31.4 Minimum Spanning Trees 110531.5 Finding Shortest Paths 111131.6 Case Study: The Weighted Nine Tails Problem 1119

32.3 Creating Tasks and Threads 1130

32.5 Case Study: Flashing Text 113732.6 GUI Event Dispatch Thread 113832.7 Case Study: Clock with Audio 1139

32.9 Thread Synchronization 114432.10 Synchronization Using Locks 114832.11 Cooperation among Threads 115032.12 Case Study: Producer/Consumer 1155

33.2 Client/Server Computing 1176

Trang 28

33.3 The InetAddressClass 1183

33.4 Serving Multiple Clients 1184

33.6 Sending and Receiving Objects 1190

33.7 Case Study: Distributed Tic-Tac-Toe Games 1195

Trang 29

Chapter 47 2-4 Trees and B-Trees 47-1

A PPENDIXES

Appendix C Operator Precedence Chart 1256

Appendix E Special Floating-Point Values 1260

Trang 30

Locations of VideoNotes

http://www.pearsonhighered.com/liang

Chapter 1 Introduction to Computers, Programs, and Java

Chapter 2 Elementary Programming

Chapter 3 Selections

Chapter 4 Loops

Chapter 5 Methods

Chapter 7 Multidimensional Arrays

Chapter 8 Objects and Classes

p

VideoNote

xxix

Trang 31

Chapter 10 Thinking in Objects

Immutable objects and this keyword 370

Chapter 11 Inheritance and Polymorphism

Polymorphism and dynamic binding demo 423

Chapter 12 GUI Basics

Chapter 13 Graphics

Chapter 14 Exception Handling and Text I/O

Chapter 15 Abstract Classes and Interfaces

Calendar and GregorianCalendar classes 567

Chapter 16 Event-Driven Programming

Chapter 17 GUI Components

Chapter 18 Applets and Multimedia

Trang 32

Audio and image 695

Chapter 19 Binary I/O

Trang 34

■ To write a simple Java program (§1.7).

■ To display output on the console (§1.7)

■ To explain the basic syntax of a Java program (§1.7)

■ To create, compile, and run Java programs (§1.8)

■ To display output using the JOptionPanemessage dialog boxes (§1.9)

■ To become familiar with Java programming style and

Trang 35

1.1 Introduction

The central theme of this book is to learn how to solve problems by writing a program.

This book is about programming So, what is programming? The term programming means to create (or develop) software, which is also called a program In basic terms, software contains

the instructions that tell a computer—or a computerized device—what to do

Software is all around you, even in devices that you might not think would need it Ofcourse, you expect to find and use software on a personal computer, but software also plays arole in running airplanes, cars, cell phones, and even toasters On a personal computer, youuse word processors to write documents, Web browsers to explore the Internet, and e-mailprograms to send messages These programs are all examples of software Software develop-

ers create software with the help of powerful tools called programming languages.

This book teaches you how to create programs by using the Java programming language.There are many programming languages, some of which are decades old Each language wasinvented for a specific purpose—to build on the strengths of a previous language, for exam-ple, or to give the programmer a new and unique set of tools Knowing that there are so manyprogramming languages available, it would be natural for you to wonder which one is best.But, in truth, there is no “best” language Each one has its own strengths and weaknesses.Experienced programmers know that one language might work well in some situations, whereas

a different language may be more appropriate in other situations For this reason, seasonedprogrammers try to master as many different programming languages as they can, givingthem access to a vast arsenal of software-development tools

If you learn to program using one language, you should find it easy to pick up other guages The key is to learn how to solve problems using a programming approach That is themain theme of this book

lan-You are about to begin an exciting journey: learning how to program At the outset, it ishelpful to review computer basics, programs, and operating systems If you are already famil-iar with such terms as CPU, memory, disks, operating systems, and programming languages,you may skip the review in Sections 1.2–1.4

1.2 What Is a Computer?

A computer is an electronic device that stores and processes data.

A computer includes both hardware and software In general, hardware comprises the visible,

physical elements of the computer, and software provides the invisible instructions that trol the hardware and make it perform specific tasks Knowing computer hardware isn’tessential to learning a programming language, but it can help you better understand the effectsthat a program’s instructions have on the computer and its components This section intro-duces computer hardware components and their functions

con-A computer consists of the following major hardware components (Figure 1.1):

■ A central processing unit (CPU)

■ Memory (main memory)

■ Storage devices (such as disks and CDs)

■ Input devices (such as the mouse and keyboard)

■ Output devices (such as monitors and printers)

■ Communication devices (such as modems and network interface cards)

A computer’s components are interconnected by a subsystem called a bus You can think

of a bus as a sort of system of roads running among the computer’s components; data and

Key Point

Trang 36

F IGURE 1.1 A computer consists of a CPU, memory, storage devices, input devices, output

devices, and communication devices

motherboard

power travel along the bus from one part of the computer to another In personal computers,

the bus is built into the computer’s motherboard, which is a circuit case that connects all of

the parts of a computer together, as shown in Figure 1.2

1.2.1 Central Processing Unit

The central processing unit (CPU) is the computer’s brain It retrieves instructions from

memory and executes them The CPU usually has two components: a control unit and an

arithmetic/logic unit The control unit controls and coordinates the actions of the other

com-ponents The arithmetic/logic unit performs numeric operations (addition, subtraction,

multi-plication, division) and logical operations (comparisons)

Today’s CPUs are built on small silicon semiconductor chips that contain millions of tiny

electric switches, called transistors, for processing information.

Every computer has an internal clock, which emits electronic pulses at a constant rate

These pulses are used to control and synchronize the pace of operations A higher clock speed

enables more instructions to be executed in a given period of time The unit of measurement of

clock speed is the hertz (Hz), with 1 hertz equaling 1 pulse per second In the 1990s computers

measured clocked speed in megahertz (MHz), but CPU speed has been improving continuously,

CPU

speed

hertz megahertz

Trang 37

and the clock speed of a computer is now usually stated in gigahertz (GHz) Intel’s newest

processors run at about 3 GHz

CPUs were originally developed with only one core The core is the part of the processor

that performs the reading and executing of instructions In order to increase CPU processingpower, chip manufacturers are now producing CPUs that contain multiple cores A multicoreCPU is a single component with two or more independent processors Today’s consumercomputers typically have two, three, and even four separate cores Soon, CPUs with dozens oreven hundreds of cores will be affordable

1.2.2 Bits and Bytes

Before we discuss memory, let’s look at how information (data and programs) are stored in

a computer

A computer is really nothing more than a series of switches Each switch exists in twostates: on or off Storing information in a computer is simply a matter of setting a sequence

of switches on or off If the switch is on, its value is 1 If the switch is off, its value is 0

These 0s and 1s are interpreted as digits in the binary number system and are called bits

(binary digits)

The minimum storage unit in a computer is a byte A byte is composed of eight bits A

small number such as 3can be stored as a single byte To store a number that cannot fit into asingle byte, the computer uses several bytes

Data of various kinds, such as numbers and characters, are encoded as a series of bytes As

a programmer, you don’t need to worry about the encoding and decoding of data, which the

computer system performs automatically, based on the encoding scheme An encoding

scheme is a set of rules that govern how a computer translates characters, numbers, and

sym-bols into data the computer can actually work with Most schemes translate each characterinto a predetermined string of numbers In the popular ASCII encoding scheme, for example,the character Cis represented as 01000011in one byte

Trang 38

01000011 01110010 01100101 01110111 00000011

Encoding for character ‘C’

Encoding for character ‘r’

Encoding for character ‘e’

Encoding for character ‘w’

Encoding for number 3

2000 2001 2002 2003 2004 Memory address Memory content

F IGURE 1.3 Memory stores data and program instructions in uniquely addressed memory

locations Each memory location can store one byte of data

A computer’s storage capacity is measured in bytes and multiples of the byte, as follows:

A kilobyte (KB) is about 1,000 bytes.

A megabyte (MB) is about 1 million bytes.

A gigabyte (GB) is about 1 billion bytes.

A terabyte (TB) is about 1 trillion bytes.

A typical one-page word document might take 20 KB Therefore, 1 MB can store 50 pages of

documents and 1 GB can store 50,000 pages of documents A typical two-hour high-resolution

movie might take 8 GB, so it would require 160 GB to store 20 movies

A computer’s memory consists of an ordered sequence of bytes for storing programs as well

as data that the program is working with You can think of memory as the computer’s work

area for executing a program A program and its data must be moved into the computer’s

memory before they can be executed by the CPU

Every byte in the memory has a unique address, as shown in Figure 1.3 The address is

used to locate the byte for storing and retrieving the data Since the bytes in the memory can

be accessed in any order, the memory is also referred to as random-access memory (RAM).

Today’s personal computers usually have at least 1 gigabyte of RAM, but they more

com-monly have 2 to 4 GB installed Generally speaking, the more RAM a computer has, the faster

it can operate, but there are limits to this simple rule of thumb

A memory byte is never empty, but its initial content may be meaningless to your program

The current content of a memory byte is lost whenever new information is placed in it

Like the CPU, memory is built on silicon semiconductor chips that have millions of

tran-sistors embedded on their surface Compared to CPU chips, memory chips are less

compli-cated, slower, and less expensive

1.2.4 Storage Devices

A computer’s memory (RAM) is a volatile form of data storage: any information that has been

stored in memory (that is, saved) is lost when the system’s power is turned off Programs and data

are permanently stored on storage devices and are moved, when the computer actually uses them,

to memory, which operates at much faster speeds than permanent storage devices can

kilobyte (KB) megabyte (MB) gigabyte (GB) terabyte (TB)

memory

unique address

RAM

storage devices

Trang 39

F IGURE 1.4 A hard disk is a device for permanently storing programs and data.

There are three main types of storage devices:

■ Magnetic disk drives

■ Optical disc drives (CD and DVD)

■ USB flash drives

Drives are devices for operating a medium, such as disks and CDs A storage medium

physically stores data and program instructions The drive reads data from the medium andwrites data onto the medium

Disks

A computer usually has at least one hard disk drive (Figure 1.4) Hard disks are used for

per-manently storing data and programs Newer computers have hard disks that can store from

200 to 800 gigabytes of data Hard disk drives are usually encased inside the computer, butremovable hard disks are also available

CDs and DVDs

CD stands for compact disc There are two types of CD drives: CD-R and CD-RW A CD-R is

for read-only permanent storage; the user cannot modify its contents once they are recorded

A CD-RW can be used like a hard disk; that is, you can write data onto the disc, and then

over-write that data with new data A single CD can hold up to 700 MB Most new PCs areequipped with a CD-RW drive that can work with both CD-R and CD-RW discs

DVD stands for digital versatile disc or digital video disc DVDs and CDs look alike, and

you can use either to store data A DVD can hold more information than a CD; a standardDVD’s storage capacity is 4.7 GB Like CDs, there are two types of DVDs: DVD-R (read-only) and DVD-RW (rewritable)

Trang 40

F IGURE 1.5 USB flash drives are very portable and can store a lot of data.

Function

Modifier

Numeric Keypad Page Up

Insert

Delete

Page Down

Arrows

F IGURE 1.6 A computer keyboard consists of the keys for sending input to a computer

USB Flash Drives

Universal serial bus (USB) connectors allow the user to attach many kinds of peripheral

devices to the computer You can use a USB to connect a printer, digital camera, mouse,

exter-nal hard disk drive, and other devices to the computer

A USB flash drive is a device for storing and transporting data A flash drive is small—

about the size of a pack of gum, as shown in Figure 1.5 It acts like a portable hard drive that

can be plugged into your computer’s USB port USB flash drives are currently available with

up to 256 GB storage capacity

1.2.5 Input and Output Devices

Input and output devices let the user communicate with the computer The most common input

devices are keyboards and mice The most common output devices are monitors and printers.

The Keyboard

A keyboard is a device for entering input Figure 1.6 shows a typical keyboard Compact

key-boards are available without a numeric keypad

Function keys are located across the top of the keyboard and are prefaced with the letter F.

Their functions depend on the software currently being used

function key

Ngày đăng: 27/02/2014, 05:20

TỪ KHÓA LIÊN QUAN