SlideShare a Scribd company logo
Java Java Java Objectoriented Problem Solving
3rd Edition Ralph Morelli Ralph Walde download
https://ebookbell.com/product/java-java-java-objectoriented-
problem-solving-3rd-edition-ralph-morelli-ralph-walde-42892438
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.
Objectoriented Programming From Problem Solving To Java Programming
Series 1st Edition Jose M Garrido
https://ebookbell.com/product/objectoriented-programming-from-problem-
solving-to-java-programming-series-1st-edition-jose-m-garrido-1691376
Java Programming Fundamentals Problem Solving Through Object Oriented
Analysis And Design 1st Edition Premchand S Nair
https://ebookbell.com/product/java-programming-fundamentals-problem-
solving-through-object-oriented-analysis-and-design-1st-edition-
premchand-s-nair-2406494
Java Methods Objectoriented Programming And Data Structures Third Ap
3rd Ap Maria Litvin
https://ebookbell.com/product/java-methods-objectoriented-programming-
and-data-structures-third-ap-3rd-ap-maria-litvin-59073076
Java Methods Objectoriented Programming And Data Structures 4th
Edition 4th Maria Litvin
https://ebookbell.com/product/java-methods-objectoriented-programming-
and-data-structures-4th-edition-4th-maria-litvin-60399372
Beginning Java 17 Fundamentals Objectoriented Programming In Java 17
3rd Ed Kishori Sharan
https://ebookbell.com/product/beginning-java-17-fundamentals-
objectoriented-programming-in-java-17-3rd-ed-kishori-sharan-36428050
Beginning Scala 3 A Functional And Objectoriented Java Language 3rd Ed
Pollak
https://ebookbell.com/product/beginning-scala-3-a-functional-and-
objectoriented-java-language-3rd-ed-pollak-38030352
The Java Workshop Learn Objectoriented Programming And Kickstart Your
Career In Software Development David Cuartielles
https://ebookbell.com/product/the-java-workshop-learn-objectoriented-
programming-and-kickstart-your-career-in-software-development-david-
cuartielles-46712648
Learn Objectoriented Java The Hard Way Graham Mitchell
https://ebookbell.com/product/learn-objectoriented-java-the-hard-way-
graham-mitchell-48927976
Java Programming A Step By Step Beginners Guide To Code With An
Objectoriented Program Megane Noel
https://ebookbell.com/product/java-programming-a-step-by-step-
beginners-guide-to-code-with-an-objectoriented-program-megane-
noel-47526070
Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph Walde
Java, Java, Java
Object-Oriented Problem Solving
Third Edition
R. Morelli and R. Walde
Trinity College
Hartford, CT
June 25, 2017
This work is licensed under a
Creative Commons Attribution 4.0 International License (CC BY 4.0).
This book was previously published by
Pearson Education, Inc.
Preface to the Open Source
Edition
Java, Java, Java, 3e was previously published by Pearson Education, Inc.
The first edition (2000) and the second edition (2003) were published by
Prentice-Hall. In 2010 Pearson Education, Inc. reassigned the copyright to
the authors, and we are happy now to be able to make the book available
under an open source license.
This PDF edition of the book is available under a Creative Commons
Attribution 4.0 International License, which allows the book to be used,
modified, and shared with attribution:
(https://creativecommons.org/licenses/by/4.0/).
– Ralph Morelli and Ralph Walde
– Hartford, CT
– December 30, 2016
i
ii
Preface to the Third Edition
We have designed this third edition of Java, Java, Java to be suitable for
a typical Introduction to Computer Science (CS1) course or for a slightly
more advanced Java as a Second Language course. This edition retains the
“objects first” approach to programming and problem solving that was
characteristic of the first two editions. Throughout the text we emphasize
careful coverage of Java language features, introductory programming
concepts, and object-oriented design principles.
The third edition retains many of the features of the first two editions,
including:
• Early Introduction of Objects
• Emphasis on Object Oriented Design (OOD)
• Unified Modeling Language (UML) Diagrams
• Self-study Exercises with Answers
• Programming, Debugging, and Design Tips.
• From the Java Library Sections
• Object-Oriented Design Sections
• End-of-Chapter Exercises
• Companion Web Site, with Power Points and other Resources
The In the Laboratory sections from the first two editions have been moved
onto the book’s Companion Web Site. Table 1 shows the Table of Contents
for the third edition.
What’s New in the Third Edition
The third edition has the following substantive changes:
• Although the book retains its emphasis on a “running example”
that is revisited in several chapters, the CyberPet examples have
been replaced with a collection of games and puzzle examples. The
CyberPet examples from earlier editions will be available on the
Companion Web Site.
iii
iv
Table 1: Table of Contents for the Third Edition.
Chapter Topic
Chapter 0 Computers, Objects, and Java (revised)
Chapter 1 Java Program Design and Development
Chapter 2 Objects: Defining, Creating, and Using
Chapter 3 Methods: Communicating with Objects (revised)
Chapter 4 Input/Output: Designing the User Interface (new)
Chapter 5 Java Data and Operators
Chapter 6 Control Structures
Chapter 7 Strings and String Processing
Chapter 8 Inheritance and Polymorphism (new)
Chapter 9 Arrays and Array Processing
Chapter 10 Exceptions: When Things Go Wrong
Chapter 11 Files and Streams
Chapter 12 Recursive Problem Solving
Chapter 13 Graphical User Interfaces
Chapter 14 Threads and Concurrent Programming
Chapter 15 Sockets and Networking (expanded)
Chapter 16 Data Structures: Lists, Stacks, and
Queues (revised and expanded)
• Chapters 0 (Computers, Objects, and Java) and 1 (Java Program De-
sign and Development) have been substantially reorganized and
rewritten. The new presentation is designed to reduce the pace
with which new concepts are introduced. The treatment of object-
oriented (OO) and UML concepts has also been simplified, and some
of the more challenging OO topics, such as polymorphism, have
been moved to a new Chapter 8.
• The new Java 1.5 Scanner class is introduced in Chapter 2 and is
used to perform simple input operations.
• Chapter 4 (Input/Output: Designing the User Interface) has been
completely written. Rather than relying primarily on applet inter-
faces, as in the second edition, this new chapter provides indepen-
dent introductions to both a command-line interface and a graphi-
cal user interface (GUI). Instructors can choose the type of interface
that best suits their teaching style. The command-line interface is
based on the BufferedReader class and is used throughout the
rest of the text. The GUI is designed to work with either graphi-
cal applications or applets. Both approaches are carefully presented
to highlight the fundamentals of user-interface design. The chapter
concludes with an optional section that introduces file I/O using the
new Scanner class.
• Much of the discussion of inheritance and polymorphism, which
was previously woven through the first five chapters in the second
edition, has been integrated into a new Chapter 8.
• An optional graphics track is woven throughout the text. Beginning
with simple examples in Chapters 1 and 2, this track also includes
v
some of the examples that were previously presented in Chapter 10
of the second edition.
• Chapter 15, on Sockets and Networking, is expanded to cover some
of the more advanced Java technologies that have emerged, includ-
ing servlets and Java Server Pages.
• Chapter 16, on Data Structures, has been refocused on how to use
data structures. It makes greater use of Java’s Collection Framework,
including the LinkedList and Stack classes and the List inter-
face. It has been expanded to cover some advanced data structures,
such as sets, maps, and binary search trees.
The Essentials Edition
An Essentials Edition of the third edition, which will include Chapters 0-
12, will be published as a separate title. The Essentials Edition will cover
those topics (Chapters 0-9) that are covered in almost all introductory
(CS1) courses, but it will also include topics (Exceptions, File I/O, and
Recursion) that many CS1 instructors have requested.
Why Start with Objects?
The Third Edition still takes an objects-early approach to teaching Java,
with the assumption that teaching beginners the “big picture” early gives
them more time to master the principles of object-oriented programming.
This approach seems now to have gained in popularity as more and more
instructors have begun to appreciate the advantages of the object-oriented
perspective.
Object Orientation (OO) is a fundamental problem solving and design
concept, not just another language detail that should be relegated to the
middle or the end of the book (or course). If OO concepts are introduced
late, it is much too easy to skip over them when push comes to shove in
the course.
The first time I taught Java in our CS1 course I followed the same ap-
proach I had been taking in teaching C and C++ — namely, start with the
basic language features and structured programming concepts and then,
somewhere around midterm, introduce object orientation. This approach
was familiar, for it was one taken in most of the textbooks then available
in both Java and C++.
One problem with this approach was that many students failed to get
the big picture. They could understand loops, if-else constructs, and arith-
metic expressions, but they had difficulty decomposing a programming
problem into a well-organized Java program. Also, it seemed that this
procedural approach failed to take advantage of the strengths of Java’s
object orientation. Why teach an object-oriented language if you’re going
to treat it like C or Pascal?
I was reminded of a similar situation that existed when Pascal was the
predominant CS1 language. Back then the main hurdle for beginners was
procedural abstraction — learning the basic mechanisms of procedure call
vi
and parameter passing and learning how to design programs as a collec-
tion of procedures. Oh! Pascal!, my favorite introductory text, was typical
of a “procedures early” approach. It covered procedures and parameters
in Chapter 2, right after covering the assignment and I/O constructs in
Chapter 1. It then covered program design and organization in Chap-
ter 3. It didn’t get into loops, if-else, and other structured programming
concepts until Chapter 4 and beyond.
Today, the main hurdle for beginners is the concept of object abstraction.
Beginning programmers must be able to see a program as a collection of
interacting objects and must learn how to decompose programming prob-
lems into well-designed objects. Object orientation subsumes both proce-
dural abstraction and structured programming concepts from the Pascal
days. Teaching objects-early takes a top-down approach to these three im-
portant concepts. The sooner you begin to introduce objects and classes,
the better the chances that students will master the important principles
of object orientation.
Java is a good language for introducing object orientation. Its object
model is better organized than C++. In C++ it is easy to “work around”
or completely ignore OO features and treat the language like C. In Java
there are good opportunities for motivating the discussion of object orien-
tation. For example, it’s almost impossible to discuss GUI-based Java ap-
plications without discussing inheritance and polymorphism. Thus rather
than using contrived examples of OO concepts, instructors can use some
of Java’s basic features — the class library, Swing and GUI components —
to motivate these discussions in a natural way.
Organization of the Text
The book is still organized into three main parts. Part I (Chapters 0-4) in-
troduces the basic concepts of object orientation and the basic features of
the Java language. Part II (Chapters 5-9) focuses on remaining language el-
ements, including data types, control structures, string and array process-
ing, and inheritance and polymorphism. Part III (Chapters 10-16) covers
advanced topics, including exceptions, file I/O, recursion, GUIs, threads
and concurrent programming, sockets and networking, data structures,
servlets, and Java Server Pages.
The first two parts make up the topics that are typically covered in an
introductory CS1 course. The chapters in Part III are self-contained and
can be selectively added to the end of a CS1 course if time permits.
The first part (Chapters 0 through 4) introduces the basic concepts of
object orientation, including objects, classes, methods, parameter passing,
information hiding, and a little taste of inheritance, and polymorphism.
The primary focus in these chapters is on introducing the basic idea that
an object-oriented program is a collection of objects that communicate and
cooperate with each other to solve problems. Java language elements are
introduced as needed to reinforce this idea. Students are given the basic
building blocks for constructing Java programs from scratch.
Although the programs in the first few chapters have limited function-
ality in terms of control structures and data types, the priority is placed
vii
Table 2: A one-semester course.
Weeks Topics Chapters
1 Object Orientation, UML Chapter 0
Program Design and Development Chapter 1
2-3 Objects and Class Definitions Chapter 2
Methods and Parameters Chapter 3
Selection structure (if-else)
4 User Interfaces and I/O Chapter 4
5 Data Types and Operators Chapter 5
6–7 Control Structures (Loops) Chapter 6
Structured Programming
8 String Processing (loops) Chapter 7
9 Inheritance and Polymorphism Chapter 8
10 Array Processing Chapter 9
11 Recursion Chapter 12
12 Advanced Topic (Exceptions) Chapter 10
13 Advanced Topic (GUIs) Chapter 11
Advanced Topic (Threads) Chapter 15
on how objects are constructed and how they interact with each other
through method calls and parameter passing.
The second part (Chapters 5 through 9) focuses on the remaining lan-
guage elements, including data types and operators (Chapter 5), control
structures (Chapter 6), strings (Chapter 7), and arrays (Chapter 9). It
also provides thorough coverage of inheritance and polymorphism, the
primary mechanisms of object orientation: (Chapter 8).
Part three (Chapters 10 through 16) covers a variety of advanced topics
(Table 1). Topics from these chapters can be used selectively depending
on instructor and student interest.
Throughout the book, key concepts are introduced through simple,
easy-to-grasp examples. Many of the concepts are used to create a set
of games, which are used as a running example throughout the text. Our
pedagogical approach focuses on design. Rather than starting of with lan-
guage details, programming examples are carefully developed with an
emphasis on the principles of object-oriented design.
Table2 provides an example syllabus from our one-semester CS1
course. Our semester is 13 weeks (plus one reading week during which
classes do not meet). We pick and choose from among the advanced topics
during the last two weeks of the course, depending on the interests and
skill levels of the students.
Ralph Morelli
June 25, 2017
viii
Contents
0 Computers, Objects, and Java 1
0.1 Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
0.2 What Is a Computer? . . . . . . . . . . . . . . . . . . . . . . . 2
0.3 Networks, the Internet and the World Wide Web . . . . . . . 4
0.4 Why Study Programming? . . . . . . . . . . . . . . . . . . . . 6
0.5 Programming Languages . . . . . . . . . . . . . . . . . . . . 7
0.6 Why Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
0.7 What Is Object-Oriented Programming? . . . . . . . . . . . . 11
1 Java Program Design and Development 23
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.2 Designing Good Programs . . . . . . . . . . . . . . . . . . . . 24
1.3 Designing a Riddle Program . . . . . . . . . . . . . . . . . . . 26
1.4 Java Language Elements . . . . . . . . . . . . . . . . . . . . . 34
1.5 Editing, Compiling, and Running a Java Program . . . . . . 48
1.6 From the Java Library: System and
PrintStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
2 Objects: Using, Creating, and Defining 61
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.2 Using String Objects . . . . . . . . . . . . . . . . . . . . . . 62
2.3 Drawing Shapes with a Graphics Object (Optional) . . . . 66
2.4 Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . 69
2.5 CASE STUDY: Simulating a Two-Person Game . . . . . . . . 76
2.6 From the Java Library: java.util.Scanner. . . . . . . . . 90
3 Methods: Communicating with Objects 101
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
3.2 Passing Information to an Object . . . . . . . . . . . . . . . . 102
3.3 Constructor Methods . . . . . . . . . . . . . . . . . . . . . . . 109
3.4 Retrieving Information from an Object . . . . . . . . . . . . . 114
3.5 Passing a Value and Passing a Reference . . . . . . . . . . . . 118
3.6 Flow of Control: Control Structures . . . . . . . . . . . . . . . 121
3.7 Testing an Improved OneRowNim . . . . . . . . . . . . . . . . 130
3.8 From the Java Library java.lang.Object . . . . . . . . . 135
3.9 Object-Oriented Design: Inheritance and Polymorphism . . 136
3.10 Drawing Lines and Defining Graphical Methods (Optional) 138
4 Input/Output: Designing the User Interface 149
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
ix
x CONTENTS
4.2 The User Interface . . . . . . . . . . . . . . . . . . . . . . . . . 150
4.3 A Command-Line Interface . . . . . . . . . . . . . . . . . . . 151
4.4 A Graphical User Interface (GUI) . . . . . . . . . . . . . . . . 160
4.5 Case Study: The One Row Nim Game . . . . . . . . . . . . . 176
4.6 From the Java Library: java.io.File
and File Input (Optional) . . . . . . . . . . . . . . . . . . . . . 183
5 Java Data and Operators 197
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
5.2 Boolean Data and Operators . . . . . . . . . . . . . . . . . . . 199
5.3 Numeric Data and Operators . . . . . . . . . . . . . . . . . . 205
5.4 From the Java Library java.lang.Math . . . . . . . . . . . 216
5.5 Numeric Processing Examples . . . . . . . . . . . . . . . . . 217
5.6 From the Java Library
java.text.NumberFormat . . . . . . . . . . . . . . . . . . 229
5.7 Character Data and Operators . . . . . . . . . . . . . . . . . . 231
5.8 Example: Character Conversions . . . . . . . . . . . . . . . . 235
5.9 Problem Solving = Representation + Action . . . . . . . . . . 237
6 Control Structures 241
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
6.2 Flow of Control: Repetition Structures . . . . . . . . . . . . . 242
6.3 Counting Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 243
6.4 Example: Car Loan . . . . . . . . . . . . . . . . . . . . . . . . 252
6.5 Graphics Example: Drawing a Checkerboard . . . . . . . . . 255
6.6 Conditional Loops . . . . . . . . . . . . . . . . . . . . . . . . 259
6.7 Example: Computing Averages . . . . . . . . . . . . . . . . . 266
6.8 Example: Data Validation . . . . . . . . . . . . . . . . . . . . 270
6.9 Principles of Loop Design . . . . . . . . . . . . . . . . . . . . 270
6.10 The switch Multiway Selection Structure . . . . . . . . . . . 273
6.11 OBJECT-ORIENTED DESIGN:
Structured Programming . . . . . . . . . . . . . . . . . . . . . 277
7 Strings and String Processing 297
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
7.2 String Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
7.3 Finding Things Within a String . . . . . . . . . . . . . . . . . 304
7.4 Example: Keyword Search . . . . . . . . . . . . . . . . . . . . 306
7.5 From the Java Library: java.lang.StringBuffer . . . . . . . . . 308
7.6 Retrieving Parts of Strings . . . . . . . . . . . . . . . . . . . . 310
7.7 Example: Processing Names and Passwords . . . . . . . . . 312
7.8 Processing Each Character in a String . . . . . . . . . . . . 313
7.9 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . 317
7.10 From the Java Library:
java.util.StringTokenizer . . . . . . . . . . . . . . . . . . . . . 323
7.11 Handling Text in a Graphics Context
(Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
8 Inheritance and Polymorphism 337
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
8.2 Java’s Inheritance Mechanism . . . . . . . . . . . . . . . . . . 338
CONTENTS xi
8.3 Abstract Classes, Interfaces,
and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . 347
8.4 Example: A Toggle Button . . . . . . . . . . . . . . . . . . . . 353
8.5 Example: The Cipher Class Hierarchy . . . . . . . . . . . . . 357
8.6 Case Study: A Two Player Game Hierarchy . . . . . . . . . . 363
8.7 Principles Of Object-Oriented Design . . . . . . . . . . . . . 384
9 Arrays and Array Processing 393
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
9.2 One-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 394
9.3 Simple Array Examples . . . . . . . . . . . . . . . . . . . . . 401
9.4 Example: Counting Frequencies of Letters . . . . . . . . . . . 403
9.5 Array Algorithms: Sorting . . . . . . . . . . . . . . . . . . . . 406
9.6 Array Algorithms: Searching . . . . . . . . . . . . . . . . . . 414
9.7 Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 417
9.8 Multidimensional Arrays (Optional) . . . . . . . . . . . . . . 426
9.9 OBJECT-ORIENTED DESIGN:
Polymorphic Sorting (Optional) . . . . . . . . . . . . . . . . . 428
9.10 From the Java Library: java.util.Vector . . . . . . . . . . . . . 430
9.11 Case Study: An N-Player Computer Game . . . . . . . . . . 431
9.12 A GUI-Based Game (Optional Graphics) . . . . . . . . . . . . 437
10 Exceptions: When Things Go Wrong 459
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
10.2 Handling Exceptional Conditions . . . . . . . . . . . . . . . . 460
10.3 Java’s Exception Hierarchy . . . . . . . . . . . . . . . . . . . 462
10.4 Handling Exceptions Within a Program . . . . . . . . . . . . 466
10.5 Error Handling and Robust
Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . 477
10.6 Creating and Throwing Your Own
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.7 From the Java Library: JOptionPane . . . . . . . . . . . . . 489
11 Files and Streams: Input/Output Techniques 499
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
11.2 Streams and Files . . . . . . . . . . . . . . . . . . . . . . . . . 500
11.3 CASE STUDY: Reading and Writing Text Files . . . . . . . . 505
11.4 The File Class . . . . . . . . . . . . . . . . . . . . . . . . . . 518
11.5 Example: Reading and Writing Binary Files . . . . . . . . . . 521
11.6 Object Serialization: Reading and Writing Objects . . . . . . 530
11.7 From the Java Library
javax.swing.JFileChooser . . . . . . . . . . . . . . . . 535
11.8 Using File Data in Programs . . . . . . . . . . . . . . . . . . . 536
12 Recursive Problem Solving 545
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
12.2 Recursive Definition . . . . . . . . . . . . . . . . . . . . . . . 549
12.3 Recursive String Methods . . . . . . . . . . . . . . . . . . . . 551
12.4 Recursive Array Processing . . . . . . . . . . . . . . . . . . . 563
12.5 Example: Drawing (Recursive) Fractals . . . . . . . . . . . . 569
xii CONTENTS
12.6 OBJECT-ORIENTED DESIGN:
Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
12.7 OBJECT-ORIENTED DESIGN:
Recursion or Iteration? . . . . . . . . . . . . . . . . . . . . . . 574
12.8 From the Java Library:
javax.swing.JComboBox . . . . . . . . . . . . . . . . . . . . . 577
13 Graphical User Interfaces 591
13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
13.2 Java GUIs: From AWT to Swing . . . . . . . . . . . . . . . . . 592
13.3 The Swing Component Set . . . . . . . . . . . . . . . . . . . . 595
13.4 OBJECT-ORIENTED DESIGN:
Model-View-Controller Architecture . . . . . . . . . . . . . . 596
13.5 The Java Event Model . . . . . . . . . . . . . . . . . . . . . . 598
13.6 CASE STUDY: Designing a Basic GUI . . . . . . . . . . . . . 602
13.7 Containers and Layout Managers . . . . . . . . . . . . . . . . 614
13.8 Checkboxes, Radio Buttons, and Borders . . . . . . . . . . . 620
13.9 Menus and Scroll Panes . . . . . . . . . . . . . . . . . . . . . 629
14 Threads and Concurrent Programming 643
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
14.2 What Is a Thread? . . . . . . . . . . . . . . . . . . . . . . . . . 644
14.3 From the Java Library: java.lang.Thread . . . . . . . . . 648
14.4 Thread States and Life Cycle . . . . . . . . . . . . . . . . . . . 654
14.5 Using Threads to Improve
Interface Responsiveness . . . . . . . . . . . . . . . . 656
14.6 CASE STUDY: Cooperating Threads . . . . . . . . . . . . . . 664
14.7 CASE STUDY: The Game of Pong . . . . . . . . . . . . . . . . 679
15 Sockets and Networking 693
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
15.2 An Overview of Networks . . . . . . . . . . . . . . . . . . . . 694
15.3 Using Multimedia Network Resources for a Graphical Pro-
gram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
15.4 From the Java Library: java.net.URL . . . . . . . . . . . . 701
15.5 The Slide Show Program . . . . . . . . . . . . . . . . . . . . . 704
15.6 Adding Text Network Resources for an
Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
15.7 Client/Server Communication via Sockets . . . . . . . . . . 719
15.8 CASE STUDY: Generic Client/Server Classes . . . . . . . . . 724
15.9 Playing One Row Nim Over the Network . . . . . . . . . . . 732
15.10Java Network Security Restrictions . . . . . . . . . . . . . . . 741
15.11Java Servlets and Java Server Pages . . . . . . . . . . . . . . . 742
16 Data Structures: Lists, Stacks, and Queues 757
16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
16.2 The Linked List Data Structure . . . . . . . . . . . . . . . . . 758
16.3 OBJECT-ORIENTED DESIGN:
The List Abstract Data Type (ADT) . . . . . . . . . . . . . . . 770
16.4 The Stack ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
16.5 The Queue ADT . . . . . . . . . . . . . . . . . . . . . . . . . . 778
CONTENTS xiii
16.6 From the Java Library: The Java Collections Framework
and Generic Types . . . . . . . . . . . . . . . . . . . . . . . . 782
16.7 Using the Set and Map Interfaces . . . . . . . . . . . . . . . 785
16.8 The Binary Search Tree Data Structure . . . . . . . . . . . . . 789
A Coding Conventions 801
B The Java Development Kit 809
C The ASCII and Unicode Character Sets 819
D Java Keywords 821
E Operator Precedence Hierarchy 823
F Java Inner Classes 825
G Java Autoboxing and Enumeration 831
H Java and UML Resources 837
xiv CONTENTS
OBJECTIVES
After studying this chapter, you will
• Understand basic computer terminology that will be used throughout the book.
• Become familiar with the notion of programming.
• Understand why Java is a good introductory programming language.
• Become familiar with Java objects and classes.
• Know some of the principles of the object-oriented programming approach.
OUTLINE
0.1 Welcome
0.2 What Is a Computer?
Special Topic: Processors Then and Now
0.3 Networks, the Internet and the World Wide Web
0.4 Why Study Programming?
0.5 Programming Languages
0.6 Why Java?
0.7 What Is Object-Oriented Programming?
Chapter Summary
Exercises
Chapter 0
Computers, Objects, and
Java
1
2 CHAPTER 0 • Computers, Objects, and Java
0.1 Welcome
Welcome to Java, Java, Java, a book that introduces you to object-oriented
programming using the Java language. When considering the purpose
of this text, three important questions might come to mind: Why study
programming? Why study Java? What is object-oriented programming?
This chapter will address these questions. First, we provide a brief in-
troduction to computers and the Internet and World Wide Web (WWW).
Then, we address why someone would study programming and we ex-
amine types of programming languages. We introduce the Java program-
ming language and conclude the chapter by exploring object-oriented pro-
gramming principles and how Java is an object-oriented programming
language.
0.2 What Is a Computer?
A computer is a machine that performs calculations and processes infor-
mation. A computer works under the control of a computer program, a
set of instructions that tell a computer what to do. Hardware refers to the
electronic and mechanical components of a computer. Software refers to
the programs that control the hardware.
A general-purpose computer of the sort that we will be programming can
store many different programs in its memory. That is what gives it the
ability to perform a wide variety of functions, from word processing to
browsing the Internet. This is in contrast to a special-purpose computer, such
as the one that resides in your microwave oven or the one that controls
your digital watch or calculator. These types of computers contain control
programs that are fixed and cannot be changed.
A computer’s hardware is organized into several main subsystems or
components (Fig. 1).
Figure 1: A diagram of the main
functional components in a com-
puter system. The arrows indicate
the flow of information between
various components.
Secondary
Storage
Main Memory
Input Devices
Keyboard
Mouse
Optical
Scanner
Output Devices
Printer
Monitor
Audio
Speakers
Central
Processing
Unit
(CPU)
Disk Drive
CD-ROM
DVD
• Output devices provide a means by which information held in the com-
puter can be displayed in some understandable or usable form. Com-
mon output devices include printers, monitors, and audio speakers.
SECTION 0.2 • What Is a Computer? 3
• Input devices bring data and information into the computer. Some of
the more common input devices are the keyboard, mouse, microphone,
and scanner.
• Primary memory or main memory of a computer is used to store both
data and programs. This type of memory, which is often called RAM,
short for Random Access Memory, is built entirely out of electronic
components—integrated circuit chips—which makes it extremely fast.
A computer’s main memory is volatile, which means that any informa-
tion stored in it is lost when the computer’s power is turned off. In a
sense, main memory acts as the computer’s scratch pad, storing both
programs and data temporarily while a program is running.
• Secondary storage devices are used for long-term or permanent stor-
age of relatively large amounts of information. These devices include
hard drives or magnetic disks, compact disks (CDs), digital video disks
(DVDs), and magnetic tapes. All of these devices are non-volatile, mean-
ing that they retain information when the computer’s power is turned
off. Compared to a computer’s primary memory, these devices are
relatively slow.
• The central processing unit (CPU) is the computer’s main engine. The
CPU is the computer’s microprocessor, such as the Intel Pentium pro-
cessor, which serves as the foundation for most Windows PCs, or the
Power-PC processor, which serves as the foundation for Macintosh
computers. The CPU is designed to perform the fetch-execute cycle, Fetch-execute cycle
whereby it repeatedly gets the next machine instruction from memory
and executes it. Under the direction of computer programs (software),
the CPU issues signals that control the other components that make up
the computer system. One portion of the CPU, known as the arithmetic-
logic unit (ALU), performs all calculations, such as addition and sub-
traction, and all logical comparisons, such as when one piece of data is
compared to another to determine if they are equal.
There are two main types of software:
• Application software refers to programs designed to provide a particular
task or service, such as word processors, computer games, spreadsheet
programs, and Web browsers.
• System software includes programs that perform the basic operations
that make a computer usable. For example, an important piece of
system software is the operating system, which contains programs that
manage the data stored on the computer’s disks.
An operating system assists application software in performing tasks
that are considered primitive or low-level, such as managing the com-
puter’s memory and its input and output devices.
Another important thing that the operating system does is to serve as
an interface between the user and the hardware. The operating system
determines how the user will interact with the system, or conversely, how
the system will look and feel to the user. For example, in command-line
systems, such as Unix and DOS (short for Disk Operating System), a pro-
gram is run by typing its name on the command line. By contrast, in
4 CHAPTER 0 • Computers, Objects, and Java
graphically based systems, such as Windows and Macintosh, a program
is run by clicking on its icon with the mouse. Thus, this “point-and-click”
interface has a totally different “look and feel” but does the same thing.
Special Topic: Processors Then and Now
To give you some idea of how rapidly computer hardware technology
has advanced, let’s compare the first digital processor with one of today’s
models.
The ENIAC (which stood for Electronic Numerical Integrator and Cal-
culator) was developed in 1946 at the University of Pennsylvania primar-
ily for calculating ballistic trajectories for the U.S. Army. ENIAC occupied
more than 640 square feet of floor space and weighed nearly 30 tons. In-
stead of the integrated circuits or chip technology used in today’s comput-
ers, ENIAC’s digital technology was based on over 17,000 vacuum tubes.
ENIAC, which could perform around 300 multiplications per second, ran
more than 500 times faster than other computing machines of that day and
age. To program the ENIAC, you would have to manipulate hundreds of
cables and switches. It took two or three days for a team of several pro-
grammers, most of whom were young women, to set up a single program
that would then run for a few seconds.
One of today’s most advanced and powerful processors for desktop
computers is Intel’s Pentium IV processor. This chip contains 42 million
transistors and runs at speeds over 3 GHz (3 gigahertz or 3 billion cycles
per second). The Pentium processor is small enough to fit in a space the
size of your pinky finger’s fingernail. Despite its size, it executes millions
of instructions per second, thereby enabling it to support a huge range of
multimedia applications, including three-dimensional graphics, stream-
ing audio and video, and speech recognition applications. To write pro-
grams for the Pentium, you can choose from a wide range of high-level
programming languages, including the Java language.
0.3 Networks, the Internet and the World Wide
Web
Most personal computers contain software that enables them to be con-
nected to various-sized networks of computers. Networks allow many in-
dividual users to share costly computer resources, such as a high-speed
printer or a large disk drive or application server that is used to store and
distribute both data and programs to the computers on the network. Net-
works can range in size from local area networks (LANs), which connect
computers and peripherals over a relatively small area, such as within a
lab or a building, through wide area networks (WANs), which can span large
geographic areas, such as cities and nations.
Client/server computing Application servers are just one example of client/server computing, a
computing approach made possible by networks. According to this ap-
proach, certain computers on the network are set up as servers, which pro-
vide certain well-defined services to client computers. For example, one
computer in a network may be set up as the email server, with the responsi-
SECTION 0.3 • Networks, the Internet and the World Wide Web 5
bility of sending, receiving, and storing mail for all users on the network.
To access their email on the email server, individual users employ client
application software that resides on their desktop computers, such as Out-
look Express or Eudora or Pine. Similarly, another server may be set up as
a Web server, with the responsibility of storing and serving up Web pages
for all the users on the network. Users can run Web browsers, another type
of client software, to access Web pages on the server. Java is particularly
well suited for these types of networked or distributed applications, where
part of the application software resides on a server and part resides on the
client computer.
The Internet (with a capital I) is a network of networks whose geo-
graphical area covers the entire globe. The World Wide Web (WWW) is
another example of distributed, client/server computing. The WWW is
not a separate physical network. Rather it is a subset of the Internet that
uses the HyperText Transfer Protocol (HTTP). A protocol is a set of rules
and conventions that govern how communication takes place between
two computers. HTTP is a multimedia protocol, which means that it
supports the transmission of text, graphics, sound, and other forms of
information. Certain computers within a network run special software
that enables them to play the role of HTTP (or Web) servers. They store
Web documents and are capable of handling requests for documents
from client browser applications. The servers and clients can be located
anywhere on the Internet.
The documents stored on Web servers are encoded in a special text-
based language known as HyperText Markup Language, or HTML. Web
browsers, such as Netscape’s Navigator and Microsoft’s Internet Explorer,
are designed to interpret documents coded in this language. The language
itself is very simple. Its basic elements are known as tags, which consist
of certain keywords or other text contained within angle brackets, < and
>. For example, if you wanted to italicize text on a Web page, you would
enclose it between the < I > and < /I > tags. Thus, the following HTML
code

$I$ I t a l i c font$/I$ can be used for $I$emphasis$/I$ .
would be displayed by the Web browser as
Italic font can be used for emphasis.
When you use a Web browser to surf the Internet, you repeatedly instruct
your browser to go to a certain location and retrieve a page that is encoded
in HTML. For example, if you typed the following URL (Uniform Resource
Locator)

http : //www. prenhall . com/morelli/index . html
into your browser, the browser would send a message to the Web server
www located in the prenhall.com domain—the prenhall portion of
this address specifies Prentice Hall and the com portion specifies the com-
mercial domain of the Internet—requesting that the document named
index.html in the morelli directory be retrieved and sent back to your
6 CHAPTER 0 • Computers, Objects, and Java
Figure 2: WWW: The client’s
browser requests a page from a
Web server. When the HTML doc-
ument is returned, it is interpreted
and displayed by the browser.
Display
Internet
Send a document
Request a document
HTML
document
Server
Client
HTTP
software
Text
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
Browser
software
computer (Fig. 2). The beauty of the Web is that it is possible to embed
text, sound, video, and graphics within an HTML document, making it
possible to download a wide range of multimedia resources through this
(relatively) simple mechanism.
The Web has begun to change business, entertainment, commerce, and
education. The fact that it is possible to download computer games and
other application software from the Web is changing the way software and
other digital products are purchased and distributed. Similarly, as noted
earlier, many businesses have begun to organize their information systems
into intranets—private networks that implement the HTTP protocol. Cur-
rently, one of the biggest areas of development on the Web is commerce.
As consumers become more comfortable that credit-card information can
be securely transmitted over the Web (as it can over a telephone), the Web
will explode as a marketing medium as powerful, perhaps, as television
is today. Because Java has been designed to support secure, distributed,
networked applications, it is ideally suited to be used as the language for
these types of applications.
0.4 Why Study Programming?
A computer program is a set of instructions that directs the computer’s
behavior. Computer programming is the art and science of designing and
writing programs. Years ago it was widely believed that entrance into
the computer age would require practically everyone to learn how to pro-
gram. But this did not prove to be true. Today’s computers come with so
much easy-to-use software that knowing how to use a computer no longer
requires programming skills.
Another reason to study programming might be to enter into a career
as a computer scientist. However, although programming is one of its
primary tools, computer science is a broad and varied discipline, which
ranges from engineering subjects, such as processor design, to mathemat-
ical subjects, such as performance analysis. There are many computer sci-
entists who do little or no programming as part of their everyday work.
If you plan to major or minor in computer science, you will certainly
learn to program, but good careers in the computing field are available
to programmers and nonprogrammers alike.
SECTION 0.5 • Programming Languages 7
One of the best reasons to study programming is because it is a cre-
ative and enjoyable problem-solving activity. This book will teach you to
develop well-designed solutions to a range of interesting problems. One
of the best things about programming is that you can actually see and
experience your solutions as running programs. As many students have
indicated, there’s really nothing like the kick you get from seeing your
program solving a problem you’ve been struggling with. Designing and
building well-written programs provides a powerful sense of accomplish-
ment and satisfaction. What’s more, Java is a language that makes pro-
gramming even more fun, because once they’re finished, many Java pro-
grams can be posted on the World Wide Web (WWW) for all the world to
see!
0.5 Programming Languages
Most computer programs today are written in a high-level language, such
as Java, C, C++, or FORTRAN. A programming language is considered
high level if its statements resemble English-language statements. For
example, all of the languages just mentioned have some form of an “if”
statement, which says, “if some condition holds, then take some action.”
Computer scientists have invented hundreds of high-level program-
ming languages, although relatively few of these have been put to prac-
tical use. Some of the widely used languages have special features that
make them suitable for one type of programming application or another.
COBOL (COmmon Business-Oriented Language), for example, is still
widely used in commercial applications. FORTRAN (FORmula TRANsla-
tor) is still preferred by some engineers and scientists. C and C++ are still
the primary languages used by operating system programmers.
In addition to having features that make them suitable for certain types
of applications, high-level languages use symbols and notation that make
them easily readable by humans. For example, arithmetic operations in
Java make use of familiar operators such as “+” and “−” and “/”, so that
arithmetic expressions look more or less the way they do in algebra. So,
to take the average of two numbers, you might use the expression

( a + b ) / 2
The problem is that computers cannot directly understand such expres-
sions. In order for a computer to run a program, the program must first
be translated into the computer’s machine language, which is the language
understood by its CPU or microprocessor. Each type of microprocessor
has its own particular machine language. That’s why when you buy soft-
ware it runs either on a Macintosh, which uses the Power-PC chip, or on a
Windows machine, which uses the Pentium chip, but not on both. When a Platform independence
program can run on just one type of chip, it is known as platform dependent.
In general, machine languages are based on the binary code, a two-
valued system that is well suited for electronic devices. In a binary repre-
sentation scheme, everything is represented as a sequence of 1’s and 0’s,
which corresponds closely to the computer’s electronic “on” and “off”
states. For example, in binary code, the number 13 would be repre-
8 CHAPTER 0 • Computers, Objects, and Java
sented as 1101. Similarly, a particular address in the computer’s memory
might be represented as 01100011, and an instruction in the computer’s
instruction set might be represented as 001100.
The instructions that make up a computer’s machine language are very
simple and basic. For example, a typical machine language might in-
clude instructions for ADD, SUBTRACT, DIVIDE, and MULTIPLY, but it
wouldn’t contain an instruction for AVERAGE. In most cases, a single in-
struction, called an opcode, carries out a single machine operation on one
or more pieces of data, called its operands. Therefore, the process of av-
eraging two numbers would have to be broken down into two or more
steps. A machine language instruction itself might have something sim-
ilar to the following format, in which an opcode is followed by several
operands, which refer to the locations in the computer’s primary memory
where the data are stored. The following instruction says ADD the num-
ber in LOCATION1 to the number in LOCATION2 and store the result in
LOCATION3:
Opcode Operand 1 Operand 2 Operand 3
011110 110110 111100 111101
(ADD) (LOCATION 1) (LOCATION 2) (LOCATION 3)
Given the primitive nature of machine language, an expression like
(a + b)/2 would have to be translated into a sequence of several machine
language instructions that, in binary code, might look as follows:

011110110110111100111101
000101000100010001001101
001000010001010101111011
In the early days of computing, before high-level languages were de-
veloped, computers had to be programmed directly in their machine
languages, an extremely tedious and error-prone process. Imagine how
difficult it would be to detect an error that consisted of putting a 0 in the
preceding program where a 1 should occur!
Fortunately, we no longer have to worry about machine languages, be-
cause special programs can be used to translate a high-level or source
code program into machine language code or object code, which is the
only code that can be executed or run by the computer. In general, a pro-
gram that translates source code to object code is known as a translator
(Fig. 3). Thus, with suitable translation software for Java or C++ we can
write programs as if the computer could understand Java or C++ directly.
Source code translators come in two varieties. An interpreter trans-
lates a single line of source code directly into machine language and ex-
ecutes the code before going on to the next line of source code. A com-
piler translates the entire source code program into executable object code,
which means that the object code can then be run directly without further
translation.
There are advantages and disadvantages to both approaches. Inter-
preted programs generally run less efficiently than compiled programs,
SECTION 0.6 • Why Java? 9
High-level
language
Translator
software
Machine
language
Source
code
Object
code
(a+b)/2
000110101
101000110
101000110
Figure 3: Translator software
translates high-level source code to
machine language object code.
because they must translate and execute each line of the program before
proceeding to the next line. If a line of code is repeated, an interpreter
would have to translate the line each time it is encountered. By contrast,
once compiled, an object program is just executed without any need for
further translation. It is also much easier to refine compiled code to make
it run more efficiently. But interpreters are generally quicker and easier
to develop and provide somewhat better error messages when things go
wrong. Some languages that you may have heard of, such as BASIC, LISP,
and Perl, are mostly used in interpreted form, although compilers are also
available for these languages. Programs written in COBOL, FORTRAN,
C, C++, and Pascal are compiled. As we will see in the next section,
Java programs use both compilation and interpretation in their translation
process.
0.6 Why Java?
Originally named “Oak” after a tree outside the office of its developer,
James Goslin, Java is a relatively young programming language. It was
initially designed by Sun Microsystems in 1991 as a language for em-
bedding programs into electronic consumer devices, such as microwave
ovens and home security systems. However, the tremendous popularity
of the Internet and the World Wide Web (WWW) led Sun to recast Java as
a language for embedding programs into Web-based applications. As you
recall, the Internet is a global computer network, and the WWW is that
portion of the network that provides multimedia access to a vast range of
information. Java has become one of the most important languages for
Web and Internet applications.
Java has also generated significant interest in the business community,
where it is has proved to have tremendous commercial potential. In addi-
tion to being a useful tool for helping businesses to promote their products
and services over the Internet, Java is also a good language for distribut-
ing software and providing services to employees and clients on private
corporate networks or intranets.
Because of its original intended role as a language for programming mi-
croprocessors embedded in consumer appliances, Java has been designed
with a number of interesting features:
• Java is object oriented. Object-oriented languages divide programs
into separate modules, called objects, that encapsulate the program’s
data and operations. Thus, object-oriented programming (OOP) and
object-oriented design (OOD) refer to a particular way of organizing pro- Object-oriented Languages
10 CHAPTER 0 • Computers, Objects, and Java
grams, one which is rapidly emerging as the preferred approach for
building complex software systems. Unlike the C++ language, in which
object-oriented features were grafted onto the C language, Java was
designed from scratch as an object-oriented language.
• Java is robust, meaning that errors in Java programs don’t cause system
crashes as often as errors in other programming languages. Certain
features of the language enable many potential errors to be detected
before a program is run.
• Java is platform independent. A platform, in this context, is just a particu-
Platform independence
lar kind of computer system, such as a Macintosh or Windows system.
Java’s trademark is “Write once, run anywhere.” This means that a Java
program can be run without changes on different kinds of computers.
This is not true for other high-level programming languages. This porta-
bility – the ability to run on virtually any platform – is one reason that
Java is well suited for WWW applications.
• Java is a distributed language, which means that its programs can be
designed to run on computer networks. In addition to the language it-
self, Java comes with an extensive collection of code libraries—software
that has been designed to be used directly for particular types of
applications—that make it particularly easy to build software systems
for the Internet and the WWW. This is one of the reasons why Java is so
well suited for supporting applications on corporate networks.
• Java is a secure language. Designed to be used on networks, Java con-
tains features that protect against untrusted code—code that might in-
troduce a virus or corrupt your system in some way. For example,
once they are downloaded into your browser, Web-based Java pro-
grams are prevented from reading and writing information from and
to your desktop computer.
Despite this list of attractive features, perhaps the best reason for choosing
Java as an introductory programming language is its potential for bring-
ing fun and excitement into learning how to program. There are few other
languages in which a beginning programmer can write a computer game
or a graphically based application that can be distributed on a Web page to
just about any computer in the world. The simplicity of Java’s design and
its easily accessible libraries bring such accomplishments within reach of
the most novice programmers.
For example, we will work on projects throughout the text that involve
games and puzzles. We start out in Chapter 2 by designing very simple
games that involve storing and retrieving data. As we learn more sophisti-
cated programming techniques, we gradually build more complexity into
the games and puzzles. For example, we learn how to create interactive,
two-person games in Chapter 4. In Chapter 8, we develop some games
and puzzles that are played on virtual game boards. Finally, in Chapter 14
we learn how to introduce games with multiple players on different com-
puters. To get a look at where we are headed you might want to visit the
authors’ companion Web site:

http : //www. cs . t r i n c o l l . edu/˜ram/ j j j /
SECTION 0.7 • What Is Object-Oriented Programming? 11
0.7 What Is Object-Oriented Programming?
Java is an object-oriented (OO) language, and this book takes an object-
oriented approach to programming. So before beginning our discussion
of Java, it is important that we introduce some of the underlying con-
cepts involved in object-oriented programming. We need to talk about
what an object is, how objects are grouped into classes, how classes are
related to each other, and how objects use messages to interact with and
communicate with each other.
0.7.1 Basic Object-Oriented Programming Metaphor:
Interacting Objects
A Java program, and any object-oriented program, is a collection of inter-
acting objects that models a collection of real-world
Figure 4: A model of a kitchen.
objects. Think of the model that a kitchen designer might use to layout
your new kitchen (Fig. 4). It will contain objects that represent the various
kitchen appliances and cabinets. Each object in the model is a simplified
version of the corresponding real object. For example, a rectangle might
be used to represent the refrigerator.
A kitchen model is mostly static. It doesn’t change. Once put into place,
its various objects just stand there in a certain relation to each other. By
contrast, a computer program is dynamic. It changes. It does things and
performs certain actions. The objects in a computer program communi-
cate with each other and they change over time. In this respect, the objects
that make up our computer programs are very anthropomorphic, a big word
that means “like people.” If we are eating together and I want you to pass
me the salt, I say, “Please pass me the salt,” and you invariably comply.
Similarly, when you (Student X) put your ATM card into an ATM machine,
the ATM object asks the bank’s database object “Give me Student X’s bank
account object” and the database invariably complies. If you tell the ATM
you want to withdraw $100 dollars it tells your bank account object to
deduct $100 from your current balance. And so it goes. Both you and
your bank account are changed objects as a result of the transaction.
0.7.2 What is an Object?
So what is an object? Just as in the real world, an object is any thing
whatsoever. An object can be a physical thing, such as a Car, or a mental
thing, such as an Idea. It can be a natural thing, such as an Animal, or
an artificial, human-made thing, such as a ATM. A program that manages
an ATM would involve BankAccounts and Customer objects. A chess
program would involve a Board object and ChessPiece objects.
Throughout this text, we will use the notation shown in Figure 5 to
depict objects and to illustrate object-oriented concepts. The notation is
known as the Unified Modeling Language, or UML for short, and it is a
standard in the object-oriented programming community. As the diagram
shows, an object is represented by a rectangle whose label consists of the
object’s (optional) id and its type. An object’s id is the name by which
it is referred to in the computer program. In this case we show a ATM
object, who’s id is not given, and a ChessPiece object, named pawn1.
An object’s label is always underlined.
12 CHAPTER 0 • Computers, Objects, and Java
Figure 5: In UML, objects are rep-
resented by rectangles that are la-
beled with a two-part label of the
form id:Type. The object’s label is
always underlined.
0.7.3 Attributes and Values
Just as with real objects, the objects in our programs have certain char-
acteristic attributes. For example, an ATM object would have a current
amount of cash that it could dispense. A ChessPiece object might
have a pair of row and column attributes that specify its position on the
chess board. Notice that an object’s attributes are themselves objects. The
ATM’s cash attribute and the chess piece’s row and column attributes
are Numbers.
Figure 6 shows two ATM objects and their respective attributes. As you
can see, an object’s attributes are listed in a second partition of the UML
diagram. Notice that each attribute has a value. So the lobby:ATM has a
$8650.0 in cash, while the drivethru:ATM has only $150.0 in cash.
Figure 6: A second partition of an
object diagram is used to display
the object’s attributes and their
values.
We sometimes refer to the collection of an object’s attributes and values
as its state. For example, the current state of the lobby:ATM is $8650.0 in
cash. Of course, this is a gross simplification of an ATM’s state, which
would also include many other attributes. But, hopefully, you see the
point.
0.7.4 Actions and Messages
In addition to their attributes, objects also have characteristic actions or
behaviors. As we have already said, objects in programs are dynamic.
They do things or have things done to them. In fact, programming in
Java is largely a matter of getting objects to perform certain actions for
us. For example, in a chess program the ChessPieces have the ability to
moveTo() a new position on the chess board. Similarly, when a customer
pushes the “Current Balance” button on an ATM machine, this is telling
the ATM to report() the customer’s current bank balance. (Note how
we use parentheses to distinguish actions from objects and attributes.)
The actions that are associated with an object can be used to send mes-
sages to the objects and to retrieve information from objects. A message
is the passing of information or data from one object to another. Figure 7
illustrates how this works. In UML, messages are represented by arrows.
SECTION 0.7 • What Is Object-Oriented Programming? 13
Figure 7: Messages in UML are
represented by labeled arrows. In
this example, we are telling a
pawn to move from its current po-
sition to row 3 column 4.
In this example, we are telling pawn1:ChessPiece to moveTo(3,4).
The numbers 3 and 4 in this case are arguments that tell the pawn what
square to move to. (A chess board has 8 rows and 8 columns and each
square is identified by its row and column coordinates.) In general, an
argument is a data value that specializes the content of a message in some
way. In this example we are telling the pawn to move forward by 1 row.
If we wanted the pawn to move forward by 2 rows, we would send the
message moveTo(4,4).
The diagram in Figure 8 depicts a sequence of messages representing
an idealized ATM transaction. First, an ATM customer asks the ATM ma-
chine to report his current balance. The ATM machine in turn asks the
customer’s bank account to report the customer’s balance. The ATM re-
ceives the value $528.52 from the bank account and passes it along to the
customer. In this case, the message does not involve an argument. But it
does involve a result. A result is information or data that is returned to
the object that sent the message.
Figure 8: This UML diagram
illustrates an ATM transaction
in which a customer asks the
ATM machine for his current bal-
ance. The ATM gets this informa-
tion from an object representing
the customer’s bank account and
passes it to the customer.
Obviously, in order to respond to a message, an object has to know
how to perform the action that is requested. The pawn has to know how
to move to a designated square. The ATM has to know how to find out
the customer’s current balance. Indeed, an object can only respond to
messages that are associated with its characteristic actions and behaviors.
You can’t tell an ATM to move forward 2 squares. And you can’t ask a
chess piece to tell you your current bank balance.
Responding to a message or performing an action sometimes causes
a change in an object’s state. For example, after performing moveTo(3,
4), the pawn will be on a different square. Its position will have changed.
On the other hand, some messages (or actions) leave the object’s state un-
changed. Reporting the customer’s bank account balance doesn’t change
the balance.
0.7.5 What is a Class?
A class is a template for an object. A class encapsulates the attributes and
actions that characterize a certain type of object. In an object-oriented pro-
gram, classes serve as blueprints or templates for the objects that the pro-
14 CHAPTER 0 • Computers, Objects, and Java
Figure 9: A UML diagram of the
Rectangle class.
gram uses. We say that an object is an instance of a class. A good analogy
here is to think of a class as a cookie cutter and its objects, or instances, as
individual cookies. Just as we use the cookie cutter to stamp out cookies
of a certain type, in an object-oriented program, we use a definition of a
class to create objects of a certain type.
Writing an object-oriented program is largely a matter of designing
classes and writing definitions for those classes in Java. Designing a
class is a matter of specifying all of the attributes and behaviors that are
characteristic of that type of object.
For example, suppose we are writing a drawing program. One type
of object we would need for our program is a rectangle. A Rectangle
object has two fundamental attributes, a length and a width. Given
these attributes, we can define characteristic rectangle actions, such as the
ability to calculate its area and the ability to draw itself. Identifying an
object’s attributes and actions is the kind of design activity that goes into
developing an object-oriented program.
Figure 9 shows a UML diagram of our Rectangle class. Like the sym-
bol for an object, a UML class symbol has up to three partitions. Unlike the
UML object symbol, the label for a UML class gives just the class’s name
and it is not underlined. The second partition lists the class’s attributes
and the third partition lists the classes actions. Our rectangle has four
attributes. The first two, x and y, determine a rectangles position on a
two-dimensional graph. The second two, length and width, determine
a rectangle’s dimensions. Note that the attributes have no values. This is
because the class represents a general type of rectangle. It specifies what
all rectangles have in common, without representing any particular rect-
angle. Like a cookie cutter for a cookie, a class gives the general shape of
an object. The content is not included.
0.7.6 Variables and Methods
Up to this point we have been using the terms attribute and action to de-
scribe an object’s features. We will continue to use this terminology when
talking in general about objects or when talking about an object or class
represented by a UML diagram.
However, when talking about a programming language, the more com-
mon way to describe an object’s features are to talk about its variables
and methods. A variable, which corresponds to an attribute, is a named
memory location that can store a certain type of value. You can think of a
variable as a special container that can only hold objects of a certain type.
For example, as Figure 9 shows, Rectangle’s length and width are
SECTION 0.7 • What Is Object-Oriented Programming? 15
variables that can store a certain type of numeric value known as an int.
An int value is a whole number, such as 76 or -5.
A method, which corresponds to an action or a behavior, is a named
chunk of code that can be called upon or invoked to perform a certain
pre-defined set of actions. For example, in our Rectangle object, the
calculateArea() method can be called upon to calculate the rectan-
gle’s area. It would do this, of course, by multiplying the rectangle’s
length by its width. Similarly, the draw() method can be invoked to draw
a picture of the rectangle. It would take the actions necessary to draw a
rectangle on the console.
0.7.7 Instance versus Class Variables and Methods
Variables and methods can be associated either with objects or their
classes. An instance variable (or instance method) is a variable (or
method) that belongs to an object. By contrast, a class variable (or class
method) is a variable (or method) that is associated with the class itself.
An example will help make this distinction clear.
An instance variable will have different values for different instances.
For example, individual Rectangles will have different values for their
length, width, x, and y variables. So these are examples of instance
variables. The calculateArea() method is an example of an instance
method because it uses the instance’s current length and width values
in its calculation. Similarly, the draw() method is an instance method,
because it uses the object’s length and width to draw the object’s shape.
An example of a class variable would be a variable in the Rectangle
class that is used to keep track of how many individual Rectangles
have been created. (Our drawing program might need this information
to help manage its memory resources.) Suppose we name this variable
nRectangles and suppose we add 1 to it each time a new Rectangle
instance is created.
An example of a method that is associated with the class is a special
method known as a constructor. This is a method used to create an object.
It is used to create an instance of a class. Calling a constructor to create an
object is like pressing the cookie cutter into the cookie dough: the result is
an individual cookie (object).
Figure 10 illustrates these concepts. Note that class variables are un-
derlined in the UML diagram. We have modified the Rectangle class
to include its constructor method, which is named Rectangle(). Note
that it takes four arguments, representing the values that we want to give
as the rectangle’s x, y, length and width respectively. Note also how the
Rectangle class’s nRectangles variable has a value of 2, representing
that two Rectangle instances have been created. These are shown as
members of the Rectangle class.
It won’t be obvious to you at this point, but nRectangles is a value
that has to be associated with the Rectangle class, not with its instances.
To see this let’s imagine what happens when a new Rectangle instance
is created. Figure 11 illustrates the process. When the Rectangle()
constructor is invoked, its arguments (100, 50, 25, 10) are used by the
Rectangle class to create a Rectangle object located at x=100, y=50 and
with a length of 25 and width of 10. The constructor method also increases
16 CHAPTER 0 • Computers, Objects, and Java
Figure 10: The Rectangle class
and two of its instances. Note that
the class variable, nRectangles,
is underlined to distinguish it
from length and width, the in-
stance variables.
the value of nRectangles by 1 as a way of keeping count of how many
objects it has created.
Figure 11: Constructing a
Rectangle instance.
0.7.8 Class Hierarchy and Inheritance
How are classes related to each other? In Java, and in any other object-
oriented language, classes are organized in a class hierarchy. A class hier-
archy is like an upside-down tree. At the very top of the hierarchy is the
most general class. In Java, the most general class is the Object class. The
classes below Object in the hierarchy are known as its subclasses. Since
all of the objects we use in our programs belong to some class or other,
this is like saying that all objects are Objects.
Figure 12 illustrates the concept of a class hierarchy using the classes
that we have described in this section. Notice that the Object class oc-
curs at the top of the hierarchy. It is the most general class. It has fea-
tures that are common to all Java objects. As you move down the hierar-
chy, the classes become more and more specialized. A Rectangle is an
Object but it contains attributes – length and width – that are common
to all rectangles but not to other objects in the hierarchy. For example, an
ATM object does not necessarily have a length and a width. Notice that we
have added a Square class to the hierarchy. A Square is a special type
of Rectangle, namely one who’s length equals its width.
To introduce some important terminology associated with this kind of
hierarchy, we say that the Rectangle class is a subclass of the Object
Superclass and subclass
SECTION 0.7 • What Is Object-Oriented Programming? 17
hierarchy of Java
class. The Square class is a subclass of both Rectangle and Object.
Classes that occur above a given class in the hierarchy are said to be its
superclasses. Thus Rectangle class is superclass of the Square class.
The Object class is also a superclass of Square. In general, we say that
a subclass extends a superclass, meaning that it adds additional elements
(attributes and/or methods) to those contained in its superclasses. We saw
this in the case of the Square class. It adds the feature that its length and
width are always equal.
Another important concept associated with a class hierarchy is the no- Class inheritance
tion of class inheritance, whereby a subclass inherits elements (attributes
and/or methods) from its superclasses. To take an example from the nat-
ural world, think of the sort of inheritance that occurs between a horse
and a mammal. A horse is a mammal. So horses inherit the characteristic
of being warm blooded by virtue of also being mammals. (This is dif-
ferent from the kind of individual inheritance whereby you inherit your
mother’s blue eyes and your father’s black hair.)
To illustrate how inheritance works, lets go back to our chess program.
There are several different types of ChessPieces. There are Pawns, and
Knights, and Queens and Kings. Figure 13 illustrates the chess piece
hierarchy. A pair of attributes that all chess pieces have in common is
their row and column position on the chess board. Because all chess
pieces have these attributes in common, they are located at the top of the
ChessPiece hierarchy and inherited by all ChessPiece subclasses. Of
course, the row and column attributes are given different values in each
ChessPiece object.
One of the actions that all chess pieces have in common is that they can
moveTo() a given square on the chess board. But different types of chess
pieces have different ways of moving. For example, a Bishop can only
move along diagonals on the chess board, whereas a Rook can only move
along a row or column on the chess board. So, clearly, we can’t describe
a moveTo() method that will work for all ChessPieces. This is why
we put the moveTo() method in all of the ChessPiece subclasses. The
ChessPiece class also has a moveTo() method, but note that its name is
italicized. This indicates that it cannot be completely defined at that level.
Finally, note that in chess, the king has certain special attributes and
actions. Thus only the king can be put in check. This means that the king is
under attack and in danger of being captured, thereby ending the game.
Similarly, only the king has the ability to castle. This is special move that
18 CHAPTER 0 • Computers, Objects, and Java
Figure 13: The ChessPiece hier-
archy.
a king can make together with one of its rooks under certain conditions.
Thus, the reason we show the inCheck attribute and castle() action in
the King class is because these are characteristics that particular to Kings.
In this way, a class hierarchy represents a specialization of classes as you
move from top to bottom. The most general class, ChessPiece, is at the
top of the hierarchy. Its attributes and methods are passed on to (inher-
ited by) its subclasses. However, in addition to the attributes and methods
they inherit from their superclasses, the subclasses define their own spe-
cial attributes and methods. Each of the subclasses, Pawn, Bishop, and
so on, represents some kind of specialization of the superclass. In this ex-
ample, each of the subclasses have their own distinctive ways of moving.
And the King subclass has unique attributes and actions (inCheck and
castle().
0.7.9 Principles of Object-Oriented Design
As we have discussed, an object-oriented program is composed of many
objects communicating with each other. The process of designing an
object-oriented program to solve some problem or other involves several
important principles:
• Divide-and-Conquer Principle. Generally, the first step in designing
a program is to divide the overall problem into a number of objects
that will interact with each other to solve the problem. Thus, an object-
oriented program employs a division of labor much as we do in organiz-
ing many of our real-world tasks. This divide-and-conquer approach is
an important problem-solving strategy.
• Encapsulation Principle. Once the objects are identified, the next step
involves deciding, for each object, what attributes it has and what ac-
tions it will take. The goal here is to encapsulate within each object
SECTION 0.7 • What Is Object-Oriented Programming? 19
the expertise needed to carry out its role in the program. Each object
is a self-contained module with a clear responsibility and the tools (at-
tributes and actions) necessary to carry out its role. Just as a dentist
encapsulates the expertise needed to diagnose and treat a tooth ache, a
well-designed object contains the information and methods needed to
perform its role.
• Interface Principle. In order for objects to work cooperatively and effi-
ciently, we have to clarify exactly how they should interact, or interface,
with one another. An object’s interface should be designed to limit the
way the object can be used by other objects. Think of how the different
interfaces presented by a digital and analog watch determine how the
watches are used. In a digital watch, time is displayed in discrete units,
and buttons are used to set the time in hours, minutes and seconds. In
an analog watch, the time is displayed by hands on a clock face, and
time is set, less precisely, by turning a small wheel.
• Information Hiding Principle. In order to enable objects to work to-
gether cooperatively, certain details of their individual design and per-
formance should be hidden from other objects. To use the watch anal-
ogy again, in order to use a watch we needn’t know how its time keep-
ing mechanism works. That level of detail is hidden from us. Hiding
such implementation details protects the watch’s mechanism, while not
limiting its usefulness.
• Generality Principle. To make objects as generally useful as possible,
we design them not for a particular task but rather for a particular kind
of task. This principle underlies the use of software libraries. As we will
see, Java comes with an extensive library of classes that specialize in
performing certain kinds of input and output operations. For example,
rather than having to write our own method to print a message on the
console, we can use a library object to handle our printing tasks.
• Extensibility Principle. One of the strengths of the object-oriented ap-
proach is the ability to extend an object’s behavior to handle new tasks.
This also has its analogue in the everyday world. If a company needs
sales agents to specialize in hardware orders, it would be more eco-
nomical to extend the skills of its current sales agents instead of train-
ing a novice from scratch. In the same way, in the object-oriented ap-
proach, an object whose role is to input data might be specialized to
input numeric data.
• Abstraction Principle. Abstraction is the ability to focus on the impor-
tant features of an object when trying to work with large amounts of
information. For example, if we are trying to design a floor plan for a
kitchen, we can focus on the shapes and relative sizes of the appliances
and ignore attributes such as color, style, and manufacturer. The ob-
jects we design in our Java programs will be abstractions in this sense
because they ignore many of the attributes that characterize the real
objects and focus only on those attributes that are essential for solving
a particular problem.
These, then, are the principles that will guide our discussion as we learn
how to design and write object-oriented Java programs.
20 CHAPTER 0 • Computers, Objects, and Java
CHAPTER SUMMARY Technical Terms
action (behavior)
argument
attribute
class
class inheritance
class hierarchy
class method
class variable
compiler
computer program
constructor
high-level language
instance
instance method
instance variable
interpreter
method
message
object
object code
object oriented
result
source code
subclass
superclass
Unified Modeling
Language (UML)
variable
Summary of Important Points
• A computer system generally consists of input/output devices, pri-
mary and secondary memory, and a central processing unit. A com-
puter can only run programs in its own machine language, which is
based on the binary code. Special programs known as compilers and in-
terpreters translate source code programs written in a high-level language,
such as Java, into machine language object code programs.
• Application software refers to programs designed to provide a particu-
lar task or service; systems software assists the user in using application
software.
• The client/server model is a form of distributed computing in which part
of the software for a task is stored on a server and part on client comput-
ers.
• HyperText Markup Language (HTML) is the language used to encode
WWW documents.
• A Java program is a set of interacting objects. This is the basic
metaphor of object-oriented programming.
• An object in a Java program encapsulates the program’s attributes (or
variables) and actions (or methods). A variable is a named memory lo-
cation where data of appropriate type can be stored. A method is a
named section of code that can be called (or invoked) when needed.
• An object’s methods are used to pass messages to it.
• A class is an abstract template that defines the characteristics and be-
haviors of all objects of a certain type.
• An object is an instance of a class. An object has instance methods and in-
stance variables. A class method (or class variable) is a method (or variable)
that is associated with the class itself, not with its instances.
• A constructor is a special method that is used to construct objects.
• Java classes are organized into a class hierarchy, with the Object class
at the top of the hierarchy. For a given class, classes that occur below it
in the hierarchy are called its subclasses, while classes that occur above
it are called its superclasses.
• Classes inherit attributes and methods from their superclasses. This is
known as class inheritance.
• The main principles of the object-oriented programming approach are
as follows:
• Divide and Conquer: Successful problem solving involves breaking
a complex problem into objects.
CHAPTER 0 • Exercises 21
• Encapsulation and Modularity: Each object should be assigned a
clear role.
• Public Interface: Each object should present a clear public interface
that determines how other objects will use it.
• Information Hiding: Each object should shield its users from unnec-
essary details of how it performs its role.
• Generality: Objects should be designed to be as general as possible.
• Extensibility: Objects should be designed so that their functionality
can be extended to carry out more specialized tasks.
• Abstraction is the ability to group a large quantity of information into
a single chunk so it can be managed as a single entity.
EXERCISES
EXERCISE 0.1 Fill in the blanks in each of the following statements.
a. Dividing a problem or a task into parts is an example of the
principle.
b. Designing a class so that it shields certain parts of an object from other objects
is an example of the principle.
c. Java programs that can run without change on a wide variety of computers is
an example of .
d. The fact that social security numbers are divided into three parts is an example
of the principle.
e. To say that a program is robust means that .
f. An is a separate module that encapsulates a Java program’s
attributes and actions.
EXERCISE 0.2 Explain the difference between each of the following pairs of
concepts.
a. hardware and software
b. systems and application software
c. compiler and interpreter
d. machine language and high-level language
e. general-purpose and special-purpose computer
f. primary and secondary memory
g. the CPU and the ALU
h. the Internet and the WWW
i. a client and a server
j. HTTP and HTML
k. source and object code
EXERCISE 0.3 Fill in the blanks in each of the following statements.
a. A is a set of instructions that directs a computer’s behavior.
b. A disk drive would be an example of a device.
c. A mouse is an example of an device.
d. A monitor is an example of an device.
e. The computer’s functions like a scratch pad.
f. Java is an example of a programming language.
g. The Internet is a network of .
22 CHAPTER 0 • Computers, Objects, and Java
h. The protocol used by the World Wide Web is the protocol.
i. Web documents are written in code.
j. A is a networked computer that is used to store data for other
computers on the network.
EXERCISE 0.4 Identify the component of computer hardware that is responsi-
ble for the following functions.
a. executing the fetch-execute cycle
b. arithmetic operations
c. executing instructions
d. storing programs while they are executing
e. storing programs and data when the computer is off
EXERCISE 0.5 Explain why a typical piece of software, such as a word proces-
sor, cannot run on both a Macintosh and a Windows machine.
EXERCISE 0.6 What advantages do you see in platform independence? What
are the disadvantages?
EXERCISE 0.7 In what sense is a person’s name an abstraction? In what sense
is any word of the English language an abstraction?
EXERCISE 0.8 Analyze the process of writing a research paper in terms of the
divide-and-conquer and encapsulation principles.
EXERCISE 0.9 Analyze your car by using object-oriented design principles. In
other words, pick one of your car’s systems, such as the braking system, and ana-
lyze it in terms of the divide-and-conquer, encapsulation, information-hiding, and
interface principles.
EXERCISE 0.10 Make an object oriented analysis of the interaction between, a
student, librarian, and a library database when a student checks a book out of a
college library.
OBJECTIVES
After studying this chapter, you will
• Know the basic steps involved in program development.
• Understand some of the basic elements of the Java language.
• Know how to use simple output operations in a Java program.
• Be able to distinguish between different types of errors in a
program.
• Understand how a Java program is translated into machine language.
• Understand the difference between a Java console application and a Java
Swing application.
• Know how to edit, compile, and run Java programs.
OUTLINE
1.1 Introduction
1.2 Designing Good Programs
1.3 Designing a Riddle Program
Special Topic: Grace Hopper and the First Computer Bug
1.4 Java Language Elements
1.5 Editing, Compiling, and Running a Java Program
1.6 From the Java Library: System and PrintStream
1.7 From the Java Library: System and PrintStream
Chapter Summary
Solutions to Self-Study Exercises
Exercises
Chapter 1
Java Program Design and
Development
23
24 CHAPTER 1 • Java Program Design and Development
1.1 Introduction
This chapter introduces some of the basic concepts and techniques in-
volved in Java program design and development. We begin by identi-
fying the main steps in designing an object-oriented program. The steps
are illustrated by designing a program that “asks” and “answers” riddles.
As an example of a riddle, consider the question “What is black and white
and read all over?” The answer, of course, is a newspaper. Following
the design phase, we then focus on the steps involved in coding a Java
program, including the process of editing, compiling, and running a pro-
gram. Because Java programs can be text based applications or window
based graphical applications, we describe how the coding process differs
for these two varieties.
Next we begin to familiarize ourselves with Java’s extensive class li-
brary by studying its PrintStream and System classes. These classes
contain objects and methods that enable us to print output from a pro-
gram. By the end of the chapter you will be able to design and write a
Java application that “sings” your favorite song.
1.2 Designing Good Programs
Programming is not simply a question of typing Java code. Rather, it in-
volves a considerable amount of planning and careful designing. Badly
designed programs rarely work correctly. Even though it is tempting for
novice programmers to start entering code almost immediately, one of the
first rules of programming is
JAVA PROGRAMMING TIP The sooner you begin to type code,
the longer the program will take to finish, because careful design of
the program must precede coding. This is particularly true of
object-oriented programs.
In other words, the more thought and care you put into designing a pro-
gram, the more likely you are to end up with one that works correctly. The
following subsections provide a brief overview of the program develop-
ment process.
1.2.1 The Software Engineering Life Cycle
Software engineering is the process of designing and writing software.
The software life cycle refers to the different phases involved in the design
and development of a computer program. Our presentation of examples
in the book will focus on four phases of the overall life cycle. In the spec-
ification phase we provide a statement of the problem and a detailed de-
scription of what the program will do. In the design phase we describe
the details of the various classes, methods, and data that will be used in
the program. The implementation phase refers to the actual coding of the
program into Java. In the testing phase we test the program’s performance
to make sure it is correct, recoding it or redesigning it as necessary.
Figure 1.1 gives a more detailed overview of the program development
process, focusing most of the attention on the design phase of the software
SECTION 1.2 • Designing Good Programs 25
life cycle. It shows that designing an object-oriented program is a matter
of asking the right questions about the classes, data, and methods that
make up the program.
Overall, the program development process can be viewed as one that
repeatedly applies the divide-and-conquer principle. That is, most pro-
gramming problems can be repeatedly divided until you have a collection
of relatively easy-to-solve subproblems, each of which can be handled by
an object. In this way the program is divided into a collection of interact- Divide and conquer
ing objects. For each object we design a class. During class design, each
object is divided further into its variables and methods.
Problem Specification
What exactly is the problem?
How will the program be used?
How will the program behave?
Data Design
What types of instance variables
are needed?
Should they be public or private?
Algorithm Design
What information is needed?
What control structures are needed?
Problem Decomposition
What objects will be used and how
will they interact with each other?
The problem is divided into
objects. For each object we
design a class.
Program Development
Process
The object's role
decomposes into
tasks. Each task
can be assigned to
a method.
Method design involves
designing an algorithm.
Errors may require
recoding or
redesigning.
Coding into Java
Stepwise refinement
Fixing syntax errors
Testing, Debugging, Revising
Designing test data and test cases
Fixing semantic errors
Class Design
What role or roles will the object perform?
What variables (attributes) will it need?
What methods (behaviors) will it use?
What interface will it present?
What information will it hide?
Method Design
What task will the method perform?
What information will it need?
What algorithm will it use?
What result will it produce?
Figure 1.1: An overview of the
program development process.
When should we stop subdividing? How much of a task should be
assigned to a single object or a single method? The answers to these and
similar questions are not easy. Good answers require the kind of judg-
ment that comes through experience, and frequently there is more than
one good way to design a solution. Here again, as we learn more about
26 CHAPTER 1 • Java Program Design and Development
object-oriented programming, we’ll learn more about how to make these
design decisions.
1.3 Designing a Riddle Program
The first step in the program-development process is making sure you un-
derstand the problem (Fig. 1.1). Thus, we begin by developing a detailed
specification, which should address three basic questions:
• What exactly is the problem to be solved?
• How will the program be used?
• How should the program behave?
In the real world, the problem specification is often arrived at through
an extensive discussion between the customer and the developer. In an
introductory programming course, the specification is usually assigned
by the instructor.
To help make these ideas a little clearer, let’s design an object-oriented
solution to a simple problem.
Problem Specification. Design a class that will represent a riddle with
a given question and answer. The definition of this class should make
it possible to store different riddles and to retrieve a riddle’s question
and answer independently.
1.3.1 Problem Decomposition
Most problems are too big and too complex to be tackled all at once. So
the next step in the design process is to divide the problem into parts that
Divide and conquer
make the solution more manageable. In the object-oriented approach, a
problem is divided into objects, where each object will handle one specific
aspect of the program’s overall job. In effect, each object will become an
expert or specialist in some aspect of the program’s overall behavior.
Note that there is some ambiguity here about how far we should go
in decomposing a given program. This ambiguity is part of the design
process. How much we should decompose the program before its parts
become “simple to solve” depends on the problem we’re trying to solve
and on the problem solver.
One useful design guideline for trying to decide what objects are
needed is the following:
JAVA EFFECTIVE DESIGN Looking for Nouns. Choosing a
program’s objects is often a matter of looking for nouns in the problem
specification.
Again, there’s some ambiguity involved in this guideline. For example,
the key noun in our current problem is riddle, so our solution will involve
an object that serves as a model for a riddle. The main task of this Java
object will be simply to represent a riddle. Two other nouns in the spec-
ification are question and answer. Fortunately, Java has built-in String
SECTION 1.3 • Designing a Riddle Program 27
objects that represent strings of characters such as words or sentences. We
can use two String objects for the riddle’s question and answer. Thus,
for this simple problem, we need only design one new type of object—a
riddle—whose primary role will be to represent a riddle’s question and
answer.
Don’t worry too much if our design decisions seem somewhat myste-
rious at this stage. A good understanding of object-oriented design can
come only after much design experience, but this is a good place to start.
1.3.2 Object Design
Once we have divided a problem into a set of cooperating objects, de-
signing a Java program is primarily a matter of designing and creating
the objects themselves. In our example, this means we must now design
the features of our riddle object. For each object, we must answer the
following basic design questions:
• What role will the object perform in the program?
• What data or information will it need?
• What actions will it take?
• What interface will it present to other objects?
• What information will it hide from other objects?
For our riddle object, the answers to these questions are shown in Fig-
ure 1.2. Note that although we talk about “designing an object,” we are
really talking about designing the object’s class. A class defines the col-
lection of objects that belong to it. The class can be considered the ob-
ject’s type. This is the same as for real-world objects. Thus, Seabiscuit is a
horse—that is, Seabiscuit is an object of type horse. Similarly, an individ-
ual riddle, such as the newspaper riddle, is a riddle. That is, it is an object
of type Riddle.
The following discussion shows how we arrived at the decisions for the
design specifications for the Riddle class, illustrated in Figure 1.2.
• Class Name: Riddle
• Role: To store and retrieve a question and answer
• Attributes (Information)
• question: A variable to store a riddle’s question (private)
• answer: A variable to store a riddle’s answer (private)
• Behaviors
• Riddle(): A method to set a riddle’s question and answer
• getQuestion(): A method to return a riddle’s question
• getAnswer(): A method to return a riddle’s answer
Figure 1.2: Design specification
for the Riddle class.
The role of the Riddle object is to model an ordinary riddle. Because What is the object’s role?
a riddle is defined in terms of its question and answer, our Riddle ob-
ject will need some way to store these two pieces of information. As we
learned in Chapter 0, an instance variable is a named memory location that
belongs to an object. The fact that the memory location is named, makes
it easy to retrieve the data stored there by invoking the variable’s name.
For example, to print a riddle’s question we would say something like
“print question,” and whatever is stored in question would be retrieved
and printed.
28 CHAPTER 1 • Java Program Design and Development
In general, instance variables are used to store the information that an
object needs to perform its role. They correspond to what we have been
What information will the object
need? calling the object’s attributes. Deciding on these variables provides the
answer to the question, “What information does the object need?”
Next we decide what actions a Riddle object will take. A useful design
guideline for actions of objects is the following:
JAVA EFFECTIVE DESIGN Looking for Verbs. Choosing the
behavior of an object is often a matter of looking for verbs in the
problem specification.
What actions will the object take?
For this problem, the key verbs are set and retrieve. As specified in Fig-
ure 1.2, each Riddle object should provide some means of setting the
values of its question and answer variables and a means of retrieving each
value separately.
Each of the actions we have identified will be encapsulated in a Java
method. As you recall from Chapter 0, a method is a named section of
code that can be invoked, or called upon, to perform a particular action.
In the object-oriented approach, calling a method (method invocation) is
the means by which interaction occurs among objects. Calling a method
is like sending a message between objects. For example, when we want to
get a riddle’s answer, we would invoke the getAnswer() method. This
is like sending the message “Give me your answer.” One special method,
known as a constructor, is invoked when an object is first created. We will
use the Riddle() constructor to give specific values to riddle’s question
and answer variables.
In designing an object, we must decide which methods should be made
available to other objects. This determines what interface the object should
What interface will it present, and
what information will it hide? present and what information it should hide from other objects. In gen-
eral, those methods that will be used to communicate with an object are
designated as part of the object’s interface. Except for its interface, all
other information maintained by each riddle should be kept “hidden”
from other objects. For example, it is not necessary for other objects to
know where a riddle object stores its question and answer. The fact that
they are stored in variables named question and answer, rather than
variables named ques and ans, is irrelevant to other objects.
JAVA EFFECTIVE DESIGN Object Interface. An object’s interface
should consist of just those methods needed to communicate with or
to use the object.
JAVA EFFECTIVE DESIGN Information Hiding. An object should
hide most of the details of its implementation.
SECTION 1.3 • Designing a Riddle Program 29
Taken together, these various design decisions lead to the specification
Figure 1.3: A UML class diagram
representing the Riddle class.
shown in Figure 1.3. As our discussion has illustrated, we arrived at the
decisions by asking and answering the right questions. In most classes the
attributes (variables) are private. This is represented by a minus sign (−).
In this example, the operations (methods) are public, which is represented
by the plus sign (+). The figure shows that the Riddle class has two
hidden (or private) variables for storing data and three visible (or public)
methods that represent the operations that it can perform.
1.3.3 Data, Methods, and Algorithms
Among the details that must be worked out in designing a riddle object is
deciding what type of data, methods, and algorithms we need. There are
two basic questions involved:
• What type of data will be used to represent the information needed by
the riddle?
• How will each method carry out its task?
Like other programming languages, Java supports a wide range of differ-
ent types of data, some simple and some complex. Obviously a riddle’s What type of data will be used?
question and answer should be represented by text. As we noted earlier,
Java has a String type, which is designed to store text, which can be
considered a string of characters.
In designing a method, you have to decide what the method will do. In How will each method carry out its
task?
order to carry out its task, a method will need certain information, which
it may store in variables. Plus, it will have to carry out a sequence of
individual actions to perform the task. This is called its algorithm, which
is a step-by-step description of the solution to a problem. And, finally, you
must decide what result the method will produce. Thus, as in designing
objects, it is important to ask the right questions:
• What specific task will the method perform?
• What information will it need to perform its task?
• What algorithm will the method use?
• What result will the method produce?
Methods can be thought of as using an algorithm to complete a required
action. The algorithm required for the Riddle() constructor is very sim-
ple but also typical of constructors for many classes. It takes two strings
and assigns the first to the question instance variable and then assigns
the second to the answer instance variable. The algorithms for the other
two methods for the Riddle class are even simpler. They are referred to
as get methods that merely return or produce the value that is currently
stored in an instance variable.
Not all methods are so simple to design, and not all algorithms are so
simple. Even when programming a simple arithmetic problem, the steps Algorithm design
involved in the algorithm will not always be as obvious as they are when
doing the calculation by hand. For example, suppose the problem were
to calculate the sum of a list of numbers. If we were telling our classmate
how to do this problem, we might just say, “add up all the numbers and
report their total.” But this description is far too vague to be used in a
program. By contrast, here’s an algorithm that a program could use:
1. Set the initial value of the sum to 0.
30 CHAPTER 1 • Java Program Design and Development
2. If there are no more numbers to total, go to step 5.
3. Add the next number to the sum.
4. Go to step 2.
5. Report the sum.
Note that each step in this algorithm is simple and easy to follow. It would
be relatively easy to translate it into Java. Because English is somewhat
imprecise as an algorithmic language, programmers frequently write al-
gorithms in the programming language itself or in pseudocode, a hy-
Pseudocode
brid language that combines English and programming language struc-
tures without being too fussy about programming language syntax. For
example, the preceding algorithm might be expressed in pseudocode as
follows:

sum = 0
while ( more numbers remain )
add next number to sum
print the sum
Of course, it is unlikely that an experienced programmer would take
the trouble to write out pseudocode for such a simple algorithm. But
many programming problems are quite complex and require careful de-
sign to minimize the number of errors that the program contains. In such
situations, pseudocode could be useful.
Another important part of designing an algorithm is to trace it—that is,
to step through it line by line—on some sample data. For example, we
might test the list-summing algorithm by tracing it on the list of numbers
shown in the margin.
Sum List of Numbers
0 54 30 20
54 30 20
84 20
104 -
Initially, the sum starts out at 0 and the list of numbers contains 54,
30, and 20. On each iteration through the algorithm, the sum increases
by the amount of the next number, and the list diminishes in size. The
algorithm stops with the correct total left under the sum column. While
this trace didn’t turn up any errors, it is frequently possible to find flaws
in an algorithm by tracing it in this way.
1.3.4 Coding into Java
Once a sufficiently detailed design has been developed, it is time to start
generating Java code. The wrong way to do this would be to type the en-
tire program and then compile and run it. This generally leads to dozens
of errors that can be both demoralizing and difficult to fix.
The right way to code is to use the principle of stepwise refinement.
The program is coded in small stages, and after each stage the code is
Stepwise refinement
compiled and tested. For example, you could write the code for a single
method and test that method before moving on to another part of the pro-
gram. In this way, small errors are caught before moving on to the next
stage.
The code for the Riddle class is shown in Figure 1.4. Even though
we have not yet begun learning the details of the Java language, you
can easily pick out the key parts in this program: the instance variables
question and answer of type String, which are used to store the
riddle’s data; the Riddle() constructor and the getQuestion() and
SECTION 1.3 • Designing a Riddle Program 31

/∗
∗ F i l e : R i d d l e . j a v a
∗ A u t h o r : J a v a , J a v a , J a v a
∗ D e s c r i p t i o n : D e f i n e s a s i m p l e r i d d l e .
∗/
public class Riddle extends Object // C l a s s h e a d e r
{ // B e g i n c l a s s b o d y
private String question ; // I n s t a n c e v a r i a b l e s
private String answer ;
public Riddle ( String q , String a ) // C o n s t r u c t o r m e t h o d
{
question = q ;
answer = a ;
} // R i d d l e ( )
public String getQuestion ( ) // I n s t a n c e m e t h o d
{
return question ;
} // g e t Q u e s t i o n ( )
public String getAnswer ( ) // I n s t a n c e m e t h o d
{
return answer ;
} // g e t A n s w e r ( )
} // R i d d l e c l a s s // End c l a s s b o d y
Figure 1.4: The Riddle class definition.
getAnswer() methods make up the interface. The specific language de-
tails needed to understand each of these elements will be covered in this
and the following chapter.
1.3.5 Syntax and Semantics
Writing Java code requires that you know its syntax and semantics. A
language’s syntax is the set of rules that determines whether a partic- Syntax
ular statement is correctly formulated. As an example of a syntax rule,
consider the following two English statements:

The rain in Spain f a l l s mainly on the plain . // V a l i d
Spain rain the mainly in on the f a l l s plain . // I n v a l i d
The first sentence follows the rules of English syntax (grammar), and it
means that it rains a lot on the Spanish plain. The second sentence does
not follow English syntax, and, as a result, it is rendered meaningless. An
example of a Java syntax rule is that a Java statement must end with a
semicolon.
However, unlike in English, where one can still be understood even
when one breaks a syntax rule, in a programming language the syntax
rules are very strict. If you break even the slightest syntax rule—for ex-
32 CHAPTER 1 • Java Program Design and Development
ample, if you forget just a single semicolon—the program won’t work at
all.
Similarly, the programmer must know the semantics of the language—
Semantics
that is, the meaning of each statement. In a programming language, a
statement’s meaning is determined by what effect it will have on the pro-
gram. For example, to set the sum to 0 in the preceding algorithm, an as-
signment statement is used to store the value 0 into the memory location
named sum. Thus, we say that the statement

sum = 0;
assigns 0 to the memory location sum, where it will be stored until some
other part of the program needs it.
Learning Java’s syntax and semantics is a major part of learning to
program. This aspect of learning to program is a lot like learning a for-
eign language. The more quickly you become fluent in the new language
(Java), the better you will be at expressing solutions to interesting pro-
gramming problems. The longer you struggle with Java’s rules and con-
ventions, the more difficult it will be to talk about problems in a common
language. Also, computers are a lot fussier about correct language than
humans, and even the smallest syntax or semantic error can cause tremen-
dous frustration. So, try to be very precise in learning Java’s syntax and
semantics.
1.3.6 Testing, Debugging, and Revising
Coding, testing, and revising a program is an repetitive process, one
that may require you to repeat the different program-development stages
shown in (Fig. 1.1). According to the stepwise-refinement principle, the
process of developing a program should proceed in small, incremental
steps, where the solution becomes more refined at each step. However,
no matter how much care you take, things can still go wrong during the
coding process.
A syntax error is an error that breaks one of Java’s syntax rules. Such er-
rors will be detected by the Java compiler. Syntax errors are relatively easy
Syntax errors
to fix once you understand the error messages provided by the compiler.
As long as a program contains syntax errors, the programmer must correct
them and recompile the program. Once all the syntax errors are corrected,
the compiler will produce an executable version of the program, which
can then be run.
When a program is run, the computer carries out the steps specified
in the program and produces results. However, just because a program
runs does not mean that its actions and results are correct. A running
program can contain semantic errors, also called logic errors. A semantic
Semantic errors
error is caused by an error in the logical design of the program causing it
to behave incorrectly, producing incorrect results.
Unlike syntax errors, semantic errors cannot be detected automatically.
For example, suppose that a program contains the following statement for
calculating the area of a rectangle:

return length + width ;
SECTION 1.3 • Designing a Riddle Program 33
Because we are adding length and width instead of multiplying them,
the area calculation will be incorrect. Because there is nothing syntacti-
cally wrong with the expression length + width, the compiler won’t
detect an error in this statement. Thus, the computer will still execute this
statement and compute the incorrect area.
Semantic errors can only be discovered by testing the program and they
are sometimes very hard to detect. Just because a program appears to run
correctly on one test doesn’t guarantee that it contains no semantic errors.
It might just mean that it has not been adequately tested.
Fixing semantic errors is known as debugging a program, and when sub-
tle errors occur it can be the most frustrating part of the whole program
development process. The various examples presented will occasionally
provide hints and suggestions on how to track down bugs, or errors, in
your code. One point to remember when you are trying to find a very sub-
tle bug is that no matter how convinced you are that your code is correct
and that the bug must be caused by some kind of error in the computer,
the error is almost certainly caused by your code!
1.3.7 Writing Readable Programs
Becoming a proficient programmer goes beyond simply writing a pro-
gram that produces correct output. It also involves developing good pro- Programming style
gramming style, which includes how readable and understandable your
code is. Our goal is to help you develop a programming style that satisfies
the following principles:
• Readability. Programs should be easy to read and understand. Com-
ments should be used to document and explain the program’s code.
• Clarity. Programs should employ well-known constructs and standard
conventions and should avoid programming tricks and unnecessarily
obscure or complex code.
• Flexibility. Programs should be designed and written so that they are
easy to modify.
Special Topic: Grace Hopper and
the First Computer Bug
Rear Admiral Grace Murray Hopper (1906–1992) was a pioneer computer
programmer and one of the original developers of the COBOL program-
ming language, which stands for COmmon Business-Oriented Language.
Among her many achievements and distinctions, Admiral Hopper also
had a role in coining the term computer bug.
In August 1945, she and a group of other programmers were working
on the Mark I, an electro-mechanical computer developed at Harvard that
was one of the ancestors of today’s electronic computers. After several
hours of trying to figure out why the machine was malfunctioning, some-
one located and removed a two-inch moth from one of the computer’s
circuits. From then on whenever anything went wrong with a computer,
Admiral Hopper and others would say “it had bugs in it.” The first bug
itself is still taped to Admiral Hopper’s 1945 log book, which is now in the
collection of the Naval Surface Weapons Center.
34 CHAPTER 1 • Java Program Design and Development
In 1991, Admiral Hopper was awarded the National Medal of Tech-
nology by President George Bush. To commemorate and honor Admiral
Hopper’s many contributions, the U.S. Navy recently named a warship
after her. For more information on Admiral Hopper, see the Web site at

http : //www. chips . navy . mil/
1.4 Java Language Elements
In this section we will introduce some of the key elements of the Java
language by describing the details of a small program. We will look at how
a program is organized and what the various parts do. Our intent is to
introduce important language elements, many of which will be explained
in greater detail in later sections.
The program we will study is a Java version of the traditional Hel-
loWorld program—”traditional” because practically every introductory
programming text begins with it. When it is run, the HelloWorld program
(Fig. 1.5) just displays the greeting “Hello, World!” on the console.

1 /∗
2 ∗ F i l e : H e l l o W o r l d . j a v a
3 ∗ A u t h o r : J a v a J a v a J a v a
4 ∗ D e s c r i p t i o n : P r i n t s H e l l o , W o r l d ! g r e e t i n g .
5 ∗/
6 public class HelloWorld extends Object // C l a s s h e a d e r
7 { // S t a r t c l a s s b o d y
8 private String greeting = ”Hello , World ! ” ;
9 public void greet ( ) // M e t h o d d e f i n i t i o n
10 { // S t a r t m e t h o d b o d y
11 System . out . println ( greeting ) ; // O u t p u t s t a t e m e n t
12 } // g r e e t ( ) // End m e t h o d b o d y
13 public s t a t i c void main ( String args [ ] ) // M e t h o d h e a d e r
14 {
15 HelloWorld helloworld ; // d e c l a r e
16 helloworld = new HelloWorld ( ) ; // c r e a t e
17 helloworld . greet ( ) ; // M e t h o d c a l l
18 } // m a i n ( )
19 } // H e l l o W o r l d // End c l a s s b o d y
Figure 1.5: The HelloWorld application program.
1.4.1 Comments
The first thing to notice about the HelloWorld program is the use of com-
ments. A comment is a non-executable portion of a program that is used
to document the program. Because comments are not executable instruc-
tions they are just ignored by the compiler. Their sole purpose is to make
the program easier for the programmer to read and understand.
The HelloWorld program contains examples of two types of Java
comments. Any text contained within /* and */ is considered a comment.
Another Random Document on
Scribd Without Any Related Topics
general. At all events, my passport through that important part of the French
camp was signed by several hundreds of those brave fellows, as well as by
innumerable smiles from the fair and dark heroines, the cantinières of the
first French division. With a promise to return soon, I retired, having
experienced much gratification and enriched my budget of anecdote.
In this interesting visit to the French camp, head-quarters, canteens, c.,
and becoming well acquainted with the officers’ and soldiers’ popottes—
which name I immediately added to my gastronomic bill of fare—the three
hours I had to spare nearly expired. The sun was rapidly descending to the
level of the ocean in the direction of Kamiesch.
Having paid my bill at the canteen, and shaken hands with nearly a
whole regiment, I jumped on my pony and galloped all the way home,
perfectly satisfied with my day’s work, which at the time I felt was one of
the most interesting of my life.
CHAPTER XVIII.
A UNIVERSAL CALAMITY.
Miss Nightingale dangerously ill—Her removal to the Sanatorium—Worst form of
Crimean fever—General consternation—Conversation with the Captain—Better news—
Visit the Sanatorium—Disembarkation of the Sardinians—Bridge over the London—
Admiral Boxer—Act as interpreter—Overwhelmed with complaints—Soda-water for
horses—All right at last—Alexandrian horse-flesh—A character—An interesting ride—
The General Hospital—Reasons for my return to Turkey—Letters—Head-quarters again—
Lord Raglan’s anxiety for Miss Nightingale—Return to Balaklava—Admiral Boxer and
the Sardinians—All in the wrong—Quieted at last.
ALAS! how short are the moments in which real happiness favours us with
its charms, and how quickly it deserts one in the midst of mirth and joy! On
this eventful day, I was doomed to experience the truth of the saying that
“sorrow treads upon the heels of joy;” for I had scarcely set my foot upon
the deck of the London, when P. M. came and apprised me that Miss
Nightingale was not expected to live. It appeared that after my departure
she had a terrible attack of fever, and was obliged to be immediately
removed to the hospital. On asking to which establishment this excellent
lady had been taken, I was told the Sanatorium. P. M. continued, “Several
doctors, Mr. and Mrs. Bracebridge, and myself, accompanied her there—I
have only been back a few minutes.”
“Why did you not take her to the General Hospital? It was much nearer.”
“Don’t you know that cholera is raging there?”
“There certainly are a few cases. Do you think I can do anything for
her?”
“No, I am sure you cannot; she is not allowed to take anything, and the
doctors have forbidden any one to be admitted, except her private nurse,
Mrs. Roberts.”
It was then getting late—Mr. Bracebridge had not returned. The captain
and P. M. gave me a full account of this lamentable event. It appeared that
about noon Miss Wear had come on board to see Miss Nightingale upon
business. She found that lady very poorly, but thinking it was a slight
indisposition, took no notice of it, more especially as Miss Nightingale did
not complain in the least. About two, by the orders of Mrs. Roberts, they
were obliged to send in a great hurry for a doctor. Mrs. Roberts stated that
her mistress had been suddenly taken dangerously ill—that she was in fact
attacked by the worst form of Crimean fever. The first thing ordered by the
doctor was her instant removal to the hospital on the heights.
“So,” said the captain, who was relating this part of the sad history, “I set
all my men to work. We got a stretcher from the hospital, and she was
carried very carefully by my men and some soldiers sent by the governor.”
“I followed through Balaklava,” said P. M., “amidst a regular procession
of soldiers, holding a white umbrella over her face. The crowd was so great,
we could scarcely pass, and it took us nearly an hour to get up to the
heights. I assure you, all Balaklava was in an uproar.”
“What do the doctors say of the case?”
“That the lady is dangerously ill, and that no one must go near her, not
even Mr. Bracebridge.”
“What mournful tidings!” I said. “I should not be surprised if she caught
the fever from the patient at Dr. Henderson’s. I warned her of the danger of
exposing herself so much several times.”
“By-the-bye, where is Mr. Bracebridge?”
“I left him there.”
“Does he intend to come back, or stay where he is?”
“I don’t know, but I do not see what good he can do there.”
“I hope we shall hear better news when he returns.”
“Now, Mr. Soyer, tell us about your visit to head-quarters. Did you see
Lord Raglan?”
“Certainly I did.”
“And how were you received?” asked the captain.
“Admirably,” I replied.
“I hear his lordship is a most amiable and kind man.”
“He is indeed, I assure you; and I cannot but express my gratitude for the
reception he afforded me. I am certain he will be very sorry to hear of Miss
Nightingale’s serious and sudden illness, for he inquired very kindly after
her this morning.”
My companions made many more inquiries respecting the events of the
day; but I had forgotten all, I was so absorbed by this unexpected blow. It
seemed likely to upset all our plans. I spoke to the captain of the several
visits Miss Nightingale had paid to the sick officer at Dr. Henderson’s at the
time he was so dangerously ill, remarking upon her neglect of herself by
going all day without refreshment, and braving all weathers. We could not
help noticing how singular it appeared, that after her hard labours at Scutari,
and escaping both the cholera and fevers which raged there, she should be
so suddenly taken ill at Balaklava. It was indeed very melancholy and
remarkable. At last Mr. Bracebridge returned. He informed us that Miss
Nightingale was a little better, but that such a violent case of fever required
a certain time. “Mrs. Roberts,” he continued, “is with her, and the boy to go
for the doctor, in case he should be needed.”
“Poor boy!” said the captain, “how he cried when he saw his mistress
carried upon a stretcher by soldiers!”
“Yes,” said Mr. Bracebridge, “he is a very affectionate lad.”
After a few questions about my visit to Lord Raglan, being all very
much fagged, we retired for the night. Upon that occasion, owing to
excessive fatigue and the absence of rats, which had at length been
successfully turned out of my cabin without making use of my receipt, I
enjoyed a comfortable night’s rest. The next morning, at eight precisely,
Louis was at his post with the pony, of which I could not, however, make
use, not knowing what alteration Miss Nightingale’s illness might cause at
both hospitals, where, no doubt, my presence would be required. I sent Dr.
Hall a note, apologizing for not waiting upon him that day, and postponing
our visit to the day following, if agreeable to him. Louis promised to send
me an answer at five o’clock by the doctor’s courier. No news had been
received at the General Hospital from the Sanatorium; therefore Mr.
Bracebridge and myself went up the first thing, instead of going to Mr.
Upton, as we had previously arranged. On our arrival, the report was
anything but favourable; and this seemed to paralyse all our energies.
Indeed, for a few days no business of consequence was transacted. My
kitchen at the Sanatorium alone progressed. I offered my services to Drs.
Henderson and Hadley, in case I could be of use to Miss Nightingale. Dr.
Henderson said, “I am the only cook she requires at present. We must wait
nearly a week before I can leave her in your hands, even should her illness
take a favourable turn.” I then begged of him to give me his private opinion
of her state.
“She is suffering, I assure you, Monsieur Soyer, from as bad an attack of
fever as I have seen; but I should say the chances are in her favour, because
she does not fret in the slightest degree, but is perfectly composed.”
On calling at the General Hospital for Dr. Hall’s reply, I found that he
had fixed the same time the next day for our visit. We then returned on
board the London. Many inquiries respecting Miss Nightingale had been
made by almost all the authorities, amongst whom were Sir John Macneil,
Captain Tulloch, Admiral Boxer, the Governor, Commissary Filder, and Dr.
Sutherland. The latter went at once to see her. Finding she had all proper
attention, he came in the evening, and requested us to leave her as quiet as
possible. He told Mr. Bracebridge on no account to go near her, not even if
sent for, as any excitement might be fatal. This request was of course
punctually attended to.
The remainder of the Sardinian army had now arrived. The
disembarkation kept the harbour in a constant bustle, morning, noon, and
night. It was, in fact, a real maritime bivouac, and our vessel very much
resembled the famed metropolis from which it takes its name. During the
night a strong bridge was built over it, communicating with the shore on the
one side, and one of the Sardinian ships, which had been towed alongside,
on the other. This was made for the purpose of landing men and horses. At
five in the morning I was up and on deck, as from the noise it was
impossible to sleep. The first person on board was Admiral Boxer, as busy
as could be, giving his orders. On seeing me, he inquired about Miss
Nightingale.
“What a good job,” said he, “they were able to remove her from here!”
“You are right, admiral. I perceive you are about to put the troops from
one of the vessels on shore.”
“From one, say you? I am landing the whole of the Sardinian army, and
some of our own troops besides.”
“At any rate, I think this is one of the greatest curiosities of the Crimean
war.”
“Why?” asked the admiral, talking to twenty others at the time.
“Why, admiral, pray who would have thought of seeing while in the
Crimea a Sardinian army cross London Bridge?”
“Ha! ha! ha! true enough; that’s not bad; singular things are seen and
done in time of war. What do you think of their soldiers, Monsieur Soyer?”
“Fine fellows!”
“They are fine fellows. But I wish they spoke English—we should get on
much quicker.”
“I’ll speak to them for you, if you like, admiral.”
“Ah, to be sure, so you can.”
I immediately set about acting as interpreter between the English admiral
and the Sardinian captains. In his anxiety to get rid of them as quickly as
possible, Admiral Boxer asked whether they had pretty much what they
required; a question which brought about ten complainants on deck, who
surrounded me. One had no hay, barley, or water for his horses. They all
spoke at the same time, and made a hubbub which could only be feebly
imitated at the Paris Stock Exchange.
“What’s all this row about? This will never do,” said the admiral. “Pray
don’t tell them who I am, or they will bother my life out.”
“I have told them, and that’s why they are making such a row. I asked
them, as you wished me, whether they had everything they wanted.”
“I said pretty much what they wanted.”
“I know you did, admiral, and so I told them; but they say they don’t
know the meaning of that.”
“Tell them they are fine fellows—fine fellows, and that there is a
beautiful camp ready for them, where they will find everything they require,
without any drawback. I will send lots of men to wait upon them directly;
but they must get out of the harbour before night.”
General della Marmora sent for the admiral; so he left me to settle the
matter, which I did in a very few words.
“My dear fellows,” said I to them, “your valuable services will be much
better appreciated by your sovereign and General-in-chief if you put up
with a little inconvenience for the present, and remain quiet, than if, on the
contrary, you are too particular.”
“Do you know, monsieur, that our horses have not had a drop of water
to-day?”
“Colonel,” said I, “I am not at all surprised at that; and more, you must
put up with it.”
“Why?” he asked.
“Simply because you can’t get it, unless you like to do as I did yesterday
—give them soda-water.”
“Do you mean to say there is no water at all in this grand vessel?”
“None, except soda-water.”
“Eh bien,” said another, “give de soda-water alors.”
“What, for the horses?”
“Oui, for the chevals!”
“Here, my man,” said I to one of the crew, “tell the steward to bring a
dozen of soda-water for the colonel’s horse. Mind, colonel, it costs a
shilling a bottle; but, as you are a good customer, and take a dozen, no
doubt he will let you have it cheaper.”
“I will not pay a sou for this bubbling water. I know what you mean. It
fizzes like champagne, but it is not good to drink. The horses will never
touch it. I thought it was spring-water that you called soda-water.”
At all events, the soda-water was brought, to the great annoyance of the
colonel, who thought he should have to pay for it; but I sent for some sherry
and a few glasses, and we drank a bottle or two, instead of giving it to the
horses, to the great gratification of the colonel, who, after partaking of it,
said he liked it much better with sherry than brandy. About twenty banabaks
soon after arrived with water in skins and leathern horse-buckets. The
horses were properly watered; and thus ended the Sardinian revolt in the
harbour of Balaklava, on the 14th of May, in the year 1855, beneath the
ruins of the Genoese Tower and fortifications built by their ancestors.
The Sardinian troops and horses soon after crossed new London Bridge;
by eight o’clock I was mounting my horse to go and meet Dr. Hall. The
troops that had then landed were in full march towards their very
picturesque camp at the top of the mountain; a band of music was playing at
their head, and their artillery train and baggage-waggons followed. The
weather was brilliant, and the heat of the sun intense. Louis was mounted
upon a fine black horse, which the doctor had brought from Alexandria.
Nobody but Louis could ride him, on account of his tricks. His appearance
was worthy of the finest circus in the world for the performance of the high
school of equitation. To this splendid animal Louis owed his reputation and
popularity; and, as he lived at head-quarters, all the Staff knew him. It is
hardly possible to describe his personal appearance. He was short in stature,
with extraordinary large ears; his long moustaches, hair, and eyebrows were
between the colour of a canary bird and that of the dun pony I was riding.
His dress was of a similar colour, with the exception of his cap, which was,
if possible, of an intenser yellow. This contrast of colours in an individual
mounted upon such a splendid charger, caused him to be remarked by every
one throughout the camp.
Our ride seemed very short, for Louis, who is a very clever fellow, was
full of anecdote, and related some that were really very amusing. He spoke
several languages, frequently mingling one with another. He spoke his own
language, the French, worse than any other, he had been so long away from
his native land. He was present at the battles of Alma, Balaklava,
Inkermann, and the Tchernaya, where his charger was wounded close to the
Traktir Bridge, he, as usual during an action, keeping in close attendance on
his brave master, more especially if danger was imminent; and no better fate
had he at the battle of Inkermann, where he was seriously wounded in the
leg, and the traces of both wounds are, I regret to say, still apparent. On the
eve of my departure from the seat of war, I, out of veneration for this once
splendid charger, purchased him of his owner, who would probably have
been obliged to abandon his faithful steed to the tender mercies of the
hungry inhabitants, who, doubtless, had they got him in their clutches,
would have given him a dressing à la Tartare, or perhaps converted his
body into those suspicious articles of food, sausages. On his voyage home,
in charge of a careful groom, Neptune had no more respect for this four-
legged hero than for the commonest quadruped; for not only was he
pitched, bit, and tossed about in all directions, but worse still, when the ship
Clarendon arrived off Cadiz, she struck on a sunken rock, and the most
valueless animals were thrown overboard; but “Inkermann,” with his usual
luck, in spite of Mars and Neptune, escaped the plunge taken by his less
fortunate companions, and is now in London, enjoying, as hitherto, his full
feed, though in the profoundest retirement, having sold out of the army.
Louis spoke very highly of his master, and never seemed to be pleased or
displeased at anything—good news, bad, or indifferent, were all the same to
him. If you said to him, “The weather is very bad,” he would answer, “I
have nothing to do with that, no more than if it were fine.” On asking him,
at our first interview, if he was a Frenchman, “Of course I am,” he replied;
“all my family were Frenchmen.” I must say that, with all his eccentricity,
he was very obliging; and I feel very grateful for the kind attentions he paid
me, particularly during my serious illness, when he often visited me. Upon
our arrival, the doctor’s horse was at the door, and his master soon made his
appearance.
“Good morning, Doctor! I fear we are behind time.”
“I can always employ my time here,” said he, looking at his watch; “you
are only a few minutes late.”
We then, started. Louis asked whether he was to accompany us; to which
the doctor answered, “No: I expect Dr. Henderson from Balaklava, so be in
the way; tell him we are gone to the General Hospital.”
During our ride, I told my companion about the Sardinian insurrection
near our new London Bridge, which seemed to amuse him very much. He
informed me that Miss Nightingale had passed a better night, but was far
from being out of danger. The cannon of Sebastopol made a fearful noise.
“Have you seen Sebastopol yet, Monsieur Soyer?”
“Yes, I have, Doctor, and was rather close, too!” and I related our
Nightingale campaign.
“To-day you will have another view, quite as good, though not so
dangerous.”
We then began talking upon business, and I was speaking of my having
visited the military and civil hospitals in France, when Dr. Henderson
galloped after us, and a conversation ensued relative to the arrival of the
armies, and the fact that many of the men had been attacked by fever,
before their hospitals were ready. Dr. Hall decided upon a course of action,
and we alighted at the General Hospital. The doctor, Mr. Mouatt, was
unfortunately out, but was expected back shortly. Dr. Henderson left us, and
I accompanied Dr. Hall round several huts. He visited all the worst cases,
which were at that time very numerous. We then repaired to the kitchen,
which, as I have before said, was far from being equal to the requirements
of such an immense hospital. It was in the open air, and ill provided with
things necessary for the establishment. Having pointed this out to Dr. Hall,
he immediately agreed that one similar to that at the Sanatorium should be
erected; but Dr. Mouatt was not present. The want of materials and of
workmen was so great, that, previous to its erection, I was obliged to leave
the Crimea and return to Scutari for a short time. My head man there had
been taken ill, and his life was, as he thought, in great danger. Several times
prior to my return he had threatened to run away, which would quite have
upset all my former efforts.
I remained in the Crimea about ten days longer, and my reader will
perceive that every minute of my time was occupied. I devoted some of it to
the most important hospital of all—the one before Sebastopol; a plan for the
improvement of which I immediately made and forwarded to the proper
parties, so much was I impressed with the necessity of having a kitchen
erected immediately. Fearing that I should be obliged to leave the Crimea
for Scutari before it could be even commenced, the day after my visit I
wrote two official letters, one to Lord Raglan, and the other to Dr. Hall. The
General-in-chief and Dr. Hall had both visited the spot, and agreed with me
that it was one of the most important hospitals in the East. It was situated
under the very walls of Sebastopol, subject to a divided attack, or to a
sortie, and might at any moment be suddenly encumbered with a large
number of wounded, requiring a great quantity of nutritious articles, more
particularly beverages, after any surgical operation. In reply I received the
following communications:—
Before Sevastopol, 30th May, 1855.
Sir,—I am directed by Lord Raglan to acknowledge the receipt of your several
communications of the 25th and 28th instants, and to express to you his lordship’s thanks
for the valuable information contained therein.
I have the honor to be, Sir,
Your obedient servant,
Thos. Steele,
Lieut.-Col., Military Sec.
Mons. Soyer.
My dear Mr. Soyer,—I have this day received your letter of the 22nd June, and am
much obliged to you for your thoughtful care of our wants in the all-important business of
cooking for both sick and well. Our new hospital is nearly fit for the reception of patients;
but you know how tedious the want of labor makes everything here. I was out at the
Monastery yesterday, and was glad to see that they had commenced on the kitchen, and
were going to fit it up after your excellent model at the Castle.
Very truly yours,
J. Hall.
5th July, 1855.
I also had several interviews with Dr. Mouatt, who took my suggestion
during my absence in hand, but never apparently succeeded in carrying it
out, although the materials requisite were simply planks, nails, and bricks.
I merely advert to the foregoing in answer to some observations that
were wafted about the camp to the effect that I never took much trouble
about this particular hospital, while in reality it was the very first which
attracted my attention, as the above letters will convince my readers.
Upon our return from the hospital to head-quarters, I called at Colonel
Steele’s. Lord Raglan was just going out, and the first question he asked,
even before I had time to pay my respects, was—“How is poor Miss
Nightingale?”
“A little better to-day. Dr. Henderson, whom I have just seen, says she
has passed a better night.”
“Well, I hope she has; I shall pay her a visit as soon as possible—that is,
when she is a little better. Was she ill at all at Scutari?”
“Not, my Lord, while I was there, and, I think, not before. It is rather
remarkable that she should catch the Crimean fever just after her arrival.”
I told Lord Raglan of her imprudence in visiting a patient at Dr.
Henderson’s, who had been attacked by the worst form of Crimean fever;
also, of her remaining out so late, and not taking any refreshment.
“She appears,” said Lord Raglan, “to have no fear.”
“None whatever.”
I recounted her visit to the three-gun battery, and the scene that took
place upon the centre mortar. Lord Raglan remarked—“It should be called
the Nightingale mortar.”
He then jumped upon his horse, and I had but a few minutes to explain
the result of my visit with Dr. Hall to the various hospitals. I mentioned that
the most important thing was the immediate erection of a kitchen for the
General Hospital, in case of a decided attack upon Sebastopol.
“Very true, Monsieur Soyer,” said Lord Raglan.
I stated that I had addressed a letter to his lordship to that effect.
“Yes, I have seen it, and it shall be attended to.”
Lord Raglan and his staff then started in the direction of the French
head-quarters, and I towards Balaklava, where I arrived about dusk. I left
my pony at the General Hospital, and walked to the opposite side of the
harbour, which I had in the morning left all in confusion, and, to my
astonishment, found quiet and almost deserted. The only person I saw was
Admiral Boxer, who came and thanked me for the assistance I had given
him in the morning.
“Don’t mention it, admiral,” said I; “I shall at all times be happy to do
everything in my power to render myself agreeable to you. Pray tell me,
where are they all gone?”
“To their camp, to be sure.”
“What—regiments, horses, and all?”
“Yes, the vessels alongside this morning have not only discharged their
cargoes, but are, I believe, out of the harbour and anchored in the bay. We
shall have two more in, which must be discharged to-morrow.”
“This silence is almost inconceivable after so much noise and bustle.”
“It is,” said the admiral. “I don’t understand those Sardinians, they speak
so fast and loud; but they are fine fellows for all that, and no mistake.”
The words were hardly out of his mouth, when two Sardinians attached
to the commissariat came towards us, and inquired whether we understood
French or Italian. I informed them that I spoke French.
“Then, pray, sir, can you tell us where to find ce diable d’amiral
Anglais?”
“What do they say?” asked Admiral Boxer, addressing me.
“Nothing particular,” I replied. “Gentlemen,” said I, turning to the
Sardinians, “what could the admiral do for you? It is very probable that I
shall have the pleasure of seeing him this evening.”
The one who had as yet scarcely spoken exclaimed—“A truce to the
pleasure! I wish I could get hold of him, I would tell him my mind in a few
words.”
“Pray be calm, gentlemen.”
All this time Admiral Boxer kept asking—“What do they say? They are
speaking about me, I know they are. Tell them they are a fine set of fellows,
and I will do anything for them, but they must be out by to-morrow night.”
“Very well; but first let me inquire what the row is all about.”
“Do so.”
“Now, gentlemen, what is it you want? for here is a person who can do
as much for you as the admiral himself, and perhaps more.”
“Ah, pray ask him, then.”
“But you have not yet told me what you require.”
“Eh bien!” they said, both speaking at once, “pray, my friend, ask this
gentleman to tell the English admiral to postpone the order for our landing
to-morrow morning till the next day. It is impossible for us to land our men
and horses so early. We have above four hundred horses on board; not half
of which have been watered to-day, nor can they be, till we find some water.
There is only a small pump to draw it from the hold of the vessel, and it
takes hours to water a few horses.”
Having explained this their chief trouble to the admiral, he said—“Tell
them there will be plenty of water for them by four o’clock in the morning.”
When I had done so, they inquired whether they could depend upon that
gentleman’s word. I assured them that they might.
“With respect to the other matters, we ought to see the admiral himself.”
“Oh, don’t trouble yourself; I will do the rest for you.”
This was merely a request concerning themselves. I did not like to
trouble the admiral about it, and I thought the best way to get rid of them
was to show them his flag-ship, telling them they might go there if they
liked, but that it was a hundred to one if they found him on board.
“No, no!” said one of them; “it is dinner-time, and the English like their
dinner too well; he is sure to be at home, so we will go and see.” Having
their boat with them, they went across.
The admiral asked—“What do they want besides the water for their
horses?”
“Oh, they were inquiring about the camp.”
I then related all our conversation, at which the admiral laughed heartily,
saying he could understand some of it, but they spoke so very fast.
“When they come on board to-morrow, they will be sure to recognise
me.”
“Oh no! having only seen you in the dark, they will not know you again;
and I shall be there. Don’t trouble yourself; they will be quiet enough when
they get all they want, and they have a very fine camp.”
“Have you seen it?”
“No, admiral, not yet.”
“Then you ought to go and see it; they are building a large hospital there.
Mind, they have reason to complain. I am aware they ought to have more
time; but see what a fleet I have in such a small harbour, and every day
there are more troops coming. Perhaps an expedition of our own troops will
sail shortly, so I must be prepared for everything. That is what has kept me
on this side of the harbour to-night; besides, I wished to see how they were
going on with the new quay.”
“You have done wonders, admiral, on this side of the harbour since my
arrival.”
“Remember, Monsieur Soyer, we cannot always do as we like. We are
not in England.” We parted for the night.
CHAPTER XIX.
HAPS AND MISHAPS IN CAMP.
Dinner on board the Baraguay d’Hilliers—Bread-biscuit—Good news of Miss
Nightingale—Operations at the Sanatorium kitchen—A borrowed pony—Don’t lose the
saddle—No police nor newspapers—Difficulties at Balaklava—Dry vegetables in cake—A
receipt—Promise of support—A new mother—Mrs. Seacole’s enthusiasm—The lady’s
sons—Advice—My pony lost—A friend in need—Mr. Russell—Mr. Angel—Crimean Hue
and Cry—Useless inquiries—Monsieur Armand’s difficulties—A dinner at the Post-office
—A jovial party—Festivity and song—Break up at last.
ON reaching the London, I found Mr. Bracebridge dressed and waiting for
me to go and dine on board the Baraguay d’Hilliers, with Sir John Macneil
and Captain Tulloch. We had that evening a most interesting conversation
on all kinds of army stores and provisions. Sir John, who took a vital
interest in my mission, gave me several important hints, and I submitted my
opinion of the salt as well as fresh meats—fresh and dried vegetables, and
especially the bread, which at that period arrived daily from Constantinople,
but which, in consequence of its being sometimes put on board ship before
it had got quite cool, lost a great deal of its nutritive quality during the
passage. Had it been made in the Crimea of the same materials, it would
have been very good. I was informed that bakeries were to be established. I
told Sir John that I had made a kind of bread-biscuit, somewhat like
common bread, but baked in flat cakes about twelve times the size of an
ordinary biscuit; it would keep for months, and then eat well, though rather
dry; it would soak well in tea, coffee, or soup, and be very palatable; it was
made of three parts flour and one of peameal, and was reported upon by the
medical gentlemen as being very nutritious and wholesome. A few days
later I had the pleasure of showing some to those gentlemen, and they both
highly approved of it. I afterwards had some made on board the Abundance.
I submitted it to them, and they pronounced it excellent.[13]
The evening we spent on board the Baraguay d’Hilliers will not be soon
forgotten. After a short nautical and nocturnal trip upon the water, we
arrived safely in our old London. On our way to the Baraguay d’Hilliers,
Mr. Bracebridge informed me that Miss Nightingale was pronounced out of
danger, and that the news had been telegraphed to London. The medical
men were of opinion that she should return to Scutari, and after a few days’
rest proceed to England. Although out of danger, she would not be able to
quit Balaklava for eight or ten days. The next morning, at seven o’clock, I
was at the Sanatorium kitchen, which was finished. I set my soldier-cooks
to work, and all went on admirably. It was then ten o’clock, so I called upon
Dr. Hadley (the chief doctor at the Sanatorium, who had succeeded Dr.
Henderson, and to both of these gentlemen I must return my sincere thanks
for their assistance and kindness), and requested him to come and taste
some extra diets and soups I had prepared for the convalescents.
Recollecting that I had not called upon Lord Raglan’s chef de cuisine, I
mentioned the circumstance to Dr. Hadley, stating how much I wished to do
so, but that I had no horse. Dr. Hadley very kindly offered me his pony, a
fine grey, smartly caparisoned, which I at once accepted. When I had
mounted, Dr. Hadley said—“Soyer, if you fall off, mind and get up again;
for,” said he, “joking apart, though the pony is very quiet, recollect the road
to Balaklava is a queer one, therefore take care of yourself. We should not
mind so much if we had done with, you; but as we really require your
services, for our own sakes take care of yourself.”
“I will do so,” said I, laughing, “were it only for the sake of your pony,
which might get loose if I were to fall off, and you might not recover him
again.”
“Never mind the pony,” said he: “you may lose him; but, whatever you
do, don’t lose the saddle. We had better have a bit of supper on your return
this evening, off that Yorkshire ham—you can cook it on your bivouac
stove.”
“So we will, Doctor. I shall be back at six.”
“Don’t stay in the camp after dark; I can assure you it is a very
dangerous place. Robberies and murders are of frequent occurrence, though
we hear but little about them. We have no police, and no newspapers are
published here, so we know nothing but what passes in our own circle.”
“You are perfectly right, Doctor; though I am not afraid, as I never travel
without a revolver; yet it is best to be upon the safe side.”
Having fixed upon six o’clock for my return, and seven for supper, I
started. There were about twenty convalescents outside the wards, enjoying
the warmth of the sun’s rays. They were all in high glee at hearing our
dialogue, which seemed to revive them from a state of lethargy to the
consciousness of life.
The ride from the top of the Genoese heights to Balaklava harbour, by a
new road, through mud, over rocks, rivulets, c., and mounted upon a
strange nag, was anything but pleasant to my feelings as a horseman. At all
events, after numerous slippery evolutions on the part of my new charger, I
found myself safe at the bottom of the ravine; but here another difficulty
presented itself. The quay of the harbour was encumbered with French and
Sardinian waggons, mules, and horses. The French, who had a wine depôt
there for the troops, were strongly fortified with about a hundred pipes of
wine, instead of gabions. So crowded was the road from the immense traffic
and the unloading of shipping stores, that it took me nearly half-an-hour to
ride a few hundred yards. This brought me as far as the Commissariat,
where I had to call upon Commissary Filder. I found that he had just
returned from head-quarters. We had about ten minutes’ conversation upon
business. I related the result of my visit to the various provision stores—
made remarks upon the same, and particularly upon the dry vegetables at
that time issued to the troops. He then referred me to Under-Commissary
Adams, to whom I promised a scale for a fresh composition of dry
vegetables in cake, more suitable for the troops, in lieu of the finer and
more expensive quality then issued in boxes. They were composed of one
vegetable only, and were much too highly dried, having thus lost their
aroma as well as their nutritious qualities. I therefore proposed that the firm
of Messrs. Chollet, in Paris, should prepare a sample of cakes of dried
vegetables, to be called coarse julienne, for the army. Each hundredweight
of fresh vegetables was to consist of the following proportions:—
Twenty pounds of carrots, twenty pounds of turnips, ten of parsnips,
fifteen of onions, twenty of cabbage, five of celery, and ten of leeks; with
one pound of aromatic seasoning, composed of four ounces of thyme, four
of winter savory, two of bayleaf, four of pepper, and an ounce of cloves; the
whole to be pulverized and mixed with the vegetables.
Each cake was to serve for one hundred men, and to be marked in
compartments of ten rations each, like chocolate cakes, instead of being
marked upon the wrapper, which is always torn off when the vegetables are
issued, and the soldiers cannot tell about quantity. This plan will obviate
that evil; for I had seen in camp piles of this excellent vegetable rising
pyramidically from the soldiers’ canteen pan while cooking, in consequence
of their having put in the best part of three days’ rations instead of one. The
dry rations are issued for three days at a time.
My proposition having met with the approval of the authorities, was at
once forwarded to the War Office.
I also promised to submit to Commissary Filder’s notice several plans
for improvement in the distribution of the meat.
“Monsieur Soyer,” said he, “anything you may propose or point out as
an improvement will, so far as it is practicable, be carried out. Lose no time;
the sooner you let us have it the better.”
After this interview, I went to inspect the kitchen, where I saw Mr.
Fitzgerald, the purveyor, to whom I also made my report. As this is the first
time I have had the pleasure of introducing this gentleman to the notice of
my readers, it would be an omission on my part were I not to return my
grateful acknowledgments for the readiness with which he at all times
assisted me to obtain what I required for the hospitals in the Crimea. It is
true he was at first rather reluctant; this I attributed to his not having
received the proper instructions from the authorities.
Having the best part of the day before me, I set off at a gallop towards
head-quarters, intending to keep the promise I had made Lord Raglan
respecting his dilapidated culinary department, and also to make the
acquaintance of M. Armand, his chef de cuisine. As I was not well
acquainted with the road across the country, I made up my mind to follow
the high one which passes close to head-quarters. When about half-way, I
perceived a group of officers standing by the road-side round a kind of tent
much like a gipsy tent, but considerably larger. This excited my interest,
and I was riding towards it, when, to my astonishment, several voices called
out—“Soyer! Soyer! come here—come this way!” I readily complied with
the invitation, and found two or three gentlemen whom I had the pleasure of
knowing. During our conversation, an old dame of a jovial appearance, but
a few shades darker than the white lily, issued from the tent, bawling out, in
order to make her voice heard above the noise, “Who is my new son?” to
which one of the officers replied, “Monsieur Soyer, to be sure; don’t you
know him?”
“God bless me, my son, are you Monsieur Soyer of whom I heard so
much in Jamaica? Well, to be sure! I have sold many and many a score of
your Relish and other sauces—God knows how many.”
“My dear lady,” said I, “don’t blame me for that; I assure you I am not at
all offended with you for so doing, and shall allow you to sell as much more
in the Crimea.”
“So I would if I could only get them. Bless me, I had a gross about ten
days ago, and they are all gone; nor can I get any more for another month
perhaps. Come down, my son, and take a glass of champagne with my old
friend, Sir John Campbell.”
I immediately alighted, and Sir John came towards me and shook me
heartily by the hand, saying, “Welcome to the seat of war, Monsieur
Soyer!”
“Many thanks, general, for your kind wishes. I had the pleasure of
leaving my card at Cathcart’s Hill the other day.”
“You did; and I was very sorry that I was out when you called; but mind,
you must come and dine with me some day.”
“Thank you, general, I shall do myself the honour.”
“Now, Mrs. Seacole, give us another bottle of champagne.”
“Mrs. Seacole,” I exclaimed; “is that lady the celebrated Mrs. Seacole?”
“Of course,” said the general.
She then came forth from her bivouac cellar, with two bottles in her
hands, exclaiming, “I shall stand mine, and no mistake.”
We all declared it would never do for a lady to stand treat in the Crimea.
“Lord bless you, Monsieur Soyer,” said the lady, “don’t you know me?”
“Yes, I do now, my dear madam.”
“Well, all those fine fellows you see here are my Jamaica sons—are you
not?” said she, opening the champagne, and addressing the general.
“We are, Mrs. Seacole, and a very good mother you have been to us.”
“I have known you, general, for many years.”
“Well, here’s a health to all.”
We emptied our glasses, and returned the compliment. The general then
left, again expressing his desire to see me at Cathcart’s Hill.
“Walk inside, walk inside, my sons; you will be better there—it is not so
hot. Go in, Monsieur Soyer.”
No sooner had we entered than the old lady expressed her desire to
consult me about what she should do to make money in her new
speculation, in which she had embarked a large capital, pointing to two iron
houses in course of construction on the other side of the road. She told me
that her intention was to have beds there for visitors, which I persuaded her
not to do, saying, “All the visitors—and they are few in number—sleep on
board the vessels in the harbour, and the officers under canvass in the camp.
Lay in a good stock of hams, wines, spirits, ale and porter, sauces, pickles,
and a few preserves and dry vegetables—in short, anything which will not
spoil by keeping.”
“Yes,” said she, “I mean to have all that.”
“In that case you will no doubt make money, as you are so well known
to all the army.”
“I assure you, the last time Lord Raglan passed here, he spoke to me for
more than ten minutes, and promised to do all he could for me.”
“That’s right,” we all said.
“I know Miss Nightingale too. She was very kind to me when I passed
through Scutari, on my way here; she gave me lodging and everything I
required, in the hospital.”
“We passed this way a few days before Miss Nightingale was taken ill,”
said I.
“I know you did; and I am sure, if the lady had known I was here, she
would have called to see me. Thank God, I hear she is quite out of danger.”
“Yes, she is improving.”
“When you see her, present my best respects, and tell the dear lady that I
shall go and see her.”
“I will, Mrs. Seacole. Good-bye.”
“Good-bye, my son.”
On getting up in a hurry to be off, I missed my horse, and found one of
the officers’ chargers, which had been left in charge of the same man to
whom I had given mine, led by a Zouave. Upon inquiring of the Zouave
where the man had gone, he informed me that he did not know, but that he
had given him a shilling (which he showed me) to hold this animal for, as
far as he could understand, about an hour, while he went on the grey in the
direction of head-quarters. I called Mrs. Seacole out, and told her what had
happened. She stepped up to the Zouave, and he began talking so fast, that I
shall not forget the expression he made as long as I live. His speech may be
thus translated: “By the name of Jupiter! I have neither stolen nor sold your
horse. Look at me! (showing his corporation.) If you like, captain, to lend
me this quadruped, I will soon find the voyiou (meaning a low rascal).
There is my name and the number of my regiment. We are encamped near
the French head-quarters.”
All this time Mrs. Seacole had been looking about, and every grey pony
she saw far or near was mine—at least in her eyes. The two officers
mounted their horses, and went one one way and the other another, but soon
returned, having found nothing. Having sent in all directions without being
able to obtain any trace of the pony, we concluded that the animal was lost.
I take this opportunity of publicly thanking those two gentlemen for the
vivid interest they took in trying to find the borrowed steed. I very much
regret that I do not recollect their names. They will no doubt remember the
circumstance if this little work falls into their hands.[14]
All our efforts to find the pony being useless, I made up my mind to
walk back to Balaklava. Just as I was thanking Mrs. Seacole for her
extraordinary exertions, Mr. Day, her partner, came in, and he advised me to
go at once to the Hue and Cry, at head-quarters.
“How am I to do this?” I asked.
“Take my pony. It is not twenty minutes’ ride from hence; and you will
stand a good chance of getting it back, especially if the man who held it was
an Englishman. He is sure to be found in the English camp.”
Thanking him for his kindness, I mounted, and started full gallop for
head-quarters. I made inquiries at the Post-office, where I had the pleasure
of meeting Mr. Russell, who introduced me to Mr. Angel, the postmaster. I
then inquired for the Hue and Cry, and related the circumstances under
which I had lost my pony. All seemed highly amused. They laughed heartily
at my expense, and I could not help joining in the merriment. Mr. Angel
invited me to dine with him, having a few friends that evening to join his
popotte.
“I am much obliged, my dear sir; but I am staying at Balaklava, and I
suppose you dine late.”
“About six o’clock,” replied Mr. Angel. “You can sleep here. We have no
bed, it’s true; but I can lend you a blanket; and there is a small hut, which is
empty, you can have all to yourself. Mr. Bracebridge slept there the night
before last, when on a visit to Captain Boucher, a friend of his.”
“Oh, as far as that goes, I shall be comfortable enough.”
“Then you will dine with me?”
“I will,” said I, “and am much obliged for your kind invitation.”
I thought by accepting it, I should have an excellent opportunity of
looking out for my pony in the morning, if I did not happen to find it that
night; I therefore went to the Hue and Cry, and gave the best description, to
my knowledge, as I had not had the honour of his acquaintance long, and
did not know of any private marks by which he might be recognised. They
gave me but faint hopes of seeing it again, and by way of comforting me,
showed me a long list of missing horses, mules, and ponies, enough to fill
half a column of the Times.
“I don’t care so much about the pony, as that can be replaced; but the
saddle is a new one from London, and neither the animal nor the saddle
belong to me.”
“You may, perhaps,” said one, “find the horse, but not the saddle,
especially if it is gone to the French camp, for, believe me, the Zouaves are
very fond of English saddles, as well as everything they can get hold of
which does not require feeding; so they will probably keep the saddle and
turn the horse loose. At all events, we will do what we can for you; but I
advise you to look out for yourself.”
It was then about four o’clock, and I had an hour’s ride about the camp,
but it was all in vain. Every inquiry proved fruitless; and I could not obtain
the slightest clue to the lost pony. I could not help smiling when I
recollected Dr. Hadley’s last words, “You may lose the horse but don’t lose
the saddle.” Hoping for better luck next day, I returned to head-quarters,
and begged Lord Raglan’s groom to give Mr. Day’s pony a night’s lodging.
Making sure Monsieur Armand would be in, I went to see him. He was
rather busy, but he received me very politely, and showed me what he called
his kitchen, though it had not the slightest claim to the title, as it was all but
destitute of culinary utensils. The provisions were of inferior quality; but, as
he told me, the best he could procure. I then offered my services if I could
be of any use in getting stoves or a small oven erected.
“Ever since I have been here,” he replied, “I have been asking for one or
two charcoal stoves and a few shelves, but not a thing can I obtain for love
or money.”
“Upon my word you surprise me! How can that be in the house of the
Commander-in-chief? Truly, every one has much to do.”
“Such is the case.”
“Never mind; I think I shall be able to get something done for you, as his
lordship has spoken to me upon the subject.”
“I shall be much obliged to you if you will,” said he; and then pointed
out the principal things he required, which were soon afterwards furnished.
As it was nearly six o’clock, I left him, and returned to the Post-office,
where a sumptuous table was laid out. There was actually a tablecloth and
real plates, knives, forks, and various kinds of glasses. In fact, for the
Crimea, it was as the French say, épatant. We sat down six to dinner; and
had some very strong preserved soup, a very nice tough fowl—the
remainder of the bill of fare was made from the ration meat. We had very
good wine; and, perhaps, never was a dinner better relished, or
accompanied with more mirth and jokes. Russell the great was the hero,
besides having an Angel for the host. Towards eight o’clock, the party
amounted to about fifteen, as far as we could discern through the clouded
atmosphere with which the room was filled. Every one was smoking; some
large chibouques, long and short pipes, a few cigars, but no cigarettes. The
unexpected increase to our party, I must observe, was partly owing to our
vocal abilities, several lively choruses having attracted Mr. Angel’s
illustrious neighbours, as the denizens of the woods were allured by the
melody of Orpheus.
Our mirth at last became so boisterous that it not only brought around us
men of all ranks, but attracted the attention of the Commander-in-chief,
who sent to inquire what the noise was about. This we considered a rather
inharmonious inquiry, but found that, by decreasing the pitch of our vocal
organs from allegro to piano, we should produce as much effect, with less
noise, as his lordship wisely called it; though I heard the next day, that Lord
Raglan, who was sitting at his door enjoying the fresh air with several
gentlemen of his staff, enjoyed it, and gave orders that we should not be
disturbed. Complaints poured in from the numerous tents which surrounded
head-quarters. It was then about ten o’clock, which is equivalent to twelve
or one p.m. in London. The mot d’ordre from our chairman was, “Tell those
who cannot sleep to join our bacchanalian party.” So many took the hint,
that no room could at length be obtained in the modern Crimean Temple of
Momus.
At last the order took a more positive character, for the very Angel who
was presiding, observed, and very justly, that they were all playing the devil
with him, and still more so with his cellar, which being but meagerly
stocked, could not long stand so severe an attack. He therefore begged all
new comers to go back to their quarters, and bring or send the liquid
requisite to keep up the spirits of the guests till midnight—which was done.
Every one, like Cinderella, disappeared, by slipping quietly out at the most
convenient opportunity.
CHAPTER XX.
EXPEDITIONS ON HORSE AND ON FOOT.
Comfortable couch—A terrible sortie—The borrowed animal reclaimed—A bad
position—Lord Raglan lends me another steed—General Estcourt—Female improvements
—Visit to the French camp—A French canteen—A lively vivandière—French regimental
kitchens—Discoveries—Interview with Colonel Steele—Pertinent remarks—A carriage—
Mrs. Estcourt and her sister—General Camp Hospital—Cathcart’s Hill—Strange reports—
Concert à la Soyer—Receipt for a stew—Conversation with Sir John Campbell—A flag of
truce—A good peep at Sebastopol—A cavalcade of amateurs—A sad spectacle—A narrow
escape—Noisy night.
NEXT morning, I found myself wrapped up in a horse-cloth, with a pair of
top-boots for a pillow. The unfeeling and ungrateful board to which I had
intrusted my precious limbs, had by the morning stamped his patron’s seal
upon my back. The following day we learnt that a terrible sortie had taken
place in the night, and that there had been a severe loss of men on both
sides. At an early hour the court-yard was thronged with officers;
despatches were flying in every direction; the cannon was roaring as usual,
but the fusillade had ceased. I then went to the stable for my pony, when I
found the owner, Mr. Day, upon his back, just going home.
“Ah, Monsieur Soyer, I made sure that you had lost my pony as well as
your own. I expected you back immediately, being in want of it.”
“I was not aware of that, or I would have walked from your place sooner
than have deprived you of it.”
“Oh, never mind. Have you heard anything of your animal?”
“No! but I am going to look after him this morning. That is the reason
why I slept at head-quarters last night.”
“I am going about the camp,” said he, “and will inquire for you.”
He then started, of course leaving me without a horse, and with dreadful
pains in my back and legs, which I attributed to the softness of the bed with
which I had been favoured; though I could not boast of a single feather, like
that Tocrisse of a recruit, who took one out of his master’s feather bed, laid
it down on the boarded floor of his hut, and next morning told his
companions that his master must be foolish to sleep upon a feather bed.
“Why?” asked they.
“Why, if one feather is so hard, what must the lot the captain sleeps upon
be?”
The worst of my position was, how to get another horse, as it was
impossible for me to walk all day about the camp, being so stiff and tired. I
went to Lord Raglan’s coachman, and inquired if he had one to spare. He
replied—
“Monsieur Soyer, we can spare a pony for you, but you must ask
permission of the master of the horse or Lord Raglan, as I have special
orders not to lend one upon my own responsibility. I am sure his lordship
will let you have it immediately.”
At this moment I caught sight of Lord Raglan’s valet, and I begged him
to make the request; which he did, and came to tell me that his lordship
desired I should have it by all means. Once more mounted, I made an early
call upon the friends of the previous night, most of whom resided round
head-quarters. I had the pleasure of being introduced to General Estcourt,
who took me to see the printing press where my receipts for the army were
done—some of which have appeared in the public press. Afterwards I went
with him to his quarters, which, though small, were very neatly arranged.
The taste was not military, and I thought that I detected the work of a
female hand, which I could not help remarking to the general.
“You are right, Monsieur,” said he, smiling—“it has only lately been
arranged by ladies. Mrs. Estcourt and my sister are here, and this is a little
bit of their handywork. They are staying on board ship at Balaklava, and
come here every day. Before they arrived I had only this small room
(showing me his bed made upon boards) where I sleep as well as ever I did
in my life. The only thing which awakes me in the night is when the cannon
ceases firing—I am so used to it.”
“I believe that, general, and have no doubt you seldom miss hearing a
report. In fact, you are the nearest of those at head-quarters to Sebastopol.”
I then inquired about the sortie of the previous night. The general said he
did not know the result of it, and very kindly invited me to breakfast, which
I declined, having to go round the French camp in search of my pony.
“I shall be happy,” said General Estcourt, “to do anything I can for you;
and if you call in the afternoon, my wife and her sister will be here, and I
will introduce you to them.”
Thanking him kindly, I retired, and proceeded round the French camp
making inquiries; then to their head-quarters, where I met Captain Boucher,
General Canrobert’s aide-de-camp, with whom I had the pleasure of
travelling. He promised to introduce me to the general, who, he said, would
be very glad to see me. Upon my telling him about my pony, he remarked—
“If he is in our camp you are sure to get him back, for we have put a stop
to that kind of piracy by very severe punishment. They used to come and
steal our horses from our very stables; but tell me what sort of a horse he is,
and I will advertise him with the others, and we shall know in less than five
or six hours if he is in our camp? the plan we have adopted cannot fail.”
Having described the animal to the captain, I thanked him for his
kindness.
Considering my French review terminated, I thought of returning at once
to the English head-quarters, having to see several of the authorities upon
business. On my way I happened to pass by a nice French canteen. I
inquired if I could get any breakfast? A rather stout vivandière, dressed in
the uniform of the Imperial Guard, very politely said to me:
“What a stupid question to ask! Do you think we have not everything
required for the purpose here? Perhaps, Captain of the Lord knows what
regiment, you think we have come out merely to thread pearls, sing ‘Partant
pour la Syrie,’ and dance the Fandango.”
On my way I visited several regimental kitchens and tasted the soup.
Some was better than at others. They had no vegetables excepting some
vegetable marrow—more likely to spoil the soup than improve it. I made
several important discoveries respecting the system of cooking pursued in
the French camp, after visiting, with some of my new acquaintances, a row
of twelve kitchens, which number, they informed me, was required for each
regiment—being at the rate of one per company. One man was told off as
cook for every squad or mess of sixteen. The buildings were composed of
mud and stone, and covered an extent of about four hundred yards. I bade
my brave companions farewell, and left them quite a happy man, having
entirely forgotten horse and saddle, in making the discovery that in lieu of
four hundred yards of space, a dozen buildings, and about eighty men for
each regiment, an immense consumption of fuel, and smoke enough to
blind three parts of the army—as the men were all cooks in turn—my
system was simple, effective, and vastly superior to that even of the French,
which had hitherto always been considered as preferable to the English.
This was indeed the case, for all French soldiers understand a little cooking,
and their canteen, pan was far superior to that in use amongst the English
troops, which I condemned at first sight in the camp at Chobham.
I returned to head-quarters, intending to communicate my discovery to
Lord Raglan; but learning that he was very busy, and would not be
disengaged till evening, I went to Colonel Steele, who, in spite of the
pressure of business, gave me an immediate audience, and promised to
speak to Lord Raglan on the subject. Head-quarters were that day, in a
manner, taken by storm. They were literally besieged, and this gave me an
opportunity of getting acquainted with several officers and other officials
whom I had not the pleasure of knowing—or, at least, only by sight.
Amongst these were Sir George Brown, Sir W. Codrington, Sir Colin
Campbell, Lord Rokeby, Captain Whitmore, and Brevet-Major A.
Macdonald.
Lord Raglan passed me in the passage, and said, “You wish to see me,
Monsieur Soyer?”
Knowing his lordship was much occupied, I replied, “Colonel Steele will
give you the particulars that I came to communicate.”
“That will do; but have you found your horse?”
“No, my lord.”
“I have been to visit Miss Nightingale. She is still very ill. Bad job, bad
job, poor lady!” he continued, walking away towards Colonel Steele’s
office, with his hands full of papers.
After this I called upon Doctor Hall, with whom I had a few minutes’
conversation upon business. Louis was somewhere about, busily engaged,
and, as usual, unwilling to give a direct reply, no matter what question you
put to him. He came to see me. I inquired if he knew anything about the
sortie of the previous night, upon which he answered that the black horse he
rode the day before had thrown him in the mud, and made him in such a
mess. I replied in his style:
“The sun is very hot to-day.”
Upon which he observed, “he never was there in his life.”
I begged of him to tell me how he was to-morrow.
“Don’t believe that,” said he; “it is quite false.”
An interesting young man indeed was Louis.
A very great curiosity then made its appearance, breaking the thread of
our scientific conversation. What, reader, do you think it was? A carriage!—
a thing unknown in the camp—or at least a bad imitation of one—drawn by
two very obstinate mules, one pulling against the other, which seemed to
amuse my intelligent friend Louis, who never liked to see anything going
on smoothly. General Estcourt went out to meet it, and two ladies alighted.
To this Louis thoroughly objected, saying—“Ladies, indeed! they are the
two female Zouaves who performed in the Anglaises pour Rire, at the
theatre in their camp. One,” said he, “is Jean Huguet—the other Panaudet,
aide-de-camp to the drum-major of a regiment of cavalry. The first plays
Lady Painbeche in that tragedy—the other, Lady Don’t-you-wish-you-may-
get-it.”
Very fertile indeed was the brain of Louis at composition of the higher
school; and, like Marplot, never wishing to see anything in its right light, he
succeeded admirably. The sight of a carriage was something wonderful, but
two ladies at once, and fashionably dressed, was too much good-luck. I
advanced towards them, and had the honour of being introduced by the
general to Mrs. Estcourt and his sister. The general invited me to walk in,
and I had the honour of taking a glass of wine with the fair—who might
well be called fairies at the time—ladies being so scarce, in fact, all but
invisible, in the Crimea.
After a short, but very interesting, conversation with the ladies, I retired,
leaving some copies of my receipts with Mrs. Estcourt, who kindly
undertook to look at the proofs before printing. Thence I proceeded to the
General Camp Hospital, and there met Doctor Mouatt, who told me he was
waiting for the bricks for his oven from the Ordnance Office at head-
quarters. I informed him that I had given in the plan for a kitchen, and
endeavoured to convince him of the necessity of having it done at once.
“I am well aware of that, and it shall be attended to.”
All inquiries respecting my pony were fruitless. At last, upon asking at a
canteen, a soldier told me he had heard of one being found in some
regiment, but could not tell me which one, though he thought it was
somewhere about Cathcart’s Hill.
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

More Related Content

Similar to Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph Walde (20)

PDF
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
linkyalsida
 
PDF
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
lucotkioes
 
PDF
Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
SULTHAN BASHA
 
PDF
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
chueyseipp1i
 
PDF
3350703
Vipul Chauhan
 
PPT
01slide
Horesh Kumar
 
PDF
Functional Programming In Scala Second Edition Meap V08 2nd All Chapters Avai...
cawulineriku
 
PPT
01slide (1)ffgfefge
bsnl007
 
PPT
Core java-introduction
Ramlal Pawar
 
PDF
Course-Plan-Object Oriented Concept (18CS45)1.pdf
abhijit.tec
 
PPT
Java for C++ programers
Salahaddin University-Erbil
 
PPTX
VMC___JAVA-THIRD QUARTER-SHS TWELVE.pptx
michellebacayplacide
 
PDF
Essentials of Database Management 1st Edition Hoffer Solutions Manual
lelanaarshat
 
PDF
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
tomzikyamben
 
PDF
Introduction to Java
Professional Guru
 
PPTX
object oriented programming systems OOPS
GUNASEKARAN331094
 
PDF
(Data structures) programming and problem solving
Shishir Roy
 
PDF
Programming and problem solving with c++, 3rd edition
Indian Maritime University, Visakhapatnam
 
DOCX
Mi0041 java and web design
smumbahelp
 
DOCX
Mi0041 java and web design
smumbahelp
 
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
linkyalsida
 
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
lucotkioes
 
Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
SULTHAN BASHA
 
(eBook PDF) Introduction to Programming with Java: A Problem Solving Approach...
chueyseipp1i
 
3350703
Vipul Chauhan
 
01slide
Horesh Kumar
 
Functional Programming In Scala Second Edition Meap V08 2nd All Chapters Avai...
cawulineriku
 
01slide (1)ffgfefge
bsnl007
 
Core java-introduction
Ramlal Pawar
 
Course-Plan-Object Oriented Concept (18CS45)1.pdf
abhijit.tec
 
Java for C++ programers
Salahaddin University-Erbil
 
VMC___JAVA-THIRD QUARTER-SHS TWELVE.pptx
michellebacayplacide
 
Essentials of Database Management 1st Edition Hoffer Solutions Manual
lelanaarshat
 
Introduction To Objectoriented Programming An 3rd Edition Timothy Budd
tomzikyamben
 
Introduction to Java
Professional Guru
 
object oriented programming systems OOPS
GUNASEKARAN331094
 
(Data structures) programming and problem solving
Shishir Roy
 
Programming and problem solving with c++, 3rd edition
Indian Maritime University, Visakhapatnam
 
Mi0041 java and web design
smumbahelp
 
Mi0041 java and web design
smumbahelp
 

Recently uploaded (20)

PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PPTX
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PDF
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPT
21st Century Literature from the Philippines and the World QUARTER 1/ MODULE ...
isaacmendoza76
 
PPTX
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PPTX
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Parsing HTML read and write operations and OS Module.pptx
Ramakrishna Reddy Bijjam
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
21st Century Literature from the Philippines and the World QUARTER 1/ MODULE ...
isaacmendoza76
 
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
Ad

Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph Walde

  • 1. Java Java Java Objectoriented Problem Solving 3rd Edition Ralph Morelli Ralph Walde download https://ebookbell.com/product/java-java-java-objectoriented- problem-solving-3rd-edition-ralph-morelli-ralph-walde-42892438 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Objectoriented Programming From Problem Solving To Java Programming Series 1st Edition Jose M Garrido https://ebookbell.com/product/objectoriented-programming-from-problem- solving-to-java-programming-series-1st-edition-jose-m-garrido-1691376 Java Programming Fundamentals Problem Solving Through Object Oriented Analysis And Design 1st Edition Premchand S Nair https://ebookbell.com/product/java-programming-fundamentals-problem- solving-through-object-oriented-analysis-and-design-1st-edition- premchand-s-nair-2406494 Java Methods Objectoriented Programming And Data Structures Third Ap 3rd Ap Maria Litvin https://ebookbell.com/product/java-methods-objectoriented-programming- and-data-structures-third-ap-3rd-ap-maria-litvin-59073076 Java Methods Objectoriented Programming And Data Structures 4th Edition 4th Maria Litvin https://ebookbell.com/product/java-methods-objectoriented-programming- and-data-structures-4th-edition-4th-maria-litvin-60399372
  • 3. Beginning Java 17 Fundamentals Objectoriented Programming In Java 17 3rd Ed Kishori Sharan https://ebookbell.com/product/beginning-java-17-fundamentals- objectoriented-programming-in-java-17-3rd-ed-kishori-sharan-36428050 Beginning Scala 3 A Functional And Objectoriented Java Language 3rd Ed Pollak https://ebookbell.com/product/beginning-scala-3-a-functional-and- objectoriented-java-language-3rd-ed-pollak-38030352 The Java Workshop Learn Objectoriented Programming And Kickstart Your Career In Software Development David Cuartielles https://ebookbell.com/product/the-java-workshop-learn-objectoriented- programming-and-kickstart-your-career-in-software-development-david- cuartielles-46712648 Learn Objectoriented Java The Hard Way Graham Mitchell https://ebookbell.com/product/learn-objectoriented-java-the-hard-way- graham-mitchell-48927976 Java Programming A Step By Step Beginners Guide To Code With An Objectoriented Program Megane Noel https://ebookbell.com/product/java-programming-a-step-by-step- beginners-guide-to-code-with-an-objectoriented-program-megane- noel-47526070
  • 5. Java, Java, Java Object-Oriented Problem Solving Third Edition R. Morelli and R. Walde Trinity College Hartford, CT June 25, 2017
  • 6. This work is licensed under a Creative Commons Attribution 4.0 International License (CC BY 4.0). This book was previously published by Pearson Education, Inc.
  • 7. Preface to the Open Source Edition Java, Java, Java, 3e was previously published by Pearson Education, Inc. The first edition (2000) and the second edition (2003) were published by Prentice-Hall. In 2010 Pearson Education, Inc. reassigned the copyright to the authors, and we are happy now to be able to make the book available under an open source license. This PDF edition of the book is available under a Creative Commons Attribution 4.0 International License, which allows the book to be used, modified, and shared with attribution: (https://creativecommons.org/licenses/by/4.0/). – Ralph Morelli and Ralph Walde – Hartford, CT – December 30, 2016 i
  • 8. ii
  • 9. Preface to the Third Edition We have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course. This edition retains the “objects first” approach to programming and problem solving that was characteristic of the first two editions. Throughout the text we emphasize careful coverage of Java language features, introductory programming concepts, and object-oriented design principles. The third edition retains many of the features of the first two editions, including: • Early Introduction of Objects • Emphasis on Object Oriented Design (OOD) • Unified Modeling Language (UML) Diagrams • Self-study Exercises with Answers • Programming, Debugging, and Design Tips. • From the Java Library Sections • Object-Oriented Design Sections • End-of-Chapter Exercises • Companion Web Site, with Power Points and other Resources The In the Laboratory sections from the first two editions have been moved onto the book’s Companion Web Site. Table 1 shows the Table of Contents for the third edition. What’s New in the Third Edition The third edition has the following substantive changes: • Although the book retains its emphasis on a “running example” that is revisited in several chapters, the CyberPet examples have been replaced with a collection of games and puzzle examples. The CyberPet examples from earlier editions will be available on the Companion Web Site. iii
  • 10. iv Table 1: Table of Contents for the Third Edition. Chapter Topic Chapter 0 Computers, Objects, and Java (revised) Chapter 1 Java Program Design and Development Chapter 2 Objects: Defining, Creating, and Using Chapter 3 Methods: Communicating with Objects (revised) Chapter 4 Input/Output: Designing the User Interface (new) Chapter 5 Java Data and Operators Chapter 6 Control Structures Chapter 7 Strings and String Processing Chapter 8 Inheritance and Polymorphism (new) Chapter 9 Arrays and Array Processing Chapter 10 Exceptions: When Things Go Wrong Chapter 11 Files and Streams Chapter 12 Recursive Problem Solving Chapter 13 Graphical User Interfaces Chapter 14 Threads and Concurrent Programming Chapter 15 Sockets and Networking (expanded) Chapter 16 Data Structures: Lists, Stacks, and Queues (revised and expanded) • Chapters 0 (Computers, Objects, and Java) and 1 (Java Program De- sign and Development) have been substantially reorganized and rewritten. The new presentation is designed to reduce the pace with which new concepts are introduced. The treatment of object- oriented (OO) and UML concepts has also been simplified, and some of the more challenging OO topics, such as polymorphism, have been moved to a new Chapter 8. • The new Java 1.5 Scanner class is introduced in Chapter 2 and is used to perform simple input operations. • Chapter 4 (Input/Output: Designing the User Interface) has been completely written. Rather than relying primarily on applet inter- faces, as in the second edition, this new chapter provides indepen- dent introductions to both a command-line interface and a graphi- cal user interface (GUI). Instructors can choose the type of interface that best suits their teaching style. The command-line interface is based on the BufferedReader class and is used throughout the rest of the text. The GUI is designed to work with either graphi- cal applications or applets. Both approaches are carefully presented to highlight the fundamentals of user-interface design. The chapter concludes with an optional section that introduces file I/O using the new Scanner class. • Much of the discussion of inheritance and polymorphism, which was previously woven through the first five chapters in the second edition, has been integrated into a new Chapter 8. • An optional graphics track is woven throughout the text. Beginning with simple examples in Chapters 1 and 2, this track also includes
  • 11. v some of the examples that were previously presented in Chapter 10 of the second edition. • Chapter 15, on Sockets and Networking, is expanded to cover some of the more advanced Java technologies that have emerged, includ- ing servlets and Java Server Pages. • Chapter 16, on Data Structures, has been refocused on how to use data structures. It makes greater use of Java’s Collection Framework, including the LinkedList and Stack classes and the List inter- face. It has been expanded to cover some advanced data structures, such as sets, maps, and binary search trees. The Essentials Edition An Essentials Edition of the third edition, which will include Chapters 0- 12, will be published as a separate title. The Essentials Edition will cover those topics (Chapters 0-9) that are covered in almost all introductory (CS1) courses, but it will also include topics (Exceptions, File I/O, and Recursion) that many CS1 instructors have requested. Why Start with Objects? The Third Edition still takes an objects-early approach to teaching Java, with the assumption that teaching beginners the “big picture” early gives them more time to master the principles of object-oriented programming. This approach seems now to have gained in popularity as more and more instructors have begun to appreciate the advantages of the object-oriented perspective. Object Orientation (OO) is a fundamental problem solving and design concept, not just another language detail that should be relegated to the middle or the end of the book (or course). If OO concepts are introduced late, it is much too easy to skip over them when push comes to shove in the course. The first time I taught Java in our CS1 course I followed the same ap- proach I had been taking in teaching C and C++ — namely, start with the basic language features and structured programming concepts and then, somewhere around midterm, introduce object orientation. This approach was familiar, for it was one taken in most of the textbooks then available in both Java and C++. One problem with this approach was that many students failed to get the big picture. They could understand loops, if-else constructs, and arith- metic expressions, but they had difficulty decomposing a programming problem into a well-organized Java program. Also, it seemed that this procedural approach failed to take advantage of the strengths of Java’s object orientation. Why teach an object-oriented language if you’re going to treat it like C or Pascal? I was reminded of a similar situation that existed when Pascal was the predominant CS1 language. Back then the main hurdle for beginners was procedural abstraction — learning the basic mechanisms of procedure call
  • 12. vi and parameter passing and learning how to design programs as a collec- tion of procedures. Oh! Pascal!, my favorite introductory text, was typical of a “procedures early” approach. It covered procedures and parameters in Chapter 2, right after covering the assignment and I/O constructs in Chapter 1. It then covered program design and organization in Chap- ter 3. It didn’t get into loops, if-else, and other structured programming concepts until Chapter 4 and beyond. Today, the main hurdle for beginners is the concept of object abstraction. Beginning programmers must be able to see a program as a collection of interacting objects and must learn how to decompose programming prob- lems into well-designed objects. Object orientation subsumes both proce- dural abstraction and structured programming concepts from the Pascal days. Teaching objects-early takes a top-down approach to these three im- portant concepts. The sooner you begin to introduce objects and classes, the better the chances that students will master the important principles of object orientation. Java is a good language for introducing object orientation. Its object model is better organized than C++. In C++ it is easy to “work around” or completely ignore OO features and treat the language like C. In Java there are good opportunities for motivating the discussion of object orien- tation. For example, it’s almost impossible to discuss GUI-based Java ap- plications without discussing inheritance and polymorphism. Thus rather than using contrived examples of OO concepts, instructors can use some of Java’s basic features — the class library, Swing and GUI components — to motivate these discussions in a natural way. Organization of the Text The book is still organized into three main parts. Part I (Chapters 0-4) in- troduces the basic concepts of object orientation and the basic features of the Java language. Part II (Chapters 5-9) focuses on remaining language el- ements, including data types, control structures, string and array process- ing, and inheritance and polymorphism. Part III (Chapters 10-16) covers advanced topics, including exceptions, file I/O, recursion, GUIs, threads and concurrent programming, sockets and networking, data structures, servlets, and Java Server Pages. The first two parts make up the topics that are typically covered in an introductory CS1 course. The chapters in Part III are self-contained and can be selectively added to the end of a CS1 course if time permits. The first part (Chapters 0 through 4) introduces the basic concepts of object orientation, including objects, classes, methods, parameter passing, information hiding, and a little taste of inheritance, and polymorphism. The primary focus in these chapters is on introducing the basic idea that an object-oriented program is a collection of objects that communicate and cooperate with each other to solve problems. Java language elements are introduced as needed to reinforce this idea. Students are given the basic building blocks for constructing Java programs from scratch. Although the programs in the first few chapters have limited function- ality in terms of control structures and data types, the priority is placed
  • 13. vii Table 2: A one-semester course. Weeks Topics Chapters 1 Object Orientation, UML Chapter 0 Program Design and Development Chapter 1 2-3 Objects and Class Definitions Chapter 2 Methods and Parameters Chapter 3 Selection structure (if-else) 4 User Interfaces and I/O Chapter 4 5 Data Types and Operators Chapter 5 6–7 Control Structures (Loops) Chapter 6 Structured Programming 8 String Processing (loops) Chapter 7 9 Inheritance and Polymorphism Chapter 8 10 Array Processing Chapter 9 11 Recursion Chapter 12 12 Advanced Topic (Exceptions) Chapter 10 13 Advanced Topic (GUIs) Chapter 11 Advanced Topic (Threads) Chapter 15 on how objects are constructed and how they interact with each other through method calls and parameter passing. The second part (Chapters 5 through 9) focuses on the remaining lan- guage elements, including data types and operators (Chapter 5), control structures (Chapter 6), strings (Chapter 7), and arrays (Chapter 9). It also provides thorough coverage of inheritance and polymorphism, the primary mechanisms of object orientation: (Chapter 8). Part three (Chapters 10 through 16) covers a variety of advanced topics (Table 1). Topics from these chapters can be used selectively depending on instructor and student interest. Throughout the book, key concepts are introduced through simple, easy-to-grasp examples. Many of the concepts are used to create a set of games, which are used as a running example throughout the text. Our pedagogical approach focuses on design. Rather than starting of with lan- guage details, programming examples are carefully developed with an emphasis on the principles of object-oriented design. Table2 provides an example syllabus from our one-semester CS1 course. Our semester is 13 weeks (plus one reading week during which classes do not meet). We pick and choose from among the advanced topics during the last two weeks of the course, depending on the interests and skill levels of the students. Ralph Morelli June 25, 2017
  • 14. viii
  • 15. Contents 0 Computers, Objects, and Java 1 0.1 Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 0.2 What Is a Computer? . . . . . . . . . . . . . . . . . . . . . . . 2 0.3 Networks, the Internet and the World Wide Web . . . . . . . 4 0.4 Why Study Programming? . . . . . . . . . . . . . . . . . . . . 6 0.5 Programming Languages . . . . . . . . . . . . . . . . . . . . 7 0.6 Why Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 0.7 What Is Object-Oriented Programming? . . . . . . . . . . . . 11 1 Java Program Design and Development 23 1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 1.2 Designing Good Programs . . . . . . . . . . . . . . . . . . . . 24 1.3 Designing a Riddle Program . . . . . . . . . . . . . . . . . . . 26 1.4 Java Language Elements . . . . . . . . . . . . . . . . . . . . . 34 1.5 Editing, Compiling, and Running a Java Program . . . . . . 48 1.6 From the Java Library: System and PrintStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 2 Objects: Using, Creating, and Defining 61 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 2.2 Using String Objects . . . . . . . . . . . . . . . . . . . . . . 62 2.3 Drawing Shapes with a Graphics Object (Optional) . . . . 66 2.4 Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . 69 2.5 CASE STUDY: Simulating a Two-Person Game . . . . . . . . 76 2.6 From the Java Library: java.util.Scanner. . . . . . . . . 90 3 Methods: Communicating with Objects 101 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 3.2 Passing Information to an Object . . . . . . . . . . . . . . . . 102 3.3 Constructor Methods . . . . . . . . . . . . . . . . . . . . . . . 109 3.4 Retrieving Information from an Object . . . . . . . . . . . . . 114 3.5 Passing a Value and Passing a Reference . . . . . . . . . . . . 118 3.6 Flow of Control: Control Structures . . . . . . . . . . . . . . . 121 3.7 Testing an Improved OneRowNim . . . . . . . . . . . . . . . . 130 3.8 From the Java Library java.lang.Object . . . . . . . . . 135 3.9 Object-Oriented Design: Inheritance and Polymorphism . . 136 3.10 Drawing Lines and Defining Graphical Methods (Optional) 138 4 Input/Output: Designing the User Interface 149 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 ix
  • 16. x CONTENTS 4.2 The User Interface . . . . . . . . . . . . . . . . . . . . . . . . . 150 4.3 A Command-Line Interface . . . . . . . . . . . . . . . . . . . 151 4.4 A Graphical User Interface (GUI) . . . . . . . . . . . . . . . . 160 4.5 Case Study: The One Row Nim Game . . . . . . . . . . . . . 176 4.6 From the Java Library: java.io.File and File Input (Optional) . . . . . . . . . . . . . . . . . . . . . 183 5 Java Data and Operators 197 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 5.2 Boolean Data and Operators . . . . . . . . . . . . . . . . . . . 199 5.3 Numeric Data and Operators . . . . . . . . . . . . . . . . . . 205 5.4 From the Java Library java.lang.Math . . . . . . . . . . . 216 5.5 Numeric Processing Examples . . . . . . . . . . . . . . . . . 217 5.6 From the Java Library java.text.NumberFormat . . . . . . . . . . . . . . . . . . 229 5.7 Character Data and Operators . . . . . . . . . . . . . . . . . . 231 5.8 Example: Character Conversions . . . . . . . . . . . . . . . . 235 5.9 Problem Solving = Representation + Action . . . . . . . . . . 237 6 Control Structures 241 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 6.2 Flow of Control: Repetition Structures . . . . . . . . . . . . . 242 6.3 Counting Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 243 6.4 Example: Car Loan . . . . . . . . . . . . . . . . . . . . . . . . 252 6.5 Graphics Example: Drawing a Checkerboard . . . . . . . . . 255 6.6 Conditional Loops . . . . . . . . . . . . . . . . . . . . . . . . 259 6.7 Example: Computing Averages . . . . . . . . . . . . . . . . . 266 6.8 Example: Data Validation . . . . . . . . . . . . . . . . . . . . 270 6.9 Principles of Loop Design . . . . . . . . . . . . . . . . . . . . 270 6.10 The switch Multiway Selection Structure . . . . . . . . . . . 273 6.11 OBJECT-ORIENTED DESIGN: Structured Programming . . . . . . . . . . . . . . . . . . . . . 277 7 Strings and String Processing 297 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 7.2 String Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 7.3 Finding Things Within a String . . . . . . . . . . . . . . . . . 304 7.4 Example: Keyword Search . . . . . . . . . . . . . . . . . . . . 306 7.5 From the Java Library: java.lang.StringBuffer . . . . . . . . . 308 7.6 Retrieving Parts of Strings . . . . . . . . . . . . . . . . . . . . 310 7.7 Example: Processing Names and Passwords . . . . . . . . . 312 7.8 Processing Each Character in a String . . . . . . . . . . . . 313 7.9 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . 317 7.10 From the Java Library: java.util.StringTokenizer . . . . . . . . . . . . . . . . . . . . . 323 7.11 Handling Text in a Graphics Context (Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 8 Inheritance and Polymorphism 337 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 8.2 Java’s Inheritance Mechanism . . . . . . . . . . . . . . . . . . 338
  • 17. CONTENTS xi 8.3 Abstract Classes, Interfaces, and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . 347 8.4 Example: A Toggle Button . . . . . . . . . . . . . . . . . . . . 353 8.5 Example: The Cipher Class Hierarchy . . . . . . . . . . . . . 357 8.6 Case Study: A Two Player Game Hierarchy . . . . . . . . . . 363 8.7 Principles Of Object-Oriented Design . . . . . . . . . . . . . 384 9 Arrays and Array Processing 393 9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 9.2 One-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 394 9.3 Simple Array Examples . . . . . . . . . . . . . . . . . . . . . 401 9.4 Example: Counting Frequencies of Letters . . . . . . . . . . . 403 9.5 Array Algorithms: Sorting . . . . . . . . . . . . . . . . . . . . 406 9.6 Array Algorithms: Searching . . . . . . . . . . . . . . . . . . 414 9.7 Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 417 9.8 Multidimensional Arrays (Optional) . . . . . . . . . . . . . . 426 9.9 OBJECT-ORIENTED DESIGN: Polymorphic Sorting (Optional) . . . . . . . . . . . . . . . . . 428 9.10 From the Java Library: java.util.Vector . . . . . . . . . . . . . 430 9.11 Case Study: An N-Player Computer Game . . . . . . . . . . 431 9.12 A GUI-Based Game (Optional Graphics) . . . . . . . . . . . . 437 10 Exceptions: When Things Go Wrong 459 10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 10.2 Handling Exceptional Conditions . . . . . . . . . . . . . . . . 460 10.3 Java’s Exception Hierarchy . . . . . . . . . . . . . . . . . . . 462 10.4 Handling Exceptions Within a Program . . . . . . . . . . . . 466 10.5 Error Handling and Robust Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . 477 10.6 Creating and Throwing Your Own Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 10.7 From the Java Library: JOptionPane . . . . . . . . . . . . . 489 11 Files and Streams: Input/Output Techniques 499 11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 11.2 Streams and Files . . . . . . . . . . . . . . . . . . . . . . . . . 500 11.3 CASE STUDY: Reading and Writing Text Files . . . . . . . . 505 11.4 The File Class . . . . . . . . . . . . . . . . . . . . . . . . . . 518 11.5 Example: Reading and Writing Binary Files . . . . . . . . . . 521 11.6 Object Serialization: Reading and Writing Objects . . . . . . 530 11.7 From the Java Library javax.swing.JFileChooser . . . . . . . . . . . . . . . . 535 11.8 Using File Data in Programs . . . . . . . . . . . . . . . . . . . 536 12 Recursive Problem Solving 545 12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 12.2 Recursive Definition . . . . . . . . . . . . . . . . . . . . . . . 549 12.3 Recursive String Methods . . . . . . . . . . . . . . . . . . . . 551 12.4 Recursive Array Processing . . . . . . . . . . . . . . . . . . . 563 12.5 Example: Drawing (Recursive) Fractals . . . . . . . . . . . . 569
  • 18. xii CONTENTS 12.6 OBJECT-ORIENTED DESIGN: Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 12.7 OBJECT-ORIENTED DESIGN: Recursion or Iteration? . . . . . . . . . . . . . . . . . . . . . . 574 12.8 From the Java Library: javax.swing.JComboBox . . . . . . . . . . . . . . . . . . . . . 577 13 Graphical User Interfaces 591 13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 13.2 Java GUIs: From AWT to Swing . . . . . . . . . . . . . . . . . 592 13.3 The Swing Component Set . . . . . . . . . . . . . . . . . . . . 595 13.4 OBJECT-ORIENTED DESIGN: Model-View-Controller Architecture . . . . . . . . . . . . . . 596 13.5 The Java Event Model . . . . . . . . . . . . . . . . . . . . . . 598 13.6 CASE STUDY: Designing a Basic GUI . . . . . . . . . . . . . 602 13.7 Containers and Layout Managers . . . . . . . . . . . . . . . . 614 13.8 Checkboxes, Radio Buttons, and Borders . . . . . . . . . . . 620 13.9 Menus and Scroll Panes . . . . . . . . . . . . . . . . . . . . . 629 14 Threads and Concurrent Programming 643 14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644 14.2 What Is a Thread? . . . . . . . . . . . . . . . . . . . . . . . . . 644 14.3 From the Java Library: java.lang.Thread . . . . . . . . . 648 14.4 Thread States and Life Cycle . . . . . . . . . . . . . . . . . . . 654 14.5 Using Threads to Improve Interface Responsiveness . . . . . . . . . . . . . . . . 656 14.6 CASE STUDY: Cooperating Threads . . . . . . . . . . . . . . 664 14.7 CASE STUDY: The Game of Pong . . . . . . . . . . . . . . . . 679 15 Sockets and Networking 693 15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 15.2 An Overview of Networks . . . . . . . . . . . . . . . . . . . . 694 15.3 Using Multimedia Network Resources for a Graphical Pro- gram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700 15.4 From the Java Library: java.net.URL . . . . . . . . . . . . 701 15.5 The Slide Show Program . . . . . . . . . . . . . . . . . . . . . 704 15.6 Adding Text Network Resources for an Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708 15.7 Client/Server Communication via Sockets . . . . . . . . . . 719 15.8 CASE STUDY: Generic Client/Server Classes . . . . . . . . . 724 15.9 Playing One Row Nim Over the Network . . . . . . . . . . . 732 15.10Java Network Security Restrictions . . . . . . . . . . . . . . . 741 15.11Java Servlets and Java Server Pages . . . . . . . . . . . . . . . 742 16 Data Structures: Lists, Stacks, and Queues 757 16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 16.2 The Linked List Data Structure . . . . . . . . . . . . . . . . . 758 16.3 OBJECT-ORIENTED DESIGN: The List Abstract Data Type (ADT) . . . . . . . . . . . . . . . 770 16.4 The Stack ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . 776 16.5 The Queue ADT . . . . . . . . . . . . . . . . . . . . . . . . . . 778
  • 19. CONTENTS xiii 16.6 From the Java Library: The Java Collections Framework and Generic Types . . . . . . . . . . . . . . . . . . . . . . . . 782 16.7 Using the Set and Map Interfaces . . . . . . . . . . . . . . . 785 16.8 The Binary Search Tree Data Structure . . . . . . . . . . . . . 789 A Coding Conventions 801 B The Java Development Kit 809 C The ASCII and Unicode Character Sets 819 D Java Keywords 821 E Operator Precedence Hierarchy 823 F Java Inner Classes 825 G Java Autoboxing and Enumeration 831 H Java and UML Resources 837
  • 21. OBJECTIVES After studying this chapter, you will • Understand basic computer terminology that will be used throughout the book. • Become familiar with the notion of programming. • Understand why Java is a good introductory programming language. • Become familiar with Java objects and classes. • Know some of the principles of the object-oriented programming approach. OUTLINE 0.1 Welcome 0.2 What Is a Computer? Special Topic: Processors Then and Now 0.3 Networks, the Internet and the World Wide Web 0.4 Why Study Programming? 0.5 Programming Languages 0.6 Why Java? 0.7 What Is Object-Oriented Programming? Chapter Summary Exercises Chapter 0 Computers, Objects, and Java 1
  • 22. 2 CHAPTER 0 • Computers, Objects, and Java 0.1 Welcome Welcome to Java, Java, Java, a book that introduces you to object-oriented programming using the Java language. When considering the purpose of this text, three important questions might come to mind: Why study programming? Why study Java? What is object-oriented programming? This chapter will address these questions. First, we provide a brief in- troduction to computers and the Internet and World Wide Web (WWW). Then, we address why someone would study programming and we ex- amine types of programming languages. We introduce the Java program- ming language and conclude the chapter by exploring object-oriented pro- gramming principles and how Java is an object-oriented programming language. 0.2 What Is a Computer? A computer is a machine that performs calculations and processes infor- mation. A computer works under the control of a computer program, a set of instructions that tell a computer what to do. Hardware refers to the electronic and mechanical components of a computer. Software refers to the programs that control the hardware. A general-purpose computer of the sort that we will be programming can store many different programs in its memory. That is what gives it the ability to perform a wide variety of functions, from word processing to browsing the Internet. This is in contrast to a special-purpose computer, such as the one that resides in your microwave oven or the one that controls your digital watch or calculator. These types of computers contain control programs that are fixed and cannot be changed. A computer’s hardware is organized into several main subsystems or components (Fig. 1). Figure 1: A diagram of the main functional components in a com- puter system. The arrows indicate the flow of information between various components. Secondary Storage Main Memory Input Devices Keyboard Mouse Optical Scanner Output Devices Printer Monitor Audio Speakers Central Processing Unit (CPU) Disk Drive CD-ROM DVD • Output devices provide a means by which information held in the com- puter can be displayed in some understandable or usable form. Com- mon output devices include printers, monitors, and audio speakers.
  • 23. SECTION 0.2 • What Is a Computer? 3 • Input devices bring data and information into the computer. Some of the more common input devices are the keyboard, mouse, microphone, and scanner. • Primary memory or main memory of a computer is used to store both data and programs. This type of memory, which is often called RAM, short for Random Access Memory, is built entirely out of electronic components—integrated circuit chips—which makes it extremely fast. A computer’s main memory is volatile, which means that any informa- tion stored in it is lost when the computer’s power is turned off. In a sense, main memory acts as the computer’s scratch pad, storing both programs and data temporarily while a program is running. • Secondary storage devices are used for long-term or permanent stor- age of relatively large amounts of information. These devices include hard drives or magnetic disks, compact disks (CDs), digital video disks (DVDs), and magnetic tapes. All of these devices are non-volatile, mean- ing that they retain information when the computer’s power is turned off. Compared to a computer’s primary memory, these devices are relatively slow. • The central processing unit (CPU) is the computer’s main engine. The CPU is the computer’s microprocessor, such as the Intel Pentium pro- cessor, which serves as the foundation for most Windows PCs, or the Power-PC processor, which serves as the foundation for Macintosh computers. The CPU is designed to perform the fetch-execute cycle, Fetch-execute cycle whereby it repeatedly gets the next machine instruction from memory and executes it. Under the direction of computer programs (software), the CPU issues signals that control the other components that make up the computer system. One portion of the CPU, known as the arithmetic- logic unit (ALU), performs all calculations, such as addition and sub- traction, and all logical comparisons, such as when one piece of data is compared to another to determine if they are equal. There are two main types of software: • Application software refers to programs designed to provide a particular task or service, such as word processors, computer games, spreadsheet programs, and Web browsers. • System software includes programs that perform the basic operations that make a computer usable. For example, an important piece of system software is the operating system, which contains programs that manage the data stored on the computer’s disks. An operating system assists application software in performing tasks that are considered primitive or low-level, such as managing the com- puter’s memory and its input and output devices. Another important thing that the operating system does is to serve as an interface between the user and the hardware. The operating system determines how the user will interact with the system, or conversely, how the system will look and feel to the user. For example, in command-line systems, such as Unix and DOS (short for Disk Operating System), a pro- gram is run by typing its name on the command line. By contrast, in
  • 24. 4 CHAPTER 0 • Computers, Objects, and Java graphically based systems, such as Windows and Macintosh, a program is run by clicking on its icon with the mouse. Thus, this “point-and-click” interface has a totally different “look and feel” but does the same thing. Special Topic: Processors Then and Now To give you some idea of how rapidly computer hardware technology has advanced, let’s compare the first digital processor with one of today’s models. The ENIAC (which stood for Electronic Numerical Integrator and Cal- culator) was developed in 1946 at the University of Pennsylvania primar- ily for calculating ballistic trajectories for the U.S. Army. ENIAC occupied more than 640 square feet of floor space and weighed nearly 30 tons. In- stead of the integrated circuits or chip technology used in today’s comput- ers, ENIAC’s digital technology was based on over 17,000 vacuum tubes. ENIAC, which could perform around 300 multiplications per second, ran more than 500 times faster than other computing machines of that day and age. To program the ENIAC, you would have to manipulate hundreds of cables and switches. It took two or three days for a team of several pro- grammers, most of whom were young women, to set up a single program that would then run for a few seconds. One of today’s most advanced and powerful processors for desktop computers is Intel’s Pentium IV processor. This chip contains 42 million transistors and runs at speeds over 3 GHz (3 gigahertz or 3 billion cycles per second). The Pentium processor is small enough to fit in a space the size of your pinky finger’s fingernail. Despite its size, it executes millions of instructions per second, thereby enabling it to support a huge range of multimedia applications, including three-dimensional graphics, stream- ing audio and video, and speech recognition applications. To write pro- grams for the Pentium, you can choose from a wide range of high-level programming languages, including the Java language. 0.3 Networks, the Internet and the World Wide Web Most personal computers contain software that enables them to be con- nected to various-sized networks of computers. Networks allow many in- dividual users to share costly computer resources, such as a high-speed printer or a large disk drive or application server that is used to store and distribute both data and programs to the computers on the network. Net- works can range in size from local area networks (LANs), which connect computers and peripherals over a relatively small area, such as within a lab or a building, through wide area networks (WANs), which can span large geographic areas, such as cities and nations. Client/server computing Application servers are just one example of client/server computing, a computing approach made possible by networks. According to this ap- proach, certain computers on the network are set up as servers, which pro- vide certain well-defined services to client computers. For example, one computer in a network may be set up as the email server, with the responsi-
  • 25. SECTION 0.3 • Networks, the Internet and the World Wide Web 5 bility of sending, receiving, and storing mail for all users on the network. To access their email on the email server, individual users employ client application software that resides on their desktop computers, such as Out- look Express or Eudora or Pine. Similarly, another server may be set up as a Web server, with the responsibility of storing and serving up Web pages for all the users on the network. Users can run Web browsers, another type of client software, to access Web pages on the server. Java is particularly well suited for these types of networked or distributed applications, where part of the application software resides on a server and part resides on the client computer. The Internet (with a capital I) is a network of networks whose geo- graphical area covers the entire globe. The World Wide Web (WWW) is another example of distributed, client/server computing. The WWW is not a separate physical network. Rather it is a subset of the Internet that uses the HyperText Transfer Protocol (HTTP). A protocol is a set of rules and conventions that govern how communication takes place between two computers. HTTP is a multimedia protocol, which means that it supports the transmission of text, graphics, sound, and other forms of information. Certain computers within a network run special software that enables them to play the role of HTTP (or Web) servers. They store Web documents and are capable of handling requests for documents from client browser applications. The servers and clients can be located anywhere on the Internet. The documents stored on Web servers are encoded in a special text- based language known as HyperText Markup Language, or HTML. Web browsers, such as Netscape’s Navigator and Microsoft’s Internet Explorer, are designed to interpret documents coded in this language. The language itself is very simple. Its basic elements are known as tags, which consist of certain keywords or other text contained within angle brackets, < and >. For example, if you wanted to italicize text on a Web page, you would enclose it between the < I > and < /I > tags. Thus, the following HTML code $I$ I t a l i c font$/I$ can be used for $I$emphasis$/I$ . would be displayed by the Web browser as Italic font can be used for emphasis. When you use a Web browser to surf the Internet, you repeatedly instruct your browser to go to a certain location and retrieve a page that is encoded in HTML. For example, if you typed the following URL (Uniform Resource Locator) http : //www. prenhall . com/morelli/index . html into your browser, the browser would send a message to the Web server www located in the prenhall.com domain—the prenhall portion of this address specifies Prentice Hall and the com portion specifies the com- mercial domain of the Internet—requesting that the document named index.html in the morelli directory be retrieved and sent back to your
  • 26. 6 CHAPTER 0 • Computers, Objects, and Java Figure 2: WWW: The client’s browser requests a page from a Web server. When the HTML doc- ument is returned, it is interpreted and displayed by the browser. Display Internet Send a document Request a document HTML document Server Client HTTP software Text y y y y y y y y y y y y y y y y y y y y Browser software computer (Fig. 2). The beauty of the Web is that it is possible to embed text, sound, video, and graphics within an HTML document, making it possible to download a wide range of multimedia resources through this (relatively) simple mechanism. The Web has begun to change business, entertainment, commerce, and education. The fact that it is possible to download computer games and other application software from the Web is changing the way software and other digital products are purchased and distributed. Similarly, as noted earlier, many businesses have begun to organize their information systems into intranets—private networks that implement the HTTP protocol. Cur- rently, one of the biggest areas of development on the Web is commerce. As consumers become more comfortable that credit-card information can be securely transmitted over the Web (as it can over a telephone), the Web will explode as a marketing medium as powerful, perhaps, as television is today. Because Java has been designed to support secure, distributed, networked applications, it is ideally suited to be used as the language for these types of applications. 0.4 Why Study Programming? A computer program is a set of instructions that directs the computer’s behavior. Computer programming is the art and science of designing and writing programs. Years ago it was widely believed that entrance into the computer age would require practically everyone to learn how to pro- gram. But this did not prove to be true. Today’s computers come with so much easy-to-use software that knowing how to use a computer no longer requires programming skills. Another reason to study programming might be to enter into a career as a computer scientist. However, although programming is one of its primary tools, computer science is a broad and varied discipline, which ranges from engineering subjects, such as processor design, to mathemat- ical subjects, such as performance analysis. There are many computer sci- entists who do little or no programming as part of their everyday work. If you plan to major or minor in computer science, you will certainly learn to program, but good careers in the computing field are available to programmers and nonprogrammers alike.
  • 27. SECTION 0.5 • Programming Languages 7 One of the best reasons to study programming is because it is a cre- ative and enjoyable problem-solving activity. This book will teach you to develop well-designed solutions to a range of interesting problems. One of the best things about programming is that you can actually see and experience your solutions as running programs. As many students have indicated, there’s really nothing like the kick you get from seeing your program solving a problem you’ve been struggling with. Designing and building well-written programs provides a powerful sense of accomplish- ment and satisfaction. What’s more, Java is a language that makes pro- gramming even more fun, because once they’re finished, many Java pro- grams can be posted on the World Wide Web (WWW) for all the world to see! 0.5 Programming Languages Most computer programs today are written in a high-level language, such as Java, C, C++, or FORTRAN. A programming language is considered high level if its statements resemble English-language statements. For example, all of the languages just mentioned have some form of an “if” statement, which says, “if some condition holds, then take some action.” Computer scientists have invented hundreds of high-level program- ming languages, although relatively few of these have been put to prac- tical use. Some of the widely used languages have special features that make them suitable for one type of programming application or another. COBOL (COmmon Business-Oriented Language), for example, is still widely used in commercial applications. FORTRAN (FORmula TRANsla- tor) is still preferred by some engineers and scientists. C and C++ are still the primary languages used by operating system programmers. In addition to having features that make them suitable for certain types of applications, high-level languages use symbols and notation that make them easily readable by humans. For example, arithmetic operations in Java make use of familiar operators such as “+” and “−” and “/”, so that arithmetic expressions look more or less the way they do in algebra. So, to take the average of two numbers, you might use the expression ( a + b ) / 2 The problem is that computers cannot directly understand such expres- sions. In order for a computer to run a program, the program must first be translated into the computer’s machine language, which is the language understood by its CPU or microprocessor. Each type of microprocessor has its own particular machine language. That’s why when you buy soft- ware it runs either on a Macintosh, which uses the Power-PC chip, or on a Windows machine, which uses the Pentium chip, but not on both. When a Platform independence program can run on just one type of chip, it is known as platform dependent. In general, machine languages are based on the binary code, a two- valued system that is well suited for electronic devices. In a binary repre- sentation scheme, everything is represented as a sequence of 1’s and 0’s, which corresponds closely to the computer’s electronic “on” and “off” states. For example, in binary code, the number 13 would be repre-
  • 28. 8 CHAPTER 0 • Computers, Objects, and Java sented as 1101. Similarly, a particular address in the computer’s memory might be represented as 01100011, and an instruction in the computer’s instruction set might be represented as 001100. The instructions that make up a computer’s machine language are very simple and basic. For example, a typical machine language might in- clude instructions for ADD, SUBTRACT, DIVIDE, and MULTIPLY, but it wouldn’t contain an instruction for AVERAGE. In most cases, a single in- struction, called an opcode, carries out a single machine operation on one or more pieces of data, called its operands. Therefore, the process of av- eraging two numbers would have to be broken down into two or more steps. A machine language instruction itself might have something sim- ilar to the following format, in which an opcode is followed by several operands, which refer to the locations in the computer’s primary memory where the data are stored. The following instruction says ADD the num- ber in LOCATION1 to the number in LOCATION2 and store the result in LOCATION3: Opcode Operand 1 Operand 2 Operand 3 011110 110110 111100 111101 (ADD) (LOCATION 1) (LOCATION 2) (LOCATION 3) Given the primitive nature of machine language, an expression like (a + b)/2 would have to be translated into a sequence of several machine language instructions that, in binary code, might look as follows: 011110110110111100111101 000101000100010001001101 001000010001010101111011 In the early days of computing, before high-level languages were de- veloped, computers had to be programmed directly in their machine languages, an extremely tedious and error-prone process. Imagine how difficult it would be to detect an error that consisted of putting a 0 in the preceding program where a 1 should occur! Fortunately, we no longer have to worry about machine languages, be- cause special programs can be used to translate a high-level or source code program into machine language code or object code, which is the only code that can be executed or run by the computer. In general, a pro- gram that translates source code to object code is known as a translator (Fig. 3). Thus, with suitable translation software for Java or C++ we can write programs as if the computer could understand Java or C++ directly. Source code translators come in two varieties. An interpreter trans- lates a single line of source code directly into machine language and ex- ecutes the code before going on to the next line of source code. A com- piler translates the entire source code program into executable object code, which means that the object code can then be run directly without further translation. There are advantages and disadvantages to both approaches. Inter- preted programs generally run less efficiently than compiled programs,
  • 29. SECTION 0.6 • Why Java? 9 High-level language Translator software Machine language Source code Object code (a+b)/2 000110101 101000110 101000110 Figure 3: Translator software translates high-level source code to machine language object code. because they must translate and execute each line of the program before proceeding to the next line. If a line of code is repeated, an interpreter would have to translate the line each time it is encountered. By contrast, once compiled, an object program is just executed without any need for further translation. It is also much easier to refine compiled code to make it run more efficiently. But interpreters are generally quicker and easier to develop and provide somewhat better error messages when things go wrong. Some languages that you may have heard of, such as BASIC, LISP, and Perl, are mostly used in interpreted form, although compilers are also available for these languages. Programs written in COBOL, FORTRAN, C, C++, and Pascal are compiled. As we will see in the next section, Java programs use both compilation and interpretation in their translation process. 0.6 Why Java? Originally named “Oak” after a tree outside the office of its developer, James Goslin, Java is a relatively young programming language. It was initially designed by Sun Microsystems in 1991 as a language for em- bedding programs into electronic consumer devices, such as microwave ovens and home security systems. However, the tremendous popularity of the Internet and the World Wide Web (WWW) led Sun to recast Java as a language for embedding programs into Web-based applications. As you recall, the Internet is a global computer network, and the WWW is that portion of the network that provides multimedia access to a vast range of information. Java has become one of the most important languages for Web and Internet applications. Java has also generated significant interest in the business community, where it is has proved to have tremendous commercial potential. In addi- tion to being a useful tool for helping businesses to promote their products and services over the Internet, Java is also a good language for distribut- ing software and providing services to employees and clients on private corporate networks or intranets. Because of its original intended role as a language for programming mi- croprocessors embedded in consumer appliances, Java has been designed with a number of interesting features: • Java is object oriented. Object-oriented languages divide programs into separate modules, called objects, that encapsulate the program’s data and operations. Thus, object-oriented programming (OOP) and object-oriented design (OOD) refer to a particular way of organizing pro- Object-oriented Languages
  • 30. 10 CHAPTER 0 • Computers, Objects, and Java grams, one which is rapidly emerging as the preferred approach for building complex software systems. Unlike the C++ language, in which object-oriented features were grafted onto the C language, Java was designed from scratch as an object-oriented language. • Java is robust, meaning that errors in Java programs don’t cause system crashes as often as errors in other programming languages. Certain features of the language enable many potential errors to be detected before a program is run. • Java is platform independent. A platform, in this context, is just a particu- Platform independence lar kind of computer system, such as a Macintosh or Windows system. Java’s trademark is “Write once, run anywhere.” This means that a Java program can be run without changes on different kinds of computers. This is not true for other high-level programming languages. This porta- bility – the ability to run on virtually any platform – is one reason that Java is well suited for WWW applications. • Java is a distributed language, which means that its programs can be designed to run on computer networks. In addition to the language it- self, Java comes with an extensive collection of code libraries—software that has been designed to be used directly for particular types of applications—that make it particularly easy to build software systems for the Internet and the WWW. This is one of the reasons why Java is so well suited for supporting applications on corporate networks. • Java is a secure language. Designed to be used on networks, Java con- tains features that protect against untrusted code—code that might in- troduce a virus or corrupt your system in some way. For example, once they are downloaded into your browser, Web-based Java pro- grams are prevented from reading and writing information from and to your desktop computer. Despite this list of attractive features, perhaps the best reason for choosing Java as an introductory programming language is its potential for bring- ing fun and excitement into learning how to program. There are few other languages in which a beginning programmer can write a computer game or a graphically based application that can be distributed on a Web page to just about any computer in the world. The simplicity of Java’s design and its easily accessible libraries bring such accomplishments within reach of the most novice programmers. For example, we will work on projects throughout the text that involve games and puzzles. We start out in Chapter 2 by designing very simple games that involve storing and retrieving data. As we learn more sophisti- cated programming techniques, we gradually build more complexity into the games and puzzles. For example, we learn how to create interactive, two-person games in Chapter 4. In Chapter 8, we develop some games and puzzles that are played on virtual game boards. Finally, in Chapter 14 we learn how to introduce games with multiple players on different com- puters. To get a look at where we are headed you might want to visit the authors’ companion Web site: http : //www. cs . t r i n c o l l . edu/˜ram/ j j j /
  • 31. SECTION 0.7 • What Is Object-Oriented Programming? 11 0.7 What Is Object-Oriented Programming? Java is an object-oriented (OO) language, and this book takes an object- oriented approach to programming. So before beginning our discussion of Java, it is important that we introduce some of the underlying con- cepts involved in object-oriented programming. We need to talk about what an object is, how objects are grouped into classes, how classes are related to each other, and how objects use messages to interact with and communicate with each other. 0.7.1 Basic Object-Oriented Programming Metaphor: Interacting Objects A Java program, and any object-oriented program, is a collection of inter- acting objects that models a collection of real-world Figure 4: A model of a kitchen. objects. Think of the model that a kitchen designer might use to layout your new kitchen (Fig. 4). It will contain objects that represent the various kitchen appliances and cabinets. Each object in the model is a simplified version of the corresponding real object. For example, a rectangle might be used to represent the refrigerator. A kitchen model is mostly static. It doesn’t change. Once put into place, its various objects just stand there in a certain relation to each other. By contrast, a computer program is dynamic. It changes. It does things and performs certain actions. The objects in a computer program communi- cate with each other and they change over time. In this respect, the objects that make up our computer programs are very anthropomorphic, a big word that means “like people.” If we are eating together and I want you to pass me the salt, I say, “Please pass me the salt,” and you invariably comply. Similarly, when you (Student X) put your ATM card into an ATM machine, the ATM object asks the bank’s database object “Give me Student X’s bank account object” and the database invariably complies. If you tell the ATM you want to withdraw $100 dollars it tells your bank account object to deduct $100 from your current balance. And so it goes. Both you and your bank account are changed objects as a result of the transaction. 0.7.2 What is an Object? So what is an object? Just as in the real world, an object is any thing whatsoever. An object can be a physical thing, such as a Car, or a mental thing, such as an Idea. It can be a natural thing, such as an Animal, or an artificial, human-made thing, such as a ATM. A program that manages an ATM would involve BankAccounts and Customer objects. A chess program would involve a Board object and ChessPiece objects. Throughout this text, we will use the notation shown in Figure 5 to depict objects and to illustrate object-oriented concepts. The notation is known as the Unified Modeling Language, or UML for short, and it is a standard in the object-oriented programming community. As the diagram shows, an object is represented by a rectangle whose label consists of the object’s (optional) id and its type. An object’s id is the name by which it is referred to in the computer program. In this case we show a ATM object, who’s id is not given, and a ChessPiece object, named pawn1. An object’s label is always underlined.
  • 32. 12 CHAPTER 0 • Computers, Objects, and Java Figure 5: In UML, objects are rep- resented by rectangles that are la- beled with a two-part label of the form id:Type. The object’s label is always underlined. 0.7.3 Attributes and Values Just as with real objects, the objects in our programs have certain char- acteristic attributes. For example, an ATM object would have a current amount of cash that it could dispense. A ChessPiece object might have a pair of row and column attributes that specify its position on the chess board. Notice that an object’s attributes are themselves objects. The ATM’s cash attribute and the chess piece’s row and column attributes are Numbers. Figure 6 shows two ATM objects and their respective attributes. As you can see, an object’s attributes are listed in a second partition of the UML diagram. Notice that each attribute has a value. So the lobby:ATM has a $8650.0 in cash, while the drivethru:ATM has only $150.0 in cash. Figure 6: A second partition of an object diagram is used to display the object’s attributes and their values. We sometimes refer to the collection of an object’s attributes and values as its state. For example, the current state of the lobby:ATM is $8650.0 in cash. Of course, this is a gross simplification of an ATM’s state, which would also include many other attributes. But, hopefully, you see the point. 0.7.4 Actions and Messages In addition to their attributes, objects also have characteristic actions or behaviors. As we have already said, objects in programs are dynamic. They do things or have things done to them. In fact, programming in Java is largely a matter of getting objects to perform certain actions for us. For example, in a chess program the ChessPieces have the ability to moveTo() a new position on the chess board. Similarly, when a customer pushes the “Current Balance” button on an ATM machine, this is telling the ATM to report() the customer’s current bank balance. (Note how we use parentheses to distinguish actions from objects and attributes.) The actions that are associated with an object can be used to send mes- sages to the objects and to retrieve information from objects. A message is the passing of information or data from one object to another. Figure 7 illustrates how this works. In UML, messages are represented by arrows.
  • 33. SECTION 0.7 • What Is Object-Oriented Programming? 13 Figure 7: Messages in UML are represented by labeled arrows. In this example, we are telling a pawn to move from its current po- sition to row 3 column 4. In this example, we are telling pawn1:ChessPiece to moveTo(3,4). The numbers 3 and 4 in this case are arguments that tell the pawn what square to move to. (A chess board has 8 rows and 8 columns and each square is identified by its row and column coordinates.) In general, an argument is a data value that specializes the content of a message in some way. In this example we are telling the pawn to move forward by 1 row. If we wanted the pawn to move forward by 2 rows, we would send the message moveTo(4,4). The diagram in Figure 8 depicts a sequence of messages representing an idealized ATM transaction. First, an ATM customer asks the ATM ma- chine to report his current balance. The ATM machine in turn asks the customer’s bank account to report the customer’s balance. The ATM re- ceives the value $528.52 from the bank account and passes it along to the customer. In this case, the message does not involve an argument. But it does involve a result. A result is information or data that is returned to the object that sent the message. Figure 8: This UML diagram illustrates an ATM transaction in which a customer asks the ATM machine for his current bal- ance. The ATM gets this informa- tion from an object representing the customer’s bank account and passes it to the customer. Obviously, in order to respond to a message, an object has to know how to perform the action that is requested. The pawn has to know how to move to a designated square. The ATM has to know how to find out the customer’s current balance. Indeed, an object can only respond to messages that are associated with its characteristic actions and behaviors. You can’t tell an ATM to move forward 2 squares. And you can’t ask a chess piece to tell you your current bank balance. Responding to a message or performing an action sometimes causes a change in an object’s state. For example, after performing moveTo(3, 4), the pawn will be on a different square. Its position will have changed. On the other hand, some messages (or actions) leave the object’s state un- changed. Reporting the customer’s bank account balance doesn’t change the balance. 0.7.5 What is a Class? A class is a template for an object. A class encapsulates the attributes and actions that characterize a certain type of object. In an object-oriented pro- gram, classes serve as blueprints or templates for the objects that the pro-
  • 34. 14 CHAPTER 0 • Computers, Objects, and Java Figure 9: A UML diagram of the Rectangle class. gram uses. We say that an object is an instance of a class. A good analogy here is to think of a class as a cookie cutter and its objects, or instances, as individual cookies. Just as we use the cookie cutter to stamp out cookies of a certain type, in an object-oriented program, we use a definition of a class to create objects of a certain type. Writing an object-oriented program is largely a matter of designing classes and writing definitions for those classes in Java. Designing a class is a matter of specifying all of the attributes and behaviors that are characteristic of that type of object. For example, suppose we are writing a drawing program. One type of object we would need for our program is a rectangle. A Rectangle object has two fundamental attributes, a length and a width. Given these attributes, we can define characteristic rectangle actions, such as the ability to calculate its area and the ability to draw itself. Identifying an object’s attributes and actions is the kind of design activity that goes into developing an object-oriented program. Figure 9 shows a UML diagram of our Rectangle class. Like the sym- bol for an object, a UML class symbol has up to three partitions. Unlike the UML object symbol, the label for a UML class gives just the class’s name and it is not underlined. The second partition lists the class’s attributes and the third partition lists the classes actions. Our rectangle has four attributes. The first two, x and y, determine a rectangles position on a two-dimensional graph. The second two, length and width, determine a rectangle’s dimensions. Note that the attributes have no values. This is because the class represents a general type of rectangle. It specifies what all rectangles have in common, without representing any particular rect- angle. Like a cookie cutter for a cookie, a class gives the general shape of an object. The content is not included. 0.7.6 Variables and Methods Up to this point we have been using the terms attribute and action to de- scribe an object’s features. We will continue to use this terminology when talking in general about objects or when talking about an object or class represented by a UML diagram. However, when talking about a programming language, the more com- mon way to describe an object’s features are to talk about its variables and methods. A variable, which corresponds to an attribute, is a named memory location that can store a certain type of value. You can think of a variable as a special container that can only hold objects of a certain type. For example, as Figure 9 shows, Rectangle’s length and width are
  • 35. SECTION 0.7 • What Is Object-Oriented Programming? 15 variables that can store a certain type of numeric value known as an int. An int value is a whole number, such as 76 or -5. A method, which corresponds to an action or a behavior, is a named chunk of code that can be called upon or invoked to perform a certain pre-defined set of actions. For example, in our Rectangle object, the calculateArea() method can be called upon to calculate the rectan- gle’s area. It would do this, of course, by multiplying the rectangle’s length by its width. Similarly, the draw() method can be invoked to draw a picture of the rectangle. It would take the actions necessary to draw a rectangle on the console. 0.7.7 Instance versus Class Variables and Methods Variables and methods can be associated either with objects or their classes. An instance variable (or instance method) is a variable (or method) that belongs to an object. By contrast, a class variable (or class method) is a variable (or method) that is associated with the class itself. An example will help make this distinction clear. An instance variable will have different values for different instances. For example, individual Rectangles will have different values for their length, width, x, and y variables. So these are examples of instance variables. The calculateArea() method is an example of an instance method because it uses the instance’s current length and width values in its calculation. Similarly, the draw() method is an instance method, because it uses the object’s length and width to draw the object’s shape. An example of a class variable would be a variable in the Rectangle class that is used to keep track of how many individual Rectangles have been created. (Our drawing program might need this information to help manage its memory resources.) Suppose we name this variable nRectangles and suppose we add 1 to it each time a new Rectangle instance is created. An example of a method that is associated with the class is a special method known as a constructor. This is a method used to create an object. It is used to create an instance of a class. Calling a constructor to create an object is like pressing the cookie cutter into the cookie dough: the result is an individual cookie (object). Figure 10 illustrates these concepts. Note that class variables are un- derlined in the UML diagram. We have modified the Rectangle class to include its constructor method, which is named Rectangle(). Note that it takes four arguments, representing the values that we want to give as the rectangle’s x, y, length and width respectively. Note also how the Rectangle class’s nRectangles variable has a value of 2, representing that two Rectangle instances have been created. These are shown as members of the Rectangle class. It won’t be obvious to you at this point, but nRectangles is a value that has to be associated with the Rectangle class, not with its instances. To see this let’s imagine what happens when a new Rectangle instance is created. Figure 11 illustrates the process. When the Rectangle() constructor is invoked, its arguments (100, 50, 25, 10) are used by the Rectangle class to create a Rectangle object located at x=100, y=50 and with a length of 25 and width of 10. The constructor method also increases
  • 36. 16 CHAPTER 0 • Computers, Objects, and Java Figure 10: The Rectangle class and two of its instances. Note that the class variable, nRectangles, is underlined to distinguish it from length and width, the in- stance variables. the value of nRectangles by 1 as a way of keeping count of how many objects it has created. Figure 11: Constructing a Rectangle instance. 0.7.8 Class Hierarchy and Inheritance How are classes related to each other? In Java, and in any other object- oriented language, classes are organized in a class hierarchy. A class hier- archy is like an upside-down tree. At the very top of the hierarchy is the most general class. In Java, the most general class is the Object class. The classes below Object in the hierarchy are known as its subclasses. Since all of the objects we use in our programs belong to some class or other, this is like saying that all objects are Objects. Figure 12 illustrates the concept of a class hierarchy using the classes that we have described in this section. Notice that the Object class oc- curs at the top of the hierarchy. It is the most general class. It has fea- tures that are common to all Java objects. As you move down the hierar- chy, the classes become more and more specialized. A Rectangle is an Object but it contains attributes – length and width – that are common to all rectangles but not to other objects in the hierarchy. For example, an ATM object does not necessarily have a length and a width. Notice that we have added a Square class to the hierarchy. A Square is a special type of Rectangle, namely one who’s length equals its width. To introduce some important terminology associated with this kind of hierarchy, we say that the Rectangle class is a subclass of the Object Superclass and subclass
  • 37. SECTION 0.7 • What Is Object-Oriented Programming? 17 hierarchy of Java class. The Square class is a subclass of both Rectangle and Object. Classes that occur above a given class in the hierarchy are said to be its superclasses. Thus Rectangle class is superclass of the Square class. The Object class is also a superclass of Square. In general, we say that a subclass extends a superclass, meaning that it adds additional elements (attributes and/or methods) to those contained in its superclasses. We saw this in the case of the Square class. It adds the feature that its length and width are always equal. Another important concept associated with a class hierarchy is the no- Class inheritance tion of class inheritance, whereby a subclass inherits elements (attributes and/or methods) from its superclasses. To take an example from the nat- ural world, think of the sort of inheritance that occurs between a horse and a mammal. A horse is a mammal. So horses inherit the characteristic of being warm blooded by virtue of also being mammals. (This is dif- ferent from the kind of individual inheritance whereby you inherit your mother’s blue eyes and your father’s black hair.) To illustrate how inheritance works, lets go back to our chess program. There are several different types of ChessPieces. There are Pawns, and Knights, and Queens and Kings. Figure 13 illustrates the chess piece hierarchy. A pair of attributes that all chess pieces have in common is their row and column position on the chess board. Because all chess pieces have these attributes in common, they are located at the top of the ChessPiece hierarchy and inherited by all ChessPiece subclasses. Of course, the row and column attributes are given different values in each ChessPiece object. One of the actions that all chess pieces have in common is that they can moveTo() a given square on the chess board. But different types of chess pieces have different ways of moving. For example, a Bishop can only move along diagonals on the chess board, whereas a Rook can only move along a row or column on the chess board. So, clearly, we can’t describe a moveTo() method that will work for all ChessPieces. This is why we put the moveTo() method in all of the ChessPiece subclasses. The ChessPiece class also has a moveTo() method, but note that its name is italicized. This indicates that it cannot be completely defined at that level. Finally, note that in chess, the king has certain special attributes and actions. Thus only the king can be put in check. This means that the king is under attack and in danger of being captured, thereby ending the game. Similarly, only the king has the ability to castle. This is special move that
  • 38. 18 CHAPTER 0 • Computers, Objects, and Java Figure 13: The ChessPiece hier- archy. a king can make together with one of its rooks under certain conditions. Thus, the reason we show the inCheck attribute and castle() action in the King class is because these are characteristics that particular to Kings. In this way, a class hierarchy represents a specialization of classes as you move from top to bottom. The most general class, ChessPiece, is at the top of the hierarchy. Its attributes and methods are passed on to (inher- ited by) its subclasses. However, in addition to the attributes and methods they inherit from their superclasses, the subclasses define their own spe- cial attributes and methods. Each of the subclasses, Pawn, Bishop, and so on, represents some kind of specialization of the superclass. In this ex- ample, each of the subclasses have their own distinctive ways of moving. And the King subclass has unique attributes and actions (inCheck and castle(). 0.7.9 Principles of Object-Oriented Design As we have discussed, an object-oriented program is composed of many objects communicating with each other. The process of designing an object-oriented program to solve some problem or other involves several important principles: • Divide-and-Conquer Principle. Generally, the first step in designing a program is to divide the overall problem into a number of objects that will interact with each other to solve the problem. Thus, an object- oriented program employs a division of labor much as we do in organiz- ing many of our real-world tasks. This divide-and-conquer approach is an important problem-solving strategy. • Encapsulation Principle. Once the objects are identified, the next step involves deciding, for each object, what attributes it has and what ac- tions it will take. The goal here is to encapsulate within each object
  • 39. SECTION 0.7 • What Is Object-Oriented Programming? 19 the expertise needed to carry out its role in the program. Each object is a self-contained module with a clear responsibility and the tools (at- tributes and actions) necessary to carry out its role. Just as a dentist encapsulates the expertise needed to diagnose and treat a tooth ache, a well-designed object contains the information and methods needed to perform its role. • Interface Principle. In order for objects to work cooperatively and effi- ciently, we have to clarify exactly how they should interact, or interface, with one another. An object’s interface should be designed to limit the way the object can be used by other objects. Think of how the different interfaces presented by a digital and analog watch determine how the watches are used. In a digital watch, time is displayed in discrete units, and buttons are used to set the time in hours, minutes and seconds. In an analog watch, the time is displayed by hands on a clock face, and time is set, less precisely, by turning a small wheel. • Information Hiding Principle. In order to enable objects to work to- gether cooperatively, certain details of their individual design and per- formance should be hidden from other objects. To use the watch anal- ogy again, in order to use a watch we needn’t know how its time keep- ing mechanism works. That level of detail is hidden from us. Hiding such implementation details protects the watch’s mechanism, while not limiting its usefulness. • Generality Principle. To make objects as generally useful as possible, we design them not for a particular task but rather for a particular kind of task. This principle underlies the use of software libraries. As we will see, Java comes with an extensive library of classes that specialize in performing certain kinds of input and output operations. For example, rather than having to write our own method to print a message on the console, we can use a library object to handle our printing tasks. • Extensibility Principle. One of the strengths of the object-oriented ap- proach is the ability to extend an object’s behavior to handle new tasks. This also has its analogue in the everyday world. If a company needs sales agents to specialize in hardware orders, it would be more eco- nomical to extend the skills of its current sales agents instead of train- ing a novice from scratch. In the same way, in the object-oriented ap- proach, an object whose role is to input data might be specialized to input numeric data. • Abstraction Principle. Abstraction is the ability to focus on the impor- tant features of an object when trying to work with large amounts of information. For example, if we are trying to design a floor plan for a kitchen, we can focus on the shapes and relative sizes of the appliances and ignore attributes such as color, style, and manufacturer. The ob- jects we design in our Java programs will be abstractions in this sense because they ignore many of the attributes that characterize the real objects and focus only on those attributes that are essential for solving a particular problem. These, then, are the principles that will guide our discussion as we learn how to design and write object-oriented Java programs.
  • 40. 20 CHAPTER 0 • Computers, Objects, and Java CHAPTER SUMMARY Technical Terms action (behavior) argument attribute class class inheritance class hierarchy class method class variable compiler computer program constructor high-level language instance instance method instance variable interpreter method message object object code object oriented result source code subclass superclass Unified Modeling Language (UML) variable Summary of Important Points • A computer system generally consists of input/output devices, pri- mary and secondary memory, and a central processing unit. A com- puter can only run programs in its own machine language, which is based on the binary code. Special programs known as compilers and in- terpreters translate source code programs written in a high-level language, such as Java, into machine language object code programs. • Application software refers to programs designed to provide a particu- lar task or service; systems software assists the user in using application software. • The client/server model is a form of distributed computing in which part of the software for a task is stored on a server and part on client comput- ers. • HyperText Markup Language (HTML) is the language used to encode WWW documents. • A Java program is a set of interacting objects. This is the basic metaphor of object-oriented programming. • An object in a Java program encapsulates the program’s attributes (or variables) and actions (or methods). A variable is a named memory lo- cation where data of appropriate type can be stored. A method is a named section of code that can be called (or invoked) when needed. • An object’s methods are used to pass messages to it. • A class is an abstract template that defines the characteristics and be- haviors of all objects of a certain type. • An object is an instance of a class. An object has instance methods and in- stance variables. A class method (or class variable) is a method (or variable) that is associated with the class itself, not with its instances. • A constructor is a special method that is used to construct objects. • Java classes are organized into a class hierarchy, with the Object class at the top of the hierarchy. For a given class, classes that occur below it in the hierarchy are called its subclasses, while classes that occur above it are called its superclasses. • Classes inherit attributes and methods from their superclasses. This is known as class inheritance. • The main principles of the object-oriented programming approach are as follows: • Divide and Conquer: Successful problem solving involves breaking a complex problem into objects.
  • 41. CHAPTER 0 • Exercises 21 • Encapsulation and Modularity: Each object should be assigned a clear role. • Public Interface: Each object should present a clear public interface that determines how other objects will use it. • Information Hiding: Each object should shield its users from unnec- essary details of how it performs its role. • Generality: Objects should be designed to be as general as possible. • Extensibility: Objects should be designed so that their functionality can be extended to carry out more specialized tasks. • Abstraction is the ability to group a large quantity of information into a single chunk so it can be managed as a single entity. EXERCISES EXERCISE 0.1 Fill in the blanks in each of the following statements. a. Dividing a problem or a task into parts is an example of the principle. b. Designing a class so that it shields certain parts of an object from other objects is an example of the principle. c. Java programs that can run without change on a wide variety of computers is an example of . d. The fact that social security numbers are divided into three parts is an example of the principle. e. To say that a program is robust means that . f. An is a separate module that encapsulates a Java program’s attributes and actions. EXERCISE 0.2 Explain the difference between each of the following pairs of concepts. a. hardware and software b. systems and application software c. compiler and interpreter d. machine language and high-level language e. general-purpose and special-purpose computer f. primary and secondary memory g. the CPU and the ALU h. the Internet and the WWW i. a client and a server j. HTTP and HTML k. source and object code EXERCISE 0.3 Fill in the blanks in each of the following statements. a. A is a set of instructions that directs a computer’s behavior. b. A disk drive would be an example of a device. c. A mouse is an example of an device. d. A monitor is an example of an device. e. The computer’s functions like a scratch pad. f. Java is an example of a programming language. g. The Internet is a network of .
  • 42. 22 CHAPTER 0 • Computers, Objects, and Java h. The protocol used by the World Wide Web is the protocol. i. Web documents are written in code. j. A is a networked computer that is used to store data for other computers on the network. EXERCISE 0.4 Identify the component of computer hardware that is responsi- ble for the following functions. a. executing the fetch-execute cycle b. arithmetic operations c. executing instructions d. storing programs while they are executing e. storing programs and data when the computer is off EXERCISE 0.5 Explain why a typical piece of software, such as a word proces- sor, cannot run on both a Macintosh and a Windows machine. EXERCISE 0.6 What advantages do you see in platform independence? What are the disadvantages? EXERCISE 0.7 In what sense is a person’s name an abstraction? In what sense is any word of the English language an abstraction? EXERCISE 0.8 Analyze the process of writing a research paper in terms of the divide-and-conquer and encapsulation principles. EXERCISE 0.9 Analyze your car by using object-oriented design principles. In other words, pick one of your car’s systems, such as the braking system, and ana- lyze it in terms of the divide-and-conquer, encapsulation, information-hiding, and interface principles. EXERCISE 0.10 Make an object oriented analysis of the interaction between, a student, librarian, and a library database when a student checks a book out of a college library.
  • 43. OBJECTIVES After studying this chapter, you will • Know the basic steps involved in program development. • Understand some of the basic elements of the Java language. • Know how to use simple output operations in a Java program. • Be able to distinguish between different types of errors in a program. • Understand how a Java program is translated into machine language. • Understand the difference between a Java console application and a Java Swing application. • Know how to edit, compile, and run Java programs. OUTLINE 1.1 Introduction 1.2 Designing Good Programs 1.3 Designing a Riddle Program Special Topic: Grace Hopper and the First Computer Bug 1.4 Java Language Elements 1.5 Editing, Compiling, and Running a Java Program 1.6 From the Java Library: System and PrintStream 1.7 From the Java Library: System and PrintStream Chapter Summary Solutions to Self-Study Exercises Exercises Chapter 1 Java Program Design and Development 23
  • 44. 24 CHAPTER 1 • Java Program Design and Development 1.1 Introduction This chapter introduces some of the basic concepts and techniques in- volved in Java program design and development. We begin by identi- fying the main steps in designing an object-oriented program. The steps are illustrated by designing a program that “asks” and “answers” riddles. As an example of a riddle, consider the question “What is black and white and read all over?” The answer, of course, is a newspaper. Following the design phase, we then focus on the steps involved in coding a Java program, including the process of editing, compiling, and running a pro- gram. Because Java programs can be text based applications or window based graphical applications, we describe how the coding process differs for these two varieties. Next we begin to familiarize ourselves with Java’s extensive class li- brary by studying its PrintStream and System classes. These classes contain objects and methods that enable us to print output from a pro- gram. By the end of the chapter you will be able to design and write a Java application that “sings” your favorite song. 1.2 Designing Good Programs Programming is not simply a question of typing Java code. Rather, it in- volves a considerable amount of planning and careful designing. Badly designed programs rarely work correctly. Even though it is tempting for novice programmers to start entering code almost immediately, one of the first rules of programming is JAVA PROGRAMMING TIP The sooner you begin to type code, the longer the program will take to finish, because careful design of the program must precede coding. This is particularly true of object-oriented programs. In other words, the more thought and care you put into designing a pro- gram, the more likely you are to end up with one that works correctly. The following subsections provide a brief overview of the program develop- ment process. 1.2.1 The Software Engineering Life Cycle Software engineering is the process of designing and writing software. The software life cycle refers to the different phases involved in the design and development of a computer program. Our presentation of examples in the book will focus on four phases of the overall life cycle. In the spec- ification phase we provide a statement of the problem and a detailed de- scription of what the program will do. In the design phase we describe the details of the various classes, methods, and data that will be used in the program. The implementation phase refers to the actual coding of the program into Java. In the testing phase we test the program’s performance to make sure it is correct, recoding it or redesigning it as necessary. Figure 1.1 gives a more detailed overview of the program development process, focusing most of the attention on the design phase of the software
  • 45. SECTION 1.2 • Designing Good Programs 25 life cycle. It shows that designing an object-oriented program is a matter of asking the right questions about the classes, data, and methods that make up the program. Overall, the program development process can be viewed as one that repeatedly applies the divide-and-conquer principle. That is, most pro- gramming problems can be repeatedly divided until you have a collection of relatively easy-to-solve subproblems, each of which can be handled by an object. In this way the program is divided into a collection of interact- Divide and conquer ing objects. For each object we design a class. During class design, each object is divided further into its variables and methods. Problem Specification What exactly is the problem? How will the program be used? How will the program behave? Data Design What types of instance variables are needed? Should they be public or private? Algorithm Design What information is needed? What control structures are needed? Problem Decomposition What objects will be used and how will they interact with each other? The problem is divided into objects. For each object we design a class. Program Development Process The object's role decomposes into tasks. Each task can be assigned to a method. Method design involves designing an algorithm. Errors may require recoding or redesigning. Coding into Java Stepwise refinement Fixing syntax errors Testing, Debugging, Revising Designing test data and test cases Fixing semantic errors Class Design What role or roles will the object perform? What variables (attributes) will it need? What methods (behaviors) will it use? What interface will it present? What information will it hide? Method Design What task will the method perform? What information will it need? What algorithm will it use? What result will it produce? Figure 1.1: An overview of the program development process. When should we stop subdividing? How much of a task should be assigned to a single object or a single method? The answers to these and similar questions are not easy. Good answers require the kind of judg- ment that comes through experience, and frequently there is more than one good way to design a solution. Here again, as we learn more about
  • 46. 26 CHAPTER 1 • Java Program Design and Development object-oriented programming, we’ll learn more about how to make these design decisions. 1.3 Designing a Riddle Program The first step in the program-development process is making sure you un- derstand the problem (Fig. 1.1). Thus, we begin by developing a detailed specification, which should address three basic questions: • What exactly is the problem to be solved? • How will the program be used? • How should the program behave? In the real world, the problem specification is often arrived at through an extensive discussion between the customer and the developer. In an introductory programming course, the specification is usually assigned by the instructor. To help make these ideas a little clearer, let’s design an object-oriented solution to a simple problem. Problem Specification. Design a class that will represent a riddle with a given question and answer. The definition of this class should make it possible to store different riddles and to retrieve a riddle’s question and answer independently. 1.3.1 Problem Decomposition Most problems are too big and too complex to be tackled all at once. So the next step in the design process is to divide the problem into parts that Divide and conquer make the solution more manageable. In the object-oriented approach, a problem is divided into objects, where each object will handle one specific aspect of the program’s overall job. In effect, each object will become an expert or specialist in some aspect of the program’s overall behavior. Note that there is some ambiguity here about how far we should go in decomposing a given program. This ambiguity is part of the design process. How much we should decompose the program before its parts become “simple to solve” depends on the problem we’re trying to solve and on the problem solver. One useful design guideline for trying to decide what objects are needed is the following: JAVA EFFECTIVE DESIGN Looking for Nouns. Choosing a program’s objects is often a matter of looking for nouns in the problem specification. Again, there’s some ambiguity involved in this guideline. For example, the key noun in our current problem is riddle, so our solution will involve an object that serves as a model for a riddle. The main task of this Java object will be simply to represent a riddle. Two other nouns in the spec- ification are question and answer. Fortunately, Java has built-in String
  • 47. SECTION 1.3 • Designing a Riddle Program 27 objects that represent strings of characters such as words or sentences. We can use two String objects for the riddle’s question and answer. Thus, for this simple problem, we need only design one new type of object—a riddle—whose primary role will be to represent a riddle’s question and answer. Don’t worry too much if our design decisions seem somewhat myste- rious at this stage. A good understanding of object-oriented design can come only after much design experience, but this is a good place to start. 1.3.2 Object Design Once we have divided a problem into a set of cooperating objects, de- signing a Java program is primarily a matter of designing and creating the objects themselves. In our example, this means we must now design the features of our riddle object. For each object, we must answer the following basic design questions: • What role will the object perform in the program? • What data or information will it need? • What actions will it take? • What interface will it present to other objects? • What information will it hide from other objects? For our riddle object, the answers to these questions are shown in Fig- ure 1.2. Note that although we talk about “designing an object,” we are really talking about designing the object’s class. A class defines the col- lection of objects that belong to it. The class can be considered the ob- ject’s type. This is the same as for real-world objects. Thus, Seabiscuit is a horse—that is, Seabiscuit is an object of type horse. Similarly, an individ- ual riddle, such as the newspaper riddle, is a riddle. That is, it is an object of type Riddle. The following discussion shows how we arrived at the decisions for the design specifications for the Riddle class, illustrated in Figure 1.2. • Class Name: Riddle • Role: To store and retrieve a question and answer • Attributes (Information) • question: A variable to store a riddle’s question (private) • answer: A variable to store a riddle’s answer (private) • Behaviors • Riddle(): A method to set a riddle’s question and answer • getQuestion(): A method to return a riddle’s question • getAnswer(): A method to return a riddle’s answer Figure 1.2: Design specification for the Riddle class. The role of the Riddle object is to model an ordinary riddle. Because What is the object’s role? a riddle is defined in terms of its question and answer, our Riddle ob- ject will need some way to store these two pieces of information. As we learned in Chapter 0, an instance variable is a named memory location that belongs to an object. The fact that the memory location is named, makes it easy to retrieve the data stored there by invoking the variable’s name. For example, to print a riddle’s question we would say something like “print question,” and whatever is stored in question would be retrieved and printed.
  • 48. 28 CHAPTER 1 • Java Program Design and Development In general, instance variables are used to store the information that an object needs to perform its role. They correspond to what we have been What information will the object need? calling the object’s attributes. Deciding on these variables provides the answer to the question, “What information does the object need?” Next we decide what actions a Riddle object will take. A useful design guideline for actions of objects is the following: JAVA EFFECTIVE DESIGN Looking for Verbs. Choosing the behavior of an object is often a matter of looking for verbs in the problem specification. What actions will the object take? For this problem, the key verbs are set and retrieve. As specified in Fig- ure 1.2, each Riddle object should provide some means of setting the values of its question and answer variables and a means of retrieving each value separately. Each of the actions we have identified will be encapsulated in a Java method. As you recall from Chapter 0, a method is a named section of code that can be invoked, or called upon, to perform a particular action. In the object-oriented approach, calling a method (method invocation) is the means by which interaction occurs among objects. Calling a method is like sending a message between objects. For example, when we want to get a riddle’s answer, we would invoke the getAnswer() method. This is like sending the message “Give me your answer.” One special method, known as a constructor, is invoked when an object is first created. We will use the Riddle() constructor to give specific values to riddle’s question and answer variables. In designing an object, we must decide which methods should be made available to other objects. This determines what interface the object should What interface will it present, and what information will it hide? present and what information it should hide from other objects. In gen- eral, those methods that will be used to communicate with an object are designated as part of the object’s interface. Except for its interface, all other information maintained by each riddle should be kept “hidden” from other objects. For example, it is not necessary for other objects to know where a riddle object stores its question and answer. The fact that they are stored in variables named question and answer, rather than variables named ques and ans, is irrelevant to other objects. JAVA EFFECTIVE DESIGN Object Interface. An object’s interface should consist of just those methods needed to communicate with or to use the object. JAVA EFFECTIVE DESIGN Information Hiding. An object should hide most of the details of its implementation.
  • 49. SECTION 1.3 • Designing a Riddle Program 29 Taken together, these various design decisions lead to the specification Figure 1.3: A UML class diagram representing the Riddle class. shown in Figure 1.3. As our discussion has illustrated, we arrived at the decisions by asking and answering the right questions. In most classes the attributes (variables) are private. This is represented by a minus sign (−). In this example, the operations (methods) are public, which is represented by the plus sign (+). The figure shows that the Riddle class has two hidden (or private) variables for storing data and three visible (or public) methods that represent the operations that it can perform. 1.3.3 Data, Methods, and Algorithms Among the details that must be worked out in designing a riddle object is deciding what type of data, methods, and algorithms we need. There are two basic questions involved: • What type of data will be used to represent the information needed by the riddle? • How will each method carry out its task? Like other programming languages, Java supports a wide range of differ- ent types of data, some simple and some complex. Obviously a riddle’s What type of data will be used? question and answer should be represented by text. As we noted earlier, Java has a String type, which is designed to store text, which can be considered a string of characters. In designing a method, you have to decide what the method will do. In How will each method carry out its task? order to carry out its task, a method will need certain information, which it may store in variables. Plus, it will have to carry out a sequence of individual actions to perform the task. This is called its algorithm, which is a step-by-step description of the solution to a problem. And, finally, you must decide what result the method will produce. Thus, as in designing objects, it is important to ask the right questions: • What specific task will the method perform? • What information will it need to perform its task? • What algorithm will the method use? • What result will the method produce? Methods can be thought of as using an algorithm to complete a required action. The algorithm required for the Riddle() constructor is very sim- ple but also typical of constructors for many classes. It takes two strings and assigns the first to the question instance variable and then assigns the second to the answer instance variable. The algorithms for the other two methods for the Riddle class are even simpler. They are referred to as get methods that merely return or produce the value that is currently stored in an instance variable. Not all methods are so simple to design, and not all algorithms are so simple. Even when programming a simple arithmetic problem, the steps Algorithm design involved in the algorithm will not always be as obvious as they are when doing the calculation by hand. For example, suppose the problem were to calculate the sum of a list of numbers. If we were telling our classmate how to do this problem, we might just say, “add up all the numbers and report their total.” But this description is far too vague to be used in a program. By contrast, here’s an algorithm that a program could use: 1. Set the initial value of the sum to 0.
  • 50. 30 CHAPTER 1 • Java Program Design and Development 2. If there are no more numbers to total, go to step 5. 3. Add the next number to the sum. 4. Go to step 2. 5. Report the sum. Note that each step in this algorithm is simple and easy to follow. It would be relatively easy to translate it into Java. Because English is somewhat imprecise as an algorithmic language, programmers frequently write al- gorithms in the programming language itself or in pseudocode, a hy- Pseudocode brid language that combines English and programming language struc- tures without being too fussy about programming language syntax. For example, the preceding algorithm might be expressed in pseudocode as follows: sum = 0 while ( more numbers remain ) add next number to sum print the sum Of course, it is unlikely that an experienced programmer would take the trouble to write out pseudocode for such a simple algorithm. But many programming problems are quite complex and require careful de- sign to minimize the number of errors that the program contains. In such situations, pseudocode could be useful. Another important part of designing an algorithm is to trace it—that is, to step through it line by line—on some sample data. For example, we might test the list-summing algorithm by tracing it on the list of numbers shown in the margin. Sum List of Numbers 0 54 30 20 54 30 20 84 20 104 - Initially, the sum starts out at 0 and the list of numbers contains 54, 30, and 20. On each iteration through the algorithm, the sum increases by the amount of the next number, and the list diminishes in size. The algorithm stops with the correct total left under the sum column. While this trace didn’t turn up any errors, it is frequently possible to find flaws in an algorithm by tracing it in this way. 1.3.4 Coding into Java Once a sufficiently detailed design has been developed, it is time to start generating Java code. The wrong way to do this would be to type the en- tire program and then compile and run it. This generally leads to dozens of errors that can be both demoralizing and difficult to fix. The right way to code is to use the principle of stepwise refinement. The program is coded in small stages, and after each stage the code is Stepwise refinement compiled and tested. For example, you could write the code for a single method and test that method before moving on to another part of the pro- gram. In this way, small errors are caught before moving on to the next stage. The code for the Riddle class is shown in Figure 1.4. Even though we have not yet begun learning the details of the Java language, you can easily pick out the key parts in this program: the instance variables question and answer of type String, which are used to store the riddle’s data; the Riddle() constructor and the getQuestion() and
  • 51. SECTION 1.3 • Designing a Riddle Program 31 /∗ ∗ F i l e : R i d d l e . j a v a ∗ A u t h o r : J a v a , J a v a , J a v a ∗ D e s c r i p t i o n : D e f i n e s a s i m p l e r i d d l e . ∗/ public class Riddle extends Object // C l a s s h e a d e r { // B e g i n c l a s s b o d y private String question ; // I n s t a n c e v a r i a b l e s private String answer ; public Riddle ( String q , String a ) // C o n s t r u c t o r m e t h o d { question = q ; answer = a ; } // R i d d l e ( ) public String getQuestion ( ) // I n s t a n c e m e t h o d { return question ; } // g e t Q u e s t i o n ( ) public String getAnswer ( ) // I n s t a n c e m e t h o d { return answer ; } // g e t A n s w e r ( ) } // R i d d l e c l a s s // End c l a s s b o d y Figure 1.4: The Riddle class definition. getAnswer() methods make up the interface. The specific language de- tails needed to understand each of these elements will be covered in this and the following chapter. 1.3.5 Syntax and Semantics Writing Java code requires that you know its syntax and semantics. A language’s syntax is the set of rules that determines whether a partic- Syntax ular statement is correctly formulated. As an example of a syntax rule, consider the following two English statements: The rain in Spain f a l l s mainly on the plain . // V a l i d Spain rain the mainly in on the f a l l s plain . // I n v a l i d The first sentence follows the rules of English syntax (grammar), and it means that it rains a lot on the Spanish plain. The second sentence does not follow English syntax, and, as a result, it is rendered meaningless. An example of a Java syntax rule is that a Java statement must end with a semicolon. However, unlike in English, where one can still be understood even when one breaks a syntax rule, in a programming language the syntax rules are very strict. If you break even the slightest syntax rule—for ex-
  • 52. 32 CHAPTER 1 • Java Program Design and Development ample, if you forget just a single semicolon—the program won’t work at all. Similarly, the programmer must know the semantics of the language— Semantics that is, the meaning of each statement. In a programming language, a statement’s meaning is determined by what effect it will have on the pro- gram. For example, to set the sum to 0 in the preceding algorithm, an as- signment statement is used to store the value 0 into the memory location named sum. Thus, we say that the statement sum = 0; assigns 0 to the memory location sum, where it will be stored until some other part of the program needs it. Learning Java’s syntax and semantics is a major part of learning to program. This aspect of learning to program is a lot like learning a for- eign language. The more quickly you become fluent in the new language (Java), the better you will be at expressing solutions to interesting pro- gramming problems. The longer you struggle with Java’s rules and con- ventions, the more difficult it will be to talk about problems in a common language. Also, computers are a lot fussier about correct language than humans, and even the smallest syntax or semantic error can cause tremen- dous frustration. So, try to be very precise in learning Java’s syntax and semantics. 1.3.6 Testing, Debugging, and Revising Coding, testing, and revising a program is an repetitive process, one that may require you to repeat the different program-development stages shown in (Fig. 1.1). According to the stepwise-refinement principle, the process of developing a program should proceed in small, incremental steps, where the solution becomes more refined at each step. However, no matter how much care you take, things can still go wrong during the coding process. A syntax error is an error that breaks one of Java’s syntax rules. Such er- rors will be detected by the Java compiler. Syntax errors are relatively easy Syntax errors to fix once you understand the error messages provided by the compiler. As long as a program contains syntax errors, the programmer must correct them and recompile the program. Once all the syntax errors are corrected, the compiler will produce an executable version of the program, which can then be run. When a program is run, the computer carries out the steps specified in the program and produces results. However, just because a program runs does not mean that its actions and results are correct. A running program can contain semantic errors, also called logic errors. A semantic Semantic errors error is caused by an error in the logical design of the program causing it to behave incorrectly, producing incorrect results. Unlike syntax errors, semantic errors cannot be detected automatically. For example, suppose that a program contains the following statement for calculating the area of a rectangle: return length + width ;
  • 53. SECTION 1.3 • Designing a Riddle Program 33 Because we are adding length and width instead of multiplying them, the area calculation will be incorrect. Because there is nothing syntacti- cally wrong with the expression length + width, the compiler won’t detect an error in this statement. Thus, the computer will still execute this statement and compute the incorrect area. Semantic errors can only be discovered by testing the program and they are sometimes very hard to detect. Just because a program appears to run correctly on one test doesn’t guarantee that it contains no semantic errors. It might just mean that it has not been adequately tested. Fixing semantic errors is known as debugging a program, and when sub- tle errors occur it can be the most frustrating part of the whole program development process. The various examples presented will occasionally provide hints and suggestions on how to track down bugs, or errors, in your code. One point to remember when you are trying to find a very sub- tle bug is that no matter how convinced you are that your code is correct and that the bug must be caused by some kind of error in the computer, the error is almost certainly caused by your code! 1.3.7 Writing Readable Programs Becoming a proficient programmer goes beyond simply writing a pro- gram that produces correct output. It also involves developing good pro- Programming style gramming style, which includes how readable and understandable your code is. Our goal is to help you develop a programming style that satisfies the following principles: • Readability. Programs should be easy to read and understand. Com- ments should be used to document and explain the program’s code. • Clarity. Programs should employ well-known constructs and standard conventions and should avoid programming tricks and unnecessarily obscure or complex code. • Flexibility. Programs should be designed and written so that they are easy to modify. Special Topic: Grace Hopper and the First Computer Bug Rear Admiral Grace Murray Hopper (1906–1992) was a pioneer computer programmer and one of the original developers of the COBOL program- ming language, which stands for COmmon Business-Oriented Language. Among her many achievements and distinctions, Admiral Hopper also had a role in coining the term computer bug. In August 1945, she and a group of other programmers were working on the Mark I, an electro-mechanical computer developed at Harvard that was one of the ancestors of today’s electronic computers. After several hours of trying to figure out why the machine was malfunctioning, some- one located and removed a two-inch moth from one of the computer’s circuits. From then on whenever anything went wrong with a computer, Admiral Hopper and others would say “it had bugs in it.” The first bug itself is still taped to Admiral Hopper’s 1945 log book, which is now in the collection of the Naval Surface Weapons Center.
  • 54. 34 CHAPTER 1 • Java Program Design and Development In 1991, Admiral Hopper was awarded the National Medal of Tech- nology by President George Bush. To commemorate and honor Admiral Hopper’s many contributions, the U.S. Navy recently named a warship after her. For more information on Admiral Hopper, see the Web site at http : //www. chips . navy . mil/ 1.4 Java Language Elements In this section we will introduce some of the key elements of the Java language by describing the details of a small program. We will look at how a program is organized and what the various parts do. Our intent is to introduce important language elements, many of which will be explained in greater detail in later sections. The program we will study is a Java version of the traditional Hel- loWorld program—”traditional” because practically every introductory programming text begins with it. When it is run, the HelloWorld program (Fig. 1.5) just displays the greeting “Hello, World!” on the console. 1 /∗ 2 ∗ F i l e : H e l l o W o r l d . j a v a 3 ∗ A u t h o r : J a v a J a v a J a v a 4 ∗ D e s c r i p t i o n : P r i n t s H e l l o , W o r l d ! g r e e t i n g . 5 ∗/ 6 public class HelloWorld extends Object // C l a s s h e a d e r 7 { // S t a r t c l a s s b o d y 8 private String greeting = ”Hello , World ! ” ; 9 public void greet ( ) // M e t h o d d e f i n i t i o n 10 { // S t a r t m e t h o d b o d y 11 System . out . println ( greeting ) ; // O u t p u t s t a t e m e n t 12 } // g r e e t ( ) // End m e t h o d b o d y 13 public s t a t i c void main ( String args [ ] ) // M e t h o d h e a d e r 14 { 15 HelloWorld helloworld ; // d e c l a r e 16 helloworld = new HelloWorld ( ) ; // c r e a t e 17 helloworld . greet ( ) ; // M e t h o d c a l l 18 } // m a i n ( ) 19 } // H e l l o W o r l d // End c l a s s b o d y Figure 1.5: The HelloWorld application program. 1.4.1 Comments The first thing to notice about the HelloWorld program is the use of com- ments. A comment is a non-executable portion of a program that is used to document the program. Because comments are not executable instruc- tions they are just ignored by the compiler. Their sole purpose is to make the program easier for the programmer to read and understand. The HelloWorld program contains examples of two types of Java comments. Any text contained within /* and */ is considered a comment.
  • 55. Another Random Document on Scribd Without Any Related Topics
  • 56. general. At all events, my passport through that important part of the French camp was signed by several hundreds of those brave fellows, as well as by innumerable smiles from the fair and dark heroines, the cantinières of the first French division. With a promise to return soon, I retired, having experienced much gratification and enriched my budget of anecdote. In this interesting visit to the French camp, head-quarters, canteens, c., and becoming well acquainted with the officers’ and soldiers’ popottes— which name I immediately added to my gastronomic bill of fare—the three hours I had to spare nearly expired. The sun was rapidly descending to the level of the ocean in the direction of Kamiesch. Having paid my bill at the canteen, and shaken hands with nearly a whole regiment, I jumped on my pony and galloped all the way home, perfectly satisfied with my day’s work, which at the time I felt was one of the most interesting of my life.
  • 57. CHAPTER XVIII. A UNIVERSAL CALAMITY. Miss Nightingale dangerously ill—Her removal to the Sanatorium—Worst form of Crimean fever—General consternation—Conversation with the Captain—Better news— Visit the Sanatorium—Disembarkation of the Sardinians—Bridge over the London— Admiral Boxer—Act as interpreter—Overwhelmed with complaints—Soda-water for horses—All right at last—Alexandrian horse-flesh—A character—An interesting ride— The General Hospital—Reasons for my return to Turkey—Letters—Head-quarters again— Lord Raglan’s anxiety for Miss Nightingale—Return to Balaklava—Admiral Boxer and the Sardinians—All in the wrong—Quieted at last. ALAS! how short are the moments in which real happiness favours us with its charms, and how quickly it deserts one in the midst of mirth and joy! On this eventful day, I was doomed to experience the truth of the saying that “sorrow treads upon the heels of joy;” for I had scarcely set my foot upon the deck of the London, when P. M. came and apprised me that Miss Nightingale was not expected to live. It appeared that after my departure she had a terrible attack of fever, and was obliged to be immediately removed to the hospital. On asking to which establishment this excellent lady had been taken, I was told the Sanatorium. P. M. continued, “Several doctors, Mr. and Mrs. Bracebridge, and myself, accompanied her there—I have only been back a few minutes.” “Why did you not take her to the General Hospital? It was much nearer.” “Don’t you know that cholera is raging there?” “There certainly are a few cases. Do you think I can do anything for her?” “No, I am sure you cannot; she is not allowed to take anything, and the doctors have forbidden any one to be admitted, except her private nurse, Mrs. Roberts.” It was then getting late—Mr. Bracebridge had not returned. The captain and P. M. gave me a full account of this lamentable event. It appeared that about noon Miss Wear had come on board to see Miss Nightingale upon business. She found that lady very poorly, but thinking it was a slight
  • 58. indisposition, took no notice of it, more especially as Miss Nightingale did not complain in the least. About two, by the orders of Mrs. Roberts, they were obliged to send in a great hurry for a doctor. Mrs. Roberts stated that her mistress had been suddenly taken dangerously ill—that she was in fact attacked by the worst form of Crimean fever. The first thing ordered by the doctor was her instant removal to the hospital on the heights. “So,” said the captain, who was relating this part of the sad history, “I set all my men to work. We got a stretcher from the hospital, and she was carried very carefully by my men and some soldiers sent by the governor.” “I followed through Balaklava,” said P. M., “amidst a regular procession of soldiers, holding a white umbrella over her face. The crowd was so great, we could scarcely pass, and it took us nearly an hour to get up to the heights. I assure you, all Balaklava was in an uproar.” “What do the doctors say of the case?” “That the lady is dangerously ill, and that no one must go near her, not even Mr. Bracebridge.” “What mournful tidings!” I said. “I should not be surprised if she caught the fever from the patient at Dr. Henderson’s. I warned her of the danger of exposing herself so much several times.” “By-the-bye, where is Mr. Bracebridge?” “I left him there.” “Does he intend to come back, or stay where he is?” “I don’t know, but I do not see what good he can do there.” “I hope we shall hear better news when he returns.” “Now, Mr. Soyer, tell us about your visit to head-quarters. Did you see Lord Raglan?” “Certainly I did.” “And how were you received?” asked the captain. “Admirably,” I replied. “I hear his lordship is a most amiable and kind man.” “He is indeed, I assure you; and I cannot but express my gratitude for the reception he afforded me. I am certain he will be very sorry to hear of Miss Nightingale’s serious and sudden illness, for he inquired very kindly after her this morning.”
  • 59. My companions made many more inquiries respecting the events of the day; but I had forgotten all, I was so absorbed by this unexpected blow. It seemed likely to upset all our plans. I spoke to the captain of the several visits Miss Nightingale had paid to the sick officer at Dr. Henderson’s at the time he was so dangerously ill, remarking upon her neglect of herself by going all day without refreshment, and braving all weathers. We could not help noticing how singular it appeared, that after her hard labours at Scutari, and escaping both the cholera and fevers which raged there, she should be so suddenly taken ill at Balaklava. It was indeed very melancholy and remarkable. At last Mr. Bracebridge returned. He informed us that Miss Nightingale was a little better, but that such a violent case of fever required a certain time. “Mrs. Roberts,” he continued, “is with her, and the boy to go for the doctor, in case he should be needed.” “Poor boy!” said the captain, “how he cried when he saw his mistress carried upon a stretcher by soldiers!” “Yes,” said Mr. Bracebridge, “he is a very affectionate lad.” After a few questions about my visit to Lord Raglan, being all very much fagged, we retired for the night. Upon that occasion, owing to excessive fatigue and the absence of rats, which had at length been successfully turned out of my cabin without making use of my receipt, I enjoyed a comfortable night’s rest. The next morning, at eight precisely, Louis was at his post with the pony, of which I could not, however, make use, not knowing what alteration Miss Nightingale’s illness might cause at both hospitals, where, no doubt, my presence would be required. I sent Dr. Hall a note, apologizing for not waiting upon him that day, and postponing our visit to the day following, if agreeable to him. Louis promised to send me an answer at five o’clock by the doctor’s courier. No news had been received at the General Hospital from the Sanatorium; therefore Mr. Bracebridge and myself went up the first thing, instead of going to Mr. Upton, as we had previously arranged. On our arrival, the report was anything but favourable; and this seemed to paralyse all our energies. Indeed, for a few days no business of consequence was transacted. My kitchen at the Sanatorium alone progressed. I offered my services to Drs. Henderson and Hadley, in case I could be of use to Miss Nightingale. Dr. Henderson said, “I am the only cook she requires at present. We must wait nearly a week before I can leave her in your hands, even should her illness
  • 60. take a favourable turn.” I then begged of him to give me his private opinion of her state. “She is suffering, I assure you, Monsieur Soyer, from as bad an attack of fever as I have seen; but I should say the chances are in her favour, because she does not fret in the slightest degree, but is perfectly composed.” On calling at the General Hospital for Dr. Hall’s reply, I found that he had fixed the same time the next day for our visit. We then returned on board the London. Many inquiries respecting Miss Nightingale had been made by almost all the authorities, amongst whom were Sir John Macneil, Captain Tulloch, Admiral Boxer, the Governor, Commissary Filder, and Dr. Sutherland. The latter went at once to see her. Finding she had all proper attention, he came in the evening, and requested us to leave her as quiet as possible. He told Mr. Bracebridge on no account to go near her, not even if sent for, as any excitement might be fatal. This request was of course punctually attended to. The remainder of the Sardinian army had now arrived. The disembarkation kept the harbour in a constant bustle, morning, noon, and night. It was, in fact, a real maritime bivouac, and our vessel very much resembled the famed metropolis from which it takes its name. During the night a strong bridge was built over it, communicating with the shore on the one side, and one of the Sardinian ships, which had been towed alongside, on the other. This was made for the purpose of landing men and horses. At five in the morning I was up and on deck, as from the noise it was impossible to sleep. The first person on board was Admiral Boxer, as busy as could be, giving his orders. On seeing me, he inquired about Miss Nightingale. “What a good job,” said he, “they were able to remove her from here!” “You are right, admiral. I perceive you are about to put the troops from one of the vessels on shore.” “From one, say you? I am landing the whole of the Sardinian army, and some of our own troops besides.” “At any rate, I think this is one of the greatest curiosities of the Crimean war.” “Why?” asked the admiral, talking to twenty others at the time. “Why, admiral, pray who would have thought of seeing while in the Crimea a Sardinian army cross London Bridge?”
  • 61. “Ha! ha! ha! true enough; that’s not bad; singular things are seen and done in time of war. What do you think of their soldiers, Monsieur Soyer?” “Fine fellows!” “They are fine fellows. But I wish they spoke English—we should get on much quicker.” “I’ll speak to them for you, if you like, admiral.” “Ah, to be sure, so you can.” I immediately set about acting as interpreter between the English admiral and the Sardinian captains. In his anxiety to get rid of them as quickly as possible, Admiral Boxer asked whether they had pretty much what they required; a question which brought about ten complainants on deck, who surrounded me. One had no hay, barley, or water for his horses. They all spoke at the same time, and made a hubbub which could only be feebly imitated at the Paris Stock Exchange. “What’s all this row about? This will never do,” said the admiral. “Pray don’t tell them who I am, or they will bother my life out.” “I have told them, and that’s why they are making such a row. I asked them, as you wished me, whether they had everything they wanted.” “I said pretty much what they wanted.” “I know you did, admiral, and so I told them; but they say they don’t know the meaning of that.” “Tell them they are fine fellows—fine fellows, and that there is a beautiful camp ready for them, where they will find everything they require, without any drawback. I will send lots of men to wait upon them directly; but they must get out of the harbour before night.” General della Marmora sent for the admiral; so he left me to settle the matter, which I did in a very few words. “My dear fellows,” said I to them, “your valuable services will be much better appreciated by your sovereign and General-in-chief if you put up with a little inconvenience for the present, and remain quiet, than if, on the contrary, you are too particular.” “Do you know, monsieur, that our horses have not had a drop of water to-day?” “Colonel,” said I, “I am not at all surprised at that; and more, you must put up with it.”
  • 62. “Why?” he asked. “Simply because you can’t get it, unless you like to do as I did yesterday —give them soda-water.” “Do you mean to say there is no water at all in this grand vessel?” “None, except soda-water.” “Eh bien,” said another, “give de soda-water alors.” “What, for the horses?” “Oui, for the chevals!” “Here, my man,” said I to one of the crew, “tell the steward to bring a dozen of soda-water for the colonel’s horse. Mind, colonel, it costs a shilling a bottle; but, as you are a good customer, and take a dozen, no doubt he will let you have it cheaper.” “I will not pay a sou for this bubbling water. I know what you mean. It fizzes like champagne, but it is not good to drink. The horses will never touch it. I thought it was spring-water that you called soda-water.” At all events, the soda-water was brought, to the great annoyance of the colonel, who thought he should have to pay for it; but I sent for some sherry and a few glasses, and we drank a bottle or two, instead of giving it to the horses, to the great gratification of the colonel, who, after partaking of it, said he liked it much better with sherry than brandy. About twenty banabaks soon after arrived with water in skins and leathern horse-buckets. The horses were properly watered; and thus ended the Sardinian revolt in the harbour of Balaklava, on the 14th of May, in the year 1855, beneath the ruins of the Genoese Tower and fortifications built by their ancestors. The Sardinian troops and horses soon after crossed new London Bridge; by eight o’clock I was mounting my horse to go and meet Dr. Hall. The troops that had then landed were in full march towards their very picturesque camp at the top of the mountain; a band of music was playing at their head, and their artillery train and baggage-waggons followed. The weather was brilliant, and the heat of the sun intense. Louis was mounted upon a fine black horse, which the doctor had brought from Alexandria. Nobody but Louis could ride him, on account of his tricks. His appearance was worthy of the finest circus in the world for the performance of the high school of equitation. To this splendid animal Louis owed his reputation and popularity; and, as he lived at head-quarters, all the Staff knew him. It is
  • 63. hardly possible to describe his personal appearance. He was short in stature, with extraordinary large ears; his long moustaches, hair, and eyebrows were between the colour of a canary bird and that of the dun pony I was riding. His dress was of a similar colour, with the exception of his cap, which was, if possible, of an intenser yellow. This contrast of colours in an individual mounted upon such a splendid charger, caused him to be remarked by every one throughout the camp. Our ride seemed very short, for Louis, who is a very clever fellow, was full of anecdote, and related some that were really very amusing. He spoke several languages, frequently mingling one with another. He spoke his own language, the French, worse than any other, he had been so long away from his native land. He was present at the battles of Alma, Balaklava, Inkermann, and the Tchernaya, where his charger was wounded close to the Traktir Bridge, he, as usual during an action, keeping in close attendance on his brave master, more especially if danger was imminent; and no better fate had he at the battle of Inkermann, where he was seriously wounded in the leg, and the traces of both wounds are, I regret to say, still apparent. On the eve of my departure from the seat of war, I, out of veneration for this once splendid charger, purchased him of his owner, who would probably have been obliged to abandon his faithful steed to the tender mercies of the hungry inhabitants, who, doubtless, had they got him in their clutches, would have given him a dressing à la Tartare, or perhaps converted his body into those suspicious articles of food, sausages. On his voyage home, in charge of a careful groom, Neptune had no more respect for this four- legged hero than for the commonest quadruped; for not only was he pitched, bit, and tossed about in all directions, but worse still, when the ship Clarendon arrived off Cadiz, she struck on a sunken rock, and the most valueless animals were thrown overboard; but “Inkermann,” with his usual luck, in spite of Mars and Neptune, escaped the plunge taken by his less fortunate companions, and is now in London, enjoying, as hitherto, his full feed, though in the profoundest retirement, having sold out of the army. Louis spoke very highly of his master, and never seemed to be pleased or displeased at anything—good news, bad, or indifferent, were all the same to him. If you said to him, “The weather is very bad,” he would answer, “I have nothing to do with that, no more than if it were fine.” On asking him, at our first interview, if he was a Frenchman, “Of course I am,” he replied; “all my family were Frenchmen.” I must say that, with all his eccentricity,
  • 64. he was very obliging; and I feel very grateful for the kind attentions he paid me, particularly during my serious illness, when he often visited me. Upon our arrival, the doctor’s horse was at the door, and his master soon made his appearance. “Good morning, Doctor! I fear we are behind time.” “I can always employ my time here,” said he, looking at his watch; “you are only a few minutes late.” We then, started. Louis asked whether he was to accompany us; to which the doctor answered, “No: I expect Dr. Henderson from Balaklava, so be in the way; tell him we are gone to the General Hospital.” During our ride, I told my companion about the Sardinian insurrection near our new London Bridge, which seemed to amuse him very much. He informed me that Miss Nightingale had passed a better night, but was far from being out of danger. The cannon of Sebastopol made a fearful noise. “Have you seen Sebastopol yet, Monsieur Soyer?” “Yes, I have, Doctor, and was rather close, too!” and I related our Nightingale campaign. “To-day you will have another view, quite as good, though not so dangerous.” We then began talking upon business, and I was speaking of my having visited the military and civil hospitals in France, when Dr. Henderson galloped after us, and a conversation ensued relative to the arrival of the armies, and the fact that many of the men had been attacked by fever, before their hospitals were ready. Dr. Hall decided upon a course of action, and we alighted at the General Hospital. The doctor, Mr. Mouatt, was unfortunately out, but was expected back shortly. Dr. Henderson left us, and I accompanied Dr. Hall round several huts. He visited all the worst cases, which were at that time very numerous. We then repaired to the kitchen, which, as I have before said, was far from being equal to the requirements of such an immense hospital. It was in the open air, and ill provided with things necessary for the establishment. Having pointed this out to Dr. Hall, he immediately agreed that one similar to that at the Sanatorium should be erected; but Dr. Mouatt was not present. The want of materials and of workmen was so great, that, previous to its erection, I was obliged to leave the Crimea and return to Scutari for a short time. My head man there had been taken ill, and his life was, as he thought, in great danger. Several times
  • 65. prior to my return he had threatened to run away, which would quite have upset all my former efforts. I remained in the Crimea about ten days longer, and my reader will perceive that every minute of my time was occupied. I devoted some of it to the most important hospital of all—the one before Sebastopol; a plan for the improvement of which I immediately made and forwarded to the proper parties, so much was I impressed with the necessity of having a kitchen erected immediately. Fearing that I should be obliged to leave the Crimea for Scutari before it could be even commenced, the day after my visit I wrote two official letters, one to Lord Raglan, and the other to Dr. Hall. The General-in-chief and Dr. Hall had both visited the spot, and agreed with me that it was one of the most important hospitals in the East. It was situated under the very walls of Sebastopol, subject to a divided attack, or to a sortie, and might at any moment be suddenly encumbered with a large number of wounded, requiring a great quantity of nutritious articles, more particularly beverages, after any surgical operation. In reply I received the following communications:— Before Sevastopol, 30th May, 1855. Sir,—I am directed by Lord Raglan to acknowledge the receipt of your several communications of the 25th and 28th instants, and to express to you his lordship’s thanks for the valuable information contained therein. I have the honor to be, Sir, Your obedient servant, Thos. Steele, Lieut.-Col., Military Sec. Mons. Soyer. My dear Mr. Soyer,—I have this day received your letter of the 22nd June, and am much obliged to you for your thoughtful care of our wants in the all-important business of cooking for both sick and well. Our new hospital is nearly fit for the reception of patients; but you know how tedious the want of labor makes everything here. I was out at the Monastery yesterday, and was glad to see that they had commenced on the kitchen, and were going to fit it up after your excellent model at the Castle. Very truly yours, J. Hall. 5th July, 1855. I also had several interviews with Dr. Mouatt, who took my suggestion during my absence in hand, but never apparently succeeded in carrying it
  • 66. out, although the materials requisite were simply planks, nails, and bricks. I merely advert to the foregoing in answer to some observations that were wafted about the camp to the effect that I never took much trouble about this particular hospital, while in reality it was the very first which attracted my attention, as the above letters will convince my readers. Upon our return from the hospital to head-quarters, I called at Colonel Steele’s. Lord Raglan was just going out, and the first question he asked, even before I had time to pay my respects, was—“How is poor Miss Nightingale?” “A little better to-day. Dr. Henderson, whom I have just seen, says she has passed a better night.” “Well, I hope she has; I shall pay her a visit as soon as possible—that is, when she is a little better. Was she ill at all at Scutari?” “Not, my Lord, while I was there, and, I think, not before. It is rather remarkable that she should catch the Crimean fever just after her arrival.” I told Lord Raglan of her imprudence in visiting a patient at Dr. Henderson’s, who had been attacked by the worst form of Crimean fever; also, of her remaining out so late, and not taking any refreshment. “She appears,” said Lord Raglan, “to have no fear.” “None whatever.” I recounted her visit to the three-gun battery, and the scene that took place upon the centre mortar. Lord Raglan remarked—“It should be called the Nightingale mortar.” He then jumped upon his horse, and I had but a few minutes to explain the result of my visit with Dr. Hall to the various hospitals. I mentioned that the most important thing was the immediate erection of a kitchen for the General Hospital, in case of a decided attack upon Sebastopol. “Very true, Monsieur Soyer,” said Lord Raglan. I stated that I had addressed a letter to his lordship to that effect. “Yes, I have seen it, and it shall be attended to.” Lord Raglan and his staff then started in the direction of the French head-quarters, and I towards Balaklava, where I arrived about dusk. I left my pony at the General Hospital, and walked to the opposite side of the harbour, which I had in the morning left all in confusion, and, to my astonishment, found quiet and almost deserted. The only person I saw was
  • 67. Admiral Boxer, who came and thanked me for the assistance I had given him in the morning. “Don’t mention it, admiral,” said I; “I shall at all times be happy to do everything in my power to render myself agreeable to you. Pray tell me, where are they all gone?” “To their camp, to be sure.” “What—regiments, horses, and all?” “Yes, the vessels alongside this morning have not only discharged their cargoes, but are, I believe, out of the harbour and anchored in the bay. We shall have two more in, which must be discharged to-morrow.” “This silence is almost inconceivable after so much noise and bustle.” “It is,” said the admiral. “I don’t understand those Sardinians, they speak so fast and loud; but they are fine fellows for all that, and no mistake.” The words were hardly out of his mouth, when two Sardinians attached to the commissariat came towards us, and inquired whether we understood French or Italian. I informed them that I spoke French. “Then, pray, sir, can you tell us where to find ce diable d’amiral Anglais?” “What do they say?” asked Admiral Boxer, addressing me. “Nothing particular,” I replied. “Gentlemen,” said I, turning to the Sardinians, “what could the admiral do for you? It is very probable that I shall have the pleasure of seeing him this evening.” The one who had as yet scarcely spoken exclaimed—“A truce to the pleasure! I wish I could get hold of him, I would tell him my mind in a few words.” “Pray be calm, gentlemen.” All this time Admiral Boxer kept asking—“What do they say? They are speaking about me, I know they are. Tell them they are a fine set of fellows, and I will do anything for them, but they must be out by to-morrow night.” “Very well; but first let me inquire what the row is all about.” “Do so.” “Now, gentlemen, what is it you want? for here is a person who can do as much for you as the admiral himself, and perhaps more.” “Ah, pray ask him, then.”
  • 68. “But you have not yet told me what you require.” “Eh bien!” they said, both speaking at once, “pray, my friend, ask this gentleman to tell the English admiral to postpone the order for our landing to-morrow morning till the next day. It is impossible for us to land our men and horses so early. We have above four hundred horses on board; not half of which have been watered to-day, nor can they be, till we find some water. There is only a small pump to draw it from the hold of the vessel, and it takes hours to water a few horses.” Having explained this their chief trouble to the admiral, he said—“Tell them there will be plenty of water for them by four o’clock in the morning.” When I had done so, they inquired whether they could depend upon that gentleman’s word. I assured them that they might. “With respect to the other matters, we ought to see the admiral himself.” “Oh, don’t trouble yourself; I will do the rest for you.” This was merely a request concerning themselves. I did not like to trouble the admiral about it, and I thought the best way to get rid of them was to show them his flag-ship, telling them they might go there if they liked, but that it was a hundred to one if they found him on board. “No, no!” said one of them; “it is dinner-time, and the English like their dinner too well; he is sure to be at home, so we will go and see.” Having their boat with them, they went across. The admiral asked—“What do they want besides the water for their horses?” “Oh, they were inquiring about the camp.” I then related all our conversation, at which the admiral laughed heartily, saying he could understand some of it, but they spoke so very fast. “When they come on board to-morrow, they will be sure to recognise me.” “Oh no! having only seen you in the dark, they will not know you again; and I shall be there. Don’t trouble yourself; they will be quiet enough when they get all they want, and they have a very fine camp.” “Have you seen it?” “No, admiral, not yet.”
  • 69. “Then you ought to go and see it; they are building a large hospital there. Mind, they have reason to complain. I am aware they ought to have more time; but see what a fleet I have in such a small harbour, and every day there are more troops coming. Perhaps an expedition of our own troops will sail shortly, so I must be prepared for everything. That is what has kept me on this side of the harbour to-night; besides, I wished to see how they were going on with the new quay.” “You have done wonders, admiral, on this side of the harbour since my arrival.” “Remember, Monsieur Soyer, we cannot always do as we like. We are not in England.” We parted for the night.
  • 70. CHAPTER XIX. HAPS AND MISHAPS IN CAMP. Dinner on board the Baraguay d’Hilliers—Bread-biscuit—Good news of Miss Nightingale—Operations at the Sanatorium kitchen—A borrowed pony—Don’t lose the saddle—No police nor newspapers—Difficulties at Balaklava—Dry vegetables in cake—A receipt—Promise of support—A new mother—Mrs. Seacole’s enthusiasm—The lady’s sons—Advice—My pony lost—A friend in need—Mr. Russell—Mr. Angel—Crimean Hue and Cry—Useless inquiries—Monsieur Armand’s difficulties—A dinner at the Post-office —A jovial party—Festivity and song—Break up at last. ON reaching the London, I found Mr. Bracebridge dressed and waiting for me to go and dine on board the Baraguay d’Hilliers, with Sir John Macneil and Captain Tulloch. We had that evening a most interesting conversation on all kinds of army stores and provisions. Sir John, who took a vital interest in my mission, gave me several important hints, and I submitted my opinion of the salt as well as fresh meats—fresh and dried vegetables, and especially the bread, which at that period arrived daily from Constantinople, but which, in consequence of its being sometimes put on board ship before it had got quite cool, lost a great deal of its nutritive quality during the passage. Had it been made in the Crimea of the same materials, it would have been very good. I was informed that bakeries were to be established. I told Sir John that I had made a kind of bread-biscuit, somewhat like common bread, but baked in flat cakes about twelve times the size of an ordinary biscuit; it would keep for months, and then eat well, though rather dry; it would soak well in tea, coffee, or soup, and be very palatable; it was made of three parts flour and one of peameal, and was reported upon by the medical gentlemen as being very nutritious and wholesome. A few days later I had the pleasure of showing some to those gentlemen, and they both highly approved of it. I afterwards had some made on board the Abundance. I submitted it to them, and they pronounced it excellent.[13] The evening we spent on board the Baraguay d’Hilliers will not be soon forgotten. After a short nautical and nocturnal trip upon the water, we arrived safely in our old London. On our way to the Baraguay d’Hilliers,
  • 71. Mr. Bracebridge informed me that Miss Nightingale was pronounced out of danger, and that the news had been telegraphed to London. The medical men were of opinion that she should return to Scutari, and after a few days’ rest proceed to England. Although out of danger, she would not be able to quit Balaklava for eight or ten days. The next morning, at seven o’clock, I was at the Sanatorium kitchen, which was finished. I set my soldier-cooks to work, and all went on admirably. It was then ten o’clock, so I called upon Dr. Hadley (the chief doctor at the Sanatorium, who had succeeded Dr. Henderson, and to both of these gentlemen I must return my sincere thanks for their assistance and kindness), and requested him to come and taste some extra diets and soups I had prepared for the convalescents. Recollecting that I had not called upon Lord Raglan’s chef de cuisine, I mentioned the circumstance to Dr. Hadley, stating how much I wished to do so, but that I had no horse. Dr. Hadley very kindly offered me his pony, a fine grey, smartly caparisoned, which I at once accepted. When I had mounted, Dr. Hadley said—“Soyer, if you fall off, mind and get up again; for,” said he, “joking apart, though the pony is very quiet, recollect the road to Balaklava is a queer one, therefore take care of yourself. We should not mind so much if we had done with, you; but as we really require your services, for our own sakes take care of yourself.” “I will do so,” said I, laughing, “were it only for the sake of your pony, which might get loose if I were to fall off, and you might not recover him again.” “Never mind the pony,” said he: “you may lose him; but, whatever you do, don’t lose the saddle. We had better have a bit of supper on your return this evening, off that Yorkshire ham—you can cook it on your bivouac stove.” “So we will, Doctor. I shall be back at six.” “Don’t stay in the camp after dark; I can assure you it is a very dangerous place. Robberies and murders are of frequent occurrence, though we hear but little about them. We have no police, and no newspapers are published here, so we know nothing but what passes in our own circle.” “You are perfectly right, Doctor; though I am not afraid, as I never travel without a revolver; yet it is best to be upon the safe side.” Having fixed upon six o’clock for my return, and seven for supper, I started. There were about twenty convalescents outside the wards, enjoying
  • 72. the warmth of the sun’s rays. They were all in high glee at hearing our dialogue, which seemed to revive them from a state of lethargy to the consciousness of life. The ride from the top of the Genoese heights to Balaklava harbour, by a new road, through mud, over rocks, rivulets, c., and mounted upon a strange nag, was anything but pleasant to my feelings as a horseman. At all events, after numerous slippery evolutions on the part of my new charger, I found myself safe at the bottom of the ravine; but here another difficulty presented itself. The quay of the harbour was encumbered with French and Sardinian waggons, mules, and horses. The French, who had a wine depôt there for the troops, were strongly fortified with about a hundred pipes of wine, instead of gabions. So crowded was the road from the immense traffic and the unloading of shipping stores, that it took me nearly half-an-hour to ride a few hundred yards. This brought me as far as the Commissariat, where I had to call upon Commissary Filder. I found that he had just returned from head-quarters. We had about ten minutes’ conversation upon business. I related the result of my visit to the various provision stores— made remarks upon the same, and particularly upon the dry vegetables at that time issued to the troops. He then referred me to Under-Commissary Adams, to whom I promised a scale for a fresh composition of dry vegetables in cake, more suitable for the troops, in lieu of the finer and more expensive quality then issued in boxes. They were composed of one vegetable only, and were much too highly dried, having thus lost their aroma as well as their nutritious qualities. I therefore proposed that the firm of Messrs. Chollet, in Paris, should prepare a sample of cakes of dried vegetables, to be called coarse julienne, for the army. Each hundredweight of fresh vegetables was to consist of the following proportions:— Twenty pounds of carrots, twenty pounds of turnips, ten of parsnips, fifteen of onions, twenty of cabbage, five of celery, and ten of leeks; with one pound of aromatic seasoning, composed of four ounces of thyme, four of winter savory, two of bayleaf, four of pepper, and an ounce of cloves; the whole to be pulverized and mixed with the vegetables. Each cake was to serve for one hundred men, and to be marked in compartments of ten rations each, like chocolate cakes, instead of being marked upon the wrapper, which is always torn off when the vegetables are issued, and the soldiers cannot tell about quantity. This plan will obviate that evil; for I had seen in camp piles of this excellent vegetable rising
  • 73. pyramidically from the soldiers’ canteen pan while cooking, in consequence of their having put in the best part of three days’ rations instead of one. The dry rations are issued for three days at a time. My proposition having met with the approval of the authorities, was at once forwarded to the War Office. I also promised to submit to Commissary Filder’s notice several plans for improvement in the distribution of the meat. “Monsieur Soyer,” said he, “anything you may propose or point out as an improvement will, so far as it is practicable, be carried out. Lose no time; the sooner you let us have it the better.” After this interview, I went to inspect the kitchen, where I saw Mr. Fitzgerald, the purveyor, to whom I also made my report. As this is the first time I have had the pleasure of introducing this gentleman to the notice of my readers, it would be an omission on my part were I not to return my grateful acknowledgments for the readiness with which he at all times assisted me to obtain what I required for the hospitals in the Crimea. It is true he was at first rather reluctant; this I attributed to his not having received the proper instructions from the authorities. Having the best part of the day before me, I set off at a gallop towards head-quarters, intending to keep the promise I had made Lord Raglan respecting his dilapidated culinary department, and also to make the acquaintance of M. Armand, his chef de cuisine. As I was not well acquainted with the road across the country, I made up my mind to follow the high one which passes close to head-quarters. When about half-way, I perceived a group of officers standing by the road-side round a kind of tent much like a gipsy tent, but considerably larger. This excited my interest, and I was riding towards it, when, to my astonishment, several voices called out—“Soyer! Soyer! come here—come this way!” I readily complied with the invitation, and found two or three gentlemen whom I had the pleasure of knowing. During our conversation, an old dame of a jovial appearance, but a few shades darker than the white lily, issued from the tent, bawling out, in order to make her voice heard above the noise, “Who is my new son?” to which one of the officers replied, “Monsieur Soyer, to be sure; don’t you know him?” “God bless me, my son, are you Monsieur Soyer of whom I heard so much in Jamaica? Well, to be sure! I have sold many and many a score of
  • 74. your Relish and other sauces—God knows how many.” “My dear lady,” said I, “don’t blame me for that; I assure you I am not at all offended with you for so doing, and shall allow you to sell as much more in the Crimea.” “So I would if I could only get them. Bless me, I had a gross about ten days ago, and they are all gone; nor can I get any more for another month perhaps. Come down, my son, and take a glass of champagne with my old friend, Sir John Campbell.” I immediately alighted, and Sir John came towards me and shook me heartily by the hand, saying, “Welcome to the seat of war, Monsieur Soyer!” “Many thanks, general, for your kind wishes. I had the pleasure of leaving my card at Cathcart’s Hill the other day.” “You did; and I was very sorry that I was out when you called; but mind, you must come and dine with me some day.” “Thank you, general, I shall do myself the honour.” “Now, Mrs. Seacole, give us another bottle of champagne.” “Mrs. Seacole,” I exclaimed; “is that lady the celebrated Mrs. Seacole?” “Of course,” said the general. She then came forth from her bivouac cellar, with two bottles in her hands, exclaiming, “I shall stand mine, and no mistake.” We all declared it would never do for a lady to stand treat in the Crimea. “Lord bless you, Monsieur Soyer,” said the lady, “don’t you know me?” “Yes, I do now, my dear madam.” “Well, all those fine fellows you see here are my Jamaica sons—are you not?” said she, opening the champagne, and addressing the general. “We are, Mrs. Seacole, and a very good mother you have been to us.” “I have known you, general, for many years.” “Well, here’s a health to all.” We emptied our glasses, and returned the compliment. The general then left, again expressing his desire to see me at Cathcart’s Hill. “Walk inside, walk inside, my sons; you will be better there—it is not so hot. Go in, Monsieur Soyer.”
  • 75. No sooner had we entered than the old lady expressed her desire to consult me about what she should do to make money in her new speculation, in which she had embarked a large capital, pointing to two iron houses in course of construction on the other side of the road. She told me that her intention was to have beds there for visitors, which I persuaded her not to do, saying, “All the visitors—and they are few in number—sleep on board the vessels in the harbour, and the officers under canvass in the camp. Lay in a good stock of hams, wines, spirits, ale and porter, sauces, pickles, and a few preserves and dry vegetables—in short, anything which will not spoil by keeping.” “Yes,” said she, “I mean to have all that.” “In that case you will no doubt make money, as you are so well known to all the army.” “I assure you, the last time Lord Raglan passed here, he spoke to me for more than ten minutes, and promised to do all he could for me.” “That’s right,” we all said. “I know Miss Nightingale too. She was very kind to me when I passed through Scutari, on my way here; she gave me lodging and everything I required, in the hospital.” “We passed this way a few days before Miss Nightingale was taken ill,” said I. “I know you did; and I am sure, if the lady had known I was here, she would have called to see me. Thank God, I hear she is quite out of danger.” “Yes, she is improving.” “When you see her, present my best respects, and tell the dear lady that I shall go and see her.” “I will, Mrs. Seacole. Good-bye.” “Good-bye, my son.” On getting up in a hurry to be off, I missed my horse, and found one of the officers’ chargers, which had been left in charge of the same man to whom I had given mine, led by a Zouave. Upon inquiring of the Zouave where the man had gone, he informed me that he did not know, but that he had given him a shilling (which he showed me) to hold this animal for, as far as he could understand, about an hour, while he went on the grey in the direction of head-quarters. I called Mrs. Seacole out, and told her what had
  • 76. happened. She stepped up to the Zouave, and he began talking so fast, that I shall not forget the expression he made as long as I live. His speech may be thus translated: “By the name of Jupiter! I have neither stolen nor sold your horse. Look at me! (showing his corporation.) If you like, captain, to lend me this quadruped, I will soon find the voyiou (meaning a low rascal). There is my name and the number of my regiment. We are encamped near the French head-quarters.” All this time Mrs. Seacole had been looking about, and every grey pony she saw far or near was mine—at least in her eyes. The two officers mounted their horses, and went one one way and the other another, but soon returned, having found nothing. Having sent in all directions without being able to obtain any trace of the pony, we concluded that the animal was lost. I take this opportunity of publicly thanking those two gentlemen for the vivid interest they took in trying to find the borrowed steed. I very much regret that I do not recollect their names. They will no doubt remember the circumstance if this little work falls into their hands.[14] All our efforts to find the pony being useless, I made up my mind to walk back to Balaklava. Just as I was thanking Mrs. Seacole for her extraordinary exertions, Mr. Day, her partner, came in, and he advised me to go at once to the Hue and Cry, at head-quarters. “How am I to do this?” I asked. “Take my pony. It is not twenty minutes’ ride from hence; and you will stand a good chance of getting it back, especially if the man who held it was an Englishman. He is sure to be found in the English camp.” Thanking him for his kindness, I mounted, and started full gallop for head-quarters. I made inquiries at the Post-office, where I had the pleasure of meeting Mr. Russell, who introduced me to Mr. Angel, the postmaster. I then inquired for the Hue and Cry, and related the circumstances under which I had lost my pony. All seemed highly amused. They laughed heartily at my expense, and I could not help joining in the merriment. Mr. Angel invited me to dine with him, having a few friends that evening to join his popotte. “I am much obliged, my dear sir; but I am staying at Balaklava, and I suppose you dine late.” “About six o’clock,” replied Mr. Angel. “You can sleep here. We have no bed, it’s true; but I can lend you a blanket; and there is a small hut, which is
  • 77. empty, you can have all to yourself. Mr. Bracebridge slept there the night before last, when on a visit to Captain Boucher, a friend of his.” “Oh, as far as that goes, I shall be comfortable enough.” “Then you will dine with me?” “I will,” said I, “and am much obliged for your kind invitation.” I thought by accepting it, I should have an excellent opportunity of looking out for my pony in the morning, if I did not happen to find it that night; I therefore went to the Hue and Cry, and gave the best description, to my knowledge, as I had not had the honour of his acquaintance long, and did not know of any private marks by which he might be recognised. They gave me but faint hopes of seeing it again, and by way of comforting me, showed me a long list of missing horses, mules, and ponies, enough to fill half a column of the Times. “I don’t care so much about the pony, as that can be replaced; but the saddle is a new one from London, and neither the animal nor the saddle belong to me.” “You may, perhaps,” said one, “find the horse, but not the saddle, especially if it is gone to the French camp, for, believe me, the Zouaves are very fond of English saddles, as well as everything they can get hold of which does not require feeding; so they will probably keep the saddle and turn the horse loose. At all events, we will do what we can for you; but I advise you to look out for yourself.” It was then about four o’clock, and I had an hour’s ride about the camp, but it was all in vain. Every inquiry proved fruitless; and I could not obtain the slightest clue to the lost pony. I could not help smiling when I recollected Dr. Hadley’s last words, “You may lose the horse but don’t lose the saddle.” Hoping for better luck next day, I returned to head-quarters, and begged Lord Raglan’s groom to give Mr. Day’s pony a night’s lodging. Making sure Monsieur Armand would be in, I went to see him. He was rather busy, but he received me very politely, and showed me what he called his kitchen, though it had not the slightest claim to the title, as it was all but destitute of culinary utensils. The provisions were of inferior quality; but, as he told me, the best he could procure. I then offered my services if I could be of any use in getting stoves or a small oven erected. “Ever since I have been here,” he replied, “I have been asking for one or two charcoal stoves and a few shelves, but not a thing can I obtain for love
  • 78. or money.” “Upon my word you surprise me! How can that be in the house of the Commander-in-chief? Truly, every one has much to do.” “Such is the case.” “Never mind; I think I shall be able to get something done for you, as his lordship has spoken to me upon the subject.” “I shall be much obliged to you if you will,” said he; and then pointed out the principal things he required, which were soon afterwards furnished. As it was nearly six o’clock, I left him, and returned to the Post-office, where a sumptuous table was laid out. There was actually a tablecloth and real plates, knives, forks, and various kinds of glasses. In fact, for the Crimea, it was as the French say, épatant. We sat down six to dinner; and had some very strong preserved soup, a very nice tough fowl—the remainder of the bill of fare was made from the ration meat. We had very good wine; and, perhaps, never was a dinner better relished, or accompanied with more mirth and jokes. Russell the great was the hero, besides having an Angel for the host. Towards eight o’clock, the party amounted to about fifteen, as far as we could discern through the clouded atmosphere with which the room was filled. Every one was smoking; some large chibouques, long and short pipes, a few cigars, but no cigarettes. The unexpected increase to our party, I must observe, was partly owing to our vocal abilities, several lively choruses having attracted Mr. Angel’s illustrious neighbours, as the denizens of the woods were allured by the melody of Orpheus. Our mirth at last became so boisterous that it not only brought around us men of all ranks, but attracted the attention of the Commander-in-chief, who sent to inquire what the noise was about. This we considered a rather inharmonious inquiry, but found that, by decreasing the pitch of our vocal organs from allegro to piano, we should produce as much effect, with less noise, as his lordship wisely called it; though I heard the next day, that Lord Raglan, who was sitting at his door enjoying the fresh air with several gentlemen of his staff, enjoyed it, and gave orders that we should not be disturbed. Complaints poured in from the numerous tents which surrounded head-quarters. It was then about ten o’clock, which is equivalent to twelve or one p.m. in London. The mot d’ordre from our chairman was, “Tell those who cannot sleep to join our bacchanalian party.” So many took the hint,
  • 79. that no room could at length be obtained in the modern Crimean Temple of Momus. At last the order took a more positive character, for the very Angel who was presiding, observed, and very justly, that they were all playing the devil with him, and still more so with his cellar, which being but meagerly stocked, could not long stand so severe an attack. He therefore begged all new comers to go back to their quarters, and bring or send the liquid requisite to keep up the spirits of the guests till midnight—which was done. Every one, like Cinderella, disappeared, by slipping quietly out at the most convenient opportunity.
  • 80. CHAPTER XX. EXPEDITIONS ON HORSE AND ON FOOT. Comfortable couch—A terrible sortie—The borrowed animal reclaimed—A bad position—Lord Raglan lends me another steed—General Estcourt—Female improvements —Visit to the French camp—A French canteen—A lively vivandière—French regimental kitchens—Discoveries—Interview with Colonel Steele—Pertinent remarks—A carriage— Mrs. Estcourt and her sister—General Camp Hospital—Cathcart’s Hill—Strange reports— Concert à la Soyer—Receipt for a stew—Conversation with Sir John Campbell—A flag of truce—A good peep at Sebastopol—A cavalcade of amateurs—A sad spectacle—A narrow escape—Noisy night. NEXT morning, I found myself wrapped up in a horse-cloth, with a pair of top-boots for a pillow. The unfeeling and ungrateful board to which I had intrusted my precious limbs, had by the morning stamped his patron’s seal upon my back. The following day we learnt that a terrible sortie had taken place in the night, and that there had been a severe loss of men on both sides. At an early hour the court-yard was thronged with officers; despatches were flying in every direction; the cannon was roaring as usual, but the fusillade had ceased. I then went to the stable for my pony, when I found the owner, Mr. Day, upon his back, just going home. “Ah, Monsieur Soyer, I made sure that you had lost my pony as well as your own. I expected you back immediately, being in want of it.” “I was not aware of that, or I would have walked from your place sooner than have deprived you of it.” “Oh, never mind. Have you heard anything of your animal?” “No! but I am going to look after him this morning. That is the reason why I slept at head-quarters last night.” “I am going about the camp,” said he, “and will inquire for you.” He then started, of course leaving me without a horse, and with dreadful pains in my back and legs, which I attributed to the softness of the bed with which I had been favoured; though I could not boast of a single feather, like that Tocrisse of a recruit, who took one out of his master’s feather bed, laid
  • 81. it down on the boarded floor of his hut, and next morning told his companions that his master must be foolish to sleep upon a feather bed. “Why?” asked they. “Why, if one feather is so hard, what must the lot the captain sleeps upon be?” The worst of my position was, how to get another horse, as it was impossible for me to walk all day about the camp, being so stiff and tired. I went to Lord Raglan’s coachman, and inquired if he had one to spare. He replied— “Monsieur Soyer, we can spare a pony for you, but you must ask permission of the master of the horse or Lord Raglan, as I have special orders not to lend one upon my own responsibility. I am sure his lordship will let you have it immediately.” At this moment I caught sight of Lord Raglan’s valet, and I begged him to make the request; which he did, and came to tell me that his lordship desired I should have it by all means. Once more mounted, I made an early call upon the friends of the previous night, most of whom resided round head-quarters. I had the pleasure of being introduced to General Estcourt, who took me to see the printing press where my receipts for the army were done—some of which have appeared in the public press. Afterwards I went with him to his quarters, which, though small, were very neatly arranged. The taste was not military, and I thought that I detected the work of a female hand, which I could not help remarking to the general. “You are right, Monsieur,” said he, smiling—“it has only lately been arranged by ladies. Mrs. Estcourt and my sister are here, and this is a little bit of their handywork. They are staying on board ship at Balaklava, and come here every day. Before they arrived I had only this small room (showing me his bed made upon boards) where I sleep as well as ever I did in my life. The only thing which awakes me in the night is when the cannon ceases firing—I am so used to it.” “I believe that, general, and have no doubt you seldom miss hearing a report. In fact, you are the nearest of those at head-quarters to Sebastopol.” I then inquired about the sortie of the previous night. The general said he did not know the result of it, and very kindly invited me to breakfast, which I declined, having to go round the French camp in search of my pony.
  • 82. “I shall be happy,” said General Estcourt, “to do anything I can for you; and if you call in the afternoon, my wife and her sister will be here, and I will introduce you to them.” Thanking him kindly, I retired, and proceeded round the French camp making inquiries; then to their head-quarters, where I met Captain Boucher, General Canrobert’s aide-de-camp, with whom I had the pleasure of travelling. He promised to introduce me to the general, who, he said, would be very glad to see me. Upon my telling him about my pony, he remarked— “If he is in our camp you are sure to get him back, for we have put a stop to that kind of piracy by very severe punishment. They used to come and steal our horses from our very stables; but tell me what sort of a horse he is, and I will advertise him with the others, and we shall know in less than five or six hours if he is in our camp? the plan we have adopted cannot fail.” Having described the animal to the captain, I thanked him for his kindness. Considering my French review terminated, I thought of returning at once to the English head-quarters, having to see several of the authorities upon business. On my way I happened to pass by a nice French canteen. I inquired if I could get any breakfast? A rather stout vivandière, dressed in the uniform of the Imperial Guard, very politely said to me: “What a stupid question to ask! Do you think we have not everything required for the purpose here? Perhaps, Captain of the Lord knows what regiment, you think we have come out merely to thread pearls, sing ‘Partant pour la Syrie,’ and dance the Fandango.” On my way I visited several regimental kitchens and tasted the soup. Some was better than at others. They had no vegetables excepting some vegetable marrow—more likely to spoil the soup than improve it. I made several important discoveries respecting the system of cooking pursued in the French camp, after visiting, with some of my new acquaintances, a row of twelve kitchens, which number, they informed me, was required for each regiment—being at the rate of one per company. One man was told off as cook for every squad or mess of sixteen. The buildings were composed of mud and stone, and covered an extent of about four hundred yards. I bade my brave companions farewell, and left them quite a happy man, having entirely forgotten horse and saddle, in making the discovery that in lieu of four hundred yards of space, a dozen buildings, and about eighty men for
  • 83. each regiment, an immense consumption of fuel, and smoke enough to blind three parts of the army—as the men were all cooks in turn—my system was simple, effective, and vastly superior to that even of the French, which had hitherto always been considered as preferable to the English. This was indeed the case, for all French soldiers understand a little cooking, and their canteen, pan was far superior to that in use amongst the English troops, which I condemned at first sight in the camp at Chobham. I returned to head-quarters, intending to communicate my discovery to Lord Raglan; but learning that he was very busy, and would not be disengaged till evening, I went to Colonel Steele, who, in spite of the pressure of business, gave me an immediate audience, and promised to speak to Lord Raglan on the subject. Head-quarters were that day, in a manner, taken by storm. They were literally besieged, and this gave me an opportunity of getting acquainted with several officers and other officials whom I had not the pleasure of knowing—or, at least, only by sight. Amongst these were Sir George Brown, Sir W. Codrington, Sir Colin Campbell, Lord Rokeby, Captain Whitmore, and Brevet-Major A. Macdonald. Lord Raglan passed me in the passage, and said, “You wish to see me, Monsieur Soyer?” Knowing his lordship was much occupied, I replied, “Colonel Steele will give you the particulars that I came to communicate.” “That will do; but have you found your horse?” “No, my lord.” “I have been to visit Miss Nightingale. She is still very ill. Bad job, bad job, poor lady!” he continued, walking away towards Colonel Steele’s office, with his hands full of papers. After this I called upon Doctor Hall, with whom I had a few minutes’ conversation upon business. Louis was somewhere about, busily engaged, and, as usual, unwilling to give a direct reply, no matter what question you put to him. He came to see me. I inquired if he knew anything about the sortie of the previous night, upon which he answered that the black horse he rode the day before had thrown him in the mud, and made him in such a mess. I replied in his style: “The sun is very hot to-day.” Upon which he observed, “he never was there in his life.”
  • 84. I begged of him to tell me how he was to-morrow. “Don’t believe that,” said he; “it is quite false.” An interesting young man indeed was Louis. A very great curiosity then made its appearance, breaking the thread of our scientific conversation. What, reader, do you think it was? A carriage!— a thing unknown in the camp—or at least a bad imitation of one—drawn by two very obstinate mules, one pulling against the other, which seemed to amuse my intelligent friend Louis, who never liked to see anything going on smoothly. General Estcourt went out to meet it, and two ladies alighted. To this Louis thoroughly objected, saying—“Ladies, indeed! they are the two female Zouaves who performed in the Anglaises pour Rire, at the theatre in their camp. One,” said he, “is Jean Huguet—the other Panaudet, aide-de-camp to the drum-major of a regiment of cavalry. The first plays Lady Painbeche in that tragedy—the other, Lady Don’t-you-wish-you-may- get-it.” Very fertile indeed was the brain of Louis at composition of the higher school; and, like Marplot, never wishing to see anything in its right light, he succeeded admirably. The sight of a carriage was something wonderful, but two ladies at once, and fashionably dressed, was too much good-luck. I advanced towards them, and had the honour of being introduced by the general to Mrs. Estcourt and his sister. The general invited me to walk in, and I had the honour of taking a glass of wine with the fair—who might well be called fairies at the time—ladies being so scarce, in fact, all but invisible, in the Crimea. After a short, but very interesting, conversation with the ladies, I retired, leaving some copies of my receipts with Mrs. Estcourt, who kindly undertook to look at the proofs before printing. Thence I proceeded to the General Camp Hospital, and there met Doctor Mouatt, who told me he was waiting for the bricks for his oven from the Ordnance Office at head- quarters. I informed him that I had given in the plan for a kitchen, and endeavoured to convince him of the necessity of having it done at once. “I am well aware of that, and it shall be attended to.” All inquiries respecting my pony were fruitless. At last, upon asking at a canteen, a soldier told me he had heard of one being found in some regiment, but could not tell me which one, though he thought it was somewhere about Cathcart’s Hill.
  • 85. 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