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

Full Download Java Concepts Compatible with Java 5 6 and 7 6th Edition Cay S. Horstmann PDF DOCX

The document provides information about the 6th edition of 'Java Concepts' by Cay S. Horstmann, which is compatible with Java 5, 6, and 7. It highlights the book's focus on teaching programming principles gradually, reinforcing sound engineering practices, and providing extensive resources for both students and instructors. Additionally, it offers links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

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

Full Download Java Concepts Compatible with Java 5 6 and 7 6th Edition Cay S. Horstmann PDF DOCX

The document provides information about the 6th edition of 'Java Concepts' by Cay S. Horstmann, which is compatible with Java 5, 6, and 7. It highlights the book's focus on teaching programming principles gradually, reinforcing sound engineering practices, and providing extensive resources for both students and instructors. Additionally, it offers links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

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

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Java Concepts Compatible with Java 5 6 and 7 6th


Edition Cay S. Horstmann

_____ Click the link below to download _____


https://ebookfinal.com/download/java-concepts-
compatible-with-java-5-6-and-7-6th-edition-cay-s-
horstmann/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Java Concepts Early Objects 7th Edition Cay S. Horstmann

https://ebookfinal.com/download/java-concepts-early-objects-7th-
edition-cay-s-horstmann/

Big Java 3rd Edition Cay S. Horstmann

https://ebookfinal.com/download/big-java-3rd-edition-cay-s-horstmann/

Core Java 2 Advanced Features 5th Edition Cay S. Horstmann

https://ebookfinal.com/download/core-java-2-advanced-features-5th-
edition-cay-s-horstmann/

Late Early objects Big Java 5th Edition Cay Horstmann

https://ebookfinal.com/download/late-early-objects-big-java-5th-
edition-cay-horstmann/
Beginning Java Java 7 Edition Ivor Horton Ivor Horton

https://ebookfinal.com/download/beginning-java-java-7-edition-ivor-
horton-ivor-horton/

C for Everyone 2nd Edition Cay S. Horstmann

https://ebookfinal.com/download/c-for-everyone-2nd-edition-cay-s-
horstmann/

C for Everyone 1st Edition Cay S. Horstmann

https://ebookfinal.com/download/c-for-everyone-1st-edition-cay-s-
horstmann/

Java EE 7 Development with NetBeans 8 3rd Edition David R.


Heffelfinger

https://ebookfinal.com/download/java-ee-7-development-with-
netbeans-8-3rd-edition-david-r-heffelfinger/

Beginning Java SE 6 Game Programming 3rd Edition Jonathan


S. Harbour

https://ebookfinal.com/download/beginning-java-se-6-game-
programming-3rd-edition-jonathan-s-harbour/
Java Concepts Compatible with Java 5 6 and 7 6th
Edition Cay S. Horstmann Digital Instant Download
Author(s): Cay S. Horstmann
ISBN(s): 9780470509470, 0470509473
Edition: 6
File Details: PDF, 27.80 MB
Year: 2009
Language: english
This online teaching and learning environment
integrates the entire digital textbook with the
most effective instructor and student resources
WRÀWHYHU\OHDUQLQJVW\OH

With WileyPLUS:

‡ Students achieve concept ‡ Instructors personalize and manage


mastery in a rich, their course more effectively with
structured environment assessment, assignments, grade
that’s available 24/7 tracking, and more

‡ manage time better


‡study smarter
‡ save money

From multiple study paths, to self-assessment, to a wealth of interactive


visual and audio resources, WileyPLUS gives you everything you need to
personalize the teaching and learning experience.

» F i n d o u t h ow t o M A K E I T YO U R S »
www.wileyplus.com
ALL THE HELP, RESOURCES, AND PERSONAL SUPPORT
YOU AND YOUR STUDENTS NEED!

2-Minute Tutorials and all Student support from an Collaborate with your colleagues,
of the resources you & your experienced student user find a mentor, attend virtual and live
students need to get started Ask your local representative events, and view resources
www.wileyplus.com/firstday for details! www.WhereFacultyConnect.com

Pre-loaded, ready-to-use Technical Support 24/7 Your WileyPLUS


assignments and presentations FAQs, online chat, Account Manager
www.wiley.com/college/quickstart and phone support Training and implementation support
www.wileyplus.com/support www.wileyplus.com/accountmanager

MAKE IT YOURS!
Java 6 th
edition

Concepts
This page intentionally left blank
6 th
edition

Java
Concepts

Cay Horstmann SAN JOSE STATE UNIVERSITY

JOHN WILEY & SONS, INC.


VICE PRESIDENT AND EXECUTIVE PUBLISHER Donald Fowley
EXECUTIVE EDITOR Beth Lang Golub
EDITORIAL ASSISTANT Michael Berlin
PRODUCTION SERVICES MANAGER Dorothy Sinclair
PRODUCTION EDITOR Janet Foxman
EXECUTIVE MARKETING MANAGER Christopher Ruel
CREATIVE DIRECTOR Harry Nolan
SENIOR DESIGNER Madelyn Lesure
PHOTO EDITOR Lisa Gee
MEDIA EDITOR Lauren Sapira
PRODUCTION SERVICES Cindy Johnson
COVER DESIGNER Howard Grossman
COVER ILLUSTRATION Susan Cyr

This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson
City. The cover was printed by RRD Jefferson City.

This book is printed on acid-free paper. ∞

Copyright © 2010, 2008, 2006, 2003 John Wiley & Sons, Inc. All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc.,
222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com. Requests to the Publisher for per-
mission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street,
Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to
a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return
instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel. Outside
of the United States, please contact your local representative.

Library of Congress Cataloging-in-Publication Data:


Horstmann, Cay S., 1959-
Java concepts : compatible with Java 5, 6, and 7 / Cay Horstmann. — 6th ed.
p. cm.
Includes index.
ISBN 978-0-470-50947-0 (pbk.)
1. Java (Computer program language) 2. Electronic data processing. I. Title.
QA76.73.J38H6754 2010
005.13'3--dc22
2009042603
ISBN 978-0-470-50947-0

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1
PREFACE

This book is an introductory text in computer science, focusing on the principles of


programming and software engineering. Here are its key features:
• Teach objects gradually.
In Chapter 2, students learn how to use objects and classes from the standard
library. Chapter 3 shows the mechanics of implementing classes from a given
specification. Students then use simple objects as they master branches, loops, and
arrays. Object-oriented design starts in Chapter 8. This gradual approach allows
students to use objects throughout their study of the core algorithmic topics,
without teaching bad habits that must be un-learned later.
• Reinforce sound engineering practices.
A focus on test-driven development encourages students to test their programs
systematically. A multitude of useful tips on software quality and common errors
encourage the development of good programming habits.
• Help students with guidance and worked examples.
Beginning programmers often ask “How do I start? Now what do I do?” Of
course, an activity as complex as programming cannot be reduced to cookbook-
style instructions. However, step-by-step guidance is immensely helpful for
building confidence and providing an outline for the task at hand. The book con-
tains a large number of “How To” guides for common tasks, with pointers to
additional worked examples on the Web.
• Focus on the essentials while being technically accurate.
An encyclopedic coverage is not helpful for a beginning programmer, but neither
is the opposite—reducing the material to a list of simplistic bullet points that give
an illusion of knowledge. In this book, the essentials of each subject are presented
in digestible chunks, with separate notes that go deeper into good practices or lan-
guage features when the reader is ready for the additional information.
• Use standard Java.
The book teaches the standard Java language—not a specialized “training
wheels” environment. The Java language, library, and tools are presented at a
depth that is sufficient to solve real-world programming problems.
• Provide an optional graphics track.
Graphical shapes are splendid examples of objects. Many students enjoy writing
programs that create drawings or use graphical user interfaces. If desired, these
topics can be integrated into the course by using the materials at the end of
Chapters 2, 3, 9, and 10.

vii
viii Preface

New in This Edition


This is the fourth edition of Big Java, and the book has once again been carefully
revised and updated. The new and improved features include:

More Help for Beginning Programmers


• The How To sections have been updated and expanded, and four new ones have
been added. Fifteen new Worked Examples (on the companion web site and in
WileyPLUS) walk students through the steps required for solving complex and
interesting problems.
• The treatment of algorithm design, planning, and the use of pseudocode has been
enhanced. Students learn to use pseudocode to define the solution algorithm in
Chapter 1.
• Chapters have been revised to focus each section on a specific learning objective.
These learning objectives also organize the chapter summary to help students
assess their progress.

Annotated Examples
• Syntax diagrams now call out features of typical example code to draw student
attention to the key elements of the syntax. Additional annotations point out
special cases, common errors, and good practice associated with the syntax.
• New example tables clearly present a variety of typical and special cases in a
compact format. Each example is accompanied by a brief note explaining the
usage shown and the values that result from it.
• The gradual introduction of objects has been further improved by providing
additional examples and insights in the early chapters.

Updated for Java 7


• Features introduced in Java 7 are covered as Special Topics so that students can
prepare for them. In this edition, we use Java 5 or 6 for the main discussion.

More Opportunities for Practice


• The test bank has been greatly expanded and improved. (See page xi.)
• A new set of lab assignments enables students to practice solving complex
problems one step at a time.
• The LabRat code evaluation feature, enhanced for this edition, gives students
instant feedback on their programming assignments. (See page xvi.)
Preface ix

A Tour of the Book


The book can be naturally grouped into four parts, as illustrated by Figure 1. The
organization of chapters offers the same flexibility as the previous edition; depen-
dencies among the chapters are also shown in the figure.

Part A: Fundamentals (Chapters 1–7)


Chapter 1 contains a brief introduction to computer science and Java programming.
Chapter 2 shows how to manipulate objects of predefined classes. In Chapter 3,
you will build your own simple classes from given specifications.
Fundamental data types, branches, loops, and arrays are covered in Chapters 4–7.

Part B: Object-Oriented Design (Chapters 8–12)


Chapter 8 takes up the subject of class design in a systematic fashion, and it intro-
duces a very simple subset of the UML notation.
The discussion of polymorphism and inheritance is split into two chapters. Chap-
ter 9 covers interfaces and polymorphism, whereas Chapter 10 covers inheritance.
Introducing interfaces before inheritance pays off in an important way: Students
immediately see polymorphism before getting bogged down with technical details
such as superclass construction.
Exception handling and basic file input/output are covered in Chapter 11. The
exception hierarchy gives a useful example for inheritance.
Chapter 12 contains an introduction to object-oriented design, including two
significant case studies.

Part C: Data Structures and Algorithms (Chapters 13–15)


Chapters 13 through 15 contain an introduction to algorithms and basic data struc-
tures, covering recursion, sorting and searching, and linked lists, stacks, and queues.
These topics can be covered as desired after Chapter 7 (see Figure 1).
Recursion is introduced from an object-oriented point of view: An object that
solves a problem recursively constructs another object of the same class that solves
a simpler problem. The idea of having the other object do the simpler job is more
intuitive than having a function call itself.
Chapter 14 covers the fundamental sorting algorithms and gives a gentle intro-
duction to big-Oh analysis. Chapter 15 introduces linked lists, stacks, and queues,
both as abstract data types and as they appear in the standard Java library.

Part D: Advanced Topics (Chapters 16–18)


Chapter 16 covers advanced data structures: hash tables, binary search trees, and
heaps. Chapter 17 introduces Java generics. This chapter is suitable for advanced
students who want to implement their own generic classes and methods. Chapter 18
completes the graphics track coverage of user interfaces with a discussion of layout
management and Swing components. These chapters are available on the Web at
www.wiley.com/college/horstmann , or in the WileyPLUS course for this book.
x Preface

Fundamentals
Object-Oriented Design
Data Structures & Algorithms
Advanced Topics
1. Introduction
WileyPLUS / Web

2. Using Objects

3. Implementing
Classes

4. Fundamental
Data Types

5. Decisions

6. Iteration
7. Arrrays and
Array Lists
8. Designing
Classes

9. Interfaces and
Polymorphism

18. Graphical
10. Inheritance
User Interfaces

11. Input/Output
and Exception
Handling

12. Object-
13. Recursion
Oriented Design

14. Sorting
and Searching

17. Generic 15. Intro to


Programming Data Structures

16. Advanced
Data Structures

Figure 1 Chapter Dependencies


Preface xi

Appendices
Appendix A lists character escape sequences and the Basic Latin and Latin-1 subsets
of Unicode. Appendices B and C summarize Java reserved words and operators.
Appendix D documents all of the library methods and classes used in this book.
In addition, Appendices E–L are available on the Web and contain quick refer-
ences on Java syntax, HTML, Java tools, binary numbers, and UML.
Appendix L contains a style guide for use with this book. Many instructors find
it highly beneficial to require a consistent style for all assignments. If this style
guide conflicts with instructor sentiment or local customs, however, it is available in
electronic form so that it can be modified.

Web Resources
This book is complemented by a complete suite of online resources and a robust
WileyPLUS course.
Go to www.wiley.com/college/horstmann to visit the online companion site, which
includes
• Source code for all examples in the book.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Laboratory exercises (and solutions for instructors only).
• Lecture presentation slides (in HTML and PowerPoint formats).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only).

WileyPLUS is an online teaching and learning environment that integrates the


digital textbook with instructor and student resources. See page xvi for details.

Media Resources
• Worked Example How Many Days Have You Been Alive?
Web resources are summarized at • Worked Example Working with Pictures
chapter end for easy reference. • Lab Exercises
www.wiley.com/ Animation Variable Initialization and Assignment
college/
Animation Parameter Passing
horstmann
Animation Object References
Practice Quiz
Code Completion Exercises

Pointers in the book


describe what students
Worked Writing an Algorithm for Tiling a Floor
will find on the Web. Example 1.1
This Worked Example shows how to develop an algorithm for laying tile in
an alternating pattern of colors.

Special Topic 5.3


Enumeration Types
Special Topic 5.3 introduces enumeration types—types that an hold one of a finite number of
values. An example of an enumeration type is a type FilingStatus with values SINGLE and
MARRIED. This is safer than using integer values, as we did in the TaxReturn class.
xii Walkthrough

A Walkthrough of the Learning Aids


The pedagogical elements in this book work together to make the book accessible
to beginners as well as those learning Java as a second language.

2.3 The Assignment Operator 39

Throughout each chapter, 2.3 The Assignment Operator


margin notes show where Use the assignment
operator (=) to
You can change the value of a variable with the assignment operator (=). For exam-
ple, consider the variable declaration
new concepts are introduced change the value
of a variable. int width = 10; 1

and provide an outline of key ideas. If you want to change the value of the variable, simply assign the new value:
width = 20; 2
The assignment replaces the original value of the variable (see Figure 1).

1
width = 10

Figure 1
Assigning a New 2 20
width =
Value to a Variable

It is an error to use a variable that has never had a value assigned to it. For exam-
ple, the following assignment statement has an error:
int height;
width = height; // ERROR—uninitialized variable height
The compiler will complain about an “uninitialized variable” when you use a vari-
able that has never been assigned a value. (See Figure 2.)

Figure 2
An Uninitialized
Annotated syntax boxes Variable height =
No value has been assigned.

provide a quick, visual overview


of new language constructs. Syntax 2.2 Assignment

Syntax variableName = value;

Example
double width = 20;
This is a variable declaration. .
. This is an assignment statement.
width = 30;
Annotations explain The value of this variable is changed.
. The new value of the variable
required components .
.
and point to more information width = width + 10;

on common errors or best practices The same name


associated with the syntax. can occur on both sides.
See Figure 3.

Summary of Learning Objectives


Explain the flow of execution in a loop.
• A while statement executes a block of code repeatedly. A condition controls for how
long the loop is executed. Each section corresponds to a
• An off-by-one error is a common error when programming loops. Think through
simple test cases to avoid this type of error. learning objective, summarized at
Use for loops to implement counting loops. chapter end, giving students
• You use a for loop when a variable runs from a starting to an ending value with a
constant increment or decrement. a roadmap for assessing what they
• Make a choice between symmetric and asymmetric loop bounds.
know and what they need to review.
• Count the number of iterations to check that your for loop is correct.
Implement loops that process a data set until a sentinel value is encountered.
• Sometimes, the termination condition of a loop can only be evaluated in the middle
of a loop. You can introduce a Boolean variable to control such a loop.
Use nested loops to implement multiple levels of iterations.
• When the body of a loop contains another loop, the loops are nested. A typical use
of nested loops is printing a table with rows and columns.
Walkthrough xiii

HOW TO 1.1 Developing and Describing an Algorithm


How To guides give step-by-step
This is the first of many “How To” sections in this book that give you step-by-step proce-
dures for carrying out important tasks in developing computer programs. guidance for common programming
Before you are ready to write a program in Java, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in tasks, emphasizing planning and
pseudocode: a sequence of precise steps formulated in English.
For example, consider this problem: You have the choice of buying two cars. One is more testing. They answer the beginner’s
fuel efficient than the other, but also more expensive. You know the price and fuel efficiency
(in miles per gallon, mpg) of both cars. You plan to keep the car for ten years. Assume a price question, “Now what do I do?” and
of $4 per gallon of gas and usage of 15,000 miles per year. You will pay cash for the car and
not worry about financing costs. Which car is the better deal? integrate key concepts into a
Step 1 Determine the inputs and outputs. problem-solving sequence.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car.
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car.

We simply want to know which car is the better buy. That is the desired output.
Step 2 Break down the problem into smaller tasks.
For each car, we need to know the total cost of driving it. Let’s do this computation sepa-
rately for each car. Once we have the total cost for each car, we can decide which car is the
better deal.
The total cost for each car is purchase price + operating cost.
We assume a constant usage and gas price for ten years, so the operating cost depends on the
cost of driving the car for one year.
The operating cost is 10 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.
The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons.
Step 3 Describe each subtask in pseudocode.
Worked Examples apply the steps in
In your description, arrange the steps so that any intermediate values are computed before the How To to a different example,
they are needed in other computations. For example, list the step
total cost = purchase price + operating cost
illustrating how they can be used to
after you have computed operating cost. plan, implement, and test a solution
Here is the algorithm for deciding which car to buy.
For each car, compute the total cost as follows:
to another programming problem.
annual fuel consumed = annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
If total cost1 < total cost2
Choose car1.
Else Worked Writing an Algorithm for Tiling a Floor
Choose car2.
Example 1.1
This Worked Example shows how to develop an algorithm for laying tile in
an alternating pattern of colors.

Worked Credit Card Processing


Example 6.1
This Worked Example uses a loop to remove spaces from a credit
card number.

180 Decisions

Table 1 Relational Operator Examples


Expression Value Comment
Example tables support beginners 3 <= 4 true 3 is less than 4; <= tests for “less than or equal”.
with multiple, concrete examples. 3 =< 4 Error The “less than or equal” operator is <=, not =<,
with the “less than” symbol first.
These tables point out common
3 > 4 false > is the opposite of <=.
errors and present another quick
4 < 4 false The left-hand side must be strictly smaller than
reference to the section’s topic. the right-hand side.

4 <= 4 true Both sides are equal; <= tests for “less than or equal”.

3 == 5 - 2 true == tests for equality.

3 != 5 - 1 true != tests for inequality. It is true that 3 is not 5 – 1.

3 = 6 / 2 Error Use == to test for equality.

1.0 / 3.0 == 0.333333333 false Although the values are very close to one
another, they are not exactly equal. See
Common Error 4.3.

"10" > 5 Error You cannot compare a string to a number.

"Tomato".substring(0, 3).equals("Tom") true Always use the equals method to check whether
two strings have the same contents.

"Tomato".substring(0, 3) == ("Tom") false Never use == to compare strings; it only checks


whether the strings are stored in the same
location. See Common Error 5.2 on page 180.

"Tom".equalsIgnoreCase("TOM") true Use the equalsIgnoreCase method if you don’t want to


distinguish between uppercase and lowercase letters.
xiv Walkthrough

1 Initialize counter for (int i = 1; i <= numberOfYears; i++)


{ Progressive figures trace code
double interest = balance * rate / 100;
i = 1 balance = balance + interest; segments to help students visualize
}
the program flow. Color is used
2 Check condition for (int i = 1; i <= numberOfYears; i++)
{
consistently to make variables and
i = 1
double interest = balance * rate / 100;
balance = balance + interest;
other elements easily recognizable.
}

3 Execute loop body for (int i = 1; i <= numberOfYears; i++)


{
double interest = balance * rate / 100; 1 box =
i = 1 balance = balance + interest; Rectangle
g
}
x = 5
y = 10
4 Update counter for (int i = 1; i <= numberOfYears; i++)
width = 20
{
double interest = balance * rate / 100; height = 30
i = 2 balance = balance + interest;
}
2 box =
Rectangle
g
5 Check condition again for (int i = 1; i <= numberOfYears; i++)
box2 =
{ x = 5
double interest = balance * rate / 100; y = 10
i = 2 balance = balance + interest;
width = 20
}
height = 30
Figure 4 Execution of a for Loop

3 box =
Rectangle
g

Students can view animations box2 =


x = 20

of key concepts on the Web. y =


width =
35
20
height = 30

Figure 21 Copying Object References

Now consider the seemingly analogous code with Rectangle objects (see
Figure 21).
Rectangle box = new Rectangle(5, 10, 20, 30); 1
Rectangle box2 = box; 2
A N I M AT I O N
box2.translate(15, 25); 3
Object References
Since box and box2 refer to the same rectangle after step 2 , both variables refer to
the moved rectangle after the call to the translate method.
Self-check exercises at the You need not worry too much about the difference between objects and object
references. Much of the time, you will have the correct intuition when you think of
end of each section are designed “the object box” rather than the technically more accurate “the object reference
stored in box”. The difference between objects and object references only becomes
to make students think through apparent when you have multiple variables that refer to the same object.
the new material—and can
SELF CHECK 25. What is the effect of the assignment String greeting2 = greeting?
spark discussion in lecture. 26. After calling greeting2.toUpperCase(), what are the contents of greeting and
greeting2?

SELF CHECK 4. What is the difference between the following two statements?
final double CM_PER_INCH = 2.54;
and
public static final double CM_PER_INCH = 2.54;
5. What is wrong with the following statement sequence?
double diameter = . . .;
double circumference = 3.14 * diameter;
6.2 for Loops 205

ch06/invest2/Investment.java
1 /**
2 A class to monitor the growth of an investment that
3
4 */
accumulates interest at a fixed annual rate.
Program listings are carefully
5
6
public class Investment
{ designed for easy reading,
7 private double balance;
8 private double rate; going well beyond simple
9 private int years;
10 color coding. Methods are set
11 /**
12
13
Constructs an Investment object from a starting balance and
interest rate.
off by a subtle outline.
14 @param aBalance the starting balance
15 @param aRate the interest rate in percent
16 */
17 public Investment(double aBalance, double aRate)
18 {
19 balance = aBalance;
20 rate = aRate;
21 years = 0;
22 }
23
24 /**
25 Keeps accumulating interest until a target balance has
26 been reached.
27 @param targetBalance the desired balance
28 */
Walkthrough xv

Common Error 7.3


Common Errors describe the kinds
Length and Size
of errors that students often make, Data Type Number of Elements
Unfortunately, the Java syntax for determining
with an explanation of why the errors the number of elements in an array, an array list, Array a.length
and a string is not at all consistent. It is a com-
occur, and what to do about them. mon error to confuse these. You just have to Array list a.size()
remember the correct syntax for every data type. String a.length()

Quality Tip 4.1


Do Not Use Magic Numbers
A magic number is a numeric constant that appears in your code without explanation. For
example, consider the following scary example that actually occurs in the Java library source:
h = 31 * h + ch;
Why 31? The number of days in January? One less than the number of bits in an integer?
Actually, this code computes a “hash code” from a string—a number that is derived from the
Quality Tips explain good characters in such a way that different strings are likely to yield different hash codes. The
value 31 turns out to scramble the character values nicely.
programming practices. A better solution is to use a named constant:
final int HASH_MULTIPLIER = 31;
These notes carefully h = HASH_MULTIPLIER * h + ch;
You should never use magic numbers in your code. Any number that is not completely self-
motivate the reason behind explanatory should be declared as a named constant. Even the most reasonable cosmic con-
stant is going to change one day. You think there are 365 days in a year? Your customers on
the advice, and explain why Mars are going to be pretty unhappy about your silly prejudice. Make a constant

the effort will be repaid later. final int DAYS_PER_YEAR = 365;


By the way, the device
final int THREE_HUNDRED_AND_SIXTY_FIVE = 365;

Productivity Hint 6.1


Hand-Tracing Loops
Arithmetic Operations and
In Programming Tip 5.2, you learned about the method of hand tracing. This method is par-
ticularly effective for understanding how a loop works.
Consider this example loop. What value is displayed?
int n = 1729;
In the following sections, 1 learn how to carry out arithmetic calculations in
you will
int sum = 0;
Productivity Hints teach students how to Java. while (n > 0) 2
{
use their time and tools more effectively. int digit = n % 10;
sum = sum + digit;
3 4 5 6

They encourage students to be more }


n = n / 10;

productive with tips and techniques System.out.println(sum); 7


1. There are three variables: n, sum, and digit. The first two variables are initialized with
such as hand-tracing. 1729 and 0 before the loop is entered.

n sum digit
1729 0

Special Topic 7.2


2. Because n is positive, enter the loop.
ArrayList Syntax Enhancements in Java 7
3. The variable digit is set to 9 (the remainder of dividing 1729 by 10). The variable sum is
set to
Java 7 introduces several 0 + 9 = 9. syntax
convenient n becomes 172.
Finally,enhancements (Recall
for array that
lists.the remainder in the division 1729 /
When you declare 10 andis construct
discarded anbecause
array both arguments
list, you arerepeat
need not integers.). Cross
the type out the old
parameter in values and
the constructor. That write
is, youthe new
can ones under the old ones.
write
ArrayList<String> names = new ArrayList<>();
Special Topics present optional instead of
n
1729
sum
0
digit

topics and provide additional ArrayList<String> names = new ArrayList<String>();


172 9 9

explanation of others. New


features of Java 7 are also
covered in these notes. Random Fact 6.1
The First Bug
According to legend, the first bug was one found in 1947 in the Mark II, a huge electro-
mechanical computer at Harvard University. It really was caused by a bug—a moth was
trapped in a relay switch. Actually, from the note that the operator left in the log book next
to the moth (see the figure), it appears as if the term “bug” had already been in active use at
the time.

Random Facts provide historical and


social information on computing—for
interest and to fulfill the “historical and
social context” requirements of the
ACM/IEEE curriculum guidelines. The First Bug

The pioneering computer scientist Maurice Wilkes wrote: “Somehow, at the Moore
School and afterwards, one had always assumed there would be no particular difficulty in
getting programs right. I can remember the exact instant in time at which it dawned on me
xvi Walkthrough

WileyPLUS
WileyPLUS is an online environment that supports students and instructors. This
book’s WileyPLUS course can complement the printed text or replace it altogether.

For Students Different learning styles, different levels of proficiency, different levels of prepara-
tion—each student is unique. WileyPLUS empowers all students to take advantage
of their individual strengths.
Integrated, multi-media resources—including audio and visual exhibits and demon-
stration problems—encourage active learning and provide multiple study paths to
fit each student’s learning preferences.
• Worked Examples apply the problem-solving steps in the book to another realis-
tic example.
• Screencast Videos present the author explaining the steps he is taking and show-
ing his work as he solves a programming problem.
• Animations of key concepts allow students to replay dynamic explanations that
instructors usually provide on a whiteboard.
Self-assessments are linked to relevant portions of the text. Students can take con-
trol of their own learning and practice until they master the material.
• Practice quizzes can reveal areas where students need to focus.
• Lab exercises can be assigned for self-study or for use in the lab.
• “Code completion” questions enable students to practice programming skills by
filling in small code snippets and getting immediate feedback.
• LabRat provides instant feedback on student solutions to all programming exer-
cises in the book.

For Instructors WileyPLUS includes all of the instructor resources found on the companion site,
and more.
WileyPLUS gives you tools for identifying those students who are falling behind,
allowing you to intervene accordingly, without having to wait for them to come to
office hours.
• Practice quizzes for pre-reading assessment, self-quizzing, or additional practice
can be used as-is or modified for your course needs.
• Multi-step laboratory exercises can be used in lab or assigned for extra student
practice.
WileyPLUS simplifies and automates student performance assessment, making
assignments, and scoring student work.
• An extensive set of multiple-choice questions for quizzing and testing have been
developed to focus on skills, not just terminology.
• “Code completion” questions can also be added to online quizzes.
• LabRat can track student work on all programming exercises in the book, adding
the student solution and a record of completion to the gradebook.
• Solutions to all review and programming exercises are provided..
Walkthrough xvii

With WileyPLUS …

Students can read the book online


and take advantage of searching
and cross-linking.

Instructors can assign drill-and-practice


questions to check that students did
their reading and grasp basic concepts.

Students can practice programming


by filling in small code snippets
and getting immediate feedback.

Students can play and replay


dynamic explanations of
concepts and program flow.

Students can check that their programming


assignments fulfill the specifications.

To order Java Concepts with its WileyPLUS course for your students, use ISBN 978-0-470-57878-0.
xviii Acknowledgments

Acknowledgments
Many thanks to Beth Golub, Lauren Sapira, Andre Legaspi, Don Fowley, Mike
Berlin, Janet Foxman, Lisa Gee, and Bud Peters at John Wiley & Sons, and Vickie
Piercey at Publishing Services for their help with this project. An especially deep
acknowledgment and thanks goes to Cindy Johnson for her hard work, sound
judgment, and amazing attention to detail.
I am grateful to Suzanne Dietrich, Rick Giles, Kathy Liszka, Stephanie Smullen,
Julius Dichter, Patricia McDermott-Wells, and David Woolbright, for their work
on the supplemental material.
Many thanks to the individuals who reviewed the manuscript for this edition,
made valuable suggestions, and brought an embarrassingly large number of errors
and omissions to my attention. They include:

Ian Barland, Radford University


Rick Birney, Arizona State University
Paul Bladek, Edmonds Community College
Robert P. Burton, Brigham Young University
Teresa Cole, Boise State University
Geoffrey Decker, Northern Illinois University
Eman El-Sheikh, University of West Florida
David Freer, Miami Dade College
Ahmad Ghafarian, North Georgia College & State University
Norman Jacobson, University of California, Irvine
Mugdha Khaladkar, New Jersey Institute of Technology
Hong Lin, University of Houston, Downtown
Jeanna Matthews, Clarkson University
Sandeep R. Mitra, State University of New York, Brockport
Parviz Partow-Navid, California State University, Los Angeles
Jim Perry, Ulster County Community College
Kai Qian, Southern Polytechnic State University
Cyndi Rader, Colorado School of Mines
Chaman Lal Sabharwal, Missouri University of Science and Technology
John Santore, Bridgewater State College
Stephanie Smullen, University of Tennessee, Chattanooga
Monica Sweat, Georgia Institute of Technology
Shannon Tauro, University of California, Irvine
Russell Tessier, University of Massachusetts, Amherst
Jonathan L. Tolstedt, North Dakota State University
David Vineyard, Kettering University
Lea Wittie, Bucknell University
Acknowledgments xix

Every new edition builds on the suggestions and experiences of prior reviewers and
users. I am grateful for the invaluable contributions these individuals have made to
this book:

Tim Andersen, Boise State University Elliot Koffman, Temple University


Ivan Bajic, San Diego State University Kathy Liszka, University of Akron
Ted Bangay, Sheridan Institute of Technology Hunter Lloyd, Montana State University
George Basham, Franklin University Youmin Lu, Bloomsburg University
Sambit Bhattacharya, Fayetteville State University John S. Mallozzi, Iona College
Joseph Bowbeer, Vizrea Corporation John Martin, North Dakota State University
Timothy A. Budd, Oregon State University Scott McElfresh, Carnegie Mellon University
Frank Butt, IBM Joan McGrory, Christian Brothers University
Jerry Cain, Stanford University Carolyn Miller, North Carolina State University
Adam Cannon, Columbia University Teng Moh, San Jose State University
Nancy Chase, Gonzaga University John Moore, The Citadel
Archana Chidanandan, Rose-Hulman Institute Faye Navabi, Arizona State University
of Technology Kevin O’Gorman, California Polytechnic State
Vincent Cicirello, The Richard Stockton College University, San Luis Obispo
of New Jersey Michael Olan, Richard Stockton College
Deborah Coleman, Rochester Institute Kevin Parker, Idaho State University
of Technology Cornel Pokorny, California Polytechnic State
Valentino Crespi, California State University, University, San Luis Obispo
Los Angeles Roger Priebe, University of Texas, Austin
Jim Cross, Auburn University C. Robert Putnam, California State University,
Russell Deaton, University of Arkansas Northridge
H. E. Dunsmore, Purdue University Neil Rankin, Worcester Polytechnic Institute
Robert Duvall, Duke University Brad Rippe, Fullerton College
Henry A. Etlinger, Rochester Institute Pedro I. Rivera Vega, University of Puerto Rico,
of Technology Mayaguez
John Fendrich, Bradley University Daniel Rogers, SUNY Brockport
John Fulton, Franklin University Carolyn Schauble, Colorado State University
David Geary, Sabreware, Inc. Christian Shin, SUNY Geneseo
Margaret Geroch, Wheeling Jesuit University Jeffrey Six, University of Delaware
Rick Giles, Acadia University Don Slater, Carnegie Mellon University
Stacey Grasso, College of San Mateo Ken Slonneger, University of Iowa
Jianchao Han, California State University, Peter Stanchev, Kettering University
Dominguez Hills Ron Taylor, Wright State University
Lisa Hansen, Western New England College Joseph Vybihal, McGill University
Elliotte Harold Xiaoming Wei, Iona College
Eileen Head, Binghamton University Todd Whittaker, Franklin University
Cecily Heiner, University of Utah Robert Willhoft, Roberts Wesleyan College
Brian Howard, Depauw University David Womack, University of Texas at
Lubomir Ivanov, Iona College San Antonio
Curt Jones, Bloomsburg University Catherine Wyman, DeVry University
Aaron Keen, California Polytechnic State Arthur Yanushka, Christian Brothers University
University, San Luis Obispo Salih Yurttas, Texas A&M University
This page intentionally left blank
CONTENTS

PREFACE vii
SPECIAL FEATURES xxviii

CHAPTER 1 INTRODUCTION 1
1.1 What Is Programming? 2
1.2 The Anatomy of a Computer 3
1.3 Translating Human-Readable Programs to Machine Code 7
1.4 The Java Programming Language 8
1.5 The Structure of a Simple Program 10
1.6 Compiling and Running a Java Program 14
1.7 Errors 17
1.8 Algorithms 19

CHAPTER 2 USING OBJECTS 31


2.1 Types 32
2.2 Variables 34
2.3 The Assignment Operator 37
2.4 Objects, Classes, and Methods 39
2.5 Method Parameters and Return Values 41
2.6 Constructing Objects 44
2.7 Accessor and Mutator Methods 46
2.8 The API Documentation 47
2.9T Implementing a Test Program 50
2.10 Object References 52
2.11G Graphical Applications and Frame Windows 54
2.12G Drawing on a Component 56
2.13G Ellipses, Lines, Text, and Color 59

CHAPTER 3 IMPLEMENTING CLASSES 73


3.1 Instance Variables 74
3.2 Encapsulation 76
3.3 Specifying the Public Interface of a Class 77
3.4 Commenting the Public Interface 81
3.5 Providing the Class Implementation 84
3.6T Unit Testing 90

xxi
xxii Contents

3.7 Local Variables 92


3.8 Implicit Parameters 94
3.9G Shape Classes 96

CHAPTER 4 FUNDAMENTAL DATA TYPES 115


4.1 Number Types 116
4.2 Constants 118
4.3 Arithmetic Operations and Mathematical Functions 123
4.4 Calling Static Methods 131
4.5 Strings 134
4.6 Reading Input 138

CHAPTER 5 DECISIONS 151


5.1 The if Statement 152
5.2 Comparing Values 156
5.3 Multiple Alternatives 165
5.4 Using Boolean Expressions 173
5.5T Code Coverage 178

CHAPTER 6 ITERATION 193


6.1 while Loops 194
6.2 for Loops 201
6.3 Common Loop Algorithms 210
6.4 Nested Loops 218
6.5 Application: Random Numbers and Simulations 221
6.6T Using a Debugger 223

CHAPTER 7 ARRAYS AND ARRAY LISTS 241


7.1 Arrays 242
7.2 Array Lists 248
7.3 Wrappers and Auto-boxing 254
7.4 The Enhanced for Loop 255
7.5 Partially Filled Arrays 257
7.6 Common Array Algorithms 259
7.7T Regression Testing 271
7.8 Two-Dimensional Arrays 274
Contents xxiii

CHAPTER 8 DESIGNING CLASSES 289


8.1 Discovering Classes 290
8.2 Cohesion and Coupling 291
8.3 Immutable Classes 294
8.4 Side Effects 295
8.5 Preconditions and Postconditions 299
8.6 Static Methods 302
8.7 Static Variables 304
8.8 Scope 307
8.9 Packages 310
8.10T Unit Test Frameworks 316

CHAPTER 9 INTERFACES AND POLYMORPHISM 329


9.1 Using Interfaces for Algorithm Reuse 330
9.2 Converting Between Class and Interface Types 336
9.3 Polymorphism 338
9.4 Using Interfaces for Callbacks 339
9.5 Inner Classes 343
9.6T Mock Objects 345
9.7G Events, Event Sources, and Event Listeners 347
9.8G Using Inner Classes for Listeners 350
9.9G Building Applications with Buttons 352
9.10G Processing Timer Events
9.11G Mouse Events

CHAPTER 10 INHERITANCE 367


10.1 Inheritance Hierarchies 368
10.2 Implementing Subclasses 371
10.3 Overriding Methods 375
10.4 Subclass Construction 378
10.5 Converting Between Subclass and Superclass Types 381
10.6 Polymorphism and Inheritance 383
10.7 Object: The Cosmic Superclass 391
10.8G Using Inheritance to Customize Frames 397
xxiv Contents

CHAPTER 11 INPUT/OUTPUT AND EXCEPTION HANDLING 407


11.1 Reading and Writing Text Files 408
11.2 Reading Text Input 411
11.3 Throwing Exceptions 419
11.4 Checked and Unchecked Exceptions 421
11.5 Catching Exceptions 423
11.6 The finally Clause 426
11.7 Designing Your Own Exception Types 428
11.8 Case Study: A Complete Example 429

CHAPTER 12 OBJECT-ORIENTED DESIGN 441


12.1 The Software Life Cycle 442
12.2 Discovering Classes 446
12.3 Relationships Between Classes 449
12.4 Case Study: Printing an Invoice 452
12.5 Case Study: An Automatic Teller Machine 463

CHAPTER 13 RECURSION 491


13.1 Triangle Numbers 492
13.2 Recursive Helper Methods 500
13.3 The Efficiency of Recursion 502
13.4 Permutations 507
13.5 Mutual Recursions 510

CHAPTER 14 SORTING AND SEARCHING 525


14.1 Selection Sort 526
14.2 Profiling the Selection Sort Algorithm 529
14.3 Analyzing the Performance of the Selection Sort Algorithm 532
14.4 Merge Sort 534
14.5 Analyzing the Merge Sort Algorithm 537
14.6 Searching 540
14.7 Binary Search 542
14.8 Sorting Real Data 545
Contents xxv

CHAPTER 15 AN INTRODUCTION TO DATA STRUCTURES 555


15.1 Using Linked Lists 556
15.2 Implementing Linked Lists 561
15.3 Abstract Data Types 572
15.4 Stacks and Queues 575

CHAPTER 16 ADVANCED DATA STRUCTURES (ADVANCED)

16.1 Sets 666


16.2 Maps 670
16.3 Hash Tables 674
16.4 Computing Hash Codes 681
16.5 Binary Search Trees 686
16.6 Binary Tree Traversal 696
16.7 Priority Queues 698
16.8 Heaps 699
16.9 The Heapsort Algorithm 709

CHAPTER 17 GENERIC PROGRAMMING (ADVANCED)

17.1 Generic Classes and Type Parameters 724


17.2 Implementing Generic Types 725
17.3 Generic Methods 728
17.4 Constraining Type Parameters 730
17.5 Type Erasure 732

CHAPTER 18 GRAPHICAL USER INTERFACES (ADVANCED)

18.1G Processing Text Input 740


18.2G Text Areas 743
18.3G Layout Management 746
18.4G Choices 748
18.5G Menus 758
18.6G Exploring the Swing Documentation 764

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


xxvi Contents

APPENDICES

APPENDIX A THE BASIC LATIN AND LATIN-1 SUBSETS OF UNICODE 589


APPENDIX B JAVA OPERATOR SUMMARY 593
APPENDIX C JAVA RESERVED WORD SUMMARY 595
APPENDIX D THE JAVA LIBRARY 597
APPENDIX E JAVA SYNTAX SUMMARY
APPENDIX F HTML SUMMARY
APPENDIX G TOOL SUMMARY
APPENDIX H JAVADOC SUMMARY
APPENDIX I NUMBER SYSTEMS
APPENDIX J BIT AND SHIFT OPERATIONS
APPENDIX K UML SUMMARY
APPENDIX L JAVA LANGUAGE CODING GUIDELINES

GLOSSARY 629
INDEX 643
ILLUSTRATION CREDITS 665

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


Contents xxvii

ALPHABETICAL LIST OF SYNTAX BOXES


Arrays 245
Array Lists 250
Assertion 301
Assignment 37
Calling a Superclass Constructor 379
Calling a Superclass Method 376
Cast 127
Catching Exceptions 424
Class Declaration 80
Comparisons 158
Constant Declaration 119
Declaring a Generic Class
Declaring a Generic Method
Declaring an Enumeration Type
Declaring an Interface 332
Implementing an Interface 333
Importing a Class from a Package 49
Inheritance 372
Instance Variable Declaration 75
Method Call 12
Method Declaration 86
Object Construction 45
Package Specification 310
Static Method Call 131
The finally Clause 427
The “for each” Loop 256
The for Statement 204
The if Statement 154
The instanceof Operator 382
The throws Clause 423
The while Statement 194
Throwing an Exception 419
Variable Declaration 35
xxviii Special Features

How Tos
Common
Chapter and Worked Quality Tips
Errors
Examples

1 Introduction Omitting Semicolons 13 Developing and Describing


Misspelling Words 19 an Algorithm 22
Writing an Algorithm for
Tiling a Floor

2 Using Objects Confusing Variable How Many Days Have Choose Descriptive
Declaration and Assign- You Been Alive? Names for Variables 36
ment Statements 38 Working with Pictures
Trying to Invoke a
Constructor Like
a Method 45

3 Implementing Declaring a Constructor Implementing a Class 88


Classes as void 81 Making a Simple Menu
Forgetting to Initialize Drawing Graphical
Object References Shapes 100
in a Constructor 93

4 Fundamental Integer Division 128 Carrying Out Do Not Use Magic


Data Types Unbalanced Computations 132 Numbers 122
Parentheses 128 Computing the Volume White Space 129
Roundoff Errors 130 and Surface Area of Factor Out
a Pyramid Common Code 129
Extracting Initials

5 Decisions A Semicolon After the Implementing an if Brace Layout 154


if Condition 156 Statement 163 Avoid Conditions with
Using == to Compare Extracting the Middle Side Effects 162
Strings 160 Calculate Sample Data
The Dangling else Manually 179
Problem 170 Prepare Test Cases
Multiple Relational Ahead of Time 179
Operators 176
Confusing && and ||
Conditions 176

6 Iteration Infinite Loops 200 Writing a Loop 215 Use for Loops for Their
Off-by-One Errors 200 Credit Card Processing Intended Purpose 206
Forgetting a Manipulating the Pixels Don’t Use != to Test
Semicolon 207 in an Image the End of a Range 208
A Semicolon Too Debugging 226 Symmetric and
Many 207 A Sample Debugging Asymmetric Bounds 208
Session Count Iterations 209

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


Special Features xxix

Productivity Special
Random Facts
Hints Topics

Understand the File System 16 Alternative Comment Syntax 13 The ENIAC and the Dawn
Have a Backup Strategy of Computing

Don’t Memorize—Use Testing Classes in an Interactive Mainframes—When Dinosaurs


Online Help 49 Environment Ruled the Earth
Applets The Evolution of the Internet

The javadoc Utility 84 Calling One Constructor Electronic Voting Machines


from Another Computer Graphics

Reading Exception Big Numbers The Pentium Floating-Point


Reports 137 Binary Numbers Bug
Combining Assignment International Alphabets
and Arithmetic
Escape Sequences
Strings and the char Type
Formatting Numbers
Using Dialog Boxes for
Input and Output

Indentation and Tabs 155 The Conditional Operator Artificial Intelligence


Hand-Tracing 171 The switch Statement
Make a Schedule and Make Enumeration Types
Time for Unexpected Lazy Evaluation of Boolean
Problems 172 Operators
De Morgan’s Law
Logging 180

Hand-Tracing Loops 198 do Loops The First Bug 228


Variables Declared
in a for Loop Header
The “Loop and a Half”
Problem
The break and continue
Statements
Loop Invariants

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


xxx Special Features

How Tos
Common
Chapter and Worked Quality Tips
Errors
Examples

7 Arrays and Bounds Errors 245 Working with Arrays Use Arrays for Sequences
Array Lists Uninitialized and and Array Lists 306 of Related Values 246
Unfilled Arrays 246 Rolling the Dice Make Parallel Arrays into
Length and Size 253 A World Population Arrays of Objects 246
Underestimating the Table
Size of a Data Set 259

8 Designing Trying to Modify Primitive Programming with Consistency 293


Classes Type Parameters 296 Packages 315 Minimize Side Effects 298
Shadowing 309 Don’t Change Contents of
Confusing Dots 314 Parameter Variables 298
Minimize the Use of
Static Methods 304
Minimize Variable
Scope 310

9 Interfaces and Forgetting to Declare Investigating Number


Polymorphism Implementing Methods Sequences
as Public 335
Trying to Instantiate
an Interface 337
Modifying Parameter Types
in the Implementing
Method 349
Forgetting to Attach
a Listener 355
By Default, Components
Have Zero Width
and Height 356
Forgetting to Repaint 356

10 Inheritance Confusing Super- and Developing an Inheritance Supply toString in


Subclasses 373 Hierarchy 386 All Classes 395
Shadowing Instance Implementing an Employee Clone Mutable Instance
Variables 374 Hierarchy for Payroll Variables in Accessor
Accidental Processing Methods
Overloading 377
Failing to Invoke the
Superclass Method 378
Overriding Methods to
Be Less Accessible 385
Declaring the equals
Method with the Wrong
Parameter Type 395

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


Special Features xxxi

Productivity Special
Random Facts
Hints Topics

Easy Printing of Arrays and Methods with a Variable An Early Internet Worm
Array Lists 268 Number of Parameters The Therac-25 Incidents
Batch Files and Shell Scripts ArrayList Syntax Enhancements
in Java 7 253
Two-Dimensional Arrays
with Variable Row Lengths
Multidimensional Arrays

Call by Value and Call by The Explosive Growth of


Reference Personal Computers
Class Invariants
Static Imports
Alternative Forms of
Instance and Static
Variable Initialization
Package Access 314

Don’t Use a Container Constants in Interfaces 335 Operating Systems


as a Listener 355 Anonymous Classes Programming Languages
Event Adapters

Abstract Classes Scripting Languages


Final Methods and Classes
Protected Access
Inheritance and the
toString Method
Inheritance and the
equals Method
Implementing the
clone Method
Enumeration Types Revisited
Adding the main Method to
the Frame Class 398

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


xxxii Special Features

How Tos
Common
Chapter and Worked Quality Tips
Errors
Examples

11 Input/Output Backslashes in Processing Text Files 416 Throw Early,


and Exception File Names 410 Analyzing Baby Names Catch Late 425
Handling Constructing a Scanner Do Not Squelch
with a String 410 Exceptions 425
Do Not Use catch and
finally in the Same
try Statement 427
Do Throw Specific
Exceptions 429

12 Object- CRC Cards and UML


Oriented Diagrams 451
Design

13 Recursion Infinite Recursion 495 Thinking Recursively 497


Tracing Through Finding Files
Recursive Methods 496

14 Sorting and The compareTo Method


Searching Can Return Any
Integer, Not Just
–1, 0, and 1 546

15 An Introduc- A Reverse Polish Notation


tion to Data Calculator
Structures

16 Advanced Forgetting to Choosing a Container Use Interface References


Data Provide hashCode Word Frequency to Manipulate Data
Structures
Structures
(Advanced)

17 Generic Genericity and


Programming Inheritance
Using Generic Types
in a Static Context

18 Graphical User Laying Out a User


Interfaces Interface
(Advanced) Implementing a Graphical
User Interface (GUI)

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


Special Features xxxiii

Productivity Special
Random Facts
Hints Topics

Regular Expressions 415 File Dialog Boxes The Ariane Rocket Incident
Reading Web Pages 411
Command Line Arguments
Automatic Resource
Management in Java 7 428

Attributes and Methods in Programmer Productivity


UML Diagrams Software Development—
Multiplicities Art or Science?
Aggregation and Association

The Limits of Computation

Insertion Sort The First Programmer


Oh, Omega, and Theta
The Quicksort Algorithm
The Parameterized
Comparable Interface 547
The Comparator Interface

The Iterable Interface Standardization


and the “For Each” Loop Reverse Polish Notation 578
Static Inner Classes

Enhancements to Collection Software Piracy


Classes in Java 7

Wildcard Types

Use a GUI Builder

Available online in WileyPLUS and at www.wiley.com/college/horstmann.


This page intentionally left blank
Chapter
1
Introduction

CHAPTER GOALS
• To understand the activity of programming
• To learn about the architecture of computers
• To learn about machine code and high-level
programming languages
• To become familiar with the structure of simple
Java programs
• To compile and run your first Java program
• To recognize compile-time and run-time errors
• To write pseudocode for simple algorithms

The purpose of this chapter is to familiarize you with the concepts


of programming and program development. It reviews the architecture of a computer and discusses
the difference between machine code and high-level programming languages. You will see how to
compile and run your first Java program, and how to diagnose errors that may occur when a
program is compiled or executed. Finally, you will learn how to formulate simple algorithms using
pseudocode notation.

1
CHAPTER CONTENTS
1.1 What Is Programming? 2 1.6 Compiling and Running a
Java Program 14
1.2 The Anatomy of a Computer 3
PRODUCTIVITY HINT 1.1: Understand the File System 16
RANDOM FACT 1.1: The ENIAC and the Dawn
PRODUCTIVITY HINT 1.2: Have a Backup Strategy
of Computing
1.7 Errors 17
1.3 Translating Human-Readable Programs
COMMON ERROR 1.2: Misspelling Words 19
to Machine Code 7
1.8 Algorithms 19
1.4 The Java Programming Language 8
HOW TO 1.1: Developing and Describing
1.5 The Structure of a Simple Program 10 an Algorithm 22
SYNTAX 1.1: Method Call 12 WORKED EXAMPLE 1.1: Writing an Algorithm for
COMMON ERROR 1.1: Omitting Semicolons 13 Tiling a Floor
SPECIAL TOPIC 1.1: Alternative Comment Syntax 13

1.1 What Is Programming?


You have probably used a computer for work or fun. Many people use computers
for everyday tasks such as balancing a checkbook or writing a term paper. Comput-
ers are good for such tasks. They can handle repetitive chores, such as totaling up
numbers or placing words on a page, without getting bored or exhausted. Comput-
ers also make good game machines because they can play sequences of sounds and
pictures, involving the human user in the process.
The flexibility of a computer is quite an amazing phenomenon. The same
machine can balance your checkbook, print your term paper, and play a game. In
contrast, other machines carry out a much narrower range of tasks—a car drives
and a toaster toasts.
A computer must be To achieve this flexibility, the computer must be programmed to perform each
programmed to task. A computer itself is a machine that stores data (numbers, words, pictures),
perform tasks. interacts with devices (the monitor screen, the sound system, the printer), and exe-
Different tasks
require different cutes programs. Programs are sequences of instructions and decisions that the com-
programs. puter carries out to achieve a task. One program balances checkbooks; a different
program, perhaps designed and constructed by a different company, processes
A computer program words; and a third program, probably from yet another company, plays a game.
executes a sequence Today’s computer programs are so sophisticated that it is hard to believe that
of very basic they are all composed of extremely primitive instructions. A typical instruction
instructions in
rapid succession. may be one of the following:
• Put a red dot onto this screen position.
• Get a number from this location in memory.
• Add up two numbers.
• If this value is negative, continue the program at that instruction.
A computer program A computer program tells a computer, in minute detail, the sequence of steps that
contains the are needed to complete a task. A program contains a huge number of simple
instruction
sequences for
instructions, and the computer executes them at great speed. The computer has no
all tasks that it intelligence—it simply executes instruction sequences that have been prepared in
can execute. advance.

2
1.2 The Anatomy of a Computer 3

To use a computer, no knowledge of programming is required. When you write a


term paper with a word processor, that computer program has been developed by
the manufacturer and is ready for you to use. That is only to be expected—you can
drive a car without being a mechanic and toast bread without being an electrician.
A primary purpose of this book is to teach you how to design and implement
computer programs. You will learn how to formulate instructions for all tasks that
your programs need to execute.
Keep in mind that programming a sophisticated computer game or word proces-
sor requires a team of many highly skilled programmers, graphic artists, and other
professionals. Your first programming efforts will be more mundane. The concepts
and skills you learn in this book form an important foundation, but you should not
expect to immediately produce professional software. A typical college degree in
computer science or software engineering takes four years to complete; this book is
intended as a text for an introductory course in such a program.
Many students find that there is an immense thrill even in simple programming
tasks. It is an amazing experience to see the computer carry out a task precisely and
quickly that would take you hours of drudgery.

SELF CHECK 1. What is required to play a music CD on a computer?


2. Why is a CD player less flexible than a computer?
3. Can a computer program develop the initiative to execute tasks in a better way
than its programmers envisioned?

1.2 The Anatomy of a Computer


To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. This section will describe
a personal computer. Larger computers have faster, larger, or more powerful com-
ponents, but they have fundamentally the same design.
At the heart of the At the heart of the computer lies the central processing unit (CPU) (see
computer lies the Figure 1). It consists of a single chip (integrated circuit) or a small number of chips.
central processing A computer chip is a component with a plastic or metal housing, metal connectors,
unit (CPU).

Figure 1
Central Processing Unit
4 Chapter 1 Introduction

Figure 2
A Memory Module with
Memory Chips

and inside wiring made principally from silicon. For a CPU chip, the inside wiring
is enormously complicated. For example, the Intel Core processor (a popular CPU
for inexpensive laptops at the time of this writing) contains several hundred million
structural elements called transistors—the elements that enable electrical signals to
control other electrical signals, making automatic computing possible. The CPU
locates and executes the program instructions; it carries out arithmetic operations
such as addition, subtraction, multiplication, and division; and it fetches data from
storage and input/output devices and sends data back.
Data and programs The computer keeps data and programs in storage. There are two kinds of stor-
are stored in primary age. Primary storage, also called random-access memory (RAM) or simply memory,
storage (memory) is fast but expensive; it is made from memory chips (see Figure 2). Primary storage
and secondary
storage (such as a loses all its data when the power is turned off. Secondary storage, usually a hard disk
hard disk). (see Figure 3), provides less expensive storage that persists without electricity. A
hard disk consists of rotating platters, which are coated with a magnetic material,
and read/write heads, which can detect and change the patterns of varying magnetic
flux on the platters.
Some computers are self-contained units, whereas others are interconnected
through networks. Home computers are usually intermittently connected to the
Internet via a dialup or broadband connection. The computers in your computer
lab are probably permanently connected to a local area network. Through the net-
work cabling, the computer can read programs from central storage locations or
send data to other computers. For the user of a networked computer, it may not
even be obvious which data reside on the computer itself and which are transmitted
through the network.
Most computers have removable storage devices that can access data or programs
on media such as memory sticks or optical disks.
To interact with a human user, a computer requires other peripheral devices. The
computer transmits information to the user through a display screen, loudspeakers,
and printers. The user can enter information and directions to the computer by
using a keyboard or a pointing device such as a mouse.
Exploring the Variety of Random
Documents with Different Content
LE PONT-DE-MONTVERT

Ce qui frappa d’abord les regards de Stevenson en arrivant au Pont-de-


Montvert ce fut le temple protestant bâti sur une plate-forme dominant le
bourg. Ce n’était que la nouveauté la plus en évidence de toutes celles
qu’il allait observer. Bien qu’il soit difficile de caractériser exactement ce
qui fait différer le Pont-de-Montvert du Monastier, de Langogne ou du
Bleymard, la différence est indéniable. La place publique, les maisons, les
allées et la rivière limpide qui le traverse dénotent déjà le Midi.
Le dimanche dans les montagnes règne un calme absolu. Ici les rues
et les cafés et cabarets sont pleins d’animation et de bruit. A l’auberge,
Stevenson déjeuna en nombreuse compagnie et de nouveaux
consommateurs arrivaient sans cesse. De ce côté de la Lozère les
paysages avaient un autre aspect et les habitants paraissaient de race
différente. Ils étaient vifs, de figure expressive, le questionnaient et lui
répondaient avec à propos. Sa manière de voyager, loin de les choquer, les
intéressait par son originalité.
Au point de vue plastique, le changement n’était pas moins agréable.
Depuis le Monastier où Stevenson avait vu une jolie femme, une seule, il
n’avait rencontré que des figures sans attraits. Ici, sur trois dames qui
avaient mangé à table avec lui, deux étaient d’une beauté au-dessus de
l’ordinaire. Et Clarisse? Que dire de Clarisse? Elle servait à table d’un air
doux, grave, indifférent, avec de grands yeux noyés de langueur; la
bouche, le nez, les joues étaient d’une pureté de lignes peu ordinaire.
Quel dommage qu’une si belle personne restât dans une auberge de
campagne et n’eût pour admirateurs que des paysans! Stevenson lui
adressa ses compliments qu’elle reçut sans baisser les yeux, comme une
personne habituée aux hommages de tous. L’humoriste ajoute
malicieusement que si Clarisse savait lire l’Anglais il se ferait scrupule de
mentionner que sa taille ne répondait pas à sa figure et qu’elle était faite
comme un échalas, mais qu’elle se formerait peut-être avec le temps.
Le Pont-de-Montvert est célèbre dans l’histoire des Camisards. C’est là
que la guerre débuta. La révocation de l’Edit de Nantes en 1685 fut un
des actes les plus impolitiques et les plus malheureux de Louis XIV. Pour
établir en France l’unité religieuse il ne recula pas devant les mesures les
plus violentes. Les hommes furent envoyés aux galères, les femmes
enfermées dans des couvents ou emprisonnées; mais ni les sévices, ni les
dragonnades, ni les incendies, ni même le gibet et la roue ne purent
ramener les dissidents à l’Eglise catholique. Ce fut alors que dans tous ces
esprits exaspérés se répandit cette espèce de trouble prophétique
constaté chez les hommes, les femmes et les tout petits enfants.
Le principal agent des persécutions était l’abbé du Chayla, inspecteur
des missions et archiprêtre des Cévennes. Il habitait à Saint-Germain-de-
Calberte, mais se rendait de temps à autre au Pont-de-Montvert où il
possédait une maison avec une prison pour les catéchumènes
récalcitrants.
A ce moment, le séjour dans le pays était devenu intolérable pour les
protestants et il était rigoureusement défendu de s’expatrier. Une famille
de six personnes qui tentait de s’enfuir à Genève sous la conduite d’un
guide connaissant bien les sentiers de ces contrées montagneuses, tomba
entre les mains des gens de du Chayla fut emprisonnée et mise aux ceps
dans le cachot du Pont-de-Montvert. Les parents des prisonniers
implorèrent le secours des protestants à une assemblée tenue au bois
d’Altefage sur le Bougès. Le prophète Séguier déclara que le temps de la
soumission était passé, qu’il fallait délivrer les captifs et purger le pays de
tous les prêtres de Baal.
Les paysans, entraînés par les discours de leurs prédicants se réunirent
en armes au nombre de plus de cinquante (Louvreleuil dit 200) et
entrèrent au Pont-de-Montvert à 10 heures du soir en chantant des
psaumes. Ils entourèrent la maison de l’archiprêtre et enfoncèrent la
porte, se servant d’une poutre en guise de bélier. Entrés au rez-de-
chaussée, ils délivrèrent les prisonniers et voulurent aussi s’emparer de du
Chayla et de ses gens réfugiés au premier étage; ceux-ci tirèrent sur eux
et en abattirent un. Alors les assaillants furieux et craignant une sérieuse
résistance mirent le feu à la maison qui fut tout aussitôt en flammes.
L’abbé chercha à s’échapper par une fenêtre, mais en tombant il se cassa
la cuisse. On le découvrit à la lueur de l’incendie, auprès de la haie du
jardin où il avait cherché à se cacher en rampant. Il fut traîné sur la place
du quai et frappé de 52 blessures dont 5 à la tête, 11 au visage, 26 à la
poitrine ou au ventre et 10 au côté ou au dos. 24 des plaies étaient
mortelles.
Je ne veux pas insister sur cette tragédie. J’en ai lu le récit dans quatre
historiens, un prêtre, deux pasteurs et un libre-penseur. A mon avis aucun
n’a gardé dans son œuvre une impartialité complète, mais j’ai le regret de
déclarer que le libre-penseur s’est montré le plus passionné des quatre. Le
Pont-de-Montvert possède un poète, brave ouvrier devenu aveugle par
suite d’un éclat de mine, qui a composé un poème en vingt-cinq chants
redisant l’histoire de cette triste guerre[3]. Il serait hasardeux de prédire à
ce poème les vingt ou trente siècles de durée, de l’Iliade, œuvre d’un
autre aveugle immortel. On y sent pourtant vibrer le sentiment persistant
que ces luttes religieuses ont laissé dans l’âme du peuple. Le vers n’a pas
l’envolée des œuvres de génie, mais on y trouve le reflet de passions que
le temps n’a pas encore tout à fait éteintes. Guerres civiles, guerres
religieuses! ne remuons pas ces cendres brûlantes de crainte d’en voir
jaillir des étincelles.
Séguier et ses montagnards chantèrent toute la nuit des cantiques de
victoire et de mort autour de ce cadavre affreusement mutilé. A l’aube, ils
se rendirent à Frugères dont le curé fut aussi tué d’un coup de fusil. Celui
de Saint-Maurice ne dut son salut qu’à la vitesse de son cheval. A Saint-
André-de-Lancize, curé et maître d’école furent également tués et mutilés.
A la Devèze une famille de six personnes fut impitoyablement immolée
pour avoir refusé de livrer ses armes, et les meurtres étaient
accompagnés de pillage; mais les troupes royales étaient déjà sur les
traces des révoltés. Le Capitaine Poul les surprit à Font-Morte. Séguier et
deux de ses compagnons furent pris, jugés et condamnés. Séguier fut
brûlé vif au Pont-de-Montvert. Les deux autres furent, l’un roué à la
Devèze, et l’autre pendu à Saint-André de l’Ancize.
La maison de du Chayla dont on refit le toit détruit par l’incendie est
encore debout à côté du pont du Rieumalet ayant devant elle le jardin en
terrasse dans lequel il tomba en s’échappant par la fenêtre.
DANS LA VALLÉE DU TARN

Mais revenons à Stevenson et à son ânesse. Les voilà en chemin sur la


nouvelle route qui va du Pont-de-Montvert à Florac par la vallée du Tarn.
Cette route court à mi-côte entre le lit de la rivière et le sommet de la
falaise, s’enfonçant dans des combes à ce moment déjà noyées dans
l’ombre, puis doublant des promontoires éclairés par le soleil à son déclin.
Le Tarn coule en grondant au fond de cette vallée profonde au sommet
de laquelle le frêne pousse parmi les rochers comme le lierre sur des murs
en ruines; mais sur les pentes inférieures, le long du vallon, le châtaignier
dresse partout sa tige robuste couronnée d’un majestueux branchage. Ces
arbres forment les uns comme des allées au bord de la rivière, d’autres
croissent sur les étroites terrasses qui s’élèvent par degrés sur la pente et
d’autres enfin poussent accrochés par les racines aux flancs des
précipices. Stevenson fait de ces arbres magnifiques une intéressante
description.
Il faut, dit-il, avoir contemplé d’une hauteur tous ces monticules de
verdure ou admiré un bouquet de châtaigniers séculaires groupés au haut
d’une colline pour avoir une idée de la puissance féconde de la nature.
J’ajouterai que le châtaignier est un arbre vraiment providentiel pour les
habitants des Cévennes. Il leur fournit libéralement son tronc, comme bois
de charpente et de menuiserie, ses branches et ses racines comme
chauffage, sa ramure pour la nourriture et la litière des animaux
domestiques. De plus une partie de la population se nourrit de châtaignes
fraîches ou séchées pendant presque la moitié de l’année.
Notre Anglais attardé par l’humeur traînarde de Modestine et la beauté
du paysage ne fit pas beaucoup de chemin pendant cette après-midi. Le
soleil avait déjà quitté l’étroite vallée du Tarn. Il fallut chercher une place
pour camper la nuit. Cela n’était pas facile. Les terrasses étaient très
étroites et la pente si rapide que l’on aurait roulé jusqu’à la rivière.
Stevenson aperçut à trente pas au-dessus de la route, une petite plate-
forme à laquelle un tronc d’arbre énorme formait une sorte d’abri et de
parapet. Il y fit monter Modestine avec grand peine et la déchargea. Mais
la place était trop étroite pour deux et il fallut trouver un plateau encore
plus haut pour y attacher l’ânesse. Après lui avoir donné sa ration de pain
et d’avoine avec un supplément de feuilles fraîches de châtaignier, le
voyageur redescendit à son campement. Des chars passèrent sur la route.
Redoutant les visites et les regards indiscrets, il se tint caché derrière son
tronc protecteur tant que la nuit ne fut pas venue. Il mangea à la hâte,
l’œil au guet et à moitié couché, pour qu’on ne put le voir. Ce camp était
bien différent de celui de la nuit précédente dans la paisible et fraîche
clairière du bois de pins. L’air était chaud et lourd. Le tremolo des
grenouilles résonnait au bord de la rivière avant même le coucher du
soleil. Quand la nuit fut tout à fait venue, de légers frémissements
passaient dans les feuilles sèches, des bruits d’insectes se faisaient
entendre et parfois des formes indistinctes semblaient se glisser entre les
châtaigniers. Des milliers de grosses fourmis couraient sur le sol; des
chauves-souris passaient rapidement et un essaim de moustiques
bourdonnaient en l’air.
Stevenson resta longtemps sans pouvoir dormir et, juste au moment
où le sommeil s’emparait de lui, un bruit sous sa tête le réveilla
brusquement. C’était comme un grattage d’ongles venant de dessous le
havresac qui lui servait d’oreiller et qui se répéta trois fois avant qu’il eût
le temps de se relever et de retourner le havresac. Il ne vit ni n’entendit
plus rien que le chant des grenouilles et le clapotis de la rivière. Le
lendemain on lui dit que les châtaigneraies étaient infestées de rats et
tous les bruits qui l’avaient alarmé provenaient probablement de ces
rongeurs; mais à cette heure et dans ce lieu, le trouble qu’il éprouva le
tint longtemps privé de sommeil.
Il fut réveillé le lundi 30 septembre à la pointe du jour par un bruit de
pas sur les cailloux, non loin de son refuge. C’était un paysan suivant au
milieu des arbres un sentier que Stevenson n’avait pas remarqué la veille.
Ce paysan passa sans regarder ni à droite ni à gauche et disparut
heureusement sans apercevoir le voyageur, mais il était grand temps de
décamper. Il était monté pour donner l’avoine à Modestine et redescendait
à la hâte lorsqu’il vit arriver un homme et un enfant auprès de sa
couchette défaite. Après un moment de silence l’homme lui dit: Vous avez
couché là?
—Oui, comme vous voyez.
—Et pourquoi?
—Ma foi! parce que j’étais fatigué, répondit Stevenson, d’un air
dégagé. L’homme lui demanda où il allait et comment il avait soupé. Puis il
ajouta d’un ton brusque: «C’est bien, allez-vous-en» et il s’éloigna à
quelque distance pour émonder un châtaignier. Stevenson peu satisfait du
gîte le quitta sans laisser de monnaie pour en acquitter le prix et descendit
sur la route en grignotant une tablette de chocolat. A cette heure matinale
la vallée était ravissante.
Bientôt la route côtoya le bord de la rivière et l’Anglais voulut faire sa
toilette du matin dans l’eau du Tarn merveilleuse de limpidité et de
fraîcheur. Se laver dans l’eau d’une rivière du bon Dieu, en plein air, c’était
à ses yeux une sorte de rite lustral et un acte d’adoration demi-païen.
Sans doute un cabinet de toilette est commode pour les ablutions, mais
cela ne dit rien à l’imagination. Stevenson ainsi rafraîchi reprit son chemin
le cœur joyeux, chantant des cantiques au Dieu invisible qui entend tout.
Il rencontra soudain une vieille femme qui lui demanda l’aumône. —
Bon, se dit-il, voici la servante qui me présente la note de mon coucher, et
il paya sans observations.
Un peu plus loin il fut rejoint par un vieillard coiffé d’un bonnet brun,
suivi d’une petite fille qui conduisait deux brebis et une chèvre. Ce brave
homme, au regard bon et intelligent sous ses traits ridés, entra en
conversation avec lui et, trompé par une réponse ambiguë de son
interlocuteur, lui déclara qu’il était méthodiste. Stevenson, touché de sa
candeur et de sa foi, s’entretint avec lui comme un fidèle coreligionnaire.
A la Vernède, hameau des bords du Tarn où il demeurait, ce bon
vieillard le mena à l’auberge et recommanda qu’on le fit bien déjeuner. Le
voyageur se loue grandement de ses bons offices ainsi que de l’accueil
bienveillant des habitants de cet endroit (tous protestants, assure-t-il).
Au-delà de la Vernède, la vallée devient de plus en plus pittoresque. Ici
ce sont des falaises rapprochées et croulant dans la rivière; plus loin des
collines élargies et couvertes de verdure. La route passe sous le vieux
château de Miral, juché sur un escarpement. Puis, c’est l’ancien Monastère
de Bedouès, aujourd’hui église et presbytère; ensuite le village de Cocurès
entouré de vignes, de vergers et de prairies. On était alors en train de
gauler les noix sur les bords de la route et de les ramasser dans des
paniers.
La vallée s’élargit là de plus en plus, mais les parties hautes des
collines sont escarpées et nues et le Tarn coule toujours bruyant dans un
lit de pierres arrondies. La température était encore très douce, pourtant
l’automne avait déjà teinté de reflets jaunes le feuillage des châtaigniers
et des peupliers. Ce pays dont des récits exagérés lui avaient fait un
tableau effrayant, Stevenson le trouvait sauvage, mais non sans attrait.
FLORAC

Nous voici à Florac, modeste sous-préfecture qui joua jadis un rôle


important pendant la guerre des Camisards. Florac, situé dans un riant
vallon, au fond d’un amphithéâtre de montagnes escarpées, possède un
vieux château transformé en prison, une esplanade centrale, ombragée de
beaux platanes, de vieilles maisons et des ruelles curieuses. Au flanc de la
montagne qui couronne la ville s’épanche la magnifique source du Pêcher
qui, en hiver, forme presque une rivière.
A Florac, observe Stevenson, les femmes sont d’une beauté
remarquable. Je ne me permettrai pas de contredire cette flatteuse
assertion.
Après déjeuner, l’Anglais fut mené au Café attenant à l’hôtel et son
voyage fut le sujet général de la conversation pendant l’après-midi.
Chacun lui donnait son avis au sujet de la direction qu’il aurait à suivre.
On alla même chercher la carte de la Sous-Préfecture pour lui faire voir le
pays à parcourir. Beaucoup de ces conseillers bénévoles étaient
protestants et Stevenson remarqua que protestants et catholiques vivaient
là ensemble en bonne harmonie.
Vers le soir un pasteur jeune encore vint le voir. «La population de
Florac, lui dit-il, est en partie protestante, en partie catholique et la
différence des croyances religieuses se double ordinairement de celle des
opinions politiques; malgré cela les gens vivent en excellents termes, se
fréquentent et se rendent service, en bons voisins.» Stevenson qui avait
été témoin des discordes du Monastier fut tout étonné de voir régner ici le
calme et la concorde. Il fut heureux de trouver cet état d’esprit dans un
coin des Cévennes où la guerre religieuse avait jadis exercé ses ravages.
DANS LA VALLÉE DE LA MIMENTE

Notre voyageur coucha à Florac et se remit en route le lendemain,


mardi 1er octobre, assez tard dans l’après-midi. Remontant un peu le
Tarnon il le franchit sur un pont couvert et entra dans la vallée de la
Mimente, affluent de cette rivière.
Des hauteurs escarpées et hérissées de rochers dominent le cours de
la Mimente; de grands chênes et des châtaigniers croissent sur les pentes
et les terrasses soutenues par des murs en pierre sèche. D’espace en
espace, des champs de sarrasin et des pommiers couverts de fruits
apparaissaient autour des hameaux aux toits d’ardoise et le vieux château
de Montvaillant dressait ses murs à mâchicoulis sur la croupe d’un
promontoire.
Bientôt le soleil disparut sur la crête des montagnes et les sons des
cors des bergers ramenant leurs troupeaux à l’étable retentirent dans la
vallée. Le voyageur dut se préoccuper de trouver une place pour camper
la nuit. Sous les arbres le sol était très en pente et couvert de pierres
roulantes; et dans les endroits découverts, des précipices hérissés de
broussailles s’étendaient jusqu’au bord de l’eau. Il aperçut enfin un coin
de pré au-dessous de la route, à un coude de la rivière. Il y descendit,
attacha Modestine à un arbre et explora les environs.
L’ombre avait envahi le vallon et l’on ne distinguait que vaguement les
objets les plus rapprochés.
Stevenson alla vers un grand chêne qui se trouvait presque au bord de
la rivière et bien qu’il aperçut une maison en face, de l’autre côté de l’eau,
il s’installa dans un enfoncement au pied du chêne pour y passer la nuit.
Quand il eut préparé son sac, donné à manger à Modestine et pris lui-
même son repas, la nuit était complète et le ciel tout illuminé d’étoiles.
Celui-là, dit notre héros, ne se doute pas de la beauté d’un pareil
spectacle qui n’a pas passé une nuit à la belle étoile. Les plus grands
poètes y ont puisé de sublimes inspirations. Un vent assez fort soufflait
sur les hauteurs et cependant cette première nuit d’octobre n’était pas
plus fraîche qu’une nuit de mai. Le sommeil de Stevenson fut plusieurs
fois troublé par les aboiements d’un chien, ce qui l’amène à déclarer que
pour un vagabond comme lui cet animal représente le monde bourgeois
par son côté le plus détestable et qu’il redoute moins un loup qu’un chien
de garde.
Le lendemain matin, mercredi 2 octobre, il fut réveillé par le même
chien qui était accouru en jappant jusque sur l’autre bord de l’eau et qui
en le voyant se mettre sur son séant s’éloigna en grondant. Le ciel était
déjà teinté de cette belle couleur gris-bleu qui précède l’aurore. La
silhouette des arbres de la montagne se détachait très nettement sur le
fond azuré du firmament. Stevenson se leva, rechargea ses hardes sur le
bât de Modestine et reprit le chemin qui remonte la Mimente. Tout le flanc
de la montagne était déjà doré par le soleil dont le disque apparut enfin,
flottant dans l’azur, dans une échancrure de la crête qui domine à l’Est. Ce
fut la quatrième et dernière nuit que notre héros passa en plein air
pendant ce voyage.
LE CŒUR DE CÉVENNES

Stevenson contempla en passant les ruines du vieux château de Saint-


Julien-d’Arpaon; il continua à suivre la route qui longe la Mimente sur la
rive gauche et franchit la rivière pour suivre la rive droite un peu avant le
hameau des Crozes. Cette route se relève peu à peu sur le flanc de la
montagne jusqu’au village de Cassagnas, agglomération de maisons
entourées de châtaigniers qui s’est fait une notoriété dans l’histoire des
Camisards.
Un de leurs arsenaux était caché non loin de là dans des cavernes de
la montagne. C’était là que la troupe de Séguier et de Salomon Couderc
avait ses provisions de vêtements, de vivres, d’armes et de munitions, là
qu’ils étaient parvenus à fabriquer de la poudre et des balles. Les blessés
y étaient aussi amenés et secrètement soignés par des femmes des
environs.
Les habitants de Cassagnas parurent intelligents et d’humeur sociable
à Stevenson. Sa qualité de protestant lui valut un bon accueil parmi cette
population entièrement calviniste, et la connaissance de l’histoire locale
dont il eut l’occasion de faire preuve lui attira la considération des fortes
têtes de l’endroit. Il dîna à l’auberge avec un gendarme et un colporteur
tous deux étrangers et catholiques. Il y eut à table une sorte de
controverse religieuse assez courtoise de part et d’autre. Le marchand
n’était pas du même avis que l’Anglais au point de vue historique et il
s’échauffa un peu dans la discussion; mais le gendarme l’approuva
pleinement. «Que chacun vive dans la religion de ses pères, dit-il
sentencieusement», et tout le monde se rangea à cette opinion.
Ce n’était pas l’avis du curé et du commandant de N.-D. des Neiges;
mais les gens de ce pays sont d’une race différente.
Le colporteur s’intéressa fort au récit du voyage de Stevenson. Il
observa que coucher dehors exposé aux loups et aux rôdeurs de nuit était
dangereux. Ce fut la seule personne qui trouva téméraire une chose si
simple. Beaucoup, il est vrai, n’en voyaient pas la nécessité; mais par
contre, le méthodiste de la Vernède s’était écrié que c’était admirable de
dormir ainsi à la lueur des étoiles, sous l’œil du Seigneur.
Stevenson repartit de là vers les deux heures. Abandonnant la route
107bis il traversa la Mimente et prit un sentier raboteux qui s’élevait sur
l’autre versant de la montagne couvert de pierres roulantes et de touffes
de broussailles. Sur le sommet du mont, il n’y avait plus trace de sentier et
Stevenson dut s’avancer au hasard sur le plateau pour retrouver son
chemin.
Cette crête forme la ligne de séparation des eaux de deux vastes
bassins. Au Nord, les cours d’eau s’écoulent dans la Garonne et l’Océan
Atlantique; au Midi, elles vont dans le bassin du Rhône.
On peut, dit notre voyageur, considérer cette montagne comme le
centre, le cœur du pays des Camisards. De leurs cinq légions, quatre
campaient dans un rayon de quelques lieues, deux au Nord, deux au Sud
et quand l’œuvre de dévastation accomplie par Julien dans les hautes
Cévennes, en octobre et novembre 1703 fut terminée, quand la pioche, la
hache et l’incendie eurent détruit les 199 villages ou hameaux des 32
paroisses environnantes, toute vie sembla s’être retirée de ce pays désolé.
Heureusement des temps meilleurs sont venus et l’activité de l’homme
a réparé ces ruines. De cette élévation le spectacle est d’une grandeur
étrange. On a derrière soi la montagne du Bougès et plus haut la cime de
la Lozère. Devant soi au Sud, on voit tout un réseau de crêtes couronnées
par des pics s’élevant les uns sur les autres. Les torrents formés par les
pluies de l’hiver ont creusé un labyrinthe de profondes vallées
empanachées de châtaigniers de haut en bas et présentant en certains
endroits des précipices de rochers vertigineux.
Le soleil allait disparaître et l’ombre avait déjà envahi le fond des
collines lorsque Stevenson rencontra un vieux berger qui le mit sur le
chemin de Saint-Germain-de-Calberte. La partie haute de ce pays est fort
solitaire. A peine aperçoit-on au loin quelque séchoir de châtaignes ou
quelque ferme isolée. Après une assez longue descente, l’Anglais trouva
une grande route poussiéreuse: la nuit était venue et la lune argenta
bientôt de sa lumière le versant de la vallée.
Stevenson prenant sa gourde qu’il avait remplie de vieux Bourgogne à
Florac la porta à ses lèvres et but à la majesté sacrée de l’astre de la nuit.
Cette libation lui rendit des forces et Modestine elle-même, ranimée par
cette lumière, prit une allure plus rapide. Sur la pente opposée, les arêtes
et les creux des ravins se distinguaient vaguement à la lueur de la lune et
au loin, dans quelque maison isolée, une fenêtre éclairée formait une
tache de feu au milieu du vaste espace d’ombre.
Après un grand nombre de tournants Stevenson trouva un ravin plus
profond que les autres que la route traversait au milieu d’une grande
obscurité et, arrivé au bord opposé, il fut tout surpris de tomber
brusquement dans Saint-Germain-de-Calberte. Ce bourg n’a ni gaz ni
réverbères et il semblait endormi dans un paisible silence. Cependant il y
avait encore de la lumière à l’auberge. Le voyageur put s’y faire donner à
souper et y prendre gîte pour la nuit.
LA DERNIÈRE JOURNÉE

Lorsque Stevenson se leva le lendemain, jeudi 3 octobre, il se mit à la


fenêtre de la chambre propre et confortable où il avait passé la nuit. Le
jour se levait sans nuages et il avait devant lui une vallée profonde plantée
de grands châtaigniers. Il sortit dans la fraîcheur du matin pour visiter les
environs.
St-Germain est assis sur la croupe d’une haute colline au milieu d’une
des plus belles châtaigneraies des Cévennes. Le temple protestant est bâti
au-dessous du bourg sur un épaulement; l’église, qui d’après Louvreleuil
remonte à Urbain V, mais qui n’offre rien de bien remarquable, s’élève au
centre de la localité. C’est là que l’Abbé du Chayla avait sa maison, son
séminaire et sa bibliothèque; c’est là qu’on rapporta son corps le
surlendemain du meurtre horrible du Pont-de-Montvert, là enfin qu’il fut
enseveli près de l’autel de la Vierge où il avait fait préparer son tombeau.
Les funérailles furent, sinon interrompues, au moins hâtées par le bruit qui
se répandait que Séguier avec sa troupe était à une demi-heure de là.
Tous les prêtres des environs réunis pour la funèbre cérémonie se
hâtèrent de s’en aller en des lieux plus sûrs.
Maintenant tout est bien tranquille à Saint-Germain-de-Calberte. Le
pouls de la vie humaine bat si lentement dans cette paisible bourgade des
Cévennes! Le passage de Stevenson y fut un gros événement, objet de
toutes sortes de commentaires. Les enfants couraient après lui, les gens
se retournaient ou se mettaient sur leur porte pour le voir passer. Cette
curiosité, quoique n’ayant rien de malveillant, l’importunait.
Il quitta les rues et se réfugia sur les terrasses qui sont à cet endroit
tapissées de vert gazon et il essaya de rendre avec le crayon les formes
inimitables des châtaigniers avec leur majestueux dais de feuillage.
Une faible brise qui soufflait à de courts intervalles agitait les branches
et les châtaignes tombaient de tous côtés autour de lui sur la pelouse
avec un petit bruit mat. Bientôt le cultivateur pourrait recueillir cette
manne précieuse. Au-dessus de sa tête il voyait ces fruits d’un brun
luisant apparaître du cœur des bogues entre-bâillées et, à travers les
arbres, l’œil embrassait un amphithéâtre de collines ensoleillées et
emmantelées de vert feuillage. Il s’était rarement trouvé en présence d’un
spectacle si impressionnant. Enveloppé dans une atmosphère de joie il
marchait d’un pied léger et en belle humeur.
Revenu à l’auberge, Stevenson déjeuna avec quelques catholiques et
la question religieuse fut encore agitée à propos d’un jeune homme qui
avait embrassé la religion réformée pour épouser une jeune fille
protestante et qui était blâmé par les deux partis. C’est une mauvaise idée
d’abandonner la foi de ses pères, disait-on ici comme à Cassagnas, et cela
paraissait résumer l’opinion commune du pays.
A cette époque le phylloxera avait ravagé les vignes de la contrée et
l’on n’y buvait qu’une pauvre piquette qui, dit Stevenson, était agréable au
goût mais peu fortifiante.
S’étant attardé à table et au café, il ne partit de Saint-Germain que peu
avant quatre heures. Il descendit au sud-ouest jusqu’au Gardon de Mialet
dont le lit large et caillouteux est à peu près à sec en été, traversa St-
Etienne-Vallée-Française et arriva vers le soir au bas de la côte de Saint-
Pierre qu’il se hâta de gravir aussi rapidement que le permettaient les pas
menus de Modestine, car il désirait contempler le côté opposé de la
montagne en plein jour.
Mais la nuit le surprit avant qu’il eût atteint le sommet. Une vallée
indistincte, s’enfonçant dans les ténèbres, formait comme un immense
trou aux pieds du voyageur; par contre les crêtes des montagnes se
détachaient nettement sur l’azur, du firmament dominées par le mont
Aigoual. Ce sommet, jadis forteresse de Castanet, chef d’une des cinq
légions des Camisards, est aujourd’hui couronné d’un observatoire
météorologique.
Au haut de la montée de Saint-Pierre Modestine et son conducteur
prirent ensemble leur dernière réfection au clair de la lune. La pauvre bête
s’était prise d’affection pour son maître et mangeait de meilleur appétit ce
qu’il lui donnait dans le creux de la main.
La descente sur Saint-Jean-du-Gard fut longue. A dix heures du soir
seulement Stevenson était arrivé dans cette ville et se mettait à table pour
souper. Il avait marché plus de six heures et gravi une côte des plus
pénibles.
ADIEU MODESTINE!!

Le vendredi 4 octobre dans la


matinée il fut constaté après
examen que Modestine n’était pas
en état de se remettre en route.
Au dire de l’hôtelier elle avait
besoin de deux jours de repos
pour le moins. Mais Stevenson
avait hâte d’arriver à Alais où
l’attendait sa correspondance. Il se
décida donc à vendre sa
compagne de voyage et à partir
l’après-midi en diligence. Des
acheteurs flairant une bonne
affaire ne tardèrent pas à se
présenter. Vers dix heures il y eut
une offre de 25 francs et avant
midi, après un marchandage
opiniâtre, l’Anglais céda la bête et
le harnais pour 35 francs. Ce
marché n’était guère avantageux
pour lui, mais il y gagnait sa
liberté.
Ce ne fut que lorsqu’il se
trouva sur la diligence, assis à côté
du postillon et roulant dans une
vallée rocailleuse parmi des oliviers, qu’il se rendit compte de sa perte.
Tant qu’il avait eu Modestine à ses côtés il avait cru la détester; mais
maintenant il sentait qu’elle lui manquait.
Du 22 septembre au 4 octobre, elle avait été pendant douze jours sa
fidèle compagne; ils avaient fait un trajet d’environ cent lieues, franchi
plusieurs chaînes de montagnes et arpenté avec leurs six jambes une
infinité de chemins de traverse, les pieds dans les cailloux ou dans la
boue.
Après la première journée, sauf quelques accès de mauvaise humeur, il
avait supporté sa lenteur avec patience. Quant à elle, la pauvre bête, elle
le regardait presque comme un Dieu et elle se plaisait à manger dans sa
main. Elle était patiente, élégante de forme, d’un gris idéal et de taille si
menue; ses défauts étaient ceux de sa race et de son sexe; mais ses
qualités, elle ne les devait qu’à elle-même. Pauvre Modestine! il ne devait
plus la revoir.
Le père Adam avait pleuré quand il lui avait livré l’ânesse et lui, l’ayant
vendue à son tour, était sur le point de pleurer pareillement. Et il aurait,
dit-il, cédé à son émotion s’il n’avait pas eu près de lui le postillon et cinq
ou six joyeux compagnons de voyage.
NOTES

[1] Le titre anglais de l’ouvrage est: Travels with a donkey in the


Cevennes, by Robert Louis Stevenson. London. Chatto and Windus.
Piccadilly.
[2]Voici une curieuse appréciation de l’ordre des trappistes par
Schopenhauer:

«C’est chez le peuple le plus gai, le plus vif, le plus sensuel,


le plus léger,—est-il besoin de nommer la France?—que cet
ordre, seul entre tous, s’est maintenu intact à travers toutes
les révolutions et il faut attribuer sa durée au sérieux profond
que l’on ne peut méconnaître dans l’esprit qui l’anime et qui
exclut toute considération secondaire. La décadence de la
religion ne l’a pas atteint, car ses racines tiennent aux
profondeurs de l’âme humaine bien plus encore qu’à quelque
dogme positif.» (La Vie, l’Amour et la Mort p. 275, 276.)

[3]La Guerre des Camisards, mise en vers par Jean-Louis Guin.—


En vente chez l’auteur, au Pont-de-Montvert (Lozère).—Prix: 3 francs.
MÉMOIRES DU CLUB CÉVENOL

Le «Bulletin illustré du Club Cévenol» publication trimestrielle, n’est


pas fait pour relater les travaux de longue haleine que des correspondants
érudits veulent bien consacrer à nos Cévennes.
Pour que le fruit de ces recherches ne soit pas perdu, la nécessité
s’imposait de publier à part les plus remarquables de ces études; c’est de
cette préoccupation qu’est née la série entreprise sous le titre générique:
«Mémoires du Club Cévenol».
Histoire,—géographie,—archéologie,—récits et légendes,—recherches
dans le sous-sol, les «Mémoires du Club Cévenol» ont un cadre assez
large pour offrir l’hospitalité à tous ces genres de travaux. Il suffira que
chacun des ouvrages présentés offre une originalité suffisante et un
caractère local pour qu’il soit digne de figurer dans la collection.
Si le succès répond à nos espérances, chaque année la collection
s’enrichira d’un volume du même format que le Bulletin. Chaque volume
des «Mémoires» sera mis en souscription par l’un des groupes du Club
Cévenol et le jour où le nombre de souscripteurs sera assez élevé, la
publication aura lieu.
L’année 1901 inaugure la série de ces études et successivement
paraîtront:
Tome I No 1 Barre et sa Seigneurie; par M. L. Jourdan, député de la
Lozère;
— No 2 La Salindrinque: par M. X., membre correspondant du
Club Cévenol;
— No 3 Voyage à travers les Cévennes; par Stevenson; adaptation
française par A. Moulharac;
Ces ouvrages viennent de paraître.
Tous ceux qui ont à cœur de grossir la phalange cévenole des
pionniers de nos montagnes, tous ceux qui veulent entretenir un
commerce intime avec les souvenirs présents et passés du coin de terre
natal, viendront à nous comme souscripteurs, apporter leur modeste part
contributive a l’œuvre entreprise et seconderont ainsi le Club Cévenol
dans la direction nouvelle où il s’est engagé au seuil du XXe siècle.

F. V.

A détacher et à renvoyer au secrétaire du groupe du Mt Liron à


LASALLE (Gard).
⁓⁓⁓⁓⁓⁓⁓⁓⁓⁓
Je soussigné (nom; prénom et adresse)....

déclare souscrire aux Nos 2 et 3 des «Mémoires du Club Cévenol» et


m’engage à verser la somme de 2 fr. plus les frais de port, dès la
réception des susdits ouvrages.

Signature,
Compagnie des SERVICES
INTERNATIONAUX
DES CHEMINS DE FER
――――

RENSEIGNEMENTS GÉNÉRAUX

La Compagnie des Services Internationaux des Chemins de fer, dont la


fondation remonte à quatorze années, a été instituée dans le but d’établir
des relations entre toutes les compagnies de Chemins de fer d’Europe et
de les représenter: elle développe les voyages dans tous les pays et fait
connaître au public les nouvelles combinaisons de billets qui lui permettent
de bénéficier des grandes réductions et des facilités accordées par les
différentes Compagnies.
Elle centralise les tarifs et horaires, soude entre elles les lignes directes
et rapides, pour les relier aux points frontières afin d’éviter toute
interruption dans les parcours.
Ces tarifs, horaires et tracés de voyages sont publiés par
l’Administration centrale, à l’aide de divers guides, remis gratuitement au
public par ses soins, dans toutes les parties du Continent.
Les bureaux de l’Administration sont installés dans l’International
Palace, 7 et 7 bis, Avenue Bosquet (près du pont de l’Alma et des
Champs-Elysées), centre essentiellement mondain et riche du Tout-Paris.

PUBLICITÉ DU BULLETIN ILLUSTRÉ ET DES MÉMOIRES DU "CLUB


CÉVENOL"

‒‒‒‒‒‒
Par suite de traités conclus avec l’Administration de la Compagnie des
Services Internationaux des chemins de fer, la publicité du Bulletin Illustré
et des Mémoires du Club Cévenol est désormais confiée à M.
l’Administrateur délégué de la Compagnie qui a bien voulu nous prêter son
concours et celui de ses agents.
L’agent spécial chargé de ce service, M. Lacoste, se présentera sous peu
chez nos anciens abonnés et chez quelques-uns de nos collègues: Tous lui
réserveront, nous n’en doutons pas, le meilleur accueil.
Excursions dans les Cévennes et les Causses
Service de Renseignements du «Club Cévenol»
Grâce à l’obligeance de M. l’Administrateur de la Compagnie des
Services Internationaux des chemins de fer, notre service de
renseignements pour les excursions dans les Cévennes et les Causses, va
être installé dans l’International Palace 7 et 7 bis, Avenue Bosquet, à
Paris.
M. Henri Degas, secrétaire du Comité central, a bien voulu se charger de
réorganiser et de diriger notre nouveau service de renseignements.
CHEMIN DE FER D’ORLÉANS
――――

PUBLICATIONS éditées par les soins de la Compagnie d’Orléans et mises


en vente dans ses gares

——————
Le Livret-Guide illustré de la Compagnie d’Orléans (Notices, Vues,
Tarifs, Horaires), est mis en vente, au prix de 30 centimes:
1o à Paris: dans les bureaux de quartier et dans les gares du Quai
d’Orsay, du Pont-Saint-Michel, d’Austerlitz, Luxembourg, Port Royal et
Denfert;
2o en Province: dans les gares et principales stations.
Les publications ci-après, éditées par les soins de la Compagnie
d’Orléans, sont mises en vente dans toutes les bibliothèques des gares de
son réseau au prix de: 25 centimes.

Le Cantal.
Le Berry (au pays de George Sand).
Bretagne.
De la Loire aux Pyrénées.
La France en chemin de fer (Itinéraire
géographique de Paris à Tours).
La France en chemin de fer (Itinéraire
géographique de St-Denis-près-Martel à
Arvant, ligne du Cantal). Premières livraisons
La France en chemin de fer (Itinéraire d’une collection
géographique de Tours à Nantes). qui sera continuée.
La France en chemin de fer (Itinéraire
géographique de Limoges à Clermont-
Ferrand, avec embranchement de Laqueuille
au Mont-Dore).

Voyage d’Excursion aux Plages de Bretagne


——————

Du 1er Mai au 31 Octobre, il est délivré des Billets de voyage


d’excursion aux plages de Bretagne, à prix réduits et comportant le
parcours ci-après:
Le Croisic, Guérande, Saint-Nazaire, Savenay, Questembert,
Ploërmel, Vannes, Auray, Pontivy, Quiberon, Le Palais (Belle-Isle-
en-Mer), Lorient, Quimperlé, Rosporden, Concarneau, Quimper,
Douarnenez, Pont-l’Abbé, Châteaulin.

ALLER ET RETOUR

Prix des billets: 1re classe, 45 fr.; 2e classe, 36 fr. Durée de validité:
30 jours.
Ces billets comportent la faculté d’arrêt à tous les points du parcours,
tant à l’aller qu’au retour. Le voyage peut être commencé à l’un
quelconque des points du parcours.
Les voyageurs peuvent s’arrêter aux gares intermédiaires situées entre
les points indiqués à l’itinéraire, à la condition de déposer, pendant le
temps de leur séjour, leurs billets à la gare à laquelle ils s’arrêtent.
Les voyageurs peuvent suivre, à leur gré, l’itinéraire dans le sens
inverse de celui indiqué ci-dessus; ils peuvent également ne pas effectuer
tous les parcours détaillés dans cet itinéraire, et se rendre directement sur
les seuls points où ils désirent passer ou séjourner, en suivant, toutefois,
le sens général de l’itinéraire qu’ils ont choisi et en abandonnant leurs
droits aux parcours non effectués. Ils peuvent de même revenir
directement à leur point de départ en suivant au retour l’itinéraire
parcouru à l’aller.
La durée de validité des Billets de Voyage d’Excursion peut être
prolongée de 10 jours, moyennant le paiement d’un supplément égal à 10
0/0 des prix ci-dessus. Cette prolongation pourra être accordée trois fois
au plus; le supplément à payer pour chaque prolongation de 10 jours
sera de 10 0/0 du prix primitif. La demande de prolongation devra être
faite et le supplément payé avant l’expiration de la durée de la validité, en
tenant compte, s’il y a lieu, de la prolongation déjà payée.
Il est délivré de toute station du réseau d’Orléans pour Savenay ou
tout autre point situé sur l’itinéraire du Voyage d’excursion aux plages de
Bretagne et inversement de Savenay, ou de tout autre point situé sur ledit
itinéraire à toute station dudit réseau, des billets spéciaux de 1re et de 2e
classe, comportant une réduction de 40 0/0 sur le prix ordinaire des
places, sous condition d’un parcours minimum de 50 kilomètres par billet.
Ces billets sont délivrés distinctement, le premier pour aller rejoindre
l’itinéraire du Voyage d’excursion aux plages de Bretagne, le second pour
quitter cet itinéraire lorsque le voyageur l’a terminé ou veut l’abandonner.
CHEMINS DE FER DU MIDI
————

VOYAGES CIRCULAIRES
PARIS—CENTRE DE LA FRANCE—PYRÉNÉES
3 Voyages différents au choix du voyageur
Billets délivrés toute l’année aux prix uniformes ci-après pour les 3
itinéraires. 1re classe, 163 fr. 50—2e classe, 122 fr. 50—Durée: 30 jours
non compris celui du départ.
Faculté de prolongation moyennant supplément de 10 %

VOYAGES CIRCULAIRES A PRIX RÉDUITS


EN PROVENCE ET AUX PYRÉNÉES

1er, 2e et 3e 68 fr. en 1re 51 fr. en 2e


parcours classe; classe.
PRIX 4e, 5e, 6e et 7e 91 — — 68 — —
parcours
8e parcours 114 — — 87 — —

Le 8e parcours peut, au moyen de billets spéciaux d’aller et retour à


prix réduits de ou pour Marseille, s’étendre de Marseille sur le littoral
jusqu’à Hyères, Cannes, Nice ou Menton, etc., au choix du voyageur.
Durée: 20 jours pour les sept premiers parcours et 25 jours pour le
huitième.
Faculté de prolongation moyennant supplément de 10 %
BILLETS D’ALLER ET RETOUR INDIVIDUELS
Pour les stations hivernales et balnéaires des Pyrénées
Billets délivrés toute l’année avec réduction de 25 % en première
classe et 20 % en 2e et 3e classes dans les gares des réseaux du Nord
(Paris-Nord excepté), de l’Etat, d’Orléans et dans les gares du Midi situées
à 50 kilomètres au moins de la destination.
—Durée: 33 jours, non compris les jours de départ et d’arrivée.
Faculté de prolongation moyennant supplément de 10 %
Ces billets doivent être demandés 3 jours à l’avance à la gare de
départ.
Un arrêt facultatif est autorisé à l’aller et au retour pour tout parcours
de plus de 400 kilomètres.

BILLETS DE FAMILLE
Pour les stations hivernales et balnéaires des Pyrénées
Billets délivrés toute l’année dans les gares des réseaux du Nord
(Paris-Nord excepté), de l’Etat, d’Orléans, du Midi et de Paris-Lyon-
Méditerranée, suivant l’itinéraire choisi par le voyageur, et avec les
réductions suivantes sur les prix du tarif général pour un parcours (aller et
retour compris) d’au moins 300 kilomètres.—Pour une famille de 2
personnes, 20 %; de 3, 25 %; de 4, 30 %; de 5, 35 %; de 6, ou plus, 40
%.
Exceptionnellement pour les parcours empruntant le réseau de Paris-
Lyon-Méditerranée, les billets ne sont délivrés qu’aux familles d’au moins
quatre personnes et le prix s’obtient en ajoutant au prix de 6 billets
simples ordinaires, le prix d’un de ces billets pour chaque membre de la
famille en plus de trois.
Arrêts facultatifs sur tous les points du parcours désignés sur la
demande.
Durée: 33 jours, non compris les jours de départ et d’arrivée.
Faculté de prolongation moyennant supplément de 10 %
Ces billets doivent être demandés au moins 4 jours à l’avance à la gare
de départ.

AVIS.—Un livret indiquant en détail les conditions dans lesquelles


peuvent être effectuées les excursions ci-dessus, est envoyé franco à
toute personne qui en fait la demande à la compagnie du Midi. Cette
demande doit être adressée au bureau commercial de la Compagnie, 54,
boulevard Haussmann, à Paris.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like