• No results found

Introduction to Java Programming, Comprehensive_CPCS 202.pdf

N/A
N/A
Protected

Academic year: 2020

Share "Introduction to Java Programming, Comprehensive_CPCS 202.pdf"

Copied!
295
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

ALWAYS LEARNING

P

EARSON

Learn more at

www.myprogramminglab.com

My

Programming

Lab™

Through the power of practice and immediate personalized

feedback, MyProgrammingLab improves your performance.

(3)
(4)

INTRODUCTION TO

JAVA

TM

PROGRAMMING

COMPREHENSIVE VERSION

Ninth Edition

Y. Daniel Liang

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

(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 coun-tries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.

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 permis-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., 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.

(6)

This book is dedicated to Professor Myers Foreman. Myers

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.

(7)
(8)

PREFACE

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.

Thiscomprehensive versioncovers 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 isby 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.

Sincerely,

Y. Daniel Liang

[email protected] www.cs.armstrong.edu/liang www.pearsonhighered.com/liang

vii

brief version

comprehensive version fundamentals-first problem-driven what is new?

(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 in programming.

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

■ Check Points provide review questions to help students track their progress and evaluate their 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 moved before introducing abstract classes and interfaces. You can however still choose to cover abstract 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 students can build robust programs early. The instructor can still choose to cover exception handling later. Text I/O is now combined with exception handling to form a new chapter.

■ 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 in Chapter 21.

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

■ Chapter 24 is expanded to introduce algorithmic techniques: dynamic programming, divide-and-conquer, backtracking, and greedy algorithm with new examples to design efficient 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 and Parallel 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 new features 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 test questions

check point key point new problems complete revision

(10)

Preface

ix

Pedagogical Features

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

■ TheObjectivesat 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.

■ TheIntroductionopens the discussion with representative problems to give the reader an overview of what to expect from the chapter.

Key Pointshighlight the important concepts covered in each section.

Check Pointsprovide 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.

■ TheChapter Summaryreviews the important subjects that students should understand and remember. It helps them reinforce the key concepts they have learned in the chapter.

Test Questionsare accessible online, grouped by sections, for students to do self-test on programming concepts and techniques.

Programming Exercisesare 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 Guidesare inserted throughout the text to offer valu-able advice and insight on important aspects of program development.

Note

Provides additional information on the subject and reinforces important concepts.

Tip

Teaches good programming style and practice.

Caution

Helps students steer away from the pitfalls of programming errors.

Design Guide

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

(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 1 Introduction to Computers, Programs, and Java

Chapter 2 Elementary Programming

Chapter 4 Loops

Chapter 5 Methods

Chapter 7 Multidimensional Arrays

Part I: Fundamentals of Programming

Chapter 3 Selections

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 6 Single-Dimensional Arrays

Part II: Object-Oriented Programming

Chapter 32 Multithreading and Parallel Programming

Chapter 42 Servlets Chapter 33 Networking

Chapter 34 Java Database Programming

Chapter 35 Internationalization

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

Chapter 20 Recursion

Ch 6

Chapter 21 Generics

Chapter 26 Implementing Lists, Stacks, Queues, and Priority Queues

Part IV: Data Structures and Algorithms

Ch 8

Ch 15

Ch 18

Chapter 47 2-4 Trees and B- Trees

Chapter 48 Red-Black Trees Chapter 25 Sorting

Pr

ef

(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

(13)

over the Internet. Chapter 34 introduces the use of Java to develop database projects, and Chapter 35 covers the use of internationalization support to develop projects for interna-tional audiences. Chapter 41 delves into advanced Java database programming. Bonus Chapters 42, 43 and 44 introduce how to use Java servlets, JavaServer Pages, and JavaServer Faces to generate dynamic content from Web servers. Chapter 45 discusses Web services, and Chapter 46 introduces remote method invocation. Chapter 50 introduces testing 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 in hex. Appendix C shows the operator precedence. Appendix D summarizes Java modifiers and their usage. Appendix E discusses special floating-point values. Appendix F introduces num-ber systems and conversions among binary, decimal, and hex numnum-bers. Finally, Appendix G introduces bitwise operations.

Java Development Tools

You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs and to compile and run the programs from the command window. You can also use a Java development tool, such as TextPad, NetBeans, or Eclipse. These tools support an integrated development 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 if you 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 program-ming. 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.

VideoNotes

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

IDE tutorials

(14)

LiveLab

This book is accompanied by a complementary Web-based course assessment and manage-ment system for instructors. The system has four main components:

■ TheAutomatic Grading Systemcan 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.

■ ThePeer Evaluation Systemenables 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

(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, contains the following resources:

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

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

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

■ Sample exams. Most exams have four parts:

■ Multiple-choice questions or short-answer questions

■ Correct programming errors

■ Trace programs

■ Write programs

■ Projects. In general, each project gives a description and asks students to analyze, design, and implement the project.

Some readers have requested the materials from the Instructor Resource Website. Please understand that these are for instructors only. Such requests will not be answered.

Algorithm Animations

We have provided numerous animations for algorithms. These are valuable pedagogical tools to demonstrate how algorithms work. Algorithm animations can be accessed from the Companion Website.

Acknowledgments

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

(16)

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.

(17)

BRIEF CONTENTS

1

Introduction to Computers, Programs,

and Java 1

2

Elementary Programming 33

3

Selections 81

4

Loops 133

5

Methods 177

6

Single-Dimensional Arrays 223

7

Multidimensional Arrays 263

8

Objects and Classes 295

9

Strings 335

10

Thinking in Objects 369

11

Inheritance and Polymorphism 407

12

GUI Basics 445

13

Graphics 479

14

Exception Handling and Text I/O 517

15

Abstract Classes and Interfaces 559

16

Event-Driven Programming 599

17

GUI Components 639

18

Applets and Multimedia 671

19

Binary I/O 709

20

Recursion 737

21

Generics 769

22

Lists, Stacks, Queues, and Priority

Queues 793

23

Sets and Maps 829

24

Developing Efficient Algorithms 853

25

Sorting 893

26

Implementing Lists, Stacks, Queues,

and Priority Queues 927

27

Binary Search Trees 961

28

Hashing 997

29

AVL Trees 1027

30

Graphs and Applications 1047

31

Weighted Graphs and Applications 1093

32

Multithreading and Parallel

Programming 1129

33

Networking 1175

34

Java Database Programming 1211

Chapters 35–50 are bonus Web chapters

35

Internationalization 35-1

36

JavaBeans 36-1

37

Containers, Layout Managers,

and Borders 37-1

38

Menus, Toolbars, and Dialogs 38-1

39

MVC and Swing Models 39-1

40

JTable and JTree 40-1

41

Advanced Database Programming 41-1

42

Servlets 42-1

43

JavaServer Pages 43-1

44

JavaServer Faces 44-1

45

Web Services 45-1

46

Remote Method Invocation 46-1

47

2-4 Trees and B-Trees 47-1

48

Red-Black Trees 48-1

49

Java 2D 49-1

50

Testing Using JUnit 50-1

A

PPENDIXES

A

Java Keywords 1251

B

The ASCII Character Set 1254

C

Operator Precedence Chart 1256

D

Java Modifiers 1258

E

Special Floating-Point Values 1260

F

Number Systems 1261

G

Bitwise Operatoirns 1265

I

NDEX 1267
(18)

CONTENTS

Chapter 1

Introduction to Computers, Programs,

and Java

1

1.1 Introduction 2

1.2 What Is a Computer? 2

1.3 Programming Languages 9

1.4 Operating Systems 12

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

1.11 Programming Errors 26

Chapter 2

Elementary Programming

33

2.1 Introduction 34

2.2 Writing a Simple Program 34

2.3 Reading Input from the Console 37

2.4 Identifiers 40

2.5 Variables 40

2.6 Assignment Statements and Assignment Expressions 42

2.7 Named Constants 43

2.8 Naming Conventions 44

2.9 Numeric Data Types and Operations 44

2.10 Numeric Literals 48

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.18 The StringType 68

2.19 Getting Input from Input Dialogs 70

Chapter 3

Selections

81

3.1 Introduction 82

3.2 booleanData Type 82

(19)

3.3 ifStatements 84

3.4 Case Study: Guessing Birthdays 86

3.5 Two-Way if-elseStatements 89

3.6 Nested ifand Multi-Way if-elseStatements 91

3.7 Common Errors in Selection Statements 93

3.8 Generating Random Numbers 96

3.9 Case Study: Computing Body Mass Index 97

3.10 Case Study: Computing Taxes 99

3.11 Logical Operators 101

3.12 Case Study: Determining Leap Year 105

3.13 Case Study: Lottery 106

3.14 switchStatements 108

3.15 Conditional Expressions 111

3.16 Formatting Console Output 112

3.17 Operator Precedence and Associativity 115

3.18 Confirmation Dialogs 117

3.19 Debugging 119

Chapter 4

Loops

133

4.1 Introduction 134

4.2 The whileLoop 134

4.3 The do-whileLoop 144

4.4 The forLoop 146

4.5 Which Loop to Use? 150

4.6 Nested Loops 152

4.7 Minimizing Numeric Errors 154

4.8 Case Studies 155

4.9 Keywords breakandcontinue 159

4.10 Case Study: Displaying Prime Numbers 162

4.11 Controlling a Loop with a Confirmation Dialog 164

Chapter 5

Methods

177

5.1 Introduction 178

5.2 Defining a Method 178

5.3 Calling a Method 180

5.4 voidMethod Example 183

5.5 Passing Parameters by Values 186

5.6 Modularizing Code 189

5.7 Case Study: Converting Decimals to Hexadecimals 191

5.8 Overloading Methods 193

5.9 The Scope of Variables 196

(20)

5.11 Case Study: Generating Random Characters 201

5.12 Method Abstraction and Stepwise Refinement 203

Chapter 6

Single-Dimensional Arrays

223

6.1 Introduction 224

6.2 Array Basics 224

6.3 Case Study: Lotto Numbers 231

6.4 Case Study: Deck of Cards 234

6.5 Copying Arrays 236

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

6.10 Searching Arrays 245

6.11 Sorting Arrays 248

6.12 The ArraysClass 252

Chapter 7

Multidimensional Arrays

263

7.1 Introduction 264

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.7 Case Study: Sudoku 274

7.8 Multidimensional Arrays 277

Chapter 8

Objects and Classes

295

8.1 Introduction 296

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

8.11 Array of Objects 326

Chapter 9

Strings

335

9.1 Introduction 336

9.2 The StringClass 336

(21)

9.3 Case Study: Checking Palindromes 347

9.4 Case Study: Converting Hexadecimals to Decimals 348

9.5 The CharacterClass 350

9.6 The StringBuilderandStringBuffer 353

9.7 Command-Line Arguments 358

Chapter 10

Thinking in Objects

369

10.1 Introduction 370

10.2 Immutable Objects and Classes 370

10.3 The Scope of Variables 371

10.4 The thisReference 373

10.5 Class Abstraction and Encapsulation 375

10.6 Object-Oriented Thinking 379

10.7 Object Composition 382

10.8 Case Study: Designing the CourseClass 384

10.9 Case Study: Designing a Class for Stacks 386

10.10 Case Study: Designing the GuessDateClass 388

10.11 Class Design Guidelines 391

10.12 Processing Primitive Data Type Values as Objects 393

10.13 Automatic Conversion between Primitive Types

and Wrapper Class Types 396

10.14 The BigIntegerandBigDecimal 397

Chapter 11

Inheritance and Polymorphism

407

11.1 Introduction 408

11.2 Superclasses and Subclasses 408

11.3 Using the superKeyword 414

11.4 Overriding Methods 418

11.5 Overriding vs. Overloading 418

11.6 The ObjectClass and Its toString() 420

11.7 Polymorphism 421

11.8 Dynamic Binding 422

11.9 Casting Objects and the instanceofOperator 425

11.10 The Object’s equalsmethod 429

11.11 The ArrayListClass 430

11.12 Case Study: A Custom Stack Class 436

11.13 The protectedData and Methods 437

11.14 Preventing Extending and Overriding 439

Chapter 12

GUI Basics

445

12.1 Introduction 446

(22)

12.3 The Java GUI API 446

12.4 Frames 449

12.5 Layout Managers 451

12.6 Using Panels as Subcontainers 458

12.7 The ColorClass 460

12.8 The FontClass 461

12.9 Common Features of Swing GUI Components 462

12.10 Image Icons 465

12.11 JButton 467

12.12 JCheckBox 471

12.13 JRadioButton 472

12.14 Labels 473

12.15 Text Fields 474

Chapter 13

Graphics

479

13.1 Introduction 480

13.2 The GraphicsClass 480

13.3 Drawing Strings, Lines, Rectangles, and Ovals 483

13.4 Case Study: The FigurePanelClass 485

13.5 Drawing Arcs 488

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.10 Displaying Images 504

13.11 Case Study: The ImageViewerClass 506

Chapter 14

Exception Handling and Text I/O

517

14.1 Introduction 518

14.2 Exception-Handling Overview 518

14.3 Exception Types 523

14.4 More on Exception Handling 526

14.5 The finallyClause 534

14.6 When to Use Exceptions 535

14.7 Rethrowing Exceptions 536

14.8 Chained Exceptions 537

14.9 Defining Custom Exception Classes 538

14.10 The FileClass 541

14.11 File Input and Output 544

14.12 File Dialogs 549

14.13 Reading Data from the Web 551

(23)

Chapter 15

Abstract Classes and Interfaces

559

15.1 Introduction 560

15.2 Abstract Classes 560

15.3 Case Study: the Abstract NumberClass 565

15.4 Case Study: CalendarandGregorianCalendar 567

15.5 Interfaces 570

15.6 The ComparableInterface 573

15.7 The Cloneable Interface 577

15.8 Interfaces vs. Abstract Classes 581

15.9 Case Study: The RationalClass 584

Chapter 16

Event-Driven Programming

599

16.1 Introduction 600

16.2 Events and Event Sources 602

16.3 Listeners, Registrations, and Handling Events 603

16.4 Inner Classes 608

16.5 Anonymous Class Listeners 609

16.6 Alternative Ways of Defining Listener Classes 612

16.7 Case Study: Loan Calculator 615

16.8 Mouse Events 617

16.9 Listener Interface Adapters 620

16.10 Key Events 621

16.11 Animation Using the TimerClass 625

Chapter 17

GUI Components

639

17.1 Introduction 640

17.2 Events for JCheckBox, JRadioButtonandJTextField 640

17.3 Text Areas 644

17.4 Combo Boxes 647

17.5 Lists 650

17.6 Scroll Bars 654

17.7 Sliders 657

17.8 Creating Multiple Windows 660

Chapter 18

Applets and Multimedia

671

18.1 Introduction 672

18.2 Developing Applets 672

18.3 The HTML File and the <applet>Tag 673

(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

Chapter 19

Binary I/O

709

19.1 Introduction 710

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

19.3 Text I/O vs. Binary I/O 711

19.4 Binary I/O Classes 712

19.5 Case Study: Copying Files 722

19.6 Object I/O 724

19.7 Random-Access Files 729

Chapter 20

Recursion

737

20.1 Introduction 738

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

20.10 Tail Recursion 758

Chapter 21

Generics

769

21.1 Introduction 770

21.2 Motivations and Benefits 770

21.3 Defining Generic Classes and Interfaces 772

21.4 Generic Methods 774

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

(25)

Chapter 22

Lists, Stacks, Queues, and

Priority Queues

793

22.1 Introduction 794

22.2 Collections 794

22.3 Iterators 798

22.4 Lists 799

22.5 The ComparatorInterface 803

22.6 Static Methods for Lists and Collections 805

22.7 Case Study: Bouncing Balls 809

22.8 The VectorandStackClasses 813

22.9 Queues and Priority Queues 814

22.10 Case Study: Evaluating Expressions 817

Chapter 23

Sets and Maps

829

23.1 Introduction 830

23.2 Sets 830

23.3 Comparing the Performance of Sets and Lists 838

23.4 Case Study: Counting Keywords 841

23.5 Maps 842

23.6 Case Study: Occurrences of Words 847

23.7 Singleton and Unmodifiable Collections and Maps 848

Chapter 24

Developing Efficient Algorithms

853

24.1 Introduction 854

24.2 Measuring Algorithm Efficiency Using Big ONotation 854

24.3 Examples: Determining Big O 856

24.4 Analyzing Algorithm Time Complexity 859

24.5 Finding Fibonacci Numbers Using Dynamic Programming 862

24.6 Finding Greatest Common Divisors Using Euclid’s Algorithm 864

24.7 Efficient Algorithms for Finding Prime Numbers 869

24.8 Finding the Closest Pair of Points Using Divide-and-Conquer 875

24.9 Solving the Eight Queens Problem Using Backtracking 877

24.10 Computational Geometry: Finding a Convex Hull 880

Chapter 25

Sorting

893

25.1 Introduction 894

25.2 Bubble Sort 894

25.3 Merge Sort 896

25.4 Quick Sort 900

25.5 Heap Sort 904

25.6 Bucket Sort and Radix Sort 911

(26)

Chapter 26

Implementing Lists, Stacks, Queues,

and Priority Queues

927

26.1 Introduction 928

26.2 Common Features for Lists 928

26.3 Array Lists 932

26.4 Linked Lists 938

26.5 Stacks and Queues 952

26.6 Priority Queues 955

Chapter 27

Binary Search Trees

961

27.1 Introduction 962

27.2 Binary Search Trees 962

27.3 Deleting Elements from a BST 975

27.4 Tree Visualization 981

27.5 Iterators 984

27.6 Case Study: Data Compression 986

Chapter 28

Hashing

997

28.1 Introduction 998

28.2 What Is Hashing? 998

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

Chapter 29

AVL Trees

1027

29.1 Introduction 1028

29.2 Rebalancing Trees 1028

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.7 The AVLTreeClass 1034

29.8 Testing the AVLTreeClass 1040

29.9 AVL Tree Time Complexity Analysis 1043

Chapter 30

Graphs and Applications

1047

30.1 Introduction 1048

30.2 Basic Graph Terminologies 1049

(27)

30.3 Representing Graphs 1051

30.4 Modeling Graphs 1056

30.5 Graph Visualization 1066

30.6 Graph Traversals 1069

30.7 Depth-First Search (DFS) 1070

30.8 Case Study: The Connected Circles Problem 1074

30.9 Breadth-First Search (BFS) 1077

30.10 Case Study: The Nine Tails Problem 1080

Chapter 31

Weighted Graphs and Applications

1093

31.1 Introduction 1094

31.2 Representing Weighted Graphs 1095

31.3 The WeightedGraphClass 1097

31.4 Minimum Spanning Trees 1105

31.5 Finding Shortest Paths 1111

31.6 Case Study: The Weighted Nine Tails Problem 1119

Chapter 32

Multithreading and Parallel

Programming

1129

32.1 Introduction 1130

32.2 Thread Concepts 1130

32.3 Creating Tasks and Threads 1130

32.4 The ThreadClass 1134

32.5 Case Study: Flashing Text 1137

32.6 GUI Event Dispatch Thread 1138

32.7 Case Study: Clock with Audio 1139

32.8 Thread Pools 1142

32.9 Thread Synchronization 1144

32.10 Synchronization Using Locks 1148

32.11 Cooperation among Threads 1150

32.12 Case Study: Producer/Consumer 1155

32.13 Blocking Queues 1158

32.14 Semaphores 1160

32.15 Avoiding Deadlocks 1162

32.16 Thread States 1163

32.17 Synchronized Collections 1163

32.18 Parallel Programming 1165

Chapter 33

Networking

1175

33.1 Introduction 1176

(28)

Contents

xxvii

33.3 The InetAddressClass 1183

33.4 Serving Multiple Clients 1184

33.5 Applet Clients 1187

33.6 Sending and Receiving Objects 1190

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

Chapter 34

Java Database Programming

1211

34.1 Introduction 1212

34.2 Relational Database Systems 1212

34.3 SQL 1216

34.4 JDBC 1227

34.5 PreparedStatement 1235

34.6 CallableStatement 1238

34.7 Retrieving Metadata 1241

Bonus Chapters 35–50 are available from the companion Website at

www.pearsonhighered.com/liang:

Chapter 35

Internationalization

35-1

Chapter 36

JavaBeans

36-1

Chapter 37

Containers, Layout Managers,

and Borders

37-1

Chapter 38

Menus, Toolbars, and Dialogs

38-1

Chapter 39

MVC and Swing Models

39-1

Chapter 40

JTable and JTree

40-1

Chapter 41

Advanced Database Programming

41-1

Chapter 42

Servlets

42-1

Chapter 43

JavaServer Pages

43-1

Chapter 44

JavaServer Faces

44-1

Chapter 45

Web Services

45-1
(29)

Chapter 47

2-4 Trees and B-Trees

47-1

Chapter 48

Red-Black Trees

48-1

Chapter 49

Java 2D

49-1

Chapter 50

Testing Using JUnit

50-1

A

PPENDIXES

Appendix A

Java Keywords 1251

Appendix B

The ASCII Character Set 1254

Appendix C

Operator Precedence Chart 1256

Appendix D

Java Modifiers 1258

Appendix E

Special Floating-Point Values 1260

Appendix F

Number Systems 1261

Appendix G

Bitwise Operations 1265
(30)

VideoNotes

Locations of VideoNotes

http://www.pearsonhighered.com/liang

Chapter 1 Introduction to Computers, Programs, and Java

Your first Java program 17

Eclipse brief tutorial 19

NetBeans brief tutorial 19 Compile and run a Java program 21

Chapter 2 Elementary Programming

Obtain input 37

Use operators / and % 51

Software development process 58

Compute loan payments 59

Compute BMI 77

Chapter 3 Selections

Program addition quiz 83

Program subtraction quiz 96 Use multi-way if-elsestatements 99

Sort three integers 123

Check point location 125

Chapter 4 Loops

Guess a number 137

Multiple subtraction quiz 139 Minimize numeric errors 154

Display loan schedule 170

Sum a series 170

Chapter 5 Methods

Define/invoke maxmethod 180

Usevoidmethod 183

Modularize code 189

Stepwise refinement 203

Reverse an integer 212

Estimate 215

Chapter 6 Single-Dimensional Arrays

Random shuffling 228

Lotto numbers 231

Selection sort 249

Coupon collector’s problem 260

Consecutive four 261

Chapter 7 Multidimensional Arrays

Find the row with the largest sum 268 Grade multiple-choice test 270

Sudoku 274

Multiply two matrices 282

Even number of 1s 289

Chapter 8 Objects and Classes

Define classes and objects 296

Use classes 311

Static vs. instance 312

Data field encapsulation 319

TheFanclass 331

p

VideoNote

(31)

Chapter 9 Strings

Check palindrome 347

Command-line argument 359

Number conversion 364

Check ISBN-10 367

Chapter 10 Thinking in Objects

Immutable objects and thiskeyword 370

TheLoanclass 376

The BMI class 380

TheStackOfIntegersclass 386

Process large numbers 397

TheMyPointclass 400

Chapter 11 Inheritance and Polymorphism

Geometric class hierarchy 408 Polymorphism and dynamic binding demo 423

TheArrayListclass 430

TheMyStackclass 436

New Accountclass 443

Chapter 12 GUI Basics

UseFlowLayout 452

Use panels as subcontainers 458 Use Swing common properties 462 Display a checkerboard 477 Display a random matrix 478

Chapter 13 Graphics

TheFigurePanelclass 485

TheMessagePanelclass 495

TheStillClockclass 500

Plot a function 511

Plot a bar chart 512

Chapter 14 Exception Handling and Text I/O

Exception-handling advantages 518 Create custom exception classes 538

Write and read data 544

HexFormatException 555

Chapter 15 Abstract Classes and Interfaces

Abstract GeometricObjectclass 560

CalendarandGregorianCalendarclasses 567 The concept of interface 570 Redesign the Rectangleclass 593

Chapter 16 Event-Driven Programming

Listener and its registration 607

Anonymous listener 610

Move message using the mouse 618

Animate a clock 628

Animate a rising flag 632

Check mouse point location 632

Chapter 17 GUI Components

Use text areas 668

Chapter 18 Applets and Multimedia

First applet 672

Run applets standalone 676

(32)

VideoNotes

xxxi

Audio and image 695

Control a group of clocks 701

Chapter 19 Binary I/O

Copy file 722

Object I/O 724

Split a large file 734

Chapter 20 Recursion

Binary search 748

Directory size 749

(33)
(34)

I

NTRODUCTION

TO

C

OMPUTERS

,

P

ROGRAMS

,

AND

J

AVA

Objectives

■ To understand computer basics, programs, and operating systems (§§1.2–1.4).

■ To describe the relationship between Java and the World Wide Web (§1.5).

■ To understand the meaning of Java language specification, API, JDK, and IDE (§1.6).

■ 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 documenta-tion (§1.10).

■ To explain the differences between syntax errors, runtime errors, and logic errors (§1.11).

CHAPTER

(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 programmingmeans 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. Of course, you expect to find and use software on a personal computer, but software also plays a role in running airplanes, cars, cell phones, and even toasters. On a personal computer, you use word processors to write documents, Web browsers to explore the Internet, and e-mail programs 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 was invented 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 many programming 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, seasoned programmers try to master as many different programming languages as they can, giving them 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 lan-guages. The key is to learn how to solve problems using a programming approach. That is the main theme of this book.

You are about to begin an exciting journey: learning how to program. At the outset, it is helpful 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 hardwareandsoftware.In general, hardware comprises the visible, physical elements of the computer, and software provides the invisible instructions that con-trol the hardware and make it perform specific tasks. Knowing computer hardware isn’t essential to learning a programming language, but it can help you better understand the effects that a program’s instructions have on the computer and its components. This section intro-duces computer hardware components and their functions.

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

what is programming? programming program

hardware software

bus

Key Point

(36)

1.2 What Is a Computer?

3

CPU

Bus

Memory

Storage Devices

Input Devices

Output Devices

Communication Devices

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

(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 coreis the part of the processor that performs the reading and executing of instructions. In order to increase CPU processing power, chip manufacturers are now producing CPUs that contain multiple cores. A multicore CPU is a single component with two or more independent processors. Today’s consumer computers typically have two, three, and even four separate cores. Soon, CPUs with dozens or even 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 two states: 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 a single 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 schemeis 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 character into a predetermined string of numbers. In the popular ASCII encoding scheme, for example, the character Cis represented as 01000011in one byte.

bits

byte

encoding scheme

CPU is placed under the fan

Memory

Motherboard

FIGURE1.2 The motherboard connects all parts of a computer together.

gigahertz

(38)

1.2 What Is a Computer?

5

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

FIGURE1.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:

■ Akilobyte (KB)is about 1,000 bytes.

■ Amegabyte (MB)is about 1 million bytes.

■ Agigabyte (GB)is about 1 billion bytes.

■ Aterabyte (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.

1.2.3

Memory

A computer’s memoryconsists 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 devicesand 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

(39)

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

Drivesare 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 and writes data onto the medium.

Disks

A computer usually has at least one hard disk drive (Figure 1.4). Hard disksare 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, but removable hard disks are also available.

CDs and DVDs

CDstands for compact disc. There are two types of CD drives: CD-R and CD-RW. A CD-Ris for read-only permanent storage; the user cannot modify its contents once they are recorded. ACD-RWcan 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 are equipped with a CD-RW drive that can work with both CD-R and CD-RW discs.

DVDstands 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 standard DVD’s storage capacity is 4.7 GB. Like CDs, there are two types of DVDs: DVD-R (read-only) and DVD-RW (rewritable).

drive

hard disk

CD-R

CD-RW

(40)

1.2 What Is a Computer?

7

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

FIGURE1.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 driveis 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 keyboardsandmice.The most common output devices are monitorsandprinters.

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 keysare located across the top of the keyboard and are prefaced with the letter F.

Their functions depend on the software currently being used.

(41)

Amodifier keyis a special key (such as the Shift,Alt, and Ctrlkeys) that modifies the nor-mal action of another key when the two are pressed simultaneously.

Thenumeric keypad, located on the right side of most keyboards, is a separate set of keys styled like a calculator to use for entering numbers quickly.

Arrow keys,located between the main keypad and the numeric keypad, are used to move the mouse pointer up, down, left, and right on the screen in many kinds of programs.

TheInsert,Delete,Page Up, and Page Down keysare used in word processing and other programs for inserting text and objects, deleting text and objects, and moving up or down through a document one screen at a time.

The Mouse

Amouseis a pointing device. It is used to move a graphical pointer (usually in the shape of an arrow) called a cursoraround the screen or to click on-screen objects (such as a button) to trigger them to perform an action.

The Monitor

The monitor displays information (text and graphics). The screen resolution and dot pitch determine the quality of the display.

Thescreen resolutionspecifies the number of pixels in horizontal and vertical dimensions of the display device. Pixels(short for “picture elements”) are tiny dots that form an image on the screen. A common resolution for a 17-inch screen, for example, is 1,024 pixels wide and 768 pixels high. The resolution can be set manually. The higher the resolution, the sharper and clearer the image is.

Thedot pitchis the amount of space between pixels, measured in millimeters. The smaller the dot pitch, the sharper the display.

1.2.6

Communication Devices

Computers can be networked through communication devices, such as a dial-up modem

(modulator/demodulator), a DSL or cable modem, a wired network interface card, or a wire-less adapter.

■ A dial-up modem uses a phone line and can transfer data at a speed up to 56,000 bps (bits per second).

■ Adigital subscriber line (DSL)connection also uses a standard phone line, but it can transfer data 20 times faster than a standard dial-up modem.

■ Acable modemuses the cable TV line maintained by the cable company and is gen-erally faster than DSL.

■ Anetwork interface card (NIC)is a device that connects a computer to a local area network (LAN), as shown in Figure 1.7. LANs are commonly used in universities, businesses, and government agencies. A high-speed NIC called 1000BaseT can transfer data at 1,000 million bits per second (mbps).

■ Wireless networking is now extremely popular in homes, businesses, and schools. Every laptop computer sold today is equipped with a wireless adapter that enables the computer to connect to a local area network and the Internet.

Note

Answers to checkpoint questions are on the Companion Website.

1.1

What are hardware and software?

1.2

List five major hardware components of a computer.

1.3

What does the acronym “CPU” stand for?

modifier key

numeric keypad

arrow keys

Insert key Delete key Page Up key Page Down key

screen resolution pixels

dot pitch

modem

digital subscriber line (DSL)

cable modem

network interface card (NIC) local area network (LAN)

million bits per second (mbps)

(42)

1.3 Programming Languages

9

Network Interface Card

LAN

FIGURE1.7 A local area network connects computers in close proximity to each other.

1.4

What unit is used to measure CPU speed?

1.5

What is a bit? What is a byte?

1.6

What is memory for? What does RAM stand for? Why is memory called RAM?

1.7

What unit is used to measure memory size?

1.8

What unit is used to measure disk size?

1.9

What is the primary difference between memory and a storage device?

1.3 Programming Languages

Computerprograms, known as software, are instructions that tell a computer what to do.

Computers do not understand human languages, so programs must be written in a language a computer can use. There are hundreds of programming languages, and they were developed to make the programming process easier for people. However, all programs must be converted into a language the computer can understand.

1.3.1

Machine Language

Figure

Figure 1.17 shows the  javac command for compiling Welcome.java. The compiler gen- gen-erates the Welcome.class file, and this file is executed using the java command.

References

Related documents

All stationary perfect equilibria of the intertemporal game approach (as slight stochastic perturbations as in Nash (1953) tend to zero) the same division of surplus as the static

Figure 2.3 shows an n sub-module, grid-connected PV string. When one sub- module is significantly shaded, its MPP current will differ from the MPP cur- rent of the other,

When the needle is lowered into the record groove and the tonearm is not resting on the lift arm, the tube of the tonearm should be parallel to the surface of the record.. If it is

Police officers in Tarrant County and across the state of Texas can make temporary detentions of you and your vehicle for several reasons: (1) A Voluntary

And while low-income households with singles or lone-parents experienced the highest incidence of affordability problems, the highest proportions of households in the

As we shall see, there are three 3-tiling configurations: two imprimitive variations of the 2-tiling (see Figure 2.3.3 and Figure 2.3.4), and a primitive configuration that we will

The college has developed web-based systems to assist faculty: initial verification /attendance, enrollment changes during the term for unofficial withdrawals, and end of term

However, there will be times when you need to interact more with the data. You might need to filter based