Java Foundations Introduction To Program Design
And Data Structures 2nd Edition 2nd Edition John
Lewis download
https://ebookbell.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-2nd-edition-john-
lewis-2355602
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Java Foundations Introduction To Program Design And Data Structures
5th Edition 5th Edition John Lewis
https://ebookbell.com/product/java-foundations-introduction-to-
program-design-and-data-structures-5th-edition-5th-edition-john-
lewis-32182666
Java Foundations Introduction To Program Design And Data Structures
4th Edition 4th Edition John Lewis
https://ebookbell.com/product/java-foundations-introduction-to-
program-design-and-data-structures-4th-edition-4th-edition-john-
lewis-37247276
Java Foundations 3rd Ed Chase Joseph Depasquale Peter Joseph Lewis
https://ebookbell.com/product/java-foundations-3rd-ed-chase-joseph-
depasquale-peter-joseph-lewis-21976870
Java Foundations Todd Greanier
https://ebookbell.com/product/java-foundations-todd-greanier-976556
Java Software Solutions Foundations Of Program Design 7th Edition 7th
Edition John Lewis
https://ebookbell.com/product/java-software-solutions-foundations-of-
program-design-7th-edition-7th-edition-john-lewis-2371348
Java Software Solutions Foundations Of Program Design 4th Edition John
Lewis
https://ebookbell.com/product/java-software-solutions-foundations-of-
program-design-4th-edition-john-lewis-1294350
Foundations Of Java For Abap Programmers 1st Edition Alistair Rooney
https://ebookbell.com/product/foundations-of-java-for-abap-
programmers-1st-edition-alistair-rooney-929496
Foundations Of Java Programming Oop Option Clin Galeriu
https://ebookbell.com/product/foundations-of-java-programming-oop-
option-clin-galeriu-30345526
Distributed Virtual Worlds Foundations And Implementation Techniques
Using Vrml Java And Corba 1st Edition Dr Stephan Diehl Auth
https://ebookbell.com/product/distributed-virtual-worlds-foundations-
and-implementation-techniques-using-vrml-java-and-corba-1st-edition-
dr-stephan-diehl-auth-4198916
Javaℱ
Foundations
Second Edition
Introduction to
Program Design & Data Structures
This page intentionally left blank
John Lewis
Virginia Tech
Peter DePasquale
The College of New Jersey
Joseph Chase
Radford University
Javaℱ
Foundations
Second Edition
Introduction to
Program Design & Data Structures
Addison-Wesley
Boston Columbus Indianapolis New York San Francisco
Upper Saddle River Amsterdam Cape Town Dubai London Madrid
Milan Munich Paris Montreal Toronto Delhi Mexico City
Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Editor-in-Chief: Michael Hirsch
Editorial Assistant: Stephanie Sellinger
Director of Marketing: Margaret Whaples
Marketing Coordinator: Kathryn Ferranti
Managing Editor: Jeffrey Holcomb
Production Project Manager: Heather McNally
Senior Manufacturing Buyer: Carol Melville
Media Manufacturing Buyer: Ginny Michaud
Art Director: Linda Knowles
Cover Designer: Susan Paradise
Cover Art: Marc Romanelli/Getty Images
Media Project Manager: Katelyn Boller
Full-Service Project Management: Rose Kernan, Nesbitt Graphics, Inc.
Composition: Nesbitt Graphics, Inc.
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on
appropriate page within text.
MicrosoftÂź and WindowsÂź are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. 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.
The programs and applications presented in this book have been included for their instructional value. They have been tested
with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations,
nor does it accept any liabilities with respect to the programs or applications.
Copyright © 2011, 2008. Pearson Education, Inc., publishing as Addison-Wesley, 501 Boylston Street, Suite 900, Boston,
Massachusetts 02116. All rights reserved. Manufactured in the United States of America. This publication is protected by
Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain
permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions
Department, 501 Boylston Street, Suite 900, Boston, Massachusetts 02116.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those
designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in
initial caps or all caps.
Library of Congress Cataloging-in-Publication Data
Lewis, John, 1963-
Java foundations : introduction to program design & data structures / John
Lewis, Peter J. DePasquale, Joseph Chase. -- 2nd ed.
p. cm.
ISBN 0-13-212881-0
1. Java (Computer program language) I. DePasquale, Peter J. (Peter Joseph)
II. Chase, Joseph, 1964- III. Title.
QA76.73.J38L48845 2010
005.13'3--dc22
2009051134
10 9 8 7 6 5 4 3 2 1–EB–14 13 12 11 10
www.pearsonhighered.com
ISBN-10: 0-13-212881-0
ISBN-13: 978-0-13-212881-0
To my wife, Sharon, for everything.
– John
To my wife, Lisa, and our twins: Lily and Adam.
– Pete
To my loving wife, Melissa, for her support and encouragement.
– Joe
This page intentionally left blank
Preface
vii
Welcome to Java Foundations. This book is designed to serve as the primary
resource for a two- or three-term introductory course sequence, ranging from the
most basic programming concepts to the design and implementation of complex
data structures. This unified approach makes the important introductory
sequence more cohesive and accessible for students.
We’ve borrowed the best elements from the industry-leading text Java Software
Solutions for the introductory material, reworked to complement the design and
vision of the overall text. For example, instead of having graphics sections spread
throughout many chapters, the coverage of graphical user interfaces is accom-
plished in a well-organized chapter of its own.
In the later chapters, the exploration of collections and data structures is mod-
eled somewhat after the coverage in Java Software Structures, but has been thor-
oughly retooled to flow cleanly from the introductory material. The result is a
comprehensive, cohesive, and seamless exploration of programming concepts.
New in the Second Edition
We appreciate the feedback we’ve received about this book and are pleased that
it served so well as an introductory text. The following modifications have been
made to improve the presentation of particular topics and the overall flow:
■ A stack is now used as the initial example of a collection so that the con-
cept of a collection is more clearly established.
■ The discussion of Generics has been expanded and clarified.
■ The coverage of the Quick Sort and Merge Sort algorithms has been
expanded.
■ The coverage of Analysis of Algorithms has been separated into its own
chapter and expanded.
■ Material on Testing and Debugging has been incorporated into more
appropriate locations of the text.
■ The coverage of Search Trees and Heaps have been divided into separate
chapters.
viii PREFACE
■ Two new chapters covering Hashing and Databases have been added.
■ End-of-chapter exercises and projects have been updated to reflect changes
in the book.
Regarding Objects
Phrases like objects-first, objects-early, and objects-late continue to be bandied
about by computing educators, despite the fact that the nuances of the pedagogy
of the introductory sequence cannot be summed up so easily. We’ll take this
opportunity to discuss our approach.
First, this book is purely object-oriented, presented in a gradual, natural man-
ner. Concepts that overlap with procedural programming, such as methods and
their invocation, are discussed in terms of an object-oriented approach. Thus, no
example is ever made up of a single class with multiple methods. In fact, in our
examples the class that contains the main method never contains another.
We use objects right from the start, and discuss everything in object-oriented
terms at all times. An overview of object-oriented concepts is given in Chapter 1,
then reinforced and fleshed out throughout the book. Classes from the Java stan-
dard class library are introduced immediately, and objects from these classes are
instantiated and used for the various services they provide. In the first four chap-
ters, students explore and write programs made up of a single class with a single
main method—but these programs actively use predefined classes and objects
from the standard library in addition to exploring fundamental programming
concepts such as expressions and conditionals.
We never introduce third-party classes simply as fodder to create examples.
That approach can confuse students by blurring the distinction between classes
that are part of the standard library (and thus always available) and “extras”
thrown in by textbook authors as a convenience. Every non-library class used
in an example is fully explored in this book. There’s no “magic” behind the
scenes.
The debate continues: should coverage of control structures come before the
details of writing classes, or vice versa? The truth is there are advantages either
way, and a knowledgeable instructor can capitalize on either approach. If class
composition comes first, it exposes the underlying essence of objects earlier and
demystifies their use. However, without the ability to use basic control structures,
the examples at that point are often uninteresting and unrealistic. This book
explores control structures before writing classes. Chapter 4 uses small, single-
method examples to examine the details of conditionals and loops, providing a
strong foundation for the multiclass examples in Chapter 5.
PREFACE ix
Chapter Breakdown
Chapter 1 (Introduction) introduces the Java programming language and the
basics of program development. It contains an introduction to object-oriented
development, including an overview of concepts and terminology. This chapter
contains broad introductory material that can be covered while students become
familiar with their development environment.
Chapter 2 (Data and Expressions) explores some of the basic types of data used
in a Java program and the use of expressions to perform calculations. It discusses
the conversion of data from one type to another, and how to read input interac-
tively from the user with the help of the Scanner class.
Chapter 3 (Using Classes and Objects) explores the use of predefined classes
and the objects that can be created from them. Classes and objects are used to
manipulate character strings, produce random numbers, perform complex calcu-
lations, and format output. Packages, enumerated types, and wrapper classes are
also discussed.
Chapter 4 (Conditionals and Loops) covers the use of boolean expressions to
make decisions. All related statements for conditionals and loops are discussed,
including the enhanced version of the for loop. The Scanner class is revisited
for iterative input parsing and reading text files.
Chapter 5 (Writing Classes) explores the basic issues related to writing classes
and methods. Topics include instance data, visibility, scope, method parameters,
and return types. Constructors, method design, static data, and method overload-
ing are covered as well. Testing and debugging are now covered in this chapter as
well.
Chapter 6 (Graphical User Interfaces) is a thorough exploration of Java GUI
processing, focusing on components, events, and listeners. Many types of compo-
nents and events are discussed using numerous GUI examples. Additionally, lay-
out mangers, containment hierarchies, borders, tooltips, and mnemonics are
introduced.
Chapter 7 (Arrays) contains extensive coverage of arrays and array processing.
Topics include bounds checking, initializer lists, command-line arguments, variable-
length parameter lists, and multidimensional arrays.
Chapter 8 (Inheritance) covers class derivations and associated concepts such
as class hierarchies, overriding, and visibility. Strong emphasis is put on the proper
use of inheritance and its role in software design.
Chapter 9 (Polymorphism) explores the concept of binding and how it relates
to polymorphism. Then we examine how polymorphic references can be accom-
plished using either inheritance or interfaces. Design issues related to polymor-
phism are examined as well.
x PREFACE
Chapter 10 (Exceptions) covers exception handling and the effects of
uncaught exceptions. The try-catch statement is examined, as well as a dis-
cussion of exception propagation. The chapter also explores the use of excep-
tions when dealing with input and output, and examines an example that writes
a text file.
Chapter 11 (Recursion) covers the concept, implementation, and proper use of
recursion. Several examples are used to elaborate on the discussion, including a
maze traversal and the classic Towers of Hanoi problem.
Chapter 12 (Analysis of Algorithms) discusses the techniques for analyzing the
complexity of algorithms, including recursive algorithms. Big Oh notation is
introduced.
Chapter 13 (Searching and Sorting) explores the linear and binary searching
algorithms, as well as five sorting algorithms. The sorts include both quadratic
and O(N log N) algorithms. The efficiency of these algorithms is examined.
Chapter 14 (Stacks) introduces the concept of a collection and establishes the
importance of separating the interface from the implementation. Stacks are used
as the initial example of a collection, and both dynamic and fixed implementa-
tions of a stack are explored. Generic types are introduced in this chapter, detail-
ing their use in supporting the collection classes.
Chapter 15 (Queues) introduces FIFO queues and discusses options for their
implementation. As with stacks, a queue is explored first conceptually, then as
tools to help us solve problems, and finally by examining their underlying data
structures. Both array-based and dynamic link implementations are discussed.
Chapter 16 (Trees) introduces the terms and concepts behind trees. Various
implementation strategies are discussed, and a recursive, linked approach is exam-
ined in detail. An example of a binary decision tree is explored as well.
Chapter 17 (Binary Search Trees) covers the concept of search trees and a
linked implementation for a classic binary search tree. Tree rotation algorithms
are also discussed.
Chapter 18 (Heaps and Priority Queues) discusses the concept of a heap and
its relationship to trees. A full linked implementation of a heap is explored.
Priority queues are used as an example of a collection in its own right, and the
natural relationship between heaps and priority queues are explored.
Chapter 19 (Graphs) discusses both directed and undirected graphs.
Additionally, weighted graphs are explored, and the differences between breadth-
first and depth-first graph traversals are covered. Minimal spanning trees are
introduced, and implementation strategies are discussed.
Chapter 20 (Hashing) covers the concept of creating a hash table to facilitate
storage and retrieval of objects. Various classes that relate to hashing from the
Java API are explored.
PREFACE xi
Chapter 21 (Databases) explores the concept of databases and their manage-
ment, and discusses the basics of SQL queries. It then explores the techniques for
establishing a connection between a Java program and a database, and the API
used to interact with it.
Student CD
The CD included with each textbook contains:
■ Source code for all of the programs in the text.
■ The Java Software Development Kit (SDK).
■ Various Java development environments, including NetBeansℱ, Eclipseℱ,
DrJava, jGRASPℱ, and TextPad¼.
Instructor Resources
The following supplements are available to qualified instructors only. Visit the
Pearson Education Instructor Resource Center (www.pearsonhighered.com/irc)
or send email to computing@aw.com for information on how to access these
resources.
■ Presentation Slides—lecture-ready presentations for each chapter in
Microsoft PowerPointÂź format.
■ Solutions—full solutions to the exercises and programming projects.
■ Test Bank with powerful test generator software—includes a wealth of
free-response, multiple-choice, and true/false questions.
Acknowledgments
Educators and students from around the world have provided feedback on previ-
ous work that has allowed us to mold this book into a fresh, valuable resource.
Your comments and questions are always welcome.
The talent and commitment of the team at Addison-Wesley continues to amaze
us. We greatly appreciate the insight of Michael Hirsch, our editor, and the hard
work of his assistant, Stephanie Sellinger. Rose Kernan at Nesbitt Graphics was a
great help throughout the production process. We thank all of these people for
ensuring that this book meets the highest quality standards.
We’d like to acknowledge the collective input from hundreds of professors and
students around the world in the development of the material upon which this
xii PREFACE
book is based. There are too many of you to individually name, but your influ-
ence on Java Software Solutions and Java Software Structures is evident in Java
Foundations.
Special thanks go to Ruth Dannenfelser, Cory Samaha, and Zach Zappala at
the College of New Jersey for their help with solutions to the database projects.
And our continued thanks go to Jason Snyder at Virginia Tech for his assistance
testing code and many other contributions.
Groups like the ACM Special Interest Group on Computer Science Education
(SIGCSE), the Consortium for Computing Sciences in Colleges (CCSC), and the
Computer Science Teachers Association (CSTA) are phenomenal resources. Their
conferences and online activities provide opportunities for educators from all lev-
els and all types of schools to share ideas and materials. If you are a computing
educator and are not involved with these groups, you’re missing out.
Finally, we thank our families for their support and patience during the busy
process of writing.
xiii
Preface vii
Chapter 1 Introduction 1
1.1 The Java Programming Language 2
A Java Program 3
Comments 5
Identifiers and Reserved Words 6
White Space 9
1.2 Program Development 11
Programming Language Levels 11
Editors, Compilers, and Interpreters 13
Development Environments 15
Syntax and Semantics 16
Errors 17
1.3 Problem Solving 18
1.4 Software Development Activities 19
1.5 Object-Oriented Programming 21
Object-Oriented Software Principles 21
Chapter 2 Data and Expressions 31
2.1 Character Strings 32
The print and println Methods 32
String Concatenation 34
Escape Sequences 37
2.2 Variables and Assignment 38
Variables 38
The Assignment Statement 40
Constants 42
2.3 Primitive Data Types 43
Integers and Floating Points 43
Contents
xiv CONTENTS
Characters 45
Booleans 47
2.4 Expressions 47
Arithmetic Operators 48
Operator Precedence 48
Increment and Decrement Operators 51
Assignment Operators 53
2.5 Data Conversion 54
Conversion Techniques 56
2.6 Reading Input Data 57
The Scanner Class 57
Chapter 3 Using Classes and Objects 71
3.1 Creating Objects 72
Aliases 74
3.2 The String Class 76
3.3 Packages 79
The import Declaration 80
3.4 The Random Class 82
3.5 The Math Class 85
3.6 Formatting Output 88
The NumberFormat Class 88
The DecimalFormat Class 90
The printf Method 92
3.7 Enumerated Types 92
3.8 Wrapper Classes 95
Autoboxing 97
Chapter 4 Conditionals and Loops 105
4.1 Boolean Expressions 106
Equality and Relational Operators 107
Logical Operators 108
CONTENTS xv
4.2 The if Statement 110
The if-else Statement 113
Using Block Statements 115
The Conditional Operator 118
Nested if Statements 119
4.3 Comparing Data 121
Comparing Floats 121
Comparing Characters 121
Comparing Objects 122
4.4 The switch Statement 123
4.5 The while Statement 127
Infinite Loops 132
Nested Loops 133
Other Loop Controls 137
4.6 Iterators 137
Reading Text Files 138
4.7 The do Statement 141
4.8 The for Statement 144
Iterators and for Loops 149
Comparing Loops 149
Chapter 5 Writing Classes 161
5.1 Classes and Objects Revisited 162
Identifying Classes and Objects 163
Assigning Responsibilities 165
5.2 Anatomy of a Class 165
Instance Data 170
UML Class Diagrams 171
5.3 Encapsulation 173
Visibility Modifiers 174
Accessors and Mutators 175
5.4 Anatomy of a Method 180
The return Statement 186
Parameters 188
xvi CONTENTS
Local Data 189
Constructors Revisited 190
5.5 Static Class Members 190
Static Variables 191
Static Methods 191
5.6 Class Relationships 192
Dependency 195
Dependencies Among Objects
of the Same Class 195
Aggregation 197
The this Reference 202
5.7 Method Design 203
Method Decomposition 204
Method Parameters Revisited 209
5.8 Method Overloading 210
5.9 Testing 216
Reviews 217
Defect Testing 217
Unit Testing 219
Integration Testing 219
System Testing 219
Test-Driven Development 220
5.10 Debugging 220
Simple Debugging with print Statements 221
Debugging Concepts 221
Chapter 6 Graphical User Interfaces 233
6.1 GUI Elements 234
Frames and Panels 235
Buttons and Action Events 239
Determining Event Sources 240
6.2 More Components 243
Text Fields 244
Check Boxes 247
Radio Buttons 250
CONTENTS xvii
Sliders 255
Combo Boxes 260
Timers 265
6.3 Layout Managers 269
Flow Layout 271
Border Layout 274
Grid Layout 278
Box Layout 280
Containment Hierarchies 284
6.4 Mouse and Key Events 284
Mouse Events 284
Key Events 292
Extending Adapter Classes 297
6.5 Dialog Boxes 298
File Choosers 301
Color Choosers 304
6.6 Some Important Details 305
Borders 305
Tool Tips and Mnemonics 309
6.7 GUI Design 315
Chapter 7 Arrays 325
7.1 Array Elements 326
7.2 Declaring and Using Arrays 327
Bounds Checking 329
Alternate Array Syntax 335
Initializer Lists 335
Arrays as Parameters 336
7.3 Arrays of Objects 337
7.4 Command-Line Arguments 346
7.5 Variable-Length Parameter Lists 348
7.6 Two-Dimensional Arrays 351
Multidimensional Arrays 355
xviii CONTENTS
Chapter 8 Inheritance 363
8.1 Creating Subclasses 364
The protected Modifier 368
The super Reference 370
Multiple Inheritance 371
8.2 Overriding Methods 374
Shadowing Variables 375
8.3 Class Hierarchies 376
The Object Class 378
Abstract Classes 380
8.4 Visibility 382
8.5 Designing for Inheritance 385
Restricting Inheritance 385
Chapter 9 Polymorphism 393
9.1 Late Binding 394
9.2 Polymorphism via Inheritance 394
9.3 Interfaces 407
Interface Hierarchies 412
The Comparable Interface 413
The Iterator Interface 413
9.4 Polymorphism via Interfaces 414
Event Processing 416
Chapter 10 Exceptions 423
10.1 Exception Handling 424
10.2 Uncaught Exceptions 425
10.3 The try-catch Statement 425
The finally Clause 429
10.4 Exception Propagation 430
CONTENTS xix
10.5 The Exception Class Hierarchy 433
Checked and Unchecked Exceptions 436
10.6 I/O Exceptions 437
Chapter 11 Recursion 447
11.1 Recursive Thinking 448
Infinite Recursion 449
Recursion in Math 449
11.2 Recursive Programming 450
Recursion vs. Iteration 453
Direct vs. Indirect Recursion 453
11.3 Using Recursion 454
Traversing a Maze 454
The Towers of Hanoi 459
Chapter 12 Analysis of Algorithms 469
12.1 Algorithm Efficiency 470
12.2 Growth Functions and Big-Oh Notation 471
12.3 Comparing Growth Functions 473
Method Calls 475
Analyzing Recursive Algorithms 477
Chapter 13 Searching and Sorting 481
13.1 Searching 482
Linear Search 485
Binary Search 487
13.2 Sorting 489
Selection Sort 490
Insertion Sort 497
Bubble Sort 498
Quick Sort 500
Merge Sort 501
xx CONTENTS
13.3 Analyzing Searching and Sorting
Algorithms 503
Comparing Search Algorithms 504
Comparing Sort Algorithms 504
Chapter 14 Stacks 513
14.1 Introduction to Collections 514
Abstract Data Types 514
The Java Collections API 516
14.2 A Stack Collection 517
14.3 Inheritance, Polymorphism,
and Generics 519
Generics 520
14.4 A Stack ADT 521
14.5 Using Stacks: Evaluating Postfix
Expressions 523
14.6 Exceptions 530
14.7 Implementing a Stack: with Arrays 532
Managing Capacity 532
14.8 The ArrayStack Class 533
The push Operation 537
The pop Operation 537
The peek Operation 538
Other Operations 538
14.9 References as Links 538
14.10 Managing Linked Lists 541
Accessing Elements 541
Inserting Nodes 542
Deleting Nodes 543
Sentinel Nodes 544
14.11 Elements Without Links 544
Doubly Linked Lists 545
CONTENTS xxi
14.12 Implementing a Stack: With Links 546
The LinkedStack Class 546
The push Operation 550
The pop Operation 552
Other Operations 555
14.13 Implementing Stacks:
The Java.Util.Stack Class 553
Unique Operations 553
Inheritance and Implementation 554
14.14 Packages 554
Organizing Packages 555
Using CLASSPATH 555
Chapter 15 Queues 567
15.1 A Queue ADT 568
15.2 Using Queues: Code Keys 570
15.3 Using Queues: Ticket Counter Simulation 574
15.4 Implementing Queues: With Links 577
The enqueue Operation 582
The dequeue Operation 583
Other Operations 583
15.5 Implementing Queues: With Arrays 584
The enqueue Operation 587
The dequeue Operation 590
Other Operations 590
Chapter 16 Trees 595
16.1 Tree Terminology 596
Tree Classifications 597
16.2 Tree Traversals 598
Preorder Traversal 600
Inorder Traversal 601
Postorder Traversal 601
Level-Order Traversal 602
xxii CONTENTS
16.3 Strategies for Implementing Trees 602
Computed Links in an Array 603
Stored Links in an Array 603
Linked Nodes 604
16.4 A Binary Tree Implementation 605
16.5 Decision Trees 606
Chapter 17 Binary Search Trees 625
17.1 Binary Search Trees 626
Adding an Element to a Binary Search Tree 627
Removing an Element from a Binary
Search Tree 629
17.2 Binary Search Tree Implementation 630
17.3 Balanced Binary Search Trees 640
Right Rotation 641
Left Rotation 642
Right-Left Rotation 642
Left-Right Rotation 643
Chapter 18 Heaps and Priority Queues 649
18.1 Heaps 650
Adding an Element to a Heap 650
Removing the Largest Element
from a Heap 651
18.2 Heap Implementation 652
18.3 Heap Sort 660
18.4 Priority Queues 660
Chapter 19 Graphs 669
19.1 Undirected Graphs 670
19.2 Directed Graphs 671
CONTENTS xxiii
19.3 Weighted Graphs 673
19.4 Common Graph Algorithms 674
Traversals 674
Testing for Connectivity 678
Minimum Spanning Trees 680
Determining the Shortest Path 682
19.5 Strategies for Implementing Graphs 683
Adjacency Lists 684
Adjacency Matrices 684
Chapter 20 Hashing 689
20.1 Hashing 690
20.2 Hashing Functions 692
The Division Method 692
The Folding Method 693
The Mid-square Method 693
The Radix Transformation Method 694
The Digit Analysis Method 694
The Length-Dependent Method 694
Hashing Functions in the Java Language 695
20.3 Resolving Collisions 695
Chaining 695
Open Addressing 698
20.4 Deleting Elements from A Hash Table 701
Deleting from a Chained Implementation 701
Deleting from an Open Addressing
Implementation 702
20.5 Hash Tables in the Java Collections API 703
The Hashtable Class 704
The HashSet Class 704
The HashMap Class 706
The IdentityHashMap Class 707
The WeakHashMap Class 709
LinkedHashSet and LinkedHashMap 710
xxiv CONTENTS
Chapter 21 Databases 717
21.1 Introduction to Databases 718
21.2 Establishing a Connection to a Database 720
Obtaining A Database Driver 720
21.3 Creating and Altering Database Tables 722
Create Table 723
Alter Table 724
Drop Column 725
21.4 Querying The Database 725
Show Columns 726
21.5 Inserting, Viewing, and Updating
(Modifying) Data 728
Insert 729
Select . . . from 729
Update 734
21.6 Deleting Data and Database Tables 735
Deleting Data 735
Deleting Database Tables 736
Appendix A Glossary 741
Appendix B Number Systems 775
Place Value 776
Bases Higher Than 10 778
Conversions 779
Shortcut Conversions 781
Appendix C The Unicode Character Set 787
Appendix D Java Bitwise Operators 791
CONTENTS xxv
Appendix E Java Modifiers 797
Java Visibility Modifiers 798
A Visibility Example 798
Other Java Modifiers 799
Appendix F Java Graphics 801
Coordinate Systems 802
Representing Color 802
Drawing Shapes 803
Polygons and Polylines 812
The Polygon Class 813
Appendix G Java Applets 821
Embedding Applets in HTML 824
More Applet Methods 824
GUIs in Applets 829
Appendix H Regular Expressions 837
Appendix I Javadoc Documentation
Generator 839
Doc Comments 840
Tags 841
Files Generated 841
Appendix J Java Syntax 845
Index 859
This page intentionally left blank
Javaℱ
Foundations
Second Edition
Introduction to
Program Design & Data Structures
This page intentionally left blank
Introduction
1
C H A P T E R O B J E C T I V E S
■ Introduce the Java programming language.
■ Describe the steps involved in program compilation
and execution.
■ Explore the issues related to problem solving in general.
■ Discuss the activities involved in the software development
process.
■ Present an overview of object-oriented principles.
This book is about writing well-designed software. We
begin by examining a very basic Java program and using it
to explore some initial programming concepts. We then lay
the groundwork for software development on a larger scale,
exploring the foundations of problem solving, the activities
involved in software development, and the principles of
object-oriented programming.
1
1
1.1 The Java Programming Language
A computer is made up of hardware and software. The hardware components of
a computer system are the physical, tangible pieces that support the computing ef-
fort. They include chips, boxes, wires, keyboards, speakers, disks, cables, print-
ers, and so on. The hardware is essentially useless without instructions to tell it
what to do. A program is a series of instructions that the hardware executes one
after another. Programs are sometimes called applications. Software consists of
programs and the data those programs use. Software is the intangible counterpart
to the physical hardware components. Together, they form a tool that we can use
to solve problems.
A program is written in a particular programming language that
uses specific words and symbols to express the problem solution. A
programming language defines a set of rules that determines exactly
how a programmer can combine the words and symbols of the lan-
guage into programming statements, which are the instructions that
are carried out when the program is executed.
Since the inception of computers, many programming languages have been cre-
ated. We use the Java language in this book to demonstrate various programming
concepts and techniques. Although our main goal is to learn these underlying
software development concepts, an important side effect will be to become profi-
cient in the development of Java programs.
Java is a relatively new programming language compared to many others. It
was developed in the early 1990s by James Gosling at Sun Microsystems. Java
was introduced to the public in 1995 and has gained tremendous popularity
since.
Java has undergone various changes since its creation. The most recent Java
technology is generally referred to as the Java 2 Platform, which is organized into
three major groups:
■ Java 2 Platform, Standard Edition (J2SE)
■ Java 2 Platform, Enterprise Edition (J2EE)
■ Java 2 Platform, Micro Edition (J2ME)
This book focuses on the Standard Edition, which, as the name implies, is
the mainstream version of the language and associated tools. Furthermore, this
book is based on the most recent version of the Standard Edition, which is
J2SE 6.0.
Some parts of early Java technologies have been deprecated, which means they
are considered old-fashioned and should not be used. When it is important, we
point out deprecated elements and discuss their preferred alternatives.
2 CHAPTER 1 Introduction
KEY CONCEPT
A computer system consists of
hardware and software that work in
concert to help us solve problems.
Java is an object-oriented programming language. Objects are the
fundamental elements that make up a program. The principles of ob-
ject-oriented software development are the cornerstone of this book.
We explore object-oriented programming concepts later in this chap-
ter and throughout the rest of the book.
The Java language is accompanied by a library of extra software that we can
use when developing programs. This software, referred to as the Java standard
class library, provides the ability to create graphics, communicate over networks,
and interact with databases, among many other features. The standard library
that supports Java programming is huge and quite versatile. Although we won’t
be able to cover all aspects of the library, we will explore many of them.
Java is used in commercial environments all over the world. It is one of the
fastest growing programming technologies of all time. So not only is it a good
language in which to learn programming concepts, it is also a practical language
that will serve you well in the future.
A Java Program
Let’s look at a simple but complete Java program. The program in Listing 1.1
prints two sentences to the screen. This particular program prints a quote by
Abraham Lincoln. The output is shown below the program listing.
All Java applications have a similar basic structure. Despite its small size and
simple purpose, this program contains several important features. Let’s carefully
dissect it and examine its pieces.
The first few lines of the program are comments, which start with
the // symbols and continue to the end of the line. Comments don’t af-
fect what the program does but are included to make the program eas-
ier to understand by humans. Programmers can and should include
comments as needed throughout a program to clearly identify the pur-
pose of the program and describe any special processing. Any written
comments or documents, including a user’s guide and technical references, are called
documentation. Comments included in a program are called inline documentation.
The rest of the program is a class definition. This class is called Lincoln,
though we could have named it just about anything we wished. The class defini-
tion runs from the first opening brace ({) to the final closing brace (}) on the last
line of the program. All Java programs are defined using class definitions.
Inside the class definition are some more comments describing the purpose of
the main method, which is defined directly below the comments. A method is a
group of programming statements that is given a name. In this case, the name of
the method is main and it contains only two programming statements. Like a
class definition, a method is also delimited by braces.
1.1 The Java Programming Language 3
KEY CONCEPT
This book focuses on the principles
of object-oriented programming.
KEY CONCEPT
Comments do not affect a program’s
processing; instead, they serve to
facilitate human comprehension.
All Java applications have a main method, which is where processing begins.
Each programming statement in the main method is executed, one at a time in order,
until the end of the method is reached. Then the program ends, or terminates. The
main method definition in a Java program is always preceded by the words public,
static, and void, which we examine later in the text. The use of String and args
does not come into play in this particular program. We describe these later also.
The two lines of code in the main method invoke another method called
println (pronounced print line). We invoke, or call, a method when we want it
to execute. The println method prints the specified characters to the screen. The
characters to be printed are represented as a character string, enclosed in double
quote characters ("). When the program is executed, it calls the println method
to print the first statement, calls it again to print the second statement, and then,
because that is the last line in the main method, the program terminates.
The code executed when the println method is invoked is not defined in this
program. The println method is part of the System.out object, which is part of
4 CHAPTER 1 Introduction
L I S T I N G 1 . 1
//********************************************************************
// Lincoln.java Java Foundations
//
// Demonstrates the basic structure of a Java application.
//********************************************************************
public class Lincoln
{
//-----------------------------------------------------------------
// Prints a presidential quote.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
System.out.println ("Whatever you are, be a good one.");
}
}
O U T P U T
A quote by Abraham Lincoln:
Whatever you are, be a good one.
1.1 The Java Programming Language 5
the Java standard class library. It’s not technically part of the Java language, but is
always available for use in any Java program. We explore the println method in
more detail in Chapter 2.
Comments
Let’s examine comments in more detail. Comments are the only language feature
that allows programmers to compose and communicate their thoughts independ-
ent of the code. Comments should provide insight into the programmer’s original
intent. A program is often used for many years, and often many modifications are
made to it over time. The original programmer often will not remember the de-
tails of a particular program when, at some point in the future, modifications are
required. Furthermore, the original programmer is not always available to make
the changes; thus, someone completely unfamiliar with the program will need to
understand it. Good documentation is therefore essential.
As far as the Java programming language is concerned, the content of com-
ments can be any text whatsoever. Comments are ignored by the computer; they
do not affect how the program executes.
The comments in the Lincoln program represent one of two types of com-
ments allowed in Java. The comments in Lincoln take the following form:
// This is a comment.
This type of comment begins with a double slash (//) and continues to the end
of the line. You cannot have any characters between the two slashes. The com-
puter ignores any text after the double slash to the end of the line. A comment can
follow code on the same line to document that particular line, as in the following
example:
System.out.println ("Monthly Report"); // always use this title
The second form a Java comment may have is the following:
/* This is another comment. */
This comment type does not use the end of a line to indicate the end of the
comment. Anything between the initiating slash-asterisk (/*) and the terminating
asterisk-slash (*/) is part of the comment, including the invisible newline charac-
ter that represents the end of a line. Therefore, this type of comment can extend
over multiple lines. No space can be between the slash and the asterisk.
If there is a second asterisk following the /* at the beginning of a comment, the
content of the comment can be used to automatically generate external documen-
tation about your program by using a tool called javadoc. More information
about javadoc is given in Appendix I.
6 CHAPTER 1 Introduction
The two basic comment types can be used to create various documentation
styles, such as:
// This is a comment on a single line.
//— — — — — — — — — — — — — — — — — — — — — — — — — — — —
// Some comments such as those above methods or classes
// deserve to be blocked off to focus special attention
// on a particular aspect of your code. Note that each of
// these lines is technically a separate comment.
//— — — — — — — — — — — — — — — — — — — — — — — — — — — —
/*
This is one comment
that spans several lines.
*/
Programmers often concentrate so much on writing code that
they focus too little on documentation. You should develop good
commenting practices and follow them habitually. Comments
should be well written, often in complete sentences. They should not
belabor the obvious but should provide appropriate insight into the
intent of the code. The following examples are not good comments:
System.out.println ("hello"); // prints hello
System.out.println ("test"); // change this later
The first comment paraphrases the obvious purpose of the line and does not
add any value to the statement. It is better to have no comment than a useless one.
The second comment is ambiguous. What should be changed later? When is
later? Why should it be changed?
Identifiers and Reserved Words
The various words used when writing programs are called identifiers. The identi-
fiers in the Lincoln program are class, Lincoln, public, static, void, main,
String, args, System, out, and println. These fall into three categories:
■ words that we make up when writing a program (Lincoln and args)
■ words that another programmer chose (String, System, out, println,
and main)
■ words that are reserved for special purposes in the language (class,
public, static, and void)
While writing the program, we simply chose to name the class Lincoln, but we
could have used one of many other possibilities. For example, we could have called
it Quote, or Abe, or GoodOne. The identifier args (which is short for arguments) is
KEY CONCEPT
Inline documentation should provide
insight into your code. It should not
be ambiguous or belabor the obvious.
1.1 The Java Programming Language 7
often used in the way we use it in Lincoln, but we could have used just about any
other identifier in its place.
The identifiers String, System, out, and println were chosen by other pro-
grammers. These words are not part of the Java language. They are part of the
Java standard library of predefined code, a set of classes and methods that some-
one has already written for us. The authors of that code chose the identifiers in
that code—we’re just making use of them.
Reserved words are identifiers that have a special meaning in a programming
language and can only be used in predefined ways. A reserved word cannot be
used for any other purpose, such as naming a class or method. In the Lincoln
program, the reserved words used are class, public, static, and void. Figure 1.1
lists all of the Java reserved words in alphabetical order. The words marked with
an asterisk are reserved for possible future use in later versions of the language but
currently have no meaning in Java.
An identifier that we make up for use in a program can be composed of any
combination of letters, digits, the underscore character (_), and the dollar sign ($),
but it cannot begin with a digit. Identifiers may be of any length. Therefore,
total, label7, nextStockItem, NUM_BOXES, and $amount are all valid identi-
fiers, but 4th_word and coin#value are not valid.
Both uppercase and lowercase letters can be used in an identifier,
and the difference is important. Java is case sensitive, which means
that two identifier names that differ only in the case of their letters
are considered to be different identifiers. Therefore, total, Total,
ToTaL, and TOTAL are all different identifiers. As you can imagine, it
is not a good idea to use multiple identifiers that differ only in their
case, because they can be easily confused.
FIGURE 1.1 Java reserved words
abstract
assert
boolean
break
byte
case
catch
char
class
const*
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto*
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
KEY CONCEPT
Java is case sensitive. The uppercase
and lowercase versions of a letter are
distinct.
8 CHAPTER 1 Introduction
Although the Java language doesn’t require it, using a consistent case format
for each kind of identifier makes your identifiers easier to understand. There
are various Java conventions regarding identifiers that should be followed,
though technically they don’t have to be. For example, we use title case (upper-
case for the first letter of each word) for class names. Throughout the text, we
describe the preferred case style for each type of identifier when it is first en-
countered.
While an identifier can be of any length, you should choose your names care-
fully. They should be descriptive but not verbose. You should avoid meaningless
names such as a or x. An exception to this rule can be made if the short name is ac-
tually descriptive, such as using x and y to represent (x, y) coordinates on a two-di-
mensional grid. Likewise, you should not use unnecessarily long names, such as the
identifier theCurrentItemBeingProcessed. The name currentItem would serve
just as well. As you might imagine, the use of identifiers that are verbose is a much less
prevalent problem than the use of names that are not descriptive.
You should always strive to make your programs as readable as
possible. Therefore, you should always be careful when abbreviating
words. You might think curStVal is a good name to represent the
current stock value, but another person trying to understand the
Identifier
An identifier is a letter followed by zero or more letters and digits.
A Java Letter includes the 26 English alphabetic characters in both
uppercase and lowercase, the $ and _ (underscore) characters, as well
as alphabetic characters from other languages. A Java Digit includes
the digits 0 through 9.
Examples:
total
MAX_HEIGHT
num1
computeWage
System
Java Letter
Java Letter
Java Digit
KEY CONCEPT
Identifier names should be
descriptive and readable.
1.1 The Java Programming Language 9
code may have trouble figuring out what you meant. It might not even be clear to
you two months after writing it.
A name in Java is a series of identifiers separated by the dot (period) character.
The name System.out is the way we designate the object through which we in-
voked the println method. Names appear quite regularly in Java programs.
White Space
All Java programs use white space to separate the words and symbols used in a
program. White space consists of blanks, tabs, and newline characters. The
phrase white space refers to the fact that, on a white sheet of paper with black
printing, the space between the words and symbols is white. The way a program-
mer uses white space is important because it can be used to emphasize parts of the
code and can make a program easier to read.
Except when it’s used to separate words, the computer ignores
white space. It does not affect the execution of a program. This fact
gives programmers a great deal of flexibility in how they format a
program. The lines of a program should be divided in logical places
and certain lines should be indented and aligned so that the pro-
gram’s underlying structure is clear.
Because white space is ignored, we can write a program in many different
ways. For example, taking white space to one extreme, we could put as many
words as possible on each line. The code in Listing 1.2, the Lincoln2 program, is
formatted quite differently from Lincoln but prints the same message.
//********************************************************************
// Lincoln2.java Java Foundations
//
// Demonstrates a poorly formatted, though valid, program.
//********************************************************************
public class Lincoln2{public static void main(String[]args){
System.out.println("A quote by Abraham Lincoln:");
System.out.println("Whatever you are, be a good one.");}}
O U T P U T
A quote by Abraham Lincoln:
Whatever you are, be a good one.
L I S T I N G 1 . 2
KEY CONCEPT
Appropriate use of white space
makes a program easier to read
and understand.
10 CHAPTER 1 Introduction
Taking white space to the other extreme, we could write almost every word
and symbol on a different line with varying amounts of spaces, such as Lincoln3,
shown in Listing 1.3.
All three versions of Lincoln are technically valid and will exe-
cute in the same way, but they are radically different from a reader’s
point of view. Both of the latter examples show poor style and make
the program difficult to understand. You may be asked to adhere to
particular guidelines when you write your programs. A software
//********************************************************************
// Lincoln3.java Java Foundations
//
// Demonstrates another valid program that is poorly formatted.
//********************************************************************
public class
Lincoln3
{
public
static
void
main
(
String
[]
args )
{
System.out.println (
"A quote by Abraham Lincoln:" )
; System.out.println
(
"Whatever you are, be a good one."
)
;
}
}
O U T P U T
A quote by Abraham Lincoln:
Whatever you are, be a good one.
L I S T I N G 1 . 3
KEY CONCEPT
You should adhere to a set of guide-
lines that establishes the way you
format and document your
programs.
1.2 Program Development 11
development company often has a programming style policy that it requires its
programmers to follow. In any case, you should adopt and consistently use a set
of style guidelines that increases the readability of your code.
1.2 Program Development
The process of getting a program running involves various activities. The pro-
gram has to be written in the appropriate programming language, such as Java.
That program has to be translated into a form that the computer can execute.
Errors can occur at various stages of this process and must be fixed. Various soft-
ware tools can be used to help with all parts of the development process as well.
Let’s explore these issues in more detail.
Programming Language Levels
Suppose a particular person is giving travel directions to a friend. That person might
explain those directions in any one of several languages, such as English, Russian, or
Italian. The directions are the same no matter which language is used to explain
them, but the manner in which the directions are expressed is different. The friend
must be able to understand the language being used in order to follow the directions.
Similarly, a problem can be solved by writing a program in one of many pro-
gramming languages, such as Java, Ada, C, C++, C#, Pascal, and Smalltalk. The
purpose of the program is essentially the same no matter which language is used,
but the particular statements used to express the instructions, and the overall or-
ganization of those instructions, vary with each language. A computer must be
able to understand the instructions in order to carry them out.
Programming languages can be categorized into the following four groups.
These groups basically reflect the historical development of computer languages.
■ machine language
■ assembly language
■ high-level languages
■ fourth-generation languages
In order for a program to run on a computer, it must be expressed in that com-
puter’s machine language. Each type of CPU has its own language. For that reason,
we can’t run a program specifically written for a Sun Workstation, with its Sparc
processor, on a Dell PC, with its Intel processor.
Each machine language instruction can accomplish only a simple task. For exam-
ple, a single machine language instruction might copy a value into a register or com-
pare a value to zero. It might take four separate machine language instructions to add
12 CHAPTER 1 Introduction
two numbers together and to store the result. However, a computer can
do millions of these instructions in a second, and therefore many simple
commands can be executed quickly to accomplish complex tasks.
Machine language code is expressed as a series of binary digits
and is extremely difficult for humans to read and write. Originally,
programs were entered into the computer by using switches or some
similarly tedious method. Early programmers found these techniques to be time
consuming and error prone.
These problems gave rise to the use of assembly language, which replaced bi-
nary digits with mnemonics, short English-like words that represent commands
or data. It is much easier for programmers to deal with words than with binary
digits. However, an assembly language program cannot be executed directly on a
computer. It must first be translated into machine language.
Generally, each assembly language instruction corresponds to an equivalent
machine language instruction. Therefore, similar to machine language, each as-
sembly language instruction accomplishes only a simple operation. Although as-
sembly language is an improvement over machine code from a programmer’s per-
spective, it is still tedious to use. Both assembly language and machine language
are considered low-level languages.
Today, most programmers use a high-level language to write software. A high-level
language is expressed in English-like phrases, and thus is easier for programmers to
read and write. A single high-level language programming statement
can accomplish the equivalent of many—perhaps hundreds—of ma-
chine language instructions. The term high-level refers to the fact that
the programming statements are expressed in a way that is far removed
from the machine language that is ultimately executed. Java is a high-
level language, as are Ada, C++, Smalltalk, and many others.
Figure 1.2 shows equivalent expressions in a high-level language, assembly lan-
guage, and machine language. The expressions add two numbers together. The as-
sembly language and machine language in this example are specific to a Sparc
processor.
The high-level language expression in Figure 1.2 is readable and intuitive for
programmers. It is similar to an algebraic expression. The equivalent assembly
language code is somewhat readable, but it is more verbose and less intuitive. The
machine language is basically unreadable and much longer. In fact, only a small
portion of the binary machine code to add two numbers together is shown in
Figure 1.2. The complete machine language code for this particular expression is
over 400 bits long.
A high-level language insulates programmers from needing to know the un-
derlying machine language for the processor on which they are working. But
KEY CONCEPT
High-level languages allow a pro-
grammer to ignore the underlying
details of machine language.
KEY CONCEPT
All programs must be translated to a
particular CPU’s machine language in
order to be executed.
1.2 Program Development 13
high-level language code must be translated into machine language in order to
be executed.
Some programming languages are considered to operate at an even higher level
than high-level languages. They might include special facilities for automatic report
generation or interaction with a database. These languages are called fourth-generation
languages, or simply 4GLs, because they followed the first three generations of
computer programming: machine, assembly, and high-level.
Editors, Compilers, and Interpreters
Several special-purpose programs are needed to help with the process of develop-
ing new programs. They are sometimes called software tools because they are
used to build programs. Examples of basic software tools include an editor, a
compiler, and an interpreter.
Initially, you use an editor as you type a program into a computer and store it
in a file. There are many different editors with many different features. You
should become familiar with the editor you will use regularly because it can dra-
matically affect the speed at which you enter and modify your programs.
Figure 1.3 on the next page shows a very basic view of the program development
process. After editing and saving your program, you attempt to translate it from
high-level code into a form that can be executed. That translation may result in er-
rors, in which case you return to the editor to make changes to the code to fix the
problems. Once the translation occurs successfully, you can execute the program
and evaluate the results. If the results are not what you want, or if you want to en-
hance your existing program, you again return to the editor to make changes.
The translation of source code into (ultimately) machine language for a partic-
ular type of CPU can occur in a variety of ways. A compiler is a program that
FIGURE 1.2 A high-level expression and its assembly language
and machine language equivalent
High-Level Language Assembly Language Machine Language
<a + b> 1d [%fp–20], %o0
1d [%fp–24], %o1
add %o0, %o1, %o0
...
1101 0000 0000 0111
1011 1111 1110 1000
1101 0010 0000 0111
1011 1111 1110 1000
1001 0000 0000 0000
...
14 CHAPTER 1 Introduction
translates code in one language to equivalent code in another language. The orig-
inal code is called source code, and the language into which it is translated is
called the target language. For many traditional compilers, the source code is
translated directly into a particular machine language. In that case, the translation
process occurs once (for a given version of the program), and the resulting exe-
cutable program can be run whenever needed.
An interpreter is similar to a compiler but has an important difference. An in-
terpreter interweaves the translation and execution activities. A small part of the
source code, such as one statement, is translated and executed. Then another
statement is translated and executed, and so on. One advantage of this technique
is that it eliminates the need for a separate compilation phase. However, the pro-
gram generally runs more slowly because the translation process occurs during
each execution.
The process generally used to translate and execute Java programs combines
the use of a compiler and an interpreter. This process is pictured in Figure 1.4.
The Java compiler translates Java source code into Java bytecode,
which is a representation of the program in a low-level form similar
to machine language code. The Java interpreter reads Java bytecode
and executes it on a specific machine. Another compiler could trans-
late the bytecode into a particular machine language for efficient ex-
ecution on that machine.
The difference between Java bytecode and true machine language
code is that Java bytecode is not tied to any particular processor type. This ap-
proach has the distinct advantage of making Java architecture neutral, and there-
fore easily portable from one machine type to another. The only restriction is that
there must be a Java interpreter or a bytecode compiler for each processor type on
which the Java bytecode is to be executed.
Since the compilation process translates the high-level Java source code into a
low-level representation, the interpretation process is more efficient than interpret-
ing high-level code directly. Executing a program by interpreting its bytecode is still
slower than executing machine code directly, but it is fast enough for most applica-
tions. Note that for efficiency, Java bytecode could be compiled into machine code.
Edit and
save program
Translate program
into executable form
errors errors
Execute program and
evaluate results
FIGURE 1.3 Editing and running a program
KEY CONCEPT
A Java compiler translates Java
source code into Java bytecode, a
low-level, architecture-neutral repre-
sentation of the program.
1.2 Program Development 15
Development Environments
A software development environment is the set of tools used to create, test, and
modify a program. Some development environments are available for free while
others, which may have advanced features, must be purchased. Some environ-
ments are referred to as integrated development environments (IDEs) because
they integrate various tools into one software program.
Any development environment will contain certain key tools, such as a Java
compiler and interpreter. Some will include a debugger, which helps you find er-
rors in a program. Other tools that may be included are documentation genera-
tors, archiving tools, and tools that help you visualize your program structure.
Sun Microsystems, the creator of the Java programming language, provides the
Java Software Development Kit (SDK), which is sometimes referred to simply as
the Java Development Kit (JDK). The SDK can be downloaded free of charge for
various hardware platforms from Sun’s Java Web site, java.sun.com, and is also
included on the CD that accompanies this book.
The SDK tools are not an integrated environment. The commands for compila-
tion and interpretation are executed on the command line. That is, the SDK does
not have a graphical user interface (GUI), with windows, menus, buttons, etc. It
also does not include an editor, although any editor that can save a document as
simple text can be used.
Sun also has a Java IDE called NetBeans (www.netbeans.org) that incorporates
the development tools of the SDK into one convenient GUI-based program. IBM
Java source
code
Java
bytecode
Java compiler
Java
interpreter
Bytecode
compiler
Machine
code
FIGURE 1.4 The Java translation and execution process
16 CHAPTER 1 Introduction
promotes a similar IDE called Eclipse (www.eclipse.org). Both
NetBeans and Eclipse are open source projects, meaning that they
are developed by a wide collection of programmers and are avail-
able for free.
A research group at Auburn University has developed jGRASP, a
free Java IDE that is included on the CD that accompanies this
book. It can also be downloaded from www.jgrasp.org. In addition to fundamen-
tal development tools, jGRASP contains tools that graphically display program
elements.
Various other Java development environments are available, and several are
provided on this book’s CD. The choice of which development environment to
use is important. The more you know about the capabilities of your environment,
the more productive you can be during program development.
Syntax and Semantics
Each programming language has its own unique syntax. The syntax rules of a lan-
guage dictate exactly how the vocabulary elements of the language can be com-
bined to form statements. These rules must be followed in order to create a pro-
gram. We’ve already discussed several Java syntax rules. For instance, the fact
that an identifier cannot begin with a digit is a syntax rule. The fact that braces
are used to begin and end classes and methods is also a syntax rule. Appendix J
formally defines the basic syntax rules for the Java programming language, and
specific rules are highlighted throughout the text.
During compilation, all syntax rules are checked. If a program is not syntacti-
cally correct, the compiler will issue error messages and will not produce byte-
code. Java has a similar syntax to the programming languages C and C++, and
therefore the look and feel of the code is familiar to people with a background in
those languages.
The semantics of a statement in a programming language define what will hap-
pen when that statement is executed. Programming languages are generally un-
ambiguous, which means the semantics of a program are well defined. That is,
there is one and only one interpretation for each statement. On the other hand,
the natural languages that humans use to communicate, such as English and
Italian, are full of ambiguities. A sentence can often have two or more different
meanings. For example, consider the following sentence:
Time flies like an arrow.
The average human is likely to interpret this sentence as a general observation:
that time moves quickly in the same way that an arrow moves quickly. However,
if we interpret the word time as a verb (as in “run the 50-yard dash and I’ll time
KEY CONCEPT
Many different development environ-
ments exist to help you create and
modify Java programs.
1.2 Program Development 17
you”) and the word flies as a noun (the plural of fly), the interpreta-
tion changes completely. We know that arrows don’t time things, so
we wouldn’t normally interpret the sentence that way, but it is a
valid interpretation of the words in the sentence. A computer would
have a difficult time trying to determine which meaning is intended.
Moreover, this sentence could describe the preferences of an unusual
insect known as a “time fly,” which might be found near an archery range. After
all, fruit flies like a banana.
The point is that one specific English sentence can have multiple valid mean-
ings. A computer language cannot allow such ambiguities to exist. If a program-
ming language instruction could have two different meanings, a computer would
not be able to determine which one should be carried out.
Errors
Several different kinds of problems can occur in software, particularly during pro-
gram development. The term computer error is often misused and varies in meaning
depending on the situation. From a user’s point of view, anything that goes awry
when interacting with a machine can be called a computer error. For example, sup-
pose you charged a $23 item to your credit card, but when you received the bill, the
item was listed at $230. After you have the problem fixed, the credit card company
apologizes for the “computer error.” Did the computer arbitrarily add a zero to the
end of the number, or did it perhaps multiply the value by 10? Of
course not. A computer follows the commands we give it and operates
on the data we provide. If our programs are wrong or our data inac-
curate, then we cannot expect the results to be correct. A common
phrase used to describe this situation is “garbage in, garbage out.”
You will encounter three kinds of errors as you develop programs:
■ compile-time error
■ run-time error
■ logical error
The compiler checks to make sure you are using the correct syntax. If you
have any statements that do not conform to the syntactic rules of the language,
the compiler will produce a syntax error. The compiler also tries to find other
problems, such as the use of incompatible types of data. The syn-
tax might be technically correct, but you may be attempting to do
something that the language doesn’t semantically allow. Any er-
ror identified by the compiler is called a compile-time error. If a
compile-time error occurs, an executable version of the program
is not created.
KEY CONCEPT
Syntax rules dictate the form of a
program. Semantics dictate the
meaning of the program statements.
KEY CONCEPT
A Java program must be syntactically
correct or the compiler will not
produce bytecode.
KEY CONCEPT
The programmer is responsible for the
accuracy and reliability of a program.
18 CHAPTER 1 Introduction
The second kind of problem occurs during program execution. It is called a
run-time error and causes the program to terminate abnormally. For example, if
we attempt to divide by zero, the program will “crash” and halt execution at that
point. Because the requested operation is undefined, the system simply abandons
its attempt to continue processing your program. The best programs are robust;
that is, they avoid as many run-time errors as possible. For example, the program
code could guard against the possibility of dividing by zero and handle the situa-
tion appropriately if it arises. In Java, many run-time problems are called
exceptions that can be caught and dealt with accordingly.
The third kind of software problem is a logical error. In this case, the software
compiles and executes without complaint, but it produces incorrect results. For
example, a logical error occurs when a value is calculated incorrectly or when a
graphical button does not appear in the correct place. A programmer must test
the program thoroughly, comparing the expected results to those that actually oc-
cur. When defects are found, they must be traced back to the source of the prob-
lem in the code and corrected. The process of finding and correcting defects in a
program is called debugging. Logical errors can manifest themselves in many
ways, and the actual root cause might be difficult to discover.
1.3 Problem Solving
Creating software involves much more than just writing code. The mechanics of
editing and running a program are necessary steps, but the heart of software de-
velopment is problem solving. We write a program to solve a particular problem.
In general, problem solving consists of multiple steps:
1. Understanding the problem.
2. Designing a solution.
3. Considering alternatives to the solution and refining the solution.
4. Implementing the solution.
5. Testing the solution and fixing any problems that exist.
Although this approach applies to any kind of problem solving, it works particu-
larly well when developing software. These steps aren’t purely linear. That is,
some of the activities will overlap others. But at some point, all of these steps
should be carefully addressed.
The first step, understanding the problem, may sound obvious, but a lack of
attention to this step has been the cause of many misguided software development
efforts. If we attempt to solve a problem we don’t completely understand, we often
end up solving the wrong problem or at least going off on improper tangents.
1.4 Software Development Activities 19
Each problem has a problem domain, the real-world issues that are key to our so-
lution. For example, if we are going to write a program to score a bowling match,
then the problem domain includes the rules of bowling. To develop a good solu-
tion, we must thoroughly understand the problem domain.
The key to designing a problem solution is breaking it down into
manageable pieces. A solution to any problem can rarely be ex-
pressed as one big task. Instead, it is a series of small cooperating
tasks that interact to perform a larger task. When developing soft-
ware, we don’t write one big program. We design separate pieces
that are responsible for certain parts of the solution, and then we in-
tegrate them with the other parts.
Our first inclination toward a solution may not be the best one. We must al-
ways consider alternatives and refine the solution as necessary. The earlier we
consider alternatives, the easier it is to modify our approach.
Implementing the solution is the act of taking the design and putting it in a us-
able form. When developing a software solution to a problem, the implementa-
tion stage is the process of actually writing the program. Too often programming
is thought of as writing code. But in most cases, the act of designing the program
should be far more interesting and creative than the process of implementing the
design in a particular programming language.
At many points in the development process, we should test our solution to find
any errors that exist so that we can fix them. Testing cannot guarantee that there
aren’t still problems yet to be discovered, but it can raise our confidence that we
have a viable solution.
Throughout this text we explore techniques that allow us to design and imple-
ment elegant programs. Although we will often get immersed in these details, we
should never forget that our primary goal is to solve problems.
1.4 Software Development Activities
Given that the goal of software development is to solve problems, it shouldn’t sur-
prise you that the activities involved in the software development process mirror the
general problem solving steps we discussed in the previous section. In particular, any
proper software development effort consists of four basic development activities:
■ Establishing the requirements.
■ Creating a design.
■ Implementing the design.
■ Testing.
KEY CONCEPT
Problem solving involves breaking
a solution down into manageable
pieces.
20 CHAPTER 1 Introduction
It would be nice if these activities, in this order, defined a step-by-step ap-
proach for developing software. However, although they may seem to be sequen-
tial, they are almost never completely linear in reality. They overlap and interact.
Let’s discuss each development activity briefly.
Software requirements specify what a program must accomplish. They indicate
the tasks that a program should perform, not how it performs them. Often, re-
quirements are expressed in a document called a functional specification.
Requirements are a clear expression of the problem to be solved. Until we truly
know what problem we are trying to solve, we can’t actually solve it.
In a classroom setting, students are generally provided the software require-
ments in the form of the problem assignment. However, even when they are
provided, such requirements need to be discussed and clarified. In professional
development, the person or group who wants a software product developed (the
client) will often provide an initial set of requirements. However, these initial re-
quirements are often incomplete, ambiguous, and perhaps even contradictory.
The software developer must work with the client to refine the requirements un-
til all key decisions about what the system will do have been addressed.
Requirements often address user interface issues such as output format, screen
layouts, and graphical interface components. Essentially, the requirements establish
the characteristics that make the program useful for the end user. They may also ap-
ply constraints to your program, such as how fast a task must be performed.
A software design indicates how a program will accomplish its requirements.
The design specifies the classes and objects needed in a program and defines
how they interact. It also specifies the relationships among the classes. Low-
level design issues deal with how individual methods accomplish their tasks.
A civil engineer would never consider building a bridge without designing it
first. The design of software is no less essential. Many problems that occur in
software are directly attributable to a lack of good design effort. It has been
shown time and again that the effort spent on the design of a program is well
worth it, saving both time and money in the long run.
During software design, alternatives need to be considered and
explored. Often, the first attempt at a design is not the best solution.
Fortunately, changes are relatively easy to make during the design
stage.
Implementation is the process of writing the source code that will
solve the problem. More precisely, implementation is the act of translating the de-
sign into a particular programming language. Too many programmers focus on
implementation exclusively when actually it should be the least creative of all de-
velopment activities. The important decisions should be made when establishing
the requirements and creating the design.
KEY CONCEPT
The effort put into design is both
crucial and cost-effective.
1.5 Object-Oriented Programming 21
Testing is the act of ensuring that a program will solve the intended problem
given all of the constraints under which it must perform. Testing includes running
a program multiple times with various inputs and carefully scrutinizing the re-
sults. But it means far more than that. Testing in one form or another should be a
part of every stage of development. The accuracy of the requirements, for in-
stance, should be tested by reviewing them with the client. We revisit the issues re-
lated to testing in Chapter 11.
1.5 Object-Oriented Programming
As we stated earlier in this chapter, Java is an object-oriented language. As the
name implies, an object is a fundamental entity in a Java program. This book is
focused on the idea of developing software by defining objects that interact with
each other.
The principles of object-oriented software development have been around for
many years, essentially as long as high-level programming languages have been
used. The programming language Simula, developed in the 1960s, had many char-
acteristics that define the modern object-oriented approach to software develop-
ment. In the 1980s and 1990s, object-oriented programming became wildly popu-
lar, due in large part to the development of programming languages like C++ and
Java. It is now the dominant approach used in commercial software development.
One of the most attractive characteristics of the object-oriented approach is the
fact that objects can be used quite effectively to represent real-world entities. We
can use a software object to represent an employee in a company, for instance.
We’d create one object per employee, each with behaviors and characteristics that
we need to represent. In this way, object-oriented programming allows us to map
our programs to the real situations that the programs represent. That is, the object-
oriented approach makes it easier to solve problems, which is the point of writing
a program in the first place.
Let’s explore the specific characteristics of the object-oriented approach that
help us solve those problems.
Object-Oriented Software Principles
Object-oriented programming ultimately requires a solid understanding of the
following terms:
■ object
■ attribute
■ method
Other documents randomly have
different content
"It is kind of you to sympathise with me," I said. "I am going to
speak to Jane Mullins to-morrow. If possible Mr. Fanning must go."
"But there is another thing," began Mrs. Furlong. She paused, and I
saw that she was about to say something, even more disagreeable
than anything she had yet uttered.
"You have your mother, of course," she continued slowly, "but you
yourself are very young, and—now I don't want to compliment you—
but you are much nicer looking than many girls; you have quite a
different air and appearance from any other girl in this house. Oh, I
hate interfering, but your mother, Miss Wickham, must be a
particularly innocent woman."
"What do you mean?" I asked.
"I mean Mr. Randolph," she answered, and she raised her eyes and
fixed them on my face.
"Mr. Randolph?" I said. "Surely you must admit that he at least is a
gentleman?"
"He is not only a gentleman, but he is more highly born and has
more money than any one else in the house; he does not belong to
the set who fill this house at all. Why does he come? This is no place
for him. In one way it is quite as unsuitable to have him here as it is
to have a man like Mr. Fanning here. Those two men represent
opposite extremes. People will talk."
"What about?" I asked.
"About you, dear."
"They cannot. I will not permit it." Then I said abruptly, standing up
in my excitement, "After all, I don't care whether they talk or not; I
was prepared for misunderstandings when I came here. Mother likes
Mr. Randolph; he at least shall stay."
"But, my child, it is not nice to be talked about; it is never nice for a
young girl. People like my husband and myself quite understand. We
know well that you and your mother are at present out of your right
position, but others will not be so considerate. Mr. Randolph is
always here."
"You think," I said, stammering, "that he comes because——"
She smiled, got up and kissed me.
"What else could he come for, Westenra?" she said softly.
"He comes because—because of mother," I answered. "He likes her;
he told me so. He is anxious about her, for he thinks she misses her
old life very much; he wants to make things easier for her. He is a
very good man, and I respect him. I don't mind what any one says, I
know in my heart he comes here because——"
"No, you do not," said Mrs. Furlong, and she looked me full in the
eyes, and I found myself colouring and stammering.
"Believe me I have not intruded upon you this evening without
cause," said the little woman. "I talked the matter over with my
husband. I would rather Mr. Fanning were here than Mr. Randolph.
Mr. Fanning is impossible, Mr. Randolph is not. He does not come
here on account of your mother, he comes here because he likes
you. I am very sorry; I felt I must speak; my husband agrees with
me."
"Do not say another word now," I said. "I am sure you mean all this
kindly, but please do not say any more now. I will think over what
you have said."
"I will leave you then, dear," she said.
She went as far as the door; she was a very kindly little woman, she
was a real lady, and she meant well, but she had hurt me so
indescribably that at that moment I almost hated her. When she
reached the door she turned and said—
"If ever my husband and I can help you, Miss Wickham (but we are
poor people), if ever we can help you, we will be glad to do so. I
know you are angry with me now, but your anger won't remain, you
will see who are your true friends by-and-by."
She closed the door softly, and I heard her gentle steps going
downstairs. I will frankly say that I did not go to bed for some time,
that I paced indignantly up and down my room. I hated Jane, I
hated Mr. Fanning, I still more cordially hated Mr. Randolph at that
moment. Mr. Fanning must go, Mr. Randolph must go. I could not
allow myself to be spoken about. How intolerable of Mr. Randolph to
have come as he had done, to have forced himself upon us, to have
invited us to go out with him, to have——and then I stopped, and a
great lump rose in my throat, and I burst into tears, for in my heart
of hearts I knew well that I did not think what he did intolerable at
all, that I respected him, and—but I did not dare to allow my
thoughts to go any further.
I even hated myself for being good-looking, until I suddenly
remembered that I had the same features as my father had. He had
conquered in all the battles in which he had borne part through his
life. My face must be a good one if it was like his. I would try to live
up to the character which my face seemed to express, and I would
immediately endeavour to get things on a different footing.
Accordingly, the next day at breakfast I studiously avoided Mr.
Randolph, and I equally studiously avoided Mr. Fanning. The
consequence was that, being as it were between two fires, I had a
most uncomfortable time, for Mr. Randolph showed me by certain
glances which he threw in my direction that he was most anxious to
consult me about something, and Mr. Fanning seemed to intercept
these glances, and to make his own most unpleasant comments
about them; and if Mr. Fanning intercepted them, so did Mrs. and
Miss Armstrong.
Miss Armstrong had now given up Mr. Randolph as almost hopeless
with regard to a flirtation, and was turning her attention in the
direction of Mr. Fanning. She talked Art at Mr. Fanning assiduously all
during breakfast, and having learned by some accident that he was
a publisher, boldly demanded from him if he would not like her to
illustrate some of his books. In reply to this he gave a profound bow,
and told her, with a certain awkward jerk of his body, that he never
gave orders in advance, that he never gave orders on the score of
friendliness, that when it came to the relations between publisher
and artist he was brutal.
"That's the word for it, Miss Armstrong," he said, "I am brutal when
it comes to a bargain. I try to make the very best I can for myself. I
never think of the artist at all. I want all the ÂŁ s d to go into my own
pocket"—and here he slapped his waistcoat loudly, and uttered a
harsh laugh, which showed all his broken teeth in a most
disagreeable manner. Miss Armstrong and her mother seemed to
think he was excellent fun, and Mrs. Armstrong said, with a quick
glance first at Mr. Randolph and then at me, that it was refreshing to
hear any man so frank, and that for her part she respected people
who gave themselves no h'airs.
Breakfast came to an end, and I sought Jane in her sanctum.
"Now, Jane," I said, "you must put away your accounts, you must
cease to think of housekeeping. You must listen to me."
"What is it, Westenra?" she said. "Has anything vexed you?" she
continued; "sit down and tell me all about it."
"Several things vex me," I answered. "Jane, we must come to an
understanding."
"What about?" she asked in some alarm; "an understanding! I
thought that was all arranged when our legal agreement was drawn
up."
"Oh, I know nothing about lawyers nor about legal agreements," I
answered; "but, Jane, there are some things I cannot put up with,
and one of them is——"
"I know," she answered; "Mr. Fanning."
"He is horrible, hateful; he is going to make himself most hateful to
me. Jane, dear Jane, he must go."
Jane looked puzzled and distressed. I expected her to say—
"He shall certainly go, my dear, I will tell him that his room is
required, and that he must leave at the end of the week." But on the
contrary she sighed. After a long pause she said—
"You want this house to be a success, I presume."
"I certainly do, but we cannot have it a success on the present
arrangement. Mr. Fanning must go, and also Mr. Randolph."
"Mr. Randolph, Mr. James Randolph!" said Jane, now colouring high,
and a sparkle of something, which seemed to be a curious mixture
of fear and indignation, filling her eyes. "And why should he go? You
do not know what you are talking about."
"I do. He must go. Ask—ask Mrs. Furlong. They talk about him here,
these hateful people; they put false constructions on his kindness; I
know he is kind and he is a gentleman, but he does me harm, Jane,
even as much harm as that horrible Mr. Fanning."
"Now, look here, Westenra Wickham," said Jane Mullins. "Are you
going to throw up the sponge, or are you not?"
"Throw up the sponge! I certainly don't mean to fail."
"You will do so if you send those two men out of the house. If you
cannot hold your own, whatever men come here, you are not the
girl I took you for. As to Mr. Randolph, be quite assured that he will
never do anything to annoy you. If people talk let them talk. When
they see nothing comes of their idle silly gossip, they will soon cease
to utter it. And as to Mr. Fanning, they will equally cease to worry
about him. If he pays he must stay, for as it is, it is difficult to let the
first-floor rooms. People don't want to pay five guineas a week to
live in Bloomsbury, and he has a small room; and it is a great relief
to me that he should be here and pay so good a sum for his room.
The thing must be met commercially, or I for one give it up."
"You, Jane, you! then indeed we shall be ruined."
"I don't really mean to, my dear child, I don't mean for a single
moment to desert you; but I must say that if 17 Graham Square is to
go on, it must go on commercial principles; and we cannot send our
best boarders away. You ask me coolly, just because things are a
little uncomfortable for you, you ask me to dismiss ten guineas a
week, for Mr. Randolph pays five guineas for his room, and Mr.
Fanning five guineas for his, and I don't know any other gentleman
who would pay an equal sum, and we must have it to balance
matters. What is to meet the rent, my dear? What is to meet the
taxes? What is to meet the butcher's, the baker's, the grocer's, the
fishmonger's bills if we dismissed our tenants. I often have a terrible
fear that we were rash to take a great expensive house like this, and
unless it is full from attic to drawing-room floor, we have not the
slightest chance of meeting our expenses. Even then I fear!—but
there I won't croak before the time; only, Westenra, you have to
make up your mind. You can go away on a visit if you wish to, I do
not counsel this for a moment, for I know you are a great attraction
here. It is because you are pretty and wear nice dresses, and look
different from the other boarders, that you attract them; and—yes, I
will say it—Mr. Randolph also attracts them. They can get no small
change out of Mr. James Randolph, so they need not try it on, but
once for all we cannot decline the people who are willing to pay us
good money, that is a foregone conclusion. Now you have got to
accept the agreeables with the disagreeables, or this whole great
scheme of yours will tumble about our heads like a pack of cards."
CHAPTER XIII
THE UGLY DRESS
On that very day I searched through mother's wardrobe and found a
piece of brown barége. It was a harsh and by no means pretty
material. I held it up to the light, and asked her what she was going
to do with it.
"Nothing," she answered, "I bought it ten years ago at a sale of
remnants, and why it has stuck to me all these years is more than I
can tell."
"May I have it?" was my next query.
"Certainly," replied mother, "but you surely are not going to have a
dress made of that ugly thing?"
"May I have it?" I asked again.
"Yes, dear, yes."
I did not say any more with regard to the barége. I turned the
conversation to indifferent matters, but when I left the room I took it
with me. I made it into a parcel and took it out. I went to a little
dressmaker in a street near by. I asked her if she would make the
ugly brown barége into an evening dress. She measured the
material, and said it was somewhat scanty.
"That does not matter," I said, "I want an ugly dress—can you
manage to make a really ugly dress for me out of it?"
"Well, Miss Wickham," she replied, fixing her pale brown eyes on my
face, "I never do go in for making ugly dresses, it would be against
my profession. You don't mean it, do you, Miss Wickham?"
"Put your best work into it," I said, suddenly changing my tone.
"Make it according to your own ideas of the fashion. Picture a young
girl going to a play, or a ball, in that dress, and make it according to
your own ideas."
"May I trim it with golden yellow chiffon and turquoise blue silk
bows?" she asked eagerly, her eyes shining.
"You may," I replied, suppressing an internal shudder. I gave her a
few further directions; she named a day when I should come to be
fitted, and I went home.
In less than a week's time the brown barége arrived back, ready for
me to wear. It was made according to Annie Starr's ideas of a
fashionable evening gown. It was the sort of garment which would
have sent the Duchess or Lady Thesiger into fits on the spot. In the
first place, the bodice was full of wrinkles, it was too wide in the
waist, and too narrow across the chest, but this was a small matter
to complain of. It was the irritating air of vulgarity all over the dress
which was so hard to bear. But, notwithstanding all these defects, it
pleased me. It would, I hoped, answer my purpose, and succeed in
making me appear very unattractive in the eyes of Mr. Randolph.
That evening I put on the brown barége for dinner. The yellow
chiffon and the turquoise blue bows were much in evidence, and I
did really feel that I was a martyr when I went downstairs in that
dress with its outré trimmings.
When I entered the drawing-room, mother glanced up at me as if
she did not know me; she then started, the colour came into her
face, and she motioned me imperatively to her side.
"Go upstairs at once and take that off," she said.
"Oh no, mother," I answered, "there is no time now, besides I—I
chose it, I admire it."
"Take it off immediately, Westenra."
"But it is your dear barége that you have kept for ten years," I said,
trying to be playful; "I must wear it, at least to-night."
I knew that I had never looked worse, and I quite gloried in the fact.
I saw Mr. Randolph from his seat near mother glance at me several
times in a puzzled way, and Mr. Fanning, after one or two astonished
glances, during which he took in the tout ensemble of the ugly robe,
began to enter into a playful bear-like flirtation with Miss Armstrong.
Dear brown barége, what service it was doing me! I secretly
determined that it should be my dinner dress every evening until it
wore itself to rags. When the turquoise blue bows became too
shabby, I might substitute them for magenta ones. I felt that I had
suddenly found an opening out of my difficulty. If I ceased to appear
attractive, Mr. Randolph and Mr. Fanning would cease to worry me,
the rest of the boarders would accept me for what I was, and my
Gordian knot would be cut. Little did I guess! It was by no means so
easy to carry out my fixed determination as I had hoped. In the first
place, poor darling mother nearly fretted herself into an illness on
account of my evening dress. She absolutely cried when she saw me
in it, and said that if I was determined to deteriorate in that way, she
would give up the boarding-house and go to the cottage in the
country without a moment's hesitation. After wearing the dress for
three or four days I was forced, very much against my will, to put on
one of my pretty black dresses, and the barége made by Annie Starr
resumed its place in my wardrobe. I determined to wear it now and
then, however—it had already done me good service. I began to
hope that neither Mr. Randolph nor Mr. Fanning thought me worth
looking at when I appeared in it.
On this evening, as I was dressing for dinner, I heard a wonderful
bumping going on in the stairs. It was the noise made by very heavy
trunks, trunks so large that they seemed scarcely able to be brought
upstairs. They were arriving at the attics, too—they were entering
the attic next to mine. Now that special attic had up to the present
remained untenanted. It was the most disagreeable room in the
house. Most of the attics were quite excellent, but this room had a
decidedly sloping roof, and rather small windows, and the paper on
the walls was ugly, and the accommodation scanty, and what those
huge boxes were going to do there was more than I could tell. The
boxes, however, entered that special attic, and then a bodily
presence followed them briskly, a loud hearty voice was heard to
speak. It said in cheerful tones—
"Thank you, that will do nicely. A large can of hot water, please, and
a couple more candles. Thanks. What hour did you say the company
dined?"
The reply was made in a low tone which I could not catch, and the
attic door was shut.
I was down in the drawing-room in my black dress—(how
comfortable I felt in it, how hateful that brown barége was, after all)
—when the door was opened, and a large, stoutly-made woman,
most richly dressed, came in. She had a quantity of grizzly grey hair,
which was turned back from her expansive forehead; a cap of
almost every colour in the rainbow bedizened her head, she wore
diamond pendants in her ears, and had a flashing diamond brooch
fastening the front of her dress. Her complexion was high, she had a
broad mouth and a constant smile. She walked straight up to Jane
Mullins.
"Well," she said, "here I am. I have not unpacked my big trunk, as
your servant said there was very little time before dinner. Please can
you tell me when Albert will be in?"
"Mr. Fanning generally comes home about now," I heard Jane say.
"Mrs. Fanning, may I introduce you to my dear young friend, Miss
Wickham—Mrs. Wickham has not yet appeared."
To my horror I saw Miss Mullins advancing across the drawing-room,
accompanied by the stout woman; they approached to my side.
"May I introduce Mrs. Fanning," said Miss Mullins—"Mr. Fanning's
mother."
"The mother of dear, godly Albert," said the stout lady. "I am proud
to say I am the mother of one of the best of sons. I am right
pleased to meet you, Miss Wickham. I may as well say at once that
Albert Fanning, my dear and only son, has mentioned your name to
me, and with an approval which would make your young cheeks
blush. Yes, I am the last person to encourage vanity in the young,
but I must repeat that if you knew all that Albert has said, you
would feel that flutter of the heart which only joy brings forth. Now,
shall we both sit in a cosy corner and enjoy ourselves, and talk
about Albert until dinner is ready?"
This treat was certainly not likely to cause my young cheeks to
blush. On the contrary, I felt myself turning pale, and I looked round
with a desperate intention of flying to Jane for protection, when the
stout lady took one of my hands.
"Ah," she said, "quite up to date, a slim young hand, and a slim
young figure, and a slim young face, too, for that matter. All that
Albert says is true, you are a very nice-looking girl. I should not say
that you had much durance in you, that remains to be proved. But
come, here's a cosy corner, I have a great deal to say."
That hand of Mrs. Fanning's had a wonderfully clinging effect; it
seemed to encircle my fingers something like an octopus, and she
pulled me gently towards the corner she had in view, and presently
had pinned me there, seating herself well in front of me, so that
there was no possible escape.
The rest of the boarders now entered the drawing-room. Mother
amongst others made her appearance; she went to her accustomed
corner, glanced at me, saw that I was in one of my black dresses,
nodded approval, concluding in her dear mind that I had probably
met some old friend in the extraordinary person who was shutting
me into the corner, and took no further notice.
Captain and Mrs. Furlong were well pleased to see that I was only
talking to a woman, it did not matter at all to them who that woman
was. And as to me I sat perfectly silent while Mrs. Fanning
discoursed on Albert. She never for a single moment, I will say for
her, turned the conversation into another channel. Albert was her
theme, and she stuck to him with the pertinacity which would have
done any leader of a debate credit. The debate was Albert. She
intended before dinner was announced to give me a true insight into
that remarkable man's most remarkable character.
"Yes," she said, "what Albert thinks is always to the point. Since a
child he never gave me what you would call a real heartache.
Determined, self-willed he is; you look, the next time you see him, at
his chin, you observe the cleft in the middle; there never was a chin
like that yet without a mind according—a mind, so to speak, set on
the duty ahead of it—a mind that is determined to conquer. That is
Albert, that is my only, godly son. You observe, when you have an
opportunity, Albert's eyes. Did you ever see anything more open
than the way they look at you? He don't mind whether it hurts your
feelings or not; if he wants to look at you, look he will."
When she said this I nodded my head emphatically, for I had found
this most disagreeable trait in Albert's eyes from the first moment I
had been unfortunate enough to make his acquaintance. But Mrs.
Fanning took my nod in high good humour.
"Ah, you have observed it," she said, "and no wonder, no wonder.
Now, when you get an opportunity, do pull him to pieces, feature by
feature; notice his brow, how lofty it is; there's talent there, and
t'aint what you would call a fly-away talent, such as those art talents
that make me quite sick. He has no talent, thank Heaven, for
painting or for poetry, or for any fal-lal of that kind, his talent lies in
a sound business direction. Oh, he has made me roar, the way he
talks of young authors and young artists, how they come to him with
their wares, and how he beats them down. It's in Albert's brow
where his talent for business lies. You mark his nose too, it's
somewhat long and a little pointed, but it's the nose of a man who
will make his mark; yes, he'll make his mark some day, and I have
told him so over and over."
Having gone through all Albert's features, she next proceeded to
describe Albert's character, and then went on to Albert's future. From
this it was an easy step to Albert's wife, and Albert's wife took up a
great deal of the good woman's attention.
"It is because I am thinking he'll soon be falling into the snares of
matrimony that I have come to stay at 17 Graham Square,"
continued Mrs. Fanning. "And it's because I want my dear and godly
son to get a wife who will be on the pattern of Solomon's virtuous
woman that I have given up my home and broken up my
establishment and come here. Now, Miss Wickham, my dear young
lady, did you or did you not hear the noise of my boxes being
brought upstairs?"
"I certainly did," I replied.
"Then you happen to occupy the bedroom next to mine?"
"I do," I said.
"That is very nice indeed, for often of an evening we will keep each
other company and discourse on Albert, to the joy of both our
hearts. The boxes are receptacles for my household gods, dear,
those dear mementoes of the past, that I could not quite part with.
Don't suppose for a moment that they are full of dresses, for
although my taste is light and festive, Albert likes gay colours, he
says they remind him of the sales of remnants in the autumn. Dear
fellow, it was the most poetical thing he ever uttered, but he has
said it once or twice. I can show you my household treasures when
you feel disposed to have an evening's real recreation. The burden
of this house, and with so delicate a mother as your good Ma, must
be heavy upon a young lass like you, but Albert tells me—but there!
I won't say any more just now, for you'll blush, and I don't want you
to blush, and I don't want to encourage those hopes that may never
be realised. I may as well whisper, though, that Albert is looking out
for a wife who will be a pattern of Solomon's virtuous woman, and
when he finds her, why she'll be lucky, that's all I can say."
Just then the pretty silver gong sounded, and people began to stand
up preparatory to going down to dinner. It was difficult even then to
move Mrs. Fanning, and for a wild moment I had a fear that I might
be imprisoned behind her in the drawing-room all during dinner,
while she still discoursed upon Albert and his attractions. Miss
Mullins, however, came to the rescue.
"Come, Miss Wickham," she cried, "we must lead the way," and
accordingly Jane, my mother, and I went down first, and the
different boarders followed us.
To my infinite distress Mrs. Fanning, being a complete stranger, had
her seat next mine. I had one comfort, however, she was better than
Albert; and Albert, who arrived presently himself, found that he was
seated next Miss Armstrong. He nodded across at his mother.
"How do, old lady," he said, "glad to find you cosily established;
everything all right, eh?"
"Yes, Albert, my son," replied the good woman, "everything is all
right, and I have been having a long conversation about you with my
interesting young friend here, Miss Westenra Wickham. By-the-by,
dear, would you kindly tell me how you got that outlandish name, I
never heard it before, and I do not believe it belongs to the Christian
religion."
"I did not know there was anything heathenish about it," I could not
help answering; "it happens to be my name, and I was fully baptized
by it."
"I will see presently whether I can take to it," responded the old
lady. "Soup? Yes, please. I will trouble you, my good girl, for (turning
to the maid) a table-spoon; I never take soup with a dessert spoon.
Thanks; that's better."
Mrs. Fanning now gave me a few moments peace, and I found, to
my great satisfaction, that she had an excellent appetite, and was
also extremely critical with regard to her food. I introduced her to
her next door neighbour, who happened to be a fat little woman,
something like herself in build. They were both gourmands, and
criticised adversely the meal to their mutual pleasure. Thus I had
time to look around me, and to consider this new aspect of affairs.
Things were scarcely likely to be more comfortable if Albert had now
got his mother to plead his cause with me. He glanced at me several
times during the meal, and once even favoured me with a broad
wink—he was really intolerable.
Meanwhile Miss Armstrong was all blushes and smirks. I heard her
suggest to Mr. Fanning that she should go the next day to see him,
and bring some of her drawings with her, and I heard him tell her in
what he was pleased to call his brutal manner that he would not be
at home, and if he were and she came would certainly not see her.
This seemed to be considered a tremendous joke by Miss Armstrong,
and her mother also joined in it, and gave Mr. Fanning a dig in the
ribs, and told him that he was the soul of wit, and had the true spirit
of heart.
Meanwhile, Mr. Randolph, my mother, Captain and Mrs. Furlong, and
the more refined portion of the establishment enjoyed themselves at
the other end of the table. I saw Mr. Randolph glance down in my
direction once or twice, and I am sure, although he was not able to
judge of the difference, the fact of seeing me once more in my
properly made black evening dress relieved his mind, for he looked
quite contented, and turned in a cheerful manner to my mother, and
when dinner was over, and we returned to the drawing-room, I was
lucky enough to be able to escape Mrs. Fanning and to go up to the
other end of the room, where I seated myself close to mother, took
hold of her hand, leant against her chair, and indulged in the luxury
of talking to Mr. Randolph. He was in a very good humour, and
suggested that we should make a party on the following evening to
another play, which was then very much in vogue.
"But not in the chocolate-coloured brougham with the pair of
horses," I said.
"We will have a cab from the nearest stand, if you prefer it," was his
instant response.
"I should much," I answered.
"And we will not dine at the Cecil," he continued; "we can have a
sort of high tea here before we start."
"That I should also like infinitely better," I answered.
"It shall be as you please," was his response. Then he began to tell
us something of the play which we were about to see, and I forgot
all about my discomforts, and enjoyed myself well.
I was putting things in order in the drawing-room that night, for this
was always one of my special duties, when Mr. Fanning, who had left
the room a long time ago, came back. He came up to me holding his
lighted candle in his hand. I started when I saw him.
"Good night," I said coldly.
"Pray don't go for a moment," he said. "I have come back here on
the express chance of seeing you."
"I cannot wait now, Mr. Fanning," I replied.
"But I really must have an interview with you, it is of the highest
importance,—when can I see you alone? When can you give me an
hour of your time quite undisturbed?"
"Never," I answered brusquely.
"Now you will forgive me for saying that that is pure nonsense. If
you will not promise me an hour of your own free will I shall take
the present opportunity of speaking to you."
"But I shall not stay," I answered with spirit, "and you cannot keep
me here against my will. Mr. Fanning, I also will take the present
opportunity of telling you that you and I have nothing in common,
that I dislike your singling me out for special conversations of any
kind, and that I hope in the future you will clearly understand that I
do not wish you to do so."
"Oh, that is all very fine," he said, "but come now; what have I done
to make myself obnoxious? There is the old lady upstairs, she has
taken no end of a fancy to you, she says you are the most charming
and the prettiest girl she has ever seen, and what have you to say
against my mother? Let me tell you that she has come to this house
on purpose to make your acquaintance."
"I have nothing whatever to say against your mother, Mr. Fanning,
but I object to the subject of conversation which she chooses to
occupy her time with while talking to me. I am not in the least
interested in you, and I wish you and your mother clearly to
understand this fact as quickly as possible."
I do not think it was in the nature of Mr. Fanning ever to look
crestfallen, or my present speech might have made him do so. He
did not even change colour, but he looked at me out of those eyes
which his mother had so vividly described, and after a moment said
softly—
"There will come a day when you will regret this. An honest heart is
offered to you and you trample it in the dust, but there will come a
day when you will be sorry. How do you think this establishment is
working?"
I was so astonished and relieved at his change of conversation that I
said—
"It seems to be going very well, don't you think so?"
"It is going well for my purpose," he replied, and then he added, "it
is working itself out in a way that will only spell one word—Ruin.
Now you ponder on that. Take it as your night-cap, and see what
sort of sleep you'll have, and when next I ask for a few moments'
conversation perhaps you'll not say no. I will not keep you any
longer for the present."
He left the room, I heard his footsteps dying down the corridor, and
the next instant he had slammed his bedroom door.
CHAPTER XIV
ANXIETY
After he had left me, and I was quite certain that I should not see
him again that night, I went straight to Jane Mullins' room. Jane was
generally up the last in the house, and I had not the slightest doubt
I should still find her in her dinner dress, and ready for conversation.
I had bidden mother good night long ago, and hoped she was sound
asleep, but I did not mind disturbing Jane. I opened the door now
and went in. As I expected, Jane was up; she was seated by the fire,
she was looking into its depths, and did not turn round at once when
I entered. The first thing she did when she became aware of the fact
that there was some one else in the room besides herself, was to
sigh somewhat deeply. Then she said in a low voice—
"What if it all turns out a mistake?" and then she jumped to her feet
and confronted me. "Yes, dear, yes," she said. "Oh, my dear
Westenra, why aren't you in bed? It is very bad indeed for young
people to be up so late. You will get quite worn and wrinkled. Let me
tell you, my love, that we can never get youth back again, and we
ought to prize it while we have it. How old are you, Westenra, my
love?"
"I shall be twenty-two my next birthday," was my answer.
"Ah, yes, yes, quite young, in the beautiful prime of youth.
Nevertheless, the bloom can be rubbed off, and then—well, it never
comes back, dear. But go to bed, Westenra, don't stay up bothering
your head. I see by that frown between your brows that you are
going to say something which I would rather not listen to. Don't tell
me to-night, Westenra, love."
"I must tell you," I answered. "I have come to see you for the
purpose. You are old enough, Jane, to bear the little disagreeable
things I tell you now and then. You are our mainstay, our prop, in
this establishment. I cannot go on without confiding in you, and you
must listen to me."
"Well, child, sit down, here is a comfortable chair." Jane got up and
offered me her own chair. I did not take it.
"What nonsense," I said, "sit down again. Here, this little hassock at
your feet will suit me far better."
I seated myself as I spoke, and laid my hand across Jane's knee.
"Now, that is cosy," I said. She touched my arm as though she loved
to touch it, and then she laid her firm, weather-beaten hand on my
shoulder, and then, as if impelled by an unwonted impulse, she bent
forward and kissed me on my cheek.
"You are a very nice girl. Since I knew you life has been far
pleasanter to me," said Jane Mullins. "I thank you for giving me a bit
of love. Whatever happens I want you to remember that."
"I do," I answered; "you have very little idea how much I care for
you, Jane, and how immensely I respect you. There are, I think,
very few women who would have acted as you have done. I am fully
convinced there is a mystery in all your actions which has not yet
been explained to me, but I have not come here to-night to talk
about that. I have come here to ask you one or two questions, and
to tell you one or two things, and my first question is this—Why
were you sighing when I came in, and why did you murmur to
yourself, 'What if it all turns out a mistake?' Will you explain those
words, Jane."
"No," replied Jane stoutly, "for you were eavesdropping when you
heard them, and there is no reason why I should explain what you
had no right to listen to."
"Thank you; you have answered me very sensibly, and I won't say
another word on the subject of your sigh and your remarkable
speech. But now to turn to the matter which has brought me to your
room so late in the evening."
"Well, dear, it is past midnight, and you know how early I am up. It
is a little unreasonable of you; what has brought you, darling?"
"Mr. Fanning has brought me."
"Oh dear, oh dear, that tiresome man again," said Miss Mullins.
"You don't like him yourself, do you, Jane?"
"It is a great pity he is not different," said Jane, "for he is extremely
well off."
"O Jane! pray don't talk nonsense. Do you suppose that a person
with the name of Fanning could have any interest whatever for me?
Now, please, get that silly idea out of your head once for all."
"Oh, as far as any use that there is in it, I have long ago got it out of
my head," replied Jane; "but the thing to be considered is this, that
he has not got it out of his head—nor has his mother—and that
between them they can make things intensely disagreeable. Now, if
Mr. Randolph was going to stay here, I should not have an anxious
moment."
"What do you mean?" I cried; "is Mr. Randolph going away?" A deep
depression seemed suddenly to come over me; I could not quite
account for it.
"He is, dear; and it is because he must be absent for two or three
months that I am really anxious. He will come back again; but
sudden and important news obliges him to go to Australia. He is
going in a fortnight, and it is that that frets him. You will be left to
the tender mercies of Mr. Fanning and Mrs. Fanning, and you have
got so much spirit you are sure to offend them both mortally, and
then they will leave, and—oh dear, I do think that things are dark.
My dear Westenra, I often wonder if we shall pull through after all."
"That is what I want to speak to you about," I answered. "Mr.
Fanning came into the drawing-room just now, and was very rude
and very unlike a gentleman. I was alone there, and he said he had
something to say to me in private, and, of course, I refused to listen.
He wanted to insist on my granting him an interview, and said that
he could compel me to listen if he chose. Think of any gentleman
speaking like that!"
"They don't mind what they say, nor what they do, when they're in
love," muttered Jane.
"I won't allow you to say that," I answered, springing to my feet;
"the man is intolerable. Jane, he must go; there is no help for it."
"He must stay, dear, and I cannot disclose all my reasons now."
I stood clasping and unclasping my hands, and staring at Jane.
"You knew beforehand, did you not, Westenra, that there would be
disagreeables connected with this scheme?"
"Of course I knew it; but I never did think that the disagreeables
would resolve themselves into Mr. Fanning."
"We never know beforehand where the shoe is going to pinch,"
remarked Jane in a sententious voice.
"Well, I have something else to say," I continued. "Mr. Fanning was
not only very unpleasant to me, but he told me something which I
can scarcely believe. He said that our boarding-house, which
seemed to be going so well, was not going well at all. He said there
was only one word to spell how it was going, and that word was
RUIN. O Jane! it can't be true?"
"Let us hope not," said Jane, but she turned very white. "I will tell
you one thing, Westenra," she continued. "If you don't want to have
utter ruin you must go on behaving as nicely as ever you can,
bearing with every one, being gentle and considerate, and trying to
make every one happy. And in especial, you must bear with Mr.
Fanning and with Mrs. Fanning; you must be particularly civil to
them both, for if they go others will go; and whatever happens,
Westenra, remember your mother is not to be worried. I know what
I am saying, your mother is not to be worried. Your mother must
never guess that things are not as right as they should be. When Mr.
Randolph comes back everything will be right, but during his
absence we will have to go through rather a tight place; and Albert
Fanning is the sort of person who might take advantage of us, and
what you must do, my dear girl, is to be guileful."
"Guileful!" I cried; "never."
"But you must, my love, you must be guileful and wary; you need
not give him a single straw to go upon, but at the same time you
must be civil. There now, that is all I can tell you for the present. Go
to bed, child, for I have to do the daily accounts, and must be up at
six in the morning. It's that new cook, she frets me more than I can
say, she don't do things proper; and I noticed that Mrs. Fanning
sniffed at her soup instead of eating it this evening, and the turbot
was not as fresh as it ought to be. Go to bed, Westenra, go to bed."
I left the room. There was no use in staying any longer with Jane.
She certainly had not reassured me. She seemed puzzled and
anxious about the establishment; and why were not things going
well? And what had Mr. Fanning to do with it; and why, why was Mr.
Randolph going away?
The next morning after breakfast I went into the drawing-room for
my usual task of dusting and arranging the furniture and refilling the
vases with fresh flowers, when Mr. Randolph suddenly came in.
"It will be best for you and Mrs. Wickham to meet me at the
Criterion to-night," he said. "As you won't give me the opportunity of
offering you dinner at the Cecil, that seems the next best thing to
do. I have got a box in a good part of the house, so we need not be
there more than a few minutes before it commences. I shall meet
you at the entrance and conduct you to your seats."
His manner showed some excitement, quite out of keeping with his
ordinary demeanour, and I noticed that he scarcely glanced at me.
His face was somewhat worn, too, in expression, and although he
generally had himself in complete control, he now looked nearly as
anxious and worried as Jane herself. He scarcely waited for my
compliance with the arrangement he had proposed, but glancing at
the door, spoke abruptly—
"Something unexpected and very grievous has occurred, and I am
obliged to leave England by the Smyrna, which sails on Saturday
week."
"Miss Mullins told me last night that you were going away," I replied.
I also now avoided looking at him. I was playing with some large
sprays of mimosa which had been sent in from the market. To my
dying day I shall never forget how that mimosa seemed to slip
about, and would not get into the best position in the vase in which
I was placing it.
"Effective," he said, as he watched my movements, "but it withers
quickly; it wants its native air."
"I suppose so," I answered.
"Have you ever seen it growing?"
"No; I have never been to the South."
"You have a good deal to see. I hope some day——" He broke off.
"Where are you going when you do go away?" I asked.
"To Sydney first, perhaps to Melbourne."
"It will be nice for you to leave England during our unpleasant winter
weather."
"There is nothing nice about my visit," he said; "I dislike going more
than I have any words to express. In particular, I am sorry to leave
your mother; but before I go I want"—he dropped his voice and
came a step nearer.
"What?" I asked.
"I am anxious that your mother should see a doctor—a specialist, I
mean. I am not satisfied with her condition."
"But mother is really quite well," I said impulsively. "You have not
known her long, Mr. Randolph; she never was really strong. She is
quite as well as she ever was."
"A specialist could assure us on that point, could he not?" was his
reply. "I want Dr. Reade to give me a diagnosis of her case."
"Dr. Reade," I cried.
"Yes; I should like her to see him between now and the day when I
must leave England. I cannot possibly be back under from four to
five months, and if my mind can be relieved of a very pressing
anxiety, you would not deny me the satisfaction, would you?"
"But why should your mind be anxious?" I asked boldly. I looked full
into his face as I spoke, and then I met a look which caused me to
turn faint, and yet to feel happy, as I had never felt happy before. I
lowered my eyes and looked out of the window. He gave a quick
sigh, and then said suddenly—
"How like your father you are."
"My father? But you never knew him."
"I never knew him, but I have often looked at his picture. Can you
tell me how he won his V.C.?"
"Saving a comrade, bringing one of his brother officers out of the
thick of the fight; he received his own fatal wound in doing so. He
did not survive the action two months."
"A fine fellow! A splendid action," said Mr. Randolph, enthusiasm in
his voice. "You will think over what I have said, and I will not keep
you now. We shall meet at the Criterion this evening. Good-bye for
the present."
CHAPTER XV
DR. READE
I cannot recall anything about the play. I only know that we had
excellent seats and a good view of the house, and that mother
seemed to enjoy everything. As to Mr. Randolph, I doubt if he did
enjoy that play. He was too much a man of the world to show any of
his emotions, but I saw by a certain pallor round his mouth, and a
rather dragged look about his eyes, that he was suffering, and I
could not imagine why. I had always in my own mind made up a sort
of story about Jim Randolph. He was one of the fortunate people of
the earth; the good things of the world had fallen abundantly to his
share. He was nice to look at and pleasant to talk to, and of course
he had plenty of money. He could do what he pleased with his life. I
had never associated him with sorrow or trial of any sort, and to see
that look now in his eyes and round the corners of his somewhat
sensitive and yet beautifully-cut mouth, gave me a new sensation
with regard to him. The interest I felt in him immediately became
accelerated tenfold. I found myself thinking of him instead of the
play. I found myself anxious to watch his face. I even found, when
once our eyes met (his grave and dark, mine, I daresay, bold
enough and determined enough), that my heart beat fast, and the
colour flew into my face; then, strange to say, the colour came into
his face, dying his swarthy cheek just for a moment, but leaving it
the next paler than ever. He came a little nearer to me, however, and
bending forward so that mother should not hear, said in a semi-
whisper—
"You have thought about what I said this morning?"
"I have thought it over a good deal," I replied.
"You think it can be managed?"
"Dr. Anderson, mother's family physician, would do what you
require, Mr. Randolph."
"That is a good idea," he said. "Anderson can arrange a consultation.
I will see him to-morrow, and suggest it."
I did not say any more, for just then mother turned and said
something to Mr. Randolph, and Mr. Randolph bent forward and
talked to mother in that worshipping son-like way with which he
generally addressed her. If mother had ever been blessed with a
son, he could not have been more attentive nor sweeter than Jim
Randolph was, and I found myself liking him more than ever, just
because he was so good to mother, and my heart ached at the
prospect of his enforced and long absence. So much did this thought
worry me, that I could not help saying to him as we were leaving
the theatre—
"I am very sorry that you are going."
"Is that true?" he said. His face lit up, his eyes sparkled; all the tired
expression left his eyes and mouth.
"Are you saying what you mean?" he asked.
"I am most truly sorry. You have become indispensable to mother;
she will miss you sorely."
"And you—will you miss me?"
I tried to say "For mother's sake I will," but I did not utter the
words. Mr. Randolph gave me a quick glance.
"I have not told your mother yet that I am going," he said.
"I wondered if you had," I replied. "I thought of telling her myself
to-day."
"Do not say anything until nearer the time," was his somewhat
guarded response. "Ah! here comes the carriage."
"So you did order the carriage after all," I said, seeing that the same
neat brougham which he had used on the last occasion stopped the
way.
"You never forbade me to see you both home in the carriage," he
said with a laugh. "Now then, Mrs. Wickham."
Mother had been standing a little back out of the crowd. He went to
her, gave her his arm, and she stepped into the carriage, just as if it
belonged to her. Mother had always that way with Mr. Randolph's
possessions, and sometimes her manner towards him almost
annoyed me. What could it mean. Did she know something about
him which I had never heard of nor guessed?
The next day about noon Mr. Randolph entered Jane's sitting-room,
where I often spent the mornings.
"I have just come from Anderson's," he said. "He will make an
appointment with Dr. Reade to see your mother to-morrow."
"But on what plea?" I asked. "Mother is somewhat nervous. I am
sure it would not be at all good for her to think that her indisposition
was so great that two doctors must see her."
"Anderson will arrange that," replied Mr. Randolph. "He has told your
mother once or twice lately that he thinks her very weak, and would
like her to try a new system of diet. Now Reade is a great specialist
for diseases of the digestion. Both doctors will guard against any
possible shock to your mother."
"Well," I said somewhat petulantly, "I cannot imagine why you are
nervous about her. She is quite as well as she ever was."
He looked at me as if he meant to say something more, and I felt
certain that he strangled a sigh which never came to the surface.
The next moment he left the room, I looked round me in a state of
bewilderment.
In Jane's room was a bookcase, and the bookcase contained a
heterogeneous mass of books of all sorts. Amongst others was a
medical directory. I took it up now, and scarcely knowing why I did
so, turned to the name of Reade. Dr. Reade's name was entered in
the following way:—
"Reade, Henry, M.D., F.R.C.P., consulting physician to the Brompton
Hospital for Consumption, London, and to the Royal Hospital for
Diseases of the Chest, Ventnor."
I read these qualifications over slowly, and put the book back in its
place. There was nothing whatever said of Dr. Reade's qualifications
for treating that vast field of indigestion to which so many sufferers
were victims. I resolved to say something to Jane.
"What is it?" said Jane, as she came into the room. "What is fretting
you now?"
"Oh, nothing," I answered. "Dr. Reade must be a very clever
physician."
"First-class, of course. I am so pleased your mother is going to see
him."
"But I thought mother was suffering very much from weakness and
want of appetite."
"So she is, poor dear, and I am inventing quite a new sort of soup,
which is partly digested beforehand, that I think she will fancy."
"But I have been looking up Dr. Reade's name. He seems to be a
great doctor for consumption and other diseases of the chest. There
is no allusion to his extraordinary powers of treating people for
indigestion."
"Well, my dear, consumptives suffer more than most folks from
indigestion. Now, don't you worry your head; never meet troubles
half-way. I am extremely pleased that your mother is to see Dr.
Reade."
On the following morning mother herself told me that Dr. Reade was
coming.
"It is most unnecessary," she said, "and I told Dr. Anderson so. I was
only telling him yesterday that I thought his own visits need not be
quite so frequent. He is such a dear, kind man, that I do not like to
hurt his feelings; but really, Westenra, he charges me so little that it
quite goes to my heart. And now we have not our old income, this
very expensive consulting physician is not required. I told Dr.
Anderson so, but he has made up his mind. He says there is no use
in working in the dark, and that he believes I should be much
stronger if I ate more."
Dr. Reade called in the course of the morning, and Dr. Anderson
came with him. They stayed in mother's room for some little time,
and then they both went out, and Jane Mullins had an interview with
them first, and then she sent for me.
"Dr. Anderson wants to speak to you, Westenra," she said. She
rushed past me as she spoke, and I could not catch sight of her
face, so I went into her little sitting-room, where both the doctors
were waiting for me, and closed the door behind me. I was not at all
anxious. I quite believed that mother's ailment was simply want of
appetite and weakness, and I had never heard of any one dying just
from those causes.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Java Foundations Introduction To Program Design And Data Structures 2nd Edition 2nd Edition John Lewis

  • 1.
    Java Foundations IntroductionTo Program Design And Data Structures 2nd Edition 2nd Edition John Lewis download https://ebookbell.com/product/java-foundations-introduction-to- program-design-and-data-structures-2nd-edition-2nd-edition-john- lewis-2355602 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Java Foundations Introduction To Program Design And Data Structures 5th Edition 5th Edition John Lewis https://ebookbell.com/product/java-foundations-introduction-to- program-design-and-data-structures-5th-edition-5th-edition-john- lewis-32182666 Java Foundations Introduction To Program Design And Data Structures 4th Edition 4th Edition John Lewis https://ebookbell.com/product/java-foundations-introduction-to- program-design-and-data-structures-4th-edition-4th-edition-john- lewis-37247276 Java Foundations 3rd Ed Chase Joseph Depasquale Peter Joseph Lewis https://ebookbell.com/product/java-foundations-3rd-ed-chase-joseph- depasquale-peter-joseph-lewis-21976870 Java Foundations Todd Greanier https://ebookbell.com/product/java-foundations-todd-greanier-976556
  • 3.
    Java Software SolutionsFoundations Of Program Design 7th Edition 7th Edition John Lewis https://ebookbell.com/product/java-software-solutions-foundations-of- program-design-7th-edition-7th-edition-john-lewis-2371348 Java Software Solutions Foundations Of Program Design 4th Edition John Lewis https://ebookbell.com/product/java-software-solutions-foundations-of- program-design-4th-edition-john-lewis-1294350 Foundations Of Java For Abap Programmers 1st Edition Alistair Rooney https://ebookbell.com/product/foundations-of-java-for-abap- programmers-1st-edition-alistair-rooney-929496 Foundations Of Java Programming Oop Option Clin Galeriu https://ebookbell.com/product/foundations-of-java-programming-oop- option-clin-galeriu-30345526 Distributed Virtual Worlds Foundations And Implementation Techniques Using Vrml Java And Corba 1st Edition Dr Stephan Diehl Auth https://ebookbell.com/product/distributed-virtual-worlds-foundations- and-implementation-techniques-using-vrml-java-and-corba-1st-edition- dr-stephan-diehl-auth-4198916
  • 6.
  • 7.
  • 8.
    John Lewis Virginia Tech PeterDePasquale The College of New Jersey Joseph Chase Radford University Javaℱ Foundations Second Edition Introduction to Program Design & Data Structures Addison-Wesley Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
  • 9.
    Editor-in-Chief: Michael Hirsch EditorialAssistant: Stephanie Sellinger Director of Marketing: Margaret Whaples Marketing Coordinator: Kathryn Ferranti Managing Editor: Jeffrey Holcomb Production Project Manager: Heather McNally Senior Manufacturing Buyer: Carol Melville Media Manufacturing Buyer: Ginny Michaud Art Director: Linda Knowles Cover Designer: Susan Paradise Cover Art: Marc Romanelli/Getty Images Media Project Manager: Katelyn Boller Full-Service Project Management: Rose Kernan, Nesbitt Graphics, Inc. Composition: Nesbitt Graphics, Inc. Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriate page within text. MicrosoftÂź and WindowsÂź are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. 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. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Copyright © 2011, 2008. Pearson Education, Inc., publishing as Addison-Wesley, 501 Boylston Street, Suite 900, Boston, Massachusetts 02116. All rights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 501 Boylston Street, Suite 900, Boston, Massachusetts 02116. Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps. Library of Congress Cataloging-in-Publication Data Lewis, John, 1963- Java foundations : introduction to program design & data structures / John Lewis, Peter J. DePasquale, Joseph Chase. -- 2nd ed. p. cm. ISBN 0-13-212881-0 1. Java (Computer program language) I. DePasquale, Peter J. (Peter Joseph) II. Chase, Joseph, 1964- III. Title. QA76.73.J38L48845 2010 005.13'3--dc22 2009051134 10 9 8 7 6 5 4 3 2 1–EB–14 13 12 11 10 www.pearsonhighered.com ISBN-10: 0-13-212881-0 ISBN-13: 978-0-13-212881-0
  • 10.
    To my wife,Sharon, for everything. – John To my wife, Lisa, and our twins: Lily and Adam. – Pete To my loving wife, Melissa, for her support and encouragement. – Joe
  • 11.
  • 12.
    Preface vii Welcome to JavaFoundations. This book is designed to serve as the primary resource for a two- or three-term introductory course sequence, ranging from the most basic programming concepts to the design and implementation of complex data structures. This unified approach makes the important introductory sequence more cohesive and accessible for students. We’ve borrowed the best elements from the industry-leading text Java Software Solutions for the introductory material, reworked to complement the design and vision of the overall text. For example, instead of having graphics sections spread throughout many chapters, the coverage of graphical user interfaces is accom- plished in a well-organized chapter of its own. In the later chapters, the exploration of collections and data structures is mod- eled somewhat after the coverage in Java Software Structures, but has been thor- oughly retooled to flow cleanly from the introductory material. The result is a comprehensive, cohesive, and seamless exploration of programming concepts. New in the Second Edition We appreciate the feedback we’ve received about this book and are pleased that it served so well as an introductory text. The following modifications have been made to improve the presentation of particular topics and the overall flow: ■ A stack is now used as the initial example of a collection so that the con- cept of a collection is more clearly established. ■ The discussion of Generics has been expanded and clarified. ■ The coverage of the Quick Sort and Merge Sort algorithms has been expanded. ■ The coverage of Analysis of Algorithms has been separated into its own chapter and expanded. ■ Material on Testing and Debugging has been incorporated into more appropriate locations of the text. ■ The coverage of Search Trees and Heaps have been divided into separate chapters.
  • 13.
    viii PREFACE ■ Twonew chapters covering Hashing and Databases have been added. ■ End-of-chapter exercises and projects have been updated to reflect changes in the book. Regarding Objects Phrases like objects-first, objects-early, and objects-late continue to be bandied about by computing educators, despite the fact that the nuances of the pedagogy of the introductory sequence cannot be summed up so easily. We’ll take this opportunity to discuss our approach. First, this book is purely object-oriented, presented in a gradual, natural man- ner. Concepts that overlap with procedural programming, such as methods and their invocation, are discussed in terms of an object-oriented approach. Thus, no example is ever made up of a single class with multiple methods. In fact, in our examples the class that contains the main method never contains another. We use objects right from the start, and discuss everything in object-oriented terms at all times. An overview of object-oriented concepts is given in Chapter 1, then reinforced and fleshed out throughout the book. Classes from the Java stan- dard class library are introduced immediately, and objects from these classes are instantiated and used for the various services they provide. In the first four chap- ters, students explore and write programs made up of a single class with a single main method—but these programs actively use predefined classes and objects from the standard library in addition to exploring fundamental programming concepts such as expressions and conditionals. We never introduce third-party classes simply as fodder to create examples. That approach can confuse students by blurring the distinction between classes that are part of the standard library (and thus always available) and “extras” thrown in by textbook authors as a convenience. Every non-library class used in an example is fully explored in this book. There’s no “magic” behind the scenes. The debate continues: should coverage of control structures come before the details of writing classes, or vice versa? The truth is there are advantages either way, and a knowledgeable instructor can capitalize on either approach. If class composition comes first, it exposes the underlying essence of objects earlier and demystifies their use. However, without the ability to use basic control structures, the examples at that point are often uninteresting and unrealistic. This book explores control structures before writing classes. Chapter 4 uses small, single- method examples to examine the details of conditionals and loops, providing a strong foundation for the multiclass examples in Chapter 5.
  • 14.
    PREFACE ix Chapter Breakdown Chapter1 (Introduction) introduces the Java programming language and the basics of program development. It contains an introduction to object-oriented development, including an overview of concepts and terminology. This chapter contains broad introductory material that can be covered while students become familiar with their development environment. Chapter 2 (Data and Expressions) explores some of the basic types of data used in a Java program and the use of expressions to perform calculations. It discusses the conversion of data from one type to another, and how to read input interac- tively from the user with the help of the Scanner class. Chapter 3 (Using Classes and Objects) explores the use of predefined classes and the objects that can be created from them. Classes and objects are used to manipulate character strings, produce random numbers, perform complex calcu- lations, and format output. Packages, enumerated types, and wrapper classes are also discussed. Chapter 4 (Conditionals and Loops) covers the use of boolean expressions to make decisions. All related statements for conditionals and loops are discussed, including the enhanced version of the for loop. The Scanner class is revisited for iterative input parsing and reading text files. Chapter 5 (Writing Classes) explores the basic issues related to writing classes and methods. Topics include instance data, visibility, scope, method parameters, and return types. Constructors, method design, static data, and method overload- ing are covered as well. Testing and debugging are now covered in this chapter as well. Chapter 6 (Graphical User Interfaces) is a thorough exploration of Java GUI processing, focusing on components, events, and listeners. Many types of compo- nents and events are discussed using numerous GUI examples. Additionally, lay- out mangers, containment hierarchies, borders, tooltips, and mnemonics are introduced. Chapter 7 (Arrays) contains extensive coverage of arrays and array processing. Topics include bounds checking, initializer lists, command-line arguments, variable- length parameter lists, and multidimensional arrays. Chapter 8 (Inheritance) covers class derivations and associated concepts such as class hierarchies, overriding, and visibility. Strong emphasis is put on the proper use of inheritance and its role in software design. Chapter 9 (Polymorphism) explores the concept of binding and how it relates to polymorphism. Then we examine how polymorphic references can be accom- plished using either inheritance or interfaces. Design issues related to polymor- phism are examined as well.
  • 15.
    x PREFACE Chapter 10(Exceptions) covers exception handling and the effects of uncaught exceptions. The try-catch statement is examined, as well as a dis- cussion of exception propagation. The chapter also explores the use of excep- tions when dealing with input and output, and examines an example that writes a text file. Chapter 11 (Recursion) covers the concept, implementation, and proper use of recursion. Several examples are used to elaborate on the discussion, including a maze traversal and the classic Towers of Hanoi problem. Chapter 12 (Analysis of Algorithms) discusses the techniques for analyzing the complexity of algorithms, including recursive algorithms. Big Oh notation is introduced. Chapter 13 (Searching and Sorting) explores the linear and binary searching algorithms, as well as five sorting algorithms. The sorts include both quadratic and O(N log N) algorithms. The efficiency of these algorithms is examined. Chapter 14 (Stacks) introduces the concept of a collection and establishes the importance of separating the interface from the implementation. Stacks are used as the initial example of a collection, and both dynamic and fixed implementa- tions of a stack are explored. Generic types are introduced in this chapter, detail- ing their use in supporting the collection classes. Chapter 15 (Queues) introduces FIFO queues and discusses options for their implementation. As with stacks, a queue is explored first conceptually, then as tools to help us solve problems, and finally by examining their underlying data structures. Both array-based and dynamic link implementations are discussed. Chapter 16 (Trees) introduces the terms and concepts behind trees. Various implementation strategies are discussed, and a recursive, linked approach is exam- ined in detail. An example of a binary decision tree is explored as well. Chapter 17 (Binary Search Trees) covers the concept of search trees and a linked implementation for a classic binary search tree. Tree rotation algorithms are also discussed. Chapter 18 (Heaps and Priority Queues) discusses the concept of a heap and its relationship to trees. A full linked implementation of a heap is explored. Priority queues are used as an example of a collection in its own right, and the natural relationship between heaps and priority queues are explored. Chapter 19 (Graphs) discusses both directed and undirected graphs. Additionally, weighted graphs are explored, and the differences between breadth- first and depth-first graph traversals are covered. Minimal spanning trees are introduced, and implementation strategies are discussed. Chapter 20 (Hashing) covers the concept of creating a hash table to facilitate storage and retrieval of objects. Various classes that relate to hashing from the Java API are explored.
  • 16.
    PREFACE xi Chapter 21(Databases) explores the concept of databases and their manage- ment, and discusses the basics of SQL queries. It then explores the techniques for establishing a connection between a Java program and a database, and the API used to interact with it. Student CD The CD included with each textbook contains: ■ Source code for all of the programs in the text. ■ The Java Software Development Kit (SDK). ■ Various Java development environments, including NetBeansℱ, Eclipseℱ, DrJava, jGRASPℱ, and TextPad¼. Instructor Resources The following supplements are available to qualified instructors only. Visit the Pearson Education Instructor Resource Center (www.pearsonhighered.com/irc) or send email to computing@aw.com for information on how to access these resources. ■ Presentation Slides—lecture-ready presentations for each chapter in Microsoft PowerPoint¼ format. ■ Solutions—full solutions to the exercises and programming projects. ■ Test Bank with powerful test generator software—includes a wealth of free-response, multiple-choice, and true/false questions. Acknowledgments Educators and students from around the world have provided feedback on previ- ous work that has allowed us to mold this book into a fresh, valuable resource. Your comments and questions are always welcome. The talent and commitment of the team at Addison-Wesley continues to amaze us. We greatly appreciate the insight of Michael Hirsch, our editor, and the hard work of his assistant, Stephanie Sellinger. Rose Kernan at Nesbitt Graphics was a great help throughout the production process. We thank all of these people for ensuring that this book meets the highest quality standards. We’d like to acknowledge the collective input from hundreds of professors and students around the world in the development of the material upon which this
  • 17.
    xii PREFACE book isbased. There are too many of you to individually name, but your influ- ence on Java Software Solutions and Java Software Structures is evident in Java Foundations. Special thanks go to Ruth Dannenfelser, Cory Samaha, and Zach Zappala at the College of New Jersey for their help with solutions to the database projects. And our continued thanks go to Jason Snyder at Virginia Tech for his assistance testing code and many other contributions. Groups like the ACM Special Interest Group on Computer Science Education (SIGCSE), the Consortium for Computing Sciences in Colleges (CCSC), and the Computer Science Teachers Association (CSTA) are phenomenal resources. Their conferences and online activities provide opportunities for educators from all lev- els and all types of schools to share ideas and materials. If you are a computing educator and are not involved with these groups, you’re missing out. Finally, we thank our families for their support and patience during the busy process of writing.
  • 18.
    xiii Preface vii Chapter 1Introduction 1 1.1 The Java Programming Language 2 A Java Program 3 Comments 5 Identifiers and Reserved Words 6 White Space 9 1.2 Program Development 11 Programming Language Levels 11 Editors, Compilers, and Interpreters 13 Development Environments 15 Syntax and Semantics 16 Errors 17 1.3 Problem Solving 18 1.4 Software Development Activities 19 1.5 Object-Oriented Programming 21 Object-Oriented Software Principles 21 Chapter 2 Data and Expressions 31 2.1 Character Strings 32 The print and println Methods 32 String Concatenation 34 Escape Sequences 37 2.2 Variables and Assignment 38 Variables 38 The Assignment Statement 40 Constants 42 2.3 Primitive Data Types 43 Integers and Floating Points 43 Contents
  • 19.
    xiv CONTENTS Characters 45 Booleans47 2.4 Expressions 47 Arithmetic Operators 48 Operator Precedence 48 Increment and Decrement Operators 51 Assignment Operators 53 2.5 Data Conversion 54 Conversion Techniques 56 2.6 Reading Input Data 57 The Scanner Class 57 Chapter 3 Using Classes and Objects 71 3.1 Creating Objects 72 Aliases 74 3.2 The String Class 76 3.3 Packages 79 The import Declaration 80 3.4 The Random Class 82 3.5 The Math Class 85 3.6 Formatting Output 88 The NumberFormat Class 88 The DecimalFormat Class 90 The printf Method 92 3.7 Enumerated Types 92 3.8 Wrapper Classes 95 Autoboxing 97 Chapter 4 Conditionals and Loops 105 4.1 Boolean Expressions 106 Equality and Relational Operators 107 Logical Operators 108
  • 20.
    CONTENTS xv 4.2 Theif Statement 110 The if-else Statement 113 Using Block Statements 115 The Conditional Operator 118 Nested if Statements 119 4.3 Comparing Data 121 Comparing Floats 121 Comparing Characters 121 Comparing Objects 122 4.4 The switch Statement 123 4.5 The while Statement 127 Infinite Loops 132 Nested Loops 133 Other Loop Controls 137 4.6 Iterators 137 Reading Text Files 138 4.7 The do Statement 141 4.8 The for Statement 144 Iterators and for Loops 149 Comparing Loops 149 Chapter 5 Writing Classes 161 5.1 Classes and Objects Revisited 162 Identifying Classes and Objects 163 Assigning Responsibilities 165 5.2 Anatomy of a Class 165 Instance Data 170 UML Class Diagrams 171 5.3 Encapsulation 173 Visibility Modifiers 174 Accessors and Mutators 175 5.4 Anatomy of a Method 180 The return Statement 186 Parameters 188
  • 21.
    xvi CONTENTS Local Data189 Constructors Revisited 190 5.5 Static Class Members 190 Static Variables 191 Static Methods 191 5.6 Class Relationships 192 Dependency 195 Dependencies Among Objects of the Same Class 195 Aggregation 197 The this Reference 202 5.7 Method Design 203 Method Decomposition 204 Method Parameters Revisited 209 5.8 Method Overloading 210 5.9 Testing 216 Reviews 217 Defect Testing 217 Unit Testing 219 Integration Testing 219 System Testing 219 Test-Driven Development 220 5.10 Debugging 220 Simple Debugging with print Statements 221 Debugging Concepts 221 Chapter 6 Graphical User Interfaces 233 6.1 GUI Elements 234 Frames and Panels 235 Buttons and Action Events 239 Determining Event Sources 240 6.2 More Components 243 Text Fields 244 Check Boxes 247 Radio Buttons 250
  • 22.
    CONTENTS xvii Sliders 255 ComboBoxes 260 Timers 265 6.3 Layout Managers 269 Flow Layout 271 Border Layout 274 Grid Layout 278 Box Layout 280 Containment Hierarchies 284 6.4 Mouse and Key Events 284 Mouse Events 284 Key Events 292 Extending Adapter Classes 297 6.5 Dialog Boxes 298 File Choosers 301 Color Choosers 304 6.6 Some Important Details 305 Borders 305 Tool Tips and Mnemonics 309 6.7 GUI Design 315 Chapter 7 Arrays 325 7.1 Array Elements 326 7.2 Declaring and Using Arrays 327 Bounds Checking 329 Alternate Array Syntax 335 Initializer Lists 335 Arrays as Parameters 336 7.3 Arrays of Objects 337 7.4 Command-Line Arguments 346 7.5 Variable-Length Parameter Lists 348 7.6 Two-Dimensional Arrays 351 Multidimensional Arrays 355
  • 23.
    xviii CONTENTS Chapter 8Inheritance 363 8.1 Creating Subclasses 364 The protected Modifier 368 The super Reference 370 Multiple Inheritance 371 8.2 Overriding Methods 374 Shadowing Variables 375 8.3 Class Hierarchies 376 The Object Class 378 Abstract Classes 380 8.4 Visibility 382 8.5 Designing for Inheritance 385 Restricting Inheritance 385 Chapter 9 Polymorphism 393 9.1 Late Binding 394 9.2 Polymorphism via Inheritance 394 9.3 Interfaces 407 Interface Hierarchies 412 The Comparable Interface 413 The Iterator Interface 413 9.4 Polymorphism via Interfaces 414 Event Processing 416 Chapter 10 Exceptions 423 10.1 Exception Handling 424 10.2 Uncaught Exceptions 425 10.3 The try-catch Statement 425 The finally Clause 429 10.4 Exception Propagation 430
  • 24.
    CONTENTS xix 10.5 TheException Class Hierarchy 433 Checked and Unchecked Exceptions 436 10.6 I/O Exceptions 437 Chapter 11 Recursion 447 11.1 Recursive Thinking 448 Infinite Recursion 449 Recursion in Math 449 11.2 Recursive Programming 450 Recursion vs. Iteration 453 Direct vs. Indirect Recursion 453 11.3 Using Recursion 454 Traversing a Maze 454 The Towers of Hanoi 459 Chapter 12 Analysis of Algorithms 469 12.1 Algorithm Efficiency 470 12.2 Growth Functions and Big-Oh Notation 471 12.3 Comparing Growth Functions 473 Method Calls 475 Analyzing Recursive Algorithms 477 Chapter 13 Searching and Sorting 481 13.1 Searching 482 Linear Search 485 Binary Search 487 13.2 Sorting 489 Selection Sort 490 Insertion Sort 497 Bubble Sort 498 Quick Sort 500 Merge Sort 501
  • 25.
    xx CONTENTS 13.3 AnalyzingSearching and Sorting Algorithms 503 Comparing Search Algorithms 504 Comparing Sort Algorithms 504 Chapter 14 Stacks 513 14.1 Introduction to Collections 514 Abstract Data Types 514 The Java Collections API 516 14.2 A Stack Collection 517 14.3 Inheritance, Polymorphism, and Generics 519 Generics 520 14.4 A Stack ADT 521 14.5 Using Stacks: Evaluating Postfix Expressions 523 14.6 Exceptions 530 14.7 Implementing a Stack: with Arrays 532 Managing Capacity 532 14.8 The ArrayStack Class 533 The push Operation 537 The pop Operation 537 The peek Operation 538 Other Operations 538 14.9 References as Links 538 14.10 Managing Linked Lists 541 Accessing Elements 541 Inserting Nodes 542 Deleting Nodes 543 Sentinel Nodes 544 14.11 Elements Without Links 544 Doubly Linked Lists 545
  • 26.
    CONTENTS xxi 14.12 Implementinga Stack: With Links 546 The LinkedStack Class 546 The push Operation 550 The pop Operation 552 Other Operations 555 14.13 Implementing Stacks: The Java.Util.Stack Class 553 Unique Operations 553 Inheritance and Implementation 554 14.14 Packages 554 Organizing Packages 555 Using CLASSPATH 555 Chapter 15 Queues 567 15.1 A Queue ADT 568 15.2 Using Queues: Code Keys 570 15.3 Using Queues: Ticket Counter Simulation 574 15.4 Implementing Queues: With Links 577 The enqueue Operation 582 The dequeue Operation 583 Other Operations 583 15.5 Implementing Queues: With Arrays 584 The enqueue Operation 587 The dequeue Operation 590 Other Operations 590 Chapter 16 Trees 595 16.1 Tree Terminology 596 Tree Classifications 597 16.2 Tree Traversals 598 Preorder Traversal 600 Inorder Traversal 601 Postorder Traversal 601 Level-Order Traversal 602
  • 27.
    xxii CONTENTS 16.3 Strategiesfor Implementing Trees 602 Computed Links in an Array 603 Stored Links in an Array 603 Linked Nodes 604 16.4 A Binary Tree Implementation 605 16.5 Decision Trees 606 Chapter 17 Binary Search Trees 625 17.1 Binary Search Trees 626 Adding an Element to a Binary Search Tree 627 Removing an Element from a Binary Search Tree 629 17.2 Binary Search Tree Implementation 630 17.3 Balanced Binary Search Trees 640 Right Rotation 641 Left Rotation 642 Right-Left Rotation 642 Left-Right Rotation 643 Chapter 18 Heaps and Priority Queues 649 18.1 Heaps 650 Adding an Element to a Heap 650 Removing the Largest Element from a Heap 651 18.2 Heap Implementation 652 18.3 Heap Sort 660 18.4 Priority Queues 660 Chapter 19 Graphs 669 19.1 Undirected Graphs 670 19.2 Directed Graphs 671
  • 28.
    CONTENTS xxiii 19.3 WeightedGraphs 673 19.4 Common Graph Algorithms 674 Traversals 674 Testing for Connectivity 678 Minimum Spanning Trees 680 Determining the Shortest Path 682 19.5 Strategies for Implementing Graphs 683 Adjacency Lists 684 Adjacency Matrices 684 Chapter 20 Hashing 689 20.1 Hashing 690 20.2 Hashing Functions 692 The Division Method 692 The Folding Method 693 The Mid-square Method 693 The Radix Transformation Method 694 The Digit Analysis Method 694 The Length-Dependent Method 694 Hashing Functions in the Java Language 695 20.3 Resolving Collisions 695 Chaining 695 Open Addressing 698 20.4 Deleting Elements from A Hash Table 701 Deleting from a Chained Implementation 701 Deleting from an Open Addressing Implementation 702 20.5 Hash Tables in the Java Collections API 703 The Hashtable Class 704 The HashSet Class 704 The HashMap Class 706 The IdentityHashMap Class 707 The WeakHashMap Class 709 LinkedHashSet and LinkedHashMap 710
  • 29.
    xxiv CONTENTS Chapter 21Databases 717 21.1 Introduction to Databases 718 21.2 Establishing a Connection to a Database 720 Obtaining A Database Driver 720 21.3 Creating and Altering Database Tables 722 Create Table 723 Alter Table 724 Drop Column 725 21.4 Querying The Database 725 Show Columns 726 21.5 Inserting, Viewing, and Updating (Modifying) Data 728 Insert 729 Select . . . from 729 Update 734 21.6 Deleting Data and Database Tables 735 Deleting Data 735 Deleting Database Tables 736 Appendix A Glossary 741 Appendix B Number Systems 775 Place Value 776 Bases Higher Than 10 778 Conversions 779 Shortcut Conversions 781 Appendix C The Unicode Character Set 787 Appendix D Java Bitwise Operators 791
  • 30.
    CONTENTS xxv Appendix EJava Modifiers 797 Java Visibility Modifiers 798 A Visibility Example 798 Other Java Modifiers 799 Appendix F Java Graphics 801 Coordinate Systems 802 Representing Color 802 Drawing Shapes 803 Polygons and Polylines 812 The Polygon Class 813 Appendix G Java Applets 821 Embedding Applets in HTML 824 More Applet Methods 824 GUIs in Applets 829 Appendix H Regular Expressions 837 Appendix I Javadoc Documentation Generator 839 Doc Comments 840 Tags 841 Files Generated 841 Appendix J Java Syntax 845 Index 859
  • 31.
  • 32.
  • 33.
  • 34.
    Introduction 1 C H AP T E R O B J E C T I V E S ■ Introduce the Java programming language. ■ Describe the steps involved in program compilation and execution. ■ Explore the issues related to problem solving in general. ■ Discuss the activities involved in the software development process. ■ Present an overview of object-oriented principles. This book is about writing well-designed software. We begin by examining a very basic Java program and using it to explore some initial programming concepts. We then lay the groundwork for software development on a larger scale, exploring the foundations of problem solving, the activities involved in software development, and the principles of object-oriented programming. 1 1
  • 35.
    1.1 The JavaProgramming Language A computer is made up of hardware and software. The hardware components of a computer system are the physical, tangible pieces that support the computing ef- fort. They include chips, boxes, wires, keyboards, speakers, disks, cables, print- ers, and so on. The hardware is essentially useless without instructions to tell it what to do. A program is a series of instructions that the hardware executes one after another. Programs are sometimes called applications. Software consists of programs and the data those programs use. Software is the intangible counterpart to the physical hardware components. Together, they form a tool that we can use to solve problems. A program is written in a particular programming language that uses specific words and symbols to express the problem solution. A programming language defines a set of rules that determines exactly how a programmer can combine the words and symbols of the lan- guage into programming statements, which are the instructions that are carried out when the program is executed. Since the inception of computers, many programming languages have been cre- ated. We use the Java language in this book to demonstrate various programming concepts and techniques. Although our main goal is to learn these underlying software development concepts, an important side effect will be to become profi- cient in the development of Java programs. Java is a relatively new programming language compared to many others. It was developed in the early 1990s by James Gosling at Sun Microsystems. Java was introduced to the public in 1995 and has gained tremendous popularity since. Java has undergone various changes since its creation. The most recent Java technology is generally referred to as the Java 2 Platform, which is organized into three major groups: ■ Java 2 Platform, Standard Edition (J2SE) ■ Java 2 Platform, Enterprise Edition (J2EE) ■ Java 2 Platform, Micro Edition (J2ME) This book focuses on the Standard Edition, which, as the name implies, is the mainstream version of the language and associated tools. Furthermore, this book is based on the most recent version of the Standard Edition, which is J2SE 6.0. Some parts of early Java technologies have been deprecated, which means they are considered old-fashioned and should not be used. When it is important, we point out deprecated elements and discuss their preferred alternatives. 2 CHAPTER 1 Introduction KEY CONCEPT A computer system consists of hardware and software that work in concert to help us solve problems.
  • 36.
    Java is anobject-oriented programming language. Objects are the fundamental elements that make up a program. The principles of ob- ject-oriented software development are the cornerstone of this book. We explore object-oriented programming concepts later in this chap- ter and throughout the rest of the book. The Java language is accompanied by a library of extra software that we can use when developing programs. This software, referred to as the Java standard class library, provides the ability to create graphics, communicate over networks, and interact with databases, among many other features. The standard library that supports Java programming is huge and quite versatile. Although we won’t be able to cover all aspects of the library, we will explore many of them. Java is used in commercial environments all over the world. It is one of the fastest growing programming technologies of all time. So not only is it a good language in which to learn programming concepts, it is also a practical language that will serve you well in the future. A Java Program Let’s look at a simple but complete Java program. The program in Listing 1.1 prints two sentences to the screen. This particular program prints a quote by Abraham Lincoln. The output is shown below the program listing. All Java applications have a similar basic structure. Despite its small size and simple purpose, this program contains several important features. Let’s carefully dissect it and examine its pieces. The first few lines of the program are comments, which start with the // symbols and continue to the end of the line. Comments don’t af- fect what the program does but are included to make the program eas- ier to understand by humans. Programmers can and should include comments as needed throughout a program to clearly identify the pur- pose of the program and describe any special processing. Any written comments or documents, including a user’s guide and technical references, are called documentation. Comments included in a program are called inline documentation. The rest of the program is a class definition. This class is called Lincoln, though we could have named it just about anything we wished. The class defini- tion runs from the first opening brace ({) to the final closing brace (}) on the last line of the program. All Java programs are defined using class definitions. Inside the class definition are some more comments describing the purpose of the main method, which is defined directly below the comments. A method is a group of programming statements that is given a name. In this case, the name of the method is main and it contains only two programming statements. Like a class definition, a method is also delimited by braces. 1.1 The Java Programming Language 3 KEY CONCEPT This book focuses on the principles of object-oriented programming. KEY CONCEPT Comments do not affect a program’s processing; instead, they serve to facilitate human comprehension.
  • 37.
    All Java applicationshave a main method, which is where processing begins. Each programming statement in the main method is executed, one at a time in order, until the end of the method is reached. Then the program ends, or terminates. The main method definition in a Java program is always preceded by the words public, static, and void, which we examine later in the text. The use of String and args does not come into play in this particular program. We describe these later also. The two lines of code in the main method invoke another method called println (pronounced print line). We invoke, or call, a method when we want it to execute. The println method prints the specified characters to the screen. The characters to be printed are represented as a character string, enclosed in double quote characters ("). When the program is executed, it calls the println method to print the first statement, calls it again to print the second statement, and then, because that is the last line in the main method, the program terminates. The code executed when the println method is invoked is not defined in this program. The println method is part of the System.out object, which is part of 4 CHAPTER 1 Introduction L I S T I N G 1 . 1 //******************************************************************** // Lincoln.java Java Foundations // // Demonstrates the basic structure of a Java application. //******************************************************************** public class Lincoln { //----------------------------------------------------------------- // Prints a presidential quote. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("A quote by Abraham Lincoln:"); System.out.println ("Whatever you are, be a good one."); } } O U T P U T A quote by Abraham Lincoln: Whatever you are, be a good one.
  • 38.
    1.1 The JavaProgramming Language 5 the Java standard class library. It’s not technically part of the Java language, but is always available for use in any Java program. We explore the println method in more detail in Chapter 2. Comments Let’s examine comments in more detail. Comments are the only language feature that allows programmers to compose and communicate their thoughts independ- ent of the code. Comments should provide insight into the programmer’s original intent. A program is often used for many years, and often many modifications are made to it over time. The original programmer often will not remember the de- tails of a particular program when, at some point in the future, modifications are required. Furthermore, the original programmer is not always available to make the changes; thus, someone completely unfamiliar with the program will need to understand it. Good documentation is therefore essential. As far as the Java programming language is concerned, the content of com- ments can be any text whatsoever. Comments are ignored by the computer; they do not affect how the program executes. The comments in the Lincoln program represent one of two types of com- ments allowed in Java. The comments in Lincoln take the following form: // This is a comment. This type of comment begins with a double slash (//) and continues to the end of the line. You cannot have any characters between the two slashes. The com- puter ignores any text after the double slash to the end of the line. A comment can follow code on the same line to document that particular line, as in the following example: System.out.println ("Monthly Report"); // always use this title The second form a Java comment may have is the following: /* This is another comment. */ This comment type does not use the end of a line to indicate the end of the comment. Anything between the initiating slash-asterisk (/*) and the terminating asterisk-slash (*/) is part of the comment, including the invisible newline charac- ter that represents the end of a line. Therefore, this type of comment can extend over multiple lines. No space can be between the slash and the asterisk. If there is a second asterisk following the /* at the beginning of a comment, the content of the comment can be used to automatically generate external documen- tation about your program by using a tool called javadoc. More information about javadoc is given in Appendix I.
  • 39.
    6 CHAPTER 1Introduction The two basic comment types can be used to create various documentation styles, such as: // This is a comment on a single line. //— — — — — — — — — — — — — — — — — — — — — — — — — — — — // Some comments such as those above methods or classes // deserve to be blocked off to focus special attention // on a particular aspect of your code. Note that each of // these lines is technically a separate comment. //— — — — — — — — — — — — — — — — — — — — — — — — — — — — /* This is one comment that spans several lines. */ Programmers often concentrate so much on writing code that they focus too little on documentation. You should develop good commenting practices and follow them habitually. Comments should be well written, often in complete sentences. They should not belabor the obvious but should provide appropriate insight into the intent of the code. The following examples are not good comments: System.out.println ("hello"); // prints hello System.out.println ("test"); // change this later The first comment paraphrases the obvious purpose of the line and does not add any value to the statement. It is better to have no comment than a useless one. The second comment is ambiguous. What should be changed later? When is later? Why should it be changed? Identifiers and Reserved Words The various words used when writing programs are called identifiers. The identi- fiers in the Lincoln program are class, Lincoln, public, static, void, main, String, args, System, out, and println. These fall into three categories: ■ words that we make up when writing a program (Lincoln and args) ■ words that another programmer chose (String, System, out, println, and main) ■ words that are reserved for special purposes in the language (class, public, static, and void) While writing the program, we simply chose to name the class Lincoln, but we could have used one of many other possibilities. For example, we could have called it Quote, or Abe, or GoodOne. The identifier args (which is short for arguments) is KEY CONCEPT Inline documentation should provide insight into your code. It should not be ambiguous or belabor the obvious.
  • 40.
    1.1 The JavaProgramming Language 7 often used in the way we use it in Lincoln, but we could have used just about any other identifier in its place. The identifiers String, System, out, and println were chosen by other pro- grammers. These words are not part of the Java language. They are part of the Java standard library of predefined code, a set of classes and methods that some- one has already written for us. The authors of that code chose the identifiers in that code—we’re just making use of them. Reserved words are identifiers that have a special meaning in a programming language and can only be used in predefined ways. A reserved word cannot be used for any other purpose, such as naming a class or method. In the Lincoln program, the reserved words used are class, public, static, and void. Figure 1.1 lists all of the Java reserved words in alphabetical order. The words marked with an asterisk are reserved for possible future use in later versions of the language but currently have no meaning in Java. An identifier that we make up for use in a program can be composed of any combination of letters, digits, the underscore character (_), and the dollar sign ($), but it cannot begin with a digit. Identifiers may be of any length. Therefore, total, label7, nextStockItem, NUM_BOXES, and $amount are all valid identi- fiers, but 4th_word and coin#value are not valid. Both uppercase and lowercase letters can be used in an identifier, and the difference is important. Java is case sensitive, which means that two identifier names that differ only in the case of their letters are considered to be different identifiers. Therefore, total, Total, ToTaL, and TOTAL are all different identifiers. As you can imagine, it is not a good idea to use multiple identifiers that differ only in their case, because they can be easily confused. FIGURE 1.1 Java reserved words abstract assert boolean break byte case catch char class const* continue default do double else enum extends false final finally float for goto* if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while KEY CONCEPT Java is case sensitive. The uppercase and lowercase versions of a letter are distinct.
  • 41.
    8 CHAPTER 1Introduction Although the Java language doesn’t require it, using a consistent case format for each kind of identifier makes your identifiers easier to understand. There are various Java conventions regarding identifiers that should be followed, though technically they don’t have to be. For example, we use title case (upper- case for the first letter of each word) for class names. Throughout the text, we describe the preferred case style for each type of identifier when it is first en- countered. While an identifier can be of any length, you should choose your names care- fully. They should be descriptive but not verbose. You should avoid meaningless names such as a or x. An exception to this rule can be made if the short name is ac- tually descriptive, such as using x and y to represent (x, y) coordinates on a two-di- mensional grid. Likewise, you should not use unnecessarily long names, such as the identifier theCurrentItemBeingProcessed. The name currentItem would serve just as well. As you might imagine, the use of identifiers that are verbose is a much less prevalent problem than the use of names that are not descriptive. You should always strive to make your programs as readable as possible. Therefore, you should always be careful when abbreviating words. You might think curStVal is a good name to represent the current stock value, but another person trying to understand the Identifier An identifier is a letter followed by zero or more letters and digits. A Java Letter includes the 26 English alphabetic characters in both uppercase and lowercase, the $ and _ (underscore) characters, as well as alphabetic characters from other languages. A Java Digit includes the digits 0 through 9. Examples: total MAX_HEIGHT num1 computeWage System Java Letter Java Letter Java Digit KEY CONCEPT Identifier names should be descriptive and readable.
  • 42.
    1.1 The JavaProgramming Language 9 code may have trouble figuring out what you meant. It might not even be clear to you two months after writing it. A name in Java is a series of identifiers separated by the dot (period) character. The name System.out is the way we designate the object through which we in- voked the println method. Names appear quite regularly in Java programs. White Space All Java programs use white space to separate the words and symbols used in a program. White space consists of blanks, tabs, and newline characters. The phrase white space refers to the fact that, on a white sheet of paper with black printing, the space between the words and symbols is white. The way a program- mer uses white space is important because it can be used to emphasize parts of the code and can make a program easier to read. Except when it’s used to separate words, the computer ignores white space. It does not affect the execution of a program. This fact gives programmers a great deal of flexibility in how they format a program. The lines of a program should be divided in logical places and certain lines should be indented and aligned so that the pro- gram’s underlying structure is clear. Because white space is ignored, we can write a program in many different ways. For example, taking white space to one extreme, we could put as many words as possible on each line. The code in Listing 1.2, the Lincoln2 program, is formatted quite differently from Lincoln but prints the same message. //******************************************************************** // Lincoln2.java Java Foundations // // Demonstrates a poorly formatted, though valid, program. //******************************************************************** public class Lincoln2{public static void main(String[]args){ System.out.println("A quote by Abraham Lincoln:"); System.out.println("Whatever you are, be a good one.");}} O U T P U T A quote by Abraham Lincoln: Whatever you are, be a good one. L I S T I N G 1 . 2 KEY CONCEPT Appropriate use of white space makes a program easier to read and understand.
  • 43.
    10 CHAPTER 1Introduction Taking white space to the other extreme, we could write almost every word and symbol on a different line with varying amounts of spaces, such as Lincoln3, shown in Listing 1.3. All three versions of Lincoln are technically valid and will exe- cute in the same way, but they are radically different from a reader’s point of view. Both of the latter examples show poor style and make the program difficult to understand. You may be asked to adhere to particular guidelines when you write your programs. A software //******************************************************************** // Lincoln3.java Java Foundations // // Demonstrates another valid program that is poorly formatted. //******************************************************************** public class Lincoln3 { public static void main ( String [] args ) { System.out.println ( "A quote by Abraham Lincoln:" ) ; System.out.println ( "Whatever you are, be a good one." ) ; } } O U T P U T A quote by Abraham Lincoln: Whatever you are, be a good one. L I S T I N G 1 . 3 KEY CONCEPT You should adhere to a set of guide- lines that establishes the way you format and document your programs.
  • 44.
    1.2 Program Development11 development company often has a programming style policy that it requires its programmers to follow. In any case, you should adopt and consistently use a set of style guidelines that increases the readability of your code. 1.2 Program Development The process of getting a program running involves various activities. The pro- gram has to be written in the appropriate programming language, such as Java. That program has to be translated into a form that the computer can execute. Errors can occur at various stages of this process and must be fixed. Various soft- ware tools can be used to help with all parts of the development process as well. Let’s explore these issues in more detail. Programming Language Levels Suppose a particular person is giving travel directions to a friend. That person might explain those directions in any one of several languages, such as English, Russian, or Italian. The directions are the same no matter which language is used to explain them, but the manner in which the directions are expressed is different. The friend must be able to understand the language being used in order to follow the directions. Similarly, a problem can be solved by writing a program in one of many pro- gramming languages, such as Java, Ada, C, C++, C#, Pascal, and Smalltalk. The purpose of the program is essentially the same no matter which language is used, but the particular statements used to express the instructions, and the overall or- ganization of those instructions, vary with each language. A computer must be able to understand the instructions in order to carry them out. Programming languages can be categorized into the following four groups. These groups basically reflect the historical development of computer languages. ■ machine language ■ assembly language ■ high-level languages ■ fourth-generation languages In order for a program to run on a computer, it must be expressed in that com- puter’s machine language. Each type of CPU has its own language. For that reason, we can’t run a program specifically written for a Sun Workstation, with its Sparc processor, on a Dell PC, with its Intel processor. Each machine language instruction can accomplish only a simple task. For exam- ple, a single machine language instruction might copy a value into a register or com- pare a value to zero. It might take four separate machine language instructions to add
  • 45.
    12 CHAPTER 1Introduction two numbers together and to store the result. However, a computer can do millions of these instructions in a second, and therefore many simple commands can be executed quickly to accomplish complex tasks. Machine language code is expressed as a series of binary digits and is extremely difficult for humans to read and write. Originally, programs were entered into the computer by using switches or some similarly tedious method. Early programmers found these techniques to be time consuming and error prone. These problems gave rise to the use of assembly language, which replaced bi- nary digits with mnemonics, short English-like words that represent commands or data. It is much easier for programmers to deal with words than with binary digits. However, an assembly language program cannot be executed directly on a computer. It must first be translated into machine language. Generally, each assembly language instruction corresponds to an equivalent machine language instruction. Therefore, similar to machine language, each as- sembly language instruction accomplishes only a simple operation. Although as- sembly language is an improvement over machine code from a programmer’s per- spective, it is still tedious to use. Both assembly language and machine language are considered low-level languages. Today, most programmers use a high-level language to write software. A high-level language is expressed in English-like phrases, and thus is easier for programmers to read and write. A single high-level language programming statement can accomplish the equivalent of many—perhaps hundreds—of ma- chine language instructions. The term high-level refers to the fact that the programming statements are expressed in a way that is far removed from the machine language that is ultimately executed. Java is a high- level language, as are Ada, C++, Smalltalk, and many others. Figure 1.2 shows equivalent expressions in a high-level language, assembly lan- guage, and machine language. The expressions add two numbers together. The as- sembly language and machine language in this example are specific to a Sparc processor. The high-level language expression in Figure 1.2 is readable and intuitive for programmers. It is similar to an algebraic expression. The equivalent assembly language code is somewhat readable, but it is more verbose and less intuitive. The machine language is basically unreadable and much longer. In fact, only a small portion of the binary machine code to add two numbers together is shown in Figure 1.2. The complete machine language code for this particular expression is over 400 bits long. A high-level language insulates programmers from needing to know the un- derlying machine language for the processor on which they are working. But KEY CONCEPT High-level languages allow a pro- grammer to ignore the underlying details of machine language. KEY CONCEPT All programs must be translated to a particular CPU’s machine language in order to be executed.
  • 46.
    1.2 Program Development13 high-level language code must be translated into machine language in order to be executed. Some programming languages are considered to operate at an even higher level than high-level languages. They might include special facilities for automatic report generation or interaction with a database. These languages are called fourth-generation languages, or simply 4GLs, because they followed the first three generations of computer programming: machine, assembly, and high-level. Editors, Compilers, and Interpreters Several special-purpose programs are needed to help with the process of develop- ing new programs. They are sometimes called software tools because they are used to build programs. Examples of basic software tools include an editor, a compiler, and an interpreter. Initially, you use an editor as you type a program into a computer and store it in a file. There are many different editors with many different features. You should become familiar with the editor you will use regularly because it can dra- matically affect the speed at which you enter and modify your programs. Figure 1.3 on the next page shows a very basic view of the program development process. After editing and saving your program, you attempt to translate it from high-level code into a form that can be executed. That translation may result in er- rors, in which case you return to the editor to make changes to the code to fix the problems. Once the translation occurs successfully, you can execute the program and evaluate the results. If the results are not what you want, or if you want to en- hance your existing program, you again return to the editor to make changes. The translation of source code into (ultimately) machine language for a partic- ular type of CPU can occur in a variety of ways. A compiler is a program that FIGURE 1.2 A high-level expression and its assembly language and machine language equivalent High-Level Language Assembly Language Machine Language <a + b> 1d [%fp–20], %o0 1d [%fp–24], %o1 add %o0, %o1, %o0 ... 1101 0000 0000 0111 1011 1111 1110 1000 1101 0010 0000 0111 1011 1111 1110 1000 1001 0000 0000 0000 ...
  • 47.
    14 CHAPTER 1Introduction translates code in one language to equivalent code in another language. The orig- inal code is called source code, and the language into which it is translated is called the target language. For many traditional compilers, the source code is translated directly into a particular machine language. In that case, the translation process occurs once (for a given version of the program), and the resulting exe- cutable program can be run whenever needed. An interpreter is similar to a compiler but has an important difference. An in- terpreter interweaves the translation and execution activities. A small part of the source code, such as one statement, is translated and executed. Then another statement is translated and executed, and so on. One advantage of this technique is that it eliminates the need for a separate compilation phase. However, the pro- gram generally runs more slowly because the translation process occurs during each execution. The process generally used to translate and execute Java programs combines the use of a compiler and an interpreter. This process is pictured in Figure 1.4. The Java compiler translates Java source code into Java bytecode, which is a representation of the program in a low-level form similar to machine language code. The Java interpreter reads Java bytecode and executes it on a specific machine. Another compiler could trans- late the bytecode into a particular machine language for efficient ex- ecution on that machine. The difference between Java bytecode and true machine language code is that Java bytecode is not tied to any particular processor type. This ap- proach has the distinct advantage of making Java architecture neutral, and there- fore easily portable from one machine type to another. The only restriction is that there must be a Java interpreter or a bytecode compiler for each processor type on which the Java bytecode is to be executed. Since the compilation process translates the high-level Java source code into a low-level representation, the interpretation process is more efficient than interpret- ing high-level code directly. Executing a program by interpreting its bytecode is still slower than executing machine code directly, but it is fast enough for most applica- tions. Note that for efficiency, Java bytecode could be compiled into machine code. Edit and save program Translate program into executable form errors errors Execute program and evaluate results FIGURE 1.3 Editing and running a program KEY CONCEPT A Java compiler translates Java source code into Java bytecode, a low-level, architecture-neutral repre- sentation of the program.
  • 48.
    1.2 Program Development15 Development Environments A software development environment is the set of tools used to create, test, and modify a program. Some development environments are available for free while others, which may have advanced features, must be purchased. Some environ- ments are referred to as integrated development environments (IDEs) because they integrate various tools into one software program. Any development environment will contain certain key tools, such as a Java compiler and interpreter. Some will include a debugger, which helps you find er- rors in a program. Other tools that may be included are documentation genera- tors, archiving tools, and tools that help you visualize your program structure. Sun Microsystems, the creator of the Java programming language, provides the Java Software Development Kit (SDK), which is sometimes referred to simply as the Java Development Kit (JDK). The SDK can be downloaded free of charge for various hardware platforms from Sun’s Java Web site, java.sun.com, and is also included on the CD that accompanies this book. The SDK tools are not an integrated environment. The commands for compila- tion and interpretation are executed on the command line. That is, the SDK does not have a graphical user interface (GUI), with windows, menus, buttons, etc. It also does not include an editor, although any editor that can save a document as simple text can be used. Sun also has a Java IDE called NetBeans (www.netbeans.org) that incorporates the development tools of the SDK into one convenient GUI-based program. IBM Java source code Java bytecode Java compiler Java interpreter Bytecode compiler Machine code FIGURE 1.4 The Java translation and execution process
  • 49.
    16 CHAPTER 1Introduction promotes a similar IDE called Eclipse (www.eclipse.org). Both NetBeans and Eclipse are open source projects, meaning that they are developed by a wide collection of programmers and are avail- able for free. A research group at Auburn University has developed jGRASP, a free Java IDE that is included on the CD that accompanies this book. It can also be downloaded from www.jgrasp.org. In addition to fundamen- tal development tools, jGRASP contains tools that graphically display program elements. Various other Java development environments are available, and several are provided on this book’s CD. The choice of which development environment to use is important. The more you know about the capabilities of your environment, the more productive you can be during program development. Syntax and Semantics Each programming language has its own unique syntax. The syntax rules of a lan- guage dictate exactly how the vocabulary elements of the language can be com- bined to form statements. These rules must be followed in order to create a pro- gram. We’ve already discussed several Java syntax rules. For instance, the fact that an identifier cannot begin with a digit is a syntax rule. The fact that braces are used to begin and end classes and methods is also a syntax rule. Appendix J formally defines the basic syntax rules for the Java programming language, and specific rules are highlighted throughout the text. During compilation, all syntax rules are checked. If a program is not syntacti- cally correct, the compiler will issue error messages and will not produce byte- code. Java has a similar syntax to the programming languages C and C++, and therefore the look and feel of the code is familiar to people with a background in those languages. The semantics of a statement in a programming language define what will hap- pen when that statement is executed. Programming languages are generally un- ambiguous, which means the semantics of a program are well defined. That is, there is one and only one interpretation for each statement. On the other hand, the natural languages that humans use to communicate, such as English and Italian, are full of ambiguities. A sentence can often have two or more different meanings. For example, consider the following sentence: Time flies like an arrow. The average human is likely to interpret this sentence as a general observation: that time moves quickly in the same way that an arrow moves quickly. However, if we interpret the word time as a verb (as in “run the 50-yard dash and I’ll time KEY CONCEPT Many different development environ- ments exist to help you create and modify Java programs.
  • 50.
    1.2 Program Development17 you”) and the word flies as a noun (the plural of fly), the interpreta- tion changes completely. We know that arrows don’t time things, so we wouldn’t normally interpret the sentence that way, but it is a valid interpretation of the words in the sentence. A computer would have a difficult time trying to determine which meaning is intended. Moreover, this sentence could describe the preferences of an unusual insect known as a “time fly,” which might be found near an archery range. After all, fruit flies like a banana. The point is that one specific English sentence can have multiple valid mean- ings. A computer language cannot allow such ambiguities to exist. If a program- ming language instruction could have two different meanings, a computer would not be able to determine which one should be carried out. Errors Several different kinds of problems can occur in software, particularly during pro- gram development. The term computer error is often misused and varies in meaning depending on the situation. From a user’s point of view, anything that goes awry when interacting with a machine can be called a computer error. For example, sup- pose you charged a $23 item to your credit card, but when you received the bill, the item was listed at $230. After you have the problem fixed, the credit card company apologizes for the “computer error.” Did the computer arbitrarily add a zero to the end of the number, or did it perhaps multiply the value by 10? Of course not. A computer follows the commands we give it and operates on the data we provide. If our programs are wrong or our data inac- curate, then we cannot expect the results to be correct. A common phrase used to describe this situation is “garbage in, garbage out.” You will encounter three kinds of errors as you develop programs: ■ compile-time error ■ run-time error ■ logical error The compiler checks to make sure you are using the correct syntax. If you have any statements that do not conform to the syntactic rules of the language, the compiler will produce a syntax error. The compiler also tries to find other problems, such as the use of incompatible types of data. The syn- tax might be technically correct, but you may be attempting to do something that the language doesn’t semantically allow. Any er- ror identified by the compiler is called a compile-time error. If a compile-time error occurs, an executable version of the program is not created. KEY CONCEPT Syntax rules dictate the form of a program. Semantics dictate the meaning of the program statements. KEY CONCEPT A Java program must be syntactically correct or the compiler will not produce bytecode. KEY CONCEPT The programmer is responsible for the accuracy and reliability of a program.
  • 51.
    18 CHAPTER 1Introduction The second kind of problem occurs during program execution. It is called a run-time error and causes the program to terminate abnormally. For example, if we attempt to divide by zero, the program will “crash” and halt execution at that point. Because the requested operation is undefined, the system simply abandons its attempt to continue processing your program. The best programs are robust; that is, they avoid as many run-time errors as possible. For example, the program code could guard against the possibility of dividing by zero and handle the situa- tion appropriately if it arises. In Java, many run-time problems are called exceptions that can be caught and dealt with accordingly. The third kind of software problem is a logical error. In this case, the software compiles and executes without complaint, but it produces incorrect results. For example, a logical error occurs when a value is calculated incorrectly or when a graphical button does not appear in the correct place. A programmer must test the program thoroughly, comparing the expected results to those that actually oc- cur. When defects are found, they must be traced back to the source of the prob- lem in the code and corrected. The process of finding and correcting defects in a program is called debugging. Logical errors can manifest themselves in many ways, and the actual root cause might be difficult to discover. 1.3 Problem Solving Creating software involves much more than just writing code. The mechanics of editing and running a program are necessary steps, but the heart of software de- velopment is problem solving. We write a program to solve a particular problem. In general, problem solving consists of multiple steps: 1. Understanding the problem. 2. Designing a solution. 3. Considering alternatives to the solution and refining the solution. 4. Implementing the solution. 5. Testing the solution and fixing any problems that exist. Although this approach applies to any kind of problem solving, it works particu- larly well when developing software. These steps aren’t purely linear. That is, some of the activities will overlap others. But at some point, all of these steps should be carefully addressed. The first step, understanding the problem, may sound obvious, but a lack of attention to this step has been the cause of many misguided software development efforts. If we attempt to solve a problem we don’t completely understand, we often end up solving the wrong problem or at least going off on improper tangents.
  • 52.
    1.4 Software DevelopmentActivities 19 Each problem has a problem domain, the real-world issues that are key to our so- lution. For example, if we are going to write a program to score a bowling match, then the problem domain includes the rules of bowling. To develop a good solu- tion, we must thoroughly understand the problem domain. The key to designing a problem solution is breaking it down into manageable pieces. A solution to any problem can rarely be ex- pressed as one big task. Instead, it is a series of small cooperating tasks that interact to perform a larger task. When developing soft- ware, we don’t write one big program. We design separate pieces that are responsible for certain parts of the solution, and then we in- tegrate them with the other parts. Our first inclination toward a solution may not be the best one. We must al- ways consider alternatives and refine the solution as necessary. The earlier we consider alternatives, the easier it is to modify our approach. Implementing the solution is the act of taking the design and putting it in a us- able form. When developing a software solution to a problem, the implementa- tion stage is the process of actually writing the program. Too often programming is thought of as writing code. But in most cases, the act of designing the program should be far more interesting and creative than the process of implementing the design in a particular programming language. At many points in the development process, we should test our solution to find any errors that exist so that we can fix them. Testing cannot guarantee that there aren’t still problems yet to be discovered, but it can raise our confidence that we have a viable solution. Throughout this text we explore techniques that allow us to design and imple- ment elegant programs. Although we will often get immersed in these details, we should never forget that our primary goal is to solve problems. 1.4 Software Development Activities Given that the goal of software development is to solve problems, it shouldn’t sur- prise you that the activities involved in the software development process mirror the general problem solving steps we discussed in the previous section. In particular, any proper software development effort consists of four basic development activities: ■ Establishing the requirements. ■ Creating a design. ■ Implementing the design. ■ Testing. KEY CONCEPT Problem solving involves breaking a solution down into manageable pieces.
  • 53.
    20 CHAPTER 1Introduction It would be nice if these activities, in this order, defined a step-by-step ap- proach for developing software. However, although they may seem to be sequen- tial, they are almost never completely linear in reality. They overlap and interact. Let’s discuss each development activity briefly. Software requirements specify what a program must accomplish. They indicate the tasks that a program should perform, not how it performs them. Often, re- quirements are expressed in a document called a functional specification. Requirements are a clear expression of the problem to be solved. Until we truly know what problem we are trying to solve, we can’t actually solve it. In a classroom setting, students are generally provided the software require- ments in the form of the problem assignment. However, even when they are provided, such requirements need to be discussed and clarified. In professional development, the person or group who wants a software product developed (the client) will often provide an initial set of requirements. However, these initial re- quirements are often incomplete, ambiguous, and perhaps even contradictory. The software developer must work with the client to refine the requirements un- til all key decisions about what the system will do have been addressed. Requirements often address user interface issues such as output format, screen layouts, and graphical interface components. Essentially, the requirements establish the characteristics that make the program useful for the end user. They may also ap- ply constraints to your program, such as how fast a task must be performed. A software design indicates how a program will accomplish its requirements. The design specifies the classes and objects needed in a program and defines how they interact. It also specifies the relationships among the classes. Low- level design issues deal with how individual methods accomplish their tasks. A civil engineer would never consider building a bridge without designing it first. The design of software is no less essential. Many problems that occur in software are directly attributable to a lack of good design effort. It has been shown time and again that the effort spent on the design of a program is well worth it, saving both time and money in the long run. During software design, alternatives need to be considered and explored. Often, the first attempt at a design is not the best solution. Fortunately, changes are relatively easy to make during the design stage. Implementation is the process of writing the source code that will solve the problem. More precisely, implementation is the act of translating the de- sign into a particular programming language. Too many programmers focus on implementation exclusively when actually it should be the least creative of all de- velopment activities. The important decisions should be made when establishing the requirements and creating the design. KEY CONCEPT The effort put into design is both crucial and cost-effective.
  • 54.
    1.5 Object-Oriented Programming21 Testing is the act of ensuring that a program will solve the intended problem given all of the constraints under which it must perform. Testing includes running a program multiple times with various inputs and carefully scrutinizing the re- sults. But it means far more than that. Testing in one form or another should be a part of every stage of development. The accuracy of the requirements, for in- stance, should be tested by reviewing them with the client. We revisit the issues re- lated to testing in Chapter 11. 1.5 Object-Oriented Programming As we stated earlier in this chapter, Java is an object-oriented language. As the name implies, an object is a fundamental entity in a Java program. This book is focused on the idea of developing software by defining objects that interact with each other. The principles of object-oriented software development have been around for many years, essentially as long as high-level programming languages have been used. The programming language Simula, developed in the 1960s, had many char- acteristics that define the modern object-oriented approach to software develop- ment. In the 1980s and 1990s, object-oriented programming became wildly popu- lar, due in large part to the development of programming languages like C++ and Java. It is now the dominant approach used in commercial software development. One of the most attractive characteristics of the object-oriented approach is the fact that objects can be used quite effectively to represent real-world entities. We can use a software object to represent an employee in a company, for instance. We’d create one object per employee, each with behaviors and characteristics that we need to represent. In this way, object-oriented programming allows us to map our programs to the real situations that the programs represent. That is, the object- oriented approach makes it easier to solve problems, which is the point of writing a program in the first place. Let’s explore the specific characteristics of the object-oriented approach that help us solve those problems. Object-Oriented Software Principles Object-oriented programming ultimately requires a solid understanding of the following terms: ■ object ■ attribute ■ method
  • 55.
    Other documents randomlyhave different content
  • 56.
    "It is kindof you to sympathise with me," I said. "I am going to speak to Jane Mullins to-morrow. If possible Mr. Fanning must go." "But there is another thing," began Mrs. Furlong. She paused, and I saw that she was about to say something, even more disagreeable than anything she had yet uttered. "You have your mother, of course," she continued slowly, "but you yourself are very young, and—now I don't want to compliment you— but you are much nicer looking than many girls; you have quite a different air and appearance from any other girl in this house. Oh, I hate interfering, but your mother, Miss Wickham, must be a particularly innocent woman." "What do you mean?" I asked. "I mean Mr. Randolph," she answered, and she raised her eyes and fixed them on my face. "Mr. Randolph?" I said. "Surely you must admit that he at least is a gentleman?" "He is not only a gentleman, but he is more highly born and has more money than any one else in the house; he does not belong to the set who fill this house at all. Why does he come? This is no place for him. In one way it is quite as unsuitable to have him here as it is to have a man like Mr. Fanning here. Those two men represent opposite extremes. People will talk." "What about?" I asked. "About you, dear." "They cannot. I will not permit it." Then I said abruptly, standing up in my excitement, "After all, I don't care whether they talk or not; I was prepared for misunderstandings when I came here. Mother likes Mr. Randolph; he at least shall stay."
  • 57.
    "But, my child,it is not nice to be talked about; it is never nice for a young girl. People like my husband and myself quite understand. We know well that you and your mother are at present out of your right position, but others will not be so considerate. Mr. Randolph is always here." "You think," I said, stammering, "that he comes because——" She smiled, got up and kissed me. "What else could he come for, Westenra?" she said softly. "He comes because—because of mother," I answered. "He likes her; he told me so. He is anxious about her, for he thinks she misses her old life very much; he wants to make things easier for her. He is a very good man, and I respect him. I don't mind what any one says, I know in my heart he comes here because——" "No, you do not," said Mrs. Furlong, and she looked me full in the eyes, and I found myself colouring and stammering. "Believe me I have not intruded upon you this evening without cause," said the little woman. "I talked the matter over with my husband. I would rather Mr. Fanning were here than Mr. Randolph. Mr. Fanning is impossible, Mr. Randolph is not. He does not come here on account of your mother, he comes here because he likes you. I am very sorry; I felt I must speak; my husband agrees with me." "Do not say another word now," I said. "I am sure you mean all this kindly, but please do not say any more now. I will think over what you have said." "I will leave you then, dear," she said. She went as far as the door; she was a very kindly little woman, she was a real lady, and she meant well, but she had hurt me so indescribably that at that moment I almost hated her. When she reached the door she turned and said—
  • 58.
    "If ever myhusband and I can help you, Miss Wickham (but we are poor people), if ever we can help you, we will be glad to do so. I know you are angry with me now, but your anger won't remain, you will see who are your true friends by-and-by." She closed the door softly, and I heard her gentle steps going downstairs. I will frankly say that I did not go to bed for some time, that I paced indignantly up and down my room. I hated Jane, I hated Mr. Fanning, I still more cordially hated Mr. Randolph at that moment. Mr. Fanning must go, Mr. Randolph must go. I could not allow myself to be spoken about. How intolerable of Mr. Randolph to have come as he had done, to have forced himself upon us, to have invited us to go out with him, to have——and then I stopped, and a great lump rose in my throat, and I burst into tears, for in my heart of hearts I knew well that I did not think what he did intolerable at all, that I respected him, and—but I did not dare to allow my thoughts to go any further. I even hated myself for being good-looking, until I suddenly remembered that I had the same features as my father had. He had conquered in all the battles in which he had borne part through his life. My face must be a good one if it was like his. I would try to live up to the character which my face seemed to express, and I would immediately endeavour to get things on a different footing. Accordingly, the next day at breakfast I studiously avoided Mr. Randolph, and I equally studiously avoided Mr. Fanning. The consequence was that, being as it were between two fires, I had a most uncomfortable time, for Mr. Randolph showed me by certain glances which he threw in my direction that he was most anxious to consult me about something, and Mr. Fanning seemed to intercept these glances, and to make his own most unpleasant comments about them; and if Mr. Fanning intercepted them, so did Mrs. and Miss Armstrong. Miss Armstrong had now given up Mr. Randolph as almost hopeless with regard to a flirtation, and was turning her attention in the
  • 59.
    direction of Mr.Fanning. She talked Art at Mr. Fanning assiduously all during breakfast, and having learned by some accident that he was a publisher, boldly demanded from him if he would not like her to illustrate some of his books. In reply to this he gave a profound bow, and told her, with a certain awkward jerk of his body, that he never gave orders in advance, that he never gave orders on the score of friendliness, that when it came to the relations between publisher and artist he was brutal. "That's the word for it, Miss Armstrong," he said, "I am brutal when it comes to a bargain. I try to make the very best I can for myself. I never think of the artist at all. I want all the £ s d to go into my own pocket"—and here he slapped his waistcoat loudly, and uttered a harsh laugh, which showed all his broken teeth in a most disagreeable manner. Miss Armstrong and her mother seemed to think he was excellent fun, and Mrs. Armstrong said, with a quick glance first at Mr. Randolph and then at me, that it was refreshing to hear any man so frank, and that for her part she respected people who gave themselves no h'airs. Breakfast came to an end, and I sought Jane in her sanctum. "Now, Jane," I said, "you must put away your accounts, you must cease to think of housekeeping. You must listen to me." "What is it, Westenra?" she said. "Has anything vexed you?" she continued; "sit down and tell me all about it." "Several things vex me," I answered. "Jane, we must come to an understanding." "What about?" she asked in some alarm; "an understanding! I thought that was all arranged when our legal agreement was drawn up." "Oh, I know nothing about lawyers nor about legal agreements," I answered; "but, Jane, there are some things I cannot put up with, and one of them is——"
  • 60.
    "I know," sheanswered; "Mr. Fanning." "He is horrible, hateful; he is going to make himself most hateful to me. Jane, dear Jane, he must go." Jane looked puzzled and distressed. I expected her to say— "He shall certainly go, my dear, I will tell him that his room is required, and that he must leave at the end of the week." But on the contrary she sighed. After a long pause she said— "You want this house to be a success, I presume." "I certainly do, but we cannot have it a success on the present arrangement. Mr. Fanning must go, and also Mr. Randolph." "Mr. Randolph, Mr. James Randolph!" said Jane, now colouring high, and a sparkle of something, which seemed to be a curious mixture of fear and indignation, filling her eyes. "And why should he go? You do not know what you are talking about." "I do. He must go. Ask—ask Mrs. Furlong. They talk about him here, these hateful people; they put false constructions on his kindness; I know he is kind and he is a gentleman, but he does me harm, Jane, even as much harm as that horrible Mr. Fanning." "Now, look here, Westenra Wickham," said Jane Mullins. "Are you going to throw up the sponge, or are you not?" "Throw up the sponge! I certainly don't mean to fail." "You will do so if you send those two men out of the house. If you cannot hold your own, whatever men come here, you are not the girl I took you for. As to Mr. Randolph, be quite assured that he will never do anything to annoy you. If people talk let them talk. When they see nothing comes of their idle silly gossip, they will soon cease to utter it. And as to Mr. Fanning, they will equally cease to worry about him. If he pays he must stay, for as it is, it is difficult to let the first-floor rooms. People don't want to pay five guineas a week to
  • 61.
    live in Bloomsbury,and he has a small room; and it is a great relief to me that he should be here and pay so good a sum for his room. The thing must be met commercially, or I for one give it up." "You, Jane, you! then indeed we shall be ruined." "I don't really mean to, my dear child, I don't mean for a single moment to desert you; but I must say that if 17 Graham Square is to go on, it must go on commercial principles; and we cannot send our best boarders away. You ask me coolly, just because things are a little uncomfortable for you, you ask me to dismiss ten guineas a week, for Mr. Randolph pays five guineas for his room, and Mr. Fanning five guineas for his, and I don't know any other gentleman who would pay an equal sum, and we must have it to balance matters. What is to meet the rent, my dear? What is to meet the taxes? What is to meet the butcher's, the baker's, the grocer's, the fishmonger's bills if we dismissed our tenants. I often have a terrible fear that we were rash to take a great expensive house like this, and unless it is full from attic to drawing-room floor, we have not the slightest chance of meeting our expenses. Even then I fear!—but there I won't croak before the time; only, Westenra, you have to make up your mind. You can go away on a visit if you wish to, I do not counsel this for a moment, for I know you are a great attraction here. It is because you are pretty and wear nice dresses, and look different from the other boarders, that you attract them; and—yes, I will say it—Mr. Randolph also attracts them. They can get no small change out of Mr. James Randolph, so they need not try it on, but once for all we cannot decline the people who are willing to pay us good money, that is a foregone conclusion. Now you have got to accept the agreeables with the disagreeables, or this whole great scheme of yours will tumble about our heads like a pack of cards."
  • 62.
    CHAPTER XIII THE UGLYDRESS On that very day I searched through mother's wardrobe and found a piece of brown barége. It was a harsh and by no means pretty material. I held it up to the light, and asked her what she was going to do with it. "Nothing," she answered, "I bought it ten years ago at a sale of remnants, and why it has stuck to me all these years is more than I can tell." "May I have it?" was my next query. "Certainly," replied mother, "but you surely are not going to have a dress made of that ugly thing?" "May I have it?" I asked again. "Yes, dear, yes." I did not say any more with regard to the barége. I turned the conversation to indifferent matters, but when I left the room I took it with me. I made it into a parcel and took it out. I went to a little dressmaker in a street near by. I asked her if she would make the ugly brown barége into an evening dress. She measured the material, and said it was somewhat scanty.
  • 63.
    "That does notmatter," I said, "I want an ugly dress—can you manage to make a really ugly dress for me out of it?" "Well, Miss Wickham," she replied, fixing her pale brown eyes on my face, "I never do go in for making ugly dresses, it would be against my profession. You don't mean it, do you, Miss Wickham?" "Put your best work into it," I said, suddenly changing my tone. "Make it according to your own ideas of the fashion. Picture a young girl going to a play, or a ball, in that dress, and make it according to your own ideas." "May I trim it with golden yellow chiffon and turquoise blue silk bows?" she asked eagerly, her eyes shining. "You may," I replied, suppressing an internal shudder. I gave her a few further directions; she named a day when I should come to be fitted, and I went home. In less than a week's time the brown barĂ©ge arrived back, ready for me to wear. It was made according to Annie Starr's ideas of a fashionable evening gown. It was the sort of garment which would have sent the Duchess or Lady Thesiger into fits on the spot. In the first place, the bodice was full of wrinkles, it was too wide in the waist, and too narrow across the chest, but this was a small matter to complain of. It was the irritating air of vulgarity all over the dress which was so hard to bear. But, notwithstanding all these defects, it pleased me. It would, I hoped, answer my purpose, and succeed in making me appear very unattractive in the eyes of Mr. Randolph. That evening I put on the brown barĂ©ge for dinner. The yellow chiffon and the turquoise blue bows were much in evidence, and I did really feel that I was a martyr when I went downstairs in that dress with its outrĂ© trimmings. When I entered the drawing-room, mother glanced up at me as if she did not know me; she then started, the colour came into her face, and she motioned me imperatively to her side.
  • 64.
    "Go upstairs atonce and take that off," she said. "Oh no, mother," I answered, "there is no time now, besides I—I chose it, I admire it." "Take it off immediately, Westenra." "But it is your dear barĂ©ge that you have kept for ten years," I said, trying to be playful; "I must wear it, at least to-night." I knew that I had never looked worse, and I quite gloried in the fact. I saw Mr. Randolph from his seat near mother glance at me several times in a puzzled way, and Mr. Fanning, after one or two astonished glances, during which he took in the tout ensemble of the ugly robe, began to enter into a playful bear-like flirtation with Miss Armstrong. Dear brown barĂ©ge, what service it was doing me! I secretly determined that it should be my dinner dress every evening until it wore itself to rags. When the turquoise blue bows became too shabby, I might substitute them for magenta ones. I felt that I had suddenly found an opening out of my difficulty. If I ceased to appear attractive, Mr. Randolph and Mr. Fanning would cease to worry me, the rest of the boarders would accept me for what I was, and my Gordian knot would be cut. Little did I guess! It was by no means so easy to carry out my fixed determination as I had hoped. In the first place, poor darling mother nearly fretted herself into an illness on account of my evening dress. She absolutely cried when she saw me in it, and said that if I was determined to deteriorate in that way, she would give up the boarding-house and go to the cottage in the country without a moment's hesitation. After wearing the dress for three or four days I was forced, very much against my will, to put on one of my pretty black dresses, and the barĂ©ge made by Annie Starr resumed its place in my wardrobe. I determined to wear it now and then, however—it had already done me good service. I began to hope that neither Mr. Randolph nor Mr. Fanning thought me worth looking at when I appeared in it.
  • 65.
    On this evening,as I was dressing for dinner, I heard a wonderful bumping going on in the stairs. It was the noise made by very heavy trunks, trunks so large that they seemed scarcely able to be brought upstairs. They were arriving at the attics, too—they were entering the attic next to mine. Now that special attic had up to the present remained untenanted. It was the most disagreeable room in the house. Most of the attics were quite excellent, but this room had a decidedly sloping roof, and rather small windows, and the paper on the walls was ugly, and the accommodation scanty, and what those huge boxes were going to do there was more than I could tell. The boxes, however, entered that special attic, and then a bodily presence followed them briskly, a loud hearty voice was heard to speak. It said in cheerful tones— "Thank you, that will do nicely. A large can of hot water, please, and a couple more candles. Thanks. What hour did you say the company dined?" The reply was made in a low tone which I could not catch, and the attic door was shut. I was down in the drawing-room in my black dress—(how comfortable I felt in it, how hateful that brown barĂ©ge was, after all) —when the door was opened, and a large, stoutly-made woman, most richly dressed, came in. She had a quantity of grizzly grey hair, which was turned back from her expansive forehead; a cap of almost every colour in the rainbow bedizened her head, she wore diamond pendants in her ears, and had a flashing diamond brooch fastening the front of her dress. Her complexion was high, she had a broad mouth and a constant smile. She walked straight up to Jane Mullins. "Well," she said, "here I am. I have not unpacked my big trunk, as your servant said there was very little time before dinner. Please can you tell me when Albert will be in?"
  • 66.
    "Mr. Fanning generallycomes home about now," I heard Jane say. "Mrs. Fanning, may I introduce you to my dear young friend, Miss Wickham—Mrs. Wickham has not yet appeared." To my horror I saw Miss Mullins advancing across the drawing-room, accompanied by the stout woman; they approached to my side. "May I introduce Mrs. Fanning," said Miss Mullins—"Mr. Fanning's mother." "The mother of dear, godly Albert," said the stout lady. "I am proud to say I am the mother of one of the best of sons. I am right pleased to meet you, Miss Wickham. I may as well say at once that Albert Fanning, my dear and only son, has mentioned your name to me, and with an approval which would make your young cheeks blush. Yes, I am the last person to encourage vanity in the young, but I must repeat that if you knew all that Albert has said, you would feel that flutter of the heart which only joy brings forth. Now, shall we both sit in a cosy corner and enjoy ourselves, and talk about Albert until dinner is ready?" This treat was certainly not likely to cause my young cheeks to blush. On the contrary, I felt myself turning pale, and I looked round with a desperate intention of flying to Jane for protection, when the stout lady took one of my hands. "Ah," she said, "quite up to date, a slim young hand, and a slim young figure, and a slim young face, too, for that matter. All that Albert says is true, you are a very nice-looking girl. I should not say that you had much durance in you, that remains to be proved. But come, here's a cosy corner, I have a great deal to say." That hand of Mrs. Fanning's had a wonderfully clinging effect; it seemed to encircle my fingers something like an octopus, and she pulled me gently towards the corner she had in view, and presently had pinned me there, seating herself well in front of me, so that there was no possible escape.
  • 67.
    The rest ofthe boarders now entered the drawing-room. Mother amongst others made her appearance; she went to her accustomed corner, glanced at me, saw that I was in one of my black dresses, nodded approval, concluding in her dear mind that I had probably met some old friend in the extraordinary person who was shutting me into the corner, and took no further notice. Captain and Mrs. Furlong were well pleased to see that I was only talking to a woman, it did not matter at all to them who that woman was. And as to me I sat perfectly silent while Mrs. Fanning discoursed on Albert. She never for a single moment, I will say for her, turned the conversation into another channel. Albert was her theme, and she stuck to him with the pertinacity which would have done any leader of a debate credit. The debate was Albert. She intended before dinner was announced to give me a true insight into that remarkable man's most remarkable character. "Yes," she said, "what Albert thinks is always to the point. Since a child he never gave me what you would call a real heartache. Determined, self-willed he is; you look, the next time you see him, at his chin, you observe the cleft in the middle; there never was a chin like that yet without a mind according—a mind, so to speak, set on the duty ahead of it—a mind that is determined to conquer. That is Albert, that is my only, godly son. You observe, when you have an opportunity, Albert's eyes. Did you ever see anything more open than the way they look at you? He don't mind whether it hurts your feelings or not; if he wants to look at you, look he will." When she said this I nodded my head emphatically, for I had found this most disagreeable trait in Albert's eyes from the first moment I had been unfortunate enough to make his acquaintance. But Mrs. Fanning took my nod in high good humour. "Ah, you have observed it," she said, "and no wonder, no wonder. Now, when you get an opportunity, do pull him to pieces, feature by feature; notice his brow, how lofty it is; there's talent there, and t'aint what you would call a fly-away talent, such as those art talents
  • 68.
    that make mequite sick. He has no talent, thank Heaven, for painting or for poetry, or for any fal-lal of that kind, his talent lies in a sound business direction. Oh, he has made me roar, the way he talks of young authors and young artists, how they come to him with their wares, and how he beats them down. It's in Albert's brow where his talent for business lies. You mark his nose too, it's somewhat long and a little pointed, but it's the nose of a man who will make his mark; yes, he'll make his mark some day, and I have told him so over and over." Having gone through all Albert's features, she next proceeded to describe Albert's character, and then went on to Albert's future. From this it was an easy step to Albert's wife, and Albert's wife took up a great deal of the good woman's attention. "It is because I am thinking he'll soon be falling into the snares of matrimony that I have come to stay at 17 Graham Square," continued Mrs. Fanning. "And it's because I want my dear and godly son to get a wife who will be on the pattern of Solomon's virtuous woman that I have given up my home and broken up my establishment and come here. Now, Miss Wickham, my dear young lady, did you or did you not hear the noise of my boxes being brought upstairs?" "I certainly did," I replied. "Then you happen to occupy the bedroom next to mine?" "I do," I said. "That is very nice indeed, for often of an evening we will keep each other company and discourse on Albert, to the joy of both our hearts. The boxes are receptacles for my household gods, dear, those dear mementoes of the past, that I could not quite part with. Don't suppose for a moment that they are full of dresses, for although my taste is light and festive, Albert likes gay colours, he says they remind him of the sales of remnants in the autumn. Dear fellow, it was the most poetical thing he ever uttered, but he has
  • 69.
    said it onceor twice. I can show you my household treasures when you feel disposed to have an evening's real recreation. The burden of this house, and with so delicate a mother as your good Ma, must be heavy upon a young lass like you, but Albert tells me—but there! I won't say any more just now, for you'll blush, and I don't want you to blush, and I don't want to encourage those hopes that may never be realised. I may as well whisper, though, that Albert is looking out for a wife who will be a pattern of Solomon's virtuous woman, and when he finds her, why she'll be lucky, that's all I can say." Just then the pretty silver gong sounded, and people began to stand up preparatory to going down to dinner. It was difficult even then to move Mrs. Fanning, and for a wild moment I had a fear that I might be imprisoned behind her in the drawing-room all during dinner, while she still discoursed upon Albert and his attractions. Miss Mullins, however, came to the rescue. "Come, Miss Wickham," she cried, "we must lead the way," and accordingly Jane, my mother, and I went down first, and the different boarders followed us. To my infinite distress Mrs. Fanning, being a complete stranger, had her seat next mine. I had one comfort, however, she was better than Albert; and Albert, who arrived presently himself, found that he was seated next Miss Armstrong. He nodded across at his mother. "How do, old lady," he said, "glad to find you cosily established; everything all right, eh?" "Yes, Albert, my son," replied the good woman, "everything is all right, and I have been having a long conversation about you with my interesting young friend here, Miss Westenra Wickham. By-the-by, dear, would you kindly tell me how you got that outlandish name, I never heard it before, and I do not believe it belongs to the Christian religion." "I did not know there was anything heathenish about it," I could not help answering; "it happens to be my name, and I was fully baptized
  • 70.
    by it." "I willsee presently whether I can take to it," responded the old lady. "Soup? Yes, please. I will trouble you, my good girl, for (turning to the maid) a table-spoon; I never take soup with a dessert spoon. Thanks; that's better." Mrs. Fanning now gave me a few moments peace, and I found, to my great satisfaction, that she had an excellent appetite, and was also extremely critical with regard to her food. I introduced her to her next door neighbour, who happened to be a fat little woman, something like herself in build. They were both gourmands, and criticised adversely the meal to their mutual pleasure. Thus I had time to look around me, and to consider this new aspect of affairs. Things were scarcely likely to be more comfortable if Albert had now got his mother to plead his cause with me. He glanced at me several times during the meal, and once even favoured me with a broad wink—he was really intolerable. Meanwhile Miss Armstrong was all blushes and smirks. I heard her suggest to Mr. Fanning that she should go the next day to see him, and bring some of her drawings with her, and I heard him tell her in what he was pleased to call his brutal manner that he would not be at home, and if he were and she came would certainly not see her. This seemed to be considered a tremendous joke by Miss Armstrong, and her mother also joined in it, and gave Mr. Fanning a dig in the ribs, and told him that he was the soul of wit, and had the true spirit of heart. Meanwhile, Mr. Randolph, my mother, Captain and Mrs. Furlong, and the more refined portion of the establishment enjoyed themselves at the other end of the table. I saw Mr. Randolph glance down in my direction once or twice, and I am sure, although he was not able to judge of the difference, the fact of seeing me once more in my properly made black evening dress relieved his mind, for he looked quite contented, and turned in a cheerful manner to my mother, and when dinner was over, and we returned to the drawing-room, I was
  • 71.
    lucky enough tobe able to escape Mrs. Fanning and to go up to the other end of the room, where I seated myself close to mother, took hold of her hand, leant against her chair, and indulged in the luxury of talking to Mr. Randolph. He was in a very good humour, and suggested that we should make a party on the following evening to another play, which was then very much in vogue. "But not in the chocolate-coloured brougham with the pair of horses," I said. "We will have a cab from the nearest stand, if you prefer it," was his instant response. "I should much," I answered. "And we will not dine at the Cecil," he continued; "we can have a sort of high tea here before we start." "That I should also like infinitely better," I answered. "It shall be as you please," was his response. Then he began to tell us something of the play which we were about to see, and I forgot all about my discomforts, and enjoyed myself well. I was putting things in order in the drawing-room that night, for this was always one of my special duties, when Mr. Fanning, who had left the room a long time ago, came back. He came up to me holding his lighted candle in his hand. I started when I saw him. "Good night," I said coldly. "Pray don't go for a moment," he said. "I have come back here on the express chance of seeing you." "I cannot wait now, Mr. Fanning," I replied. "But I really must have an interview with you, it is of the highest importance,—when can I see you alone? When can you give me an hour of your time quite undisturbed?"
  • 72.
    "Never," I answeredbrusquely. "Now you will forgive me for saying that that is pure nonsense. If you will not promise me an hour of your own free will I shall take the present opportunity of speaking to you." "But I shall not stay," I answered with spirit, "and you cannot keep me here against my will. Mr. Fanning, I also will take the present opportunity of telling you that you and I have nothing in common, that I dislike your singling me out for special conversations of any kind, and that I hope in the future you will clearly understand that I do not wish you to do so." "Oh, that is all very fine," he said, "but come now; what have I done to make myself obnoxious? There is the old lady upstairs, she has taken no end of a fancy to you, she says you are the most charming and the prettiest girl she has ever seen, and what have you to say against my mother? Let me tell you that she has come to this house on purpose to make your acquaintance." "I have nothing whatever to say against your mother, Mr. Fanning, but I object to the subject of conversation which she chooses to occupy her time with while talking to me. I am not in the least interested in you, and I wish you and your mother clearly to understand this fact as quickly as possible." I do not think it was in the nature of Mr. Fanning ever to look crestfallen, or my present speech might have made him do so. He did not even change colour, but he looked at me out of those eyes which his mother had so vividly described, and after a moment said softly— "There will come a day when you will regret this. An honest heart is offered to you and you trample it in the dust, but there will come a day when you will be sorry. How do you think this establishment is working?"
  • 73.
    I was soastonished and relieved at his change of conversation that I said— "It seems to be going very well, don't you think so?" "It is going well for my purpose," he replied, and then he added, "it is working itself out in a way that will only spell one word—Ruin. Now you ponder on that. Take it as your night-cap, and see what sort of sleep you'll have, and when next I ask for a few moments' conversation perhaps you'll not say no. I will not keep you any longer for the present." He left the room, I heard his footsteps dying down the corridor, and the next instant he had slammed his bedroom door.
  • 74.
    CHAPTER XIV ANXIETY After hehad left me, and I was quite certain that I should not see him again that night, I went straight to Jane Mullins' room. Jane was generally up the last in the house, and I had not the slightest doubt I should still find her in her dinner dress, and ready for conversation. I had bidden mother good night long ago, and hoped she was sound asleep, but I did not mind disturbing Jane. I opened the door now and went in. As I expected, Jane was up; she was seated by the fire, she was looking into its depths, and did not turn round at once when I entered. The first thing she did when she became aware of the fact that there was some one else in the room besides herself, was to sigh somewhat deeply. Then she said in a low voice— "What if it all turns out a mistake?" and then she jumped to her feet and confronted me. "Yes, dear, yes," she said. "Oh, my dear Westenra, why aren't you in bed? It is very bad indeed for young people to be up so late. You will get quite worn and wrinkled. Let me tell you, my love, that we can never get youth back again, and we ought to prize it while we have it. How old are you, Westenra, my love?" "I shall be twenty-two my next birthday," was my answer.
  • 75.
    "Ah, yes, yes,quite young, in the beautiful prime of youth. Nevertheless, the bloom can be rubbed off, and then—well, it never comes back, dear. But go to bed, Westenra, don't stay up bothering your head. I see by that frown between your brows that you are going to say something which I would rather not listen to. Don't tell me to-night, Westenra, love." "I must tell you," I answered. "I have come to see you for the purpose. You are old enough, Jane, to bear the little disagreeable things I tell you now and then. You are our mainstay, our prop, in this establishment. I cannot go on without confiding in you, and you must listen to me." "Well, child, sit down, here is a comfortable chair." Jane got up and offered me her own chair. I did not take it. "What nonsense," I said, "sit down again. Here, this little hassock at your feet will suit me far better." I seated myself as I spoke, and laid my hand across Jane's knee. "Now, that is cosy," I said. She touched my arm as though she loved to touch it, and then she laid her firm, weather-beaten hand on my shoulder, and then, as if impelled by an unwonted impulse, she bent forward and kissed me on my cheek. "You are a very nice girl. Since I knew you life has been far pleasanter to me," said Jane Mullins. "I thank you for giving me a bit of love. Whatever happens I want you to remember that." "I do," I answered; "you have very little idea how much I care for you, Jane, and how immensely I respect you. There are, I think, very few women who would have acted as you have done. I am fully convinced there is a mystery in all your actions which has not yet been explained to me, but I have not come here to-night to talk about that. I have come here to ask you one or two questions, and to tell you one or two things, and my first question is this—Why were you sighing when I came in, and why did you murmur to
  • 76.
    yourself, 'What ifit all turns out a mistake?' Will you explain those words, Jane." "No," replied Jane stoutly, "for you were eavesdropping when you heard them, and there is no reason why I should explain what you had no right to listen to." "Thank you; you have answered me very sensibly, and I won't say another word on the subject of your sigh and your remarkable speech. But now to turn to the matter which has brought me to your room so late in the evening." "Well, dear, it is past midnight, and you know how early I am up. It is a little unreasonable of you; what has brought you, darling?" "Mr. Fanning has brought me." "Oh dear, oh dear, that tiresome man again," said Miss Mullins. "You don't like him yourself, do you, Jane?" "It is a great pity he is not different," said Jane, "for he is extremely well off." "O Jane! pray don't talk nonsense. Do you suppose that a person with the name of Fanning could have any interest whatever for me? Now, please, get that silly idea out of your head once for all." "Oh, as far as any use that there is in it, I have long ago got it out of my head," replied Jane; "but the thing to be considered is this, that he has not got it out of his head—nor has his mother—and that between them they can make things intensely disagreeable. Now, if Mr. Randolph was going to stay here, I should not have an anxious moment." "What do you mean?" I cried; "is Mr. Randolph going away?" A deep depression seemed suddenly to come over me; I could not quite account for it.
  • 77.
    "He is, dear;and it is because he must be absent for two or three months that I am really anxious. He will come back again; but sudden and important news obliges him to go to Australia. He is going in a fortnight, and it is that that frets him. You will be left to the tender mercies of Mr. Fanning and Mrs. Fanning, and you have got so much spirit you are sure to offend them both mortally, and then they will leave, and—oh dear, I do think that things are dark. My dear Westenra, I often wonder if we shall pull through after all." "That is what I want to speak to you about," I answered. "Mr. Fanning came into the drawing-room just now, and was very rude and very unlike a gentleman. I was alone there, and he said he had something to say to me in private, and, of course, I refused to listen. He wanted to insist on my granting him an interview, and said that he could compel me to listen if he chose. Think of any gentleman speaking like that!" "They don't mind what they say, nor what they do, when they're in love," muttered Jane. "I won't allow you to say that," I answered, springing to my feet; "the man is intolerable. Jane, he must go; there is no help for it." "He must stay, dear, and I cannot disclose all my reasons now." I stood clasping and unclasping my hands, and staring at Jane. "You knew beforehand, did you not, Westenra, that there would be disagreeables connected with this scheme?" "Of course I knew it; but I never did think that the disagreeables would resolve themselves into Mr. Fanning." "We never know beforehand where the shoe is going to pinch," remarked Jane in a sententious voice. "Well, I have something else to say," I continued. "Mr. Fanning was not only very unpleasant to me, but he told me something which I can scarcely believe. He said that our boarding-house, which
  • 78.
    seemed to begoing so well, was not going well at all. He said there was only one word to spell how it was going, and that word was RUIN. O Jane! it can't be true?" "Let us hope not," said Jane, but she turned very white. "I will tell you one thing, Westenra," she continued. "If you don't want to have utter ruin you must go on behaving as nicely as ever you can, bearing with every one, being gentle and considerate, and trying to make every one happy. And in especial, you must bear with Mr. Fanning and with Mrs. Fanning; you must be particularly civil to them both, for if they go others will go; and whatever happens, Westenra, remember your mother is not to be worried. I know what I am saying, your mother is not to be worried. Your mother must never guess that things are not as right as they should be. When Mr. Randolph comes back everything will be right, but during his absence we will have to go through rather a tight place; and Albert Fanning is the sort of person who might take advantage of us, and what you must do, my dear girl, is to be guileful." "Guileful!" I cried; "never." "But you must, my love, you must be guileful and wary; you need not give him a single straw to go upon, but at the same time you must be civil. There now, that is all I can tell you for the present. Go to bed, child, for I have to do the daily accounts, and must be up at six in the morning. It's that new cook, she frets me more than I can say, she don't do things proper; and I noticed that Mrs. Fanning sniffed at her soup instead of eating it this evening, and the turbot was not as fresh as it ought to be. Go to bed, Westenra, go to bed." I left the room. There was no use in staying any longer with Jane. She certainly had not reassured me. She seemed puzzled and anxious about the establishment; and why were not things going well? And what had Mr. Fanning to do with it; and why, why was Mr. Randolph going away?
  • 79.
    The next morningafter breakfast I went into the drawing-room for my usual task of dusting and arranging the furniture and refilling the vases with fresh flowers, when Mr. Randolph suddenly came in. "It will be best for you and Mrs. Wickham to meet me at the Criterion to-night," he said. "As you won't give me the opportunity of offering you dinner at the Cecil, that seems the next best thing to do. I have got a box in a good part of the house, so we need not be there more than a few minutes before it commences. I shall meet you at the entrance and conduct you to your seats." His manner showed some excitement, quite out of keeping with his ordinary demeanour, and I noticed that he scarcely glanced at me. His face was somewhat worn, too, in expression, and although he generally had himself in complete control, he now looked nearly as anxious and worried as Jane herself. He scarcely waited for my compliance with the arrangement he had proposed, but glancing at the door, spoke abruptly— "Something unexpected and very grievous has occurred, and I am obliged to leave England by the Smyrna, which sails on Saturday week." "Miss Mullins told me last night that you were going away," I replied. I also now avoided looking at him. I was playing with some large sprays of mimosa which had been sent in from the market. To my dying day I shall never forget how that mimosa seemed to slip about, and would not get into the best position in the vase in which I was placing it. "Effective," he said, as he watched my movements, "but it withers quickly; it wants its native air." "I suppose so," I answered. "Have you ever seen it growing?" "No; I have never been to the South."
  • 80.
    "You have agood deal to see. I hope some day——" He broke off. "Where are you going when you do go away?" I asked. "To Sydney first, perhaps to Melbourne." "It will be nice for you to leave England during our unpleasant winter weather." "There is nothing nice about my visit," he said; "I dislike going more than I have any words to express. In particular, I am sorry to leave your mother; but before I go I want"—he dropped his voice and came a step nearer. "What?" I asked. "I am anxious that your mother should see a doctor—a specialist, I mean. I am not satisfied with her condition." "But mother is really quite well," I said impulsively. "You have not known her long, Mr. Randolph; she never was really strong. She is quite as well as she ever was." "A specialist could assure us on that point, could he not?" was his reply. "I want Dr. Reade to give me a diagnosis of her case." "Dr. Reade," I cried. "Yes; I should like her to see him between now and the day when I must leave England. I cannot possibly be back under from four to five months, and if my mind can be relieved of a very pressing anxiety, you would not deny me the satisfaction, would you?" "But why should your mind be anxious?" I asked boldly. I looked full into his face as I spoke, and then I met a look which caused me to turn faint, and yet to feel happy, as I had never felt happy before. I lowered my eyes and looked out of the window. He gave a quick sigh, and then said suddenly— "How like your father you are."
  • 81.
    "My father? Butyou never knew him." "I never knew him, but I have often looked at his picture. Can you tell me how he won his V.C.?" "Saving a comrade, bringing one of his brother officers out of the thick of the fight; he received his own fatal wound in doing so. He did not survive the action two months." "A fine fellow! A splendid action," said Mr. Randolph, enthusiasm in his voice. "You will think over what I have said, and I will not keep you now. We shall meet at the Criterion this evening. Good-bye for the present."
  • 82.
    CHAPTER XV DR. READE Icannot recall anything about the play. I only know that we had excellent seats and a good view of the house, and that mother seemed to enjoy everything. As to Mr. Randolph, I doubt if he did enjoy that play. He was too much a man of the world to show any of his emotions, but I saw by a certain pallor round his mouth, and a rather dragged look about his eyes, that he was suffering, and I could not imagine why. I had always in my own mind made up a sort of story about Jim Randolph. He was one of the fortunate people of the earth; the good things of the world had fallen abundantly to his share. He was nice to look at and pleasant to talk to, and of course he had plenty of money. He could do what he pleased with his life. I had never associated him with sorrow or trial of any sort, and to see that look now in his eyes and round the corners of his somewhat sensitive and yet beautifully-cut mouth, gave me a new sensation with regard to him. The interest I felt in him immediately became accelerated tenfold. I found myself thinking of him instead of the play. I found myself anxious to watch his face. I even found, when once our eyes met (his grave and dark, mine, I daresay, bold enough and determined enough), that my heart beat fast, and the colour flew into my face; then, strange to say, the colour came into his face, dying his swarthy cheek just for a moment, but leaving it
  • 83.
    the next palerthan ever. He came a little nearer to me, however, and bending forward so that mother should not hear, said in a semi- whisper— "You have thought about what I said this morning?" "I have thought it over a good deal," I replied. "You think it can be managed?" "Dr. Anderson, mother's family physician, would do what you require, Mr. Randolph." "That is a good idea," he said. "Anderson can arrange a consultation. I will see him to-morrow, and suggest it." I did not say any more, for just then mother turned and said something to Mr. Randolph, and Mr. Randolph bent forward and talked to mother in that worshipping son-like way with which he generally addressed her. If mother had ever been blessed with a son, he could not have been more attentive nor sweeter than Jim Randolph was, and I found myself liking him more than ever, just because he was so good to mother, and my heart ached at the prospect of his enforced and long absence. So much did this thought worry me, that I could not help saying to him as we were leaving the theatre— "I am very sorry that you are going." "Is that true?" he said. His face lit up, his eyes sparkled; all the tired expression left his eyes and mouth. "Are you saying what you mean?" he asked. "I am most truly sorry. You have become indispensable to mother; she will miss you sorely." "And you—will you miss me?"
  • 84.
    I tried tosay "For mother's sake I will," but I did not utter the words. Mr. Randolph gave me a quick glance. "I have not told your mother yet that I am going," he said. "I wondered if you had," I replied. "I thought of telling her myself to-day." "Do not say anything until nearer the time," was his somewhat guarded response. "Ah! here comes the carriage." "So you did order the carriage after all," I said, seeing that the same neat brougham which he had used on the last occasion stopped the way. "You never forbade me to see you both home in the carriage," he said with a laugh. "Now then, Mrs. Wickham." Mother had been standing a little back out of the crowd. He went to her, gave her his arm, and she stepped into the carriage, just as if it belonged to her. Mother had always that way with Mr. Randolph's possessions, and sometimes her manner towards him almost annoyed me. What could it mean. Did she know something about him which I had never heard of nor guessed? The next day about noon Mr. Randolph entered Jane's sitting-room, where I often spent the mornings. "I have just come from Anderson's," he said. "He will make an appointment with Dr. Reade to see your mother to-morrow." "But on what plea?" I asked. "Mother is somewhat nervous. I am sure it would not be at all good for her to think that her indisposition was so great that two doctors must see her." "Anderson will arrange that," replied Mr. Randolph. "He has told your mother once or twice lately that he thinks her very weak, and would like her to try a new system of diet. Now Reade is a great specialist
  • 85.
    for diseases ofthe digestion. Both doctors will guard against any possible shock to your mother." "Well," I said somewhat petulantly, "I cannot imagine why you are nervous about her. She is quite as well as she ever was." He looked at me as if he meant to say something more, and I felt certain that he strangled a sigh which never came to the surface. The next moment he left the room, I looked round me in a state of bewilderment. In Jane's room was a bookcase, and the bookcase contained a heterogeneous mass of books of all sorts. Amongst others was a medical directory. I took it up now, and scarcely knowing why I did so, turned to the name of Reade. Dr. Reade's name was entered in the following way:— "Reade, Henry, M.D., F.R.C.P., consulting physician to the Brompton Hospital for Consumption, London, and to the Royal Hospital for Diseases of the Chest, Ventnor." I read these qualifications over slowly, and put the book back in its place. There was nothing whatever said of Dr. Reade's qualifications for treating that vast field of indigestion to which so many sufferers were victims. I resolved to say something to Jane. "What is it?" said Jane, as she came into the room. "What is fretting you now?" "Oh, nothing," I answered. "Dr. Reade must be a very clever physician." "First-class, of course. I am so pleased your mother is going to see him." "But I thought mother was suffering very much from weakness and want of appetite."
  • 86.
    "So she is,poor dear, and I am inventing quite a new sort of soup, which is partly digested beforehand, that I think she will fancy." "But I have been looking up Dr. Reade's name. He seems to be a great doctor for consumption and other diseases of the chest. There is no allusion to his extraordinary powers of treating people for indigestion." "Well, my dear, consumptives suffer more than most folks from indigestion. Now, don't you worry your head; never meet troubles half-way. I am extremely pleased that your mother is to see Dr. Reade." On the following morning mother herself told me that Dr. Reade was coming. "It is most unnecessary," she said, "and I told Dr. Anderson so. I was only telling him yesterday that I thought his own visits need not be quite so frequent. He is such a dear, kind man, that I do not like to hurt his feelings; but really, Westenra, he charges me so little that it quite goes to my heart. And now we have not our old income, this very expensive consulting physician is not required. I told Dr. Anderson so, but he has made up his mind. He says there is no use in working in the dark, and that he believes I should be much stronger if I ate more." Dr. Reade called in the course of the morning, and Dr. Anderson came with him. They stayed in mother's room for some little time, and then they both went out, and Jane Mullins had an interview with them first, and then she sent for me. "Dr. Anderson wants to speak to you, Westenra," she said. She rushed past me as she spoke, and I could not catch sight of her face, so I went into her little sitting-room, where both the doctors were waiting for me, and closed the door behind me. I was not at all anxious. I quite believed that mother's ailment was simply want of appetite and weakness, and I had never heard of any one dying just from those causes.
  • 87.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com