100% found this document useful (4 votes)
295 views

Java Software Solutions Global Edition John Lewis All Chapter Instant Download

ebook

Uploaded by

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

Java Software Solutions Global Edition John Lewis All Chapter Instant Download

ebook

Uploaded by

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

Full download ebook at ebookgate.

com

Java Software Solutions Global Edition John


Lewis

https://ebookgate.com/product/java-software-
solutions-global-edition-john-lewis/

Download more ebook from https://ebookgate.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Java Software Structures Designing and Using Data


Structures 3rd Edition John Lewis

https://ebookgate.com/product/java-software-structures-designing-
and-using-data-structures-3rd-edition-john-lewis/

Java Foundations Introduction to Program Design and


Data Structures 2nd Edition John Lewis

https://ebookgate.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-john-lewis/

Java Security Solutions 1st Edition Helton

https://ebookgate.com/product/java-security-solutions-1st-
edition-helton/

Software Solutions for Rapid Prototyping 1st Edition


Ian Gibson

https://ebookgate.com/product/software-solutions-for-rapid-
prototyping-1st-edition-ian-gibson/
Software Testing and Continuous Quality Improvement 2nd
ed Edition William E. Lewis

https://ebookgate.com/product/software-testing-and-continuous-
quality-improvement-2nd-ed-edition-william-e-lewis/

On Grand Strategy 1st Edition John Lewis Gaddis

https://ebookgate.com/product/on-grand-strategy-1st-edition-john-
lewis-gaddis/

Writing compilers and interpreters software engineering


approach using Java 3. udg Edition Mak

https://ebookgate.com/product/writing-compilers-and-interpreters-
software-engineering-approach-using-java-3-udg-edition-mak/

Raspberry Pi Cookbook Software and Hardware Problems


and Solutions 2nd Edition Monk

https://ebookgate.com/product/raspberry-pi-cookbook-software-and-
hardware-problems-and-solutions-2nd-edition-monk/

Software engineering measurement 1st Edition John C.


Munson Ph.D.

https://ebookgate.com/product/software-engineering-
measurement-1st-edition-john-c-munson-ph-d/
gLobaL
ediTion

Java Software Solutions


Foundations of Program Design
eighTh ediTion

John Lewis • William Loftus


java
TM
Eighth Edition

SOFTWARE SOLUTIONS

FOUNDATIONS OF PROGRAM DESIGN


Global Edition

JOHN LEWIS
Virginia Tech

WILLIAM LOFTUS
Accenture

Global Edition contributions by
Mohit Tahiliani
NITK Surathkal

Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Editorial Director: Marcia Horton Manufacturing Buyer: Lisa McDowell
Editor-in-Chief: Michael Hirsch Art Director: Linda Knowles
Editorial Assistant: Stephanie Sellinger Cover Designer: Shree Mohanambal
Vice President, Marketing: Patrice Jones Inbakumar/Lumina
Marketing Manager: Yezan Alayan Datamatics, Inc.
Marketing Coordinator: Kathryn Ferranti Image Permission Coordinator: Rita Wenning
Vice President, Production: Vince O’Brien Cover Photograph: Eugene Sergeev/Shutterstock
Managing Editor: Jeff Holcomb Media Editor: Daniel Sandin
Production Project Manager: Marilyn Lloyd Media Project Manager: Wanda Rockwell
Head, Learning Asset Full-Service Project Management: Harleen Chopra, Cenveo®
Acquisition, Global Edition: Laura Dent Publisher Services
Acquisitions Editor, Global Edition: Karthik Subramaniun Composition: Cenveo Publisher Services
Project Editor, Global Edition: Anuprova Dey Printer/Binder: Courier Kendallville
Chowdhuri. Cover Printer: Courier Kendallville
Senior Operations Supervisor: Alan Fischer Text Font: Sabon LT Std

Pearson Education Limited


Edinburgh Gate
Harlow
Essex CM20 2JE
England
and Associated Companies throughout the world
Visit us on the World Wide Web at:
www.pearsonglobaleditions.com
© Pearson Education Limited 2015
The rights of John Lewis and William Loftus to be identified as the authors of this work have been asserted by them in
accordance with the Copyright, Designs and Patents Act 1988.
Authorized adaptation from the United States edition, entitled Java Software Solutions: Foundations Of Program Design, 8th
edition, ISBN 978-0-13-359495-9, by John Lewis and William Loftus, published by Pearson Education © 2015.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmittedin any form or
by any means, electronic, mechanical, photocopying, recording or otherwise, withouteither the prior written permission of
the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd,
Saffron House, 6–10 Kirby Street, LondonEC1N 8TS.
All trademarks used herein are the property of their respective owners.The use of any trademark in this text does not vest in
the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any
affiliation with or endorsement of this book by such owners.
Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear below,
or on appropriate page within text.

Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This
book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
Typeset in 8 Sabon LT Std by Cenveo Publishing Services
Printed and bound by Courier Kendallville
The publisher’s policy is to use paper manufactured from sustainable forests.

10 9 8 7 6 5 4 3 2 1—DOC—14 13 12 11 10

ISBN 10: 1292018232


ISBN 13: 978-1-29-201823-2 (Print)
ISBN 13: 978-1-29-206977-7 (PDF)
This book is dedicated to our families.
Sharon, Justin, Kayla, Nathan, and Samantha Lewis
and
Veena, Isaac, and Dévi Loftus
This page is intentionally left blank.
Preface
Welcome to the Eighth Edition of Java Software Solutions: Foundations of
Program Design. We are pleased that this book has served the needs of so many
students and faculty over the years. This edition has been tailored further to
improve the coverage of topics key to introductory computing.

New to This Edition


The biggest updates to this edition include the following:
■ Updated all graphical screen shots.
■ Added additional screen shots to show interface options.
■ Revised end-of-chapter exercises and programming projects.
■ Revised all code for consistent spacing issues.
■ Improved discussions of Java translation, text file I/O, and other topics.
Feedback from both instructors and students continues to make it clear that we
have hit the mark with the overall vision of the book. The emphasis remains on
presenting underlying core concepts in a clear and gradual manner. The Graphics
Track sections in each chapter still segregate the coverage of graphics and graphi-
cal user interfaces, giving extreme flexibility in how that material gets covered.
The casual writing style and entertaining examples still rule the day.
The displays of screen shots for graphics-based programs, including programs with
graphical user interfaces, have all been updated. The previous versions were dated in
terms of the look-and-feel. We also updated some as needed to improve pedagogy.
On some graphics programs, we added additional screen shots in situations
where it was beneficial to see how the program window looks under different
situations or window sizes.
We also focused on the end-of-chapter exercises and programming projects in
this revision. We added, subtracted, and modified these to provide an appropriate
and updated set.
Throughout the book, the examples had become inconsistent in some issues
related to the use of white space. We carefully went through each example and
code fragment to ensure that a consistent and appropriate style was applied.
Finally, as always, we improved discussions throughout the book, sometimes
in minor ways, and a few include significant improvements. In particular, the
discussion of Java translation was updated in Chapter 1 and throughout to focus
5
6 prEfacE

on term JVM rather than the less helpful term interpreter. The figure related to
the translation process was also updated. The text file I/O discussion was also
updated, along with its example.

cornerstones of the Text


This text is based on the following basic ideas that we believe make for a sound
introductory text:
■ True object-orientation. A text that really teaches a solid object-oriented
approach must use what we call object-speak. That is, all processing should
be discussed in object-oriented terms. That does not mean, however, that
the first program a student sees must discuss the writing of multiple classes
and methods. A student should learn to use objects before learning to write
them. This text uses a natural progression that culminates in the ability to
design real object-oriented solutions.
■ Sound programming practices. Students should not be taught how to
program; they should be taught how to write good software. There’s a
difference. Writing software is not a set of cookbook actions, and a good
program is more than a collection of statements. This text integrates
practices that serve as the foundation of good programming skills. These
practices are used in all examples and are reinforced in the discussions.
Students learn how to solve problems as well as how to implement solu-
tions. We introduce and integrate basic software engineering techniques
throughout the text. The Software Failure vignettes reiterate these lessons
by demonstrating the perils of not following these sound practices.
■ Examples. Students learn by example. This text is filled with fully
implemented examples that demonstrate specific concepts. We have
intertwined small, readily understandable examples with larger, more
realistic ones. There is a balance between graphics and nongraphics programs.
The VideoNotes provide additional examples in a live presentation format.
■ Graphics and GUIs. Graphics can be a great motivator for students, and
their use can serve as excellent examples of object-orientation. As such,
we use them throughout the text in a well-defined set of sections that we
call the Graphics Track. This coverage includes the use of event processing
and GUIs. Students learn to build GUIs in the appropriate way by using a
natural progression of topics. The Graphics Track can be avoided entirely
for those who do not choose to use graphics.

chapter Breakdown
Chapter 1 (Introduction) introduces computer systems in general, including basic
architecture and hardware, networking, programming, and language translation.
Java is introduced in this chapter, and the basics of general program development,
prEfacE 7

as well as object-oriented programming, are discussed. This chapter contains


broad introductory material that can be covered while students become familiar
with their development environment.
Chapter 2 (Data and Expressions) explores some of the basic types of data used
in a Java program and the use of expressions to perform calculations. It discusses
the conversion of data from one type to another and how to read input interac-
tively from the user with the help of the standard Scanner class.
Chapter 3 (Using Classes and Objects) explores the use of predefined classes
and the objects that can be created from them. Classes and objects are used to
manipulate character strings, produce random numbers, perform complex calcu-
lations, and format output. Enumerated types are also discussed.
Chapter 4 (Writing Classes) explores the basic issues related to writing classes
and methods. Topics include instance data, visibility, scope, method parameters,
and return types. Encapsulation and constructors are covered as well. Some of the
more involved topics are deferred to or revisited in Chapter 6.
Chapter 5 (Conditionals and Loops) covers the use of boolean expressions to
make decisions. Then the if statement and while loop are explored in detail.
Once loops are established, the concept of an iterator is introduced and the
Scanner class is revisited for additional input parsing and the reading of text files.
Finally, the ArrayList class introduced, which provides the option for managing
a large number of objects.
Chapter 6 (More Conditionals and Loops) examines the rest of Java’s condi-
tional (switch) and loop (do, for) statements. All related statements for condi-
tionals and loops are discussed, including the enhanced version of the for loop.
The for-each loop is also used to process iterators and ArrayList objects.
Chapter 7 (Object-Oriented Design) reinforces and extends the coverage of issues
related to the design of classes. Techniques for identifying the classes and objects
needed for a problem and the relationships among them are discussed. This chap-
ter also covers static class members, interfaces, and the design of enumerated type
classes. Method design issues and method overloading are also discussed.
Chapter 8 (Arrays) contains extensive coverage of arrays and array processing.
The nature of an array as a low-level programming structure is contrasted to the
higher-level object management approach. Additional topics include command-
line arguments, variable length parameter lists, and multidimensional arrays.
Chapter 9 (Inheritance) covers class derivations and associated concepts such
as class hierarchies, overriding, and visibility. Strong emphasis is put on the
proper use of inheritance and its role in software design.
Chapter 10 (Polymorphism) explores the concept of binding and how it relates
to polymorphism. Then we examine how polymorphic references can be accom-
plished using either inheritance or interfaces. Sorting is used as an example of
polymorphism. Design issues related to polymorphism are examined as well.
8 prEfacE

Chapter 11 (Exceptions) explores the class hierarchy from the Java standard
library used to define exceptions, as well as the ability to define our own excep-
tion objects. We also discuss the use of exceptions when dealing with input and
output and examine an example that writes a text file.
Chapter 12 (Recursion) covers the concept, implementation, and proper use of
recursion. Several examples from various domains are used to demonstrate how
recursive techniques make certain types of processing elegant.
Chapter 13 (Collections) introduces the idea of a collection and its underlying
data structure. Abstraction is revisited in this context and the classic data struc-
tures are explored. Generic types are introduced as well. This chapter serves as an
introduction to a CS2 course.

Supplements
Student Online resources
These student resources can be accessed at the book’s Companion Website,
www.pearsonglobaleditions.com/lewis:
■ Source Code for all the programs in the text
■ Links to Java development environments
■ VideoNotes: short step-by-step videos demonstrating how to solve prob-
lems from design through coding. VideoNotes allow for self-paced
instruction with easy navigation including the ability to select, play, re-
wind, fast-forward, and stop within each VideoNote exercise. Margin icons
in your textbook let you know when a VideoNote video is available for a
particular concept or homework problem.

Instructor resources
The following supplements are available to qualified instructors only. Visit the
Pearson Education Instructor Resource Center www.pearsonglobaleditions.com/
lewis for information on how to access them:
■ Presentation Slides—in PowerPoint.
■ Solutions—includes solutions to exercises and programming projects.
■ Test Bank with powerful test generator software—includes a wealth of free
response, multiple-choice, and true/false type questions.
■ Lab Manual—lab exercises are designed to accompany the topic
progression in the text.
prEfacE 9

features
Key concepts. Throughout the text, the Key Concept boxes highlight funda-
mental ideas and important guidelines. These concepts are summarized at the
end of each chapter.
Listings. All programming examples are presented in clearly labeled listings, fol-
lowed by the program output, a sample run, or screen shot display as appropri-
ate. The code is colored to visually distinguish comments and reserved words.
Syntax Diagrams. At appropriate points in the text, syntactic elements of the
Java language are discussed in special highlighted sections with diagrams that
clearly identify the valid forms for a statement or construct. Syntax diagrams for
the entire Java language are presented in Appendix L.
Graphics Track. All processing that involves graphics and graphical user inter-
faces is discussed in one or two sections at the end of each chapter that we col-
lectively refer to as the Graphics Track. This material can be skipped without loss
of continuity, or focused on specifically as desired. The material in any Graphics
Track section relates to the main topics of the chapter in which it is found.
Graphics Track sections are indicated by a brown border on the edge of the page.
Summary of Key concepts. The Key Concepts presented throughout a chap-
ter are summarized at the end of the chapter.
Self-review Questions and answers. These short-answer questions review
the fundamental ideas and terms established in the preceding section. They are
designed to allow students to assess their own basic grasp of the material. The
answers to these questions can be found at the end of the book in Appendix N.
Exercises. These intermediate problems require computations, the analysis or
writing of code fragments, and a thorough grasp of the chapter content. While the
exercises may deal with code, they generally do not require any online activity.
programming projects. These problems require the design and implementation
of Java programs. They vary widely in level of difficulty.
VideoNotes. Presented by the author, VideoNotes explain topics visually through
informal videos in an easy-to-follow format, giving students the extra help they need
to grasp important concepts. Look for this VideoNote icon to see which in-chapter
topics and end-of-chapter Programming Projects are available as VideoNotes.
Software failures. These between-chapter vignettes discuss real-world flaws in
software design, encouraging students to adopt sound design practices from the
beginning.

acknowledgments
I am most grateful to the faculty and students from around the world who have
provided their feedback on previous editions of this book. I am pleased to see
10 prEfacE

the depth of the faculty’s concern for their students and the students’ thirst for
knowledge. Your comments and questions are always welcome.
I am particularly thankful for the assistance, insight, and attention to detail
of Robert Burton from Brigham Young University. For years, Robert has con-
sistently provided valuable feedback that helps shape and evolve this textbook.
Brian Fraser of Simon Fraser University also has recently provided some excel-
lent feedback that helped clarify some issues in this edition. Such interaction with
computing educators is incredibly valuable.
I also want to thank Dan Joyce from Villanova University, who developed the
Self-Review questions, ensuring that each relevant topic had enough review mate-
rial, as well as developing the answers to each.
I continue to be amazed at the talent and effort demonstrated by the team at
Pearson. Matt Goldstein, our editor, has amazing insight and commitment. His
assistant, Kelsey Loanes, is a source of consistent and helpful support. Marketing
Manager Yez Alayan makes sure that instructors understand the pedagogical advan-
tages of the text. The cover was designed by the skilled talents of Joyce Wells. Scott
Disanno, Marilyn Lloyd, and Kayla Smith-Tarbox led the production effort. The
Addison-Wesley folks were supported by a phenomenal team at Cenveo Publisher
Services including Jerilyn Bockorick for the interior design and Harleen Chopra
for project management. We thank all of these people for ensuring that this book
meets the highest quality standards.
Special thanks go to the following people who provided valuable advice to us
about this book via their participation in focus groups, interviews, and reviews.
They, as well as many other instructors and friends, have provided valuable feed-
back. They include:

Elizabeth Adams James Madison University


Hossein Assadipour Rutgers University
David Atkins University of Oregon
Lewis Barnett University of Richmond
Thomas W. Bennet Mississippi College
Gian Mario Besana DePaul University
Hans-Peter Bischof Rochester Institute of Technology
Don Braffitt Radford University
Robert Burton Brigham Young University
John Chandler Oklahoma State University
Robert Cohen University of Massachusetts, Boston
Dodi Coreson Linn Benton Community College
James H. Cross II Auburn University
Eman El-Sheikh University of West Florida
Sherif Elfayoumy University of North Florida
prEfacE 11

Christopher Eliot University of Massachusetts, Amherst


Wanda M. Eanes Macon State College
Stephanie Elzer Millersville University
Matt Evett Eastern Michigan University
Marj Feroe Delaware County Community College, Pennsylvania
John Gauch University of Kansas
Chris Haynes Indiana University
James Heliotis Rochester Institute of Technology
Laurie Hendren McGill University
Mike Higgs Austin College
Stephen Hughes Roanoke College
Daniel Joyce Villanova University
Saroja Kanchi Kettering University
Gregory Kapfhammer Allegheny College
Karen Kluge Dartmouth College
Jason Levy University of Hawaii
Peter MacKenzie McGill University
Jerry Marsh Oakland University
Blayne Mayfield Oklahoma State University
Gheorghe Muresan Rutgers University
Laurie Murphy Pacific Lutheran University
Dave Musicant Carleton College
Faye Navabi-Tadayon Arizona State University
Lawrence Osborne Lamar University
Barry Pollack City College of San Francisco
B. Ravikumar University of Rhode Island
David Riley University of Wisconsin (La Crosse)
Bob Roos Allegheny College
Carolyn Rosiene University of Hartford
Jerry Ross Lane Community College
Patricia Roth Southeastern Polytechnic State University
Carolyn Schauble Colorado State University
Arjit Sengupta Georgia State University
Bennet Setzer Kennesaw State University
Vijay Srinivasan JavaSoft, Sun Microsystems, Inc.
Stuart Steiner Eastern Washington University
Katherine St. John Lehman College, CUNY
Alexander Stoytchev Iowa State University
Ed Timmerman University of Maryland, University College
Shengru Tu University of New Orleans
Paul Tymann Rochester Institute of Technology
John J. Wegis JavaSoft, Sun Microsystems, Inc.
12 prEfacE

Ken Williams North Carolina Agricultural and Technical University


Linda Wilson Dartmouth College
David Wittenberg Brandeis University
Wang-Chan Wong California State University (Dominguez Hills)

Thanks also go to my friends and former colleagues at Villanova University


who have provided so much wonderful feedback. They include Bob Beck, Cathy
Helwig, Anany Levitin, Najib Nadi, Beth Taddei, and Barbara Zimmerman.
Special thanks go to Pete DePasquale of The College of New Jersey for the
design and evolution of the PaintBox project, as well as the original Java Class
Library appendix.
Many other people have helped in various ways. They include Ken Arnold,
Mike Czepiel, John Loftus, Sebastian Niezgoda, and Saverio Perugini. Our apolo-
gies to anyone we may have omitted.
The ACM Special Interest Group on Computer Science Education (SIGCSE) is a
tremendous resource. Their conferences provide an opportunity for educators from
all levels and all types of schools to share ideas and materials. If you are an educator
in any area of computing and are not involved with SIGCSE, you’re missing out.
Pearson Education wishes to thank Arup Bhattacharjee, Soumen Mukherjee and
Raghavan for reviewing the Global Edition.
Contents

preface 5

chapter 1 Introduction 27

1.1 computer processing 28


Software Categories 29
Digital Computers 31
Binary Numbers 33

1.2 Hardware components 36


Computer Architecture 37
Input/Output Devices 38
Main Memory and Secondary Memory 39
The Central Processing Unit 43

1.3 Networks 46
Network Connections 46
Local-Area Networks and
Wide-Area Networks 48
The Internet 49
The World Wide Web 50
Uniform Resource Locators 51

1.4 The Java programming Language 52


A Java Program 54
Comments 56
Identifiers and Reserved Words 57
White Space 60

1.5 program Development 62


Programming Language Levels 62
Editors, Compilers, and Interpreters 65
Development Environments 66
Syntax and Semantics 67
Errors 68

13
14 cONTENTS

1.6 Object-Oriented programming 70


Problem Solving 71
Object-Oriented Software Principles 72

chapter 2 Data and Expressions 83

2.1 character Strings 84


The print and println Methods 84
String Concatenation 86
Escape Sequences 89
2.2 Variables and assignment 91
Variables 91
The Assignment Statement 93
Constants 95
2.3 primitive Data Types 97
Integers and Floating Points 97
Characters 99
Booleans 100
2.4 Expressions 101
Arithmetic Operators 101
Operator Precedence 102
Increment and Decrement Operators 106
Assignment Operators 107
2.5 Data conversion 109
Conversion Techniques 111
2.6 Interactive programs 113
The Scanner Class 113
2.7 Graphics 118
Coordinate Systems 118
Representing Color 120
2.8 applets 121
Executing Applets Using the Web 124
2.9 Drawing Shapes 125
The Graphics Class 125
Software failure:
NASA Mars Climate Orbiter
and Polar Lander 137
cONTENTS 15

chapter 3 Using classes and Objects 139

3.1 creating Objects 140


Aliases 142

3.2 The String class 144

3.3 packages 148


The import Declaration 150

3.4 The Random class 152

3.5 The Math class 155

3.6 formatting Output 158


The NumberFormat Class 158
The DecimalFormat Class 160
The printf Method 161

3.7 Enumerated Types 164

3.8 Wrapper classes 167


Autoboxing 169

3.9 components and containers 169


Frames and Panels 170

3.10 Nested panels 174

3.11 Images 177

chapter 4 Writing classes 185

4.1 classes and Objects revisited 186

4.2 anatomy of a class 188


Instance Data 193
UML Class Diagrams 193

4.3 Encapsulation 195


Visibility Modifiers 196
Accessors and Mutators 197

4.4 anatomy of a Method 198


The return Statement 200
Parameters 201
16 cONTENTS

Local Data 201


Bank Account Example 202

4.5 constructors revisited 207

4.6 Graphical Objects 208

4.7 Graphical User Interfaces 217

4.8 Buttons 218

4.9 Text fields 222

Software failure:
Denver Airport Baggage
Handling System 231

chapter 5 conditionals and Loops 233

5.1 Boolean Expressions 234


Equality and Relational Operators 235
Logical Operators 236
5.2 The if Statement 239
The if-else Statement 242
Using Block Statements 245
Nested if Statements 249

5.3 comparing Data 252


Comparing Floats 252
Comparing Characters 253
Comparing Objects 254
5.4 The while Statement 256
Infinite Loops 260
Nested Loops 262
The break and continue Statements 265

5.5 Iterators 267


Reading Text Files 268

5.6 The arrayList class 271

5.7 Determining Event Sources 274


cONTENTS 17

5.8 check Boxes and radio Buttons 277


Check Boxes 277
Radio Buttons 281

Software failure:
Therac-25 293

chapter 6 More conditionals and Loops 295

6.1 The switch Statement 296

6.2 The conditional Operator 300

6.3 The do Statement 301


6.4 The for Statement 305
The for-each Loop 308
Comparing Loops 310

6.5 Drawing with Loops and conditionals 311

6.6 Dialog Boxes 317

chapter 7 Object-Oriented Design 327

7.1 Software Development activities 328

7.2 Identifying classes and Objects 329


Assigning Responsibilities 331

7.3 Static class Members 331


Static Variables 332
Static Methods 332

7.4 class relationships 336


Dependency 336
Dependencies Among Objects
of the Same Class 336
Aggregation 342
The this Reference 346

7.5 Interfaces 348


The Comparable Interface 353
The Iterator Interface 354
18 cONTENTS

7.6 Enumerated Types revisited 355

7.7 Method Design 358


Method Decomposition 359
Method Parameters Revisited 364

7.8 Method Overloading 369

7.9 Testing 371


Reviews 372
Defect Testing 372

7.10 GUI Design 375

7.11 Layout Managers 376


Flow Layout 378
Border Layout 382
Grid Layout 385
Box Layout 387

7.12 Borders 391

7.13 containment Hierarchies 395

Software failure:
2003 Northeast Blackout 403

chapter 8 arrays 405

8.1 array Elements 406

8.2 Declaring and Using arrays 407


Bounds Checking 410
Alternate Array Syntax 415
Initializer Lists 415
Arrays as Parameters 416

8.3 arrays of Objects 418

8.4 command-Line arguments 428

8.5 Variable Length parameter Lists 430

8.6 Two-Dimensional arrays 434


Multidimensional Arrays 438
cONTENTS 19

8.7 polygons and polylines 439


The Polygon Class 442

8.8 Mouse Events 444

8.9 Key Events 453

Software failure:
LA Air Traffic Control 467

chapter 9 Inheritance 469

9.1 creating Subclasses 470


The protected Modifier 473
The super Reference 476
Multiple Inheritance 479

9.2 Overriding Methods 481


Shadowing Variables 483

9.3 class Hierarchies 484


The Object Class 486
Abstract Classes 487
Interface Hierarchies 489

9.4 Visibility 489

9.5 Designing for Inheritance 492


Restricting Inheritance 493

9.6 The component class Hierarchy 494

9.7 Extending adapter classes 497


9.8 The Timer class 501
Software failure:
Ariane 5 Flight 501 511

chapter 10 polymorphism 513

10.1 Late Binding 514

10.2 polymorphism via Inheritance 515


20 cONTENTS

10.3 polymorphism via Interfaces 528

10.4 Sorting 530


Selection Sort 531
Insertion Sort 537
Comparing Sorts 538

10.5 Searching 539


Linear Search 539
Binary Search 541
Comparing Searches 545

10.6 Designing for polymorphism 545

10.7 Event processing 547

10.8 file choosers 548

10.9 color choosers 551

10.10 Sliders 553

chapter 11 Exceptions 563

11.1 Exception Handling 564

11.2 Uncaught Exceptions 565


11.3 The try-catch Statement 566
The finally Clause 570

11.4 Exception propagation 571

11.5 The Exception class Hierarchy 575


Checked and Unchecked Exceptions 578

11.6 I/O Exceptions 579


11.7 Tool Tips and Mnemonics 583

11.8 combo Boxes 590

11.9 Scroll panes 595

11.10 Split panes 598


cONTENTS 21

chapter 12 recursion 609

12.1 recursive Thinking 610


Infinite Recursion 610
Recursion in Math 611

12.2 recursive programming 612


Recursion vs. Iteration 615
Direct vs. Indirect Recursion 615

12.3 Using recursion 616


Traversing a Maze 617
The Towers of Hanoi 622

12.4 recursion in Graphics 627


Tiled Pictures 627
Fractals 630

chapter 13 collections 643

13.1 collections and Data Structures 644


Separating Interface from Implementation 644

13.2 Dynamic representations 645


Dynamic Structures 645
A Dynamically Linked List 646
Other Dynamic List Representations 651

13.3 Linear Data Structures 653


Queues 653
Stacks 654

13.4 Non-Linear Data Structures 657


Trees 657
Graphs 658

13.5 The Java collections apI 660


Generics 660
22 cONTENTS

appendix a Glossary 667

appendix B Number Systems 691

appendix c The Unicode character Set 699

appendix D Java Operators 703

appendix E Java Modifiers 709

appendix f Java coding Guidelines 713

appendix G Java applets 719

appendix H regular Expressions 721

appendix I Javadoc Documentation Generator 723

appendix J The paintBox project 729

appendix K GUI Events 741

appendix L Java Syntax 745

appendix M The Java class Library 759

appendix N answers to Self-review Questions 761

Index 815
cONTENTS 23

VideoNote
Overview of program elements. 55
comparison of Java IDEs. 67
Examples of various error types. 69
Developing a solution for pp 1.2. 80
Example using strings and escape sequences. 89
review of primitive data and expressions. 102
Example using the Scanner class. 117
Example using drawn shapes. 127
Developing a solution of pp 2.10. 135
creating objects. 141
Example using the random and Math classes. 155
Example using frames and panels. 176
Developing a solution of pp 3.6. 184
Dissecting the Die class. 190
Discussion of the account class. 204
Example using an extended Jpanel. 208
Overview of GUI development. 217
Developing a solution of pp 4.2. 228
Examples using conditionals. 247
Examples using while loops. 259
Examples using check boxes and radio buttons. 281
Developing a solution of pp 5.4. 290
Examples using for loops. 306
Developing a solution of pp 6.2 322
Exploring the static modifier. 331
Examples of method overloading. 370
Discussion of layout managers. 382
Developing a solution of pp 7.1. 400
24 cONTENTS

Overview of arrays. 409


Discussion of the Lettercount example. 414
Example using rubberbanding and arrays. 449
Developing a solution of pp 8.5. 462
Overview of inheritance. 475
Example using a class hierarchy. 487
Example using the Timer class. 501
Developing a solution of pp 9.11. 509
Exploring the firm program. 516
Sorting comparable objects. 532
Developing a solution of pp 10.1. 560
proper exception handling. 571
Exploring GUI design details. 587
Developing a solution of pp 11.1. 606
Tracing the MazeSearch program. 620
Exploring the Towers of Hanoi. 623
Developing a solution of pp 12.1. 639
Example using a linked list. 646
Implementing a queue. 654
Developing a solution of pp 13.3. 664
Credits

Cover: © Eugene Sergeev/Shutterstock


01-2 Screenshots reprinted with permission from Apple, Inc.
02-SF NASA Earth Observing System
03-3 Java API doucumentation. Used by permission of Oracle Corporate Counsel
04-SFd Susan Van Etten/PhotoEdit
05-SF-b David Joel/Stone/Getty Images
07-SF-c-1 and 07-SF-c-2 National Oceanic and Atmospheric Administration
08-SF-a Matthew McVay/Getty Images
09-SF-e Mario Fourmy/REA/Redux Pictures
Listing 10.13 Robert Frost, The Road Not Taken (1916)
Display Listing 11.13 © MShieldsPhotos/Alamy
M.1 http://docs.oracle.com/javase7/docs/api
UNF02-01, UNF11-01, UNF12-01 John Lewis
© Microsoft Corporation. Used with permission from Microsoft. MICROSOFT
AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS
ABOUT THE SUITABILITY OF THE INFORMATION CONTAINED IN
THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED AS PART
OF THE SERVICES FOR ANY PURPOSE. ALL SUCH DOCUMENTS
AND RELATED GRAPHICS ARE PROVIDED “AS IS” WITHOUT
WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE
SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS
OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED, OR
STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/
OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE
FROM THE SERVICES. THE DOCUMENTS AND RELATED GRAPHICS
CONTAINED HEREIN COULD INCLUDE TECHNICAL INACCURACIES
OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY
ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR
ITS RESPECTIVE SUPPLIERS MAY MAKE IMPROVEMENTS AND/
OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S)
DESCRIBED HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY
BE VIEWED IN FULL WITHIN THE SOFTWARE VERSION SPECIFIED. 25
This page is intentionally left blank.
Introduction
Chap t e r

O b j e C t i v e s
Describe the relationship between hardware and software.
1
● Define various types of software and how they are used.

● Identify the core hardware components of a computer and explain their


roles.

● Explain how the hardware components interact to execute programs and


manage data.

● Describe how computers are connected into networks to share information.

● Introduce the Java programming language.

● Describe the steps involved in program compilation and execution.

● Present an overview of object-oriented principles.

This book is about writing well-designed software. To understand


software, we must first have a fundamental understanding of its role
in a computer system. Hardware and software cooperate in a com-
puter system to accomplish complex tasks. The purpose of various
hardware components, and the way those components are connected
into networks, are important prerequisites to the study of software
development. This chapter first discusses basic computer processing
and then begins our exploration of software development by intro-
ducing the Java programming language and the principles of object-
oriented programming.

27
28 Chapter 1 Introduction

1.1 Computer processing


All computer systems, whether it’s a desktop, laptop, tablet, smart phone, gaming
console, or a special-purpose device like a car’s navigation system, share certain
characteristics. The details vary, but they all process data in similar ways. While the
majority of this book deals with the development of software, we’ll begin with an
overview of computer processing to set the context. It’s important to establish some
fundamental terminology and see how key pieces of a computer system interact.
A computer system is made up of hardware and software. The hardware com-
ponents of a computer system are the physical, tangible pieces that support the
computing effort. They include chips, boxes, wires, keyboards, speakers, disks,
memory cards, USB flash drives (also called jump drives), cables, plugs, printers,
mice, monitors, routers, and so on. If you can physically touch it and it can be
considered part of a computer system, then it is computer hardware.

K e Y C O n C e pt
The hardware components of a computer are essentially useless
A computer system consists of
without instructions to tell them what to do. A program is a series of
hardware and software that work in instructions that the hardware executes one after another. Software
concert to help us solve problems. consists of programs and the data those programs use. Software is
the intangible counterpart to the physical hardware components.
Together they form a tool that we can use to help solve problems.
The key hardware components in a computer system are
■ central processing unit (CPU)
■ input/output (I/O) devices
■ main memory
■ secondary memory devices
Each of these hardware components is described in detail in the next section. For
now, let’s simply examine their basic roles. The central processing unit (CPU) is
the device that executes the individual commands of a program. Input/output
(I/O) devices, such as the keyboard, mouse, and monitor, allow a human being to
interact with the computer.
Programs and data are held in storage devices called memory, which fall into
two categories: main memory and secondary memory. Main memory is the storage
device that holds the software while it is being processed by the CPU. Secondary
memory devices store software in a relatively permanent manner. The most impor-
tant secondary memory device of a typical computer system is the hard disk that
resides inside the main computer box. A USB flash drive is also an important sec-
ondary memory device. A typical USB flash drive cannot store nearly as much infor-
mation as a hard disk. USB flash drives have the advantage of portability; they can
be removed temporarily or moved from computer to computer as needed. Another
portable secondary memory device is the compact disc (CD).
1 . 1 Computer Processing 29

Figure 1.1 A simplified view of a computer system

Figure 1.1 shows how information moves among the basic hardware compo-
nents of a computer. Suppose you have an executable program you wish to run.
The program is stored on some secondary memory device, such as a hard disk.
When you instruct the computer to execute your program, a copy of the program
is brought in from secondary memory and stored in main memory. The CPU reads
the individual program instructions from main memory. The CPU
then executes the instructions one at a time until the program ends. KeY COnCept
The data that the instructions use, such as two numbers that will The CPU reads the program
be added together, also are stored in main memory. They are either instructions from main memory,
executing them one at a time until
brought in from secondary memory or read from an input device the program ends.
such as the keyboard. During execution, the program may display
information to an output device such as a monitor.
The process of executing a program is fundamental to the operation of a com-
puter. All computer systems basically work in the same way.

software Categories
Software can be classified into many categories using various criteria. At this point
we will simply differentiate between system programs and application programs.
The operating system is the core software of a computer. It performs two
important functions. First, it provides a user interface that allows the user to inter-
act with the machine. Second, the operating system manages computer resources
such as the CPU and main memory. It determines when programs are allowed to
run, where they are loaded into memory, and how hardware devices communi-
cate. It is the operating system’s job to make the computer easy to
use and to ensure that it runs efficiently. KeY COnCept
Several popular operating systems are in use today. The Windows The operating system provides
a user interface and manages
operating system was developed for personal computers by Microsoft, computer resources.
which has captured the lion’s share of the operating systems market.
30 Chapter 1 Introduction

Various versions of the Unix operating system are also quite popular, especially
in larger computer systems. A version of Unix called Linux was developed as an
open source project, which means that many people contributed to its develop-
ment and its code is freely available. Because of that, Linux has become a par-
ticular favorite among some users. Mac OS X is an operating system used for
computing systems developed by Apple Computers.
Operating systems are often specialized for mobile devices such as smart phones
and tablets. The iOS operating system from Apple is used on the iPhone, iPad, and
iPod Touch. It is similar in functionality and appearance to the desktop Mac OS,
but tailored for the smaller devices. Likewise, Windows Phone is the version of the
Windows operating system from Microsoft used in their phones. Android is a Linux-
based mobile operating system developed by Google and used on many phones.
An application (often shortened in conversation to “app”) is a generic term for
just about any software other than the operating system. Word processors, missile
control systems, database managers, Web browsers, and games all can be consid-
ered application programs. Each application program has its own user interface
that allows the user to interact with that particular program.
The user interface for most modern operating systems and applications is a
graphical user interface (GUI, pronounced “gooey”), which, as the name implies,
makes use of graphical screen elements. Among many others, these elements include
■ windows, which are used to separate the screen into distinct work areas
■ icons, which are small images that represent computer resources, such as a file
■ menus, checkboxes, and radio buttons, which provide the user with select-
able options
■ sliders, which allow the user to select from a range of values
■ buttons, which can be “pushed” with a mouse click to indicate a user selection
The mouse is the primary input device used with GUIs; thus, GUIs are some-
times called point-and-click interfaces. The screen shot in Figure 1.2 shows an
example of a GUI.

K e Y C O n C e pt
The interface to an application or operating system is an impor-
As far as the user is concerned, the
tant part of the software because it is the only part of the program
interface is the program. with which the user interacts directly. To the user, the interface is
the program. Throughout this book we discuss the design and imple-
mentation of graphical user interfaces.
The focus of this book is the development of high-quality application pro-
grams. We explore how to design and write software that will perform calcula-
tions, make decisions, and present results textually or graphically. We use the
Java programming language throughout the text to demonstrate various comput-
ing concepts.
1 . 1 Computer Processing 31

F igure 1.2 An example of a graphical user interface (GUI)

Digital Computers
Two fundamental techniques are used to store and manage information: analog
and digital. Analog information is continuous, in direct proportion to the source
of the information. For example, an alcohol thermometer is an analog device for
measuring temperature. The alcohol rises in a tube in direct proportion to the
temperature outside the tube. Another example of analog information is an elec-
tronic signal used to represent the vibrations of a sound wave. The signal’s voltage
varies in direct proportion to the original sound wave. A stereo amplifier sends
this kind of electronic signal to its speakers, which vibrate to reproduce the sound.
We use the term analog because the signal is directly analogous to the information
it represents. Figure 1.3 graphically depicts a sound wave captured
by a microphone and represented as an electronic signal. KeY COnCept
Digital technology breaks information into discrete pieces and Digital computers store information
by breaking it into pieces and repre-
represents those pieces as numbers. The music on a compact disc is senting each piece as a number.
stored digitally, as a series of numbers. Each number represents the
32 Chapter 1 Introduction

Sound wave Analog signal of the sound wave

Figure 1.3 A sound wave and an electronic analog signal


that represents the wave

voltage level of one specific instance of the recording. Many of these measure-
ments are taken in a short period of time, perhaps 44,000 measurements every
second. The number of measurements per second is called the sampling rate. If
samples are taken often enough, the discrete voltage measurements can be used
to generate a continuous analog signal that is “close enough” to the original. In
most cases, the goal is to create a reproduction of the original signal that is good
enough to satisfy the human senses.
Figure 1.4 shows the sampling of an analog signal. When analog information
is converted to a digital format by breaking it into pieces, we say it has been

Information can be lost


between samples

Analog signal

Sampling process

Sampled values 12 11 39 40 7 14 47

Figure 1. 4 Digitizing an analog signal by sampling


1 . 1 Computer Processing 33

H i , H e a t h e r.

72 105 44 32 72 101 97 116 104 101 114 46

Figure 1.5 Text is stored by mapping each character to a number

digitized. Because the changes that occur in a signal between samples are lost, the
sampling rate must be sufficiently fast.
Sampling is only one way to digitize information. For example, a sentence of
text is stored on a computer as a series of numbers, where each number represents
a single character in the sentence. Every letter, digit, and punctuation symbol has
been assigned a number. Even the space character is assigned a number. Consider
the following sentence:
Hi, Heather.
The characters of the sentence are represented as a series of 12 numbers, as shown
in Figure 1.5. When a character is repeated, such as the uppercase 'H', the same
representation number is used. Note that the uppercase version of a letter is stored as
a different number from the lowercase version, such as the 'H' and 'h' in the word
Heather. They are considered separate and distinct characters.
Modern electronic computers are digital. Every kind of information, including
text, images, numbers, audio, video, and even program instructions, is broken into
pieces. Each piece is represented as a number. The information is stored by storing
those numbers.

binary numbers
A digital computer stores information as numbers, but those numbers are not stored
as decimal values. All information in a computer is stored and managed as binary
values. Unlike the decimal system, which has 10 digits (0 through 9), the binary
number system has only two digits (0 and 1). A single binary digit is called a bit.
All number systems work according to the same rules. The base value of a
number system dictates how many digits we have to work with and indicates the
place value of each digit in a number. The decimal number system
KeY COnCept
is base 10, whereas the binary number system is base 2. Appendix B
Binary is used to store and move
contains a detailed discussion of number systems. information in a computer because
Modern computers use binary numbers because the devices that the devices that store and manipu-
late binary data are inexpensive and
store and move information are less expensive and more reliable reliable.
if they have to represent only one of two possible values. Other
34 Chapter 1 Introduction

than this characteristic, there is nothing special about the binary number system.
Computers have been created that use other number systems to store and move
information, but they aren’t as convenient.
Some computer memory devices, such as hard drives, are magnetic in nature.
Magnetic material can be polarized easily to one extreme or the other, but intermedi-
ate levels are difficult to distinguish. Therefore, magnetic devices can be used to rep-
resent binary values quite effectively—a magnetized area represents a binary 1 and a
demagnetized area represents a binary 0. Other computer memory devices are made
up of tiny electrical circuits. These devices are easier to create and are less likely to fail
if they have to switch between only two states. We’re better off reproducing millions
of these simple devices than creating fewer, more complicated ones.
Binary values and digital electronic signals go hand in hand. They improve our
ability to transmit information reliably along a wire. As we’ve seen, an analog signal
has continuously varying voltage with infinitely many states, but a digital signal is
discrete, which means the voltage changes dramatically between one extreme (such
as +5 volts) and the other (such as –5 volts). At any point, the voltage of a digital
signal is considered to be either “high,” which represents a binary 1, or “low,”
which represents a binary 0. Figure 1.6 compares these two types of signals.
As a signal moves down a wire, it gets weaker and degrades due to environ-
mental conditions. That is, the voltage levels of the original signal change slightly.
The trouble with an analog signal is that as it fluctuates, it loses its original infor-
mation. Since the information is directly analogous to the signal, any change in
the signal changes the information. The changes in an analog signal cannot be
recovered because the degraded signal is just as valid as the original. A digital
signal degrades just as an analog signal does, but because the digital signal is
originally at one of two extremes, it can be reinforced before any information is
lost. The voltage may change slightly from its original value, but it still can be
interpreted correctly as either high or low.
The number of bits we use in any given situation determines the number of
unique items we can represent. A single bit has two possible values, 0 and 1, and

Analog signal Digital signal

Figure 1 . 6 An analog signal vs. a digital signal


1 . 1 Computer Processing 35

therefore can represent two possible items or situations. If we want to represent


the state of a light bulb (off or on), one bit will suffice, because we can interpret 0
as the light bulb being off and 1 as the light bulb being on. If we want to represent
more than two things, we need more than one bit.
Two bits, taken together, can represent four possible items because there are
exactly four permutations of two bits: 00, 01, 10, and 11. Suppose we want to
represent the gear that a car is in (park, drive, reverse, or neutral). We would need
only two bits, and could set up a mapping between the bit permutations and the
gears. For instance, we could say that 00 represents park, 01 represents drive, 10
represents reverse, and 11 represents neutral. In this case, it wouldn’t matter if we
switched that mapping around, though in some cases the relationships between
the bit permutations and what they represent are important.
Three bits can represent eight unique items, because there are KeY COnCept
eight permutations of three bits. Similarly, four bits can represent 16 There are exactly 2N permutations of
items, five bits can represent 32 items, and so on. Figure 1.7 shows N bits. Therefore, N bits can repre-
the relationship between the number of bits used and the number of sent up to 2N unique items.
items they can represent. In general, N bits can represent 2N unique
items. For every bit added, the number of items that can be represented doubles.

1 bit 2 bits 3 bits 4 bits 5 bits


2 items 4 items 8 items 16 items 32 items
0 00 000 0000 00000 10000
1 01 001 0001 00001 10001
10 010 0010 00010 10010
11 011 0011 00011 10011
100 0100 00100 10100
101 0101 00101 10101
110 0110 00110 10110
111 0111 00111 10111
1000 01000 11000
1001 01001 11001
1010 01010 11010
1011 01011 11011
1100 01100 11100
1101 01101 11101
1110 01110 11110
1111 01111 11111

Figure 1.7 The number of bits used determines the number


of items that can be represented.
36 Chapter 1 Introduction

We’ve seen how a sentence of text is stored on a computer by mapping char-


acters to numeric values. Those numeric values are stored as binary numbers.
Suppose we want to represent character strings in a language that contains 256
characters and symbols. We would need to use eight bits to store each character
because there are 256 unique permutations of eight bits (28 equals 256). Each bit
permutation, or binary value, is mapped to a specific character.
How many bits would be needed to represent 195 countries of the world?
Seven wouldn’t be enough, because 27 equals 128. Eight bits would be enough,
but some of the 256 permutations would not be mapped to a country.
Ultimately, representing information on a computer boils down to the number
of items there are to represent and determining the way those items are mapped
to binary values.

selF-review QuestiOns (see answers in Appendix N)


SR 1.1 What is hardware? What is software?
SR 1.2 What are the two primary functions of an operating system?
SR 1.3 The music on a CD is created using a sampling rate of 44,000 mea-
surements per second. Each measurement is stored as a number that
represents a specific voltage level. How many such numbers are used
to store a three-minute long song? How many such numbers does it
take to represent one hour of music?
SR 1.4 What happens to information when it is stored digitally?
SR 1.5 How many unique items can be represented with the following?

a. 2 bits
b. 4 bits
c. 5 bits
d. 7 bits

SR 1.6 Suppose you want to represent each of the 50 states of the United
States using a unique permutation of bits. How many bits would be
needed to store each state representation? Why?

1.2 hardware Components


Let’s examine the hardware components of a computer system in more detail.
Consider the desktop computer described in Figure 1.8. What does it all mean? Is
the system capable of running the software you want it to? How does it compare
with other systems? These terms are explained throughout this section.
1 . 2 Hardware Components 37

Figure 1.8 The hardware specification of a particular computer

Computer architecture
The architecture of a house defines its structure. Similarly, we use the term com-
puter architecture to describe how the hardware components of a computer are put
together. Figure 1.9 illustrates the basic architecture of a generic computer system.
Information travels between components across a group of wires called a bus.

Figure 1.9 Basic computer architecture


38 Chapter 1 Introduction

The CPU and the main memory make up the core of a computer.
K e Y C O n C e pt
The core of a computer is made up
As we mentioned earlier, main memory stores programs and data
of main memory, which stores pro- that are in active use, and the CPU methodically executes program
grams and data, and the CPU, which instructions one at a time.
executes program instructions one
at a time.
Suppose we have a program that computes the average of a list of
numbers. The program and the numbers must reside in main memory
while the program runs. The CPU reads one program instruction from
main memory and executes it. If an instruction needs data, such as a number in the
list, to perform its task, the CPU reads that information as well. This process repeats
until the program ends. The average, when computed, is stored in main memory to
await further processing or long-term storage in secondary memory.
Almost all devices in a computer system other than the CPU and main memory
are called peripherals; they operate at the periphery, or outer edges, of the system
(although they may be in the same box). Users don’t interact directly with the
CPU or main memory. Although they form the essence of the machine, the CPU
and main memory would not be useful without peripheral devices.
Controllers are devices that coordinate the activities of specific peripherals. Every
device has its own particular way of formatting and communicating data, and part
of the controller’s role is to handle these idiosyncrasies and isolate them from the
rest of the computer hardware. Furthermore, the controller often handles much of
the actual transmission of information, allowing the CPU to focus on other activities.
Input/output (I/O) devices and secondary memory devices are considered periph-
erals. Another category of peripherals consist of data transfer devices, which allow
information to be sent and received between computers. The computer specified in
Figure 1.8 includes a network card, also called a wireless network interface controller
(WNIC), which connects to a radio-based computer network.
In some ways, secondary memory devices and data transfer devices can be
thought of as I/O devices because they represent a source of information (input)
and a place to send information (output). For our discussion, however, we define
I/O devices as those devices that allow the user to interact with the computer.

input/Output Devices
Let’s examine some I/O devices in more detail. The most common input devices
are the keyboard and the mouse or trackpad. Others include
■ bar code readers, such as the ones used at a retail store checkout
■ microphones, used by voice recognition systems that interpret voice commands
■ virtual reality devices, such as handheld devices that interpret the move-
ment of the user’s hand
■ scanners, which convert text, photographs, and graphics into machine-
readable form
1 . 2 Hardware Components 39

■ cameras, which capture still pictures and video, and can also be used to
process special input such as QR codes
Monitors and printers are the most common output devices. Others include
■ plotters, which move pens across large sheets of paper (or vice versa)
■ speakers, for audio output
■ goggles, for virtual reality display
Some devices can provide both input and output capabilities. A touch screen
system can detect the user touching the screen at a particular place. Software can
then use the screen to display text and graphics in response to the user’s touch.
Touch screens have become commonplace for handheld devices.
The desktop computer described in Figure 1.8 includes a monitor with a
17-inch diagonal display area. It makes use of liquid crystal display (LCD)
technology, unlike the older cathode ray tube (CRT) monitors that required
substantial voltage and generally were not portable. A picture is represented in a
computer by breaking it up into separate picture elements, or pixels. The monitor
might display a grid of 1280 by 1024 pixels. Representing and managing graphi-
cal data is discussed in more detail in Chapter 2.

Main Memory and secondary Memory


KeY COnCept
Main memory is made up of a series of small, consecutive memory
An address is a unique number asso-
locations, as shown in Figure 1.10. Associated with each memory ciated with a memory location.
location is a unique number called an address.

4802
Data values are stored in
Addresses 4803 memory locations.
4804
4805
4806 Large values are stored
4807 in consecutive memory
locations.
4808
4809
4810
4811
4812

Figure 1.10 Memory locations


40 Chapter 1 Introduction

Unit Symbol Number of Bytes


0
byte 2 =1
10
kilobyte KB 2 = 1024
20
megabyte MB 2 = 1,048,576
30
gigabyte GB 2 = 1,073,741,824
40
terabyte TB 2 = 1,099,511,627,776
50
petabyte PB 2 = 1,125,899,906,842,624

Fig u r e 1 . 1 1 Units of binary storage

When data is stored in a memory location, it overwrites and destroys any


information that was previously stored at that location. However, the process of
reading data from a memory location does not affect it.
On many computers, each memory location consists of eight bits, or one byte,
of information. If we need to store a value that cannot be represented in a single
byte, such as a large number, then multiple, consecutive bytes are used to store
the data.
The storage capacity of a device such as main memory is the total number of
bytes it can hold. Devices can store thousands or millions of bytes, so you should
become familiar with larger units of measure. Because computer memory is based
on the binary number system, all units of storage are powers of two. A kilobyte
(KB) is 1024, or 210, bytes. Some larger units of storage are a megabyte (MB), a
gigabyte (GB), a terabyte (TB), and a petabyte (PB) as listed in Figure 1.11. It’s
usually easier to think about these capacities by rounding them off. For example,
most computer users think of a kilobyte as approximately one thousand bytes, a
megabyte as approximately one million bytes, and so forth.
Many personal computers have four gigabytes of main memory,
K e Y C O n C e pt or RAM, such as the system described in Figure 1.8 (we discuss
Main memory is volatile, meaning RAM in more detail later in this chapter). A large main memory
the stored information is maintained
only as long as electric power is
allows large programs or multiple programs to run efficiently,
supplied. because they don’t have to retrieve information from secondary
memory as often.
Main memory is usually volatile, meaning that the information stored in it
will be lost if its electric power supply is turned off. When you are working
on a computer, you should often save your work onto a secondary memory
device such as a USB flash drive in case the power goes out. Secondary memory
devices are usually nonvolatile; the information is retained even if the power
supply is turned off.
1 . 2 Hardware Components 41

The cache is used by the central processing unit (CPU) to reduce the average
access time to instructions and data. The cache is a small, fast memory that stores
the contents of the most frequently used main memory locations. Contemporary
CPUs include an instruction cache to speed up the fetching of executable instruc-
tions and a data cache to speed up the fetching and storing of data.
The most common secondary storage devices are hard disks and USB flash
drives. A typical USB flash drive stores between 1 GB and 256 GB of information.
The storage capacities of hard drives vary, but on personal computers, capacities
typically range between 120 GB and 500 GB, such as in the system described in
Figure 1.8. Some hard disks can store 2 TB of data.
A USB flash drive consists of a small printed circuit board carrying the circuit
elements and a USB connector, insulated electrically and protected inside a plastic,
metal, or rubberized case, which can be carried in a pocket or on a key chain, for
example.
A disk is a magnetic medium on which bits are represented as magnetized parti-
cles. A read/write head passes over the spinning disk, reading or writing information
as appropriate. A hard disk drive might actually contain several disks in a vertical
column with several read/write heads, such as the one shown in Figure 1.12.
To get an intuitive feel for how much information these devices can store,
consider that all the information in this book, including pictures and formatting,
requires about 7 MB of storage.
Magnetic tapes also have been used as secondary storage but are considerably
slower than hard disk and USB flash drives because of the way information is
accessed. A hard disk is a direct access device since the read/write head can move, in
general, directly to the information needed. A USB flash drive is also a direct access

Read/write
head

Disks

Figure 1.12 A hard disk drive with multiple disks and read/write heads
42 Chapter 1 Introduction

device, but nothing moves mechanically. The terms direct access and random access
are often used interchangeably. However, information on a tape can be accessed
only after first getting past the intervening data. A tape must be rewound or fast-for-
warded to get to the appropriate position. A tape is therefore considered a sequential
access device. For these reasons, tapes largely have fallen out of use as a computing
storage device, just as audio cassettes have been supplanted by compact discs.
Two other terms are used to describe memory devices: random access
memory (RAM) and read-only memory (ROM). It’s important to understand
these terms because they are used often and their names can be misleading. The
terms RAM and main memory are basically interchangeable, describing the
memory where active programs and data are stored. ROM can refer to chips
on the computer motherboard or to portable storage such as a compact disc.
ROM chips typically store software called BIOS (basic input/output system)
that provide the preliminary instructions needed when the computer is turned
on initially. After information is stored on ROM, generally it is not altered (as
the term read-only implies) during typical computer use. Both RAM and ROM
are direct (or random) access devices.
A CD-ROM is a portable secondary memory device. CD stands
K e Y C O n C e pt
The surface of a CD has both
for compact disc. It is called ROM because information is stored
smooth areas and small pits. A pit permanently when the CD is created and cannot be changed. Like
represents a binary 1 and a smooth its musical CD counterpart, a CD-ROM stores information in binary
area represents a binary 0. format. When the CD is initially created, a microscopic pit is pressed
into the disc to represent a binary 1, and the disc is left smooth to
represent a binary 0. The bits are read by shining a low-intensity laser beam onto
the spinning disc. The laser beam reflects strongly from a smooth area on the
disc but weakly from a pitted area. A sensor receiving the reflection determines
whether each bit is a 1 or a 0 accordingly. A typical CD-ROM’s storage capacity
ranges between 650 and 900 MB.
Variations on basic CD technology emerged quickly. Most personal computers
are equipped with a CD-Recordable (CD-R) drive. A CD-R can be used to cre-
ate a CD for music or for general computer storage. Once created, you can use a
CD-R disc in a standard CD player, but you can’t change the information on a
CD-R disc once it has been “burned.” Music CDs that you buy are pressed from
a mold, whereas CD-Rs are burned with a laser.
A CD-Rewritable (CD-RW) disc can be erased and reused. It can be reused because
the pits and flat surfaces of a normal CD are simulated on a CD-RW
K e Y C O n C e pt by coating the surface of the disc with a material that, when heated
A rewritable CD simulates the pits to one temperature becomes amorphous (and therefore nonreflective)
and smooth areas of a regular CD and when heated to a different temperature becomes crystalline (and
by using a coating that can be made
amorphous or crystalline as needed.
therefore reflective). The CD-RW media doesn’t work in all players, but
CD-RW drives can create both CD-R and CD-RW discs.
1 . 2 Hardware Components 43

CDs were initially a popular format for music; they later evolved to be used
as a general computer storage device. Similarly, the DVD format was originally
created for video and is now making headway as a general format for computer
data. DVD once stood for digital video disc or digital versatile disc, but now the
acronym generally stands on its own. A DVD has a tighter format (more bits per
square inch) than a CD and can therefore store much more information. DVD-
ROMs eventually may replace CD-ROMs completely because there is a compat-
ible migration path, meaning that a DVD drive can read a CD-ROM. Similar to
CD-R and CD-RW, there are DVD-R and DVD-RW discs. The drive listed in
Figure 1.8 allows the user to read and write CD-RW discs and read DVD-ROMs,
including the ability to play music CDs and watch DVD videos.
The speed of a CD or DVD is expressed in multiples of x, which represents
a data transfer speed of 153,600 bytes of data per second for a CD; nine times
that speed, or about 1.5 megabytes of data per second, for a DVD; and three
times the speed of a DVD, or 4.5 megabytes of data per second, for a Blu-ray
disc. The drive described in Figure 1.8 has a maximum data access speed of
16x, or about 72 MB of data per second. A dual-layer Blu-ray disc has a stor-
age capacity of 50 GB.
The capacity of storage devices changes continually as technology improves.
A general rule in the computer industry suggests that storage capacity approxi-
mately doubles every 18 months. However, this progress eventually will slow
down as capacities approach absolute physical limits.

the Central processing unit


The central processing unit (CPU) interacts with main memory to perform all
fundamental processing in a computer. The CPU interprets and executes instruc-
tions, one after another, in a continuous cycle. It is made up of three important
components, as shown in Figure 1.13. The control unit coordinates the processing
steps, the registers provide a small amount of storage space in the CPU itself, and
the arithmetic/logic unit performs calculations and makes decisions. The registers
are the smallest, fastest cache in the system.
The control unit coordinates the transfer of data and instructions between
main memory and the registers in the CPU. It also coordinates the execution of
the circuitry in the arithmetic/logic unit to perform operations on data stored in
particular registers.
In most CPUs, some registers are reserved for special purposes. For example,
the instruction register holds the current instruction being executed. The pro-
gram counter is a register that holds the address of the next instruction to be
executed. In addition to these and other special-purpose registers, the CPU also
44 Chapter 1 Introduction

CPU

Arithmetic/logic
unit

Bus
Main
Control unit
memory

Registers

Figure 1 . 1 3 CPU components and main memory

contains a set of general-purpose registers that are used for temporary storage
of values as needed.
The concept of storing both program instructions and data together in main
memory is the underlying principle of the von Neumann architecture of computer
design, named after John von Neumann, a Hungarian-American mathematician
who first advanced this programming concept in 1945. These computers continu-
ally follow the fetch-decode-execute cycle depicted in Figure 1.14. An instruction
is fetched from main memory at the address stored in the program counter and is
put into the instruction register. The program counter is incremented
K e Y C O n C e pt at this point to prepare for the next cycle. Then the instruction is
The fetch-decode-execute cycle
decoded electronically to determine which operation to carry out.
forms the foundation of computer
processing. Finally, the control unit activates the correct circuitry to carry out
the instruction, which may load a data value into a register or add
two values together, for example.
The CPU is constructed on a chip called a microprocessor, a device that is part
of the main circuit board of the computer. This board also contains ROM chips

Fetch an instruction Decode the instruction


from main memory and increment program
counter

Execute the instruction

Figure 1.14 The continuous fetch-decode-execute cycle


1 . 2 Hardware Components 45

and communication sockets to which device controllers, such as the controller


that manages the video display, can be connected.
Another crucial component of the main circuit board is the system clock. The
clock generates an electronic pulse at regular intervals, which synchronizes the events
of the CPU. The rate at which the pulses occur is called the clock speed, and it varies
depending on the processor. The computer described in Figure 1.8 includes an Intel
Core i7 processor that runs at a clock speed of 3.07 gigahertz (GHz), or approxi-
mately 3.1 billion pulses per second. The speed of the system clock provides a rough
measure of how fast the CPU executes instructions. Similar to storage capacities, the
speed of processors is constantly increasing with advances in technology.

s e l F - r e v iew QuestiOns (see answers in Appendix N)


SR 1.7 How many bytes are in each of the following?

a. 3 KB
b. 2 MB
c. 4 GB

SR 1.8 How many bits are there in each of the following?

a. 8 bytes
b. 2 KB
c. 4 MB

SR 1.9 The music on a CD is created using a sampling rate of 44,000 mea-


surements per second. Each measurement is stored as a number that
represents a specific voltage level. Suppose each of these numbers
requires two bytes of storage space. How many MB does it take to
represent one hour of music?
SR 1.10 What are the two primary hardware components in a computer? How
do they interact?
SR 1.11 What is a memory address?
SR 1.12 What does volatile mean? Which memory devices are volatile and
which are nonvolatile?
SR 1.13 Select the word from the following list that best matches each of the
following phrases:
controller, CPU, main, network card, peripheral, RAM, register,
ROM, secondary

a. Almost all devices in a computer system, other than the CPU and
the main memory, are categorized as this.
46 Chapter 1 Introduction

b. A device that coordinates the activities of a peripheral device.


c. Allows information to be sent and received.
d. This type of memory is usually volatile.
e. This type of memory is usually nonvolatile.
f. This term basically is interchangeable with the term “main memory.”
g. Where the fundamental processing of a computer takes place.

1.3 networks
A single computer can accomplish a great deal, but connecting several computers
together into networks can dramatically increase productivity and facilitate the
sharing of information. A network consists of two or more computers connected
together so they can exchange information. Using networks has become the nor-
mal mode of commercial computer operation. New technologies are
K e Y C O n C e pt emerging every day to capitalize on the connected environments of
A network consists of two or more
modern computer systems.
computers connected together so
that they can exchange information. Figure 1.15 shows a simple computer network. One of the devices
on the network is a printer, which allows any computer connected
to the network to print a document on that printer. One of the computers on
the network is designated as a file server, which is dedicated to storing programs
and data that are needed by many network users. A file server usually has a large
amount of secondary memory. When a network has a file server, each individual
computer doesn’t need its own copy of a program.

network Connections
If two computers are directly connected, they can communicate in basically the
same way that information moves across wires inside a single machine. When

File server

Shared printer

Figur e 1 . 1 5 A simple computer network


1 . 3 Networks 47

Figure 1.16 Point-to-point connections

connecting two geographically close computers, this solution works well and is
called a point-to-point connection. However, consider the task of connecting many
computers together across large distances. If point-to-point connections are used,
every computer is directly connected by a wire to every other computer in the
network. A separate wire for each connection is not a workable solution because
every time a new computer is added to the network, a new communication line will
have to be installed for each computer already in the network. Furthermore, a single
computer can handle only a small number of direct connections.
Figure 1.16 shows multiple point-to-point connections. Consider the number of
communication lines that would be needed if two or three additional computers were
added to the network. These days, local networks, such as those within a single build-
ing, often use wireless connections, minimizing the need for running wires.
Compare the diagrams in Figure 1.15 and Figure 1.16. All of the computers
shown in Figure 1.15 share a single communication line. Each computer on the
network has its own network address, which uniquely identifies it. These addresses
are similar in concept to the addresses in main memory except that they identify
individual computers on a network instead of individual memory locations inside
a single computer. A message is sent across the line from one computer to another
by specifying the network address of the computer for which it is intended.
Sharing a communication line is cost effective and makes adding
new computers to the network relatively easy. However, a shared line KeY COnCept
Sharing a communication line creates
introduces delays. The computers on the network cannot use the com- delays, but it is cost effective and
munication line at the same time. They have to take turns sending infor- simplifies adding new computers to
mation, which means they have to wait when the line is busy. the network.

One technique to improve network delays is to divide large mes-


sages into segments, called packets, and then send the individual packets across
the network intermixed with pieces of other messages sent by other users. The
packets are collected at the destination and reassembled into the original message.
This situation is similar to a group of people using a conveyor belt to move a set
of boxes from one place to another. If only one person were allowed to use the
conveyor belt at a time, and that person had a large number of boxes to move,
48 Chapter 1 Introduction

the others would be waiting a long time before they could use it. By taking turns,
each person can put one box on at a time, and they all can get their work done.
It’s not as fast as having a conveyor belt of your own, but it’s not as slow as hav-
ing to wait until everyone else is finished.

local-area networks and wide-area networks


A local-area network (LAN) is designed to span short distances and connect a
relatively small number of computers. Usually a LAN connects the machines in
only one building or in a single room. LANs are convenient to install and manage
and are highly reliable. As computers became increasingly small and
K e Y C O n C e pt versatile, LANs provided an inexpensive way to share information
A local-area network (LAN) is an throughout an organization. However, having a LAN is like having
effective way to share information a telephone system that allows you to call only the people in your
and resources throughout an
organization.
own town. We need to be able to share information across longer
distances.
A wide-area network (WAN) connects two or more LANs, often across long
distances. Usually one computer on each LAN is dedicated to handling the com-
munication across a WAN. This technique relieves the other computers in a LAN
from having to perform the details of long-distance communication. Figure 1.17
shows several LANs connected into a WAN. The LANs connected by a WAN are
often owned by different companies or organizations and might even be located
in different countries.

One computer
LAN
in a LAN

Long-distance
connection

Figur e 1 . 1 7 LANs connected into a WAN


1 . 3 Networks 49

The impact of networks on computer systems has been dramatic. Computing


resources can now be shared among many users, and computer-based commu-
nication across the entire world is common. In fact, the use of networks is now
so pervasive that some computers require network resources in order to operate.

the internet
Throughout the 1970s, an agency in the Department of Defense known as the
Advanced Research Projects Agency (ARPA) funded several projects to explore
network technology. One result of these efforts was the ARPANET, a WAN that
eventually became known as the Internet. The Internet is a network of networks.
The term Internet comes from the WAN concept of internetworking—connecting
many smaller networks together.
From the late 1980s through the present day, the Internet has KeY COnCept
grown incredibly. In 1983, there were fewer than 600 computers The Internet is a wide-area network
connected to the Internet. At the present time, the Internet serves (WAN) that spans the globe.
billions of users worldwide. As more and more computers con-
nect to the Internet, the task of keeping up with the larger number of users
and heavier traffic has been difficult. New technologies have replaced the
ARPANET several times since the initial development, each time providing more
capacity and faster processing.
A protocol is a set of rules that governs how two things communicate. The
software that controls the movement of messages across the Internet must con-
form to a set of protocols called TCP/IP (pronounced by spelling out the let-
ters, T-C-P-I-P). TCP stands for Transmission Control Protocol, and IP stands
for Internet Protocol. The IP software defines how information is formatted
and transferred from the source to the destination. The TCP software handles
problems such as pieces of information arriving out of their original order or
information getting lost, which can happen if too much information converges
at one location at the same time.
Every computer connected to the Internet has an IP address that uniquely iden-
tifies it among all other computers on the Internet. An example of an IP address
is 204.192.116.2. Fortunately, the users of the Internet rarely have
to deal with IP addresses. The Internet allows each computer to be KeY COnCept
given a name. Like IP addresses, the names must be unique. The Every computer connected to the
Internet has an IP address that
Internet name of a computer is often referred to as its Internet
uniquely identifies it.
address. An example of Internet address is hector.vt.edu.
The first part of an Internet address is the local name of a specific computer. The
rest of the address is the domain name, which indicates the organization to which
the computer belongs. For example, vt.edu is the domain name for the network
of computers at Virginia Tech, and hector is the name of a particular computer on
Another random document with
no related content on Scribd:
would restore loyalty, De Witt hove his topsails to the mast, and
formed line.
By four in the afternoon the English line was also formed and well
up, the only order issued from the Resolution being “to attack, but
hold their fire until close in with the enemy.” Then the whole of the
English van bore down upon the Dutch, who kept up an intermittent
and harmless fire as it approached. Just then the Dutch line tacked,
and the two fleets came into almost instant collision. They were so
close together that an unusual number of shots told, and the crash
of the first broadside was terrific; the roar of artillery continuing
incessantly for more than an hour.
After that the action became less furious, and there were pauses
in the storm of battle. The Dutch ships fell off to a greater distance,
and, as a breeze arose the clouds of powder smoke partially cleared
away. But, although the Dutch fell back, they fell back fighting, and
with their faces to the enemy; and, with their usual obstinate valor
they continued the battle until night fell upon the scene of slaughter.
The Dutch had lost most men, while the English had suffered most
severely in masts and rigging. It was thought by experienced
commanders, in both fleets, that De Witt would have been
completely defeated and broken had he not drawn off at nightfall.
Ruyter had, as usual, commanded his important division with
consummate skill and bravery. He lost a large proportion of the crew
of his own ship, and his masts and rigging were almost destroyed,
and the hull seriously shattered. De Witt himself, by his courage and
conduct during the battle, atoned in part for his rashness in fighting
such an enemy in the then condition of his fleet. But, in spite of their
efforts, the Dutch had the worst of it. Two of their ships foundered
in the first shock of battle; and two others were boarded and taken,
one of them being the Rear Admiral’s flag-ship. As has been seen,
the loss of life in the Dutch fleet was great, and this, in addition to
the general disaffection, caused about twenty of De Witt’s captains
to take advantage of the darkness, withdraw their ships from the
main fleet, and make for Zealand, where they carried the first news
of disaster.
As many of the Dutch fleet remained in sight, and kept their lights
burning during the night, Blake naturally assumed that they would
fight again at daylight. Every one, therefore, on board the English
fleet was engaged in repairing damages, in securing prisoners,
caring for the wounded and burying the dead.
At daylight the whole fleet bore down for the Dutch position, and,
from the attitude of the latter, it seemed likely that the bloody work
of the previous day would begin again.
De Witt wished to fight; but a change of counsel took place before
the fleets got within cannon shot of each other. Evertz and De
Ruyter’s opinion prevailed, and it was decided to collect the
scattered ships, to gain one of their own ports, repair, refit, and re-
man the ships, and await the orders of the States General.
Blake, in his disabled state, could not prevent them from carrying
out this decision; and was obliged to content himself with petty raids
upon the Dutch coasts, such as Tromp had inflicted upon the English
in the preceding year.
The news of this action was received in London and throughout
England with great exultation. It was the first great naval action
fought by the English since the days of Elizabeth. England had come
off victorious against the best seamen and most experienced
admirals of the world. Tromp, Evertz, and Ruyter had been regarded
as invincible sea commanders; yet now a land officer, with but three
years’ experience of the sea, with soldiers and landsmen, had
successfully withstood the attacks of veteran sailors who had swept
the great navies of Spain from the face of the ocean.
Blake took his place at once among the highest of living Admirals.

Parliament wished at once to release the ships hired from the


merchant service, and to reduce the fortifications about Deal and
Sandown.
This Blake replied to by a demand for thirty new frigates, but such
was the momentary confidence and security felt that he did not
obtain them. Vendome’s renewed complaints were treated with
haughty indifference, and the Council dreamed of a “mare clausum,”
the dominion of the Narrow Seas, and the exclusion of the Dutch
from all the valuable fisheries.
They little understood the resources and determination of the
people with whom they had to deal.

1652-3.

And now we shall see how sturdy Van Tromp came to the fore
again.
De Witt’s return with his discomfited fleet was the signal for great
disorders in Holland. The enemies of the Orange party did not
hesitate to accuse him of rashness, cowardice and treason. The
sailors of the fleet, who had been almost mutinous before the battle,
really became so after it.
Even on board his own flag-ship De Witt was not entirely free from
danger. He had, before sailing, executed some seamen for mutiny,
and excited much silent rage thereby; but when he came back
unsuccessful, the popular passions were aroused, and he was
mobbed as soon as he landed, in Flushing; his proud heart being
almost broken by the insult from a people he had served so long and
well, he fell sick, and relinquished his command. Ruyter shared some
of his unpopularity, but was persuaded to continue in his command.
Having so often triumphed at sea, the Dutch could not understand
that their reverses were not the result of gross misconduct in their
sea generals; and they now remembered that, if Tromp’s success in
the early part of the war had not been very great, he had not, at
least, suffered defeat, and they felt that the elements, and not man,
had destroyed the powerful fleet which he had lost.
His reputation became once more the first in Holland, while
personal feeling and his past training peculiarly fitted him to meet
the English.
The States General were ready to reverse their decision when they
found him necessary, and this was confirmed when they found that
the King of Denmark, alarmed by the sudden growth of England’s
maritime power, was making interest with leading Dutch statesmen,
not only for a vigorous renewal of hostilities, but also for the
restoration of Tromp to his offices and honors.
The most eminent of his rivals in naval ability and in political
influence were, upon his restoration, appointed to serve under him
as Vice and Rear Admirals. These were De Witt, Ruyter, Evertz and
Floritz. De Witt, completely mortified and disgusted, excused himself
on the plea of ill health; and Ruyter joined the fleet as second in
command.
The Danish King now refused to allow the English ships, which
had been sent to the Baltic for the naval stores so necessary to the
fleet, to return through the Sound or the Belts, and thus proved a
new enemy for the Commonwealth to deal with.
As the term for which Blake had been appointed sole General and
Admiral of the fleet had expired, he requested the appointment of
two colleagues, as he considered the coast command of England
equally important with that of the cruising fleet.
Colonel Deane and General Monk were accordingly so
commissioned, both these officers being in the land service, and at
that time actively employed in Scotland.
Winter had now set in, and Blake distributed the fleet, some for
convoy duty, and some for repairs. The Dutch were hard at work in
their dock-yards, and Blake, with a reduced force, cruised from port
to port of the Channel, not expecting the enemy to appear at sea
before the return of fine weather. In this he had greatly mistaken the
energy and influence of Tromp, who, in an incredibly short time,
fitted out and manned a vast fleet; and while the English squadrons
were dispersed in various directions, suddenly appeared off the
Goodwins with more than one hundred sail of the line, frigates and
fire-ships. His plan was bold and well conceived. Coming suddenly
into the Downs with this large force, he intended to close up the
Thames, cut off reinforcements preparing there, and then to fall
upon Blake’s division, and either capture it or drive it westward out
of the Channel; then, with the coast at his mercy, he could dictate
terms to the Commonwealth. At that time a winter cruise or
campaign was hardly thought possible; but Tromp relied upon a
swift and daring blow to finish the war in a few days.
Blake was then in the Triumph, and the first intimation he had of
Tromp’s being at sea was from his own look-out ships. On the 9th of
December the two fleets were in presence of each other, between
Calais and Dover; and the English Admiral then learned that Tromp
was in command, and accordingly prepared himself for serious work.
A council of war was held on board the Triumph. Blake declared
his intention to fight, even without his detached squadrons, rather
than leave the coast exposed to the incursions of the great and
uncrippled Dutch fleet.
All that December day the two Admirals worked for the weather
gage. The succeeding night was long, cold and stormy, and the ships
were unable to keep well together. At daylight of the 10th the
manœuvres for the weather gage were renewed, the two flag-ships,
the Brederode and the Triumph, both drawing toward the Nase, and
by three in the afternoon the fleets were quite near each other, off
that headland of Essex.
Tromp being most anxious to engage, made a sudden effort to get
alongside the English Admiral. The latter’s ship, however, by a skillful
evolution, passed under the Brederode’s bows to the weather gage.
In passing the two ships exchanged broadsides, and the battle
opened. Blake’s ship was closely followed by the Garland, and
missing the Triumph, Tromp ran afoul of this second ship, and
carried away her bowsprit and head. The Garland and the Brederode
then engaged, the English ship, though much lighter, fighting bravely
until joined by the Bonaventure, 30, when the two together rather
overmatched the Brederode. Tromp, by every possible appeal,
encouraged his men; but his position was becoming very precarious,
when Evertz, seeing him in such straits, attacked the Bonaventure,
placing that small ship between the two Dutch flag-ships. The four
ships were all grappled together, and it was more than an hour
before the weight of metal obliged the two English ships to yield.
After they had suffered great loss the Dutch boarded and captured
them. Of the other English ships the Triumph, the Vanguard and the
Victory bore the brunt of the action. In spite of being surrounded by
enemies, and suffering severely in men, hull, masts and rigging, they
all came out of the desperate encounter uncaptured. Night came
early at that season, and the fleets were about separating, when
Blake heard of the capture of the Garland and Bonaventure, and he
at once attempted their recapture. This brought on a more
destructive conflict than the previous one. Blake was surrounded by
the Dutch ships, and the Triumph was three times boarded, and the
assailants as often repulsed. She was reduced to a wreck, and with
difficulty kept afloat, and had it not been for the Sapphire and the
Vanguard, which stood by him with extraordinary courage and
devotion, the English Admiral must have succumbed. Thick fog and
darkness at last interposed and enabled Blake to draw off his ships
toward Dover Roads.
The next morning there was a dense fog, and the Dutch were not
to be seen. His disabled vessels required a shelter, and the English
Admiral, therefore, resolved to run into the Thames, and there repair
damages, ascertain the enemy’s intentions, and wait the recall and
concentration of his scattered squadrons.
In the action off the Nase the Dutch had had much the best of it,
but had lost many men, and one of their ships had blown up, every
soul on board of her perishing. Tromp’s and Ruyter’s ships were both
unfitted for further service, and many others were crippled; but they
were the victors, and once more masters of the Channel.
Blake offered to resign, but the Council would not hear of this, and
only seemed intent upon weeding out of the fleet those captains
who had not shown sufficient zeal and courage. Several were broken
after proper inquiry, among others, Blake’s own brother, who was
reported as guilty of neglect of duty.
More vessels were concentrated and placed under Blake’s orders,
and the effective force of the navy raised to 30,000 men.
While reforms, renovations and recruitments were being carried
on under Blake’s own eye, Tromp sailed up and down the Channel
with a broom at his masthead, typical of his having swept the
Narrow Seas; and the States General proclaimed a state of blockade
of the British Islands.
Caricatures and ballads were circulated in the Dutch cities, all
bearing upon the late naval event. The fear that Tromp would seize
the Channel islands, and the certainty that he had effectually cut off
commerce, hastened the preparations of the English for a second
winter campaign; and, on the 8th of February, 1653, Blake, still in
the Triumph, sailed, at the head of some sixty men-of-war and
frigates, having Monk and Deane with 1200 soldiers from the army
on board. Penn, the father of the Quaker proprietor of Pennsylvania,
was the vice admiral, and Lawson the rear admiral.
In the Straits of Dover he was joined by the Portsmouth squadron,
of twenty sail; and with this addition to his strength, Blake resolved
to seek the Dutch fleet, and once more give battle.
Tromp had gone to the southward, to meet a large fleet of Dutch
traders which had collected near Rochelle, with the intention of
convoying them home. Here intelligence reached him that the
English were about to quit the Thames with a large fleet, and he
hoped to be able to return in time to block it up in the river mouth,
and to keep the Portsmouth squadron from effecting a junction with
the main body. But Blake had stolen a march upon the Dutch
Admiral, and when the latter came up with Cape la Hogue, he was
surprised to find a force equal to his own prepared to dispute the
passage of the seas so lately swept by his broom. He, however,
accepted battle eagerly, for he was confident of victory.

THE BATTLE OFF PORTLAND.

Day was just breaking, on the morning of the 18th of February,


1653, when the Dutch van was made out from the masthead of the
Triumph. Blake was on deck at once, and a grand spectacle he must
have had, as the sun rose, showing the heaving wintry sea covered
with ships, their sails and pendants lighted up by the early rays.
There were seventy-three Dutch ships of war, convoying more than
three hundred merchant ships. Owing to the darkness the ships had
not seen each other until only three or four miles apart. The English
flag-ships happened to be all within hailing distance of each other,
but General Monk was some miles astern, in the Vanguard, and the
bulk of the English fleet about five miles astern of Admiral Blake
when the Dutchmen hove in sight.
Tromp, with his seaman’s eye, saw his advantage, and at once
availed himself of it.
With the wind in his favor he might have forced his way by, and
carried his convoy to the Scheldt in safety, returning at his leisure to
give battle. But he chose to play a bolder game, and fancying that
his enemy’s vanguard of some twenty ships could not resist the
weight of his attack, he sent his fleet of traders to windward, out of
range, with orders to await there the issue of the engagement.
This great battle was fought under circumstances which lent it
thrilling interest. Both nations had had time to collect their best
fleets, and the largest and finest vessels they had were there
arrayed against each other, commanded by the most renowned
Admirals. Blake, Deane, Penn and Lawson were on one side; Tromp,
De Ruyter, Evertz, Swers, Floritz and De Wilde, all great names, on
the other.
The fleets were nearly equal in strength, and their relative merits
had to be determined on that day. Even the common seamen on
each side felt that this was the decisive battle.
At the outset the Dutch had the wind, and therefore, the
advantage of position. They were also well up together, and when
they opened on the English vanguard it seemed almost impossible
for only about twenty ships to withstand the crash of so many heavy
broadsides.
As usual, the Triumph was the first of the English to engage, and
the Brederode, ever in the van, was ready to meet her, reserving her
fire until within musket shot, when her broadside would have most
deadly effect. With a strong favoring breeze Tromp shot by the
Triumph, pouring a fearful broadside into her as he passed; and
then, tacking, gave her a second and more destructive one, leaving
her with decks strewed with killed and wounded, and torn canvas,
stranded rigging, and tottering masts. After this the two Admirals
parted for the day, for Penn came dashing up, in the Speaker,
followed by other vessels, to cover Blake from some part of the
circle of fire which threatened him with destruction.
As the other divisions of the English fleet came up the battle
became general. On both sides the wreck and destruction was awful.
In less than one hour after the first shot was fired almost every ship
engaged had received serious damage. At one moment an English
crew was to be seen boarding a Dutch man-of-war, and the next
they would be driven back, and their own vessel boarded in turn by
the doughty Hollanders. Here might be seen a ship completely
wrapped in flames; there one foundering, with all her men, their
cries for help unheeded by either friend or foe; perhaps elsewhere
occurred a fearful explosion, which sent ship and crew into the air
together, and added fresh volume to the lurid cloud which hung over
the scene.
Cotemporary writers say that the tremendous roar of artillery
could be heard along the shores of the Channel, from Boulogne on
the one side to Portland Bill on the other.
About midday Monk succeeded in arriving up with his division, and
the contest was now entirely upon equal terms. De Ruyter, as ever,
in the forefront of battle, added, if possible, to his already well
earned renown. Early in the day he singled out and engaged the
Prosperous, a hired ship of forty guns, commanded by a Captain
Barker. The English ship maintained so steady a fire, in response,
that De Ruyter, impatient, and wishing to finish her and pass on to
fresh combats, called away his boarders, ran his ship alongside the
Prosperous, and the Dutchmen gallantly boarded, leaping down on
her deck, sword and pistol in hand. But, to their surprise, they were
driven back again in a very few minutes. Not satisfied with forcing
back his assailants, Barker threatened De Ruyter in return; but the
brave old Dutchman, singing out, “Come lads! that was nothing! at
them again!” led them to a second and more successful boarding.
Barker and his officers were unable to resist this renewed assault,
and were soon prisoners. At this very moment Blake, with several
vessels, came up to their assistance. The prize was recovered, and
Ruyter himself was surrounded by the English. Vice Admiral Evertz
and Captains Swers and Krink hastened, in their turn, to relieve
Ruyter from his dangerous position, and the battle soon raged with
extraordinary violence around this new centre. Penn’s ship, the
Speaker, was so shattered as to be unfit for further service, and
when night put an end to the first day’s engagement he was
despatched to the Isle of Wight, for the ships left at that station.
The Dutch Captain Cruik, in the Ostrich, was very conspicuous in
this day’s engagement. Like a true sailor, he fought till he had not a
spar showing above his bulwarks, and his deck was literally covered
with the dead and wounded of his devoted crew. At last he was
boarded by the English; but, as the ship appeared to be sinking, and
her officers and crew were nearly all killed or wounded, the boarders
made hasty plunder of her valuables and left her to her fate. De
Wilde offered his aid to bring her off; but suddenly it fell calm, and
not having a particle of sail spread, the attempt to tow her off failed,
and she was again abandoned. Next morning Blake found her
floating about, without a living soul on board, and the unburied
corpses lying just as they had fallen; occasionally, under a more than
ordinarily heavy roll, showing a startling movement.
Captain Swers, afterward a most distinguished Dutch Admiral, was
taken prisoner. He had gone to the assistance of Captain De Port,
who was being roughly handled by two English frigates, and the four
ships were immediately locked together. De Port’s ship had several
shots between wind and water, and began to fill. He himself was
severely wounded by a large splinter; nevertheless, as he lay on his
back, in great agony, he waved his sword, and shouted words of
encouragement to his men, until ship and crew all went down into
the deep together.
The Dutch had always been noted for close fire, but on this
occasion the English fire proved quite as deadly and regular. Swer’s
ship foundered from shot holes, himself and those of the officers
and crew left being taken on board the frigates, and their lives thus
preserved.
Toward dusk of the second day Blake felt himself in a sufficiently
strong position to be able to send some of his best sailing ships with
orders to gain the wind, and if possible prevent the escape of the
vast fleet of rich traders which had remained hove to, awaiting the
issue of the action. Tromp saw the movement, and at once divined
the cause, so he fell back, with a great part of his fleet, to cover his
convoy. This movement put an end to that day’s action; for, seeing
their Admiral make sail and leave the enemy, some of the Dutch
Captains made sail, and, under the cover of night, were soon far
away. Blake remained on the scene of action, but with his men too
much exhausted, and his vessels too much damaged, to permit of a
chase in a mid-winter night.
Both sides had shown the most devoted valor and untiring zeal.
The Dutch had had eight large ships either taken or destroyed.
During the battle the Prosperous, the Oak, the Assistance, the
Sampson, and several other English ships had been boarded and
taken, although most of them were afterward recaptured. The
Sampson was so damaged that her Captain, Button, and his officers
and men, were taken out of her, and she was allowed to sink.
The flag-ship Triumph suffered most severely. Her Captain,
Andrew Ball, was killed, as was the Admiral’s secretary, Sparrow,
who was shot down at his side, and nearly half her crew were killed.
Blake himself was wounded in the thigh; and the same ball which
lamed him for life tore away a part of Deane’s buff coat.
The Dutch loss was never ascertained, but it was very heavy, for
some of their ships had nearly all the men killed or wounded; and
the appearance of their gun-decks, spattered with blood and brains,
shocked even the callous captors.
At night Blake sent many of his wounded on shore, where
preparations were made for them, all classes turning out to relieve
and succor them. Collections of money and clothing were made in all
the South and West of England, and the miserable provision made at
that day for the sick and wounded was supplemented by the
spontaneous gifts of the people.
Blake’s own wound, which was not really dangerous at first,
required repose and proper treatment, but he would not go on
shore.
At night the fleets lay close together, never losing sight of each
other’s lights during the whole of the long winter’s night. During
these dark hours all hands were employed in stopping leaks,
repairing sails, and getting gun tackle in readiness to renew the
contest in the morning.
A dead calm had succeeded to the fresh breeze which was
blowing when the battle began; and if it continued the Dutch could
have no choice as to renewing the fight. But at daylight a light
breeze sprang up, and Tromp, anxious to take home his convoy in
safety, disposed his men of war in the form of a crescent, with the
traders in the centre, and crowding all sail, stood directly up
Channel. Blake followed in pursuit, with all his available ships. It was
noon, however, before the Triumph came within gunshot of the
rearmost Dutch ship, and it was two in the afternoon before the
main body came up with them, off Dungeness.
Seeing that he would be compelled to fight, Tromp ordered his
convoy to make the best of their way to the nearest Dutch port,
keeping close along Calais and Dunkirk, for protection; and then he
turned upon his pursuers, like a lion at bay.
The battle was renewed with great fury. De Ruyter again
performed miracles of courage and conduct, but the fortune of war
was against him. After some hours his own ship became
unmanageable, and would have fallen into the enemy’s hands but
for Tromp, who saw his danger, and sent a ship to extricate him.
With great difficulty this was accomplished. An hour or two later
Tromp began to haul off towards Boulogne, but it was not until night
fell again that the hostile fleets separated once more.
That night proved bitterly cold, but unusually clear, for winter, so
that the English fleet was enabled to keep the Dutch lights in sight.
On this day just closed Blake had captured or destroyed five of his
enemy’s ships, and, in consequence of the recent reforms, had not
had occasion to complain of the want of courage, steadiness or
promptness of a single commanding officer. In the Dutch fleet Tromp
had to contend against want of concert, party bitterness and
personal envy in many of his captains. At the close of this day’s
fighting several of the latter sent word on board the Brederode that
they were out of powder, and Tromp was compelled to send them
away in the night, so as to prevent cowardice and treason from
spreading to the other ships. To conceal his true motive he
pretended to give them orders to take a new position, to windward
of the convoy, to protect them from the light craft of the English,
which were hovering about.
But when day dawned Blake saw at a glance that the Dutch fleet
was considerably reduced in numbers, and inferred that a squadron
had been despatched during the night to cover the convoy; and he
at once sent a squadron of fleet sailers after them, while he himself
bore down once more on his reduced but unconquered enemy.
Tromp met him with undaunted courage, and, as usual, fought
desperately. But the most he could now hope for, with his reduced
fleet, was to occupy Blake until his richly laden convoy could reach a
friendly port. But even this seemed doubtful. After the first shock of
this day’s renewed fighting he felt that he would be able to afford
them but small protection; and he sent Captain Van Ness to the
merchant fleet, with orders to crowd all sail for Calais Road. As the
fight went on he again sent another officer to hurry them in, or else
the English frigates would soon be among them. But the wind was
blowing from the French coast, and Van Ness’ most energetic efforts
were insufficient to carry the confused mass of traders near enough
to the Roads to be out of danger. More than half the men-of-war and
frigates of the Dutch fleet had been scattered, taken, or sunk, by
this time, and many of the captains who were left had, contrary to
Tromp’s orders, retreated upon the flying convoy. Confusion now
reigned, and as the English came up, the merchantmen, in their
alarm, either ran foul of each other and knocked themselves to
pieces, or fell into the enemy’s hands.
Still engaged with the retreating Dutch men-of-war, Blake arrived
on the scene in the afternoon, and finding some of the merchant
ships actually throwing themselves into his way, he began to suspect
that it was done to lure him to make captures and give the
discomfited fleet time to rally. He accordingly gave strict orders that
every man-of-war still in condition to follow and fight should press
on after the main body of the enemy, leaving the traders to be either
picked up by the frigates detailed for the purpose, or driven where
they could be captured after the Dutch fleet was swept from the
Channel. At last darkness put an end to the chase. Tromp ran in and
anchored the remnant of his fleet under the French shore, about
four miles from Calais. They were in number about one-half what he
had sailed with; and all of them more or less damaged.
Blake’s pilots all agreed that Tromp could not, as the winds and
tides then were, come out to sea again, in order to get home. He,
therefore, anchored his fleet also, and set to repair damages. The
night was dark and a gale was blowing, and ships’ lights could not
be seen at any distance. At daylight the sea was clear where so
many ships had been at anchor at sunset. Tromp had slipped away
toward Dunkirk; and afterward succeeded in entering the various
ports of Zealand.
Blake felt that it would not be well for him to follow the enemy
into the flats and shallows of his own coast, and so he stood over for
England. The bad weather continuing, he carried his fleet and the
prizes into Stoke Bay, whence he reported his success to Parliament.
During these successive days of fighting there had been great loss
of life. Seven Dutch captains were killed, and three taken prisoners.
Three English captains were killed, and Blake himself, Rear-Admiral
Lawson, and many other distinguished officers wounded. The total
loss on each side was never published. A day of thanksgiving was
appointed in England, and provision made by public subscription, as
well as by the State, for the widows and children of those who had
fallen.
Blake took no rest, in spite of his wound, but refitted and
revictualed his ships, intending to strike a blow at the Brest
privateers.
But in April he received information that the equally indefatigable
Tromp was making great efforts to equip another fleet. He at once
proceeded off the Texel, with about one hundred sail. In the Texel
he saw many men-of-war, but Tromp himself had already gone out
to the Northward, to convoy in an expected fleet of traders from
Spain and the Levant. By good seamanship he brought them safe
home, but not by the Channel which he had formerly brushed down
with his broom.
Then came Cromwell’s assumption of supreme power; and political
events of magnitude usurped, in English minds, the Dutch war, and
all other matters.
Blake’s opinions were known to be unfavorable to the extreme
practices of the Protector, and when the Dutch heard of the
revolution which had occurred in London, by means of the army,
they jumped to the conclusion that their redoubtable naval enemy
would no longer carry on the war with the same energy. But in this
they were deceived. Blake was loyal to his country and her welfare,
before all, and told his captains that “it was not for them to mind
affairs of State, but to keep foreigners from fooling us.” Though he
suspected Cromwell, and abhorred military rule, he had patriotism
enough not to deprive his country of such services as he could
render, because it had allowed itself to submit, in an irregular way,
to a power not of his choosing.
It was fortunate that he took this resolution promptly, for Tromp,
Evertz, Ruyter and De Witt, under the impression that the English
fleet was divided by political discord, sailed for Dover Road, with one
hundred and thirty ships, manned in haste, took some prizes, and
began firing upon the town.
The English fleet was then in three divisions. Deane and Monk,
sailing together, in the Resolution, had under their orders thirty-eight
sail, carrying 1440 guns, and about 6000 men; Penn had thirty-three
sail, with 1200 guns, and 5000 men; and Lawson had thirty-four
ships, with 1200 guns, and about 5000 men. The Dutch had a few
more ships than the English, but were about equal in guns and men.
When Tromp thus suddenly reappeared, Blake was at the North,
with a small fleet, but couriers rode overland, day and night, to
apprise him that the Dutch were again in the Channel, and had fired
upon Dover.
He made all sail for the South as soon as he heard this important
news, having a favoring breeze, and burning with anxiety to join the
main fleet before a battle took place.
But on the 2d of June, before he arrived, the hostile fleets sighted
each other near the Gable, and were soon in collision. Lawson was
in advance of the English fleet, and broke through the Dutch line
about midday, separating Ruyter’s division from the rest, and
engaging it heavily before the main body on either side could get up.
In about an hour Tromp came to Ruyter’s relief, and the action
then became general. One of the first shots which struck the
Resolution killed General Deane, and Monk threw his cloak over the
mangled body, and called to his men to avenge his death. For some
hours the Dutch fought with reckless courage, and when night fell
both fleets had sustained great damage and loss, but nothing was
decided. All that night, while the hostile fleets lay to, near each
other, repairing damages, Blake was carrying every possible stitch of
sail, to reach the fleet. He was, of course, unaware of the day’s
events, of the death of his friend and comrade, Deane, and of the
doubtful position of the English fleet. The officers and men who had
been engaged on the English side watched anxiously for signs of the
coming of their great leader, but when the summer morning dawned
no trace of his sails could be seen on the northern horizon. Tromp
was unaware that Blake was expected that day, as he believed him
to be too far North to be recalled. He, therefore, spent the whole
morning in manœuvres for the weather gage. A calm put a stop to
this at about noon, and then the great guns opened again on both
sides, and the battle was renewed with great energy, but neither
side seemed to have any decided advantage. If there was any it was
upon the side of the Dutch. But early in the afternoon Blake
managed to draw near, with a light air, and his thundering
broadsides upon the flank and rear of the Hollanders put new life
into the harassed and flagging English. Young Blake was the first of
the English reinforcement to engage the enemy, and, as if to
announce the arrival of the great captain upon the scene, he broke
through the Dutch line, belching forth death from both batteries, and
greeted with tremendous cheers from the English ships.
By four o’clock the battle was over, and the retreat of the Dutch
began. Tromp fought with the energy of despair; but nothing could
withstand the onset of such a force, led by Blake himself.
The Brederode boarded Penn’s flag-ship, the James, but the attack
was repulsed by Penn’s crew, who, in turn, boarded the Brederode,
and would probably have captured that ship had not Tromp, resolved
not to fall into his enemy’s hands alive, thrown a match into the
magazine, and caused an explosion, which sent the upper deck and
the gallant boarders upon it into the air, the planks shivered into
splinters, and the men horribly scorched and mutilated.
Most strange to relate, Tromp himself was but little hurt; but a
report of his death spreading, many of his captains, thinking all was
lost, bore up and fled. De Ruyter and De Witt exerted themselves in
vain to stem the tide of disorder and defeat. Tromp, after his
marvelous escape, left the wrecked Brederode for a fast sailing
frigate, and passed through his fleet, encouraging those who stood
fast, and threatening the waverers, while he fired upon some who
fled the scene.
But it was too late. The day was lost, and the brave old man had
at last, reluctantly, to give the order for retreat.
Just then a fresh gale sprang up, but the English fleet pressed sail
after them, sank some ships, captured others, and were only made
to cease by darkness coming on.
Favored by the darkness, Tromp anchored in Ostend Road, and
next day escaped, with the remnant of his fleet, into Weilingen.
The news of this great defeat threw the United Provinces into a
dangerous ferment. The mob rose in many towns, and committed
great excesses. The Admirals offered to resign; and they all declared
that they would go to sea no more with such an organized fleet as
they then possessed. De Witt openly acknowledged that the English
were, for the present, masters of the sea.
The naval power of Holland was indeed, for the time, completely
broken; and the final battle of the war, hazarded and lost two
months later, was an expiring effort, made with crippled resources,
and under circumstances of the greatest discouragement.
The English fleet, though it kept the sea, was scarcely in better
condition than that of their enemy. Blake kept the Dutch coast
blockaded, nevertheless, while their commerce was intercepted and
their fisheries idle. In doing this his fleet suffered from bad and
scanty provisions, which brought on much sickness. Blake himself
fell ill, and had to be taken on shore, more dead than alive, leaving
to Monk, Penn and Lawson the carrying out of his plans.
One more blow, and all was over. In the temporary absence of the
English blockading fleet, the Dutch squadrons at Weilingen and the
Texel put to sea, and effected a junction. But their shattered fleet
was felt to be unfit to cope with their powerful opponents, and when
they met the English fleet, they endeavored to avoid a battle. But
Penn and Lawson pressed sail to come up with them, and some
fighting had already taken place, when night came on, and stopped
it.
Next day a heavy gale prevented a renewal of the action; but on
the next the fleets once more met.
During the close fighting which ensued the aged and able Van
Tromp received a musket ball through the heart, and fell upon his
own quarter-deck,—an appropriate death for the gallant but
unfortunate veteran.
At his death his fleet fled; the English pursuing without mercy, for
the ruthless Monk was now in command, and had ordered his
captains to give no quarter. They made no prisoners; and the end of
the engagement was rather a massacre than a battle.
Immediately after this the humbled States General sued for peace.
IX.
FRENCH AND DUTCH IN THE MEDITERRANEAN. A.D.
1676.

n the latter part of 1674 Messina and a part of Sicily


revolted against the Spaniards, and Louis XIV
resolved to sustain the insurrection, in pursuance
of his political designs. In consequence, Duquesne,
who had just been named General of the Naval
Forces, sailed from Toulon, on January 29th, 1675,
with eight ships-of-war, bound for the Sicilian
coast.
Before we detail his operations there, it may be
of interest to give some sketch of this very
remarkable man.
Abraham, Marquis Duquesne, one of the greatest
seamen France ever produced, was born in Dieppe,
an important seaport in the north of France. He
entered the navy early, and soon rose to the command of a ship, in
which he joined in the recapture of some of the French islands from
the Spaniards, for which service he was reported most favorably to
the great Richelieu. During these operations he learned of the death
of his father, in action with the Spaniards, and Duquesne seems ever
after to have entertained the greatest dislike for this nation, causing
them to feel the effects of his resentment on numberless occasions.
In 1638 he, under circumstances of great difficulty and danger,
rescued from under the guns of St. Sebastian several French vessels
which had been stranded there. The same year, at the battle of
Gattari, Duquesne decided the victory by blowing up the Spanish
admiral’s flag-ship, by means of a fire-vessel.
The next year he served on the Biscayan coast, and, at Santona,
was dangerously wounded in the jaw by a bullet, while boarding a
Spanish galleon.
During 1641 he served against Spain in the Mediterranean, was
constantly engaged, and again wounded. In succeeding years he
was actively employed, at Cape de Gatte, and at Carthagena, and
was again wounded.
Already a veteran, Duquesne was obliged, by the neglect into
which the French navy fell after Richelieu’s death, to take service
under the Swedes, then engaged in a naval war with Denmark.
Queen Christina, who knew his merit, received him cordially, and
made him a vice-admiral.
In this capacity he was engaged in the naval battle of 1644, under
Fleming and Torstensen, against the old king, Christian IV, of
Denmark. He also served in other naval battles, in the north, under
Admiral Wrangel.
Peace being concluded between Denmark and Sweden, Duquesne
left the service of the latter State, and returned to his own country;
and, in 1645, was again actively employed against Spain, and was
again wounded.
In 1647, being then a capitaine de vaisseau, he was sent to
Sweden to purchase four vessels of the line for the French navy.
After this he had command of Dunkirk, in French Flanders, for five
years.
In 1653 occurred the naval operations of the Duke de Vendome,
about the mouth of the Gironde, in consequence of the civil war of
the Fronde. The French navy had at this time so decreased that the
Duke, in summoning Duquesne from the North Sea to his assistance,
was obliged to ask the latter to man and equip some of the vessels
at his own expense.
On his way down the Channel to join the Duke, Duquesne met an
English squadron, which summoned him to lower his flag, a token of
submission at that time imposed upon all foreigners by the English,
if within Ushant or even Finisterre. To this demand Duquesne
returned a haughty refusal, whereupon a very close and murderous
engagement took place, which resulted in the English, although
quite equal in guns to the French, being put to flight.
On arriving off the Gironde a Spanish squadron, operating in
connection with the insurgents, attempted to bar his progress; but
he drove them off, and succeeded in joining the Duke, and greatly
assisted in the reduction of Bordeaux and all Guienne.
In recognition of his services Anne of Austria bestowed upon
Duquesne a chateau and estate in Brittany, with a promise of
reimbursement for his expenses in fitting out his squadron.
The peace of 1659 relegated Duquesne to civil life; but Colbert,
during this cessation of arms, had the wisdom to imitate Richelieu in
fostering and rebuilding the navy of France, so that, when war broke
out between France and Holland, in 1672, the former was able at
once to send to sea a formidable fleet
During this year Duquesne held a high command in the great
naval battles in the North Sea; particularly those off Southwood,
where Vice Admiral d’Estrées was opposed to the Dutch Admiral
Benkaërt; as well as the two battles where the combined French and
English fleets, under Prince Rupert, Admiral Spragge, and d’Estrées,
fought the Hollanders under Ruyter, Cornelis, Tromp and Benkaërt.
England suddenly made peace with Holland, but France continued
the war, with the alliance of Spain, Germany, and the two Sicilies;
and it is at this point that we take up Duquesne’s battles with the
Dutch fleet.
When he sailed from Toulon, in January, 1675, he had on board
the Duke de Vivonne, General of the Galleys of France, who had
been named Viceroy of Sicily. He had in charge a convoy, also, with
a great store of wheat and other provisions for Messina.
On February 11th, in sight of the Sicilian coast, Duquesne and
Vivonne were attacked by a Spanish fleet of twenty men-of-war and
seventeen galleys, commanded by Don Melchoir de la Cueva.
Duquesne sustained the attack of this large force with such vigor
and determination that he gave time for the Chevalier de Valbelle to
arrive from Messina with a considerable reinforcement, when, in his
turn taking the offensive, he drove off the Spanish fleet, pursued it
until it took refuge in Naples, and then triumphantly entered Messina
with his convoy.
He soon after, in concert with Vivonne, captured the town of
Agosta; after which Duquesne was sent back to France, with the
greater part of the fleet, to bring back to Sicily munitions of war and
reinforcements, then much needed at Messina.
On his arrival at Toulon, Duquesne learned that the great Dutch
naval commander, Ruyter, had entered the Mediterranean, to
operate in conjunction with the Spanish fleet. He was placed in
command of a very considerable fleet, to enable him to measure his
forces with those of the redoubtable Hollander who had been so
successful against the English and others. Duquesne was then sixty-
four years of age, and Ruyter was near seventy.
The Dutch Admiral had risen from the lowest origin to be the
Admiral of Holland. This was the result of his own great ability and
bravery; and he was so much the favorite of the Dutch government
and people that, although he begged to be excused from further
service, on account of age, nothing would satisfy them but that he
should make this one important campaign. Duquesne sailed again,
from Toulon, on the 17th of December, 1675, with a fleet of twenty
ships-of-the-line, and six fire-ships, bound for Messina.
As soon as the veteran Ruyter heard that he had put to sea, he
hastened to meet him. Some days before this an English trader had
met the illustrious Admiral of Holland off Melazzo, about twenty-five
miles from Messina. The Englishman inquired what he was doing in
those parts, and Ruyter replied that “he was waiting for the brave
Admiral Duquesne.”
The hostile fleets met on the 16th of January, 1676, off the Lipari
Islands, between Salino and Stromboli, under the very shadow of
the ever active volcano.
The whole day was passed in reconnoitring each other’s strength,
and in manœuvring; and during the whole succeeding night the
fleets were working for the weather gage. Each commander had a
true respect for the courage and ability of his opponent; and each
knew that he must expect an exceptionally vigorous attack.
On the morning of the 8th, at daylight, Duquesne, who had
obtained the advantage of the wind, crowded sail down upon the
Dutch fleet, which lay about two leagues to leeward.
The French were in three divisions. Their van was commanded by
Preuilly d’Humières; the rear by Gabaret l’ainé, both excellent
officers; the centre was under the command of Duquesne himself,
who had his flag in the Saint Esprit, and was immediately supported
by the Chevalier de Valbelle, in the Pompeux, and that splendid
sailor, Tourville, in the Sceptre.
The Dutch fleet, which comprised twenty-four ships-of-the-line,
two flutes, and four fire-ships, was also divided into three. Their van
was commanded by Verschoor, their rear by De Haan, and the centre
by Ruyter himself.
The French came down in such a beautiful line that Ruyter himself
showed and expressed a sailor’s admiration for the skill and
discretion shown. The French van opened fire at about nine in the
morning, and both fleets immediately engaged. The battle, as may
be supposed from the character of the officers, was a most obstinate
and well contested one, and continued for seven hours, with very
varying fortunes. At the termination each side claimed a victory; but
the advantage was clearly with Duquesne, for the Dutch fleet, which
was there to bar his passage, was so much injured that Ruyter could
not prevent Duquesne from entering Messina with his fleet; which he
did, on the following day, without molestation from the Dutch.
In the course of the battle Ruyter’s flag-ship, the Concordia, and
Duquesne’s flag-ship, the Saint Esprit, had an encounter, which
lasted until the Concordia declined further battle, after so sharp and
murderous an engagement that Ruyter said it was the hottest fight
he had ever been in in his life; and no one was a better judge.
But this battle of the Lipari Islands was only the prelude to a still
more desperate and important one.
The active and enterprising Duquesne, having refitted at Messina,
sailed from that port again, with two objects in view. The first was to
protect important convoys of stores and provisions expected from
France; and the second to protect the town of Agosta from an
expected attack by the Dutch fleet.
Ruyter, hearing that Duquesne was again at sea, went straight to
meet him, with his fleet reinforced by a Spanish squadron, under the
command of Don Francisco de la Cerda.
The rival Admirals made each other out on the 21st of April, and
the next day the fleets met off Agosta, which is some fifteen miles to
the northward of Syracuse.
Duquesne had now thirty sail-of-the-line, and eight fire-ships.
Ruyter had twenty-nine sail, nine galleys, and four fire-ships.
On this occasion the French Admiral had entrusted the command
of his van to Almeiras, his rear to Commodore Gabaret l’ainé, and
himself commanded the centre.
Ruyter, in this battle, preferred to command the van himself, and
not the centre, as was usual for the Commander-in-chief.
The Spanish ships he put in the centre of his line of battle, and
Vice-admiral de Haan in command of his rear division.
At about two in the afternoon Ruyter, with the van division,
attacked that of Almeiras, which sustained his vigorous assault with
great steadiness. Unfortunately, however, Almeiras was soon killed
by a cannon-ball, and wavering and indecision at once showed itself
in his division; but the Chevalier de Valbelle coming up, and
assuming command, the temporary confusion ceased, and the
division conducted itself well. Just then Duquesne came down to the
assistance of his van; and the battle became general all along the
line, the firing of the two well drilled and well appointed fleets being
described as unusually sharp and terrible.
The two Admirals’ ships, the Saint Esprit and the Concordia, met
once more, and a most obstinate and destructive fight ensued. For a
long time it was doubtful which would have the advantage. At last
the Concordia suddenly and unexpectedly slacked her fire; then it
ceased, and she wore ship, and made sail in retreat. Ruyter had
been badly wounded, his left foot being carried off, and his right leg
broken in two places, while, in falling, he had injured his head
severely.
Even after he fell he continued to exhort those about him to fight
courageously, but, disheartened by the strong resistance of the
French, and by the desperate wounds of their beloved Commander-
in-Chief, the Dutch van, from that moment, ceased their fire and ran
to leeward, leaving their centre and rear still heavily engaged.
Vice Admiral de Haan was true to his reputation as a superior sea
officer, and made desperate efforts to retrieve the fortunes of the
day, but the victory was with the French, and De Haan was glad to
be able to withdraw his fleet, at nightfall, and to take refuge in the
convenient port of Syracuse.
Duquesne remained off the port all night, his battle lanterns
burning, and the next day took every means to provoke the Dutch to
come out and renew the battle, but without effect.
This ended the naval battle of Ætna, or Mount Gibel.
Ruyter died seven days after the battle.
On the 28th of May Vivonne, the Viceroy of Sicily, came out of
Messina with Duquesne, in his flag-ship, the Saint Esprit, with the
intention of attacking the combined fleets of Holland and Spain,
which were then together, and lying in Palermo. They arrived off that
city on the 31st, and next day the Spanish and Dutch fleets came
out. But it was not until the second of June that a decisive battle
was fought. It was decided in a comparatively short time, for no less
than twelve of the Dutch and Spanish ships, set on fire by the fire-
ships of Duquesne, blew up, destroying, besides their officers and
crews, Admiral de Haan, Don Diégo d’Ibarra, Don Francisco de la
Cerda, Flores, and other admirals and principal officers.
The French loss in this last engagement was comparatively
insignificant.
Upon his return from this engagement Duquesne met the
“Concordia,” which had left Syracuse with the remains of Ruyter,
which she was carrying back to Holland. Giving the ship free
passage, he saluted the remains of the illustrious seaman in an
appropriate manner. Louis XIV, in learning of Ruyter’s death, ordered
all of his forts and batteries (in sight of which the Dutch ship passed
while bearing his remains) to salute. This was considered very
remarkable, for Ruyter was a Protestant, which, in that day, was
considered worse, in France, than being a political enemy.
Still more remarkable, Duquesne was a Protestant, and when it
came to recompensing him for his long and arduous and
distinguished services, Louis XIV required him to renounce the
Protestant faith, promising him a Marshal’s baton, and other honors.
Duquesne simply replied that, if he was a Protestant, his services
were Catholic. He received the domain of Du Bouchet, and
afterwards a Marquisate, but never was really in favor with Louis.
It may be of interest to some to continue the history of this great
French sailor.
He continued to serve at sea, though an old man; and among
some other exploits of his of this date, was the burning of some
Spanish vessels in the very port of Barcelona.
After the peace of Nimeguen he kept very quiet, and seldom went
to court, an unusual thing in those days, especially for those who
had such claims as Duquesne.
In 1682 he was sent with a fleet to Algiers, which city he
bombarded for several days, with great effect, but was compelled,
by bad weather, to return and winter at Toulon.
In June, 1683, he reappeared before Algiers, completely reducing
the place by his fire, so that the population rose up against the Dey.
All the French slaves were given up, but Mezzo Morto, who had
succeeded to the Dey, who had been put to death by the insurgents,
renewed the defence, when the bombardment was continued by
Duquesne, to such an extent that it rendered the Algerines harmless
for a long time, by destroying all their vessels and naval stores.
Two years after this Duquesne commanded the French fleet which
bombarded Genoa, and, at different times, inflicted so much damage
that the Doge and four Senators were obliged to come to Versailles,
to beg pardon, in person, from the King. It was on this occasion that
the Doge was asked what he found most surprising in Versailles, and
answered “that it was to find himself there.”
The Genoese expedition was Duquesne’s last service. He had been
sixty years in actual service, a time only rivaled by Doria. The
revocation of the Edict of Nantes distressed the veteran beyond
measure. He alone, of all the Protestants of France, was excepted
from proscription, and enabled to retain his rank and honors. But his
children and friends, his relatives and co-religionists, were banished
from their homes; and this had a most depressing effect upon the
Admiral, and, no doubt, hastened his death.
He died at Paris, on February 2, 1688, aged seventy-eight years.
With his last words he implored his eldest son not to serve against
his country, as many of the exiled Huguenots were then doing. So
great was the feeling at the time of his death, that his remains were
privately buried, his son’s request to have them sent to him in
Switzerland being refused; but he erected a tablet to his memory.
This was in great contrast with the splendid obsequies and the
tomb given by Holland to his adversary, Ruyter.
Louis XVI afterwards tried to make reparation for this treatment of
such a great French naval hero, by placing Duquesne’s portrait in the
royal apartments at Versailles. In 1844 the City of Dieppe erected a
bronze statue in his honor, and one of the large vessels of the
French navy is generally called “Duquesne.”
A CARAVEL OF THE TIME OF COLUMBUS.
X.
BATTLE OF CAPE LA HAGUE. A. D. 1692.

a Hague, or La Hougue, is in the Department of the


Manche, in the north of France. It is to the
westward of Cherbourg and on the same
peninsula. It is often confounded with La Hogue,
another cape to the eastward of Cherbourg; and
the battle which took place off this point in 1692,
and which gave such a fatal blow to the naval
power of Louis XIV, is generally called, in the
histories, La Hogue.
Louis XIV, having seen the failure of the
expedition which he had prepared to attack
Ireland, with a view to the re-establishment of
James II, resolved, if possible, to strike a vital blow
at England in another manner. He, therefore, prepared an armament
which was to protect and take part in a descent upon the territory of
England, herself the hereditary enemy of France.
The French King reckoned not only upon the number and force of
his fleet, but also upon the revulsion in public opinion which seemed
to have taken place in England, in regard to King William. Many
eminent persons, among others the famous Duke of Marlborough,
were known to have opened secret relations with James II; and that
Prince had reason to count upon many adherents in the English
fleet, which he had for a long time commanded, previous to his
accession. Among others, he is said to have depended upon Admiral
Russel and Rear Admiral Carter.
Louis XIV, confident in the ultimate result of all his designs, laid
down the plan of a naval expedition, by which he would be enabled
to land a force of 30,000 men, fully equipped, upon the English
coast.
Tourville was ordered to the command of the French fleet. Aimé
Hilarion de Cottentin, Count de Tourville, was born at the Chateau of
Tourville, in Normandy, in 1642. He entered the Order of Malta while
still a boy, and at the age of eighteen began to serve in the galleys
of the Order, where he soon made a reputation, so much so that he
was called to court, and given the grade of Capitaine de Vaisseau.
He served under the Duke de Beaufort, at the relief of Candia, then
besieged by the Turks; and afterward distinguished himself in the
war with Holland; and still later, distinguished himself at the relief of
Messina, which had revolted against the Spanish rule.
The following year he took part in Duquesne’s brilliant expedition
against the Algerines and Tripolitans, when the Corsairs received the
most crushing blows which had ever been dealt to them, up to that
time.
In 1684 he participated in the bombardment of Genoa, and four
years after, in a successful cruise against the Dutch. In the same
year he inflicted a severe bombardment upon Algiers.
In 1689, being now an Admiral, he commanded a fleet which, in
connection with one under D’Estrées, was to support the cause of
James II. This combined fleet succeeded in landing some few men
and some munitions of war in Ireland, but, on the whole, the
operation was a failure. While in command of the French fleet, in the
year following, he had a battle with the Anglo-Dutch fleet, off the
Isle of Wight, which was a most inglorious affair for the English,
their Admiral, the Earl of Torrington, behaving with great want of
spirit. The result was that Tourville captured and burned many of the
English ships, not losing one himself. The sturdy Dutchmen made a
good fight, and came off much better than their English allies.
In 1692, as above stated, Tourville was ordered to the fleet fitted
for a descent on England; and now we shall take up the account of
the battle once more.
The bulk of Tourville’s fleet was in Brest, and as the spring opened
he received orders to sail from that port, enter the Channel, and
attack the English fleet, no matter in what force they might be

You might also like