0% found this document useful (0 votes)
9 views

Complete Download Data Abstraction Problem Solving with Java Walls and Mirrors 3rd ed Edition Prichard PDF All Chapters

The document promotes various educational ebooks available for download at ebookgate.com, including titles on data abstraction and problem-solving using Java and C. It provides links to multiple editions and related subjects, emphasizing instant access to digital formats like PDF and ePub. Additionally, it includes detailed contents and structure of the book 'Data Abstraction and Problem Solving with Java: Walls and Mirrors, 3rd Edition' by Janet J. Prichard and Frank M. Carrano.

Uploaded by

focusluzzigo
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
0% found this document useful (0 votes)
9 views

Complete Download Data Abstraction Problem Solving with Java Walls and Mirrors 3rd ed Edition Prichard PDF All Chapters

The document promotes various educational ebooks available for download at ebookgate.com, including titles on data abstraction and problem-solving using Java and C. It provides links to multiple editions and related subjects, emphasizing instant access to digital formats like PDF and ePub. Additionally, it includes detailed contents and structure of the book 'Data Abstraction and Problem Solving with Java: Walls and Mirrors, 3rd Edition' by Janet J. Prichard and Frank M. Carrano.

Uploaded by

focusluzzigo
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/ 82

Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.

com

Data Abstraction Problem Solving with Java Walls


and Mirrors 3rd ed Edition Prichard

https://ebookgate.com/product/data-abstraction-problem-
solving-with-java-walls-and-mirrors-3rd-ed-edition-prichard/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Data Abstraction Problem Solving with Java Walls and


Mirrors 3rd Edition Janet J. Prichard

https://ebookgate.com/product/data-abstraction-problem-solving-with-
java-walls-and-mirrors-3rd-edition-janet-j-prichard/

ebookgate.com

Data Abstraction and Problem Solving with C Walls and


Mirrors 3rd Edition Frank M. Carrano

https://ebookgate.com/product/data-abstraction-and-problem-solving-
with-c-walls-and-mirrors-3rd-edition-frank-m-carrano/

ebookgate.com

Data Structures Problem Solving Using Java 4th Edition


Mark Allen Weiss

https://ebookgate.com/product/data-structures-problem-solving-using-
java-4th-edition-mark-allen-weiss/

ebookgate.com

Computational Physics Problem Solving with Python 3rd


Edition Páez

https://ebookgate.com/product/computational-physics-problem-solving-
with-python-3rd-edition-paez/

ebookgate.com
Data structures and abstractions with Java 2nd ed Edition
Carrano

https://ebookgate.com/product/data-structures-and-abstractions-with-
java-2nd-ed-edition-carrano/

ebookgate.com

Problem solving with C Ninth Edition Mock

https://ebookgate.com/product/problem-solving-with-c-ninth-edition-
mock/

ebookgate.com

Problem Solving and Troubleshooting in AIX 5L 2nd ed


Edition Ibm Redbooks

https://ebookgate.com/product/problem-solving-and-troubleshooting-in-
aix-5l-2nd-ed-edition-ibm-redbooks/

ebookgate.com

Process Data and Classifier Models for Accessible


Supervised Classification Problem Solving 1st Edition
Steven De Bruyne
https://ebookgate.com/product/process-data-and-classifier-models-for-
accessible-supervised-classification-problem-solving-1st-edition-
steven-de-bruyne/
ebookgate.com

Java and XML 3rd ed Edition Edelson

https://ebookgate.com/product/java-and-xml-3rd-ed-edition-edelson/

ebookgate.com
Data Abstraction
& Problem Solving
with JAVA™
WA L L S
AND
MIR R OR S
This page intentionally left blank
Data Abstraction
& Problem Solving
with JAVA™
WA L L S
AND
MIR R OR S
3rd Edition

Janet J. Prichard
Bryant University

Frank Carrano
University of Rhode Island

International Edition contributions by


Indrajit Banerjee
Bengal Engineering and Science University
Editorial Director: Marcia Horton Acquisitions Editor, International Edition:
Editor-in-Chief: Michael Hirsch Arunabha Deb
Editorial Assistant: Stephanie Sellinger Publishing Assistant, International Edition:
Marketing Manager: Yezan Alayan Shokhi Shah
Marketing Coordinator: Kathryn Ferranti Senior Operations Supervisor: Alan Fischer
Vice President, Production: Vince O’Brien Operations Specialist: Lisa McDowell
Managing Editor: Jeff Holcomb Text Designer: Sandra Rigney
Senior Production Project Manager: Marilyn Lloyd Cover Designer: Jodi Notowitz
Publisher, International Edition: Angshuman Cover Image: Getty Images/Steve Wall
Chakraborty Full-Service Vendor: GEX Publishing Services
Printer/Binder: Courier Stoughton

Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this text-
book appear on appropriate page within text.

Authorized adaptation from the United States edition, entitled Data Abstraction and Problem Solving with
Java: Walls and Mirrors, 3rd edition, ISBN 978-0-13-212230-6 by Frank M. Carrano and Janet J. Prichard
published by Pearson Education © 2011.

If you purchased this book within the United States or Canada you should be aware that it has been imported
without the approval of the Publisher or the Author.

Copyright © 2011 Pearson Education Limited, Edinburgh Gate, Harlow.

All rights reserved. Manufactured in the United States of America. This publication is protected by
Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopy-
ing, recording, or likewise.

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library

Many of the designations by manufacturers and seller to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the publisher was aware of a trademark claim, the designa-
tions have been printed in initial caps or all caps.

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

ISBN 10: 0-273-75120-4


ISBN 13: 978-0-273-75120-5
Brief Contents

PART ONE
Problem-Solving Techniques 25
1 Review of Java Fundamentals 27
2 Principles of Programming and Software Engineering 105
3 Recursion: The Mirrors 161
4 Data Abstraction: The Walls 221
5 Linked Lists 265

PART TWO
Problem Solving with Abstract
Data Types 337
6 Recursion as a Problem-Solving Technique 339
7 Stacks 375
8 Queues 433
9 Advanced Java Topics 479
10 Algorithm Efficiency and Sorting 529
11 Trees 585
12 Tables and Priority Queues 667
13 Advanced Implementations of Tables 723
14 Graphs 801
15 External Methods 847

APPENDICES
A A Comparison of Java to C++ 887
B Unicode Character Codes (ASCII Subset) 891
C Java Resources 892
D Mathematical Induction 894
Glossary 901
Self-Test Answers 921
Index 945 5
This page intentionally left blank
Contents

Preface 15
Chapter Dependency Chart 18

PART ONE
Problem-Solving Techniques 25
1 Review of Java Fundamentals 27
1.1 Language Basics 28
Comments 28
Identifiers and Keywords 28
Variables 28
Primitive Data Types 29
References 30
Literal Constants 30
Named Constants 31
Assignments and Expressions 32
Arrays 35
1.2 Selection Statements 38
The if Statement 39
The switch Statement 40
1.3 Iteration Statements 41
The while Statement 41
The for Statement 42
The do Statement 45
1.4 Program Structure 45
Packages 46
Classes 47
Data Fields 48
Methods 50
How to Access Members of an Object 54
Class Inheritance 54

7
8 Contents

1.5 Useful Java Classes 56


The Object Class 56
The Array Class 58
String Classes 59
1.6 Java Exceptions 64
Catching Exceptions 64
Throwing Exceptions 71
1.7 Text Input and Output 73
Input 73
Output 75
The Console Class 78
1.8 File Input and Output 80
Text Files 82
Object Serialization 90
Summary 93 Cautions 96 Self-Test Exercises 96
Exercises 97 Programming Problems 102
2 Principles of Programming and
Software Engineering 105
2.1 Problem Solving and Software Engineering 106
What Is Problem Solving? 106
The Life Cycle of Software 107
What Is a Good Solution? 117
2.2 Achieving an Object-Oriented Design 119
Abstraction and Information Hiding 120
Object-Oriented Design 122
Functional Decomposition 124
General Design Guidelines 125
Modeling Object-Oriented Designs Using UML 126
Advantages of an Object-Oriented Approach 130
2.3 A Summary of Key Issues in Programming 131
Modularity 131
Modifiability 133
Ease of Use 135
Fail-Safe Programming 136
Style 142
Debugging 146
Summary 149 Cautions 150 Self-Test Exercises 150
Exercises 151 Programming Problems 156
3 Recursion: The Mirrors 161
3.1 Recursive Solutions 162
A Recursive Valued Method: The Factorial of n 165
A Recursive void Method: Writing a String Backward 172
Contents 9

3.2 Counting Things 183


Multiplying Rabbits (The Fibonacci Sequence) 183
Organizing a Parade 185
Mr. Spock’s Dilemma (Choosing k out of n Things) 188
3.3 Searching an Array 190
Finding the Largest Item in an Array 191
Binary Search 192
Finding the k th Smallest Item in an Array 196
3.4 Organizing Data 200
The Towers of Hanoi 200
3.5 Recursion and Efficiency 204
Summary 211 Cautions 211 Self-Test Exercises 212
Exercises 213 Programming Problems 219
4 Data Abstraction: The Walls 221
4.1 Abstract Data Types 222
4.2 Specifying ADTs 227
The ADT List 228
The ADT Sorted List 233
Designing an ADT 235
Axioms (Optional) 239
4.3 Implementing ADTs 242
Java Classes Revisited 243
Java Interfaces 245
Java Packages 248
An Array-Based Implementation of the ADT List 250
Summary 257 Cautions 257 Self-Test Exercises 258
Exercises 259 Programming Problems 262
5 Linked Lists 265
5.1 Preliminaries 266
Object References 266
Resizeable Arrays 272
Reference-Based Linked Lists 273
5.2 Programming with Linked Lists 277
Displaying the Contents of a Linked List 277
Deleting a Specified Node from a Linked List 279
Inserting a Node into a Specified Position of a Linked List 282
A Reference-Based Implementation of the ADT List 288
Comparing Array-Based and Reference-Based Implementations 292
Passing a Linked List to a Method 295
Processing Linked Lists Recursively 295
10 Contents

5.3 Variations of the Linked List 301


Tail References 301
Circular Linked Lists 302
Dummy Head Nodes 304
Doubly Linked Lists 304
5.4 Application: Maintaining an Inventory 308
5.5 The Java Collections Framework 314
Generics 315
Iterators 316
The Java Collection’s Framework List Interface 319
Summary 322 Cautions 324 Self-Test Exercises 325
Exercises 327 Programming Problems 331

PART TWO
Problem Solving with Abstract
Data Types 337
6 Recursion as a Problem-Solving Technique 339
6.1 Backtracking 340
The Eight Queens Problem 340
6.2 Defining Languages 345
The Basics of Grammars 346
Two Simple Languages 347
Algebraic Expressions 350
6.3 The Relationship Between Recursion and Mathematical Induction 360
The Correctness of the Recursive Factorial Method 360
The Cost of Towers of Hanoi 361
Summary 363 Cautions 363 Self-Test Exercises 364
Exercises 364 Programming Problems 368
7 Stacks 375
7.1 The Abstract Data Type Stack 376
Developing an ADT During the Design of a Solution 376
7.2 Simple Applications of the ADT Stack 382
Checking for Balanced Braces 382
Recognizing Strings in a Language 386
7.3 Implementations of the ADT Stack 387
An Array-Based Implementation of the ADT Stack 389
A Reference-Based Implementation of the ADT Stack 391
An Implementation That Uses the ADT List 393
Comparing Implementations 395
The Java Collections Framework Class Stack 395
7.4 Application: Algebraic Expressions 397
Evaluating Postfix Expressions 397
Converting Infix Expressions to Equivalent Postfix Expressions 399
Contents 11

7.5 Application: A Search Problem 402


A Nonrecursive Solution That Uses a Stack 404
A Recursive Solution 412
7.6 The Relationship Between Stacks and Recursion 415
Summary 417 Cautions 417 Self-Test Exercises 418
Exercises 419 Programming Problems 424
8 Queues 433
8.1 The Abstract Data Type Queue 434
8.2 Simple Applications of the ADT Queue 436
Reading a String of Characters 436
Recognizing Palindromes 437
8.3 Implementations of the ADT Queue 438
A Reference-Based Implementation 440
An Array-Based Implementation 443
An Implementation That Uses the ADT List 449
The JCF Interfaces Queue and Deque 450
Comparing Implementations 456
8.4 A Summary of Position-Oriented ADTs 457
8.5 Application: Simulation 458
Summary 468 Cautions 469 Self-Test Exercises 469
Exercises 470 Programming Problems 474
9 Advanced Java Topics 479
9.1 Inheritance Revisited 480
Java Access Modifiers 486
Is-a and Has-a Relationships 488
9.2 Dynamic Binding and Abstract Classes 490
Abstract Classes 493
Java Interfaces Revisited 498
9.3 Java Generics 499
Generic Classes 499
Generic Wildcards 501
Generic Classes and Inheritance 502
Generic Implementation of the Class List 505
Generic Methods 507
9.4 The ADTs List and Sorted List Revisited 508
Implementations of the ADT Sorted List That Use the ADT List 509
9.5 Iterators 513
Summary 517 Cautions 518 Self-Test Exercises 518
Exercises 519 Programming Problems 524
12 Contents

10 Algorithm Efficiency and Sorting 529


10.1 Measuring the Efficiency of Algorithms 530
The Execution Time of Algorithms 531
Algorithm Growth Rates 533
Order-of-Magnitude Analysis and Big O Notation 533
Keeping Your Perspective 539
The Efficiency of Searching Algorithms 541
10.2 Sorting Algorithms and Their Efficiency 542
Selection Sort 543
Bubble Sort 547
Insertion Sort 549
Mergesort 551
Quicksort 557
Radix Sort 569
A Comparison of Sorting Algorithms 571
The Java Collections Framework Sort Algorithm 572
Summary 576 Cautions 577 Self-Test Exercises 577
Exercises 578 Programming Problems 582
11 Trees 585
11.1 Terminology 586
11.2 The ADT Binary Tree 594
Basic Operations of the ADT Binary Tree 594
General Operations of the ADT Binary Tree 595
Traversals of a Binary Tree 598
Possible Representations of a Binary Tree 601
A Reference-Based Implementation of the ADT Binary Tree 605
Tree Traversals Using an Iterator 610
11.3 The ADT Binary Search Tree 618
Algorithms for the Operations of the ADT Binary Search Tree 624
A Reference-Based Implementation
of the ADT Binary Search Tree 639
The Efficiency of Binary Search Tree Operations 643
Treesort 648
Saving a Binary Search Tree in a File 649
The JCF Binary Search Algorithm 652
11.4 General Trees 653
Summary 655 Cautions 656 Self-Test Exercises 656
Exercises 658 Programming Problems 664
12 Tables and Priority Queues 667
12.1 The ADT Table 668
Selecting an Implementation 675
A Sorted Array-Based Implementation of the ADT Table 682
A Binary Search Tree Implementation of the ADT Table 685
Contents 13

12.2 The ADT Priority Queue: A Variation of the ADT Table 687
Heaps 691
A Heap Implementation of the ADT Priority Queue 700
Heapsort 702
12.3 Tables and Priority Queues in the JCF 705
The JCF Map Interface 705
The JCF Set Interface 709
The JCF PriorityQueue Class 713
Summary 715 Cautions 716 Self-Test Exercises 716
Exercises 717 Programming Problems 720
13 Advanced Implementations of Tables 723
13.1 Balanced Search Trees 724
2-3 Trees 725
2-3-4 Trees 745
Red-Black Trees 752
AVL Trees 755
13.2 Hashing 761
Hash Functions 765
Resolving Collisions 767
The Efficiency of Hashing 776
What Constitutes a Good Hash Function? 779
Table Traversal: An Inefficient Operation under Hashing 781
The JCF Hashtable and TreeMap Classes 782
The Hashtable Class 782
The TreeMap Class 785
13.3 Data with Multiple Organizations 788
Summary 793 Cautions 794 Self-Test Exercises 795
Exercises 795 Programming Problems 798
14 Graphs 801
14.1 Terminology 802
14.2 Graphs as ADTs 805
Implementing Graphs 806
Implementing a Graph Class Using the JCF 809
14.3 Graph Traversals 812
Depth-First Search 814
Breadth-First Search 815
Implementing a BFS Iterator Class Using the JCF 817
14.4 Applications of Graphs 820
Topological Sorting 820
Spanning Trees 823
Minimum Spanning Trees 828
14 Contents

Shortest Paths 831


Circuits 835
Some Difficult Problems 838
Summary 839 Cautions 840 Self-Test Exercises 840
Exercises 841 Programming Problems 844
15 External Methods 847
15.1 A Look at External Storage 848
15.2 Sorting Data in an External File 851
15.3 External Tables 859
Indexing an External File 861
External Hashing 865
B-Trees 869
Traversals 879
Multiple Indexing 881
Summary 882 Cautions 883 Self-Test Exercises 883
Exercises 883 Programming Problems 886

A A Comparison of Java to C++ 887

B Unicode Character Codes (ASCII Subset) 891

C Java Resources 892


Java Web Sites 892
Using Java SE 6 892
Integrated Development Environments (IDEs) 893
D Mathematical Induction 894
Example 1 894
Example 2 895
Example 3 896
Example 4 897
Example 5 897
Self-Test Exercises 898 Exercises 898
Glossary 901
Self-Test Answers 921
Index 945
Preface

Welcome to the third edition of Data Abstraction and Problem Solving with
Java: Walls and Mirrors. Java is a popular language for beginning computer
science courses. It is particularly suitable to teaching data abstraction in an
object-oriented way.
This book is based on the original Intermediate Problem Solving and Data
Structures: Walls and Mirrors by Paul Helman and Robert Veroff (© 1986 by
Benjamin Cummings Publishing Company, Inc.). This work builds on their
organizational framework and overall perspective and includes technical and
textual content, examples, figures, and exercises derived from the original
work. Professors Helman and Veroff introduced two powerful analogies, walls
and mirrors, that have made it easier for us to teach—and to learn—computer
science.
With its focus on data abstraction and other problem-solving tools, this
book is designed for a second course in computer science. In recognition of
the dynamic nature of the discipline and the great diversity in undergraduate
computer science curricula, this book includes comprehensive coverage of
enough topics to make it appropriate for other courses as well. For example,
you can use this book in courses such as introductory data structures or
advanced programming and problem solving. The goal remains to give stu-
dents a superior foundation in data abstraction, object-oriented programming,
and other modern problem-solving techniques.

New in this edition


Uses Java 6: This edition has been thoroughly revised to be compatible with
the latest release of Java, known as Java 6. All code has been completely revised
to be Java 6 compliant. Generics are also an important part of Java 6, and this
material is discussed in depth in Chapter 9, and then used throughout the
remainder of the collections in the text.

Enhanced Early Review of Java: We have increased the amount of coverage of


the Java language in the first chapter of the book to help students make the transi-
tion from their introduction to Java course to this course. Chapter 1 provides a
15
16 Preface

concise review of important Java material, including brief discussions on


constructors, object equality, inheritance, and the Array class. A discus-
sion of the Console class from Java 6 was also added to Chapter 1.
Chapter 9 focuses on advanced Java techniques, and includes an enhanced
discussion of how to create an iterator class.

Linked List: The node class for linked lists has been simplified. The implemen-
tation now assumes the node class is package access only, and the other classes in
the same package have direct access to the data within a node. Students are asked
to explore the implications of making the data private in a node as an exercise.

Updates the Use of the Java Collections Framework: The Java Collections
Framework is discussed throughout the text, with a section added to show the JFC
classes that parallel those presented in the text. The Deque class, added in Java 6, is
presented in Chapter 8.

Other enhancements: Additional changes aimed at improving the overall


usability of the text include new exercises and a new cleaner design that
enhances the book’s readability.

TO THE STUDENT
Thousands of students before you have read and learned from Walls and Mirrors.
The walls and mirrors in the title represent two fundamental problem-solving
techniques that appear throughout the book. Data abstraction isolates and hides
the implementation details of a module from the rest of the program, much as a
wall can isolate and hide you from your neighbor. Recursion is a repetitive tech-
nique that solves a problem by solving smaller problems of exactly the same type,
much as mirror images that grow smaller with each reflection.
This book was written with you in mind. As former college students, and as
educators who are constantly learning, we appreciate the importance of a clear
presentation. Our goal is to make this book as understandable as possible. To
help you learn and to review for exams, we have included such learning aids as
margin notes, chapter summaries, self-test exercises with answers, and a glossary.
As a help during programming, you will find Java reference materials in
Chapter 1, and inside the covers. You should review the list of this book’s fea-
tures given later in this preface under the section “Pedagogical Features.”
The presentation makes some basic assumptions about your knowledge of
Java as reviewed in Chapter 1. Some of you may need to review this language
or learn it for the first time by consulting this chapter. Others will find that
they already know most of the constructs presented in Chapter 1. You will
need to know about the selection statements if and switch; the iteration
statements for, while, and do; classes, methods, and arguments; arrays;
strings; and files. In addition to the material in Chapter 1, this book discusses
advanced Java topics such as generics and iterators in Chapter 9. We assume no
experience with recursive methods, which are included in Chapters 3 and 6.
Preface 17

All of the Java source code that appears in this book is available for your
use. Later in this preface, the description of supplementary materials explains
how to obtain these files. See page 21—Supplemental Materials—for instruc-
tions on how to access these files.

TO THE INSTRUCTOR
This edition of Walls and Mirrors uses Java 6 to enhance its emphasis on data
abstraction and data structures. The book carefully accounts for the strengths
and weaknesses of the Java language and remains committed to a pedagogical
approach that makes the material accessible to students at the introductory level.

Prerequisites
We assume that readers either know the fundamentals of Java or know another
language and have an instructor who will help them make the transition to Java.
By using Chapter 1, students without a strong Java background can quickly pick
up what they need to know to be successful in the course. In addition, the book
formally discusses Java classes. Included are the basic concepts of a class, inherit-
ance, polymorphism, interfaces, and packages. Although the book provides an
introduction to these topics in connection with the implementations of abstract
data types (ADTs) as classes, the emphasis of the book remains on the ADTs, not
on Java. The material is presented in the context of object-based programming,
but it assumes that future courses will cover object-oriented design and software
engineering in detail, so that the focus can remain on data abstraction. We do,
however, introduce the Unified Modeling Language (UML) as a design tool.

Organization
The chapters in this book are organized into two parts. In most cases, Chapters 1
through 11 will form the core of a one-semester course. Chapters 1 or 2 might
be review material for your students. The coverage given to Chapters 11
through 15 will depend on the role the course plays in your curriculum.

Flexibility
The extensive coverage of this book should provide you with the material that
you want for your course. You can select the topics you desire and present them
in an order that fits your schedule. A chapter dependency chart follows, and
shows which chapters should be covered before a given chapter can be taught.

Part 1: Problem-Solving Techniques. The first two chapters in Part 1


resemble an extension of an introductory course in that their emphasis is on
major issues in programming and software engineering. Chapter 3 introduces
recursion for those students who have had little exposure to this important
topic. The ability to think recursively is one of the most useful skills that a
18 Preface

Chapter 2
Principles Chapter 1
Java review

Chapter 4
Data abstraction
Chapter 3
Recursion
Chapter 5
Linked lists
Chapter 6
More recursion

Chapter 7 Chapter 8 Chapter 9 Chapter 10


Stacks Queues Advanced Java Algorithm efficienc y, sorting

Chapter 11
Trees

Chapter 12
Tables, priority queues
Chapter 14
Graphs Chapter 15
Chapter 13 Section on Section on
Advanced tables external tables external sorting

Dependency by one section of chapter


Dependency that you can ignore
Knowledge of Java helpful to begin these chapters
Preface 19

computer scientist can possess and is often of great value in helping one to
understand better the nature of a problem. Recursion is discussed extensively
in this chapter and again in Chapter 6 and is used throughout the book.
Included examples range from simple recursive definitions to recursive algo-
rithms for language recognition, searching, and sorting.
Chapter 4 discusses data abstraction and abstract data types (ADTs) in
detail. After a discussion of the specification and use of an ADT, the chapter
discusses Java classes, interfaces, and packages, and uses them to implement
ADTs. Chapter 5 presents additional implementation tools in its discussion of
Java reference variables and linked lists.
You can choose among the topics in Part 1 according to the background
of your students and cover these topics in several orders.

Part 2: Problem Solving with Abstract Data Types. Part 2 continues the
use of data abstraction as a problem-solving technique. Basic abstract data types
such as the stack, queue, binary tree, binary search tree, table, heap, and priority
queue are first specified and then implemented as classes. The ADTs are used in
examples and their implementations are compared.
Chapter 9 extends the treatment of Java classes by covering inheritance,
the relationships among classes, generics, and iterators. Chapter 10 formalizes
the earlier discussions of an algorithm’s efficiency by introducing order-of-
magnitude analysis and Big O notation. The chapter examines the efficiency of
several searching and sorting algorithms, including the recursive mergesort and
quicksort.
Part 2 also includes advanced topics—such as balanced search trees (2-3,
2-3-4, red-black, and AVL trees) and hashing—that are examined as table
implementations. These implementations are analyzed to determine the table
operations that each supports best.
Finally, data storage in external direct access files is considered. Mergesort
is modified to sort such data, and external hashing and B-tree indexes are used
to search it. These searching algorithms are generalizations of the internal
hashing schemes and 2-3 trees already developed.
In Part 1, you can choose among topics according to your students’ back-
ground. Three of the chapters in this part provide an extensive introduction to
data abstraction and recursion. Both topics are important, and there are
various opinions about which should be taught first. Although in this book a
chapter on recursion both precedes and follows the chapter on data abstrac-
tion, you can simply rearrange this order.
Part 2 treats topics that you can also cover in a flexible order. For exam-
ple, you can cover all or parts of Chapter 9 on advanced Java topics either
before or after you cover stacks (Chapter 7). You can cover algorithm effi-
ciency and sorting (Chapter 10) any time after Chapter 6. You can introduce
trees before queues or graphs before tables, or cover hashing, balanced search
trees, or priority queues any time after tables and in any order. You also can
cover external methods (Chapter 15) earlier in the course. For example, you
can cover external sorting after you cover mergesort in Chapter 10.
20 Preface

Data Abstraction
The design and use of abstract data types (ADTs) permeate this book’s
problem-solving approach. Several examples demonstrate how to design an
ADT as part of the overall design of a solution. All ADTs are first specified—in
both English and pseudocode—and then used in simple applications before
implementation issues are considered. The distinction between an ADT and
the data structure that implements it remains in the forefront throughout the
discussion. The book explains both encapsulation and Java classes early. Stu-
dents see how Java classes hide an implementation’s data structure from the
client of the ADT. Abstract data types such as lists, stacks, queues, trees, tables,
heaps, and priority queues form the basis of our discussions.

Problem Solving
This book helps students learn to integrate problem-solving and program-
ming abilities by emphasizing both the thought processes and the techniques
that computer scientists use. Learning how a computer scientist develops, ana-
lyzes, and implements a solution is just as important as learning the mechanics
of the algorithm; a cookbook approach to the material is insufficient.
The presentation includes analytical techniques for the development of
solutions within the context of example problems. Abstraction, the successive
refinement of both algorithms and data structures, and recursion are used to
design solutions to problems throughout the book.
Java references and linked list processing are introduced early and used
in building data structures. The book also introduces at an elementary level
the order-of-magnitude analysis of algorithms. This approach allows the
consideration—first at an informal level, and then more quantitatively—of
the advantages and disadvantages of array-based and reference-based data
structures. An emphasis on the trade-offs among potential solutions and
implementations is a central problem-solving theme.
Finally, programming style, documentation including preconditions and
postconditions, debugging aids, and loop invariants are important parts of the
problem-solving methodology used to implement and verify solutions. These
topics are covered throughout the book.

Applications
Classic application areas arise in the context of the major topics of this book.
For example, the binary search, quicksort, and mergesort algorithms provide
important applications of recursion and introduce order-of-magnitude analy-
sis. Such topics as balanced search trees, hashing, and file indexing continue
the discussion of searching. Searching and sorting are considered again in the
context of external files.
Algorithms for recognizing and evaluating algebraic expressions are first
introduced in the context of recursion and are considered again later as an
Preface 21

application of stacks. Other applications include, for example, the Eight


Queens problem as an example of backtracking, event-driven simulation as an
application of queues, and graph searching and traversals as other important
applications of stacks and queues.

Pedagogical Features
The pedagogical features and organization of this book were carefully
designed to facilitate learning and to allow instructors to tailor the material
easily to a particular course. This book contains the following features that
help students not only during their first reading of the material, but also
during subsequent review:
 Chapter outlines and previews
 Key Concepts boxes
 Margin notes
 Chapter summaries
 Cautionary warnings about common errors and misconceptions
 Self-test exercises with answers
 Chapter exercises and programming problems. The most challenging exer-
cises are labeled with asterisks. Answers to the exercises appear in the
Instructor’s Resource Manual.
 Specifications for all major ADTs in both English and pseudocode
 Java class definitions for all major ADTs
 Examples that illustrate the role of ADTs in the problem-solving process
 Appendixes, including a review of Java
 Glossary of terms

SUPPLEMENTAL MATERIALS
The following supplementary materials are available online to all readers of this
book at www.pearsonhighered.com/cssupport.
 Source code of all the Java classes, methods, and programs that appear in
the book
 Errata: We have tried not to make mistakes, but mistakes are inevitable. A
list of detected errors is available and updated as necessary. You are invited
to contribute your finds.
22 Preface

The following instructor supplements are only available to qualified


instructors. Please visit Addison-Wesley’s Instructor Resource Center
(www.pearsonhighered.com/irc) or contact your local Addison-Wesley
Sales Representative to access them.
 Instructor’s Guide with Solutions: This manual contains teaching hints,
sample syllabi, and solutions to all the end-of-chapter exercises in the
book.
 Test Bank: A collection of multiple choice, true/false, and short-answer
questions
 PowerPoint Lectures: Lecture notes with figures from the book

TALK TO US
This book continues to evolve. Your comments, suggestions, and correc-
tions will be greatly appreciated. You can contact us through the publisher at
computing@aw.com, or:

Computer Science Editorial Office


Addison-Wesley
501 Boylston Street, Suite 900
Boston, MA 02116

ACKNOWLEDGMENTS
The suggestions from outstanding reviewers have, through the past few editions,
contributed greatly to this book’s present form. In alphabetical order, they are:
Ronald Alferez—University of California at Santa Barbara
Claude W. Anderson—Rose-Hulman Institute of Technology
Don Bailey—Carleton University
N. Dwight Barnette—Virginia Tech
Jack Beidler—University of Scranton
Elizabeth Sugar Boese—Colorado State University
Debra Burhans—Canisius College
Tom Capaul—Eastern Washington University
Eleanor Boyle Chlan—Johns Hopkins University
Chakib Chraibi—Barry University
Jack N. Donato—Jefferson Community College
Susan Gauch—University of Kansas
Mark Holliday—Western Carolina University
Lily Hou—SUN Microsystems, Inc.
Helen H. Hu—Westminster College
Lester I. McCann—The University of Arizona
Rameen Mohammadi—SUNY, Oswego
Narayan Murthy—Pace University
Thaddeus F. Pawlicki—University of Rochester
Preface 23

Timothy Rolfe—Eastern Washington University


Hongjun Song—University of Memphis
For their peer reviews of the international edition, we would like to thank:
Arup Kumar Bhattacharjee—RCC Institute of Information Technology
Soumen Mukherjee—RCC Institute of Information Technology
We especially thank the people who produced this book. Our editors at
Addison-Wesley, Michael Hirsch and Stephanie Sellinger, provided invaluable
guidance and assistance. Also, Marilyn Lloyd, Linda Knowles, Yez Alayan and
Kathryn Ferranti contributed their expertise and care during the final produc-
tion and in the marketing of the book.
Many other wonderful people have contributed in various ways. They are
Doug McCreadie, Michael Hayden, Sarah Hayden, Andrew Hayden, Albert
Prichard, Frances Prichard, Sarah Mason, Karen Mellor, Maybeth Conway, Ted
Emmott, Lorraine Berube, Marge White, James Kowalski, Ed Lamagna, Gerard
Baudet, Joan Peckham, Victor Fay-Wolfe, Bala Ravikumar, Karl Abrahamson,
Ronnie Smith, James Wirth, Randy Hale, John Cardin, Gail Armstrong, Tom
Manning, Jim Abreu, Bill Harding, Hal Records, Laurie MacDonald, Ken
Fougere, Ken Sousa, Chen Zhang, Suhong Li, Richard Glass, and Aby
Chaudhury. In special memory of Wallace Wood.
Numerous other people provided input for the previous editions of Walls and
Mirrors at various stages of its development. All of their comments were useful and
greatly appreciated. In alphabetical order, they are: Stephen Alberg, Vicki Allan,
Jihad Almahayni, James Ames, Andrew Azzinaro, Tony Baiching, Don Bailey,
Wolfgang W. Bein, Sto Bell, David Berard, John Black, Richard Botting, Wolfin
Brumley, Philip Carrigan, Stephen Clamage, Michael Clancy, David Clayton,
Michael Cleron, Chris Constantino, Shaun Cooper, Charles Denault, Vincent J.
DiPippo, Suzanne Dorney, Colleen Dunn, Carl Eckberg, Karla Steinbrugge Fant,
Jean Foltz, Marguerite Hafen, George Hamer, Judy Hankins, Lisa Hellerstein, Mary
Lou Hines, Jack Hodges, Stephanie Horoschak, John Hubbard, Kris Jensen,
Thomas Judson, Laura Kenney, Roger King, Ladislav Kohout, Jim LaBonte, Jean
Lake, Janusz Laski, Cathie LeBlanc, Urban LeJeune, John M. Linebarger, Ken
Lord, Paul Luker, Manisha Mande, Pierre-Arnoul de Marneffe, John Marsaglia, Jane
Wallace Mayo, Mark McCormick, Dan McCracken, Vivian McDougal, Shirley
McGuire, Sue Medeiros, Jim Miller, Guy Mills, Cleve Moler, Paul Nagin, Rayno
Niemi, Paul Nagin, John O’Donnell, Andrew Oldroyd, Larry Olsen, Raymond L.
Paden, Roy Pargas, Brenda C. Parker, Keith Pierce, Lucasz Pruski, George B. Purdy,
David Radford, Steve Ratering, Stuart Regis, J. D. Robertson, John Rowe, Michael
E. Rupp, Sharon Salveter, Charles Saxon, Chandra Sekharan, Linda Shapiro, Yujian
Sheng, Mary Shields, Carl Spicola, Richard Snodgrass, Neil Snyder, Chris Spannabel,
Paul Spirakis, Clinton Staley, Matt Stallman, Mark Stehlick, Harriet Taylor, David
Teague, David Tetreault, John Turner, Susan Wallace, James E. Warren, Jerry Weltman,
Nancy Wiegand, Howard Williams, Brad Wilson, Salih Yurttas, and Alan Zaring.
Thank you all.
F. M. C.
J. J. P.
This page intentionally left blank
PART O NE

Problem-Solving
Techniques

T he primary concern of the six chapters in Part One of this book is to


develop a repertoire of problem-solving techniques that form the basis
of the rest of the book. Chapter 1 begins by providing a brief overview of
Java fundamentals. Chapter 2 describes the characteristics of a good solu-
tion and the ways to achieve one. These techniques emphasize abstraction,
modularity, and information hiding. The remainder of Part One discusses
data abstraction for solution design, more Java for use in implementations,
and recursion as a problem-solving strategy.
This page intentionally left blank
CHAPTER 1

Review of Java
Fundamentals

T his book assumes that you already know how to write


programs in a modern programming language. If that
language is Java, you can probably skip this chapter, return-
1.1 Language Basics
Comments
Identifiers and Keywords
Variables
ing to it for reference as necessary. If instead you know a Primitive Data Types
language such as C++, this chapter will introduce you to References
Java. Literal Constants
It isn’t possible to cover all of Java in these pages. Named Constants
Instead this chapter focuses on the parts of the language Assignments and Expressions
Arrays
used in this book. First we discuss basic language con-
structs such as variables, data types, expressions, opera- 1.2 Selection Statements
tors, arrays, decision constructs, and looping constructs. The if Statement
The switch Statement
Then we look at the basics of program structure, including
packages, classes, and methods, with a brief introduction to 1.3 Iteration Statements
inheritance. We continue with useful Java classes, excep- The while Statement
tions, text input and output, and files. The for Statement
The do Statement

1.4 Program Structure


Packages
Classes
Data Fields
Methods
How to Access Members of an Object
1.5 Useful Java Classes
The Object Class
String Classes
1.6 Java Exceptions
Catching Exceptions
Throwing Exceptions
1.7 Text Input and Output
Input
Output
1.8 File Input and Output
Text Files
Object Serialization
Summary 27
Cautions
28 Chapter 1 Review of Java Fundamentals

1.1 Language Basics


Let’s begin with the elements of the language that allow you to perform
simple actions within a program. The following sections provide a brief over-
view of the basic language constructs of Java.

Comments
A variety of com- Each comment line in Java begins with two slashes (//) and continues until the
menting styles are end of the line. You can also begin a multiple-line comment with the characters
available in Java /* and end it with */. Although the programs in this book do not use /* and */,
it is a good idea to use this notation during debugging. That is, to isolate an
error, you can temporarily ignore a portion of a program by enclosing it within
/* and */. However, a comment that begins with /* and ends with */ cannot
contain another comment that begins with /* and ends with */. Java also has a
third kind of comment that is used to generate documentation automatically
using javadoc, a documentation utility available in the Software Development
Kit (SDK). This comment uses a /** to start and a */ to end.

Identifiers and Keywords


A Java identifier is a sequence of letters, digits, underscores, and dollar signs
that must begin with either a letter or an underscore. Java distinguishes
Java is case between uppercase and lowercase letters, so be careful when typing identifiers.
sensitive You use identifiers to name various parts of the program. Certain identifi-
ers, however, are reserved by Java as keywords, and you should not use them
for other purposes. A list of all Java keywords appears inside the front cover of
this book. The keywords that occur within Java statements in this book are in
boldface.

Variables
A variable contains A variable, whose name is a Java identifier, represents a memory location that
either the value of a contains a value of a primitive data type or a reference. You declare a variable’s
primitive data type data type by preceding the variable name with the data type, as in
or a reference to an
object
double radius; // radius of a sphere
String name; // reference to a String object

Note that the second declaration does not create a String object, only a vari-
able that stores the location of a String object. You must use the new operator
to create a new object.
Language Basics 29

Primitive Data Types


The primitive data types in Java are organized into four categories: boolean,
character, integer, and floating point. For example, the following two lines
declare variables of the primitive type double.

double radius;
double radiusCubed;

Some of the data types are available in two forms and sizes. Figure 1-1 lists
the available primitive data types.
A boolean value can be either true or false. You represent characters by
enclosing them in single quotes or by providing their Unicode integer value
(see Appendix B). Integer values are signed and allow numbers such as –5 and
+98. The floating-point types provide for real numbers that have both an
integer portion and a fractional portion. Character and integer types are called
integral types. Integral and floating-point types are called arithmetic types.
A value of a primitive type is not considered to be an object and thus
cannot be used in situations where an object type is expected. For this reason,
the package java.lang provides corresponding wrapper classes for each of A wrapper class is
the primitive types. Figure 1-1 also lists the wrapper class corresponding to available for each
each of the primitive types. primitive data type
Each of these classes provides a constructor to convert a value of a primi-
tive type to an object when necessary. Once such an object has been created,
the value contained within the object cannot be modified. Here is a simple
example involving integers:

int x = 9; You can represent


Integer intObject = new Integer(x); the value of a
System.out.println("The value stored in intObject = " primitive data type
by using a wrapper
+ intObject.intValue()); class

Category Data Type Wrapper Class


Boolean boolean Boolean
Character char Character
Integer byte Byte
short Short
int Integer
long Long
Floating point float Float
double Double

FIGURE 1-1

Primitive data types and corresponding wrapper classes


30 Chapter 1 Review of Java Fundamentals

The class Integer has a method intValue that retrieves the value stored
in an Integer object. Classes corresponding to the other primitive types
provide methods with similar functionality.
Java has a feature called autoboxing that makes it easier to convert from a
primitive type to their equivalent wrapper class counterparts. In the previous
example, we explicitly created a new Integer object to store the value 9. With
autoboxing, we can simply write

Integer intObject = 9;

The compiler automatically adds the code to convert the integer value into the
proper class (Integer in this example).
The reverse process of converting an object of one of the wrapper
classes into a value of the corresponding primitive type is called auto-unboxing.
In the example

int x = intObject + 1;

the compiler again automatically generates the code to convert the Integer
object intObject to a primitive type (int in this example) so that the expres-
sion can be evaluated.

References
A reference variable Java has one other type, called a reference, that is used to locate an object.
contains an object’s Unlike other languages, such as C++, Java does not allow the programmer to
location in memory perform any operations on the reference value. When an object is created using
the new operator, the location of the object in memory is returned and can be
assigned to a reference variable. For example, the following line shows the ref-
erence variable name being assigned the location of a new string object:

String name = new String("Sarah");

A special reference value of null is provided to indicate that a reference vari-


able has no object to reference.

Literal Constants
Literal constants You use literal constants to indicate particular values within a program. In the
indicate particular following expression, the 4 and 3 are examples of literal constants that are used
values within a within a computation.
program

4 * Math.PI * radiusCubed / 3
Language Basics 31

You can also use a literal constant to initialize the value of a variable. For exam-
ple, you use true and false as the values of a boolean variable, as we men-
tioned previously.
You write decimal integer constants without commas, decimal points, or
leading zeros.1 The default data type of such a constant is either int, if small Do not begin a
enough, or long. decimal integer
You write floating constants, which have a default type of double, with a constant with zero
decimal point. You can specify an optional power-of-10 multiplier by writing e
or E followed by the power of 10. For example, 1.2e-3 means 1.2 × 10–3.
Character constants are enclosed in single quotes—for example, 'A' and
'2'—and have a default type of char. You write a literal character string as a
sequence of characters enclosed in double quotes.
Several characters have names that use a backslash notation, as given in
Figure 1-2. This notation is useful when you want to embed one of these char-
acters within a literal character string. For example, the statement

System.out.println("Hello\n Let\'s get started!");

uses the new-line character \n to place a new-line character after the string
Hello. You will learn about this use of \n in the discussion of output later in this
chapter. You also use the backslash notation to specify either a single quote as a
character constant ( \') or a double quote ( \") within a character string.

Named Constants
Unlike variables, whose values can change during program execution, named
constants have values that do not change. The declaration of a named con- The value of a
stant is like that of a variable, but the keyword final precedes the data type. named constant
For example, does not change

final float DEFAULT_RADIUS = 1.0;

Constant Name
\n New line
\t Tab
\' Single quote
\" Double quote
\0 Zero

FIGURE 1-2
Some special character constants

1. Octal and hexadecimal constants are also available, but they are not used in this
book. An octal constant begins with 0, a hex constant with 0x or 0X.
32 Chapter 1 Review of Java Fundamentals

Named constants declares DEFAULT_RADIUS as a named floating-point constant. Once a named


make a program constant such as DEFAULT_RADIUS is declared, you can use it, but you cannot
easier to read and assign it another value. By using named constants, you make your program
modify
both easier to read and easier to modify.

Assignments and Expressions


You form an expression by combining variables, constants, operators, and
parentheses. The assignment statement

An assignment radius = initialRadius;


statement assigns
the value of an
assigns to a previously declared variable radius the value of the expression on the
expression to a
variable right-hand side of the assignment operator =, assuming that initialRadius has
a value. The assignment statement

double radiusCubed = radius * radius * radius;

also declares radiusCubed’s data type, and assigns it a value.

Arithmetic expressions. You can combine variables and constants with


arithmetic operators and parentheses to form arithmetic expressions. The
arithmetic operators are

* Multiply + Binary add or unary plus


/ Divide - Binary subtract or unary minus
% Remainder after division

Operators have a The operators *, /, and % have the same precedence,2 which is higher than that
set precedence of + and -; unary operators3 have a higher precedence than binary operators.
The following examples demonstrate operator precedence:
a - b / c means a - (b / c) ( precedence of / over -)

-5 / a means (-5) / a ( precedence of unary operator -)


a / -5 means a / (-5) ( precedence of unary operator -)
Arithmetic operators and most other operators are left-associative. That
is, operators of the same precedence execute from left to right within an
expression. Thus,

2. A list of all Java operators and their precedences appears inside the back cover of this
book.
3. A unary operator requires only one operand, for example, the - in -5. A binary
operator requires two operands, for example, the + in 2 + 3.
Language Basics 33

a / b * c Operators are
either left- or right-
means associative

(a / b) * c

The assignment operator and all unary operators are right-associative, as you
will see later. You can use parentheses to override operator precedence and
associativity.

Relational and logical expressions. You can combine variables and con-
stants with parentheses; with the relational, or comparison, operators <, <=,
>=, and >; and with the equality operators == (equal to) and != (not equal to)
to form a relational expression. Such an expression evaluates to false if the
specified relation is false and to true if it is true. For example, the expression
5 != 4 has a value of true because 5 is not equal to 4. Note that equality
operators have a lower precedence than relational operators. Also note that the
equality operators work correctly only with the primitive types and references. Equality operators
The == operator determines only whether two reference variables are referenc- work correctly only
ing the same object, but not whether two objects are equal. with primitive types
and references
You can combine variables and constants of the arithmetic types, rela-
tional expressions, and the logical operators && (and) and || (or) to form
logical expressions, which evaluate to false if false and to true if true. Java Logical expressions
evaluates logical expressions from left to right and stops as soon as the value of are evaluated from
the entire expression is apparent; that is, Java uses short-circuit evaluation. left to right
For example, Java determines the value of each of the following expressions Sometimes the
without evaluating (a < b): value of a logical
expression is
apparent before it
(5 == 4) && (a < b) // false since (5 == 4) is false is completely
(5 == 5) || (a < b) // true since (5 == 5) is true examined

Implicit type conversions for the primitive numeric types. Automatic con- Conversions from
versions from one numeric data type to another can occur during assignment one data type to
and during expression evaluation. For assignments, the data type of the expres- another occur
during both assign-
sion on the right-hand side of the assignment operator is converted to the data ment and expres-
type of the item on the left-hand side just before the assignment occurs. Float- sion evaluation
ing-point values are truncated—not rounded—when they are converted to
integral values.
During the evaluation of an expression, any values of type byte, char, or
short are converted to int. These conversions are called integral promo-
tions. After these conversions, if the operands of an operator differ in data
type, the data type that is lower in the following hierarchy is converted to one
that is higher (int is lowest):

int → long → float → double


34 Chapter 1 Review of Java Fundamentals

For example, if A is long and B is float, A + B is float. A copy of A’s long value
is converted to float prior to the addition; the value stored at A is unchanged.

Explicit type conversions for primitive numeric types. Numeric conversions


from one type to another are possible by means of a cast. The cast operator is a
unary operator formed by enclosing the desired data type within parentheses.
Thus, the sequence

double volume = 14.9;


You convert from System.out.print((int)volume);
one numeric type
to another by using
displays 14.
a cast

Multiple assignment. If you omit the semicolon from an assignment state-


ment, you get an assignment expression. You can embed assignment expres-
sions within assignment expressions, as in a = 5 + (b = 4).

This expression first assigns 4 to b and then 9 to a. This notation contributes to


the terseness of Java and is sometimes convenient, but it can be confusing. The
assignment operator is right-associative. Thus, a = b = c means a = (b = c).

Other assignment operators. In addition to the assignment operator =, Java


provides several two-character assignment operators that perform another
operation before assignment. For example,
a += b means a = a + b

Other operators, such as -=, *=, /=, and %=, have analogous meanings.
The operators ++ Two more operators, ++ and --, provide convenient incrementing and
and -- are useful decrementing operations:
for incrementing
and decrementing ++a means a += 1, which means a = a + 1
a variable
Similarly,
--a means a -= 1, which means a = a - 1

The operators ++ and -- can either precede their operands, as you just saw, or
follow them. Although a++, for instance, has the same effect as ++a, the results
differ when the operations are combined with assignment. For example,
b = ++a means a = a + 1; b = a
Here, the ++ operator acts on a before the assignment to b of a’s new value. In
contrast,
b = a++ means b = a; a = a + 1

The assignment operator assigns a’s old value to b before the ++ operator acts
on a. That is, the ++ operator acts on a after the assignment. The operators ++
Language Basics 35

and -- are often used within loops and with array indexes, as you will see later
in this chapter.
In addition to the operators described here, Java provides several other
operators. A summary of all Java operators and their precedences appears
inside the back cover of this book.

Arrays
An array is a collection of elements, items, or values that have the same data An array is a collec-
type. Array elements have an order: An array has a first element, a second ele- tion of data that has
ment, and so on, as well as a last element. That is, an array contains a finite, the same type
limited number of elements. Like objects, an array does not come into exist-
ence until it is allocated using the new statement. At that time, you specify the
desired size of the array. Because you can access the array elements directly and You can access
in any order, an array is a direct access, or random access, data structure. array elements
directly and in
any order
One-dimensional arrays. When you decide to use an array in your pro-
gram, you must declare it and, in doing so, indicate the data type of its ele-
ments. The following statements declare a one-dimensional array, maxTemps,
which contains the daily maximum temperatures for a given week:

final int DAYS_PER_WEEK = 7;


double [] maxTemps = new double[DAYS_PER_WEEK];

The bracket notation [] declares maxTemps as an array. The array is then allo-
cated memory for seven floating-point elements.
The declared length of an array is accessible using the data field length
associated with the array. For example, maxTemps.length is 7. You can refer Use an index to
to any of the floating-point elements in maxTemps directly by using an specify a particular
element in an array
expression, which is called the index, or subscript, enclosed in square brack-
ets. In Java, array indexes must have integer values in the range 0 to length An array index has
– 1, where length is the data field just described. The indexes for maxTemps an integer value
range from 0 to DAYS_PER_WEEK – 1. For example, maxTemps[4] is the fifth greater than or
equal to 0
element in the array. If k is an integer variable whose value is 4, maxTemps[k]
is the fifth element in the array, and maxTemps[k+1] is the sixth element.
Also, maxTemps[++k] adds 1 to k and then uses the new value of k to index
maxTemps, whereas maxTemps[k++] accesses maxTemps[k] before adding 1
to k. Note that you use one index to refer to an element in a one-dimen-
sional array.
Figure 1-3 illustrates the array maxTemps, which at present contains only
five temperatures. The last value in the array is maxTemps[4]; the values of
maxTemps[5] and maxTemps[6] are 0.0, the default initial value for floating-
point numbers.
You can initialize the elements of an array when you declare it by specify-
ing an initializer list. The initializer list is a list of values separated by commas
and enclosed in braces. For example,
36 Chapter 1 Review of Java Fundamentals

0 1 2 3 4 5 6 Index

maxTemps 82.0 71.5 61.8 75.0 88.3 0.0 0.0

maxTemps[4] Unused at present

FIGURE 1-3
A one-dimensional array of at most seven elements

You can initialize an double [] weekDayTemps = {82.0, 71.5, 61.8, 75.0, 88.3};
array when you
declare it
initializes the array weekDayTemps to have five elements with the values listed.
Thus, weekDayTemps[0] is 82.0, weekDayTemps[1] is 71.5, and so on.
You can also declare an array of object references. The declaration is
similar to that of an array of primitive types. Here is a declaration of an array
for ten String references:

String[] stuNames = new String[10];

Note that all of the references will have the initial value null until actual
String objects are created for them to reference. The following statement
creates a String object for the first element of the array:

stuName[0] = new String("Andrew");

Multidimensional arrays. You can use a one-dimensional array, which has


one index, for a simple collection of data. For example, you can organize 52
temperatures linearly, one after another. A one-dimensional array of these tem-
peratures can represent this organization.
An array can have You can also declare multidimensional arrays. You use more than one
more than one index to designate an element in a multidimensional array. Suppose that you
dimension wanted to represent the minimum temperature for each day during 52 weeks.
The following statements declare a two-dimensional array, minTemps:

final int DAYS_PER_WEEK = 7;


final int WEEKS_PER_YEAR = 52;

double[][] minTemps = new


double[DAYS_PER_WEEK][WEEKS_PER_YEAR];

These statements specify the ranges for two indexes: The first index can range
from 0 to 6, while the second index can range from 0 to 51. Most people picture
a two-dimensional array as a rectangular arrangement, or matrix, of elements
Language Basics 37

Columns

0 1 51

Rows

FIGURE 1-4

A two-dimensional array

that form rows and columns, as Figure 1-4 indicates. The first dimension given
in the definition of minTemps is the number of rows. Thus, minTemps has 7 rows
and 52 columns. Each column in this matrix represents the seven daily minimum
temperatures for a particular week.
To reference an element in a two-dimensional array, you must indicate both In a two-dimensional
the row and the column that contain the element. You make these indications of array, the first
row and column by writing two indexes, each enclosed in brackets. For example, index represents
the row, the second
minTemps[1][51] is the element in the 2nd row and the 52nd column. In the index represents the
context of the temperature example, this element is the minimum temperature column
recorded for the 2nd day (Monday) of the 52nd week. The rules for the indexes of
a one-dimensional array also apply to the indexes of multidimensional arrays.
As an example of how to use a two-dimensional array in a program, con-
sider the following program segment, which determines the smallest value in
the previously described array minTemps:

// minTemps is a two-dimensional array of daily minimum An example of using


// temperatures for 52 weeks, where each column of the a two-dimensional
// array contains temperatures for one week. array

// initially, assume the lowest temperature is


// first in the array
double lowestTemp = minTemps[0][0];
int dayOfWeek = 0;
int weekOfYear = 0;
38 Chapter 1 Review of Java Fundamentals

// search array for lowest temperature


for (int weekIndex = 0; weekIndex < WEEKS_PER_YEAR;
++weekIndex) {
for (int dayIndex = 0; dayIndex < DAYS_PER_WEEK;
++dayIndex) {
if (lowestTemp > minTemps[dayIndex][weekIndex]) {
lowestTemp = minTemps[dayIndex][weekIndex];
dayOfWeek = dayIndex;
weekOfYear = weekIndex;
} // end if
} // end for
} // end for
// Assertion: lowestTemp is the smallest value in
// minTemps and occurs on the day and week given by
// dayOfWeek and weekOfYear; that is, lowestTemp ==
// minTemps[dayOfWeek][weekOfYear].

It is entirely possible to declare minTemps as a one-dimensional array of


364 (7 * 52) elements, in which case you might use minTemps[81] instead of
minTemps[4][11] to access the minimum temperature on the 4th day of the
11th week. However, doing so will make your program harder to understand!
Although you can declare arrays with more than two dimensions, it is unusual
to have an array with more than three dimensions. The techniques for working
with such arrays, however, are analogous to those for two-dimensional arrays.
You can initialize the elements of a two-dimensional array just as you
initialize a one-dimensional array. You list the initial values row by row. For
example, the statement

int[][] x = {{1,2,3},{4,5,6}};

initializes a 2-by-3 array x so that it appears as


1 2 3
4 5 6

That is, the statement initializes the elements x[0][0], x[0][1], x[0][2],
x[1][0], x[1][1], and x[1][2] in that order. In general, when you assign
initial values to a multidimensional array, it is the last, or rightmost, index that
increases the fastest.

1.2 Selection Statements


Selection statements allow you to choose among several courses of action
according to the value of an expression. In this category of statements, Java
provides the if statement and the switch statement.
Selection Statements 39

The if Statement
You can write an if statement in one of two ways:

if (expression) An if statement has


statement1 two basic forms

or

if (expression)
statement1
else
statement2

where statement1 and statement2 represent any Java statement. Such statements can be
compound; a compound statement, or block, is a sequence of statements enclosed
in braces. Though not a requirement of Java, this text will always use a compound
statement in language constructs, even if only a single statement is required.
If the value of expression is true, statement1 is executed. Otherwise, the
first form of the if statement does nothing, whereas the second form executes Parentheses around
statement2. Note that the parentheses around expression are required. the expression in
For example, the following if statements each compare the values of two an if statement
are required
integer variables a and b:

if (a > b) {
System.out.println(a + " is larger than " + b + ".");
} // end if
System.out.println("This statement is always executed.");

if (a > b) {
larger = a;
System.out.println(a + " is larger than " + b + ".");
}
else {
larger = b;
System.out.println(b + " is larger than " + a + ".");
} // end if

System.out.println(larger + " is the larger value.");


40 Chapter 1 Review of Java Fundamentals

You can nest if statements in several ways, since either statement1 or statement2
can itself be an if statement. The following example, which determines the largest
of three integer variables a, b, and c, shows a common way to nest if statements:

You can nest if if ((a >= b) && (a >= c)) {


statements largest = a;
}
else if (b >= c) { // a is not largest at this point
largest = b;
}
else {
largest = c;
} // end if

The switch Statement


When you must choose among more than two courses of action, the if state-
A switch state- ment can become unwieldy. If your choice is to be made according to the
ment provides value of an integral expression, you can use a switch statement.
a choice of several For example, the following statement determines the number of days in a
actions according to
month. The int variable month designates the month as an integer from 1 to 12.
the value of an inte-
gral expression
switch (month) {
// 30 days hath Sept., Apr., June, and Nov.
Without a break case 9: case 4: case 6: case 11:
statement, execu- daysInMonth = 30;
tion of a case will break;
continue into the // all the rest have 31
next case case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;

// except February
case 2: // assume leapYear is true if leap
// year, else is false
if (leapYear) {
daysInMonth = 29;
}
else {
daysInMonth = 28;
} // end if
break;

default:
System.out.println("Incorrect value for Month.");
} // end switch
Iteration Statements 41

Parentheses must enclose the integral switch expression—month, in this


example. The case labels have the form

case expression:

where expression is a constant integral expression. After the switch expression


is evaluated, execution continues at the case label whose expression has the
same value as the switch expression. Subsequent statements execute until
either a break or a return is encountered or the switch statement ends.
It bears repeating that unless you terminate a case with either a break or a
return, execution of the switch statement continues. Although this action can be
useful, omitting the break statements in the previous example would be incorrect.
If no case label matches the current value of the switch expression, the
statements that follow the default label, if one exists, are executed. If no
default exists, the switch statement exits.

1.3 Iteration Statements


Java has three statements—the while, for, and do statements—that provide
for repetition by iteration—that is, loops. Each statement controls the number
of times that another Java statement—the body—is executed. The body can be
a single statement, though this text will always use a compound statement.

The while Statement


The general form of the while statement is

while (expression) A while statement


statement executes as long
as the expression
As long as the value of expression is true, statement is executed. Because expression is true
is evaluated before statement is executed, it is possible that statement will not
execute at all. Note that the parentheses around expression are required.
Suppose that you wanted to compute the sum of a list of integers stored in
an array called myArray. The following while loop accomplishes this task:

int sum = 0;
int index = 0;
while (index <= myArray.length) {
sum += myArray[index];
} // end while

The break and continue statements. You can use the break statement—
Use of a break
which you saw earlier within a switch statement—within any of the iteration state- statement within a
ments. A break statement within the body of a loop causes the loop to exit immedi- loop is generally
ately. Execution continues with the statement that follows the loop. This use of poor style
break within a while, for, or do statement is generally considered poor style.
42 Chapter 1 Review of Java Fundamentals

The continue statement stops only the current iteration of the loop and
begins the next iteration at the top of the loop. The continue statement is
valid only within while, for, or do statements.

The for Statement


The for statement provides for counted loops and has the general form

A for statement for (initialize; test; update)


lists the initializa- statement
tion, testing, and
updating steps in
one location
where initialize, test, and update are expressions. Typically, initialize is an
assignment expression that initializes a counter to control the loop. This ini-
tialization occurs only once. Then, if test, which is usually a logical expression,
is true, statement executes. The expression update executes next, usually incre-
menting or decrementing the counter. This sequence of events repeats, begin-
ning with the evaluation of test, until the value of test is false. As with the
previous constructs, statement is usually a compound statement.
For example, the following for statement sums the integers from 1 to n:

int sum = 0;
for (int counter = 1; counter <= n; ++counter) {
sum += counter;
} // end for

// this statement is always executed


int x = 0;

If n is less than 1, the for statement does not execute at all. Thus, the previous
statements are equivalent to the following while loop:

int sum = 0;
int counter = 1;
while (counter <= n) {
sum += counter;
++counter;
} // end while
// this statement is always executed
int x = 0;

In general, the logic of a for statement is equivalent to

A for statement is initialize;


equivalent to a while (test) {
while statement statement;
update;
} // end while
Iteration Statements 43

with the understanding that if statement contains a continue, update will


execute before test is evaluated again.
The following two examples demonstrate the flexibility of the for statement:

for (byte ch = 'z'; ch >= 'a'; --ch) {


// ch ranges from 'z' to 'a'
statements to process ch
} // end for

for (double x = 1.5; x < 10; x += 0.25) {


// x ranges from 1.5 to 9.75 at steps of 0.25
statements to process x
} // end for

The initialize and update portions of a for statement each can contain
several expressions separated by commas, thus performing more than one
action. For example, the following loop raises a floating-point value to an
integer power by using multiplication:

// floating-point power equals floating-point x


// raised to int n; assumes integer expon
for (power = 1.0, expon = 1; expon <= n; ++expon){
power *= x;
} // end for

Both power and expon are assigned values before the body of the loop exe-
cutes for the first time.
Because the for statement consolidates the initialization, testing, and A for statement is
updating steps of a loop into one statement, Java programmers tend to favor it usually favored over
over the while statement. For example, notice how the following while loop the while statement
sums the values in an array x:

sum = 0;
int i = 0;
while (i < x.length) {
sum += x[i];
i++;
} // end while

This loop is equivalent to the following for statement:

for (int i = 0, sum = 0; i < x.length; sum += x[i++]) {


}

In fact, this for statement has an empty body!


44 Chapter 1 Review of Java Fundamentals

You can omit any You can omit any of the expressions initialize, test, or update from a for
of the initialization, statement, but you cannot omit the semicolons. For example, you can move
testing, and updat- the update step from the previous for statement to the body of the loop:
ing steps in a for
statement, but you
cannot omit the for (int i = 0, sum = 0; i < x.length; ) {
semicolons sum += x[i++];
} // end for

You also could omit both the initialization and the update steps, as in the fol-
lowing loop:

for ( ; x > 0; ) {
statements to process nextValue in inputLine
} // end for

This for statement offers no advantage over the equivalent while


statement:

while (x > 0)

Although you can omit the test expression from for, you probably will not
want to do so, because then the loop would be infinite.

The for loop and arrays. Java provides a loop construct that simplifies iter-
ation through the elements of an array. A logical name for this loop construct
would be the “foreach” loop, but the language developers wanted to avoid
adding a new keyword to the language. So the new form of the for loop is
often referred to as the “enhanced for loop.”
The syntax for the enhanced for loop when used with arrays is as follows:

for (ArrayElementType variableName : arrayName)


statement

where ArrayElementType is the type of each element in the array, and arrayName
is the name of the array you wish to process element by element. The loop
begins with the variableName assigned the first element in the array. With each
iteration of the loop, variableName is associated with the next element in the
array. This continues until all of the elements in the array have been processed.
For example:

String[] nameList = { "Janet", "Frank", "Mike", "Doug"};


for (string name: nameList) { // for each name in nameList
System.out.println(name);
} // end for
Program Structure 45

is equivalent to the following:

String[] nameList = { "Janet", "Frank", "Mike", "Doug"};


for (int index=0; index < nameList.length; index++) {
System.out.println(nameList[index]);
} // end for

The do Statement
Use the do statement when you want to execute a loop at least once. Its
general form is

do { A do statement
statement loops at least once
} while (expression);

Here, statement executes until the value of expression is false.


For example, suppose that you execute a sequence of statements and then
ask the user whether to execute them again. The do statement is appropriate,
because you execute the statements before you decide whether to repeat them:

char response;
do {
. . . (a sequence of statements)
ask the user if they want to do it again
store user’s response in response
} while ( (response == 'Y') || (response == 'y') );

1.4 Program Structure


Let’s begin our discussion of program structure with the simple Java applica-
tion in Figure 1-5 that computes the volume of a sphere. It consists of two
classes, SimpleSphere and TestClass. Each of these classes is contained in a
separate file that has the same name as the class, with .java appended to the
end. A typical Java program consists of several classes, some of which you write
and some of which you use from the Java Application Programming Interface
(API). A Java application has one class that contains a method main, the start- Each Java applica-
ing point for program execution. Running the program in Figure 1-5 produces tion must contain at
the following output: least one class that
has a method main
The volume of a sphere of radius 19.1 inches is 29186.95

This application includes all of the basic elements of Java program struc-
ture (packages, classes, data fields, and methods). The sections that follow
discuss each of these elements.
46 Chapter 1 Review of Java Fundamentals

File SimpleSphere.java
1. Indicates SimpleSphere is part of a package ----> package MyPackage;
2. Indicates class Math is used by SimpleSphere --> import java.lang.Math;
3. Begins class SimpleSphere --------------------------> public class SimpleSphere {
4. Declares a private data field radius -----------------> private double radius;
5. Declares a constant ---------------------------------------> public static final double DEFAULT_RADIUS = 1.0;
6. A default constructor ------------------------------------> public SimpleSphere() {
7. Assignment statement ----------------------------------> radius = DEFAULT_RADIUS;
} // end default constructor
8. A second constructor ------------------------------------> public SimpleSphere(double initialRadius) {
9. Assignment statement -----------------------------------> radius = initialRadius;
} // end constructor
10. Begins method getRadius ---------------------------> public double getRadius() {
11. Returns data field radius -----------------------------> return radius;
} // end getRadius
12. Begins method getVolume ---------------------------> public double getVolume() {
13. A comment -------------------------------------------------> // Computes the volume of the sphere.
14. Declares and assigns a local variable ------------------> double radiusCubed = radius * radius * radius;
15. Returns result of computation -------------------------> return 4 * Math.PI * radiusCubed / 3;
} // end getVolume
16. Ends class SimpleSphere ----------------------------> } // end SimpleSphere

File TestClass.java
17. Indicates TestClass is part of a package ---------> package MyPackage;
18. Begins class TestClass -------------------------------> public class TestClass {
19. Begins method main -----------------------------------> static public void main(String[] args) {
20. Declares reference ball --------------------------------> SimpleSphere ball;
21. Creates a SimpleSphere object --------------------> ball = new SimpleSphere(19.1);
22. Outputs results --------------------------------------------> System.out.println("The volume of a sphere of radius "
23. Continuation of output string --------------------------> + ball.getRadius() + " inches is "
24. Continuation of output string --------------------------> + (float)ball.getVolume()
+ "cubic inches\n");
} //end main
25. Ends class TestClass ----------------------------------> } // end TestClass

FIGURE 1-5

A simple Java application

Packages
Java packages provide a mechanism for grouping related classes. To indicate
that a class is part of a package, you include a package statement as the first
program line of your code. For example, lines 1 and 17 in Figure 1-5 indicate
Program Structure 47

that both of these classes, SimpleSphere and TestClass, are in the package
MyPackage. The format of the package statement is
To include a class in
package package-name; a package, begin
the class’s source
Java assumes that all of the classes in a particular package are contained in the file with a package
statement
same directory. Furthermore, this directory must have the same name as the package.
The Java API actually consists of many predefined packages. Some of the Place the files that
more common of these packages are java.lang, java.util, and java.io. contain a package’s
The dot notation in these package names directly relates to the directory struc- classes in the same
directory
ture containing these packages. In this case, all of the directories correspond-
ing to these packages are contained in a parent directory called java.

import statement. The import statement allows you to use classes con-
tained in other packages. The format of the import statement is as follows:

import package-name.class-name; The import state-


ment provides
access to classes
For example, line 2 in Figure 1-5 imports the class Math from the package within a package
java.lang. The following line also could have been used:

import java.lang.*;

In this case, the * indicates that all of the items from the package
java.lang should be imported. Actually, this particular line can be omitted
from the program, since java.lang is implicitly imported to all Java code.
Explicitly importing java.lang.Math makes it clear to others who read your
code that you are using the class Math in this code.

Classes
An object in Java is an instance of a class. You can think of a class as a data type that An object is an
specifies the data and methods that are available for instances of the class. A class instance of a class
definition includes an optional subclassing modifier, an optional access modifier, A Java class defines
the keyword class, an optional extends clause, an optional implements clause, a new data type
and a class body. Figure 1-6 describes each of the components of a class.
When a new class is created in Java, it is either specifically made a subclass
of another class through the use of the extends clause or it is implicitly a sub-
class of the Java class Object. Creating a subclass is known as inheritance and
is discussed briefly in Chapter 4 and in depth in Chapter 9 of this text.
To create an object or instance of a class, you use the new operator. For
example, the expression

new SimpleSphere()

creates an instance of the type SimpleSphere.


48 Chapter 1 Review of Java Fundamentals

Component Syntax Description

Subclassing abstract Class must be extended to be useful.


modifier
(use only one) final Class cannot be extended.

Access public Class is available outside of package.


modifiers
no access modifier Class is available only within package.

Keyword class class-name Class should be contained in a file called


class class-name.java.

extends extends Indicates that this class is a subclass of the class


clause superclass-name superclass-name in the extends clause.

implements implements Indicates the interfaces that this class implements.


clause interface-list The interface-list is a comma-separated list of
interface names.

Class body Enclosed in braces Contains data fields and methods for the class.

FIGURE 1-6

Components of a class

Now let’s briefly examine the contents of the class body: data fields and
methods.

Data Fields
Data fields are class members that are either variables or constants. Data field
declarations can contain modifiers that control the availability of the data field
(access modifiers) or that modify the way the data field can be used (use modi-
fiers). The access modifiers are effective only if the class is declared public.
Although this text uses only a subset of the modifiers, Figure 1-7 shows them
all for completeness.
Program Structure 49

Type of modifier Keyword Description

Access modifier public Data field is available everywhere (when the class is
(use only one) also declared public).

private Data field is available only within the class.

protected Data field is available within the class, available in


subclasses, and available to classes within the same
package.

No access Data field is available within the class and within


modifier the package.

Use modifiers static Indicates that only one such data field is available
(all can be used at for all instances of this class. Without this modifier,
once) each instance has its own copy of a data field.

final The value provided for the data field cannot be


modified (a constant).

transient The data field is not part of the persistent state of


the object.

volatile The value provided for the data field can be


accessed by multiple threads of control. Java
ensures that the freshest copy of the data field is
always used.

FIGURE 1-7

Modifiers used in data field declarations

Data fields are typically declared private or protected within a class, with A class’s data fields
access provided by methods in the class. Hence, a method within a class has should be private
access to all of the data fields declared in the class. This allows the developer of or protected
the class to maintain control over how the data stored within the class is used.
Discovering Diverse Content Through
Random Scribd Documents
The Project Gutenberg eBook of Les partis
politiques en Province
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Les partis politiques en Province

Author: Paul Scudo

Release date: March 19, 2020 [eBook #61636]


Most recently updated: October 17, 2024

Language: French

Credits: Produced by Clarity, Christian Boissonnas and the Online


Distributed Proofreading Team at http://www.pgdp.net
(This
file was produced from images generously made available
by The Internet Archive/Canadian Libraries)

*** START OF THE PROJECT GUTENBERG EBOOK LES PARTIS


POLITIQUES EN PROVINCE ***
Au lecteur
Table des Matières

LES

PARTIS POLITIQUES
EN PROVINCE.

IMP. E. DÉZAIRS, A BLOIS.

LES

PARTIS POLITIQUES

EN PROVINCE,
Par P. Scudo.
PARIS,
LEQUIEN, LIBRAIRE, QUAI DES AUGUSTINS, 47.

MDCCCXXXVIII.

A LA SOCIÉTÉ ACADÉMIQUE

DE NANTES.
En témoignage
D'une vive reconnaissance.
Scudo.
I.
INTRODUCTION.
Expirant sous les débris de la société antique, le dix-huitième siècle
légua à son successeur l'impérieux devoir de trouver aux nations
délaissées une nouvelle moralité. La révolution de 89 brillera dans
l'avenir, comme une vaste épopée de l'esprit humain. Ce fut le cri
lugubre d'un monde corrompu succombant sous les coups d'une
génération nouvelle, qui s'emparait de la vie avec une impitoyable
fureur; ce fut l'acclamation spontanée et magnifique d'un peuple
malheureux, qui s'échappait des bastilles de la féodalité; ce fut
l'horrible immolation d'une caste sociale qui avait absorbé en elle
seule la puissance et la richesse de la nation; enfin, ce fut
l'apparition du principe de l'égalité, déposé par Jésus dans la
conscience du genre humain, qui, perçant l'enveloppe de la foi, se
constituait une vérité de l'intelligence.
Dans le petit nombre de lois fondamentales de l'esprit humain, il y
en a une qui les domine toutes: c'est le dogmatisme de la volonté.
La volonté de l'homme est une puissance primitive, qui ne se soumet
qu'à un principe supérieur; jamais elle n'accorde à une simple
volonté comme elle, le droit de la commander, si cette dernière ne
puise ce droit dans une source impersonnelle. Deux volontés
individuelles sont deux unités d'une même nature, qui ne peuvent
faire nombre, parce que l'une ne saurait se subordonner à l'autre. Si
dans les coups dont on l'accable, le soldat autrichien croyait voir
l'effet de la volonté du caporal qui les lui administre, il l'égorgerait à
l'instant même; mais sachant que le caporal n'est qu'un misérable
instrument, il remonte le fleuve de la hiérarchie sociale, et va
chercher la cause de son supplice jusque sur le trône de l'empire, où
sa raison trébuche et s'anéantit: l'histoire de l'humanité confirme ce
principe.
Cependant la société serait-elle possible avec ce tourbillon de
volontés individuelles, si un lien ne les réunissait pour en former un
tout harmonieux? évidemment non. Quel sera donc ce verbe
mystérieux qui établira l'ordre dans le chaos? Ici se partagent les
philosophes, et se multiplient les systèmes.
Pour qu'une volonté surgisse du sein de ses égales et vienne leur
imposer sa loi, il faut de toute nécessité qu'elle soit appuyée de l'une
des deux puissances qui seules, en ce monde, dominent les volontés
individuelles: de Dieu ou de l'humanité. Dieu et l'humanité, sources
sacrées d'où s'épandent les principes des sociétés; fleuves immenses
aux cours desquels doit se retremper la volonté qui prétend régir les
nations. Lorsque cette volonté émane de Dieu, c'est un tuteur
vigilant qui ne livre la liberté aux peuples qu'à mesure qu'ils
avancent dans le progrès; mais si elle s'échappe de l'acclamation des
masses, alors elle est le vœu intelligent des hommes émancipés.
Dans le premier cas, elle s'appelle royauté, dans le second,
souveraineté nationale.
Il est de l'essence de tout véritable principe d'être impersonnel, et
d'appartenir aux lois générales de la raison; et comme tel, il trouve
toujours une respectueuse obéissance. Mais aussitôt que ce principe
quitte les régions élevées où il a été conçu, et qu'il tombe dans la
personnalité, en perdant sa pureté originelle, il perd aussi sa force
sociale; il s'incarne alors, il s'individualise, il s'abâtardit sous la
volonté mesquine d'un homme ou d'une caste, et il périt comme un
fait isolé. Or, la volonté individuelle qui a reçu le baptême de Dieu ou
de l'humanité, se dépouille de son caractère humain, elle quitte la
terre et monte, comme le Christ, au séjour des principes; c'est à ce
titre qu'il lui est possible de gouverner les hommes. Que si, par la
succession des temps, elle manquait à sa haute destinée, alors elle
devra s'attendre à la résistance des autres volontés, qui ne verront
plus en elle qu'une force individuelle, sans mission et sans droit.
Ici il faut prévoir une question qu'on ne manquera pas de nous
faire. Comment Dieu manifeste-t-il son approbation? Comment
transmet-il son pouvoir à la volonté particulière? Admettriez-vous la
révélation? Nous répondrons à ces objections en exposant nos idées
sur la royauté.
En remontant aussi loin que possible le cours des affections de
l'homme, on trouve au fond de son intime nature un sentiment
primitif si vivace, qu'il survit à toutes les catastrophes de l'âme, et
qu'aucune forme politique ne saurait l'anéantir: c'est le sentiment
paternel. Le sentiment paternel est un délicieux amour de soi-même,
reversé sur l'image qui doit nous transmettre à l'avenir, et qui circule
dans nos veines avec la vie. Rien ne lui est antérieur, si ce n'est la
cause suprême à qui nous devons tout. En effet, la famille est une
monade sociale, placée sur la terre comme un point dans l'espace,
une note fondamentale de l'harmonie du monde. Monarchie,
république, tyrannie, tout passe et repasse au-dessus de cette unité
indestructible, qui survit aux orages de l'humanité comme le dernier
mot d'une mystérieuse Providence. C'est là, c'est au sein de la
famille que naquit et se développa la magistrature paternelle,
premier germe de l'autorité morale. Je dis premier germe de
l'autorité morale, car ce n'est ni à la force, ni à la richesse, ni à
l'assentiment de ses égaux que le père doit son pouvoir dans la
famille; il le doit à un sentiment qu'il n'a pas créé, à une cause qui
lui est supérieure. Mais quel est donc l'être fort qui donna à l'homme
cette douce affection pour sa progéniture, origine première de toute
autorité? La nature, dit le philosophe; Dieu, lui répond le chrétien:
qu'importe! vous convenez au moins que l'homme a puisé l'autorité
morale hors de sa volonté, je n'en demande pas davantage.
La magistrature paternelle était nécessaire. Il fallait aux enfants
jeunes, faibles et inexpérimentés, une autorité forte et bienveillante,
qui les guidât à travers les phénomènes du monde, et les initiât avec
prudence aux mystères de la vie. Tant que le père usa de son
pouvoir dans l'intérêt de ses enfants et pour le bonheur de la
communauté, il était juste, puisqu'il était indispensable; aussi sa
volonté était-elle religieusement exécutée, car elle avait la sainteté
d'un principe. Mais lorsqu'oubliant sa mission tutélaire, le père voulut
étouffer sous sa tyrannique personnalité l'indépendance; de ses
enfants, le fils aîné, émancipé par l'âge et la raison, se posa en face
de son père et lui dit: «Ton autorité absolue expire devant ma
liberté; et je suis libre puisque je me suffis à moi-même. Je t'ai obéi
comme père, comme magistrat chargé de soutenir ma faiblesse;
mais homme et ton égal, je te résiste.» Et assis autour de l'âtre
paternel, le fils prit part au conseil de la famille. Voilà l'origine de
l'aristocratie, qui fut le premier accent de la liberté.
La royauté antique, dans sa vénérable majesté, a tous les
caractères de la magistrature paternelle; elle en est
incontestablement le développement régulier et naturel. Vous la
voyez avec son sceptre pastoral, le front ceint d'une couronne
mystique, couverte d'un manteau sacré, se retirer dans un
tabernacle, comme une parole divine. Elle est simple et absolue, et
jamais elle ne s'inquiète de l'assentiment des peuples, qu'elle dirige
de sa puissante main. Elle les gouverne sans contrôle, car elle
souffre et prévoit pour eux; elle est l'expression des mœurs naïves
de cet âge reculé; c'est la science des vieux jours, c'est le temps et
son expérience guidant les pas incertains des nations. D'ailleurs la
royauté était la seule forme sociale que pût concevoir alors
l'intelligence des peuples; elle était la réalisation extérieure d'un
besoin de l'esprit, elle était l'expression de l'unité.
Or, l'unité est le but éternel auquel tend l'esprit humain. Il la veut
en toutes choses et à toutes les époques de la vie; seulement chez
l'homme simple elle n'est qu'une idée, chez le philosophe elle forme
un système. Les progrès des peuples ainsi que ceux de l'individu
peuvent se mesurer à la grandeur de l'unité qu'ils se sont faite. Dans
la haute antiquité l'homme voyait les bornes du monde là où
s'arrêtait l'horizon; et Dieu circonscrivait la personnalité humaine,
comme la vigne enlace de ses flexibles rameaux l'orme de nos
campagnes. Plus tard, en brisant l'égoïsme de son intelligence, il y
laissa pénétrer des phénomènes ignorés; avec les connaissances de
l'homme, s'agrandit aussi l'idée de la nature et de son auteur; et
Dieu, adoré jusqu'alors sous la forme d'une nymphe ou d'un roseau,
fut replacé par le progrès sur le trône de l'univers. D'abord il confond
tout dans une vaste unité; puis il la fractionne en mille autres par
l'abus de l'analyse; et enfin il reconstruit le tout par la puissance de
sa raison. Ignorant, il est superstitieux; l'analyse le rend athée; par
la science, il devient religieux comme Newton. C'est ainsi que sous
les symboles d'or de la nature se cachent les mystères de la destinée
humaine; mystères qui ne se dévoilent à l'humanité qu'à mesure
qu'elle avance dans l'avenir.
Si l'art, si la religion, si toutes les créations spontanées ou
réfléchies de l'esprit humain témoignent de ce besoin d'unité, ce
témoignage éclate plus encore dans l'organisation politique. La
société primitive, telle que nous la voyons s'épanouir en Orient, est
une extension de la famille et rien de plus; et la royauté est fille de
l'autorité paternelle. Les subtiles combinaisons sont indignes du sens
commun de l'histoire.
Les révolutions sociales qui, au sein de la famille, avaient arrêté
l'empiétement égoïste de l'autorité paternelle, se renouvelèrent plus
tard autour de la royauté, quand celle-ci oublia sa mission
providentielle. Héritière du pouvoir du père de famille, la royauté
était le résultat de l'accroissement de l'humanité, et de la
transformation de la famille en la tribu. Tant qu'elle resta dans les
limites de son autorité légitime, et qu'elle présida avec amour à
l'émancipation des peuples, sa volonté ne rencontra jamais un
obstacle; mais lorsqu'elle voulut résister au progrès, et refuser la
liberté à ceux qui la réclamaient et qui la méritaient, ceux-ci lui
tinrent le même langage que le fils avait tenu à son père, et
s'opposèrent à l'extension de son autorité. La royauté fit alors ce
qu'avait fait le père de famille, ce que font tous les pouvoirs quand
ils voient expirer le jour de la domination: elle employa la force. A la
force on opposa la force; et, vaincue dans ce conflit de volontés
individuelles, la royauté fut obligée d'admettre au partage de la
souveraineté ceux-là mêmes qu'elle venait de combattre. Cette
seconde aristocratie fut un nouveau progrès de la liberté.
C'est un fait incontestable: l'aristocratie a été la mère de la liberté
sociale. Les droits que l'aristocratie exigea de la puissance royale
furent ceux que plus tard les peuples réclamèrent de l'aristocratie
elle-même; partout où l'aristocratie n'a pu éclore et restreindre la
volonté égoïste de la royauté, là règne un profond despotisme.
Voyez l'Orient.
Mais cette nouvelle aristocratie, qui partage actuellement avec la
royauté les droits de la souveraineté politique, comment se conduira-
t-elle à son tour avec ceux qui plus tard viendront aussi frapper à la
porte de l'état, et demander leur émancipation? Sera-t-elle assez
juste pour leur tendre une main fraternelle, et pour les introduire
sans résistance dans la légalité? Non; elle voudra également se
perpétuer au pouvoir, et elle ne renoncera à la jouissance de ses
priviléges qu'après avoir été vaincue par la majorité. C'est par une
suite de semblables révolutions, c'est en élargissant successivement
le cercle du progrès, c'est en passant de la royauté pure à une petite
aristocratie, de celle-ci à une plus grande, que l'humanité chemine
dans l'histoire, jusqu'à ce que la résistance de ceux qui dominent
devenant trop forte, il arrive une de ces grandes catastrophes
sociales, qui bouleversent et renouvellent tout.
Le dix-huitième siècle a été un grand tribun, dont la magnifique
parole retentira loin dans l'avenir; mais il fut trop passionné pour
avoir été impartial. Saisi d'une haine profonde contre une société
avilie qu'il voulait reconstituer, il étudia l'histoire avec un cœur
courroucé et un esprit aveuglé par de mesquines préoccupations.
Pour lui, tout ce qui s'était accompli depuis la chute du paganisme
n'avait été que le pillage du monde civilisé par la barbarie; il ne
voyait dans la féodalité que le règne de la force et la négation de la
moralité humaine; aussi traversa-t-il le moyen-âge l'âme remplie
d'un sentiment de terreur et de dégoût, et il courut bien vite se jeter
dans les bras de la radieuse antiquité. Épris d'un amour ardent pour
ses turbulentes démocraties, il se plaisait à la lecture de leurs
annales comme à celles d'un poëme héroïque. Plutarque et ses
grands hommes fut le livre chéri du dix-huitième siècle. Il parcourut
ces pages vénérables de la belle humanité avec un plaisir indicible;
puis, il tira imprudemment ces larges physionomies du cadre social
qui les contenait et les expliquait, et il se les offrit comme des
symboles dignes de son adoration. La Grèce et ses vives
populations, Rome, ses conquêtes et ses sanglants orages, lui
parurent contenir l'expression la plus élevée de la liberté humaine. Il
ne s'aperçut pas, tant il était fasciné par les beautés de l'art antique,
que, dans cette Athènes, si glorieuse et si belle, la volonté sociale
émanait exclusivement de l'aristocratie de la cité! il ne vit pas, dis-je,
que, sous cette population souveraine et absolue, qui jugeait en
dernier ressort toutes les grandes questions de la patrie, gémissait
un monde d'infortunés esclaves, livrés comme de vils animaux aux
caprices du citoyen! Oui, il ignorait que ce superbe Athénien, qui
allait sur la place publique applaudir Démosthènes, avait, dans sa
maison, dans ses terres, comme un seigneur féodal, cent
malheureux occupés à labourer ses champs, et à préparer son dîner.
Enfin le dix-huitième siècle méconnut cette profonde vérité: que la
civilisation antique ne touchait que la superficie de la société; que
l'homme y était toujours immolé au citoyen; qu'il n'y était libre
qu'autant qu'il partageait la souveraineté, et que cette souveraineté
était tout entière dans les mains d'une faible minorité.
De cette fausse appréciation de la marche de l'humanité, il résulte
deux faits qui caractérisent le dix-huitième siècle, et qui ont eu sur la
révolution de 89 une influence remarquable. Du moment où les
philosophes furent convaincus que la liberté avait atteint, il y a deux
mille ans, sa plus large portée; et que le progrès, épouvanté de la
chute de la société antique, s'était arrêté sur les lèvres éloquentes
de l'art grec et romain, ils durent être forcément persuadés que pour
raviver le corps social, il n'y avait que deux moyens possibles:
déblayer le sol de l'Europe de tout ce qu'y avait apporté le tourbillon
des peuples du Nord, ramener ensuite les nations modernes aux
formes sévères de l'antique démocratie. L'influence d'un point de vue
historique sur les affaires de la vie est si grande, qu'en laissant
échapper le sens de l'esprit social de l'antiquité, le dix-huitième
siècle fut contraint de méconnaître la grande loi progressive du
genre humain. La question ainsi posée, il dut tout entreprendre pour
dépouiller nos vieilles nations chrétiennes de leur enveloppe
séculaire, et croire qu'une fois mise à nu, il serait facile de les couvrir
d'un pallion grec ou d'une toge romaine. Il ne pouvait douter un seul
instant de la maturité des masses à recevoir la souveraineté
politique, puisqu'il était malheureusement convaincu qu'Athènes,
Sparte et Rome avaient été, il y a deux mille ans, de pures
démocraties. Voilà la grande erreur de la philosophie du dernier
siècle, erreur dont nous verrons les résultats dans la suite.
La révolution de 89, fidèle en tout point aux doctrines
philosophiques du dix-huitième siècle, déplaça la source de la
souveraineté, et la fit surgir de la volonté des masses. Les hommes
sont égaux devant la loi de Dieu, avait dit le Christ; les hommes
doivent être égaux devant la loi des hommes, lui répond Mirabeau
dix-huit cents ans après; et au bruit de cette ineffable parole,
l'aristocratie française s'enfuit pour jamais dans les entrailles de la
nation. C'est ainsi qu'à travers les siècles, qui passent comme des
ombres légères, se complètent les pensées civilisatrices. Chaque
peuple paraît à son tour sur la scène du monde, où, par la bouche
de ses sages et de ses artistes, il formule le progrès.
D'abord, l'assemblée constituante porte sa main vigoureuse sur
toutes les parties de la vieille société, et débarrasse le sol de cette
foule de droits féodaux que réprouvait la raison. Puis avec une
admirable intelligence, elle se saisit de toutes les branches de
l'administration publique, et jette sur la France un réseau de lois qui
portent en tout lieu la vie et l'unité. Cette restauration des lois
organiques; cette simplification des rouages administratifs; cet esprit
d'unité, répandu sur toute la surface du pays; cette réhabilitation de
l'homme et de ses droits civils; cette justice distributive, égale pour
tous et pour chacun: voilà l'œuvre immortelle de la Constituante,
œuvre depuis long-temps préparée par les progrès de l'esprit
humain.
Nous l'avons déjà dit; deux seuls principes peuvent légitimement
gouverner le monde: le principe primordial de la tutelle gravée dans
le cœur de l'homme, qui du père de famille passa à la royauté, de
celle-ci à une aristocratie, et ainsi de suite, comme le filet d'eau qui,
du sommet des hautes montagnes, tombe de cascade en cascade et
va se perdre à l'océan; et celui de la souveraineté nationale. Ces
deux principes sont exclusifs, et ils arrivent à des époques
différentes.
Quel que soit celui de ces deux principes qui constitue la société,
elle se compose toujours de deux parties: la partie morale où réside
le gouvernement et la conscience du corps politique, et la partie
inférieure et végétative où se débattent les individualités. On peut
améliorer la seconde, simplifier ses relations avec l'état, la mettre en
harmonie avec les nouveaux besoins sans toucher à la partie morale,
sans déplacer la souveraineté: ces mouvements arrivent très
fréquemment dans la société matérielle, et portent dans l'histoire le
nom de révolution politique. L'assemblée constituante venait
d'accomplir la plus grande révolution politique des temps modernes,
et de réorganiser en toutes ses parties la société matérielle. Il
s'agissait de savoir maintenant si la raison des masses était arrivée à
ce point de maturité indispensable, pour présider à ses propres
destinées; s'il était temps de remettre au peuple sa robe virile? Cela
n'était pas douteux pour l'assemblée constituante, et d'une voix qui
troubla le monde, elle proclama la souveraineté des peuples. Il
restait à réaliser ce principe, à l'affermir dans la société. En face
d'une monarchie aussi vieille que la nation, pleine de respect pour
un roi simple et honnête homme, la main de l'assemblée hésita à
l'achèvement de son œuvre; elle eut l'incroyable simplicité de confier
à une royauté de dix siècles la garde de la souveraineté du peuple,
rapprochant ainsi deux principes inconciliables, dont l'un ne doit la
vie qu'à la mort de l'autre. Ici est la faute, ici se voit la fatale
influence de la préoccupation historique du dix-huitième siècle. A
trois cents ans d'intervalle, l'assemblée constituante commet la
même erreur que le concile de Constance, qui, après avoir réformé
l'église en son chef et dans ses membres, s'avise de réserver au
pape le droit de convoquer le concile! défaisant d'une main ce qu'il
avait fait de l'autre.
L'infortuné Louis XVI, trompé par la dignité mensongère que lui
avait conservée la constitution de 91, cherche de toutes parts
l'autorité qui est inséparable de la royauté, et il ne trouve que
résistance et mépris. Abandonné de tous les siens, assis sur un trône
solitaire comme une victime expiatoire, il entend gronder la voix
formidable des factions qui lui imputent les crimes qui sont le
résultat inévitable du pacte social qu'on lui a imposé, et il paie de sa
tête l'erreur de l'assemblée constituante. A sa mort, la confusion
s'empare des choses. Il se fait un horrible mélange de toutes les
vérités sociales. Les peuples se précipitent dans un gouffre de fange
et s'égorgent sur le cadavre de la royauté. L'esprit humain, privé
tout-à-coup de sa foi antique, court comme un démon déchaîné à
toutes les aberrations; il renverse tout ce qui s'oppose à ses fureurs,
et, la torche du fanatisme à la main, il salit les pages de l'histoire de
l'humanité des plus dégoûtantes bacchanales. Deux partis surgissent
de ce chaos mémorable, qui, comme les génies du bien et du mal,
se disputent l'empire du monde.
L'un, composé des plus nobles intelligences, fils des progrès du
temps, nourri de l'histoire et de la philosophie des nations; fort par
son éloquente parole qu'anime un profond amour de la patrie;
mélange de grâce et d'élévation, de force et d'atticisme, il résume
dans son bataillon sacré toute la civilisation française. Les Girondins,
généreux vainqueurs d'une aristocratie séculaire, prêtent une oreille
attentive aux cris des vaincus, et ne veulent pas qu'on les
abandonne à la rage de la basse démocratie. Ils savent bien que le
sang versé par les factions enfante des martyrs, et qu'on n'efface
pas une vieille société d'un coup d'éponge. Âmes naïves et sincères,
ils veulent que toutes les voix de la patrie se groupent autour de la
souveraineté nationale, et que la révolution se rattache à la chaîne
du passé. Point de hache, point de proscription, paix, miséricorde,
égalité et justice pour toutes les classes, pour tous les individus!
Mais, illustres et à jamais déplorables victimes de leur propre
faiblesse, ils succombent faute d'énergie et de prévoyance sous les
coups d'une faction sanguinaire qui, s'élançant du bas-fond de la
société, vient plonger ses griffes de fer dans le sein de la France.
La Montagne, terrible expression de l'égoïsme démocratique,
sanglante révélation de nos misères, mémorable enseignement qui
doit nous apprendre que d'horreurs on peut commettre au nom des
plus saintes vérités! ramas d'ignobles écoliers, misérables phraseurs
nés de la poussière scolastique du dix-huitième siècle, ils n'auraient
pas su administrer un village en respectant l'humanité. Sans
connaissance du passé, sans intelligence des besoins de l'avenir, ils
prennent pour symbole d'un siècle d'industrie, les sales guenilles des
misérables; et ils voudraient étouffer trente millions d'hommes sous
des formules lacédémoniennes. Écoutez-les, dans leur langage
ordurier et bouffon; ils n'ont que des insultes pour leurs victimes, et
que des abstractions de collége pour ceux qui leur demandent la
paix et le bonheur! Oh! les sublimes législateurs! qui répondent à
coup de guillotine à la moindre objection qu'on leur fait! Oui, la
Montagne sera toujours l'exécration des nobles cœurs et des esprits
élevés; elle est à l'immortel principe de la souveraineté nationale ce
que la Saint-Barthélemy fut au christianisme, la profanation d'une
vérité de l'esprit humain. Née des erreurs du dix-huitième siècle sur
l'antiquité, la Montagne immola des milliers de victimes avec des
phrases de rhéteur; elle égorgea la liberté, et la livra à la volonté
d'un soldat heureux.
L'empire ne change rien à la question des principes. Pouvoir
révolutionnaire et sans légalité, il réunit, d'une main vigoureuse et
habile, les éléments fécondants de la révolution de 89. Il organise la
société matérielle jusqu'alors si maltraitée, arme la cité d'une force
nécessaire pour la garantir des intérêts individuels, et il va sur les
champs de bataille défendre la France nouvelle contre l'Europe
monarchique.
En 1814, la maison de Bourbon remonte sur le trône de ses
ancêtres, et avec elle le principe primordial de la tutelle. Elle se
ressaisit de la souveraineté inhérente à la véritable royauté; et, si
elle juge à propos d'accorder aux besoins des temps quelques
libertés, c'est comme une concession de sa toute-puissance quelle
pourra absorber, quand elle le jugera bon. Cette absorption qu'elle
essaya l'étouffa en 1830.
La révolution de juillet, en renversant la restauration, a voulu
reprendre à la royauté le principe de la souveraineté et le replacer
dans la nation. Les hommes qui depuis quinze ans avaient
manœuvré dans le cercle de la Charte royale de 1814, et qui avaient
fait à la monarchie légitime cette facile, cette grammaticale
opposition; ces hommes, dis-je, furent bien effrayés à la vue de la
victoire populaire qu'ils étaient loin d'avoir prévue; et, satisfaits de la
proscription de la branche aînée, ils s'empressèrent de ramasser
pièce à pièce les mille fragments du gouvernement détruit, et,
soufflant de leurs petits poumons sur ce tas de brisures, ils s'en
firent un ordre social tout juste assez grand pour les héberger,
laissant le peuple vainqueur aboyer à la porte.
Ce livre n'est point un pamphlet. Philosophe, nous cherchons dans
l'étude de l'histoire à découvrir ces grands principes qui sont la base
des sociétés. Nous n'ignorons pas qu'entre ces époques
mémorables, où l'homme, dépouillé de ses vieilles croyances,
cherche à reconstruire le monde à sa nouvelle image, il y a des
moments terribles d'hésitation et de souffrance, de force et de
faiblesse, pendant lesquels l'humanité, désertant les temples d'une
voix qui expire, s'avance lentement dans l'avenir; et que souvent elle
revient se pencher douloureusement sur les débris du passé qu'elle
inonde de ses larmes. Les gouvernements, qui alors s'emparent de
la société matérielle pour donner le temps à la pensée de préparer
sa nouvelle demeure, sont très utiles; mais leur existence est
attachée à la durée des besoins qui les avaient appelés. La Charte de
1830 n'a aucun de ces caractères de grandeur et d'unité qui décèlent
une institution forte: c'est une halte de la société matérielle qui,
dans l'incertitude du chemin qu'elle doit suivre, attend le retour de
ses éclaireurs pour continuer son voyage.
On comprend le but de ce livre. C'est l'étude d'un homme
indépendant qui, sans aucune préoccupation politique, cherche à
pénétrer dans la vie intime de ces fractions sociales qui composent
une nation, à y saisir le trait qui les caractérise, et à prendre acte
des éléments qu'elles déposent dans la moralité d'un peuple.
L'auteur a voulu tracer un page de l'histoire de son temps: La
critique lui apprendra s'il a réussi dans ses efforts.
II.
DE LA FRANCE.
Au sein de la famille européenne, parmi ces nations qui naquirent
des dépouilles de l'empire romain, et que la voix du christianisme
arracha à la barbarie, il est un peuple fort et puissant, indomptable à
la guerre, actif, laborieux dans la paix, gai, spirituel, à la
physionomie douce, vive et légère, aux formes sveltes, élégantes, à
l'abord facile et communicatif, au parler bref et sentencieux: c'est le
peuple français.
La nature, qui semble ne livrer à l'humanité ses innombrables
arcanes qu'à mesure que celle-ci se rend digne de les comprendre,
tient encore caché à nos yeux avides le mystère de l'individualité des
peuples. Grande est la préoccupation du sage, lorsqu'en jetant les
yeux sur cette terre, il voit ces milliers de nations, filles d'un même
dieu, toutes marquées au front du sceau de la même famille, et
chacune distinguée par un trait particulier; toutes soumises aux
mêmes peines, aux mêmes besoins, naissant dans la douleur,
mourant dans la douleur, et chacune parcourant un sentier unique
dans la vie, et chacune laissant un passé qui lui est propre! Ce n'est
pas seulement un peuple qui diffère d'un peuple, c'est la caste qui se
dessine dans un peuple, c'est la famille dans la caste, c'est l'individu
dans la famille, c'est l'individu qui diffère de l'individu. Quelle est
donc la cause suprême qui tira de l'unité primitive de la création,
cette éclatante variété? Quel est celui qui du type éternel de la race
humaine, fit surgir ces insaisissables physionomies qui frappent et
vous étonnent? Comment sur cette face d'homme si simple a-t-on su
écrire tant d'incroyables choses, cosi dolci accenti, cosi orribili
favelle!
Les phénomènes du monde qui enveloppent et pénètrent l'homme
de toutes parts, ont dû modifier sa flexible nature; mais leur
influence a été plutôt physique que morale. Ce n'est pas dans la
langue de Monton de Montesquieu que nous trouverons le principe
qui constitue la nationalité; c'est par les idées qu'un homme diffère
d'un homme, et c'est par les idées qu'une société se distingue d'une
autre société. Lorsque deux intelligences s'abreuvent à la même
source, que deux cœurs vibrent à l'unisson, que deux âmes versent
dans la même coupe et leurs joies et leurs douleurs; alors il y a paix,
il y a harmonie, il y a société. Un peuple est une réunion d'individus
qui pendant des siècles ont vécu de la même idée, respiré sous le
même ciel, pleuré sur la même terre, prié le même dieu. Otez à ces
peuples la pensée commune qui les sustente et le temps pendant
lequel ils s'en sont nourris, et il n'y a pas de raison pour qu'un Turc
ne soit un Anglais, qu'un Français ne soit un Chinois. Les nations
sont filles du temps et de la communauté de souvenirs. C'est par les
souvenirs que vivent les peuples, et qu'ils nourrissent l'amour de leur
indépendance. C'est contre les souvenirs que se brisent les
conquérants et les despotes; c'est à rompre cette chaîne de la
pensée nationale que tendent leurs efforts, et c'est à sa résistance
que nous devons la gloire de l'humanité. On n'emporte pas la patrie
sous la semelle de ses souliers, a dit Danton: ce mot est admirable
de vérité. Non, on n'emporte pas la patrie! La patrie n'est ni dans la
richesse, ni dans la puissance, ni dans les abstractions des
philosophes. Elle est dans les lieux qui vous ont vu naître, dans la
chaumière où vous avez été bercé, dans le ruisseau qui serpente au
bas de la colline, dans le chant maternel. Elle est dans ces ineffables
souvenirs des premiers jours de la vie qui se gravent en vous,
s'attachent en vous, se font chair, se font os, grandissent et meurent
avec vous, et vous suivent depuis l'échafaud jusque sur le trône du
monde. L'esprit humain peut s'étendre, parcourir l'immensité de
l'espace, aller s'asseoir à côté même de Dieu; l'individu ne pourra
jamais quitter le coin de terre où il essaya ses premiers pas, où il
versa ses premières larmes, car il y tient par le fil des souvenirs.
Homme! par ta pensée, tu peux être le citoyen du monde; par tes
souvenirs, tu n'es qu'un faible roseau qui ne saurait vivre loin des
bords qui baignent tes racines. O Providence, que tu es belle!
La raison ne se laisse borner ni par une pierre, ni par un poteau;
elle s'indigne de tout ce qui est mal, du knout dont on frappe le
Russe, comme de l'oppression de l'esclave indien, sous la main
républicaine de l'épicier de l'Amérique. Les souvenirs, au contraire,
sont arrêtés par toute chose, par une haie, par un fossé; ils tiennent
à une feuille, à un arbre; ils s'épandent autour de vous, se
multiplient en mille rameaux, s'impriment sur tous les objets. C'est le
fauteuil de votre aïeul, c'est la grande allée du château, c'est la
mousse qui croît sur un vieux mur, c'est un baiser de mon amie
d'enfance. L'humanité est une par la raison, elle est multiple par les
souvenirs; la science est une, parce qu'elle est fille de la raison; mais
la poésie est variée comme la nature, parce qu'elle naît dans le cœur
de l'homme doux, berceau des souvenirs; la poésie est intraduisible,
car elle est l'expression intime de l'individualité; mais une vérité
mathématique est à Paris ce qu'elle est à Philadelphie.
En tout temps et en tout lieu, qu'est-ce que l'aristocratie? des
souvenirs que se transmettent cinq ou six générations de familles;
qu'est-ce qu'une famille? encore des souvenirs. Aussi la puissance
destructive de la révolution fut-elle obligée de s'arrêter devant les
souvenirs; elle a pu enlever à la noblesse sa prépondérance
politique, mais il lui a été impossible d'anéantir l'aristocratie: il aurait
fallu effacer l'histoire de France. Jamais le Portugais ne voudrait faire
partie de la monarchie espagnole; aucune réforme politique ou
religieuse n'éteindra la haine que les Irlandais portent à leurs
conquérants; et le gouvernement autrichien serait aussi libéral qu'il
est cruel et oppresseur, que l'Italie n'en serait pas moins son plus
implacable ennemi. C'est que les souvenirs sont une source
intarissable dans laquelle les peuples retrempent leur individualité;
c'est que les souvenirs sont à l'humanité, ce que l'attraction est au
système du monde.
L'attention de l'homme est faible et circonscrite dans sa puissance;
et toutes les sciences sociales ont proclamé que de la division du
travail, dépendait la perfection dans les arts et la richesse des
nations. Si la pensée humaine se divise en facultés ayant chacune sa
sphère d'action, si dans la société chaque individu se voue à une
industrie particulière, dans l'humanité chaque peuple a sa mission et
sa spécialité dans l'œuvre du progrès. L'intelligence se divise en
deux grandes parties: celle de la conception, et de la réalisation.
Passer du monde de l'abstraction à celui de la réalisation, traverser
ces Thermopyles de la raison, détacher l'idée du vague qui
l'enveloppe, la dépouiller de tout caractère dogmatique, et la réaliser
sans secousses et sans orages, c'est l'œuvre de l'artiste, c'est toute
la civilisation. Certains hommes sont propres à la conception,
certains autres à la réalisation; rarement la même tête réunit ces
deux avantages: il en est de même parmi les peuples.
La Grèce, par exemple, fut dans la haute antiquité la nation
réalisatrice par excellence. C'est dans son sein que naquirent les plus
grandes vérités sociales; elle les couva avec amour et les livra à
l'humanité, belles et puissantes. La Grèce ne créa presque rien; elle
reçut de l'Asie le germe de toutes choses. Mais il fallait à ce germe,
pour fructifier, l'intelligence des peuples helléniques. Ce ne sont pas
les bataillons d'Alexandre qui ont conquis l'Asie, c'est l'esprit de la
Grèce; c'est lui qui brisa la tiare du grand roi. Rome succéda à la
Grèce, dans la propagande sociale. Celle-ci expirait sous le
despotisme des rois macédoniens. Rome prit dans sa main toute la
civilisation antique, et y grava son image. Les républiques de la
Grèce étaient intelligentes, mais leur moralité était partielle et locale.
Rome résuma dans sa puissante synthèse ces fractions de vérités,
dont elle tira ce droit italique qui, mis au bout de son épée, devint la
loi du monde. Enfin, un cri de l'humanité souffrante enfanta le
christianisme qui, déchirant l'enveloppe patricienne du droit romain,
appela toutes les nations à la table d'un seul et vrai Dieu.
Soit qu'on remonte à la race gauloise, soit qu'on s'arrête après
l'assimilation des Francs dans le peuple conquis, ce qui toujours
distingue la nation française, c'est une grande bravoure, une
fastueuse intrépidité, l'amour de la guerre et le mépris de ses
dangers. Vaine, bruyante, pour apaiser sa sensibilité nerveuse et
occuper son excessive mobilité, il faut qu'elle piaffe, qu'elle agisse,
qu'elle brandisse sa grande épée, qu'elle soulève sous ses pas des
tourbillons de poussière, et qu'elle se jette tête baissée dans la
mêlée des combats. Ne lui demandez ni trop de discipline ni trop
d'obéissance; fière, raisonneuse, elle remplit les camps du bruit de
ses paroles, frémit sous la main de ses capitaines et s'échappe des
rangs. Ce ne sont pas les dépouilles de l'ennemi qu'elle cherche dans
les combats; c'est la gloire! Ce ne sont pas des conquêtes qu'elle
veut, mais des trophées! Pour elle, tout n'est pas de vaincre, mais de
vaincre avec honneur, avec éclat; elle méprise les ruses de la guerre,
la science de la conservation; elle aime le courage qui s'immole, la
force qui brise et renverse. Aussi affectionne-t-elle les combats
singuliers, les luttes individuelles, les courses vagabondes, les
guerres aventureuses. Voyez ce fier Gaulois nu jusqu'à la ceinture,
faisant parade de sa large poitrine, montrant ses bras nerveux, se
balançant comme un palmier sur ses hanches saillantes, s'avancer,
ainsi désarmé, contre une forêt de piques romaines? Rien n'est
changé en lui, et trente siècles après il dira à la bataille de Fontenoy:
C'est a vous de tirer les premiers, messieurs les Anglais!
Les guerres entreprises par la France ont un caractère de
générosité naïve qu'on ne rencontre nulle part. Au moindre mot elle
court aux armes, et ne s'inquiète ni du but de la guerre ni de
l'avantage qu'elle en pourra tirer. Il lui suffit qu'il y ait des coups de
lance à donner et des lauriers à cueillir. Il n'y a pas de rivage qu'elle
n'ait franchi, pas un pouce de terre qu'elle n'ait foulé sous ses pas,
et cependant, jamais elle n'a pu conserver une conquête hors du
cercle de sa nationalité. Vingt fois elle fut maîtresse de l'Italie, et
vingt fois elle en a été chassée par un ennemi moins brave et moins
généreux: c'est qu'elle manque de suite dans ses plans; c'est que
ses idées sont rapides comme la foudre, et que sa tête étant le
passage des progrès de l'humanité, elle n'a pas la constance des
peuples retardataires; c'est que trop préoccupée de l'idée générale,
elle néglige le fait particulier. Mais aussi, c'est dans sa moralité que
gît sa véritable puissance. Que lui importent les conquêtes
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like