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

(eBook PDF) Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition download

The document provides information about various editions of the eBook 'Introduction to Java Programming and Data Structures', including comprehensive and brief versions. It outlines the structure of the book, which is divided into five parts covering fundamentals, object-oriented programming, GUI programming, data structures and algorithms, and advanced Java programming. Additionally, it mentions resources available for students and instructors, such as online practice tools and video notes.

Uploaded by

yarenbrazegk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2 views

(eBook PDF) Introduction to Java Programming and Data Structures, Comprehensive Version, 11th Global Edition download

The document provides information about various editions of the eBook 'Introduction to Java Programming and Data Structures', including comprehensive and brief versions. It outlines the structure of the book, which is divided into five parts covering fundamentals, object-oriented programming, GUI programming, data structures and algorithms, and advanced Java programming. Additionally, it mentions resources available for students and instructors, such as online practice tools and video notes.

Uploaded by

yarenbrazegk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

(eBook PDF) Introduction to Java Programming and

Data Structures, Comprehensive Version, 11th


Global Edition install download

https://ebookluna.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11th-
global-edition/

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

(eBook PDF) Introduction to JAVA Programming and Data


Structures Comprehensive Version 11

https://ebookluna.com/product/ebook-pdf-introduction-to-java-
programming-and-data-structures-comprehensive-version-11/

ebookluna.com

(eBook PDF) Introduction to Java Programming, Brief


Version, Global Edition 11th Edition

https://ebookluna.com/product/ebook-pdf-introduction-to-java-
programming-brief-version-global-edition-11th-edition/

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

(eBook PDF) Java Foundations: Introduction to Program


Design and Data Structures 5th Edition

https://ebookluna.com/product/ebook-pdf-java-foundations-introduction-
to-program-design-and-data-structures-5th-edition/

ebookluna.com
(eBook PDF) Data Structures and Abstractions with Java 4th
Global Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-global-edition/

ebookluna.com

(eBook PDF) Data Structures and Abstractions with Java 4th


Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-
abstractions-with-java-4th-edition/

ebookluna.com

Data Structures and Abstractions with Java 5th Edition


(eBook PDF)

https://ebookluna.com/product/data-structures-and-abstractions-with-
java-5th-edition-ebook-pdf/

ebookluna.com

(eBook PDF) Data Structures and Other Objects Using Java


4th Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-other-
objects-using-java-4th-edition/

ebookluna.com

(eBook PDF) Data Structures and Problem Solving Using Java


4th Edition

https://ebookluna.com/product/ebook-pdf-data-structures-and-problem-
solving-using-java-4th-edition/

ebookluna.com
6 Preface

Part I: Fundamentals of Part II: Object-Oriented Part III: GUI Programming Part IV: Data Structures and Part V: Advanced Java
Programming Programming Algorithms Ch 16 Programming
Chapter 1 Introduction to Chapter 9 Objects and Classes Chapter 14 JavaFX Basics Ch 7 Chapter 18 Recursion Chapter 32 Multithreading and
Computers, Programs, and Parallel Programming
Java
Chapter 10 Thinking in Objects Chapter 15 Event-Driven Ch 13 Chapter 19 Generics
Programming and Chapter 33 Networking
Chapter 2 Elementary Animations
Chapter 11 Inheritance and Chapter 20 Lists, Stacks, Queues,
Programming
Polymorphism and Priority Queues Chapter 34 Java Database
Chapter 16 JavaFX Controls Programming
Chapter 3 Selections and Multimedia
Chapter 12 Exception Chapter 21 Sets and Maps
Handling and Text I/O Chapter 35 Advanced Database
Chapter 4 Mathematical Chapter 31 Advanced JavaFX Programming
Chapter 22 Developping
Functions, Characters, Chapter 13 Abstract Classes and FXML Efficient Algorithms
and Strings and Interfaces Chapter 36 Internationalization
Chapter 23 Sorting
Chapter 5 Loops Chapter 17 Binary I/O Chapter 37 Servlets
Chapter 24 Implementing Lists,
Chapter 6 Methods Stacks, Queues, and Priority Chapter 38 JavaServer Pages
Queues

Chapter 7 Single-Dimensional Chapter 39 JavaServer Faces


Arrays Chapter 25 Binary Search Trees
Chapter 40 RMI
Note: Chapters 1–18 are in the
Chapter 8 Multidimensional Chapter 26 AVL Trees
brief version of this book.
Arrays Chapter 41 Web Services
Note: Chapters 1–30 are in the Chapter 27 Hashing
comprehensive version.

Note: Chapters 31–44 are bonus Chapter 28 Graphs and


chapters available from the Applications
Companion Website.

Chapter 29 Weighted Graphs


and Applications

Chapter 30 Aggregate Operations


and Collection Streams

Chapter 42 2-4 Trees and B-


Trees

Chapter 43 Red-Black Trees Ch 9 Chapter 44 Testing Using JUnit


Preface  7

Organization of the Book


The chapters can be grouped into five parts that, taken together, form a comprehensive introduc-
tion to Java programming, data structures and algorithms, and database and Web programming.
Because knowledge is cumulative, the early chapters provide the conceptual basis for under-
standing programming and guide students through simple examples and exercises; subsequent
chapters progressively present Java programming in detail, culminating with the development
of comprehensive Java applications. The appendixes contain a mixed bag of topics, including an
introduction to number systems, bitwise operations, regular expressions, and enumerated types.

Part I: Fundamentals of Programming (Chapters 1–8)


The first part of the book is a stepping stone, preparing you to embark on the journey of learning
Java. You will begin to learn about Java (Chapter 1) and fundamental programming t­echniques
with primitive data types, variables, constants, assignments, expressions, and operators (­Chapter 2),
selection statements (Chapter 3), mathematical functions, characters, and strings (Chapter 4), loops
(Chapter 5), methods (Chapter 6), and arrays (Chapters 7–8). After ­Chapter 7, you can jump to
Chapter 18 to learn how to write recursive methods for solving inherently recursive problems.

Part II: Object-Oriented Programming (Chapters 9–13, and 17)


This part introduces object-oriented programming. Java is an object-oriented programming
language that uses abstraction, encapsulation, inheritance, and polymorphism to provide
great flexibility, modularity, and reusability in developing software. You will learn program-
ming with objects and classes (Chapters 9–10), class inheritance (Chapter 11), polymorphism
(­Chapter 11), exception handling (Chapter 12), abstract classes (Chapter 13), and interfaces
(Chapter 13). Text I/O is introduced in Chapter 12 and binary I/O is discussed in Chapter 17.

Part III: GUI Programming (Chapters 14–16 and Bonus Chapter 31)
JavaFX is a new framework for developing Java GUI programs. It is not only useful for
developing GUI programs, but also an excellent pedagogical tool for learning object-oriented
programming. This part introduces Java GUI programming using JavaFX in Chapters 14–16.
Major topics include GUI basics (Chapter 14), container panes (Chapter 14), drawing shapes
(Chapter 14), event-driven programming (Chapter 15), animations (Chapter 15), and GUI
­controls (Chapter 16), and playing audio and video (Chapter 16). You will learn the a­ rchitecture
of JavaFX GUI programming and use the controls, shapes, panes, image, and video to develop
useful applications. Chapter 31 covers advanced features in JavaFX.

Part IV: Data Structures and Algorithms (Chapters 18–30 and Bonus Chapters 42–43)
This part covers the main subjects in a typical data structures and algorithms course. Chapter 18
introduces recursion to write methods for solving inherently recursive problems. Chapter 19 presents
how generics can improve software reliability. Chapters 20 and 21 introduce the Java Collection
Framework, which defines a set of useful API for data structures. Chapter 22 discusses measur-
ing algorithm efficiency in order to choose an appropriate algorithm for applications. Chapter 23
describes classic sorting algorithms. You will learn how to implement several classic data struc-
tures lists, queues, and priority queues in Chapter 24. Chapters 25 and 26 introduce binary search
trees and AVL trees. Chapter 27 presents hashing and implementing maps and sets using hashing.
Chapters 28 and 29 introduce graph applications. Chapter 30 introduces aggregate operations for
collection streams. The 2-4 trees, B-trees, and red-black trees are covered in Bonus Chapters 42–43.

Part V: Advanced Java Programming (Chapters 32-41, 44)


This part of the book is devoted to advanced Java programming. Chapter 32 treats the use of
multithreading to make programs more responsive and interactive and introduces parallel pro-
gramming. Chapter 33 discusses how to write programs that talk with each other from different
8 Preface
hosts over the Internet. Chapter 34 introduces the use of Java to develop database projects.
Chapter 35 delves into advanced Java database programming. Chapter 36 covers the use of
internationalization support to develop projects for international audiences. Chapters 37 and
38 introduce how to use Java servlets and JavaServer Pages to generate dynamic content from
Web servers. Chapter 39 introduces modern Web application development using JavaServer
Faces. Chapter 40 introduces remote method invocation and Chapter 41 discusses Web ser-
vices. Chapter 44 introduces testing Java programs using JUnit.

Appendixes
This part of the book covers a mixed bag of topics. Appendix A lists Java keywords. ­Appendix B
gives tables of ASCII characters and their associated codes in decimal and in hex. Appen-
dix C shows the operator precedence. Appendix D summarizes Java modifiers and their usage.
Appendix E discusses special floating-point values. Appendix F introduces number systems and
conversions among binary, decimal, and hex numbers. Finally, Appendix G introduces bitwise
operations. Appendix H introduces regular expressions. Appendix I covers enumerated types.

Java Development Tools


You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs
and to compile and run the programs from the command window. You can also use a Java
development tool, such as NetBeans or Eclipse. These tools support an integrated develop-
ment environment (IDE) for developing Java programs quickly. Editing, compiling, building,
executing, and debugging programs are integrated in one graphical user interface. Using these
tools effectively can greatly increase your programming productivity. NetBeans and Eclipse
IDE tutorials are easy to use if you follow the tutorials. Tutorials on NetBeans and Eclipse can be found in
the supplements on the Companion Website www.pearsonglobaleditions.com/Liang.

Student Resources
The Companion Website (www.pearsonglobaleditions.com/Liang) contains the following
resources:
■■ Answers to CheckPoint questions
■■ Solutions to majority of even-numbered programming exercises
■■ Source code for the examples in the book
■■ Interactive quiz (organized by sections for each chapter)
■■ Supplements
■■ Debugging tips
■■ Video notes
■■ Algorithm animations

Supplements
The text covers the essential subjects. The supplements extend the text to introduce additional
topics that might be of interest to readers. The supplements are available from the Companion
Website.
Preface  9

Instructor Resources
The Companion Website, accessible from www.pearsonglobaleditions.com/Liang, contains the
following resources:
■■ Microsoft PowerPoint slides with interactive buttons to view full-color, syntax-highlighted
source code and to run programs without leaving the slides.
■■ Solutions to a majority of odd-numbered programming exercises.
■■ More than 200 additional programming exercises and 300 quizzes organized by ­chapters.
These exercises and quizzes are available only to the instructors. Solutions to these
­exercises and quizzes are provided.
■■ Web-based quiz generator. (Instructors can choose chapters to generate quizzes from a
large database of more than two thousand questions.)
■■ Sample exams. Most exams have four parts:
■■ Multiple-choice questions or short-answer questions
■■ Correct programming errors
■■ Trace programs
■■ Write programs
■■ Sample exams with ABET course assessment.
■■ Projects. In general, each project gives a description and asks students to analyze, design,
and implement the project.
Some readers have requested the materials from the Instructor Resource Center. Please
understand that these are for instructors only. Such requests will not be answered.

Online Practice and Assessment


with MyProgrammingLab
MyProgrammingLab helps students fully grasp the logic, semantics, and syntax of program-
ming. Through practice exercises and immediate, personalized feedback, MyProgrammingLab
improves the programming competence of beginning students who often struggle with the
basic concepts and paradigms of popular high-level programming languages.
A self-study and homework tool, a MyProgrammingLab course consists of hundreds of small
practice problems organized around the structure of this textbook. For students, the system auto-
matically detects errors in the logic and syntax of their code submissions and offers targeted hints
that enable students to figure out what went wrong—and why. For instructors, a comprehensive
gradebook tracks correct and incorrect answers and stores the code inputted by students for review.
MyProgrammingLab is offered to users of this book in partnership with Turing’s Craft, the
makers of the CodeLab interactive programming exercise system. For a full demonstration,
to see feedback from instructors and students, or to get started using MyProgrammingLab in
your course, visit www.myprogramminglab.com.

Video Notes
We are excited about the new Video Notes feature that is found in this new edition. These VideoNote

videos provide additional help by presenting examples of key topics and showing how
to solve problems completely from design through coding. Video Notes are available from
www.pearsonglobaleditions.com/Liang.
10 Preface

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

Acknowledgments
I would like to thank Armstrong State University for enabling me to teach what I write and for
supporting me in writing what I teach. Teaching is the source of inspiration for continuing to
improve the book. I am grateful to the instructors and students who have offered comments,
suggestions, corrections, and praise. My special thanks go to Stefan Andrei of Lamar Univer-
sity and William Bahn of University of Colorado Colorado Springs for their help to improve
the data structures part of this book.
This book has been greatly enhanced thanks to outstanding reviews for this and previous edi-
tions. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed (North
­Georgia College and State University), Omar Aldawud (Illinois Institute of Technology), Ste-
fan Andrei (Lamar University), Yang Ang (University of Wollongong, Australia), Kevin Bierre
(Rochester Institute of Technology), Aaron Braskin (Mira Costa High School), David Champion
(DeVry Institute), James Chegwidden (Tarrant County College), Anup Dargar (University of North
Dakota), Daryl Detrick (Warren Hills Regional High School), Charles Dierbach (Towson Univer-
sity), Frank Ducrest (University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at
Parkside), Summer Ehresman (Center Grove High School), Deena Engel (New York University),
Henry A. Etlinger (Rochester Institute of Technology), James Ten Eyck (Marist College), Myers
Foreman (Lamar University), Olac Fuentes (University of Texas at El Paso), Edward F. Gehringer
(North Carolina State University), Harold Grossman (Clemson University), Barbara Guillot (Loui-
siana State University), Stuart Hansen (University of Wisconsin, Parkside), Dan Harvey (Southern
Oregon University), Ron Hofman (Red River College, Canada), Stephen Hughes (Roanoke Col-
lege), Vladan Jovanovic (Georgia Southern University), Deborah Kabura Kariuki (Stony Point
High School), Edwin Kay (Lehigh University), Larry King (University of Texas at Dallas), Nana
Kofi (Langara College, Canada), George Koutsogiannakis (Illinois Institute of Technology), Roger
Kraft (Purdue University at Calumet), Norman Krumpe (Miami University), Hong Lin (DeVry
Institute), Dan Lipsa (Armstrong State University), James Madison (Rensselaer Polytechnic Insti-
tute), Frank Malinowski (Darton College), Tim Margush (University of Akron), Debbie Masada
(Sun Microsystems), Blayne Mayfield (Oklahoma State University), John McGrath (J.P. McGrath
Consulting), Hugh McGuire (Grand Valley State), Shyamal Mitra (University of Texas at Austin),
Michel Mitri (James Madison University), Kenrick Mock (University of Alaska Anchorage), Frank
Murgolo (California State University, Long Beach), Jun Ni (University of Iowa), Benjamin N ­ ystuen
(University of Colorado at Colorado Springs), Maureen Opkins (CA State University, Long Beach),
Gavin Osborne (University of Saskatchewan), Kevin Parker (Idaho State University), Dale Par-
son (Kutztown University), Mark Pendergast (Florida Gulf Coast University), Richard Povinelli
(Marquette University), Roger Priebe (University of Texas at Austin), Mary Ann Pumphrey (De
Anza Junior College), Pat Roth (Southern Polytechnic State University), Amr Sabry (Indiana Uni-
versity), Ben Setzer (Kennesaw State University), Carolyn Schauble (Colorado State University),
David Scuse (University of Manitoba), Ashraf Shirani (San Jose State University), Daniel Spiegel
(Kutztown University), Joslyn A. Smith (Florida Atlantic University), Lixin Tao (Pace University),
Ronald F. Taylor (Wright State University), Russ Tront (Simon Fraser University), Deborah ­Trytten
(University of Oklahoma), Michael Verdicchio (Citadel), Kent Vidrine (George Washington Uni-
versity), and Bahram Zartoshty (California State University at Northridge).
It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank Tracy
Johnson and her colleagues Marcia Horton, Demetrius Hall, Yvonne Vannatta, Kristy Alaura,
Carole Snyder, Scott Disanno, Bob Engelhardt, Shylaja Gattupalli, and their colleagues for
organizing, producing, and promoting this project.
As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.
Preface  11

Acknowledgments for the Global Edition


Pearson would like to thank and acknowledge Yvan Maillot (Univresite Haute-Alsace) and
Steven Yuwono (National ­University of Singapore) for contributing to this Global Edition,
and Arif Ahmed (National Institute of Technology, ­Silchar), Annette Bieniusa (University of
Kaiserslautern), Shaligram Prajapat (Devi Ahilya Vishwavidyalaya, Indore), and Ram Gopal
Raj (University of Malaya) for reviewing this Global Edition.
CONTENTS
Chapter 1 I ntroduction to Computers,
­Programs, and Java™ 23
1.1 Introduction 24
1.2 What Is a Computer? 24
1.3 Programming Languages 29
1.4 Operating Systems 31
1.5 Java, the World Wide Web, and Beyond 32
1.6 The Java Language Specification, API, JDK,
JRE, and IDE 33
1.7 A Simple Java Program 34
1.8 Creating, Compiling, and Executing a Java Program 37
1.9 Programming Style and Documentation 40
1.10 Programming Errors 42
1.11 Developing Java Programs Using NetBeans 45
1.12 Developing Java Programs Using Eclipse 47

Chapter 2 Elementary Programming 55


2.1 Introduction 56
2.2 Writing a Simple Program 56
2.3 Reading Input from the Console 59
2.4 Identifiers 62
2.5 Variables 62
2.6 Assignment Statements and Assignment Expressions 64
2.7 Named Constants 65
2.8 Naming Conventions 66
2.9 Numeric Data Types and Operations 67
2.10 Numeric Literals 70
2.11 Evaluating Expressions and Operator Precedence 72
2.12 Case Study: Displaying the Current Time 74
2.13 Augmented Assignment Operators 76
2.14 Increment and Decrement Operators 77
2.15 Numeric Type Conversions 79
2.16 Software Development Process 81
2.17 Case Study: Counting Monetary Units 85
2.18 Common Errors and Pitfalls 87

Chapter 3 Selections 97
3.1 Introduction 98
3.2 boolean Data Type 98
3.3 if Statements 100
3.4 Two-Way if-else Statements 102
3.5 Nested if and Multi-Way if-else Statements 103
3.6 Common Errors and Pitfalls 105
3.7 Generating Random Numbers 109
3.8 Case Study: Computing Body Mass Index 111
3.9 Case Study: Computing Taxes 112
3.10 Logical Operators 115
3.11 Case Study: Determining Leap Year 119
3.12 Case Study: Lottery 120
3.13 switch Statements 122
12
Contents  13
3.14 Conditional Operators 125
3.15 Operator Precedence and Associativity 126
3.16 Debugging 128

Chapter 4 Mathematical Functions,


Characters, and Strings 141
4.1 Introduction 142
4.2 Common Mathematical Functions 142
4.3 Character Data Type and Operations 147
4.4 The String Type 152
4.5 Case Studies 161
4.6 Formatting Console Output 167

Chapter 5 Loops 181


5.1 Introduction 182
5.2 The while Loop 182
5.3 Case Study: Guessing Numbers 185
5.4 Loop Design Strategies 188
5.5 Controlling a Loop with User Confirmation or a Sentinel Value 190
5.6 The do-while Loop 192
5.7 The for Loop 195
5.8 Which Loop to Use? 198
5.9 Nested Loops 200
5.10 Minimizing Numeric Errors 202
5.11 Case Studies 204
5.12 Keywords break and continue 208
5.13 Case Study: Checking Palindromes 211
5.14 Case Study: Displaying Prime Numbers 213

Chapter 6 Methods 227


6.1 Introduction 228
6.2 Defining a Method 228
6.3 Calling a Method 230
6.4 void vs. Value-Returning Methods 233
6.5 Passing Parameters by Values 236
6.6 Modularizing Code 239
6.7 Case Study: Converting Hexadecimals to Decimals 241
6.8 Overloading Methods 243
6.9 The Scope of Variables 246
6.10 Case Study: Generating Random Characters 247
6.11 Method Abstraction and Stepwise Refinement 249

Chapter 7 Single-Dimensional Arrays 269


7.1 Introduction 270
7.2 Array Basics 270
7.3 Case Study: Analyzing Numbers 277
7.4 Case Study: Deck of Cards 278
7.5 Copying Arrays 280
7.6 Passing Arrays to Methods 281
7.7 Returning an Array from a Method 284
7.8 Case Study: Counting the Occurrences of Each Letter 285
7.9 Variable-Length Argument Lists 288
7.10 Searching Arrays 289
7.11 Sorting Arrays 293
14 Contents
7.12 The Arrays Class 294
7.13 Command-Line Arguments 296

Chapter 8 Multidimensional Arrays 311


8.1 Introduction 312
8.2 Two-Dimensional Array Basics 312
8.3 Processing Two-Dimensional Arrays 315
8.4 Passing Two-Dimensional Arrays to Methods 317
8.5 Case Study: Grading a Multiple-Choice Test 318
8.6 Case Study: Finding the Closest Pair 320
8.7 Case Study: Sudoku 322
8.8 Multidimensional Arrays 325

Chapter 9 Objects and Classes 345


9.1 Introduction 346
9.2 Defining Classes for Objects 346
9.3 Example: Defining Classes and Creating Objects 348
9.4 Constructing Objects Using Constructors 353
9.5 Accessing Objects via Reference Variables 354
9.6 Using Classes from the Java Library 358
9.7 Static Variables, Constants, and Methods 361
9.8 Visibility Modifiers 366
9.9 Data Field Encapsulation 368
9.10 Passing Objects to Methods 371
9.11 Array of Objects 375
9.12 Immutable Objects and Classes 377
9.13 The Scope of Variables 379
9.14 The this Reference 380

Chapter 10 Object-Oriented Thinking 389


10.1 Introduction 390
10.2 Class Abstraction and Encapsulation 390
10.3 Thinking in Objects 394
10.4 Class Relationships 397
10.5 Case Study: Designing the Course Class 400
10.6 Case Study: Designing a Class for Stacks 402
10.7 Processing Primitive Data Type Values as Objects 404
10.8 Automatic Conversion between Primitive Types
and Wrapper Class Types 407
10.9 The BigInteger and BigDecimal Classes 408
10.10 The String Class 410
10.11 The StringBuilder and StringBuffer Classes 416

Chapter 11 Inheritance and


Polymorphism 433
11.1 Introduction 434
11.2 Superclasses and Subclasses 434
11.3 Using the super Keyword 440
11.4 Overriding Methods 443
11.5 Overriding vs. Overloading 444
11.6 The Object Class and Its toString() Method 446
11.7 Polymorphism 447
11.8 Dynamic Binding 447
11.9 Casting Objects and the instanceof Operator 451
11.10 The Object’s equals Method 455
Contents  15
11.11 The ArrayList Class 456
11.12 Useful Methods for Lists 462
11.13 Case Study: A Custom Stack Class 463
11.14 The protected Data and Methods 464
11.15 Preventing Extending and Overriding 467

Chapter 12 Exception Handling


and Text I/O 475
12.1 Introduction 476
12.2 Exception-Handling Overview 476
12.3 Exception Types 481
12.4 More on Exception Handling 484
12.5 The finally Clause 492
12.6 When to Use Exceptions 493
12.7 Rethrowing Exceptions 494
12.8 Chained Exceptions 495
12.9 Defining Custom Exception Classes 496
12.10 The File Class 499
12.11 File Input and Output 502
12.12 Reading Data from the Web 508
12.13 Case Study: Web Crawler 510

Chapter 13 Abstract Classes and Interfaces 521


13.1 Introduction 522
13.2 Abstract Classes 522
13.3 Case Study: the Abstract Number Class 527
13.4 Case Study: Calendar and GregorianCalendar 529
13.5 Interfaces 532
13.6 The Comparable Interface 535
13.7 The Cloneable Interface 540
13.8 Interfaces vs. Abstract Classes 545
13.9 Case Study: The Rational Class 548
13.10 Class-Design Guidelines 553

Chapter 14 JavaFX Basics 563


14.1 Introduction 564
14.2 JavaFX vs Swing and AWT 564
14.3 The Basic Structure of a JavaFX Program 564
14.4 Panes, Groups, UI Controls, and Shapes 567
14.5 Property Binding 570
14.6 Common Properties and Methods for Nodes 573
14.7 The Color Class 575
14.8 The Font Class 576
14.9 The Image and ImageView Classes 578
14.10 Layout Panes and Groups 580
14.11 Shapes 589
14.12 Case Study: The ClockPane Class 602

Chapter 15 Event-Driven Programming


and Animations 615
15.1 Introduction 616
15.2 Events and Event Sources 618
15.3 Registering Handlers and Handling Events 619
15.4 Inner Classes 623
15.5 Anonymous Inner Class Handlers 624
16 Contents
15.6 Simplifying Event Handling Using Lambda Expressions 627
15.7 Case Study: Loan Calculator 631
15.8 Mouse Events 633
15.9 Key Events 635
15.10 Listeners for Observable Objects 638
15.11 Animation 640
15.12 Case Study: Bouncing Ball 648
15.13 Case Study: US Map 652

Chapter 16 JavaFX UI Controls


and Multimedia 665
16.1 Introduction 666
16.2 Labeled and Label 666
16.3 Button 668
16.4 CheckBox 670
16.5 RadioButton 673
16.6 TextField 676
16.7 TextArea 677
16.8 ComboBox 681
16.9 ListView 684
16.10 ScrollBar 687
16.11 Slider 690
16.12 Case Study: Developing a Tic-Tac-Toe Game 693
16.13 Video and Audio 698
16.14 Case Study: National Flags and Anthems 701

Chapter 17 Binary I/O 713


17.1 Introduction 714
17.2 How Is Text I/O Handled in Java? 714
17.3 Text I/O vs. Binary I/O 715
17.4 Binary I/O Classes 716
17.5 Case Study: Copying Files 726
17.6 Object I/O 728
17.7 Random-Access Files 733

Chapter 18 Recursion 741


18.1 Introduction 742
18.2 Case Study: Computing Factorials 742
18.3 Case Study: Computing Fibonacci
Numbers 745
18.4 Problem Solving Using Recursion 748
18.5 Recursive Helper Methods 750
18.6 Case Study: Finding the Directory Size 753
18.7 Case Study: Tower of Hanoi 755
18.8 Case Study: Fractals 758
18.9 Recursion vs. Iteration 762
18.10 Tail Recursion 762

Chapter 19 Generics 773


19.1 Introduction 774
19.2 Motivations and Benefits 774
19.3 Defining Generic Classes and Interfaces 776
19.4 Generic Methods 778
19.5 Case Study: Sorting an Array of Objects 780
Contents  17
19.6 Raw Types and Backward Compatibility 782
19.7 Wildcard Generic Types 783
19.8 Erasure and Restrictions on Generics 786
19.9 Case Study: Generic Matrix Class 788

Chapter 20 L
 ists, Stacks, Queues, and
Priority Queues 797
20.1 Introduction 798
20.2 Collections 798
20.3 Iterators 802
20.4 Using the forEach Method 803
20.5 Lists 804
20.6 The Comparator Interface 809
20.7 Static Methods for Lists and Collections 813
20.8 Case Study: Bouncing Balls 816
20.9 Vector and Stack Classes 820
20.10 Queues and Priority Queues 821
20.11 Case Study: Evaluating Expressions 825

Chapter 21 Sets and Maps 837


21.1 Introduction 838
21.2 Sets 838
21.3 Comparing the Performance of Sets and Lists 846
21.4 Case Study: Counting Keywords 849
21.5 Maps 850
21.6 Case Study: Occurrences of Words 855
21.7 Singleton and Unmodifiable Collections and Maps 857

Chapter 22 Developing Efficient


Algorithms 861
22.1 Introduction 862
22.2 Measuring Algorithm Efficiency Using Big O Notation 862
22.3 Examples: Determining Big O 864
22.4 Analyzing Algorithm Time Complexity 868
22.5 Finding Fibonacci Numbers Using Dynamic
Programming 871
22.6 Finding Greatest Common Divisors Using Euclid’s
Algorithm 873
22.7 Efficient Algorithms for Finding Prime Numbers 877
22.8 Finding the Closest Pair of Points Using
Divide-and-Conquer 883
22.9 Solving the Eight Queens Problem Using Backtracking 886
22.10 Computational Geometry: Finding a Convex Hull 889

Chapter 23 Sorting 903


23.1 Introduction 904
23.2 Insertion Sort 904
23.3 Bubble Sort 906
23.4 Merge Sort 909
23.5 Quick Sort 912
23.6 Heap Sort 916
23.7 Bucket and Radix Sorts 923
23.8 External Sort 925
18 Contents

Chapter 24 I mplementing Lists, Stacks,


Queues, and Priority Queues 939
24.1 Introduction 940
24.2 Common Operations for Lists 940
24.3 Array Lists 944
24.4 Linked Lists 951
24.5 Stacks and Queues 965
24.6 Priority Queues 969

Chapter 25 Binary Search Trees 975


25.1 Introduction 976
25.2 Binary Search Trees 976
25.3 Deleting Elements from a BST 989
25.4 Tree Visualization and MVC 995
25.5 Iterators 998
25.6 Case Study: Data Compression 1000

Chapter 26 AVL Trees 1011


26.1 Introduction 1012
26.2 Rebalancing Trees 1012
26.3 Designing Classes for AVL Trees 1015
26.4 Overriding the insert Method 1016
26.5 Implementing Rotations 1017
26.6 Implementing the delete Method 1018
26.7 The AVLTree Class 1018
26.8 Testing the AVLTree Class 1024
26.9 AVL Tree Time Complexity Analysis 1027

Chapter 27 Hashing 1031


27.1 Introduction 1032
27.2 What Is Hashing? 1032
27.3 Hash Functions and Hash Codes 1033
27.4 Handling Collisions Using Open Addressing 1035
27.5 Handling Collisions Using Separate Chaining 1039
27.6 Load Factor and Rehashing 1039
27.7 Implementing a Map Using Hashing 1041
27.8 Implementing Set Using Hashing 1050

Chapter 28 Graphs and Applications 1061


28.1 Introduction 1062
28.2 Basic Graph Terminologies 1063
28.3 Representing Graphs 1064
28.4 Modeling Graphs 1070
28.5 Graph Visualization 1080
28.6 Graph Traversals 1083
28.7 Depth-First Search (DFS) 1084
28.8 Case Study: The Connected Circles Problem 1088
28.9 Breadth-First Search (BFS) 1090
28.10 Case Study: The Nine Tails Problem 1093
Contents  19

Chapter 29 W
 eighted Graphs and
Applications 1107
29.1 Introduction 1108
29.2 Representing Weighted Graphs 1109
29.3 The WeightedGraph Class 1111
29.4 Minimum Spanning Trees 1119
29.5 Finding Shortest Paths 1125
29.6 Case Study: The Weighted Nine Tails Problem 1134

Chapter 30 
Aggregate Operations
for Collection Streams 1145
30.1 Introduction 1146
30.2 Stream Pipelines 1146
30.3 IntStream, LongStream, and DoubleStream 1152
30.4 Parallel Streams 1155
30.5 Stream Reduction Using the reduce Method 1157
30.6 Stream Reduction Using the collect Method 1160
30.7 Grouping Elements Using the groupingby Collector 1163
30.8 Case Studies 1166

Chapter 31–44 are available from the Companion Website at


www.pearsonglobaleditions.com/Liang

Chapter 31 Advanced JavaFX and FXML


Chapter 32 Multithreading and Parallel
Programming
Chapter 33 Networking
Chapter 34 Java Database Programming
Chapter 35 Advanced Java Database Programming
Chapter 36 Internationalization
Chapter 37 Servlets
Chapter 38 JavaServer Pages
Chapter 39 JavaServer Faces
Chapter 40 Remote Method Invocation
Chapter 41 Web Services
Chapter 42 2-4 Trees and B-Trees
Chapter 43 Red-Black Trees
Chapter 44 Testing Using JUnit
20 Contents

Appendixes 1177
Appendix A Java Keywords 1179
Appendix B The ASCII Character Set 1180
Appendix C Operator Precedence Chart 1182
Appendix D Java Modifiers 1184
Appendix E Special Floating-Point Values 1186
Appendix F Number Systems 1187
Appendix G Bitwise Operations 1191
Appendix H Regular Expressions 1192
Appendix I Enumerated Types 1197

Quick Reference 1203


Index 1205
VideoNotes
Locations of VideoNotes
VideoNote
www.pearsonglobaleditions.com/Liang

Chapter 1 Introduction to Computers, Programs, Coupon collector’s problem 304


and Java™ 23 Consecutive four 306
Your first Java program 34
Compile and run a Java program 39 Chapter 8 Multidimensional Arrays 311
NetBeans brief tutorial 45 Find the row with the largest sum 316
Eclipse brief tutorial 47 Grade multiple-choice test 318
Sudoku 322
Chapter 2 Elementary Programming 55 Multiply two matrices 331
Obtain input 59 Even number of 1s 338
Use operators / and % 74
Software development Chapter 9 Objects and Classes 345
process 81 Define classes and objects 346
Compute loan payments 82 Use classes 358
Compute BMI 94 Static vs. instance 361
Data field encapsulation 368
Chapter 3 Selections 97 The this keyword 380
Program addition quiz 99 The Fan class 386
Program subtraction quiz 109
Use multi-way if-else Chapter 10 Object-Oriented Thinking 389
statements 112 The Loan class 391
Sort three integers 132 The BMI class 394
Check point location 134 The StackOfIntegers class 402
Process large numbers 408
Chapter 4 Mathematical Functions, Characters, The String class 410
and Strings 141 The MyPoint class 424
Introduce Math functions 142
Introduce strings and objects 152 Chapter 11 Inheritance and Polymorphism 433
Convert hex to decimal 165 Geometric class hierarchy 434
Compute great circle distance 173 Polymorphism and dynamic
Convert hex to binary 176 binding demo 448
The ArrayList class 456
Chapter 5 Loops 181 The MyStack class 463
Use while loop 182 New Account class 470
Guess a number 185
Multiple subtraction quiz 188 Chapter 12 Exception Handling and Text I/O 475
Use do-while loop 192 Exception-handling advantages 476
Minimize numeric errors 202 Create custom exception classes 496
Display loan schedule 219 Write and read data 502
Sum a series 220 HexFormatException 515

Chapter 6 Methods 227 Chapter 13 Abstract Classes and Interfaces 521


Define/invoke max method 230 Abstract GeometricObject class 522
Use void method 233 Calendar and Gregorian
Modularize code 239 Calendar classes 529
Stepwise refinement 249 The concept of interface 532
Reverse an integer 258 Redesign the Rectangle class 558
Estimate p 261
Chapter 14 JavaFX Basics 563
Chapter 7 Single-Dimensional Arrays 269 Getting started with JavaFX 564
Random shuffling 274 Understand property binding 570
Deck of cards 278 Use Image and ImageView 578
Selection sort 293 Use layout panes 580
Command-line arguments 297 Use shapes 589
21
22 VideoNotes
Display a tic-tac-toe board 608 Tic-Tac-Toe 693
Display a bar chart 610 Use Media, MediaPlayer,
and MediaView 698
Chapter 15 Event-Driven Programming Use radio buttons and text fields 705
and Animations 615 Set fonts 707
Handler and its registration 622
Anonymous handler 625 Chapter 17 Binary I/O 713
Move message using the Copy file 726
mouse 634 Object I/O 728
Animate a rising flag 640 Split a large file 738
Flashing text 646
Simple calculator 656 Chapter 18 Recursion 741
Check mouse-point location 658 Binary search 752
Display a running fan 661 Directory size 753
Fractal (Sierpinski triangle) 758
Chapter 16 JavaFX UI Controls and Multimedia 665 Search a string in a directory 769
Use ListView 684 Recursive tree 772
Use Slider 690

Animations

Chapter 7 Single-Dimensional Arrays 269 radix sort on Companion


linear search animation on Website 924
Companion Website 290
binary search animation on Chapter 24 Implementing Lists, Stacks,
Companion Website 290 Queues, and Priority Queues 939
selection sort animation on list animation on Companion
Companion Website 293 Website 940
stack and queue animation on
Chapter 8 Multidimensional Arrays 311 Companion Website 965
closest-pair animation on
the Companion Website 320 Chapter 25 Binary Search Trees 975
BST animation on
Chapter 22 Developing Efficient Algorithms 861 Companion Website 976
binary search animation on
the Companion Website 868 Chapter 26 AVL Trees 1011
selection sort animation on AVL tree animation on
the Companion Website 868 Companion Website 1012
closest-pair animation on
Companion Website 883 Chapter 27 Hashing 1031
Eight Queens animation on linear probing animation on
the Companion Website 886 Companion Website 1036
convex hull animation on quadratic probing animation on
the Companion Website 889 Companion Website 1037
separate chaining animation on
Chapter 23 Sorting 903 Companion Website 1040
insertion-sort animation on
Companion Website 904 Chapter 28 Graphs and Applications 1061
bubble sort animation on the graph learning tool on
Companion Website 907 Companion Website 1064
merge animation on Companion U.S. Map Search 1086
Website 911 Chapter 29 Weighted Graphs and
partition animation on Applications 1107
Companion Website 915 weighted graph learning tool
heap animation on Companion animation on Companion Website 1108
Website 917
Chapter

1
Introduction
to Computers,
Programs, and Java™
Objectives
■■ To understand computer basics, programs, and operating systems
(§§1.2–1.4).
■■ To describe the relationship between Java and the World Wide Web
(§1.5).
■■ To understand the meaning of Java language specification, API, JDK™,
JRE™, and IDE (§1.6).
■■ To write a simple Java program (§1.7).
■■ To display output on the console (§1.7).
■■ To explain the basic syntax of a Java program (§1.7).
■■ To create, compile, and run Java programs (§1.8).
■■ To use sound Java programming style and document programs properly
(§1.9).
■■ To explain the differences between syntax errors, runtime errors, and
logic errors (§1.10).
■■ To develop Java programs using NetBeans™ (§1.11).
■■ To develop Java programs using Eclipse™ (§1.12).
Other documents randomly have
different content
several people were killed, and one dragged by the legs to the
palace. The mob by the 20th were very unruly, and insisted the
Royal Family should not leave Naples; however, they were pacified
by the King and Queen speaking to them.
“On the 21st, at half-past 8 P.M., three Barges with myself and
Captain Hope, landed at a corner of the Arsenal. I went into the
palace and brought out the whole Royal Family, put them into the
Boats, and at half-past nine they were all safely on board the
Vanguard, when I gave immediate notice to all British Merchants
that their persons would be received on board every and any Ship in
the Squadron, their effects of value being before embarked in the
three English transports who were partly unloaded, and I had
directed that all the condemned provisions should be thrown
overboard, in order to make room for their effects. Sir William
Hamilton had also directed two Vessels to be hired for the
39
accommodation of the French emigrants, and provisions were
supplied from our Victuallers; in short, everything had been done for
the comfort of all persons embarked.
“I did not forget in these important moments that it was my duty
not to leave the chance of any Ships of War falling into the hands of
the French, therefore, every preparation was made for burning them
before I sailed; but the reasons given me by their Sicilian Majesties,
induced me not to burn them till the last moment. I, therefore,
directed the Marquis de Niza to remove all the Neapolitan Ships
outside the Squadron under his command, and if it was possible, to
equip some of them with jury masts and send them to Messina; and
whenever the French advanced near Naples, or the people revolted
against their legitimate Government, immediately to destroy the
Ships of War, and to join me at Palermo, leaving one or two Ships to
cruize between Capri and Ischia in order to prevent the entrance of
any English Ship into the Bay of Naples. On the 23rd, at 7 P.M., the
Vanguard, Sannite, and Archimedes, with about twenty sail of
Vessels left the Bay of Naples; the next day it blew harder than I
ever experienced since I have been at sea. Your Lordship will believe
that my anxiety was not lessened by the great charge that was with
me, but not a word of uneasiness escaped the lips of any of the
Royal Family. On the 25th, at 9 A.M., Prince Albert, their Majesties’
youngest child, having eat a hearty breakfast, was taken ill, and at 7
P.M. died in the arms of Lady Hamilton; and here it is my duty to tell
your Lordship the obligations which the whole Royal Family as well
as myself are under on this trying occasion to her Ladyship.... Lady
Hamilton provided her own beds, linen, &c., and became their slave,
for except one man, no person belonging to Royalty assisted the
Royal Family, nor did her Ladyship enter a bed the whole time they
were on board. Good Sir William also made every sacrifice for the
comfort of the august Family embarked with him. I must not omit to
state the kindness of Captain Hardy and every Officer in the
Vanguard, all of whom readily gave their beds for the convenience of
the numerous persons attending the Royal Family.
“At 3 P.M., being in sight of Palermo, his Sicilian Majesty’s Royal
Standard was hoisted at the main-top gallant-mast head of the
Vanguard, which was kept flying there till his Majesty got into the
Vanguard’s barge, when it was struck in the Ship and hoisted in the
Barge, and every proper honour paid to it from the Ship. As soon as
his Majesty set his foot on shore, it was struck from the Barge. The
Vanguard anchored at 2 A.M. of the 26th; at 5, I attended her
Majesty and all the Princesses on shore; her Majesty being so much
affected by the death of Prince Albert that she could not bear to go
on shore in a public manner. At 9 A.M., his Majesty went on shore,
and was received with the loudest acclamations and apparent joy.”
Alas, that one has to admit that while Lady Hamilton was the
“slave” of the Sicilian Royal Family, Nelson was rapidly becoming so
infatuated that the same word might be used to describe his
relationship with “our dear invaluable Lady Hamilton”! He also seems
to have had an exaggerated sense of the importance of the princely
personages who had placed themselves under his protection. In his
letters he speaks of “The good and amiable Queen,” “the great
Queen,” and so on. “I am here,” he writes to Captain Ball, of the
Alexander, dated Palermo, January 21st, 1799, “nor will the King or
Queen allow me to move. I have offered to go to Naples, and have
wished to go off Malta in case the Squadron from Brest should get
near you, but neither one or the other can weigh with them.” To Earl
Spencer he confides on the 6th March, “In Calabria the people have
cut down the Tree of Liberty; but I shall never consider any part of
the Kingdom of Naples safe, or even Sicily, until I hear of the
Emperor’s entering Italy, when all my Ships shall go into the Bay of
Naples, and I think we can make a Revolution against the French—at
least, my endeavours shall not be wanting. I hope to go on the
service myself, but I have my doubts if the King and Queen will
consent to my leaving them for a moment.” On the 20th of the same
month he tells St Vincent very much the same thing. “If the Emperor
moves, I hope yet to return the Royal Family to Naples. At present, I
cannot move. Would the Court but let me, I should be better, I
believe; for here I am writing from morn to eve: therefore you must
excuse this jumble of a letter.”
And after evening what? Rumour, not altogether devoid of fact,
told strange tales of gambling continued far into the night, of money
made and money lost, of an insidious enchantment which was
beginning to sully the fair soul of Britain’s greatest Admiral. How far
the influence of Lady Hamilton led Nelson to neglect his duty is a
debatable point. Admiral Mahan points out that on the 22nd October
1798, Nelson wrote to Lord St Vincent to the effect that he had
given up his original plan, “which was to have gone to Egypt and
attend to the destruction of the French shipping in that quarter,”
owing to the King’s desire that he should return to Naples, after
having arranged the blockade of Malta. This and similar expressions,
says Mahan, “show the anxiety of his mind acting against his
judgment.” The late Judge O’Connor Morris, commenting on this
phase of the Hero’s career, is most emphatic in his condemnation.
His connection with Emma Hamilton “kept him at Naples when he
ought to have been elsewhere; it led him to disobey a superior’s
orders, on one occasion when there was no excuse; it perhaps
prevented him from being present at the siege of Malta. It exposed
him, too, to just censure at home, and gave pain and offence to his
best friends; and the consciousness that he was acting wrongly
soured, in some degree, his nature, and made him morose and at
odds with faithful companions in arms.” For the defence there are no
more able advocates than Professor Sir J. Knox Laughton and Mr
James R. Thursfield, M.A. Nelson, the former asserts, “in becoming
the slave of a beautiful and voluptuous woman, did not cease to be
a great commander. There is a common idea that his passions
detained him at Naples to the neglect of his duty. This is erroneous.
He made Naples his headquarters because he was ordered to do so,
to provide for the safety of the kingdom and to take measures for
the reduction of Malta.” “The point to be observed and insisted on,”
Mr Thursfield says, “is that the whole of this pitiful tragedy belongs
only to the last seven years of Nelson’s life.” He asks, “Why should
the seven years of private lapse be allowed to overshadow the
splendid devotion of a lifetime to public duty?” This authority does
not deny that during the two years following the victory of the Nile
Nelson’s genius “suffered some eclipse,” that his passion for Lady
Hamilton was then “in its first transports, when he seemed tied to
the Court of the Two Sicilies by other bonds than those of duty,
when he annulled the capitulation at Naples and insisted on the trial
40
and execution of Caracciolo, and when he repeatedly disobeyed
the orders of Lord Keith.” He further points out that the period is the
same “during which his mental balance was more or less disturbed
by the wound he had received at the Nile, and his amour-propre was
deeply and justly mortified by the deplorable blunder of the
Admiralty in appointing Lord Keith to the chief command in
succession to Lord St Vincent.” At the time with which we are now
dealing the latter disturbing element was not present, although he
was considerably worried by the appointment of Captain Sir Sidney
Smith as commander of a squadron in the Levant, “within the district
which I had thought under my command.” “The Knight forgets the
respect due to his superior Officer”: Nelson tells Lord St Vincent, “he
has no orders from you to take my Ships away from my command;
but it is all of a piece. Is it to be borne? Pray grant me your
permission to retire, and I hope the Vanguard will be allowed to
convey me and my friends, Sir William and Lady Hamilton, to
England.” Mr Thursfield makes no mention of this vexation, perhaps
because the matter distressed the Admiral less than Lord Keith’s
appointment. On the other hand, Nelson’s correspondence contains
frequent reference to the gratuitous snub, which shows how deeply
the iron had entered into his soul. “I do feel, for I am a man, that it
is impossible for me to serve in these seas, with the Squadron under
a junior Officer:—could I have thought it!—and from Earl Spencer!”
is a typical instance. In the opinion of the same biographer, “the
influence of Lady Hamilton, which ceased only with Nelson’s life,
cannot have been the sole cause, even if it was a contributory
cause, of an attitude and temper of mind which lasted only while
other causes were in operation and disappeared with their cessation.
The evil spirit which beset him, whatever it may have been, had
41
been exorcised for ever by the time that he entered the Sound. ...
Yet the influence of Lady Hamilton was not less potent then and
afterward than it was during the period of eclipse. There are no
letters in the Morrison Collection more passionate than those which
Nelson wrote to Lady Hamilton at this time, none which show more
clearly that, as regards Lady Hamilton, and yet only in that relation,
his mental balance was still more than infirm, his moral fibre utterly
disorganized.”
With this verdict the present writer is in complete accord. Nelson
is to be censured for his moral breach and any neglect of duty which
may be traceable to it, but to condemn him to infamy is to forget his
subsequent career and to consign to the flames many other great
figures of history.
CHAPTER XI

The Neapolitan Rebels and their


French Allies
(1799)

“Speedy rewards and quick punishments are the foundation of


good government.”
Nelson.

I
n the middle of March 1799 Troubridge returned from the
Levant, his command there having been given to Sir Sidney
Smith. Vexatious as was the arrangement to both Nelson and
Lord St Vincent, it had one point of importance in its favour—and
was to have far-reaching results later—in that it enabled the Admiral
to send the trusted captain with several vessels to blockade Naples.
Troubridge was to “seize and get possession” of the islands of
Procida, Ischia, and Capri, to use his influence with the inhabitants
there and elsewhere, “in order to induce them to return to their
allegiance to his Sicilian Majesty, and to take arms to liberate their
Country from French tyranny and oppressive contributions.” On the
3rd April, Troubridge was able to tell Nelson that “All the Ponza
Islands have the Neapolitan flag flying. Your Lordship never beheld
such loyalty; the people are perfectly mad with joy, and are asking
for their beloved Monarch.” That Nelson’s hands were “full,” as he
wrote to his brother, is sufficiently evident. He had become “a
Councillor and Secretary of State,” to use his own words, and his
public correspondence, “besides the business of sixteen Sail of the
Line, and all our commerce, is with Petersburg, Constantinople, the
Consul at Smyrna, Egypt, the Turkish and Russian Admirals, Trieste,
Vienna, Tuscany, Minorca, Earl St Vincent and Lord Spencer.”
Moreover, he was now Commander-in-Chief of the Neapolitan Navy,
and had been promoted to Rear-Admiral of the Red. His health
during this trying period was far from good. He complained to his
friend the Duke of Clarence of being “seriously unwell,” and he told
Lord St Vincent, “I am almost blind and worn out, and cannot, in my
present state, hold out much longer.” He seemed to be growing
more despondent daily, the good news of the success of the Austrian
arms in Italy “does not even cheer me.”

Victory no longer attended the French cause in the northern part


of the peninsula, and the forces of the Republic were to evacuate it
and to join the main French army. On the 7th May, Ferdinand’s
kingdom was relieved of its unwelcome visitors, save only the
garrisons which were left at Capua and Caserta, and at the Castle of
St Elmo. The internal condition of the State, however, was still far
from settled. Commodore Caracciolo, representing the Jacobins,
commanded a miniature fleet in Naples Bay; Cardinal Ruffo led a
nondescript band called by the high-sounding title of “the Christian
Army,” against the Neapolitan republicans, who were in some force.
The unhappy position of the Royal Family at this time is well
described by the Queen in a letter to the Marquise d’Osmond,
mother of the Comtesse de Boigne. It is from the Appendix to the
first volume of the “Recollections” of the last-named that the extract
is taken. The communication is dated from Palermo, the 2nd May
1799.
“We continue to live between hope and dread:” she says, “the
news varies every day. We are expecting help from Russia: if it
comes it will be of the greatest service to us. The English render us
the greatest services. Were it not for them both Sicilies would be
democratised, I should be dead of grief or drowned in the sea, or
else, with my dear family, imprisoned in a castle by our rebellious
subjects. You can read in the gazettes, without my naming them to
you, how many ungrateful subjects we have. It suffices to tell you
that in their writings and their ingratitude they have surpassed their
foster-mother France, but with us the classes are different. Here it is
the class which has the most to lose which is the most violent;
nobles, bishops, monks, ordinary lawyers, but not the high
magistracy, nor the people. The latter are loyal, and show it on every
occasion.... My dear children have behaved like angels in all our
unfortunate circumstances. They suffer every kind of privation they
did not know before, without complaining, out of love for me, so
that I may notice nothing. They are always good-humoured, though
they have no amusements.”
While Troubridge was clearing the way for the return of the royal
exiles to Naples, Nelson received the startling intelligence that the
Brest fleet of nineteen sail-of-the-line had not only escaped but had
been seen off Oporto making for the Mediterranean. So far as it
went, the news was correct enough, but the French ships numbered
twenty-five instead of nineteen. Nelson’s despondency and ill-health
vanished; he lost not an instant in making his arrangements.
Troubridge was recalled from Naples, and the “band of brothers”
were ordered to join Rear-Admiral Duckworth off Port Mahon,
Nelson’s belief being that the first item on the French naval
programme was the recovery of Minorca. Shortly afterwards he
came to think that Sicily was the object of the enemy, whereupon he
cancelled his former instructions and made the island of Maritimo
the rendez-vous. This station he reached on the 23rd May with
seven ships, which he hoped to bring up to sixteen, Duckworth
having decided to wait for Lord St Vincent and not to reinforce
Nelson. Ball, who had been ordered to abandon the blockade of
Malta, had not arrived, and the delay filled the Admiral with anxiety.
“I can only have two queries about him—either that he has gone
round to Messina, imagining that the French Fleet were close to him,
or he is taken. Thus situated,” he writes to Lord St Vincent, “I have
only to remain on the north side of Maritimo, to keep covering
Palermo, which shall be protected to the last, and to wait intelligence
or orders for regulating my further proceedings.
“Your Lordship,” he adds, “may depend that the Squadron under
my command shall never fall into the hands of the Enemy; and
before we are destroyed, I have little doubt but the Enemy will have
their wings so completely clipped that they may be easily overtaken.”
On the 28th May, Nelson heard from the Commander-in-chief
that Bruix and the French fleet had been sighted off Cadiz on the 4th
inst. by Keith’s blockading squadron, the intention being to form a
junction with the Spanish fleet. In reply to Lord St Vincent’s
despatch, Nelson was able to tell his senior officer that “we are
completely on our guard,” that he had determined to go to Palermo
to get provisions and wine for six months, and to hold his vessels “in
momentary readiness to act as you may order or the circumstances
call for. My reason for remaining in Sicily is the covering the blockade
of Naples, and the certainty of preserving Sicily in case of an attack,
for if we were to withdraw our Ships, it would throw such a damp on
the people that I am sure there would be no resistance. But from
the favourable aspect of affairs in Italy, I am sure no attack will be
made here, whilst the French know we have such a force to act
against them. If Captain Ball has not entirely given up the blockade
of Malta, and the poor Islanders have not given up to the French, I
intend to continue the blockade...; for as the danger from your
happy arrival is not so great, I will run the risk of the Ships for a
short time. The Russians will, I am told, be off there in a week or
fortnight. In all this plan I am subject to your Lordship’s more able
judgment. I shall send a Frigate off Cape Corse, in case the French
Fleet should come to be eastward of Corsica, and if I can find a
small craft, one shall be on the west side of Sardinia, but the Bay of
Naples draws me dry.” Two days later, in writing to the same
correspondent to announce the safe arrival of the Vanguard at
Palermo, Nelson makes his usual acknowledgments of the services of
those under his command: “I have our dear Troubridge for my
assistant; in everything we are brothers. Hood and Hallowell are as
active and kind as ever: not that I mean to say any are otherwise;
but you know these are men of resources. Hardy was bred in the old
school, and I can assure you, that I never have been better satisfied
with the real good discipline of a Ship than the Vanguard’s. I hope
from my heart that you will meet the Dons alone: if the two Fleets
join, I am ready, and with some of my Ships in as high order as ever
went to sea.”
As it happened, Keith was able to prevent the junction of the
enemy’s fleets. His position was between them—between “the devil
and the deep sea,” as he termed it. When the look-out frigates of the
French fleet were sighted between Corsica and Genoa, orders were
received from Lord St Vincent for Keith to return to Port Mahon,
which the former thought might be the object of attack. Further
despatches came to hand a little later, urging Keith to proceed to
Minorca. The Commander-in-chief and Keith were really playing at
cross-purposes, for while St Vincent was acting only on supposition,
Keith was in touch with the enemy. It is probable in such a case that
Nelson would have led his squadron into action, but Keith was not
the type of man to risk acting on his own initiative to any great
extent, and left the Frenchmen to proceed to Spezia.
On the 8th June, Nelson vacated the Vanguard, hoisted his flag
on the Foudroyant (80), and was strengthened by the arrival of two
ships from Lord St Vincent’s fleet. He also heard of the impending
resignation of the Commander-in-chief, his indifferent health making
him “literally incapable of any service,” as he afterwards wrote to
Nelson. The unexpected news considerably distressed the Admiral.
He felt sincere admiration and regard for the gallant old sailor, who
had served his King so long and so faithfully, sentiments recorded in
a letter dated from Palermo, the 10th June 1799, as follows:—

“We have a report that you are going home. This


distresses us most exceedingly, and myself in particular; so
much so, that I have serious thoughts of returning, if that
event should take place. But for the sake of our Country, do
not quit us at this serious moment. I wish not to detract from
the merit of whoever may be your successor; but it must take
a length of time, which I hope the war will not give, to be in
any manner a St Vincent. We look up to you, as we have
always found you, as to our Father, under whose fostering
care we have been led to fame. If, my dear Lord, I have any
weight in your friendship, let me entreat you to rouse the
sleeping lion. Give not up a particle of your authority to any
one; be again our St Vincent, and we shall be happy. Your
affectionate
Nelson.”

To the Admiral’s supreme disgust his own claims to the


appointment were disregarded. Lord St Vincent’s command was
given to Lord Keith, who had the additional good fortune to find that
the French fleet was in Vado Bay. Nelson, urged on by Ferdinand and
perhaps by Lady Hamilton, was on his voyage to Naples with a body
of troops to render assistance to the royalists, when two British sail-
of-the-line hove in sight. One of them bore an important despatch
from Keith, to the effect that not only was the enemy at sea but
likely to be bound towards Nelson. The latter immediately returned
to Palermo, disembarked the soldiers and their munitions, and
cruised off Maritimo. Here he hoped to be joined by the Alexander
and Goliath, which he had ordered to proceed from Malta some days
before. Provided they arrived his force would be raised to eighteen
battleships, including three Portuguese—four less than the enemy. “I
shall wait off Maritimo,” he says, in reply to Keith, “anxiously
expecting such a reinforcement as may enable me to go in search of
the Enemy’s fleet, when not one moment shall be lost in bringing
them to battle; for I consider the best defence for his Sicilian
Majesty’s Dominions, is to place myself alongside the French.” No
further ships arrived, and Nelson therefore returned to Palermo.
Keith’s neglect aroused Nelson’s wrath to such an extent, that while
he was at sea he sent a copy of the above letter to the Earl of St
Vincent, complaining that the Commander-in-chief had not sent him
“a force fit to face the Enemy: but, as we are, I shall not get out of
their way; although, as I am, I cannot think myself justified in
exposing the world (I may almost say), to be plundered by these
miscreants. I trust your Lordship will not think me wrong in the
painful determination I conceived myself forced to make, for
agonized indeed was the mind of your Lordship’s faithful and
affectionate servant.”
Mahan remarks that Nelson’s station off Maritimo was
strategically sound, enabling him to intercept the approach of the
enemy “to either Naples or Sicily,” and it was while he was cruising
here that he received a despatch from his former Commander-in-
chief to the effect that Keith was searching for the French, and that
reinforcements were making their way to Port Mahon. Nelson was
convinced that the enemy was steering for Naples. After a brief visit
to the King at Palermo and receiving Sir William and Lady Hamilton
on board the Foudroyant, he sailed for the capital.
On Troubridge’s withdrawal from Naples, the blockade had been
placed in the hands of Captain Foote of the Seahorse, a frigate of
thirty-eight guns, who concerted with Ruffo and his Russian and
Turkish allies to rid the city of the insurgents. Fort St Elmo,
garrisoned by the few remaining French, and the castles of Uovo and
Nuovo, held by the rebels, alone held out. The Cardinal arranged an
armistice with the insurgents, and although there was further
trouble, the matter was patched up and negotiations were again
begun. Subsequently a capitulation was signed on the 23rd June.
Nelson received the news before his squadron anchored in the Bay
of Naples on the following day, and, not knowing the exact terms on
which it had been granted, characterised them as “infamous.”
The main conditions were that the forts Nuovo and Uovo should
be delivered up with their effects; that the troops should keep
possession of the places until the ships which were to be provided
for those who wished to proceed to Toulon were ready to sail; that
the garrisons should march out with the honours of war; that
“Persons and Property, both movable and immovable, of every
individual of the two Garrisons, shall be respected and guaranteed,”
a clause applicable also to prisoners which the allies had made
during the blockade of the forts; and that “All the other hostages
and State prisoners, confined in the two Forts, shall be set at liberty,
immediately after the present Capitulation is signed.” Nelson at once
ordered Foote to haul down the flag of truce flying from the
Seahorse. Sufficient of his story has been told to show that the
Admiral had little or no pity for rebels. So far back as the 6th June,
he had written to Foote that the intelligence sent to him by that
officer of the hanging of thirteen Jacobins “gave us great pleasure,”
and he also expressed the hope that three priests who had been
condemned would “dangle on the tree best adapted to their weight
of sins.” Without further ado he sent a declaration to “the Rebellious
Subjects” in the two forts that “They must surrender themselves to
His Majesty’s Royal mercy,” and addressed a summons to the
Commanding Officer of the French at the Castle of St Elmo, that he
must either accede to the terms made by Ruffo and the Russian
Commander, or “take the consequences, as I shall not agree to any
other.” A paper signed by Nelson and explained to Ruffo, but
rejected by him, announced that “the British Admiral proposes to the
Cardinal to send, in their joint names, to the French and Rebels, that
the arrival of the British fleet has completely destroyed the compact,
as would that of the French if they had had the power (which, thank
God, they have not) to come to Naples.... That as to Rebels and
Traitors, no power on earth has a right to stand between their
gracious King and them: they must instantly throw themselves on
the clemency of their Sovereign, for no other terms will be allowed
them; nor will the French be allowed even to name them in any
capitulation. If these terms are not complied with, in the time ... viz.,
two hours for the French, and instant submission on the part of the
Rebels—such very favourable conditions will never be again offered.”
Nelson knew the man with whom he was dealing, and as the
following characteristic letter to Rear-Admiral Duckworth shows, he
was quite prepared for any eventuality. With insurgents on land and
the possibility of a French fleet at sea in the near vicinity, it was
incumbent on the British Admiral not to run unnecessary risks:—
“As you will believe, the Cardinal and myself have begun our
career by a complete difference of opinion. He will send the Rebels
to Toulon,—I say they shall not go. He thinks one house in Naples
more to be prized than his Sovereign’s honour. Troubridge and Ball
are gone to the Cardinal, for him to read my declaration to the
French and Rebels, whom he persists in calling patriots—what a
prostitution of the word! I shall send Foote to get the Gun-boats
from Procida. I wish the Fleet not to be more than two-thirds of a
cable from each other. I shall send you a sketch of the anchorage, in
forty fathom water. The Foudroyant to be the Van-ship. If the French
fleet should favour us with a visit, I can easily take my station in the
centre.”
The Cardinal positively refused to entertain Nelson’s opinions,
but after some hesitation decided to discuss affairs with him on the
Foudroyant. The interview, which was stormy on both sides and
somewhat protracted, owing to the necessity of employing Lord and
Lady Hamilton as interpreters, took place on the afternoon of the
25th. Both of them held steadfastly to his own point of view. Nelson
therefore wrote that “in his opinion” the Treaty with the rebels
“cannot be carried into execution, without the approbation of his
Sicilian Majesty.”
Uovo and Nuovo were taken possession of by British seamen
under Troubridge on the evening of the 26th inst., and on the
following day, Nelson communicated the fact to the Admiralty,
adding: “This morning I am going to send a detachment under
Captain Troubridge, to cut down the dangerous Tree of Anarchy, and
to burn it before the King’s palace. The moment I can find the City a
little quieted, guns shall be got against St Elmo, when, I am sure,
the French will be glad to surrender.... In my present position, I have
not the smallest alarm should the Enemy favour us with a visit,
inferior as my force is to oppose them.” The castle capitulated on the
12th July 1799, to Nelson’s “brave friend” Troubridge, whose “great
character,” “ability and resources” were duly detailed to Lord Keith,
while the Admiral told Earl Spencer that, “On land the captain of the
Culloden is a first-rate general!” Troubridge’s reward was a
baronetcy, to which no one ever had a clearer title.
Was Nelson justified in cancelling the agreement entered into by
Ruffo and his allies and the enemy? The question has been
discussed with great vehemence and at prodigious length. Mahan’s
opinion is that “his conduct throughout was open and consistent.” He
is convinced that the Admiral acted up to his firm belief “that he not
only had a right to suspend the Capitulation, because, though
signed, it had not been executed, but that it was his bounden duty
so to do; having both legal power and adequate force to prevent its
execution.” Nelson “regarded himself as, and for the time being
actually was, the representative of the King of the Two Sicilies, as
well as the admiral of the British fleet. As representative, he was
charged with the interests and honour of the Sovereign and had
authority over all Neapolitan officials; as admiral, he wielded power
to enforce obedience, if refused. Considering the terms of the
Capitulation to be contrary to the interests and the honour of the
Kingdom, he was under an obligation to prevent their going into
effect, until the King’s decision, becoming known, should supersede
his own discretion.”
Laughton, whose biography of Nelson is much shorter than
Mahan’s, and is therefore not so comprehensive, dismisses the
matter by saying, “it is perfectly well established as the usage of
civilised war that terms granted by a military officer are conditional
on the approval of his superiors, unless he has distinct authority to
negotiate, or the capitulation has been effected wholly or in part. In
the present instance Cardinal Ruffo had not only no authority to
negotiate, but he had express orders from the King not to do so.” By
the fourth Article of the “Instructions to the troops of his Majesty,
ordered to repair to the Bay of Naples,” dated Palermo, June 10th,
1799, “All the military and political operations shall be agreed upon
by the Prince Royal and Admiral Lord Nelson. The opinion of this
latter always to have a preponderance, on account of the respect
due to his experience, as well as to the forces under his command,
which will determine the operations; and also because we are so
deeply indebted to him for the zeal and attachment of which he has
given so many proofs.” By the tenth Article, “The acts of clemency
concerning the noted offenders, and the pardoning of the same, are
reserved for the King, excepting those stipulated in the articles of
capitulation.”

The Execution of Caracciolo


Stephen Reid
About seventy Jacobins were executed for their misdeeds, but
Nelson was only concerned in the death of one of them. Commodore
Francesco Caracciolo, the commander of the Republican Navy, had
previously accompanied the Sicilian Court to Palermo, but when an
edict was issued by the French that the property of all absentees
would be confiscated, he had obtained King Ferdinand’s permission
to return. Marshal Macdonald, then Commander-in-chief of the
French Army of Naples, refers to the matter in his “Recollections.” “I
had resolved,” he writes, “to induce Admiral Caracciolo to take
service in the new fleet; he equipped a flotilla which secured respect
for the port and coasts of Naples, frequently threatened by attempts
of the English, who occupied the islands and were stationed in the
42
roads.” When Caracciolo’s position on sea became untenable, he
sought a safer asylum in one of the forts, whence he eventually fled
to the mountains disguised as a peasant. Here he was discovered
and captured. The refugee was brought on board the Foudroyant on
the morning of the 29th June. Nelson at once instructed Count
Thurn, Commander of the Sicilian frigate La Minerva, who had been
in action with Caracciolo, to assemble five of the senior officers
under his command to inquire if the prisoner were guilty of rebellion
against his lawful Sovereign, and having fired at his Sicilian Majesty’s
colours on board La Minerva. The trial duly took place; the sentence
was death. This was to be carried out “by hanging him at the fore
yard-arm of His Sicilian Majesty’s Frigate La Minerva, under your
command, at five o’clock this evening; and to cause him to hang
there until sunset, when you will have his body cut down, and
thrown into the sea.” Such were Nelson’s instructions, which were
obeyed. Parsons, who had charge of Caracciolo, describes him as “a
short, thick-set man, of apparent strength, but haggard with misery
and want; his clothing in wretched condition, but his countenance
denoting stern resolution to endure that misery like a man.” The
sympathetic narrator persists in calling him “veteran” and “old man.”
The Commodore was only forty-seven years of age, although his
wan appearance may have made him look considerably older. “At
two o’clock in the afternoon,” Parsons adds, “the veteran, with a firm
step, walked into Lord Nelson’s barge, and with a party of thirty of
our seamen, under one of our lieutenants, was taken to his [Count
Thurn’s] flagship, the gun fired, and the brave old man launched into
eternity at the expiration of the two hours from the time the
sentence had passed. The seamen of our fleet, who clustered on the
rigging like bees, consoled themselves that it was only an Italian
prince, and the admiral of Naples, that was hanging—a person of
very light estimation compared with the lowest man in a British ship.
His Majesty of Naples, the Prime Minister, Sir John Acton, and many
of the foreign ambassadors, joined and took up their quarters in the
Foudroyant two days after the execution; and my Lord Nelson
removed to the first lieutenant’s cabin as his sleeping apartment,
giving his cabin to the king’s use, and the larboard side of the
maindeck for his cooks, who condescended to officiate as ours; and
never did midshipmen fare so sumptuously as during the king’s long
stay on board the Foudroyant. The day was passed in administering
justice (Italian fashion) to the wretches who fell into the grasp of
Cardinal Ruffo’s lambs, enlivened by the bombardment of St Elmo,
which we were battering in breach. At noon, dinner was served to
the royal party and their guests on the quarter-deck; Lady
Hamilton’s graceful form bending over her harp, and her heavenly
music gave a gusto to the dessert. As the sun went down, the opera
singers, in a large, decked galley, came alongside, and all that could
delight the ear or please the eye was there to fascinate and charm.”
There is more than a suspicion of irony in the above passage. It
is useful because one can readily believe that it was the point of
view of the majority of the British petty officers and seamen. They
failed to understand why so much deference should be shown to
King Ferdinand and his Queen, who doubtless in their opinion would
have shown more royal qualifications had they remained in their
capital instead of making a hasty flight to Palermo. This is not the
place to discuss the merits and demerits of monarchy and republic,
both of which have their advantages. Certainly the foreign policy of
Great Britain at the end of the eighteenth century did not allow an
ally to be dethroned without making an effort on his behalf.
Southey, when dealing with the execution of Caracciolo, has
seen fit to introduce Nelson’s relations with Lady Hamilton into the
matter, which may be forgiven a man who published his narrative in
1813, when current scandal and gossip were often the chief
“authorities” of the historian. “Doubtless” he remarks, “the British
Admiral seemed to himself to be acting under a rigid sense of
justice, but to all other persons it was obvious that he was
influenced by an infatuated attachment—a baneful passion, which
destroyed his domestic happiness, and now, in a second instance,
stained ineffaceably his public character.” Now Lady Hamilton, as a
matter of actual fact, had nothing whatever to do with the hanging
of the traitor and did not converse with the Admiral during
Caracciolo’s detention. The rebel was tried by those of his own
nationality, and according to Mahan, “there is no ground for
doubting that he (Nelson) had authority to order a court-martial, and
to carry its sentence into execution, nor that Caracciolo came within
the jurisdiction of a court-martial properly constituted.” It is only just
to add, however, that in the opinion of the same eminent authority
there was no real necessity for such undue haste on Nelson’s part.
“He should have remembered that the act would appear to the
world, not as that of the Neapolitan plenipotentiary, but of the
British officer, and that his nation, while liable like others to bursts of
unreasoning savagery, in its normal moods delights to see justice
clothed in orderly forms, unstained by precipitation or suspicion of
perversion, advancing to its ends with the majesty of law, without
unseemly haste, providing things honest in the sight of all men. That
he did not do so, when he could have done so, has been intuitively
felt; and to the instinctive resentment thus aroused among his
countrymen has been due the facility with which the worst has been
too easily believed.”
CHAPTER XII

Nelson in Temporary Command


(1799–1800)

“The great object of the war is—Down, down with the French.”
Nelson.

K
ing Ferdinand was again on board the Foudroyant, holding
his Levées on the quarter-deck, and making himself as
affable as was possible to a man of his morose
temperament. Nelson’s infatuation for the welfare of his Majesty and
his kingdom seemed growing. The castle of St Elmo had fallen,
thereby completing the conquest of Naples, but the Admiral saw fit
to order Troubridge to march against Capua, thereby denuding the
fleet of a thousand men, who were to act in concert with four times
that number of troops. This was done after the receipt of a warning
from Keith that it might be necessary to withdraw the squadron for
the protection of Minorca.

“Should such an order come at this moment,” Nelson writes to


Earl Spencer, “it would be a cause for some consideration whether
Minorca is to be risked, or the two Kingdoms of Naples and Sicily? I
rather think my decision would be to risk the former.” In other
words, Nelson placed the interests of an allied Power before those of
his own country, although of course his services to the Sicilies were
of importance to the latter. One cannot help thinking that there is
more than a suspicion of ulterior motives in what was to lead to a
flagrant disobedience of orders. The letter concludes with the most
affectionate references to Sir William and Lady Hamilton, who were
assuredly his evil genii at the moment. According to Nelson they
were with him to his “great comfort,” without them “it would have
been impossible I could have rendered half the service to his Majesty
which I have now done: their heads and their hearts are equally
great and good.” Writing to Keith on the same day—13th July 1799—
he refers solely to King Ferdinand: “It has been and is my study to
treat his Majesty with all the respect due to so great a personage,
and I have the pleasure to believe that my humble endeavours have
met with the Royal approbation.”
After penning this communication the Admiral received a
despatch from Keith, dated the 27th June, implicitly requiring him
“to send such Ships as you can possibly spare off the Island of
Minorca to wait my orders.” This he acknowledged by saying that “as
soon as the safety of His Sicilian Majesty’s Kingdoms is secured, I
shall not lose one moment in making the detachment you are
pleased to order. At present, under God’s Providence, the safety of
His Sicilian Majesty, and his speedy restoration to his Kingdom,
depends on this Fleet, and the confidence inspired even by the
appearance of our Ships before the City is beyond all belief; and I
have no scruple in declaring my opinion that should any event draw
us from the Kingdom, that if the French remain in any part of it,
disturbances will again arise, for all order having been completely
overturned, it must take a thorough cleansing, and some little time,
to restore tranquillity.” In order to justify his conduct, Nelson next
sent a second note to Earl Spencer. After referring to his previous
letter, which showed that he was prepared for Keith’s order, he adds,
“more than ever is my mind made up, that, at this moment, I will
not part with a single Ship, as I cannot do that without drawing a
hundred and twenty men from each Ship now at the Siege of Capua,
where an Army is gone this day. I am fully aware of the act I have
committed; but, sensible of my loyal intentions, I am prepared for
any fate which may await my disobedience. Capua and Gaeta will
soon fall; and the moment the scoundrels of French are out of this
Kingdom, I shall send eight or nine Ships of the Line to Minorca. I
have done what I thought right; others may think differently; but it
will be my consolation that I have gained a Kingdom, seated a
faithful Ally of his Majesty firmly on his throne, and restored
happiness to millions. Do not think, my dear Lord, that my opinion is
formed from the arrangements of any one. No; be it good, or be it
bad, it is all my own.” The writer concludes with an appeal for Earl
Spencer’s interest with the Board of the Admiralty, which was not
vouchsafed. His having proceeded to the Bay of Naples and of the
operations against the castle of St Elmo were approved, but not of
the land warfare carried on by the seamen against Capua. Their
Lordships did not see “sufficient reason to justify your having
disobeyed the orders you had received from your Commanding-
Officer, or having left Minorca exposed to the risk of being attacked,
without having any Naval force to protect it.”
On the 19th July, Nelson was handed a second urgent despatch
from Keith, ordering him either to leave Sicily and repair to Minorca
with his whole force or to detach the greater part of his squadron
and place it under Duckworth. Keith’s “repeated information” led him
to believe that the enemy was not making for Sicily or Egypt, as had
been thought probable, but for Ireland. Nelson again refused to
obey his Commander-in-chief. Not until the 22nd inst., when Keith
informed Nelson that the French fleet was off Cape Tres Forcas, did
he see fit to dispatch Duckworth with four vessels to Minorca.
The Frenchmen succeeded in joining their Spanish allies at
Cartagena and arriving safely at Brest, from which port they did not
issue for some months, an event which does not therefore concern
us at the moment. Capua and Gaeta eventually surrendered, the
articles of capitulation being signed by Acton and Nelson on behalf
of King Ferdinand on the 31st July 1799, thus liberating “the
Kingdom of Naples from a band of robbers,” as the Admiral informed
Keith.
So far this portion of the narrative has been necessarily confined
to cold, matter-of-fact details. Mention must now be made of the
celebrations held on the first anniversary of the battle of the Nile.
Well might Nelson be fêted on such an occasion; he had served their
Sicilian Majesties all too faithfully. He thus describes the picturesque
scene for the benefit of his wife:—
“Thank God all goes well in Italy, and the Kingdom of Naples is
liberated from thieves and murderers. But still, it has so overthrown
the fabric of a regular Government, that much time and great care
are necessary to keep the Country quiet. The 1st of August was
celebrated here with as much respect as our situation would admit.
The King dined with me; and, when His Majesty drank my health, a
Royal salute of twenty-one guns was fired from all his Sicilian
Majesty’s Ships of War, and from all the Castles. In the evening there
was a general illumination. Amongst other representations, a large
Vessel was fitted out like a Roman galley; on its oars were fixed
lamps, and in the centre was erected a rostral column with my
name: at the stern were elevated two angels supporting my picture.
In short, my dear Fanny, the beauty of the whole is beyond my
powers of description. More than 2000 variegated lamps were
suspended round the Vessel. An orchestra was fitted up, and filled
with the very best musicians and singers. The piece of music was in
a great measure to celebrate my praise, describing their previous
distress, ‘but Nelson came, the invincible Nelson, and they were
preserved, and again made happy.’ This must not make you think me
vain; no, far, very far from it, I relate it more from gratitude than
43
vanity. I return to Palermo with the King to-morrow.”
It was characteristic of Nelson’s fond regard for his father that
when King Ferdinand created him Duke of Bronté, which he believed
would mean an increase of some £3000 a year to his income, he
taxed the estate to the extent of £500 per annum on behalf of the
Rev. Edmund Nelson as “a mark of gratitude to the best of parents.”
Keith being on the look-out for the forty ships of the allied fleets
—for Bruix had been joined by the Spanish fleet at Cartagena as
previously mentioned—the chief command devolved upon Nelson.
Unfortunately Keith was unable to come up with the enemy, who
entered Brest without being brought to battle. He then returned to
England. Nelson hoped that the Lords of the Admiralty would make
his temporary command permanent. Why they failed to do so is not
quite clear. Keith was sent back, and resumed command in the
following January. The situation was a most difficult one for Nelson,
especially as the King of the Two Sicilies invariably showed the white
feather when Nelson wished to conduct him to Naples: “nothing can
move him.” The Admiral’s health was still unsatisfactory. “I am
almost blind, and truly very unwell.” He was worried because the
naval force had been withdrawn from the coast of Italy, worried
about the siege of Malta, and worried by the stupidity of his Russian
and Turkish allies. But he maintained a bold front, and never let the
respective commanders know what he thought of them. Instead, he
wrote the most reassuring messages to everybody, knowing and
appreciating full well the value of optimism.
In September 1799, we find his squadron disposed at six
different points, namely off Alexandria and the coast of Egypt, under
Sir Sidney Smith; off Malta, under the Portuguese Rear-Admiral the
Marquis de Niza; at Palermo; on the coast of Naples and the Roman
coast, under Troubridge; on the north coast of Italy; and blockading
Cadiz and protecting the Straits of Gibraltar, Minorca, etc., which is
sufficient to show that his task was an arduous one. He endeavoured
to stir up enthusiasm in the land forces on behalf of Malta, Civita
Vecchia, and Rome. To Sir James Erskine, at Port Mahon, he wrote
with all the eloquence he could command to incite him to effort:
“The field of glory is a large one, and was never more open to any
one than at this moment to you. Rome would throw open her gates
44
and receive you as a deliverer; and the Pope would owe his
restoration to the Papal Chair to an heretic. This is the first great
object, as it would not only be the complete deliverance of Italy, but
restore peace and tranquillity to the torn-to-pieces Kingdom of
Naples.... The next great object is the reduction of Malta, and in any
other moment than the present, it would be a most important one....
To return to the first object, I can take upon me to say, that our King
would be much gratified that Britain not Austria should re-instate the
Pope. You are at perfect liberty to say this from me; for the world
sees the ambition of Austria, and her eagle wants to extend her
wings from the Adriatic to the Mediterranean. I will not say more,
but that I will support you to the utmost of my abilities.” Succour did
not come from Erskine but from a division of troops sent by the
veteran Russian commander Suwarrow, and, on the 1st October,
Nelson was able to inform the Admiralty of the terms entered into
with the French by Troubridge for the evacuation of Rome and Civita
Vecchia, “on which event I sincerely congratulate their Lordships.”
On the 15th of the same month Nelson sent the “Sketch of my
45
Life,” already remarked upon, to Mr John McArthur of the “Naval
Chronicle,” in which he says that when the terms of capitulation
were signed on board the Culloden, “a prophecy, made to me on my
arrival at Naples, was fulfilled, viz., ‘that I should take Rome with my
Ships.’”
“Thus,” he concludes, “may be exemplified by my Life that
perseverance in my profession will most probably meet its reward.
Without having any inheritance, or being fortunate in prize money, I
have received all the honours of my profession, been created a Peer
of Great Britain, and I may say to thee, reader:

“‘Go thou and do likewise.’”

Nelson’s enthusiasm in the matter of Italy was due partly to the


magnificent series of victories which the armies of the coalition had
won. Alessandria and Mantua had fallen, Moreau had retreated near
Novi, and Tortona had surrendered. So far everything seemed to be
pitched in a major key, but the minor element entered when the
Russians were sent into Switzerland instead of being allowed to
finish their task in Italy. Masséna won the battle of Zurich, thereby
severing the communications between the Austro-Russian forces in
Switzerland and in Italy. In October the intrepid Suwarrow, crossing
the Alps, withdrew his forces to Bavaria for the purpose of taking up
winter quarters, declining to further expose his worn-out troops.
In the same month another and more important event
happened, which was to be far-reaching in its results. On the 9th of
that month Napoleon, having been fortunate enough to escape the
vigilance of British cruisers during his long and tedious voyage from
Alexandria, landed in France. Nelson did not hear the news until the
24th, when he told Sir Sidney Smith, “I have just got a report that
appears to have some foundation, that Buonaparte has passed
Corsica in a Bombard, steering for France. No Crusader ever
returned with more humility—contrast his going in L’Orient, &c., &c.”
Nelson was not on intimate terms with Smith, and was therefore not
likely to relieve his mind “against French villany” as he did to Earl
Spencer: “The great object of the war is—Down, down with the
French!” “If I could have any Cruisers,” he said in another letter, “as
was my plan, off Cape Bon, in Africa, and between Corsica and
Toulon, Mr Buonaparte could not probably have got to France; but if
it bring on a confusion at Paris, I hope it will be for the best.” “I have
regretted sincerely the escape of Buonaparte”; he tells the Earl of
Elgin, British ambassador at Constantinople; “but those Ships which
were destined by me for the two places where he would certainly
have been intercepted, were, from the Admiralty thinking, doubtless,
that the Russians would do something at sea, obliged to be at Malta,
and other services which I thought the Russian Admiral would have
assisted me in—therefore, no blame lays at my door.” Again, “Our
news here is of a civil war in France—Buonaparte against Barras.
May God increase their confusion.”
While Sir Sidney Smith had been eminently successful at the
siege of Acre, which made Napoleon miss his “destiny” and
precluded him from changing “the face of the world,” as he himself
stated, the defeat of the Turks after their disembarkation at Aboukir
in July considerably altered the condition of affairs. Smith and the
Turkish Government were for allowing the French to return to their
native country, an arrangement not at all in accord with Nelson’s
wishes. “I own my hope yet is,” he confesses to the Earl of Elgin,
“that the Sublime Porte will never permit a single Frenchman to quit
Egypt; and I own myself wicked enough to wish them all to die in
that Country they chose to invade. We have scoundrels of French
enough in Europe without them.... I again take the liberty of
repeating that it is contrary to my opinion, allowing a single
Frenchman from Egypt to return during the war to France. It would
[be a] paper I never would subscribe to; but I submit to the better
judgment of men.” To Spencer Smith, Secretary of Embassy,
Constantinople, he says much the same thing: “I cannot bring
myself to believe they would entirely quit Egypt; and, if they would,
I never would consent to one of them returning to the Continent of
Europe during the war. I wish them to perish in Egypt, and give a
great lesson to the world of the justice of the Almighty.” “I would
have kept up a more constant communication with Egypt;” he tells
Keith on the 7th January 1800, “but I have never had the benefit of
small Vessels.” When the Admiral heard of the Convention of El
Arish, concluded by Smith and Kléber—Napoleon’s successor in
Egypt—Nelson was furious. By its terms the army and its munitions
were to be allowed to return to France. Had Nelson been
Commander-in-chief, he would have refused “to ratify any consent or
approbation of Sir Sidney Smith,” and would never “for a moment
have forgot my text—that at all risks of giving offence, not one
Frenchman should be allowed to quit Egypt.” Keith showed a firm
hand when the intelligence reached him. He would consent to “no
Capitulation with the French Army in Egypt, except as prisoners of
war,” and he insisted on the abandoning of all ships and munitions.
Moreover, no troops were to return until they were exchanged. In
due course the British Government consented to the terms which
had been made, although it disapproved of Sir Sidney Smith’s high-
handed policy. On Kléber being informed of the conditions imposed
on him by Keith, he refused to entertain them. Hostilities were
renewed before the receipt of the Order from England confirming
the capitulation, and the negotiations came to nothing.
CHAPTER XIII

Disobedience to Orders

“Pray God we may get alongside of them, the event I leave to


Providence”
Nelson.

M
alta was in a pitiful, half-starved condition. Nelson urged Sir
James Erskine at Mahon, and Brigadier-General Graham
at Messina, to send troops to its relief. They were as
adamant and refused. He was therefore kept “in desperation about
Malta” until General Fox arrived at Minorca and released the garrison
there for the more urgent necessities of the unhappy island. The
Russians upon whom the Admiral had also depended were sent
elsewhere in pursuance of the Czar’s plan to withdraw from the
enfeebled coalition.

The Portuguese having withdrawn their ships from the blockade,


it was eminently necessary to fill their place, especially as it was
understood that a French squadron was likely to be sent to the relief
of the beleaguered. Keith was back at his post in January 1800, and
was off Leghorn with Nelson on the 20th of that month. After
proceeding to Palermo they both went to Malta, where the exciting
news was received that the enemy had not only left port but had
been seen off the west end of Sicily.
The Commander-in-chief remained at Malta ready to give the
Frenchmen a warm welcome should they come his way; Nelson was
dispatched to capture the Republican squadron. This consisted of
the famous Généreux, the 74-gun ship, which had escaped after the
battle of the Nile, three corvettes, and an armed store-ship. The
Admiral had three sail-of-the-line at his service, when he came up
with Rear-Admiral Perrée on the 18th February 1800, but the chase
had already been started by the Alexander, which happened to be
cruising near. The French store-ship struck her tricoloured ensign
after a few shots had been fired, and was promptly secured. The
Généreux was then raked with several broadsides by the Success
frigate, a compliment returned by the Frenchman to the
disadvantage of the British crew, of which one man was killed and
the Master and seven men wounded. When the Foudroyant and the
Northumberland approached, and began to fight in real earnest, the
enemy’s flagship fired her broadside and surrendered. The corvettes
made good their escape. Perrée died of his wounds on the following
day. His flag was sent by the Admiral to Leopold, Prince of Salerno,
through Sir John Acton, who described King Ferdinand’s son as being
“in raptures” at the present.
On the 24th, the blockade of Malta was entrusted to Nelson by
Keith, the Commander-in-chief sailing for Genoa to assist the
Austrians in the siege of that place, which eventually fell in the first
week of the following June. The position was an ignominious one
from Nelson’s point of view, as his letters testify. He told his superior
that “Without some rest, I am gone,” and that he was “absolutely
exhausted.” In referring to Keith in a note to Lord Minto he
underlines “my Commander-in-chief,” for a reason which is fairly
obvious. “Ought I to trust Dame Fortune any more?” he asks, “her
daughter may wish to step in and tear the mother from me. I have
in truth serious thoughts of giving up active service—Greenwich
Hospital seems a fit retreat for me after being evidently thought
unfit to command in the Mediterranean.” “We of the Nile are not
equal to Lord Keith in his (Acton’s) estimation, and ought to think it
an honour to serve under such a clever man,” he tells Troubridge. “I
can say little good of myself: I am far from well”; “My state of health
is very precarious. Two days ago I dropped with a pain in my heart,
and I am always in a fever”; “my very ill state of health”; “I believe I
am almost finished,” are passages to be found in his correspondence
at this period. He informed Keith that his health was “so very
indifferent,” that he was obliged “in justice to myself, to retire to
Palermo for a few weeks, and to direct Troubridge to carry on the
service during my necessary absence. I shall quit this station when
matters are all put in a right way.”
Troubridge heard of Nelson’s decision with unfeigned sorrow. “I
beseech you,” he says in a note of such sincere regard and affection
that it is worthy of place in any “Life of Nelson,” “hear the entreaties
of a sincere friend, and do not go to Sicily for the present.”
Nelson paid no heed to the warning, and proceeded to Palermo.
While returning to Malta the Foudroyant was able to render
assistance to the Penelope (36) frigate, which was following the
Guillaume Tell (86) in much the same way as a sturdy little terrier
sometimes follows a much larger dog. After some hours the Lion
(64) came up, followed by the Foudroyant. The Guillaume Tell—the
sole remaining sail-of-the-line which had escaped at the Nile—was
endeavouring to break the blockade of Valetta, but the time had
come for her last fight with the undaunted foe. She surrendered
after a splendid resistance on Sunday morning, the 30th March, and
was towed in a very crippled and dismasted state to Syracuse. In
due course she was refitted and rendered good service in the British
navy as the Malta. Rear-Admiral Decrès was wounded and taken
prisoner, and some 200 of the 1220 men on his flagship were either
killed or rendered hors de combat.
Sir Edward Berry, who commanded the Foudroyant, wrote a
hasty letter giving Nelson a few particulars. “I had but one wish this
morning—it was for you,” is the opening sentence, “How we prayed
for you, God knows, and your sincere and faithful friend,” are the
concluding words. Could better evidence be produced of the love
which animated Nelson and his “band of brothers”? “My task is
done, my health is lost, and the orders of the great Earl of St
Vincent are completely fulfilled—thanks, ten thousand thanks, to my
brave friends!” Thus he wrote to Berry on the 5th April 1800, and on
the following day he made similar remarks to Lord Minto: “Our dear
great Earl of St Vincent’s orders to me were to follow the French
Mediterranean fleet, and to annihilate them: it has been done,
thanks to the zeal and bravery of my gallant friends! My task is
done, my health lost, and I have wrote to Lord Keith for my retreat.
May all orders be as punctually obeyed, but never again an Officer at
the close, of what I must, without being thought vain, (for such I am
represented by my enemies,) call a glorious career, be so treated! I
go with our dear friends Sir William and Lady Hamilton; but whether
by water or land depends on the will of Lord Keith.” Again and again
Nelson refers to the prowess of his comrades in arms. “The happy
capture of the William Tell,” he writes to the Capitan Pacha, “is the
finish to the whole French fleet, which my Royal Master desired me
to destroy. Having, by the bravery of the Officers and Men under my
command, accomplished my task, I am going to England for the
benefit of my health; but I can assure you, and beg of your
Excellency to assure the Grand Signior of the same, that should the
Enemy again send a Naval force to attack his Dominions, I shall hold
myself ready to come forth again for their destruction.” To the
Caimakan Pacha he says, “It was my orders, in May 1798, to destroy
the French Mediterranean fleet. By the happy capture of the
Généreux and William Tell, (the last on the 30th March,) thanks to
the Almighty, and the bravery of the Officers and Men under my
command, all, all, are taken, burnt, or sunk. Of the thirteen Sail of
the Line, not one remains; and I trust that very soon the same may
be told of their Army, who dared to land on the Territory of the
Sublime Porte. Perish all the enemies of his Imperial Majesty the
Grand Signior! Having completely obeyed my orders, with great
injury to my health, I am going to England for the benefit of it.” He
adds that he will not fail his ally, should another French fleet menace
the Turkish dominions. “I shall hold myself ready, if I am thought fit
for such a service, to come forth, and be the instrument of God’s
vengeance on such miscreant infernal scoundrels.” He writes to Earl
Spencer, enclosing Berry’s account of the capture of the French
battleship, and assures himself that his Lordship “will not be sparing
of promotion to the deserving. My friends wished me to be present.
I have no such wish; for a something might have been given me,
which now cannot. Not for all the world would I rob any man of a
sprig of laurel—much less my children of the Foudroyant! I love her
as a fond father, a darling child, and glory in her deeds. I am vain
enough to feel the effects of my school. Lord Keith sending me
nothing, I have not, of course, a free communication. I have wrote
to him for permission to return to England, when you will see a
broken-hearted man.... My complaint, which is principally a swelling
of the heart, is at times alarming to my friends....” “My mind is fixed
for retreat at this moment,” he informs “fighting Berry.” “Assure all
the Foudroyants of my sincere regard and affection for them. They
may depend upon me.” “I glory in them, my darling children, served
in my school, and all of us caught our professional zeal and fire from
the great and good Earl of St Vincent”—thus he writes to Keith.
None of his hundreds of letters more fully reveals the charming
nature of the man, than those quoted above. While Nelson was fond
enough of glory for himself, he was too large-hearted to deprive
others of it.
We have now to return to his unhappy and miscalculated
transactions with the people whom he served not wisely but too
well, to show him again “a vehement partisan of the Court of
Naples,” as Judge O’Connor Morris expresses it. “I purpose going in
the Foudroyant,” he tells Keith, on the 12th May, “in a few days, to
Palermo, as I am under an old promise to her Sicilian Majesty, that
whenever she returned to the Continent, I would escort her over.
Her Majesty has now made application to me for that purpose; and,
as it may be necessary to take another Ship for the escort, I purpose
taking the Alexander with me.” It is clear that Nelson had no right to
enter into any such arrangement, especially as there were too few
rather than too many ships for the blockade of Malta. Before Keith’s
despatch was received forbidding Nelson to use the vessels, the
Admiral had left Malta for Palermo, which he reached on the 31st
May. But he did get a despatch ordering him to take the ships then
at Leghorn to Spezia, which Nelson only partly obeyed, and
stationed himself at the former port to await the convenience of the
Queen and family. There he was met on the 24th June by his
Commander-in-chief, whose feelings may be gauged by his letter to
the Hon. A. Paget, Sir William Hamilton’s successor as Envoy
Extraordinary and Minister Plenipotentiary to the King of the Two
Sicilies. It was written at Leghorn on the 16th July, two days after
the disastrous defeat of the Austrians by Napoleon at Marengo.
He says: “I was so displeased by the withdrawing of the Ships
from before Malta, and with other proceedings that Her Majesty did
not take any notice of me latterally which had no effect on my
attention to Her Rank, what a Clamour to letting in the Ships to
Malta will occasion I assure you nothing has given me more real
46
concern it was so near exhausted.” “The Paget Papers” make it
quite clear that Queen Caroline did not go out of her way to impress
Keith, but rather exhibited a fondness for snubbing him. He writes to
Paget on another occasion to the effect that “the Queen expected
the Whole Squadron to attend on Her Court which was impossible a
Riot happened in the Square the Queen desired I would go to the
people, I declined having no Authority to do so and disapproving of
all tumults on every pretence in short Her Majesty took leave of
47
Every one in Public but me....” An extremely important letter will
also be found in the same collection of documents which sheds
much light on the personalities of the Royal folk with whom Nelson
had so much to do in this phase of his career. Paget is writing to
Lord Grenville, Secretary of State for Foreign Affairs:
“The King, whose real character has from circumstances shown
itself during and since the revolution more than at any former
period, is timid and bigoted and, as is often the case in the same
disposition, cruel and revengeful. He has no natural turn for, nor do
his habits allow him to attend to business. He has no guide for his
Conduct but that of private consideration, and to take the present
Instance, whatever plea he may set forth for delaying his return to

You might also like