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

Java Programming From Problem Analysis To Program Design 4th Edition

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

Apago PDF Enhancer

www.traintelco.com


JAVA PROGRAMMING
FROM PROBLEM ANALYSIS

TO

PROGRAM DESIGN

FOURTH EDITION

D.S. MALIK

Apago PDF Enhancer

Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States

www.traintelco.com


Java Programming: From Problem Analysis
to Program Design, Fourth Edition
D.S. Malik
Executive Editor: Marie Lee
Acquisitions Editor: Amy Jollymore

For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, 1-800-354-9706


For permission to use material from this text or product, submit
all requests online at cengage.com/permissions
Further permissions questions can be emailed to


Senior Product Manager: Alyssa Pratt
Editorial Assistant: Julia Leroux-Lindsey
Marketing Manager: Bryant Chrzan
Senior Content Project Manager: Catherine
DiMassa

ISBN-13: 978-1-4390-3566-5
ISBN-10: 1-4390-3566-0

Compositor: Integra

Course Technology
20 Channel Center
Boston, MA 02210
USA

ª 2010 Course Technology, Cengage
Learning

Cengage Learning is a leading provider of customized
learning solutions with office locations around the globe,
including Singapore, the United Kingdom, Australia, Mexico,
Brazil, and Japan. Locate your local office at:
international.cengage.com/region


Art Director: Marissa Falco

ALL RIGHTS RESERVED. No part of this work
covered by the copyright herein may be
reproduced, transmitted, stored or used in any
form or by any means graphic, electronic, or
mechanical, including but not limited to
photocopying, recording, scanning, digitizing,
taping, Web distribution, information
networks, or information storage and retrieval
systems, except as permitted under Section
107 or 108 of the 1976 United States Copyright
Act, without the prior written permission of
the publisher.

Cengage Learning products are represented in Canada
by Nelson Education, Ltd.
For your lifelong learning solutions, visit
course.cengage.com
Visit our corporate website at cengage.com

Apago Some
PDF
Enhancer
of the product names and company names used in this
book have been used for identification purposes only and may
be trademarks or registered trademarks of their respective
manufacturers and sellers.
Any fictional data related to persons or companies or URLs used
throughout this book is intended for instructional purposes only.

At the time this book was printed, any such data was fictional
and not belonging to any real persons or companies.
Course Technology, a part of Cengage Learning, reserves the
right to revise this publication and make changes from time to
time in its content without notice.
The programs in this book are for instructional purposes only.
They have been tested with care, but are not guaranteed for any
particular intent beyond educational purposes. The author and
the publisher do not offer any warranties or representations, nor
do they accept any liabilities with respect to the programs.

Printed in Canada
1 2 3 4 5 6 7 12 11 10 09

www.traintelco.com


TO
Daughter
Apago My
PDF
Enhancer

Shelly Malik

www.traintelco.com


This page intentionally left blank


Apago PDF Enhancer

www.traintelco.com


BRIEF CONTENTS

PREFACE

xix

1. An Overview of Computers and Programming Languages
2. Basic Elements of Java

1
25

3. Introduction to Objects and Input/Output

107

4. Control Structures I: Selection

165

5. Control Structures II: Repetition

225

6. Graphical User Interface (GUI) and Object-Oriented Design (OOD)


295

7. User-Defined Methods

351

Apago PDF Enhancer

8. User-Defined Classes and ADTs

425

9. Arrays

509

10. Inheritance and Polymorphism

591

11. Handling Exceptions and Events

673

12. Advanced GUIs and Graphics

733

13. Recursion


823

14. Searching and Sorting

855

APPENDIX A

Java Reserved Words

891

APPENDIX B

Operator Precedence

893

APPENDIX C

Character Sets

897

APPENDIX D

Additional Java Topics

901


APPENDIX E

Answers to Odd-Numbered Exercises

949

INDEX

973

www.traintelco.com


TABLE

CONTENTS

OF

Preface

1

xix

AN OVERVIEW OF COMPUTERS AND PROGRAMMING
LANGUAGES
1
Introduction


2

An Overview of the History of Computers

2

Elements of a Computer System
Hardware
Software

3
4
6

Language of a Computer

6

Evolution of Programming Languages

8

Apago
Enhancer
Processing PDF
a Java Program
Internet, World Wide Web, Browser, and Java

10

13

Programming with the Problem Analysis–Coding–

2

Execution Cycle

13

Programming Methodologies
Structured Programming
Object-Oriented Programming

19
19
19

Quick Review

21

Exercises

23

BASIC ELEMENTS OF JAVA

25


A Java Program

26

Basics of a Java Program

28

Comments

29

Special Symbols
Reserved Words (Keywords)

30
30

Identifiers

31

www.traintelco.com


Table of Contents

Data Types
Primitive Data Types


|

vii

32
32

Arithmetic Operators and Operator Precedence
Order of Precedence

36
39

Expressions

40

Mixed Expressions

41

Type Conversion (Casting)

43

class String

45

Strings and the Operator +

Input
Allocating Memory with Named Constants and Variables

46
48
48

Putting Data into Variables
Declaring and Initializing Variables

51
55

Input (Read) Statement

56

Reading a Single Character

61

Increment and Decrement Operators
Apago
PDF Enhancer

63

Output

66


Packages, Classes, Methods, and the import Statement

71

Creating a Java Application Program

72

Programming Style and Form
Syntax

77
77

Avoiding Bugs: Consistent, Proper Formatting

81

Debugging—Code Walk-throughs

81

More on Assignment Statements (Optional)

82

Programming Example: Convert Length

84


Programming Example: Make Change

88

Debugging: Understanding Error Messages

91

Quick Review

91

Exercises

94

Programming Exercises

www.traintelco.com

102


viii |

Java Programming: From Problem Analysis to Program Design, Fourth Edition

3


INTRODUCTION TO OBJECTS AND INPUT/OUTPUT

107

Objects and Reference Variables

108

Using Predefined Classes and Methods in a Program

112

Dot Between Class (Object) Name and Class Member:
A Precaution

114

class String

115

Input/Output

123

Formatting Output with printf

123

Using Dialog Boxes for Input/Output

Formatting the Output Using the String Method format

132
139

File Input/Output
Storing (Writing) Output to a File

145

Programming Example: Movie Ticket Sale and
Donation to Charity

147

Programming Example: Student Grade

153

Apago
PDF Enhancer
Debugging—Understanding Error Messages

4

142

156

Quick Review


156

Exercises

158

Programming Exercises

161

CONTROL STRUCTURES I: SELECTION

165

Control Structures

166

Relational Operators

168

Relational Operators and Primitive Data Types

169

Logical (Boolean) Operators and Logical Expressions

172


Order of Precedence

174

Short-Circuit Evaluation
boolean Data Type and Logical (Boolean) Expressions

www.traintelco.com

178
179


Table of Contents

Selection: if and if...else

|

180

One-Way Selection
Two-Way Selection

180
183

Compound (Block of) Statements
Multiple Selections: Nested if


187
188

Comparing if...else Statements with a Series
of if Statements
Conditional Operator (? :) (Optional)
switch Structures

191
192
193

Avoiding Bugs by Avoiding Partially Understood
Concepts and Techniques

199

Programming Example: Cable Company Billing

201

Comparing Strings
Strings, the Assignment Operator, and the Operator new
Quick Review
Exercises
Apago
PDF Enhancer

5


207
211
213
215

Programming Exercises

221

CONTROL STRUCTURES II: REPETITION

225

Why Is Repetition Needed?

226

while Looping (Repetition) Structure

227

Designing while Loops

230

Counter-Controlled while Loops
Sentinel-Controlled while Loops

231

233

Flag-Controlled While Loops
EOF-Controlled while Loops

239
243

More on Expressions in while Statements

247

Programming Example: Fibonacci Number

248

for Looping (Repetition) Structure

254

Programming Example: Classify Numbers

259

do...while Looping (Repetition) Structure
Choosing the Right Looping Structure

263
268


www.traintelco.com

ix


x

| Java Programming: From Problem Analysis to Program Design, Fourth Edition

6

break and continue Statements

268

Avoiding Bugs by Avoiding Patches

270

Nested Control Structures

272

Quick Review

277

Exercises

279


Programming Exercises

289

GRAPHICAL USER INTERFACE (GUI) AND OBJECTORIENTED DESIGN (OOD)
295
Graphical User Interface (GUI) Components
Creating a Window
JFrame

300

Getting Access to the Content Pane
JLabel

306
307

JTextField
JButton

311
315

Apago PDF Enhancer
Programming Example: Temperature Conversion

323


Object-Oriented Design
A Simplified OOD Methodology

331
332

Implementing Classes and Operations

338

Primitive Data Types and the Wrapper Classes

7

296
300

338

Quick Review

345

Exercises

346

Programming Exercises

349


USER-DEFINED METHODS

351

Predefined Methods

352

Using Predefined Methods in a Program
User-Defined Methods
Value-Returning Methods

356
359
359

return Statement

363

Final Program

366

www.traintelco.com


Table of Contents


Flow of Execution

372

Programming Example: Largest Number

373

Void Methods

375

Primitive Data Type Variables as Parameters

379

Reference Variables as Parameters

382

Parameters and Memory Allocation
Reference Variables of the String Type as Parameters:
A Precaution
The class StringBuffer

8

|

382

382
386

Primitive Type Wrapper Classes as Parameters

389

Scope of an Identifier Within a Class

390

Method Overloading: An Introduction

393

Programming Example: Data Comparison

395

Avoiding Bugs: One-Piece-at-a-Time Coding

406

Apago
PDF
Enhancer
Avoiding Bugs:
Using
‘‘Stubs’’ as Appropriate


407

Quick Review

407

Exercises

410

Programming Exercises

418

USER-DEFINED CLASSES AND ADTs

425

Classes and Objects

426

Constructors
Unified Modeling Language Class Diagrams

431
432

Variable Declaration and Object Instantiation
Accessing Class Members


433
435

Built-in Operations on Classes

436

Assignment Operator and Classes: A Precaution
Class Scope

436
438

Methods and Classes
Definitions of the Constructors and Methods

439

of the class Clock

www.traintelco.com

439

xi


xii


| Java Programming: From Problem Analysis to Program Design, Fourth Edition

Classes and the Method toString

452

Copy Constructor

458

Static Members of a Class
static Variables (Data Members) of a Class

459
461

Finalizers

465

Accessor and Mutator Methods

465

Debugging—Designing a Class and Documenting
the Design
Debugging—Design Walk-Throughs

468
471


Reference this (Optional)
Cascaded Method Calls (Optional)

472
474

Inner Classes

477

Abstract Data Types

477

Programming Example: Candy Machine

479

Quick Review
Apago
PDF Enhancer

9

497

Exercises

498


Programming Exercises

505

ARRAYS

509

Why Do We Need Arrays?

510

Arrays
Alternate Ways to Declare an Array

511
513

Accessing Array Elements
Specifying Array Size during Program Execution

513
515

Array Initialization during Declaration

516

Arrays and the Instance Variable length

Processing One-Dimensional Arrays

516
517

Array Index Out of Bounds Exception
Declaring Arrays as Formal Parameters to Methods

522
522

Assignment Operator, Relational Operators, and Arrays:
A Precaution
Arrays as Parameters to Methods

www.traintelco.com

523
525


Table of Contents

Searching an Array for a Specific Item

530

Arrays of Objects

532


Arrays of string Objects
Arrays of Objects of Other Classes

532
534

Arrays and Variable Length Parameter List (Optional)

539

Two-Dimensional Arrays

547

Accessing Array Elements

549

Two-Dimensional Array Initialization During Declaration
Processing Two-Dimensional Arrays

552
553

Passing Two-Dimensional Arrays as Parameters to Methods

557

Multidimensional Arrays


561

Programming Example: Code Detection

563

Programming Example: Text Processing

567

class Vector (Optional)
Primitive Data Types and the class Vector

574
578

Apago
PDFandEnhancer
Vector Objects
the foreach Loop

10

| xiii

578

Quick Review


579

Exercises

581

Programming Exercises

586

INHERITANCE AND POLYMORPHISM

591

Inheritance

592

Using Methods of the Superclass in a Subclass
Constructors of the Superclass and Subclass

594
600

Protected Members of a Class

609

class object


612

Java Stream Classes

614

Polymorphism
Operator instanceof

615
621

Abstract Methods and Classes

626

Interfaces

632

www.traintelco.com


xiv

|

Java Programming: From Problem Analysis to Program Design, Fourth Edition

11


Polymorphism Via Interfaces

634

Composition (Aggregation)

636

Programming Example: Grade Report

641

Quick Review

661

Exercises

663

Programming Exercises

668

HANDLING EXCEPTIONS AND EVENTS

673

Handling Exceptions Within a Program

Java’s Mechanism of Exception Handling

674
677

try/catch/finally Block

678

Java Exception Hierarchy

683

Java’s Exception Classes

686

Checked and Unchecked Exceptions

691

Apago
PDF Enhancer
More Examples of Exception Handling

693

class Exception and the Operator instanceof

696


Rethrowing and Throwing an Exception

699

Method printStackTrace

703

Exception-Handling Techniques
Terminate the Program

706
706

Fix the Error and Continue

706

Log the Error and Continue

708

Creating Your Own Exception Classes

708

Event Handling

710


Programming Example: Calculator

716

Quick Review

726

Exercises

728

Programming Exercises

731

www.traintelco.com


Table of Contents

12

xv

ADVANCED GUIs AND GRAPHICS

733


Applets

737

class Font

741

class Color

744

class Graphics

750

Converting an Application Program to an Applet
Additional GUI Components
JTextArea

758
761
761

JCheckBox

766

JRadioButton
JComboBox


773
778

JList

783

Layout Managers
FlowLayout

789
790

BorderLayout

793

Apago
PDF Enhancer
Menus
Key and Mouse Events
Key Events
Mouse Events

13

|

794

797
798
800

Programming Example: Java Kiosk

807

Quick Review

815

Exercises

816

Programming Exercises

818

RECURSION

823

Recursive Definitions

824

Direct and Indirect Recursion
Infinite Recursion


826
827

Designing Recursive Methods

827

Problem Solving Using Recursion
Tower of Hanoi: Analysis

www.traintelco.com

828
837


xvi

|

Java Programming: From Problem Analysis to Program Design, Fourth Edition

Recursion or Iteration?

838

Programming Example: Decimal to Binary

14


Conversion

839

Programming Example: Sierpinski Gasket

842

Quick Review

846

Exercises

847

Programming Exercises

850

SEARCHING AND SORTING

855

List Processing

856

Searching

Selection Sort

856
857

Insertion Sort

861

Binary Search

867

Avoiding Bugs: Developing Test Suites in Advance

Apago
PDF Enhancer
Programming Example: Election Results

871
874

Quick Review

887

Exercises

887


Programming Exercises

888

APPENDIX A: JAVA RESERVED WORDS

891

APPENDIX B: OPERATOR PRECEDENCE

893

APPENDIX C: CHARACTER SETS

897

ASCII (American Standard Code for Information
Interchange), the First 128 Characters of the
Unicode Character Set
EBCDIC (Extended Binary Coded Decimal
Interchange Code)

www.traintelco.com

897
898


Table of Contents


APPENDIX D: ADDITIONAL JAVA TOPICS

|

xvii

901

Binary (Base 2) Representation of a Nonnegative Integer 901
Converting a Base 10 Number to a Binary Number (Base 2) 901
Converting a Binary Number (Base 2) to Base 10
903
Converting a Binary Number (Base 2) to Octol (Base 8)
and Hexdecimal (Base 16)

904

Executing Java Programs Using the Command-Line
Statements
Setting the Path in Windows (XP)
Executing Java Programs

906
906
911

Java Style Documentation

915


Creating Your Own Packages

918

Multiple File Programs

921

Formatting the Output of Decimal Numbers Using
the class DecimalFormat
Packages and
User-Defined
Classes
Apago
PDF
Enhancer

921

PrimitiveType Classes

924
924

Class: IntClass
Class: LongClass

924
928


Class: CharClass

929

Class: FloatClass
Class: DoubleClass

929
930

Class: BooleanClass
Using PrimitiveType Classes in a Program

931
932

Enumeration Types

933

Programming Example: The Rock, Paper,
and Scissors Game

939

APPENDIX E: ANSWERS TO ODD-NUMBERED
EXERCISES

949


Chapter 1

949

Chapter 2

950

www.traintelco.com


xviii

|

Java Programming: From Problem Analysis to Program Design, Fourth Edition

Chapter 3

952

Chapter 4

953

Chapter 5

955

Chapter 6


957

Chapter 7

962

Chapter 8

963

Chapter 9

965

Chapter 10

966

Chapter 11

968

Chapter 12

970

Chapter 13

971


Chapter 14

971

INDEX
Apago
PDF Enhancer

www.traintelco.com

973


P REFACE

TO THE

F OURTH E DITION

Welcome to Java Programming: From Problem Analysis to Program Design, Fourth Edition. Designed
for a first Computer Science (CS1) Java course, this text will provide a breath of fresh air to you
and your students. The CS1 course serves as the cornerstone of the Computer Science curriculum. My primary goal is to motivate and excite all programming students, regardless of their level.
Motivation breeds excitement for learning. Motivation and excitement are critical factors that
lead to the success of the programming student. This text is the culmination and development of
my classroom notes throughout more than fifty semesters of teaching successful programming.
Warning: This text can be expected to create a serious reduction in the demand for programming help during your office hours. Other side effects include significantly diminished student
dependency on others while learning to program.
The primary focus in writing this text is on student learning. Therefore, in addition to clear
explanations, we address the key issues that otherwise impede student learning. For example, a

common question that arises naturally during an early programming assignment is: ‘‘How
many variables and what kinds are needed in this program?’’ We illustrate this important and
crucial step by helping students learn why variables are needed and how data in a variable is
manipulated. Next students learn that the analysis of the problem will spill the number and
types of the variables. Once students grasp this key concept, control structures, (selection and
loops) become easier to learn. The second major impediment in learning programming is
parameter passing. We pay special attention to this topic. First students learn how to use
predefined methods and how actual and formal parameters relate. Next students learn about
user-defined methods. They see visual diagrams that help them learn how methods are called
and how formal parameters affect actual parameters. Once students have a clear understanding
of these two key concepts, they readily assimilate advanced topics.

Apago PDF Enhancer

The topics are introduced at a pace that is conducive to learning. The writing style is friendly,
engaging, and straightforward. It parallels the learning style of the contemporary CS1 student.
Before introducing a key concept, the student learns why the concept is needed, and then sees
examples illustrating the concept. Special attention is paid to topics that are essential in
mastering the Java programming language and in acquiring a foundation for further study
of computer science.
Other important topics include debugging techniques and techniques for avoiding programming bugs. When a beginner compiles his/her first program and sees that the number of
errors exceeds the length of this first program, he/she becomes frustrated by the plethora of
errors, only some of which can be interpreted. To ease this frustration and help students learn
to produce correct programs, debugging and bug avoidance techniques are presented systematically throughout the text.

www.traintelco.com


xx


| Java Programming: From Problem Analysis to Program Design, Fourth Edition

Changes In The Fourth Edition
In the fourth edition, the main changes are:



In the fourth edition, throughout the text sections on debugging techniques and
techniques on avoiding programming bugs are included.



Chapter 10 of the third edition, which includes searching and sorting algorithms, is
now Chapter 14. Sequential search algorithm and the class Vector, which were
covered in Chapter 10, have been moved to Chapter 9. The additional methods of
the class String, which were covered in Chapter 10 of the third edition, are
now covered in Chapter 3. The OOD version of the programming example of
Chapter 14 is available on the Web site and the CD accompanying this book.
Furthermore, Chapter 14 also contains bubble sort and quick sort algorithms, which
are provided on the Web site and the CD accompanying this book.



Chapters 11, 12, 13, and 14 in the third edition are now Chapters 10, 11, 12, and 13,
respectively, in the fourth edition.



In the third edition, Chapter 7 contains user-defined classes so that primitive type values
can be passed as objects and methods can manipulate and pass those values back to the

calling environment. In the fourth edition, this discussion is taken out of Chapter 7 and
put in a separate section, entitled ‘‘Chapter_7_PassingPrimitiveTypeAsObjects’’. This
section is available on the Web site and the CD accompanying this book. Furthermore,
as suggested by the reviewers, additional examples are included in this chapter.

Apago PDF Enhancer




The fourth addition contains more than 30 new programming exercises.
In Chapter 5, the Programming Example, Checking Account Balance, is available on
the Web site and the CD accompanying this book.



In Appendix D, a new section on how to create Java style documentation of userdefined classes has been added.
These changes were implemented based on comments from the text reviewers of the third
edition. The source code and the programming exercises are developed and tested using Java
6.0 and the version of Java 7.0 available at the time the book was being typeset.

Approach
Once conceived as a Web programming language, Java slowly but surely found its way into
classrooms where it now serves as a first programming language in computer science curricula
(CS1). Java is a combination of traditional style programming—programming with a nongraphical user interface—and modern style programming with a graphical user interface
(GUI). This book introduces you to both styles of programming. After giving a brief
description of each chapter, we discuss how to read this book.
Chapter 1 briefly reviews the history of computers and programming languages. The reader
can quickly skim and become familiar with some of the hardware and software components of
the computer. This chapter also gives an example of a Java program and describes how a Java


www.traintelco.com


Preface to the Fourth Edition

| xxi

program is processed. The two basic problem-solving techniques, structured programming
and object-oriented design, are also presented.
After completing Chapter 2, students become familiar with the basics of Java and are ready to
write programs that are complicated enough to do some computations.
The three terms that you will encounter throughout the book are—primitive type variables,
reference variables, and objects. Chapter 3 makes clear distinctions between these terms and sets
the tone for the rest of the book. An object is a fundamental entity in an object-oriented
programming language. This chapter further explains how an object works. The class String
is one of the most important classes in Java. This chapter introduces this class and explains how
various methods of this class can be used to manipulate strings. Because input/output is fundamental to any programming language, it is introduced early, and is covered in detail in Chapter 3.
Chapters 4 and 5 introduce control structures used to alter the sequential flow of execution.
Java is equipped with powerful yet easy-to-use graphical user interface (GUI) components to
create user-friendly graphical programs. Chapter 6 introduces various GUI components and
gives examples of how to use these components in Java application programs. Because Java is
an object-oriented programming language, the second part of Chapter 6 discusses and gives
examples of how to solve various problems using object-oriented design methodology.
Chapter 7 discusses user-defined methods. Parameter passing is a fundamental concept in any
programming language. Several examples, including visual diagrams, help readers understand
this concept. It is recommended that readers with no prior programming background spend
extra time on this concept.

Apago PDF Enhancer


Chapter 8 discusses user-defined classes. In Java, a class is an important and widely used
element. It is used to create Java programs, group related operations, and it allows users to
create their own data types. This chapter uses extensive visual diagrams to illustrate how
objects of classes manipulate data.
Chapter 9 describes arrays. This chapter also introduces variable length formal parameter lists.
In addition, this chapter introduces foreach loops and explains how this loop can be used to
process the elements of an array. This chapter also discusses the sequential searching algorithm
and the class Vector.
Inheritance is an important principle of object-oriented design. It encourages code reuse.
Chapter 10 discusses inheritance, and gives various examples to illustrate how classes are
derived from existing classes. In addition, this chapter also discusses polymorphism, abstract
classes, inner classes, and composition.
An occurrence of an undesirable situation that can be detected during program execution is
called an exception. For example, division by zero is an exception. Java provides extensive
support for handing exceptions. Chapter 11 shows how to handle exceptions in a program.
Chapter 11 also discusses event handling, which was introduced in Chapter 6. Chapter 12
picks up the discussion of GUI components started in Chapter 6. This chapter introduces
additional GUI components and discusses how to create applets.

www.traintelco.com


xxii |

Java Programming: From Problem Analysis to Program Design, Fourth Edition

Chapter 13 introduces recursion. Several examples illustrate how recursive methods execute.
Chapter 14 discusses a binary search algorithm as well as bubble sort, selection sort, insertion
sort, and quick sort algorithms. The sorting algorithms: bubble sort and quick sort are

provided on the Web site and the CD accompanying this book.
Appendix A lists the reserved words in Java. Appendix B shows the precedence and
associativity of the Java operators. Appendix C lists the ASCII (American Standard Code
for Information Interchange) portion of the Unicode character set as well as the EBCDIC
(Extended Binary Code Decimal Interchange) character set.
Appendix D contains additional topics in Java. The topics covered are converting a base 10
number to binary (base 2) number and vice versa, converting a number from base 2 to base 8
(base 16) and vice versa, how to compile and execute a Java program using command line
statements, how to create Java style documentation of the user-defined classes, how to create
packages, how to use user-defined classes in a Java program, and enum type. Appendix E
gives answers to all the odd-numbered exercises in the text.

How To Use This Book
Java is a complex and very powerful language. In addition to traditional (non-GUI) programming, Java provides extensive support for creating programs that use a graphical user interface
(GUI). Chapter 3 introduces graphical input and output dialog boxes. Chapter 6 introduces
most commonly used GUI components such as labels, buttons, and text fields. More extensive
coverage of GUI components is provided in Chapter 12.

Apago PDF Enhancer

This book can be used in two ways. One way is an integrated approach in which readers learn
how to write both non-GUI and GUI programs as they learn basic programming concepts
and skills. The other approach focuses on illustrating fundamental programming concepts
with non-GUI programming first, and later incorporating GUI components. The recommended chapter sequence for each of these approaches is as follows:




Integrated approach: Study all chapters in sequence.
Non-GUI first, then GUI: Study Chapters 1–5 in sequence. Then study Chapters

7–11 and Chapters 13 and 14. This approach initially skips Chapters 6 and 12, the
primary GUI chapters. After studying Chapters 1–5, 7–11, 13, and 14, the reader can
come back to study Chapters 6 and 12, the GUI chapters. Also note that Chapter 14
can be studied after Chapter 9.

If you choose the second approach, it should also be noted that the Programming Examples in
Chapters 8 and 10 are developed first without any GUI components, and then the programs
are extended to incorporate GUI components. Also, if Chapter 6 is skipped, the reader can skip
the event handling part of Chapter 11. Chapter 13 (recursion) contains two Programming
Examples: one creates a non-GUI application program, while the other creates a program that
uses GUI. If you skip Chapters 6 and 12, you can skip the GUI part of the Programming
Examples in Chapters 8, 10, 11, and 13. Once you have studied Chapter 6 and 12, you can
study the GUI part of the Programming Examples of Chapters 8, 10, 11, and 13.

www.traintelco.com


Preface to the Fourth Edition

| xxiii

Figure 1 shows a chapter dependency diagram for this book. Solid arrows indicate that the
chapter at the beginning of the arrow is required before studying the chapter at the end of the
arrow. A dotted arrow indicates that the chapter at the beginning of the arrow is not essential
to studying the chapter at the end of the dotted arrow.
Chapter 1
Chapter 2
Chapter 3
Chapter 4


Chapter 5

Chapter 6

Chapter 7

Chapter 8

Chapter 9

Apago PDF Enhancer
Chapter 10

Chapter 14

Chapter 11

Chapter 12

Chapter 13
A dotted arrow means that the chapter is not essential to studying the following chapter.

FIGURE 1

Chapter dependency diagram

All source code and solutions have been written, compiled, and quality assurance tested
with Java 6.0 and the version of Java 7.0 available at the time the book was being typeset.

www.traintelco.com



FEATURES

OF THE

BOOK

Apago PDF Enhancer

Four-color
interior design
shows
accurate code
and related
comments.

www.traintelco.com


×