100% found this document useful (1 vote)
20 views

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF download

The document provides links to various eBooks related to Java programming and other subjects, including titles by Joyce Farrell and Roger Leroy Miller. It includes details about the 10th edition of 'Java Programming' and other educational materials available for download. Additionally, it contains copyright information and a brief overview of the book's content structure, including chapters and appendices.

Uploaded by

feutzarion39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
20 views

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF download

The document provides links to various eBooks related to Java programming and other subjects, including titles by Joyce Farrell and Roger Leroy Miller. It includes details about the 10th edition of 'Java Programming' and other educational materials available for download. Additionally, it contains copyright information and a brief overview of the book's content structure, including chapters and appendices.

Uploaded by

feutzarion39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Java Programming (MindTap Course List), 10th

Edition Joyce Farrell - eBook PDF install


download

https://ebookluna.com/download/java-programming-mindtap-course-
list-10th-edition-ebook-pdf/

Download more ebook from https://ebookluna.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Java Programming 9th Edition Joyce Farrell - eBook PDF

https://ebookluna.com/download/java-programming-ebook-pdf/

ebookluna.com

Programming Logic & Design, Comprehensive 9th edition


Joyce Farrell - eBook PDF

https://ebookluna.com/download/programming-logic-design-
comprehensive-9th-edition-ebook-pdf/

ebookluna.com

Programming Logic and Design, Comprehensive 9th Edition


Joyce Farrell - eBook PDF

https://ebookluna.com/download/programming-logic-and-design-
comprehensive-9th-edition-ebook-pdf/

ebookluna.com

Introduction to Java Programming, Comprehensive Version


10th edition- eBook PDF

https://ebookluna.com/download/introduction-to-java-programming-
comprehensive-version-ebook-pdf/

ebookluna.com
Physics for Scientists and Engineers (MindTap Course List)
10th Edition Serway - eBook PDF

https://ebookluna.com/download/physics-for-scientists-and-engineers-
mindtap-course-list-ebook-pdf/

ebookluna.com

Business Law: Text & Exercises (MindTap Course List) 10th


Edition Roger Leroy Miller - eBook PDF

https://ebookluna.com/download/business-law-text-exercises-mindtap-
course-list-ebook-pdf/

ebookluna.com

Your Career: How to Make it Happen (MindTap Course List)


10th Edition Lisa Owens - eBook PDF

https://ebookluna.com/download/your-career-how-to-make-it-happen-
mindtap-course-list-ebook-pdf/

ebookluna.com

Interpersonal Conflict 10th Edition Joyce L. Hocker -


eBook PDF

https://ebookluna.com/download/interpersonal-conflict-ebook-pdf/

ebookluna.com

(eBook PDF) Murach's Java Programming 5th Edition by Joel


Murach

https://ebookluna.com/product/ebook-pdf-murachs-java-programming-5th-
edition-by-joel-murach/

ebookluna.com
Java
Programming
Tenth Edition

Joyce Farrell

Australia • Brazil • Canada • Mexico • Singapore • United Kingdom • United States

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.

Important Notice: Media content referenced within the product description or the product
text may not be available in the eBook version.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
JavaTM Programming, Tenth Edition © 2023, © 2019, © 2016 Cengage Learning, Inc. WCN: 02-300
Joyce Farrell ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
may be reproduced or distributed in any form or by any means, except as
SVP, Higher Education Product Management: Erin
permitted by U.S. copyright law, without the prior written permission of the
Joyner
copyright owner.
VP, Product Management, Learning Experiences: Unless otherwise noted, all content is Copyright © Cengage Learning, Inc.
Thais Alencar
Unless otherwise noted, all screenshots are courtesy of Microsoft Corporation.
Product Director: Mark Santee
Microsoft is a registered trademark of Microsoft Corporation in the U.S.
Associate Product Manager: Tran Pham and/or other countries.

The names of all products mentioned herein are used for identification
Product Assistant: Ethan Wheel
purposes only and may be trademarks or registered trademarks of their
Learning Designer: Mary Convertino respective owners. Cengage Learning disclaims any affiliation, association,
connection with, sponsorship, or endorsement by such owners.
Senior Content Manager: Maria Garguilo

Associate Digital Delivery Quality Partner: David For product information and technology assistance, contact us at
O’Connor Cengage Customer & Sales Support, 1-800-354-9706
or support.cengage.com.
Technical Editor: John Freitas
For permission to use material from this text or product, submit all
Developmental Editor: Dan Seiter
requests online at www.copyright.com.

VP, Product Marketing: Jason Sakos


Library of Congress Control Number: 2021925780
Director, Product Marketing: April Danaë
ISBN: 978-0-357-67342-3
Portfolio Marketing Manager: Mackenzie Paine
Cengage
IP Analyst: Ann Hoffman
200 Pier 4 Boulevard
IP Project Manager: Integra Software Services Boston, MA 02210
USA
Production Service: Straive
Cengage is a leading provider of customized learning solutions with
Senior Designer: Erin Griffin employees residing in nearly 40 different countries and sales in more than
125 countries around the world. Find your local representative at
Cover Image Source: iStock.com/gremlin
www.cengage.com.

To learn more about Cengage platforms and services, register or access


your online learning solution, or purchase materials for your course, visit
www.cengage.com.

Notice to the Reader


Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with
any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and
include information other than that provided to it by the manufacturer. The reader is expressly warned to consider and adopt all safety
precautions that might be indicated by the activities described herein and to avoid all potential hazards. By following the instructions
contained herein, the reader willingly assumes all risks in connection with such instructions. The publisher makes no representations
or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any
such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to
such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from
the readers’ use of, or reliance upon, this material.

Printed in the United States of America


Print Number: 01   Print Year: 2022

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
BRIEF CONTENTS
PREFACEXI

CHAPTER 1 Creating Java Programs�������������������������������������������������������������������������������� 1


CHAPTER 2 Using Data���������������������������������������������������������������������������������������������������� 39
CHAPTER 3 Using Methods�������������������������������������������������������������������������������������������� 83
CHAPTER 4 Using Classes and Objects����������������������������������������������������������������������� 115
CHAPTER 5 Making Decisions�������������������������������������������������������������������������������������� 161
CHAPTER 6 Looping������������������������������������������������������������������������������������������������������� 201
CHAPTER 7 Characters, Strings, and the StringBuilder�������������������������������������� 237
CHAPTER 8 Arrays��������������������������������������������������������������������������������������������������������� 267
CHAPTER 9 Inheritance and Interfaces����������������������������������������������������������������������� 329
CHAPTER 10 Exception Handling��������������������������������������������������������������������������������� 393
CHAPTER 11 File Input and Output����������������������������������������������������������������������������� 441
CHAPTER 12 Recursion������������������������������������������������������������������������������������������������� 487
CHAPTER 13 Collections and Generics����������������������������������������������������������������������� 511
CHAPTER 14 Introduction to Swing Components���������������������������������������������������� 545
APPENDIX A Working with the Java Platform ����������������������������������������������������������� 587

APPENDIX B Data Representation ����������������������������������������������������������������������������� 591

APPENDIX C Formatting Output �������������������������������������������������������������������������������� 595

APPENDIX D Generating Random Numbers ������������������������������������������������������������ 603

APPENDIX E Javadoc ���������������������������������������������������������������������������������������������������� 607

APPENDIX F Using JavaFX and Scene Builder ����������������������������������������������������������� 613

GLOSSARY 625
INDEX 641

iii

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
PREFACEXI Key Terms 32
Review Questions 33
CHAPTER 1 Programming Exercises 34
Debugging Exercises 36
CREATING JAVA PROGRAMS 1
Game Zone 36
1.1 Learning Programming Terminology 1 Case Problems 37
1.2 Comparing Procedural and Object-
Oriented Programming Concepts 4
CHAPTER 2
Procedural Programming 4
Object-Oriented Programming 5 USING DATA 39
Understanding Classes, Objects, and Encapsulation 6
2.1 Declaring and Using Constants
Understanding Inheritance and Polymorphism 7
and Variables 39
1.3 Features of the Java Programming Declaring Variables 40
Language8
Declaring Named Constants 42
1.4 Analyzing a Java Application That The Scope of Variables and Constants 43
Produces Console Output 10
Concatenating Strings to Variables and
Understanding the Statement That Produces the Constants 43
Output10
Pitfall: Forgetting That a Variable Holds One
Understanding the First Class 12 Value at a Time 45
Understanding the main() Method 14
2.2 Learning About Integer Data
Indent Style 15
Types47
Saving a Java Class 16
2.3 Using the boolean Data Type 51
1.5 Compiling a Java Class and
Correcting Syntax Errors 18 2.4 Learning About Floating-Point
Compiling a Java Class 18 Data Types 52
Correcting Syntax Errors 19 2.5 Using the char Data Type 53
1.6 Running a Java Application and 2.6 Using the Scanner Class to
Correcting Logic Errors 23 Accept Keyboard Input 57
Running a Java Application 23 Pitfall: Using nextLine() Following One of the
Modifying a Compiled Java Class 23 Other Scanner Input Methods 59
Correcting Logic Errors 24
2.7 Using the JOptionPane Class to
1.7 Adding Comments to a Java Class 25 Accept GUI Input 64
1.8 Creating a Java Application That Using Input Dialog Boxes 64
Produces GUI Output 27 Using Confirm Dialog Boxes 66
1.9 Finding Help 29 2.8 Performing Arithmetic Using
Variables and Constants 68
Don’t Do It 30 Associativity and Precedence 69
Summary31 Writing Arithmetic Statements Efficiently 69

iv

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents v

Pitfall: Not Understanding Imprecision in Game Zone 113


Floating-Point Numbers 70 Case Problems 114
2.9 Understanding Type Conversion 72
Automatic Type Conversion 73 CHAPTER 4
Explicit Type Conversion 73
USING CLASSES AND OBJECTS 115
Don’t Do It 76 4.1 Learning About Classes
Summary 77 and Objects 115
Key Terms 77 4.2 Creating a Class 117
Review Questions 78
Programming Exercises 80
4.3 Creating Instance Methods
in a Class 119
Debugging Exercises 81
Game Zone 81 4.4 Declaring Objects and
Case Problems 82 Using Their Methods 124
Understanding Data Hiding 126

CHAPTER 3 4.5 Understanding That Classes


Are Data Types 128
USING METHODS 83 4.6 Creating and Using Constructors 131
3.1 Understanding Method Calls and Creating Constructors with Parameters 132
Placement83
4.7 Learning About the this
3.2 Understanding Method Reference134
Construction86 Using the this Reference to Make
Access Specifiers 86 Overloaded Constructors More Efficient 137
The static Modifier 87
4.8 Using static Fields 139
Return Type 87
Using Constant Fields 140
Method Name 87
Parentheses 88 4.9 Using Imported, Prewritten
Constants and Methods 143
3.3 Adding Parameters to Methods 91
The Math Class 144
Creating a Method That Receives a Single
Importing Classes That Are Not Imported
Parameter 91
Automatically 145
Creating a Method That Requires Multiple
Using the LocalDate Class 146
Parameters 94

3.4 Creating Methods That 4.10 U


 nderstanding Composition
Return Values 95 and Nested Classes 150
Composition 150
3.5 Understanding Blocks and Scope 99
Nested Classes 151
3.6 Overloading a Method 104
3.7 Learning about Ambiguity 107 Don’t Do It 153
Summary 153
Don’t Do It 108 Key Terms 154
Summary 108 Review Questions 154
Key Terms 109 Programming Exercises 156
Review Questions 109 Debugging Exercises 158
Programming Exercises 111 Game Zone 158
Debugging Exercises 113 Case Problems 159

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
vi Contents

CHAPTER 5 CHAPTER 6
MAKING DECISIONS 161 LOOPING201
5.1 Planning Decision-Making Logic 161 6.1 Learning About the Loop
5.2 The if and if…else Statements 163 Structure201
The if Statement 163 6.2 Creating while Loops 202
Pitfall: Misplacing a Semicolon in an if Statement 164 Writing a Definite while Loop 202
Pitfall: Using the Assignment Operator Instead Pitfall: Failing to Alter the Loop Control Variable
of the Equivalency Operator 165 Within the Loop Body 204
Pitfall: Attempting to Compare Objects Using Pitfall: Unintentionally Creating a Loop with
the Relational Operators 165 an Empty Body 204
The if…else Statement 166 Altering a Definite Loop’s Control Variable 206
Writing an Indefinite while Loop 206
5.3 Using Multiple Statements in
if and if…else Clauses 168 Validating Data 208

5.4 Nesting if and if…else 6.3 Using Shortcut Arithmetic


Statements172 Operators210
5.5 Using Logical AND and OR 6.4 Creating a for Loop 214
Operators174 Variations in for Loops 215
The AND Operator 174 6.5 Learning How and When to Use
The OR Operator 175 a do…while Loop 217
Short-Circuit Evaluation 175 6.6 Learning About Nested Loops 220
5.6 Making Accurate and Efficient 6.7 Improving Loop Performance 223
Decisions178 Avoiding Unnecessary Operations 223
Making Accurate Range Checks 178 Considering the Order of Evaluation of
Making Efficient Range Checks 180 Short-Circuit Operators 224
Using && and || Appropriately 180 Comparing to Zero 224
5.7 Using switch  181 Employing Loop Fusion 226
Using the switch Expression 183 A Final Note on Improving Loop Performance 226

5.8 Using the Conditional and NOT


Operators186 Don’t Do It 228
Summary 228
Using the NOT Operator 187
Key Terms 229
5.9 Understanding Operator
Review Questions 229
Precedence187
Programming Exercises 232
5.10 M
 aking Constructors More Debugging Exercises 233
Efficient by Using Decisions in
Game Zone 234
Other Methods 189
Case Problems 235

Don’t Do It 193


Summary 193 CHAPTER 7
Key Terms 194
CHARACTERS, STRINGS, AND
Review Questions 194
THE StringBuilder 237
Programming Exercises 197
Debugging Exercises 198 7.1 Understanding String Data
Game Zone 199
Problems237
Case Problems 200 7.2 Using Character Class Methods 238

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents vii

7.3 Declaring and Comparing 8.8 Using Two-Dimensional and Other


String Objects 241 Multidimensional Arrays 300
Comparing String Values 241 Passing a Two-Dimensional Array to a Method 302
Empty and null Strings 245 Using the length Field with a Two-Dimensional
Array303
7.4 Using a Variety of String
Methods246 Understanding Jagged Arrays 304
Using Other Multidimensional Arrays 304
Converting String Objects to Numbers 249

7.5 Learning About the StringBuilder 8.9 Using the Arrays Class 307
and StringBuffer Classes 253 8.10 Creating Enumerations 311

Don’t Do It 257 Don’t Do It 316


Summary 258 Summary 317
Key Terms 258 Key Terms 318
Review Questions 258 Review Questions 318
Programming Exercises 260 Programming Exercises 320
Debugging Exercises 262 Debugging Exercises 323
Game Zone 263 Game Zone 323
Case Problems 264 Case Problems 327

CHAPTER 8 CHAPTER 9
ARRAYS267 INHERITANCE AND INTERFACES 329
8.1 Declaring an Array 267 9.1 Learning About the Concept of
8.2 Initializing an Array 271 Inheritance329
Inheritance Terminology 331
8.3 Using Variable Subscripts with an
Array273 9.2 Extending Classes 332
Using the Enhanced for Loop 275 9.3 Overriding Superclass Methods 336
Using Part of an Array 275 Using the @Override Annotation 337
8.4 Declaring and Using Arrays 9.4 Calling Constructors During
of Objects 277 Inheritance339
Using the Enhanced for Loop with Objects 279 Using Superclass Constructors That Require
Manipulating Arrays of Strings 279 Arguments 340

8.5 Searching an Array and Using 9.5 Accessing Superclass Methods 344
Parallel Arrays 284 Comparing this and super 345
Using Parallel Arrays 284
9.6 Employing Information Hiding 346
Searching an Array for a Range Match 286
9.7 Methods You Cannot Override 348
8.6 Passing Arrays to and Returning
Arrays from Methods 289 A Subclass Cannot Override static Methods
in Its Superclass 348
Returning an Array from a Method 291
A Subclass Cannot Override final Methods
8.7 Sorting Array Elements 292 in Its Superclass 350
Using the Bubble Sort Algorithm 293 A Subclass Cannot Override Methods in a final
Improving Bubble Sort Efficiency 295 Superclass 351
Sorting Arrays of Objects 295 9.8 Creating and Using Abstract
Using the Insertion Sort Algorithm 296 Classes352

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
viii Contents

9.9 Using Dynamic Method Binding 359 10.7 T


 racing Exceptions Through the
Using a Superclass as a Method Parameter Type 360 Call Stack 415
9.10 C
 reating Arrays of Subclass 10.8 C
 reating Your Own Exception
Objects361 Classes419
9.11 U
 sing the Object Class and Its 10.9 Using Assertions 421
Methods364 10.10 Displaying the Virtual Keyboard 430
Using the toString() Method 364
Using the equals() Method 366 Don’t Do It 433
Overloading equals() 367 Summary 434
Overriding equals() 369 Key Terms 434
9.12 Creating and Using Interfaces 371 Review Questions 435
Creating Interfaces to Store Related Constants 374 Programming Exercises 437
Debugging Exercises 439
9.13 U
 sing records, Anonymous Inner
Classes, and Lambda Expressions 377 Game Zone 439

Using records 377 Case Problems 440

Using Anonymous Inner Classes 379


Using Lambda Expressions 380 CHAPTER 11
FILE INPUT AND OUTPUT 441
Don’t Do It 381
Summary 381
11.1 Understanding Computer Files 441
Key Terms 383 11.2 U
 sing the Path and Files
Review Questions 383 Classes443
Programming Exercises 385 Creating a Path 443
Debugging Exercises 389 Retrieving Information About a Path 444
Game Zone 390 Converting a Relative Path to an Absolute One 445
Case Problems 391 Checking File Accessibility 446
Deleting a Path 447
Determining File Attributes 448
CHAPTER 10
11.3 F
 ile Organization, Streams, and
EXCEPTION HANDLING 393 Buffers450
10.1 Learning About Exceptions 393 11.4 Using Java’s IO Classes 452
10.2 T
 rying Code and Catching Writing to a File 454
Exceptions397 Reading from a File 454
Using a try Block to Make Programs “Foolproof” 400 11.5 C
 reating and Using Sequential
Declaring and Initializing Variables in try…catch Data Files 457
Blocks 402
11.6 L
 earning About Random Access
10.3 T
 hrowing and Catching Multiple Files461
Exceptions404
11.7 W
 riting Records to a Random
10.4 Using the finally Block 408 Access Data File 463
10.5 U
 nderstanding the Advantages 11.8 R
 eading Records from a Random
of Exception Handling 410 Access Data File 468
10.6 S
 pecifying the Exceptions That Accessing a Random Access File Sequentially 468
a Method Can Throw 412 Accessing a Random Access File Randomly 470

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents ix

Don’t Do It 479 13.4 Using the LinkedList Class 524


Summary 479
13.5 Using Iterators 528
Key Terms 480
Review Questions 480
13.6 Creating Generic Classes 530
Programming Exercises 482 13.7 Creating Generic Methods 532
Debugging Exercises 484 Creating a Generic Method with More than One
Game Zone 484 Type Parameter 533

Case Problems 485


Don’t Do It 537

CHAPTER 12 Summary 538


Key Terms 538
RECURSION487 Review Questions 539

12.1 Understanding Recursion 487 Programming Exercises 541


Debugging Exercises 542
12.2 U
 sing Recursion to Solve
Game Zone 542
Mathematical Problems 489
Case Problems 543
Computing Sums 490
Computing Factorials 491
12.3 U
 sing Recursion to Manipulate CHAPTER 14
Strings495
INTRODUCTION TO Swing
Using Recursion to Separate a Phrase into Words 495
Using Recursion to Reverse the Characters in a
COMPONENTS545
String 496 14.1 U
 nderstanding Swing
12.4 U
 sing Recursion to Create Visual Components545
Patterns499 14.2 Using the JFrame Class 547
12.5 R
 ecursion’s Relationship to Customizing a JFrame’s Appearance 549
Iterative Programming 500 14.3 Using the JLabel Class 552
Changing a JLabel’s Font 553
Don’t Do It 503
14.4 Using a Layout Manager 555
Summary 503
Key Terms 504 14.5 Extending the JFrame Class 557
Review Questions 504 14.6 A
 dding JTextFields and
Programming Exercises 506 JButtons to a JFrame 559
Debugging Exercises 508 Adding JTextFields to a JFrame 559
Game Zone 509 Adding JButtons to a JFrame 560
Case Problems 510 14.7 L
 earning About Event-Driven
Programming563
CHAPTER 13 Preparing Your Class to Accept Event Messages 564
Telling Your Class to Expect Events to Happen 564
COLLECTIONS AND GENERICS 511 Telling Your Class How to Respond to Events 564
13.1 U
 nderstanding the Collection Writing an Event-Driven Program 565
Interface511 Using Multiple Event Sources 566
13.2 U
 nderstanding the List Using the setEnabled() Method 567
Interface513
14.8 U
 nderstanding Swing Event
13.3 Using the ArrayList Class 514 Listeners569

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
x Contents

14.9 U
 sing the JCheckBox, APPENDIX C
ButtonGroup, and JComboBox
Classes572 FORMATTING OUTPUT  595
The JCheckBox Class 572
The ButtonGroup Class 574 APPENDIX D
The JComboBox Class 575
GENERATING RANDOM
Don’t Do It 580 NUMBERS 603
Summary 581
Key Terms 581 APPENDIX E
Review Questions 582
JAVADOC  607
Programming Exercises 584
Debugging Exercises 585
Game Zone 585
APPENDIX F
Case Problems 586 USING JAVAFX AND SCENE
BUILDER613
APPENDIX A
GLOSSARY 625
WORKING WITH THE INDEX 641
JAVA PLATFORM 587

APPENDIX B
DATA REPRESENTATION 591

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE
Java Programming, Tenth Edition provides the beginning programmer with a guide to developing applications
using the Java programming language. Java is popular among professional programmers because it is object-
oriented, making complex problems easier to solve than in some other languages. Java is used for desktop
computing, mobile computing, game development, Web development, and numerical computing.

This course assumes that you have little or no programming experience. It provides a solid background in
good object-oriented programming techniques and introduces terminology using clear, familiar language. The
programming examples are business examples; they do not assume a mathematical background beyond high
school business math. In addition, the examples illustrate only one or two major points; they do not contain so
many features that you become lost following irrelevant and extraneous details. Complete, working programs
appear frequently in each chapter; these examples help students make the transition from the theoretical
to the practical. The code presented in each chapter also can be downloaded from the Cengage website, so
students easily can run the programs and experiment with changes to them.

The student using Java Programming, Tenth Edition builds applications from the bottom up rather than
starting with existing objects. This facilitates a deeper understanding of the concepts used in object-oriented
programming and engenders appreciation for the existing objects students use as their knowledge of the
language advances. When students complete this course, they will know how to modify and create simple Java
programs, and they will have the tools to create more complex examples. They also will have a fundamental
knowledge of object-oriented programming, which will serve them well in advanced Java courses or in studying
other object-oriented languages such as C++, C#, and Visual Basic.

Organization and Coverage


Java Programming, Tenth Edition presents Java programming concepts, enforcing good style, logical thinking,
and the object-oriented paradigm. Objects are covered right from the beginning, earlier than in many other
Java courses. You create your first Java program in Chapter 1. Chapters 2, 3, and 4 increase your understanding
about how data, classes, objects, and methods interact in an object-oriented environment.

Chapters 5 and 6 explore input and repetition structures, which are the backbone of programming logic and
essential to creating useful programs in any language. You learn the special considerations of string and array
manipulation in Chapters 7 and 8.

Chapters 9 and 10 thoroughly cover inheritance, interfaces, and exception handling. Inheritance is the object-
oriented concept that allows you to develop new objects quickly by adapting the features of existing objects,
interfaces define common methods that must be implemented in all classes that use them, and exception
handling is the object-oriented approach to handling errors. All of these are important concepts in object-
oriented design. Chapter 11 provides information about handling files so you can store and retrieve program
output.

Chapter 12 explains recursion, and Chapter 13 covers Java collections and generics. Both are important
programming concepts, and Java provides excellent ways to implement and learn about them. Chapter 14
introduces GUI Swing components, which are used to create visually pleasing, user-friendly, interactive
applications.

xi

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xii Preface

New in This Edition


The following features are new for the Tenth Edition:

❯❯Java: All programs have been tested using Java 16.

❯❯Java help: Instructions on searching for Java help have been updated to avoid using specific URLs because new
Java versions are now being released twice a year.
❯❯Text blocks: Chapter 2 introduces text blocks—a new feature since Java 13.

❯❯Methods: Methods are covered thoroughly in Chapter 3, including topics such as overloading methods and
avoiding ambiguity. In previous editions, the material was split between chapters.
❯❯Classes and objects: Classes and objects are covered thoroughly in Chapter 4. In previous editions, the material
was split between chapters.
❯❯The switch expression: Chapter 5 includes the switch expression, which became a new feature in Java 14.

❯❯Arrays: Chapter 8 covers beginning and advanced array concepts. In previous editions, this content was split
between chapters.
❯❯Inheritance and interfaces: Chapter 9 covers inheritance and interfaces. In previous editions, this content was
split between chapters.
❯❯The record keyword: Chapter 9 also introduces the record keyword, which allows simple classes to be
developed more quickly because a constructor and methods to get and set fields are created automatically
based on field definitions.
❯❯Recursion: Chapter 12 is a new chapter on recursion. The chapter presents techniques to use to solve
mathematical problems, manipulate strings, and create visual patterns using recursion.
❯❯Collections and generics: Chapter 13 is a new chapter on collections and generics. The chapter covers the
Collection and List interfaces, the ArrayList and LinkedList classes, Iterators, and generic
classes and methods.

Additionally, Java Programming, Tenth Edition includes the following features:

❯❯Objectives: Each chapter begins with a list of objectives so you know the topics that will be presented in the
chapter. In addition to providing a quick reference to topics covered, this feature provides a useful study aid.
❯❯You Do It: In each chapter, step-by-step exercises help students create multiple working programs that
emphasize the logic a programmer uses in choosing statements to include. These sections provide a means for
students to achieve success on their own—even those in online or distance learning classes.
❯❯Notes: These highlighted tips provide additional information—for example, an alternative method of performing
a procedure, another term for a concept, background information about a technique, or a common error to
avoid.
❯❯Emphasis on student research: The student frequently is advised to use the Web to investigate Java classes,
methods, and techniques. Computer languages evolve, and programming professionals must understand how to
find the latest language improvements.
❯❯Figures: Each chapter contains many figures. Code figures are most frequently 25 lines or fewer, illustrating one
concept at a time. Frequent screenshots show exactly how program output appears. Callouts appear where
needed to emphasize a point.
❯❯Color: The code figures in each chapter contain all Java keywords in blue. This helps students identify keywords
more easily, distinguishing them from programmer-selected names.
❯❯Files: More than 200 student files can be downloaded from the Cengage website. Most files contain the code
presented in the figures in each chapter; students can run the code for themselves, view the output, and make

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xiii

changes to the code to observe the effects. Other files include debugging exercises that help students improve
their programming skills.
❯❯Two Truths & a Lie: A short quiz reviews almost every chapter section, with answers provided. This quiz
contains three statements based on the preceding section of text—two statements are true, and one is false.
Over the years, students have requested answers to problems, but we have hesitated to distribute them in case
instructors want to use problems as assignments or test questions. These true-false quizzes provide students
with immediate feedback as they read, without “giving away” answers to the multiple-choice questions and
programming exercises.
❯❯Don’t Do It: This section at the end of each chapter summarizes common mistakes and pitfalls that plague new
programmers while learning the current topic.
❯❯Summary: Following each chapter is a summary that recaps the programming concepts and techniques covered
in the chapter. This feature provides a concise means for students to check their understanding of the main
points in each chapter.
❯❯Key Terms: Each chapter includes a list of newly introduced vocabulary, shown in alphabetical order. The list of
key terms provides a short review of the major concepts in the chapter.
❯❯Review Questions: Each chapter includes 20 multiple-choice questions that serve as a review of chapter topics.

❯❯Programming Exercises: Multiple programming exercises are included with each chapter. These challenge
students to create complete Java programs that solve real-world problems.
❯❯Debugging Exercises: Four debugging exercises are included with each chapter. These are programs that
contain logic or syntax errors that the student must correct. Besides providing practice in deciphering error
messages and thinking about correct logic, these exercises provide examples of complete and useful Java
programs after the errors are repaired.
❯❯Game Zone: Each chapter provides one or more exercises in which students can create interactive games
using the programming techniques learned up to that point; 50 game programs are suggested in the course.
The games are fun to create and play; writing them motivates students to master the necessary programming
techniques. Students might exchange completed game programs with each other, suggesting improvements and
discovering alternate ways to accomplish tasks.
❯❯Cases: Each chapter contains two running case problems. These cases represent projects that continue to
grow throughout a semester using concepts learned in each new chapter. Two cases allow instructors to assign
different cases in alternate semesters or to divide students in a class into two case teams.
❯❯Glossary: A glossary contains definitions for all key terms in the course.

❯❯Appendices: This edition includes useful appendices on working with the Java platform, data representation,
formatting output, generating random numbers, creating Javadoc comments, and JavaFX.
❯❯Quality: Every program example, exercise, and game solution was tested by the author and then tested again by
a quality assurance team.

MindTap Instructor Resources


MindTap activities for Java Programming, Tenth Edition are designed to help students master the skills they need in
today’s workforce. Research shows employers need critical thinkers, troubleshooters, and creative problem-solvers
to stay relevant in our fast-paced, technology-driven world. MindTap helps you achieve this with assignments and
activities that provide hands-on practice and real-life relevance. Students are guided through assignments that help
them master basic knowledge and understanding before moving on to more challenging problems.

All MindTap activities and assignments are tied to defined unit learning objectives. MindTap provides the analytics and
reporting so you can easily see where the class stands in terms of progress, engagement, and completion rates. Use

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xiv Preface

the content and learning path as is or pick and choose how our materials will wrap around yours. You control what
the students see and when they see it. Learn more at http://www.cengage.com/mindtap/.

In addition to the readings, the Java Programming, Tenth Edition MindTap includes the following:

❯❯Gradeable assessments and activities: All assessments and activities from the readings will be available as
gradeable assignments within MindTap, including Review Questions, Game Zone, Case Problems, and Two
Truths & a Lie.
❯❯Videos: Each unit is accompanied by videos that help to explain important unit concepts and provide demos on
how students can apply those concepts.
❯❯Coding Snippets: These short, ungraded coding activities are embedded in the MindTap Reader and provide
students an opportunity to practice new programming concepts “in the moment.” The coding Snippets help
transition the students from conceptual understanding to application of Java code.
❯❯Coding labs: These assignments provide real-world application and encourage students to practice new coding
skills in a complete online IDE. Guided feedback provides personalized and immediate feedback to students as
they proceed through their coding assignments so that they can understand and correct errors in their code.
❯❯Interactive study aids: Flashcards and PowerPoint lectures help users review main concepts from the units.

Instructor and Student Resources


Additional instructor and student resources for this product are available online. Instructor assets include an
Instructor’s Manual, Educator’s Guide, PowerPoint® slides, Solution and Answer Guide, solutions, and a test bank
powered by Cognero®. Student assets include data files. Sign up or sign in at www.cengage.com to search for and access
this product and its online resources.

❯❯Instructor’s Manual: The Instructor’s Manual includes additional instructional material to assist in class
preparation, including sections such as Chapter Objectives, Complete List of Chapter Activities and
Assessments, Key Terms, What’s New In This Chapter, Chapter Outline, Discussion Questions, Suggested Usage
for Lab Activities, Additional Activities and Assignments, and Additional Resources. A sample syllabus also is
available.
❯❯PowerPoint presentations: The PowerPoint slides can be used to guide classroom presentations, to make
available to students for chapter review, or to print as classroom handouts.
❯❯Solution and Answer Guide: Solutions to all end-of-chapter assignments are provided along with feedback.

❯❯Solutions: Solutions to all programming exercises are available. If an input file is needed to run a programming
exercise, it is included with the solution file.
❯❯Test bank: Cengage Testing Powered by Cognero is a flexible, online system that allows you to:
■■ Author, edit, and manage test bank content from multiple Cengage solutions.
■■ Create multiple test versions in an instant.
■■ Deliver tests from your LMS, your classroom, or wherever you want.
❯❯Educator’s Guide: The Educator’s Guide contains a detailed outline of the corresponding MindTap course.

❯❯Transition Guide: The Transition Guide outlines information on what has changed from the Ninth Edition.

❯❯Data files: Data files necessary to complete some of the steps and projects in the course are available. The Data
Files folder includes Java files that are provided for every program that appears in a figure in the text.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xv

About the Author


Joyce Farrell has taught computer programming at McHenry County College, Crystal Lake, Illinois; the University of
Wisconsin, Stevens Point, Wisconsin; and Harper College, Palatine, Illinois. Besides Java, she has written books on
programming logic and design, C#, and C++ for Cengage.

Acknowledgments
I would like to thank all of the people who helped to make this project a reality, including Tran Pham, Associate Product
Manager; Mary Convertino, Learning Designer; Maria Garguilo, Senior Content Manager; Dan Seiter, Developmental
Editor, and John Freitas, Quality Assurance Tester. I am lucky to work with these professionals who are dedicated to
producing high-quality instructional materials.

I am also grateful to the reviewers who provided comments and encouragement during this course’s development,
including Dr. Ross Foultz, Coastal Carolina University; and Dr. Carl M. Rebman, Jr., University of San Diego. Also, thank
you to Charles W. Lively III, Ph.D. – Academic Faculty, Georgia Institute of Technology, who provided the appendix on
JavaFX.

Thanks, too, to my husband, Geoff, for his constant support, advice, and encouragement. Finally, this project is
dedicated to Norman Williams Peterson, who has brought a smile to my face every time I have seen him.

Joyce Farrell

Read This Before You Begin


The following information will help you as you prepare to complete this course.

To the User of the Data Files


To complete the steps and projects in this course, you need data files that have been created specifically for some of
the exercises. Your instructor will provide the data files to you. You also can obtain the files electronically by signing
up or signing in at www.cengage.com and then searching for and accessing this product and its online resources. Note
that you can use a computer in your school lab or your own computer to complete the exercises.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you need the following:

❯❯Software: Java SE 16 or later, available from www.oracle.com/technetwork/java/index.html. Although almost


all of the examples in this course will work with earlier versions of Java, a few require Java 16 or later. You also
need a text editor, such as Notepad. A few exercises ask you to use a browser for research.
❯❯Hardware: For operating system requirements (memory and disk space), see http://java.com/en/download/
help.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xvi Preface

Features
This text focuses on helping students become better programmers and understand Java program development through
a variety of key features. In addition to Chapter Objectives, Summaries, and Key Terms, these useful features will help
students regardless of their learning styles.

You Do It

These sections walk students through program development step by step.

These notes provide additional information—for example, a common error to watch out for or
Note background information on a topic.

Two Truths & a Lie

These quizzes appear after almost every chapter section, with answers provided. Each quiz contains three
statements based on the preceding section of text—two statements are true and one is false.

Answers give immediate feedback without “giving away” answers to the multiple-choice questions and
programming problems later in the chapter. Students also have the option to take these quizzes in MindTap.

Don’t Do It Icon
The Don’t Do It icon illustrates how NOT to do something—for example, having a dead code path in a program. These
icons provide a visual jolt to the student, emphasizing that particular practices are NOT to be emulated and making
students more likely to recognize problems in existing code.

import java.util.Scanner;
public class GetUserInfo2 Don’t Do It
{
public static void main(String[] args) If you accept numeric
{ input prior to string input,
String name; the string input is ignored
int age; unless you take special
Scanner inputDevice = new Scanner(System.in); action.
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface xvii

Don’t Do It
These sections at the end of each chapter list advice for avoiding common programming errors.

Assessment

Review Questions
Review Questions test student comprehension of the major ideas and techniques presented. Twenty questions follow
each chapter.

Programming Exercises
Programming Exercises provide opportunities to practice concepts. These exercises allow students to explore each
major programming concept presented in the chapter. Additional coding labs and snippets are available in MindTap.

Debugging Exercises
Debugging Exercises are included with each chapter because examining programs critically and closely is a crucial
programming skill. Students and instructors can download these exercises at www.cengage.com.

Game Zone
Game Zone exercises are included at the end of each chapter. Students can create games as an additional entertaining
way to understand key programming concepts.

Case Problems
Case Problems provide opportunities to build more detailed programs that continue to incorporate increasing
functionality throughout the course.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1

Creating Java
Programs
Learning Objectives
When you complete this chapter, you will be able to:

1.1 Define basic programming terminology


1.2 Compare procedural and object-oriented programming
1.3 Describe the features of the Java programming language
1.4 Analyze a Java application that produces console output
1.5 Compile a Java class and correct syntax errors
1.6 Run a Java application and correct logic errors
1.7 Add comments to a Java class
1.8 Create a Java application that produces GUI output
1.9 Identify and consult resources to help develop Java programming skills

1.1 Learning Programming Terminology


You see many computers every day. There might be a laptop on your desk, and there also are computers in
your phone, in your car, and perhaps in your thermostat, washing machine, and vacuum cleaner. When you
learn computer terminology and how to program a computer, you learn a bit about how these devices work,
you develop your critical thinking skills, and you learn to communicate more clearly. You will reap all these
benefits as you work through this course.

Computer systems consist of both hardware and software.

❯❯Computer equipment, such as a monitor or keyboard, is hardware.

❯❯Programs are software. A computer program (or simply, program) is a set of instructions that you write
to tell a computer what to do.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
2 Chapter 1 Creating Java Programs

Software can be divided into two broad categories:

❯❯A program that performs a task for a user (such as calculating and producing paychecks, word processing, or
playing a game) is application software. Programs that are application software are called applications, or apps
for short.
❯❯A program that manages the computer itself (such as Windows or Linux) is system software.

The logic behind any computer program, whether it is an application or system program, determines the exact order of
instructions needed to produce desired results. Much of this course describes how to develop the logic for application
software.

You can write computer programs in high- or low-level programming languages:

❯❯A high-level programming language such as Java, Visual Basic, C++, or C# allows you to use English-like, easy-
to-remember terms such as read, write, and add.
❯❯A low-level programming language corresponds closely to a computer’s circuitry and is not as easily read or
understood. Because they correspond to circuitry, low-level languages must be customized for every type of
machine on which a program runs.

All computer programs, even high-level language programs, ultimately are converted to the lowest-level language,
which is machine language. Machine language, or machine code, is the most basic set of instructions that a computer
can execute. Each type of processor (the internal hardware that handles computer instructions) has its own set of
machine language instructions. Programmers often describe machine language using 1s and 0s to represent the on-
and-off circuitry of computer systems.

The system that uses only 1s and 0s is the binary numbering system. Appendix B describes the binary
Note system in detail. Later in this chapter, you will learn that bytecode is the name for the binary code created
when Java programs are converted to machine language.

Every programming language has its own syntax, or rules about how language elements are combined correctly to
produce usable statements. For example, depending on the specific high-level language, you might use the verb print
or write to produce output. All languages have a specific, limited vocabulary (the language’s keywords) and a specific
set of rules for using that vocabulary. When you are learning a computer programming language, such as Java, C++, or
Visual Basic, you are learning the vocabulary and syntax for that language.

Using a programming language, programmers write a series of program statements, which are similar to English
sentences. The statements carry out the program’s tasks. Program statements are also known as commands because
they are orders to the computer, such as Output this word or Add these two numbers.

After the program statements are written in a high-level programming language, a computer program called a compiler
or interpreter translates the statements into machine language. A compiler translates an entire program before carrying
out any statements, or executing them, whereas an interpreter translates one program statement at a time, executing
a statement as soon as it is translated.

Whether you use a compiler or interpreter often depends on the programming language you use.
Note For example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of
translator has its supporters; programs written in compiled languages execute more quickly, whereas
programs written in interpreted languages can be easier to develop and debug. Java uses the best of
both technologies: a compiler to translate your programming statements and an interpreter to read the
compiled code line by line when the program executes (also called at run time).

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.1 Learning Programming Terminology 3

Compilers and interpreters issue one or more error messages each time they encounter an invalid program statement—
that is, a statement containing a syntax error, or misuse of the language. Examples of syntax errors include misspelling
a keyword or omitting a word that a statement requires. When a syntax error is detected, the programmer can correct
the error and attempt another translation. Repairing all syntax errors is the first part of the process of debugging a
program—freeing the program of all flaws or errors, also known as bugs. Figure 1-1 illustrates the steps a programmer
takes while developing an executable program. You will learn more about debugging Java programs later in this chapter.

Figure 1-1 The program development process

Plan program logic

Write program language statements


that correspond to the logic

Debugging process
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language

Debugging process
Can all statements No Examine list of
be successfully
syntax errors
translated?

Yes

Execute the program

Examine
program output

Are there runtime Yes


or output errors?

No

As Figure 1-1 shows, you might write a program that compiles successfully (that is, it contains no syntax errors), but
it still might not be a correct program because it might contain one or more logic errors. A logic error is a bug that
allows a program to run, but that causes it to operate incorrectly. Correct logic requires that all the right commands
be issued in the appropriate order. Examples of logic errors include multiplying two values when you meant to divide
them or producing output prior to obtaining the appropriate input. When you develop a program of any significant
size, you should plan its logic before you write any program statements.
Correcting logic errors is much more difficult than correcting syntax errors. Syntax errors are discovered by the
language translator when you compile a program, but a program can be free of syntax errors and execute while still

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
4 Chapter 1 Creating Java Programs

retaining logic errors. Sometimes you can find logic errors by carefully examining the structure of your program (when
a group of programmers do this together, it is called a structured walkthrough), but sometimes you can identify logic
errors only when you examine a program’s output. For example, if you know an employee’s paycheck should contain
the value $4,000, but when you examine a payroll program’s output you see that it holds $40, then a logic error has
occurred. Perhaps an incorrect calculation was performed, or maybe the hours-worked value was output by mistake
instead of the net pay value. When output is incorrect, the programmer must carefully examine all the statements
within the program, revise or move the offending statements, and translate and test the program again.

Just because a program produces correct output does not mean it is free from logic errors. For example,
Note suppose that a program should multiply two values entered by the user, that the user enters two 2s, and
that the output is 4. The program might actually be adding the values by mistake. The programmer would
discover the logic error only by entering different values, such as 5 and 7, and examining the result.

Programmers call some logic errors semantic errors. For example, if you misspell a programming
Note language word, you commit a syntax error, but if you use a correct word in the wrong context, you
commit a semantic error.

Two Truths & a Lie  Learning Programming Terminology

In each “Two Truths & a Lie” section, two of the numbered statements are true, and one is false. Identify the false
statement and explain why it is false.

1. Unlike a low-level programming language, a high-level programming language allows you to use
a vocabulary of reasonable terms instead of the sequences of on-and-off switches that perform the
corresponding tasks.

2. A syntax error occurs when you violate the rules of a language; locating and repairing all syntax errors is
part of the process of debugging a program.

3. Logic errors are fairly easy to find because the software that translates a program finds all the logic errors for you.

The false statement is #3. A language translator finds syntax errors, but logic errors can still exist in a program that
is free of syntax errors.

1.2 C
 omparing Procedural and Object-Oriented
Programming Concepts
All computer programmers must deal with syntax errors and logical errors in much the same way, but they might take
different approaches to the entire programming process. Procedural programming and object-oriented programming
describe two different approaches to writing computer programs.

Procedural Programming
Procedural programming is a style of programming in which operations are executed one after another in sequence.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.2 Comparing Procedural and Object-Oriented Programming Concepts 5

The typical procedural program defines and uses named computer memory locations; each of these named locations
that can hold data is called a variable. For example, data might be read from an input device and stored in a location
the programmer has named rateOfPay. The variable value might be used in an arithmetic statement, used as the
basis for a decision, sent to an output device, or have other operations performed with it. The data stored in a variable
can change, or vary, during a program’s execution.

For convenience, the individual operations used in a computer program are often grouped into logical units called
procedures. For example, a series of four or five comparisons and calculations that together determine a person’s
federal withholding tax value might be grouped as a procedure named calculateFederalWithholding(). (As a
convention, this course will show parentheses following every procedure name.) As a procedural program executes
its statements, it can sometimes pause to call a procedure. When a program calls a procedure, the current logic is
temporarily suspended so that the procedure’s commands can execute. A single procedural program might contain any
number of procedure calls. Procedures are also called modules, methods, functions, and subroutines. Users of different
programming languages tend to use different terms. As you will learn later in this chapter, Java programmers most
frequently use the term method.

Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you take a slightly different approach
to writing computer programs. Writing object-oriented programs involves the following:

❯❯Creating classes, which are blueprints for objects

❯❯Creating objects, which are specific instances of those classes

❯❯Creating applications that manipulate or use those objects

Programmers use OO as an abbreviation for object-oriented; it is pronounced oh oh. Object-oriented


Note programming is abbreviated OOP, and pronounced to rhyme with soup.

Originally, object-oriented programming was used most frequently for two major types of applications:

❯❯Computer simulations, which attempt to mimic real-world activities so that their processes can be improved or
so that users can better understand how the real-world processes operate
❯❯Graphical user interfaces (GUIs), pronounced gooeys, which allow users to interact with a program in a graphical
environment

Thinking about objects in these two types of applications makes sense. For example, a city might want to develop a
program that simulates traffic patterns and controls traffic signals to help prevent tie-ups. Programmers would create
classes for objects such as cars and pedestrians that contain their own data and rules for behavior. For example, each
car has a speed and a method for changing that speed. The specific instances of cars could be set in motion to create
a simulation of a real city at rush hour.

Creating a GUI environment for users is also a natural use for object orientation. It is easy to think of the components
a user manipulates on a computer screen, such as buttons and scroll bars, as similar to real-world objects. Each
GUI object contains data—for example, a button on a screen has a specific size and color. Each object also contains
­behaviors—for example, each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but object-oriented programming
means more. Although many GUI programs are object oriented, not all object-oriented programs use GUI objects.
Modern businesses use object-oriented design techniques when developing all sorts of business applications, whether
they are GUI applications or not. Early in this course, you will learn object-oriented techniques that are appropriate
for any program type; in the last chapters, you will apply what you have learned about those techniques specifically
to GUI applications.

Copyright 2023 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Other documents randomly have
different content
been hoisted, and pushed, and pulled, into their respective saddles.
'Hi-hi-hi!' groaned the other boy behind Mr. Cymon Tuggs. Away
went the donkey, with the stirrups jingling against the heels of
Cymon's boots, and Cymon's boots nearly scraping the ground.
'Way-way! Wo-o-o-!' cried Mr. Cymon Tuggs as well as he could, in
the midst of the jolting.
'Don't make it gallop!' screamed Mrs. Captain Waters, behind.
'My donkey will go into the public-house!' shrieked Miss Tuggs in
the rear.
'Hi-hi-hi!' groaned both the boys together; and on went the
donkeys as if nothing would ever stop them.
Everything has an end, however; even the galloping of donkeys
will cease in time. The animal which Mr. Cymon Tuggs bestrode,
feeling sundry uncomfortable tugs at the bit, the intent of which he
could by no means divine, abruptly sidled against a brick wall, and
expressed his uneasiness by grinding Mr. Cymon Tuggs's leg on the
rough surface. Mrs. Captain Waters's donkey, apparently under the
influence of some playfulness of spirit, rushed suddenly, head first,
into a hedge, and declined to come out again: and the quadruped
on which Miss Tuggs was mounted, expressed his delight at this
humorous proceeding by firmly planting his fore-feet against the
ground, and kicking up his hind-legs in a very agile, but somewhat
alarming manner.
This abrupt termination to the rapidity of the ride, naturally
occasioned some confusion. Both the ladies indulged in vehement
screaming for several minutes; and Mr. Cymon Tuggs, besides
sustaining intense bodily pain, had the additional mental anguish of
witnessing their distressing situation, without having the power to
rescue them, by reason of his leg being firmly screwed in between
the animal and the wall. The efforts of the boys, however, assisted
by the ingenious expedient of twisting the tail of the most rebellious
donkey, restored order in a much shorter time than could have
reasonably been expected, and the little party jogged slowly on
together.
'Now let 'em walk,' said Mr. Cymon Tuggs. 'It's cruel to overdrive
'em.'
'Werry well, sir,' replied the boy, with a grin at his companion, as if
he understood Mr. Cymon to mean that the cruelty applied less to
the animals than to their riders.
'What a lovely day, dear!' said Charlotta.
'Charming; enchanting, dear!' responded Mrs. Captain Waters.
'What a beautiful prospect, Mr. Tuggs!'
Cymon looked full in Belinda's face, as he responded-'Beautiful,
indeed!' The lady cast down her eyes, and suffered the animal she
was riding to fall a little back. Cymon Tuggs instinctively did the
same.
There was a brief silence, broken only by a sigh from Mr. Cymon
Tuggs.
'Mr. Cymon,' said the lady suddenly, in a low tone, 'Mr. Cymon-I
am another's.'
Mr. Cymon expressed his perfect concurrence in a statement which
it was impossible to controvert.
'If I had not been-' resumed Belinda; and there she stopped.
'What-what?' said Mr. Cymon earnestly. 'Do not torture me. What
would you say?'
'If I had not been'-continued Mrs. Captain Waters-'if, in earlier life,
it had been my fate to have known, and been beloved by, a noble
youth-a kindred soul-a congenial spirit-one capable of feeling and
appreciating the sentiments which-'
'Heavens! what do I hear?' exclaimed Mr. Cymon Tuggs. 'Is it
possible! can I believe my-Come up!' (This last unsentimental
parenthesis was addressed to the donkey, who, with his head
between his fore-legs, appeared to be examining the state of his
shoes with great anxiety.)
'Hi-hi-hi,' said the boys behind. 'Come up,' expostulated Cymon
Tuggs again. 'Hi-hi-hi,' repeated the boys. And whether it was that
the animal felt indignant at the tone of Mr. Tuggs's command, or felt
alarmed by the noise of the deputy proprietor's boots running behind
him; or whether he burned with a noble emulation to outstrip the
other donkeys; certain it is that he no sooner heard the second
series of 'hi-hi's,' than he started away, with a celerity of pace which
jerked Mr. Cymon's hat off, instantaneously, and carried him to the
Pegwell Bay hotel in no time, where he deposited his rider without
giving him the trouble of dismounting, by sagaciously pitching him
over his head, into the very doorway of the tavern.
Great was the confusion of Mr. Cymon Tuggs, when he was put
right end uppermost, by two waiters; considerable was the alarm of
Mrs. Tuggs in behalf of her son; agonizing were the apprehensions
of Mrs. Captain Waters on his account. It was speedily discovered,
however, that he had not sustained much more injury than the
donkey-he was grazed, and the animal was grazing-and then it was
a delightful party to be sure! Mr. and Mrs. Tuggs, and the captain,
had ordered lunch in the little garden behind:-small saucers of large
shrimps, dabs of butter, crusty loaves, and bottled ale. The sky was
without a cloud; there were flower-pots and turf before them; the
sea, from the foot of the cliff, stretching away as far as the eye could
discern anything at all; vessels in the distance with sails as white,
and as small, as nicely-got-up cambric handkerchiefs. The shrimps
were delightful, the ale better, and the captain even more pleasant
than either. Mrs. Captain Waters was in such spirits after lunch!-
chasing, first the captain across the turf, and among the flower-pots;
and then Mr. Cymon Tuggs; and then Miss Tuggs; and laughing, too,
quite boisterously. But as the captain said, it didn't matter; who
knew what they were, there? For all the people of the house knew,
they might be common people. To which Mr. Joseph Tuggs
responded, 'To be sure.' And then they went down the steep wooden
steps a little further on, which led to the bottom of the cliff; and
looked at the crabs, and the seaweed, and the eels, till it was more
than fully time to go back to Ramsgate again. Finally, Mr. Cymon
Tuggs ascended the steps last, and Mrs. Captain Waters last but
one; and Mr. Cymon Tuggs discovered that the foot and ankle of
Mrs. Captain Waters, were even more unexceptionable than he had
at first supposed.
Taking a donkey towards his ordinary place of residence, is a very
different thing, and a feat much more easily to be accomplished,
than taking him from it. It requires a great deal of foresight and
presence of mind in the one case, to anticipate the numerous flights
of his discursive imagination; whereas, in the other, all you have to
do, is, to hold on, and place a blind confidence in the animal. Mr.
Cymon Tuggs adopted the latter expedient on his return; and his
nerves were so little discomposed by the journey, that he distinctly
understood they were all to meet again at the library in the evening.
The library was crowded. There were the same ladies, and the
same gentlemen, who had been on the sands in the morning, and
on the pier the day before. There were young ladies, in maroon-
coloured gowns and black velvet bracelets, dispensing fancy articles
in the shop, and presiding over games of chance in the concert-
room. There were marriageable daughters, and marriage-making
mammas, gaming and promenading, and turning over music, and
flirting. There were some male beaux doing the sentimental in
whispers, and others doing the ferocious in moustache. There were
Mrs. Tuggs in amber, Miss Tuggs in sky-blue, Mrs. Captain Waters in
pink. There was Captain Waters in a braided surtout; there was Mr.
Cymon Tuggs in pumps and a gilt waistcoat; there was Mr. Joseph
Tuggs in a blue coat and a shirt-frill.
'Numbers three, eight, and eleven!' cried one of the young ladies
in the maroon-coloured gowns.
'Numbers three, eight, and eleven!' echoed another young lady in
the same uniform.
'Number three's gone,' said the first young lady. 'Numbers eight
and eleven!'
'Numbers eight and eleven!' echoed the second young lady.
'Number eight's gone, Mary Ann,' said the first young lady.
'Number eleven!' screamed the second.
'The numbers are all taken now, ladies, if you please,' said the
first. The representatives of numbers three, eight, and eleven, and
the rest of the numbers, crowded round the table.
'Will you throw, ma'am?' said the presiding goddess, handing the
dice- box to the eldest daughter of a stout lady, with four girls.
There was a profound silence among the lookers-on.
'Throw, Jane, my dear,' said the stout lady. An interesting display
of bashfulness-a little blushing in a cambric handkerchief-a
whispering to a younger sister.
'Amelia, my dear, throw for your sister,' said the stout lady; and
then she turned to a walking advertisement of Rowlands' Macassar
Oil, who stood next her, and said, 'Jane is so very modest and
retiring; but I can't be angry with her for it. An artless and
unsophisticated girl is so truly amiable, that I often wish Amelia was
more like her sister!'
The gentleman with the whiskers whispered his admiring approval.
'Now, my dear!' said the stout lady. Miss Amelia threw-eight for
her sister, ten for herself.
'Nice figure, Amelia,' whispered the stout lady to a thin youth
beside her.
'Beautiful!'
'And such a spirit! I am like you in that respect. I can not help
admiring that life and vivacity. Ah! (a sigh) I wish I could make poor
Jane a little more like my dear Amelia!'
The young gentleman cordially acquiesced in the sentiment; both
he, and the individual first addressed, were perfectly contented.
'Who's this?' inquired Mr. Cymon Tuggs of Mrs. Captain Waters, as
a short female, in a blue velvet hat and feathers, was led into the
orchestra, by a fat man in black tights and cloudy Berlins.
'Mrs. Tippin, of the London theatres,' replied Belinda, referring to
the programme of the concert.
The talented Tippin having condescendingly acknowledged the
clapping of hands, and shouts of 'bravo!' which greeted her
appearance, proceeded to sing the popular cavatina of 'Bid me
discourse,' accompanied on the piano by Mr. Tippin; after which, Mr.
Tippin sang a comic song, accompanied on the piano by Mrs. Tippin:
the applause consequent upon which, was only to be exceeded by
the enthusiastic approbation bestowed upon an air with variations on
the guitar, by Miss Tippin, accompanied on the chin by Master
Tippin.
Thus passed the evening; thus passed the days and evenings of
the Tuggses, and the Waterses, for six weeks. Sands in the morning-
donkeys at noon-pier in the afternoon-library at night-and the same
people everywhere.
On that very night six weeks, the moon was shining brightly over
the calm sea, which dashed against the feet of the tall gaunt cliffs,
with just enough noise to lull the old fish to sleep, without disturbing
the young ones, when two figures were discernible-or would have
been, if anybody had looked for them-seated on one of the wooden
benches which are stationed near the verge of the western cliff. The
moon had climbed higher into the heavens, by two hours'
journeying, since those figures first sat down-and yet they had
moved not. The crowd of loungers had thinned and dispersed; the
noise of itinerant musicians had died away; light after light had
appeared in the windows of the different houses in the distance;
blockade-man after blockade-man had passed the spot, wending his
way towards his solitary post; and yet those figures had remained
stationary. Some portions of the two forms were in deep shadow,
but the light of the moon fell strongly on a puce-coloured boot and a
glazed stock. Mr. Cymon Tuggs and Mrs. Captain Waters were seated
on that bench. They spoke not, but were silently gazing on the sea.
'Walter will return to-morrow,' said Mrs. Captain Waters,
mournfully breaking silence.
Mr. Cymon Tuggs sighed like a gust of wind through a forest of
gooseberry bushes, as he replied, 'Alas! he will.'
'Oh, Cymon!' resumed Belinda, 'the chaste delight, the calm
happiness, of this one week of Platonic love, is too much for me!'
Cymon was about to suggest that it was too little for him, but he
stopped himself, and murmured unintelligibly.
'And to think that even this gleam of happiness, innocent as it is,'
exclaimed Belinda, 'is now to be lost for ever!'
'Oh, do not say for ever, Belinda,' exclaimed the excitable Cymon,
as two strongly-defined tears chased each other down his pale face-
it was so long that there was plenty of room for a chase. 'Do not say
for ever!'
'I must,' replied Belinda.
'Why?' urged Cymon, 'oh why? Such Platonic acquaintance as ours
is so harmless, that even your husband can never object to it.'
'My husband!' exclaimed Belinda. 'You little know him. Jealous and
revengeful; ferocious in his revenge-a maniac in his jealousy! Would
you be assassinated before my eyes?' Mr. Cymon Tuggs, in a voice
broken by emotion, expressed his disinclination to undergo the
process of assassination before the eyes of anybody.
'Then leave me,' said Mrs. Captain Waters. 'Leave me, this night,
for ever. It is late: let us return.'
Mr. Cymon Tuggs sadly offered the lady his arm, and escorted her
to her lodgings. He paused at the door-he felt a Platonic pressure of
his hand. 'Good night,' he said, hesitating.
'Good night,' sobbed the lady. Mr. Cymon Tuggs paused again.
'Won't you walk in, sir?' said the servant. Mr. Tuggs hesitated. Oh,
that hesitation! He did walk in.
'Good night!' said Mr. Cymon Tuggs again, when he reached the
drawing- room.
'Good night!' replied Belinda; 'and, if at any period of my life, I-
Hush!' The lady paused and stared with a steady gaze of horror, on
the ashy countenance of Mr. Cymon Tuggs. There was a double
knock at the street-door.
'It is my husband!' said Belinda, as the captain's voice was heard
below.
'And my family!' added Cymon Tuggs, as the voices of his relatives
floated up the staircase.
'The curtain! The curtain!' gasped Mrs. Captain Waters, pointing to
the window, before which some chintz hangings were closely drawn.
'But I have done nothing wrong,' said the hesitating Cymon.
'The curtain!' reiterated the frantic lady: 'you will be murdered.'
This last appeal to his feelings was irresistible. The dismayed Cymon
concealed himself behind the curtain with pantomimic suddenness.
Enter the captain, Joseph Tuggs, Mrs. Tuggs, and Charlotta.
'My dear,' said the captain, 'Lieutenant, Slaughter.' Two iron-shod
boots and one gruff voice were heard by Mr. Cymon to advance, and
acknowledge the honour of the introduction. The sabre of the
lieutenant rattled heavily upon the floor, as he seated himself at the
table. Mr. Cymon's fears almost overcame his reason.
'The brandy, my dear!' said the captain. Here was a situation!
They were going to make a night of it! And Mr. Cymon Tuggs was
pent up behind the curtain and afraid to breathe!
'Slaughter,' said the captain, 'a cigar?'
Now, Mr. Cymon Tuggs never could smoke without feeling it
indispensably necessary to retire, immediately, and never could smell
smoke without a strong disposition to cough. The cigars were
introduced; the captain was a professed smoker; so was the
lieutenant; so was Joseph Tuggs. The apartment was small, the door
was closed, the smoke powerful: it hung in heavy wreaths over the
room, and at length found its way behind the curtain. Cymon Tuggs
held his nose, his mouth, his breath. It was all of no use-out came
the cough.
'Bless my soul!' said the captain, 'I beg your pardon, Miss Tuggs.
You dislike smoking?'
'Oh, no; I don't indeed,' said Charlotta.
'It makes you cough.'
'Oh dear no.'
'You coughed just now.'
'Me, Captain Waters! Lor! how can you say so?'
'Somebody coughed,' said the captain.
'I certainly thought so,' said Slaughter. No; everybody denied it.
'Fancy,' said the captain.
'Must be,' echoed Slaughter.
Cigars resumed-more smoke-another cough-smothered, but
violent.
'Damned odd!' said the captain, staring about him.
'Sing'ler!' ejaculated the unconscious Mr. Joseph Tuggs.
Lieutenant Slaughter looked first at one person mysteriously, then
at another: then, laid down his cigar, then approached the window
on tiptoe, and pointed with his right thumb over his shoulder, in the
direction of the curtain.
'Slaughter!' ejaculated the captain, rising from table, 'what do you
mean?'
The lieutenant, in reply, drew back the curtain and discovered Mr.
Cymon Tuggs behind it: pallid with apprehension, and blue with
wanting to cough.
'Aha!' exclaimed the captain, furiously. 'What do I see? Slaughter,
your sabre!'
'Cymon!' screamed the Tuggses.
'Mercy!' said Belinda.
'Platonic!' gasped Cymon.
'Your sabre!' roared the captain: 'Slaughter-unhand me-the villain's
life!'
'Murder!' screamed the Tuggses.
'Hold him fast, sir!' faintly articulated Cymon.
'Water!' exclaimed Joseph Tuggs-and Mr. Cymon Tuggs and all the
ladies forthwith fainted away, and formed a tableau.
Most willingly would we conceal the disastrous termination of the
six weeks' acquaintance. A troublesome form, and an arbitrary
custom, however, prescribe that a story should have a conclusion, in
addition to a commencement; we have therefore no alternative.
Lieutenant Slaughter brought a message-the captain brought an
action. Mr. Joseph Tuggs interposed-the lieutenant negotiated. When
Mr. Cymon Tuggs recovered from the nervous disorder into which
misplaced affection, and exciting circumstances, had plunged him,
he found that his family had lost their pleasant acquaintance; that
his father was minus fifteen hundred pounds; and the captain plus
the precise sum. The money was paid to hush the matter up, but it
got abroad notwithstanding; and there are not wanting some who
affirm that three designing impostors never found more easy dupes,
than did Captain Waters, Mrs. Waters, and Lieutenant Slaughter, in
the Tuggses at Ramsgate.
CHAPTER V-HORATIO SPARKINS
'Indeed, my love, he paid Teresa very great attention on the last
assembly night,' said Mrs. Malderton, addressing her spouse, who,
after the fatigues of the day in the City, was sitting with a silk
handkerchief over his head, and his feet on the fender, drinking his
port;-'very great attention; and I say again, every possible
encouragement ought to be given him. He positively must be asked
down here to dine.'
'Who must?' inquired Mr. Malderton.
'Why, you know whom I mean, my dear-the young man with the
black whiskers and the white cravat, who has just come out at our
assembly, and whom all the girls are talking about. Young-dear me!
what's his name?-Marianne, what is his name?' continued Mrs.
Malderton, addressing her youngest daughter, who was engaged in
netting a purse, and looking sentimental.
'Mr. Horatio Sparkins, ma,' replied Miss Marianne, with a sigh.
'Oh! yes, to be sure-Horatio Sparkins,' said Mrs. Malderton.
'Decidedly the most gentleman-like young man I ever saw. I am sure
in the beautifully-made coat he wore the other night, he looked like-
like-'
'Like Prince Leopold, ma-so noble, so full of sentiment!' suggested
Marianne, in a tone of enthusiastic admiration.
'You should recollect, my dear,' resumed Mrs. Malderton, 'that
Teresa is now eight-and-twenty; and that it really is very important
that something should be done.'
Miss Teresa Malderton was a very little girl, rather fat, with
vermilion cheeks, but good-humoured, and still disengaged,
although, to do her justice, the misfortune arose from no lack of
perseverance on her part. In vain had she flirted for ten years; in
vain had Mr. and Mrs. Malderton assiduously kept up an extensive
acquaintance among the young eligible bachelors of Camberwell,
and even of Wandsworth and Brixton; to say nothing of those who
'dropped in' from town. Miss Malderton was as well known as the
lion on the top of Northumberland House, and had an equal chance
of 'going off.'
'I am quite sure you'd like him,' continued Mrs. Malderton, 'he is
so gentlemanly!'
'So clever!' said Miss Marianne.
'And has such a flow of language!' added Miss Teresa.
'He has a great respect for you, my dear,' said Mrs. Malderton to
her husband. Mr. Malderton coughed, and looked at the fire.
'Yes I'm sure he's very much attached to pa's society,' said Miss
Marianne.
'No doubt of it,' echoed Miss Teresa.
'Indeed, he said as much to me in confidence,' observed Mrs.
Malderton.
'Well, well,' returned Mr. Malderton, somewhat flattered; 'if I see
him at the assembly to-morrow, perhaps I'll ask him down. I hope
he knows we live at Oak Lodge, Camberwell, my dear?'
'Of course-and that you keep a one-horse carriage.'
'I'll see about it,' said Mr. Malderton, composing himself for a nap;
'I'll see about it.'
Mr. Malderton was a man whose whole scope of ideas was limited
to Lloyd's, the Exchange, the India House, and the Bank. A few
successful speculations had raised him from a situation of obscurity
and comparative poverty, to a state of affluence. As frequently
happens in such cases, the ideas of himself and his family became
elevated to an extraordinary pitch as their means increased; they
affected fashion, taste, and many other fooleries, in imitation of their
betters, and had a very decided and becoming horror of anything
which could, by possibility, be considered low. He was hospitable
from ostentation, illiberal from ignorance, and prejudiced from
conceit. Egotism and the love of display induced him to keep an
excellent table: convenience, and a love of good things of this life,
ensured him plenty of guests. He liked to have clever men, or what
he considered such, at his table, because it was a great thing to talk
about; but he never could endure what he called 'sharp fellows.'
Probably, he cherished this feeling out of compliment to his two
sons, who gave their respected parent no uneasiness in that
particular. The family were ambitious of forming acquaintances and
connexions in some sphere of society superior to that in which they
themselves moved; and one of the necessary consequences of this
desire, added to their utter ignorance of the world beyond their own
small circle, was, that any one who could lay claim to an
acquaintance with people of rank and title, had a sure passport to
the table at Oak Lodge, Camberwell.
The appearance of Mr. Horatio Sparkins at the assembly, had
excited no small degree of surprise and curiosity among its regular
frequenters. Who could he be? He was evidently reserved, and
apparently melancholy. Was he a clergyman?-He danced too well. A
barrister?-He said he was not called. He used very fine words, and
talked a great deal. Could he be a distinguished foreigner, come to
England for the purpose of describing the country, its manners and
customs; and frequenting public balls and public dinners, with the
view of becoming acquainted with high life, polished etiquette, and
English refinement?-No, he had not a foreign accent. Was he a
surgeon, a contributor to the magazines, a writer of fashionable
novels, or an artist?-No; to each and all of these surmises, there
existed some valid objection.-'Then,' said everybody, 'he must be
somebody.'-'I should think he must be,' reasoned Mr. Malderton,
within himself, 'because he perceives our superiority, and pays us so
much attention.'
The night succeeding the conversation we have just recorded, was
'assembly night.' The double-fly was ordered to be at the door of
Oak Lodge at nine o'clock precisely. The Miss Maldertons were
dressed in sky-blue satin trimmed with artificial flowers; and Mrs. M.
(who was a little fat woman), in ditto ditto, looked like her eldest
daughter multiplied by two. Mr. Frederick Malderton, the eldest son,
in full- dress costume, was the very beau idACal of a smart waiter;
and Mr. Thomas Malderton, the youngest, with his white dress-stock,
blue coat, bright buttons, and red watch-ribbon, strongly resembled
the portrait of that interesting, but rash young gentleman, George
Barnwell. Every member of the party had made up his or her mind
to cultivate the acquaintance of Mr. Horatio Sparkins. Miss Teresa, of
course, was to be as amiable and interesting as ladies of eight-and-
twenty on the look-out for a husband, usually are. Mrs. Malderton
would be all smiles and graces. Miss Marianne would request the
favour of some verses for her album. Mr. Malderton would patronise
the great unknown by asking him to dinner. Tom intended to
ascertain the extent of his information on the interesting topics of
snuff and cigars. Even Mr. Frederick Malderton himself, the family
authority on all points of taste, dress, and fashionable arrangement;
who had lodgings of his own in town; who had a free admission to
Covent-garden theatre; who always dressed according to the
fashions of the months; who went up the water twice a-week in the
season; and who actually had an intimate friend who once knew a
gentleman who formerly lived in the Albany,-even he had
determined that Mr. Horatio Sparkins must be a devilish good fellow,
and that he would do him the honour of challenging him to a game
at billiards.
The first object that met the anxious eyes of the expectant family
on their entrance into the ball-room, was the interesting Horatio,
with his hair brushed off his forehead, and his eyes fixed on the
ceiling, reclining in a contemplative attitude on one of the seats.
'There he is, my dear,' whispered Mrs. Malderton to Mr. Malderton.
'How like Lord Byron!' murmured Miss Teresa.
'Or Montgomery!' whispered Miss Marianne.
'Or the portraits of Captain Cook!' suggested Tom.
'Tom-don't be an ass!' said his father, who checked him on all
occasions, probably with a view to prevent his becoming 'sharp'-
which was very unnecessary.
The elegant Sparkins attitudinised with admirable effect, until the
family had crossed the room. He then started up, with the most
natural appearance of surprise and delight; accosted Mrs. Malderton
with the utmost cordiality; saluted the young ladies in the most
enchanting manner; bowed to, and shook hands with Mr. Malderton,
with a degree of respect amounting almost to veneration; and
returned the greetings of the two young men in a half-gratified, half-
patronising manner, which fully convinced them that he must be an
important, and, at the same time, condescending personage.
'Miss Malderton,' said Horatio, after the ordinary salutations, and
bowing very low, 'may I be permitted to presume to hope that you
will allow me to have the pleasure-'
'I don't think I am engaged,' said Miss Teresa, with a dreadful
affectation of indifference-'but, really-so many-'
Horatio looked handsomely miserable.
'I shall be most happy,' simpered the interesting Teresa, at last.
Horatio's countenance brightened up, like an old hat in a shower of
rain.
'A very genteel young man, certainly!' said the gratified Mr.
Malderton, as the obsequious Sparkins and his partner joined the
quadrille which was just forming.
'He has a remarkably good address,' said Mr. Frederick.
'Yes, he is a prime fellow,' interposed Tom, who always managed
to put his foot in it-'he talks just like an auctioneer.'
'Tom!' said his father solemnly, 'I think I desired you, before, not
to be a fool.' Tom looked as happy as a cock on a drizzly morning.
'How delightful!' said the interesting Horatio to his partner, as they
promenaded the room at the conclusion of the set-'how delightful,
how refreshing it is, to retire from the cloudy storms, the
vicissitudes, and the troubles, of life, even if it be but for a few short
fleeting moments: and to spend those moments, fading and
evanescent though they be, in the delightful, the blessed society of
one individual-whose frowns would be death, whose coldness would
be madness, whose falsehood would be ruin, whose constancy
would be bliss; the possession of whose affection would be the
brightest and best reward that Heaven could bestow on man?'
'What feeling! what sentiment!' thought Miss Teresa, as she
leaned more heavily on her companion's arm.
'But enough-enough!' resumed the elegant Sparkins, with a
theatrical air. 'What have I said? what have I-I-to do with sentiments
like these! Miss Malderton'-here he stopped short-'may I hope to be
permitted to offer the humble tribute of-'
'Really, Mr. Sparkins,' returned the enraptured Teresa, blushing in
the sweetest confusion, 'I must refer you to papa. I never can,
without his consent, venture to-'
'Surely he cannot object-'
'Oh, yes. Indeed, indeed, you know him not!' interrupted Miss
Teresa, well knowing there was nothing to fear, but wishing to make
the interview resemble a scene in some romantic novel.
'He cannot object to my offering you a glass of negus,' returned
the adorable Sparkins, with some surprise.
'Is that all?' thought the disappointed Teresa. 'What a fuss about
nothing!'
'It will give me the greatest pleasure, sir, to see you to dinner at
Oak Lodge, Camberwell, on Sunday next at five o'clock, if you have
no better engagement,' said Mr. Malderton, at the conclusion of the
evening, as he and his sons were standing in conversation with Mr.
Horatio Sparkins.
Horatio bowed his acknowledgments, and accepted the flattering
invitation.
'I must confess,' continued the father, offering his snuff-box to his
new acquaintance, 'that I don't enjoy these assemblies half so much
as the comfort-I had almost said the luxury-of Oak Lodge. They have
no great charms for an elderly man.'
'And after all, sir, what is man?' said the metaphysical Sparkins. 'I
say, what is man?'
'Ah! very true,' said Mr. Malderton; 'very true.'
'We know that we live and breathe,' continued Horatio; 'that we
have wants and wishes, desires and appetites-'
'Certainly,' said Mr. Frederick Malderton, looking profound.
'I say, we know that we exist,' repeated Horatio, raising his voice,
'but there we stop; there, is an end to our knowledge; there, is the
summit of our attainments; there, is the termination of our ends.
What more do we know?'
'Nothing,' replied Mr. Frederick-than whom no one was more
capable of answering for himself in that particular. Tom was about to
hazard something, but, fortunately for his reputation, he caught his
father's angry eye, and slunk off like a puppy convicted of petty
larceny.
'Upon my word,' said Mr. Malderton the elder, as they were
returning home in the fly, 'that Mr. Sparkins is a wonderful young
man. Such surprising knowledge! such extraordinary information!
and such a splendid mode of expressing himself!'
'I think he must be somebody in disguise,' said Miss Marianne.
'How charmingly romantic!'
'He talks very loud and nicely,' timidly observed Tom, 'but I don't
exactly understand what he means.'
'I almost begin to despair of your understanding anything, Tom,'
said his father, who, of course, had been much enlightened by Mr.
Horatio Sparkins's conversation.
'It strikes me, Tom,' said Miss Teresa, 'that you have made
yourself very ridiculous this evening.'
'No doubt of it,' cried everybody-and the unfortunate Tom reduced
himself into the least possible space. That night, Mr. and Mrs.
Malderton had a long conversation respecting their daughter's
prospects and future arrangements. Miss Teresa went to bed,
considering whether, in the event of her marrying a title, she could
conscientiously encourage the visits of her present associates; and
dreamed, all night, of disguised noblemen, large routs, ostrich
plumes, bridal favours, and Horatio Sparkins.
Various surmises were hazarded on the Sunday morning, as to the
mode of conveyance which the anxiously-expected Horatio would
adopt. Did he keep a gig?-was it possible he could come on
horseback?-or would he patronize the stage? These, and other
various conjectures of equal importance, engrossed the attention of
Mrs. Malderton and her daughters during the whole morning after
church.
'Upon my word, my dear, it's a most annoying thing that that
vulgar brother of yours should have invited himself to dine here to-
day,' said Mr. Malderton to his wife. 'On account of Mr. Sparkins's
coming down, I purposely abstained from asking any one but
Flamwell. And then to think of your brother-a tradesman-it's
insufferable! I declare I wouldn't have him mention his shop, before
our new guest-no, not for a thousand pounds! I wouldn't care if he
had the good sense to conceal the disgrace he is to the family; but
he's so fond of his horrible business, that he will let people know
what he is.'
Mr. Jacob Barton, the individual alluded to, was a large grocer; so
vulgar, and so lost to all sense of feeling, that he actually never
scrupled to avow that he wasn't above his business: 'he'd made his
money by it, and he didn't care who know'd it.'
'Ah! Flamwell, my dear fellow, how d'ye do?' said Mr. Malderton, as
a little spoffish man, with green spectacles, entered the room. 'You
got my note?'
'Yes, I did; and here I am in consequence.'
'You don't happen to know this Mr. Sparkins by name? You know
everybody?'
Mr. Flamwell was one of those gentlemen of remarkably extensive
information whom one occasionally meets in society, who pretend to
know everybody, but in reality know nobody. At Malderton's, where
any stories about great people were received with a greedy ear, he
was an especial favourite; and, knowing the kind of people he had to
deal with, he carried his passion of claiming acquaintance with
everybody, to the most immoderate length. He had rather a singular
way of telling his greatest lies in a parenthesis, and with an air of
self-denial, as if he feared being thought egotistical.
'Why, no, I don't know him by that name,' returned Flamwell, in a
low tone, and with an air of immense importance. 'I have no doubt I
know him, though. Is he tall?'
'Middle-sized,' said Miss Teresa.
'With black hair?' inquired Flamwell, hazarding a bold guess.
'Yes,' returned Miss Teresa, eagerly.
'Rather a snub nose?'
'No,' said the disappointed Teresa, 'he has a Roman nose.'
'I said a Roman nose, didn't I?' inquired Flamwell. 'He's an elegant
young man?'
'Oh, certainly.'
'With remarkably prepossessing manners?'
'Oh, yes!' said all the family together. 'You must know him.'
'Yes, I thought you knew him, if he was anybody,' triumphantly
exclaimed Mr. Malderton. 'Who d'ye think he is?'
'Why, from your description,' said Flamwell, ruminating, and
sinking his voice, almost to a whisper, 'he bears a strong
resemblance to the Honourable Augustus Fitz-Edward Fitz-John Fitz-
Osborne. He's a very talented young man, and rather eccentric. It's
extremely probable he may have changed his name for some
temporary purpose.'
Teresa's heart beat high. Could he be the Honourable Augustus
Fitz- Edward Fitz-John Fitz-Osborne! What a name to be elegantly
engraved upon two glazed cards, tied together with a piece of white
satin ribbon! 'The Honourable Mrs. Augustus Fitz-Edward Fitz-John
Fitz-Osborne!' The thought was transport.
'It's five minutes to five,' said Mr. Malderton, looking at his watch:
'I hope he's not going to disappoint us.'
'There he is!' exclaimed Miss Teresa, as a loud double-knock was
heard at the door. Everybody endeavoured to look-as people when
they particularly expect a visitor always do-as if they were perfectly
unsuspicious of the approach of anybody.
The room-door opened-'Mr. Barton!' said the servant.
'Confound the man!' murmured Malderton. 'Ah! my dear sir, how
d'ye do! Any news?'
'Why no,' returned the grocer, in his usual bluff manner. 'No, none
partickler. None that I am much aware of. How d'ye do, gals and
boys? Mr. Flamwell, sir-glad to see you.'
'Here's Mr. Sparkins!' said Tom, who had been looking out at the
window, 'on such a black horse!' There was Horatio, sure enough, on
a large black horse, curvetting and prancing along, like an Astley's
supernumerary. After a great deal of reining in, and pulling up, with
the accompaniments of snorting, rearing, and kicking, the animal
consented to stop at about a hundred yards from the gate, where
Mr. Sparkins dismounted, and confided him to the care of Mr.
Malderton's groom. The ceremony of introduction was gone through,
in all due form. Mr. Flamwell looked from behind his green spectacles
at Horatio with an air of mysterious importance; and the gallant
Horatio looked unutterable things at Teresa.
'Is he the Honourable Mr. Augustus What's-his-name?' whispered
Mrs. Malderton to Flamwell, as he was escorting her to the dining-
room.
'Why, no-at least not exactly,' returned that great authority-'not
exactly.'
'Who is he then?'
'Hush!' said Flamwell, nodding his head with a grave air, importing
that he knew very well; but was prevented, by some grave reasons
of state, from disclosing the important secret. It might be one of the
ministers making himself acquainted with the views of the people.
'Mr. Sparkins,' said the delighted Mrs. Malderton, 'pray divide the
ladies. John, put a chair for the gentleman between Miss Teresa and
Miss Marianne.' This was addressed to a man who, on ordinary
occasions, acted as half-groom, half-gardener; but who, as it was
important to make an impression on Mr. Sparkins, had been forced
into a white neckerchief and shoes, and touched up, and brushed, to
look like a second footman.
The dinner was excellent; Horatio was most attentive to Miss
Teresa, and every one felt in high spirits, except Mr. Malderton, who,
knowing the propensity of his brother-in-law, Mr. Barton, endured
that sort of agony which the newspapers inform us is experienced by
the surrounding neighbourhood when a pot-boy hangs himself in a
hay-loft, and which is 'much easier to be imagined than described.'
'Have you seen your friend, Sir Thomas Noland, lately, Flamwell?'
inquired Mr. Malderton, casting a sidelong look at Horatio, to see
what effect the mention of so great a man had upon him.
'Why, no-not very lately. I saw Lord Gubbleton the day before
yesterday.'
'All! I hope his lordship is very well?' said Malderton, in a tone of
the greatest interest. It is scarcely necessary to say that, until that
moment, he had been quite innocent of the existence of such a
person.
'Why, yes; he was very well-very well indeed. He's a devilish good
fellow. I met him in the City, and had a long chat with him. Indeed,
I'm rather intimate with him. I couldn't stop to talk to him as long as
I could wish, though, because I was on my way to a banker's, a very
rich man, and a member of Parliament, with whom I am also rather,
indeed I may say very, intimate.'
'I know whom you mean,' returned the host, consequentially-in
reality knowing as much about the matter as Flamwell himself.-'He
has a capital business.'
This was touching on a dangerous topic.
'Talking of business,' interposed Mr. Barton, from the centre of the
table. 'A gentleman whom you knew very well, Malderton, before
you made that first lucky spec of yours, called at our shop the other
day, and-'
'Barton, may I trouble you for a potato?' interrupted the wretched
master of the house, hoping to nip the story in the bud.
'Certainly,' returned the grocer, quite insensible of his brother-in-
law's object-'and he said in a very plain manner-'
'Floury, if you please,' interrupted Malderton again; dreading the
termination of the anecdote, and fearing a repetition of the word
'shop.'
'He said, says he,' continued the culprit, after despatching the
potato; 'says he, how goes on your business? So I said, jokingly-you
know my way-says I, I'm never above my business, and I hope my
business will never be above me. Ha, ha!'
'Mr. Sparkins,' said the host, vainly endeavouring to conceal his
dismay, 'a glass of wine?'
'With the utmost pleasure, sir.'
'Happy to see you.'
'Thank you.'
'We were talking the other evening,' resumed the host, addressing
Horatio, partly with the view of displaying the conversational powers
of his new acquaintance, and partly in the hope of drowning the
grocer's stories-'we were talking the other night about the nature of
man. Your argument struck me very forcibly.'
'And me,' said Mr. Frederick. Horatio made a graceful inclination of
the head.
'Pray, what is your opinion of woman, Mr. Sparkins?' inquired Mrs.
Malderton. The young ladies simpered.
'Man,' replied Horatio, 'man, whether he ranged the bright, gay,
flowery plains of a second Eden, or the more sterile, barren, and I
may say, commonplace regions, to which we are compelled to
accustom ourselves, in times such as these; man, under any
circumstances, or in any place-whether he were bending beneath
the withering blasts of the frigid zone, or scorching under the rays of
a vertical sun-man, without woman, would be-alone.'
'I am very happy to find you entertain such honourable opinions,
Mr. Sparkins,' said Mrs. Malderton.
'And I,' added Miss Teresa. Horatio looked his delight, and the
young lady blushed.
'Now, it's my opinion-' said Mr. Barton.
'I know what you're going to say,' interposed Malderton,
determined not to give his relation another opportunity, 'and I don't
agree with you.'
'What!' inquired the astonished grocer.
'I am sorry to differ from you, Barton,' said the host, in as positive
a manner as if he really were contradicting a position which the
other had laid down, 'but I cannot give my assent to what I consider
a very monstrous proposition.'
'But I meant to say-'
'You never can convince me,' said Malderton, with an air of
obstinate determination. 'Never.'
'And I,' said Mr. Frederick, following up his father's attack, 'cannot
entirely agree in Mr. Sparkins's argument.'
'What!' said Horatio, who became more metaphysical, and more
argumentative, as he saw the female part of the family listening in
wondering delight-'what! Is effect the consequence of cause? Is
cause the precursor of effect?'
'That's the point,' said Flamwell.
'To be sure,' said Mr. Malderton.
'Because, if effect is the consequence of cause, and if cause does
precede effect, I apprehend you are wrong,' added Horatio.
'Decidedly,' said the toad-eating Flamwell.
'At least, I apprehend that to be the just and logical deduction?'
said Sparkins, in a tone of interrogation.
'No doubt of it,' chimed in Flamwell again. 'It settles the point.'
'Well, perhaps it does,' said Mr. Frederick; 'I didn't see it before.'
'I don't exactly see it now,' thought the grocer; 'but I suppose it's
all right.'
'How wonderfully clever he is!' whispered Mrs. Malderton to her
daughters, as they retired to the drawing-room.
'Oh, he's quite a love!' said both the young ladies together; 'he
talks like an oracle. He must have seen a great deal of life.'
The gentlemen being left to themselves, a pause ensued, during
which everybody looked very grave, as if they were quite overcome
by the profound nature of the previous discussion. Flamwell, who
had made up his mind to find out who and what Mr. Horatio Sparkins
really was, first broke silence.
'Excuse me, sir,' said that distinguished personage, 'I presume you
have studied for the bar? I thought of entering once, myself-indeed,
I'm rather intimate with some of the highest ornaments of that
distinguished profession.'
'N-no!' said Horatio, with a little hesitation; 'not exactly.'
'But you have been much among the silk gowns, or I mistake?'
inquired Flamwell, deferentially.
'Nearly all my life,' returned Sparkins.

You might also like