100% found this document useful (1 vote)
28 views42 pages

(Ebook PDF) Big Java: Early Objects 5th Edition - Own The Ebook Now and Start Reading Instantly

Early

Uploaded by

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

(Ebook PDF) Big Java: Early Objects 5th Edition - Own The Ebook Now and Start Reading Instantly

Early

Uploaded by

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

Read Anytime Anywhere Easy Ebook Downloads at ebookluna.

com

(eBook PDF) Big Java: Early Objects 5th Edition

https://ebookluna.com/product/ebook-pdf-big-java-early-
objects-5th-edition/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookluna.com


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

(eBook PDF) Big Java: Early Objects, 7th Edition

https://ebookluna.com/product/ebook-pdf-big-java-early-objects-7th-
edition/

ebookluna.com

(eBook PDF) Big Java: Early Objects, 6th Edition by Cay S.


Horstmann

https://ebookluna.com/product/ebook-pdf-big-java-early-objects-6th-
edition-by-cay-s-horstmann/

ebookluna.com

(eBook PDF) Starting Out with Java: Early Objects 5th


Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-early-
objects-5th-edition/

ebookluna.com

(eBook PDF) Big Java Late Objects 2nd Edition

https://ebookluna.com/product/ebook-pdf-big-java-late-objects-2nd-
edition/

ebookluna.com
(eBook PDF) Starting Out with Java: Early Objects 5th
Global Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-early-
objects-5th-global-edition/

ebookluna.com

(eBook PDF) Java How To Program (Early Objects) 10th

https://ebookluna.com/product/ebook-pdf-java-how-to-program-early-
objects-10th/

ebookluna.com

(eBook PDF) Starting Out with Java Early Objects 6th


Edition by Tony Gaddis

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-early-
objects-6th-edition-by-tony-gaddis/

ebookluna.com

(eBook PDF) Java How to Program, Early Objects 11th


Edition by Paul J. Deitel

https://ebookluna.com/product/ebook-pdf-java-how-to-program-early-
objects-11th-edition-by-paul-j-deitel/

ebookluna.com

(eBook PDF) Big C++: Late Objects 3rd Edition

https://ebookluna.com/product/ebook-pdf-big-c-late-objects-3rd-
edition/

ebookluna.com
vi Preface

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. Chapter 9 covers inheritance and polymor-
phism, whereas Chapter 10 covers interfaces. 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–18)


Chapters 13 through 18 contain an introduction to algorithms and data structures,
covering recursion, sorting and searching, linked lists, binary trees, and hash tables.
These topics may be outside the scope of a one-semester course, but can be covered
as desired after Chapter 7 (see Figure 1). Recursion, in Chapter 13, starts with simple
examples and progresses to meaningful applications that would be difficult to imple-
ment iteratively. Chapter 14 covers quadratic sorting algorithms as well as merge sort,
with an informal introduction to big-Oh notation. Each data structure is presented
in the context of the standard Java collections library. You will learn the essential
abstractions of the standard library (such as iterators, sets, and maps) as well as the
performance characteristics of the various collections. Chapter 18 introduces Java
generics. This chapter is suitable for advanced students who want to implement their
own generic classes and methods.

Part D: Applied Topics (Chapters 19–25)


Chapters 19 through 25 cover Java programming techniques that definitely go
beyond a first course in Java (21–25 are on the book’s companion site). Although, as
already mentioned, a comprehensive coverage of the Java library would span many
volumes, many instructors prefer that a textbook should give students additional
reference material valuable beyond their first course. Some institutions also teach a
second-semester course that covers more practical programming aspects such as data-
base and network programming, rather than the more traditional in-depth material
on data structures and algorithms. This book can be used in a two-semester course
to give students an introduction to programming fundamentals and broad coverage
of applications. Alternatively, the material in the final chapters can be useful for stu-
dent projects. The applied topics include graphical user-interface design, advanced
file handling, multithreading, and those technologies that are of particular interest to
server-side programming: networking, databases, XML, and web applications. The
Internet has made it possible to deploy many useful applications on servers, often
accessed by nothing more than a browser. This server-centric approach to application
development was in part made possible by the Java language and libraries, and today,
much of the industrial use of Java is in server-side programming.

bj5_fm_06.indd 6 11/6/12 9:18 PM


Preface vii

Appendices
Many instructors find it highly beneficial to require a consistent style for all assign-
ments. If the style guide in Appendix I conflicts with instructor sentiment or local
customs, however, it is available in electronic form so that it can be modified.
A. The Basic Latin and Latin-1 Subsets F. Tool Summary
of Unicode G. Number Systems
B. Java Operator Summary H. UML Summary
C. Java Reserved Word Summary I. Java Language Coding Guidelines
D. The Java Library J. HTML Summary
E. Java Syntax Summary

Custom Book and eBook Options


Big Java may be ordered as a custom print or eBook that includes your choice of
chapters—including those from other Horstmann titles. Visit customselect.wiley.com
to create your custom book order.
To order the Wiley Select Edition of Big Java with all 25 chapters in the printed
book, specify ISBN 978-1-119-93670-1 when you order books.
Big Java is available in a variety of eBook formats at prices that are significantly
lower than the printed book. Please contact your Wiley sales rep for more informa-
tion or check www.wiley.com/college/horstmann for available versions.

Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/college/horstmann to visit the online companion sites, which include

• “CodeCheck,” a new online service currently in development by Cay Horstmann


that students can use to check their homework assignments and to work on addi-
tional practice problems. Visit http://horstmann.com/codecheck to learn more and to
try it out.
• Source code for all example programs in the book and in online examples.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Animations of key concepts.
• Lab exercises that apply chapter concepts (with solutions for instructors only).
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.

WORKED EXAMPLE 6.3 A Sample Debugging Session


Learn how to find bugs in an algorithm for counting the
Pointers in the book syllables of a word. Go to wiley.com/go/javaexamples and
download Worked Example 6.3.
describe what students
will find on the Web.
FULL CODE EXAMPLE

Go to wiley.com/go/
javacode to download
a program that dem-
onstrates variables
and assignments.

bj5_fm_06.indd 7 10/26/12 11:44 AM


viii Walkthrough

A Walkthrough of the Learning Aids


The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional
features, such as chapter objectives and a wealth of exercises, each chapter contains
elements geared to today’s visual learner.

254 Chapter 6 Loops

6.3 The for Loop


Throughout each chapter,
It often happens that you want to execute a sequence of statements a given number
margin notes show where The for loop is
used when a of times. You can use a while loop that is controlled by a counter, as in the following
example:
new concepts are introduced
value runs from a
starting point to an
ending point with a int counter = 1; // Initialize the counter
and provide an outline of key ideas. constant increment
or decrement.
while (counter <= 10) // Check the counter
{
System.out.println(counter);
counter++; // Update the counter
}

Because this loop type is so common, there is a spe-


cial form for it, called the for loop (see Syntax 6.2).
for (int counter = 1; counter <= 10; counter++)
{
Additional full code examples }
System.out.println(counter);

provides complete programs for FULL CODE EXAMPLE Some people call this loop count-controlled. In con-
trast, the while loop of the preceding section can be
students to run and modify.
Go to wiley.com/go/
javacode to download
a program that
called an event-controlled loop because it executes
uses common loop until an event occurs; namely that the balance reaches
algorithms. the target. Another commonly used term for a
count-controlled loop is definite. You know from
the outset that the loop body will be executed a
definite number of times; ten times in our example.
In contrast, you do not know how many iterations it
takes to accumulate a target balance. Such a loop is
Annotated syntax boxes called indefinite. You can visualize the for loop as
an orderly sequence of steps.
provide a quick, visual overview
of new language constructs. Syntax 6.2 for Statement

Syntax for (initialization; condition; update)


{
statements
}
These three
expressions should be related.
See page 259.

Annotations explain required This initialization The condition is This update is


components and point to more happens once
before the loop starts.
checked before
each iteration.
executed after
each iteration.
information on common errors for (int i = 5; i <= 10; i++)
or best practices associated The variable i is
{
sum = sum + i; This loop executes 6 times.
with the syntax. defined only in this for loop.
See page 261.
} See page 260.

Analogies to everyday objects are


used to explain the nature and behavior
of concepts such as variables, data
Like a variable in a computer types, loops, and more.
program, a parking space has
an identifier and a contents.

bj5_fm_06.indd 8 10/24/12 6:23 PM


Walkthrough ix

Memorable photos reinforce


analogies and help students
remember the concepts.

In the same way that there can be a street named “Main Street” in different cities,
a Java program can have multiple variables with the same name.

Problem Solving sections teach


techniques for generating ideas and 7.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 339

evaluating proposed solutions, often Now how does that help us with our problem, switching the first and the second
using pencil and paper or other half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
artifacts. These sections emphasize Java programmers, we will say that we swap the coins in positions 0 and 4:

that most of the planning and problem


solving that makes students successful
happens away from the computer.

Next, we swap the coins in positions 1 and 5:

HOW TO 6.1 Writing a Loop How To guides give step-by-step


This How To walks you through the process of implementing a guidance for common programming
loop statement. We will illustrate the steps with the following
example problem. tasks, emphasizing planning and
Problem Statement Read twelve temperature values (one for
each month) and display the number of the month with the high- testing. They answer the beginner’s
est temperature. For example, according to worldclimate.com, the
average maximum temperatures for Death Valley are (in order by question, “Now what do I do?” and
month, in degrees Celsius):
18.2 22.6 26.4 31.1 36.6 42.2 45.7 44.5 40.2 33.1 24.2 17.6
integrate key concepts into a
In this case, the month with the highest temperature (45.7 degrees problem-solving sequence.
Celsius) is July, and the program should display 7.

Step 1 Decide what work must be done inside the loop.

Every loop needs to do some kind of repetitive work, such as


• Reading another item.
• Updating a value (such as a bank balance or total).
• Incrementing a counter. Worked Examples apply
If you can’t figure out what needs to go inside the loop, start by writing down the steps that
the steps in the How To to a
WORKED EXAMPLE 6.1 Credit Card Processing different example, showing
Learn how to use a loop to remove spaces from a credit card
number. Go to wiley.com/go/javaexamples and download
how they can be used to
Worked Example 6.1.
plan, implement, and test
a solution to another
programming problem.
Table 1 Variable Declarations in Java
Variable Name Comment

int width = 20; Declares an integer variable and initializes it with 20.

int perimeter = 4 * width; The initial value need not be a fixed value. (Of course, width
must have been previously declared.)
String greeting = "Hi!"; This variable has the type String and is initialized with the
Example tables support beginners
string “Hi”. with multiple, concrete examples.
height = 30; Error: The type is missing. This statement is not a declaration
but an assignment of a new value to an existing variable—see These tables point out common
Section 2.2.5.
errors and present another quick
Error: You cannot initialize a number with the string “20”.
reference to the section’s topic.
int width = "20";
(Note the quotation marks.)
int width; Declares an integer variable without initializing it. This can be a
cause for errors—see Common Error 2.1 on page 42.
int width, height; Declares two integer variables in a single statement. In this
book, we will declare each variable in a separate statement.

bj5_fm_06.indd 9 10/24/12 6:28 PM


x Walkthrough

This means “compute the value of width + 10 1 and store that value in the variable
width 2 ” (see Figure 4).
Progressive figures trace code
In Java, it is not a problem that the variable width is used on both sides of the = sym-
bol. Of course, in mathematics, the equation width = width + 10 has no solution.
segments to help students visualize
the program flow. Color is used
1 Compute the value of the right-hand side consistently to make variables and
width = 30
other elements easily recognizable.
width + 10

40

2 Store the value in the variable Figure 3


1 Initialize counter
Execution of a for (int counter = 1; counter <= 10; counter++)
Figure 4 width = 40 for Loop {
Executing the Statement System.out.println(counter);
counter = 1 }
width = width + 10

2 Check condition
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }

3 Execute loop body


for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }

4 Update counter
for (int counter = 1; counter <= 10; counter++)
{

Students can view animations counter = 2 }


System.out.println(counter);

of key concepts on the Web.


A N I M AT I O N 5 Check condition again
for (int counter = 1; counter <= 10; counter++)
The for Loop {
System.out.println(counter);
counter = 2 }

The for loop neatly groups the initialization, condition, and update expressions
together. However, it is important to realize that these expressions are not executed
Self-check exercises at the together (see Figure 3).

end of each section are designed • The initialization is executed once, before the loop is entered. 1

to make students think through • The condition is checked before each iteration. 2 5
• The update is executed after each iteration. 4
the new material—and can
Write the for loop of the Investment class as a while loop.
spark discussion in lecture.
11.

SELF CHECK
12. How many numbers does this loop print?
for (int n = 10; n >= 0; n--)
{
System.out.println(n);
}

13. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
14. Write a for loop that computes the sum of the integers from 1 to n.

Practice It Now you can try these exercises at the end of the chapter: R6.4, R6.10, E6.8, E6.12.
Optional science and business
exercises engage students with •• Business E6.17 Currency conversion. Write a program

realistic applications of Java. that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.

• Science P6.15 Radioactive decay of radioactive materials can be


section_1/Investment.java modeled by the equation A = A0e-t (log 2/h), where A is
1 /** the amount of the material at time t, A0 is the amount
2 A class to monitor the growth of an investment that at time 0, and h is the half-life.
3 accumulates interest at a fixed annual rate.
4 */ Technetium-99 is a radioisotope that is used in imaging
5 public class Investment of the brain. It has a half-life of 6 hours. Your program
6 { should display the relative amount A / A0 in a patient
7 private double balance; body every hour for 24 hours after receiving a dose.
8 private double rate;
9 private int year;
10
11 /**
12 Constructs an Investment object from a starting balance and
13 interest rate.
14 @param aBalance the starting balance
15
16 */
@param aRate the interest rate in percent
Program listings are carefully
17 public Investment(double aBalance, double aRate)
18 { designed for easy reading,
19 balance = aBalance;
20
21
rate = aRate;
year = 0;
going well beyond simple
22
23
}
color coding. Methods are set
24
25
/**
Keeps accumulating interest until a target balance has off by a subtle outline.
26 been reached.
27 @param targetBalance the desired balance
28 */

bj5_fm_05.indd 10 10/18/12 3:25 PM


Walkthrough xi

Length and Size


Common Errors describe the kinds Common Error 7.4
Unfortunately, the Java syntax for Data Type Number of Elements
of errors that students often make, determining the number of elements
in an array, an array list, and a string Array a.length
with an explanation of why the errors is not at all consistent. It is a com-
mon error to confuse these. You just Array list a.size()

occur, and what to do about them. have to remember the correct syntax
for every data type. String a.length()

Programming Tip 5.5 Hand-Tracing


A very useful technique for understanding whether a pro-
gram works correctly is called hand-tracing. You simulate
the program’s activity on a sheet of paper. You can use this
method with pseudocode or Java code.
Get an index card, a cocktail napkin, or whatever sheet
of paper is within reach. Make a column for each variable.
Have the program code ready. Use a marker, such as a
paper clip, to mark the current statement. In your mind,
execute statements one at a time. Every time the value of a
variable changes, cross out the old value and write the new
value below the old one. Hand-tracing helps you
For example, let’s trace the getTax method with the data understand whether a
Programming Tips explain from the program run above.
When the TaxReturn object is constructed, the income
program works correctly.

good programming practices, instance variable is set to 80,000 and status is set to MARRIED. Then the getTax method is called.
In lines 31 and 32 of TaxReturn.java, tax1 and tax2 are initialized to 0.
and encourage students to be 29 public double getTax()
30 {

more productive with tips and income status tax1 tax2


31 double tax1 = 0;
32 double tax2 = 0;
33 80000 MARRIED 0 0
techniques such as hand-tracing. Because status is not SINGLE, we move to the else
branch of the outer if statement (line 46).
34 if (status == SINGLE)
35 {
36 if (income <= RATE1_SINGLE_LIMIT)
37 {
38 tax1 = RATE1 * income;
39 }
40 else
41 {
42 tax1 = RATE1 * RATE1_SINGLE_LIMIT;
43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
44 }
45 }
46 else
47 {

Special Topic 11.2 File Dialog Boxes


In a program with a graphical user interface, you will want to use a file dialog box (such as the
one shown in the figure below) whenever the users of your program need to pick a file. The
JFileChooser class implements a file dialog box for the Swing user-interface toolkit.
The JFileChooser class has many options to fine-tune the display of the dialog box, but in its
Special Topics present optional most basic form it is quite simple: Construct a file chooser object; then call the showOpenDialog
or showSaveDialog method. Both methods show the same dialog box, but the button for select-
topics and provide additional ing a file is labeled “Open” or “Save”, depending on which method you call.
For better placement of the dialog box on the screen, you can specify the user-interface
explanation of others. New component over which to pop up the dialog box. If you don’t care where the dialog box pops
up, you can simply pass null. The showOpenDialog and showSaveDialog methods return either
features of Java 7 are also JFileChooser.APPROVE_OPTION, if the user has chosen a file, or JFileChooser.CANCEL_OPTION, if the
user canceled the selection. If a file was chosen, then you call the getSelectedFile method to
covered in these notes. obtain a File object that describes the file. Here is a complete example:
FULL CODE EXAMPLE
JFileChooser chooser = new JFileChooser();
Go to wiley.com/go/ Scanner in = null;
javacode to download
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
a program that
{
demonstrates how to
use a file chooser. File selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
. . .
}

Call with
showOpenDialog
method

Computing & Society 1.1 Computers Are Everywhere


Button is “Save” when
When computers The advent of ubiqui-
showSaveDialog method
were first invented tous computing changed
is called
in the 1940s, a computer filled an many aspects of our
entire room. The photo below shows lives. Factories used
the ENIAC (electronic numerical inte- to employ people to
A JFileChooser Dialog Box
grator and computer), completed in do repetitive assembly
1946 at the University of Pennsylvania. tasks that are today car-
The ENIAC was used by the military ried out by computer-
Computing & Society presents social to compute the trajectories of projec- controlled robots, oper-
tiles. Nowadays, computing facilities ated by a few people
and historical topics on computing—for of search engines, Internet shops, and who know how to work
social networks fill huge buildings with those computers.
interest and to fulfill the “historical and called data centers. At the other end of Books, music, and mov-
the spectrum, computers are all around ies are nowadays often

social context” requirements of the us. Your cell phone has a computer consumed on com- This transit card contains a computer.
inside, as do many credit cards and fare puters, and comput-

ACM/IEEE curriculum guidelines.


cards for public transit. A modern car ers are almost always
has several computers––to control the involved in their production. The could not have been written without
engine, brakes, lights, and the radio. book that you are reading right now computers.

bj5_fm_05.indd 11 10/18/12 3:25 PM


xii Walkthrough

Web Resources

http://horstmann.com/codecheck/
CodeCheck “CodeCheck” is a new
online service currently in development
by Cay Horstmann that students can
use to check their homework and to
work on additional practice problems.
Visit http://horstmann.com/codecheck
to learn more and to try it out.

Test Bank Instructors can use quiz and


test questions designed to exercise
students’ code reading and writing skills.

10) What is displayed after executing the given code snippet?

int[] mymarks = new int[10];


int total = 0;
Scanner in = new Scanner(System.in);
for (int cnt = 1; cnt <= 10; cnt++)
{
System.out.print("Enter the marks: ");
mymarks[cnt] = in.nextInt();
total = total + mymarks[cnt];
}
System.out.println(total);

a) The code snippet displays the total marks of all ten subjects.
b) The for loop causes a run-time time error on the first iteration.
c) The code snippet causes a bounds error.
d) The code snippet displays zero.

Lab Exercises These multi-part


1.1) Consider the following Card class. exercises ask students to apply
public class Card
{
chapter concepts. They can serve
private String name; as “warm-ups” in the lab or to Animations Students can
public Card() provide additional practice. play and replay dynamic
{
name = ""; explanations of concepts
}
and program flow.
public Card(String n)
{
name = n;
}

public String getName()


{
return name;
}

public boolean isExpired()


{
return false;
}

public String format()


{
return "Card holder: " + name;
}
}

Use this class as a superclass to implement a hierarchy of related classes:

Class Data
IDCard ID number
CallingCard Card number, PIN
DriverLicense Expiration year

Write declarations for each of the subclasses. For each subclass, supply private instance variables. Leave the
bodies of the constructors and the format methods blank for now.

bj5_fm_06.indd 12 10/24/12 6:23 PM


Acknowledgments xiii

Acknowledgments
Many thanks to Beth Lang Golub, Don Fowley, Elizabeth Mills, Katherine Willis,
Jenny Welter, Wendy Ashenberg, Lisa Gee, Kevin Holm, and Tim Lindner at John
Wiley & Sons, and Vickie Piercey at Publishing Services for their help with this proj-
ect. 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 Suchindran Chatterjee, Arizona State University, Jose Cordova,
University of Louisiana, Udayan Das, DeVry University, James Johnson, Aaron
Keen, California Polytechnic State University San Luis Obispo, Norm Krumpe,
Miami University Ohio, Kathy Liszka, University of Akron, Kathleen O’Brien, San
Jose State University, Donald Smith, Columbia College, Mark Thomas, University of
Cincinnati, Laurie White, Mercer University, Brent Wilson, George Fox University,
and David Woolbright, Columbus State University, for their excellent contributions
to the supplementary materials.
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:

Eric Aaron, Wesleyan University Guy Helmer, Iowa State Bill Mongan, Drexel University
James Agnew, Anne Arundel University George Novacky, University
Community College Ed Holden, Rochester Institute of Pittsburgh
Greg Ballinger, Miami Dade of Technology Mimi Opkins, California State
College Steven Janke, Colorado College University Long Beach
Jon Beck, Truman State Mark Jones, Lock Haven Derek Pao, City University of
University University of Pennsylvania Hong Kong
Matt Boutell, Rose-Hulman Dr. Mustafa Kamal, University of Katherine Salch, Illinois Central
Institute of Technology Central Missouri College
John Bundy, DeVry University Gary J. Koehler, University of Javad Shakib, DeVry University
Chicago Florida Charlie Shu, Franklin University
Michael Carney, Finger Lakes Ronald Krawitz, DeVry Joslyn A. Smith, Florida
Community College University International University
Christopher Cassa, Norm Krumpe, Miami Robert Strader, Stephen F. Austin
Massachusetts Institute of University Ohio State University
Technology Jim Leone, Rochester Institute Jonathan S. Weissman, Finger
Dr. Suchindran S. Chatterjee, of Technology Lakes Community College
Arizona State University Kevin Lillis, St. Ambrose Katherine H. Winters, University
Tina Comston, Franklin University of Tennessee Chattanooga
University Darren Lim, Siena College Tom Wulf, University of
Lennie Cooper, Miami Dade Hong Lin, DeVry University Cincinnati
College Kuber Maharjan, Purdue Qi Yu, Rochester Institute of
Sherif Elfayoumy, University of University College of Technology
North Florida Technology at Columbus
Henry A Etlinger, Rochester Patricia McDermott-Wells,
Institute of Technology Florida International
University

bj5_fm_06.indd 13 11/9/12 11:56 AM


xiv Acknowledgments

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:

Tim Andersen, Boise State University Elliotte Harold Kai Qian, Southern Polytechnic
Ivan Bajic, San Diego State University Eileen Head, Binghamton University State University
Ted Bangay, Sheridan Institute Cecily Heiner, University of Utah Cyndi Rader, Colorado School
of Technology Brian Howard, Depauw University of Mines
Ian Barland, Radford University Lubomir Ivanov, Iona College Neil Rankin, Worcester Polytechnic
George Basham, Franklin University Norman Jacobson, University of Institute
Sambit Bhattacharya, Fayetteville California, Irvine Brad Rippe, Fullerton College
State University Curt Jones, Bloomsburg University Pedro I. Rivera Vega, University
Rick Birney, Arizona State University Aaron Keen, California Polytechnic of Puerto Rico, Mayaguez
Paul Bladek, Edmonds Community State University, San Luis Obispo Daniel Rogers, SUNY Brockport
College Mugdha Khaladkar, New Jersey Chaman Lal Sabharwal, Missouri
Joseph Bowbeer, Vizrea Corporation Institute of Technology University of Science and
Timothy A. Budd, Oregon State Elliot Koffman, Temple University Technology
University Kathy Liszka, University of Akron John Santore, Bridgewater State
Robert P. Burton, Brigham Young Hunter Lloyd, Montana State College
University University Carolyn Schauble, Colorado State
Frank Butt, IBM Youmin Lu, Bloomsburg University University
Jerry Cain, Stanford University John S. Mallozzi, Iona College Brent Seales, University of Kentucky
Adam Cannon, Columbia University John Martin, North Dakota State Christian Shin, SUNY Geneseo
Nancy Chase, Gonzaga University University Jeffrey Six, University of Delaware
Archana Chidanandan, Rose-Hulman Jeanna Matthews, Clarkson University Don Slater, Carnegie Mellon
Institute of Technology Scott McElfresh, Carnegie Mellon University
Vincent Cicirello, The Richard University Ken Slonneger, University of Iowa
Stockton College of New Jersey Joan McGrory, Christian Brothers Donald Smith, Columbia College
Teresa Cole, Boise State University University Stephanie Smullen, University of
Deborah Coleman, Rochester Institute Carolyn Miller, North Carolina Tennessee, Chattanooga
of Technology State University Monica Sweat, Georgia Institute
Jose Cordova, University of Louisiana, Sandeep R. Mitra, State University of Technology
Monroe of New York, Brockport Peter Stanchev, Kettering University
Valentino Crespi, California State Teng Moh, San Jose State University Shannon Tauro, University of
University, Los Angeles John Moore, The Citadel California, Irvine
Jim Cross, Auburn University Jose-Arturo Mora-Soto, Jesica Ron Taylor, Wright State University
Russell Deaton, University Rivero-Espinosa, and Julio-Angel Russell Tessier, University of
of Arkansas Cano-Romero, University Massachusetts, Amherst
Geoffrey Decker, Northern Illinois of Madrid Jonathan L. Tolstedt, North Dakota
University Faye Navabi, Arizona State University State University
H. E. Dunsmore, Purdue University Parviz Partow-Navid, California State David Vineyard, Kettering University
Robert Duvall, Duke University University, Los Angeles Joseph Vybihal, McGill University
Eman El-Sheikh, University of Kevin O’Gorman, California Xiaoming Wei, Iona College
West Florida Polytechnic State University, San Todd Whittaker, Franklin University
John Fendrich, Bradley University Luis Obispo Robert Willhoft, Roberts Wesleyan
David Freer, Miami Dade College Michael Olan, Richard Stockton College
John Fulton, Franklin University College Lea Wittie, Bucknell University
David Geary, Sabreware, Inc. Kevin Parker, Idaho State University David Womack, University of Texas
Margaret Geroch, Wheeling Jesuit Jim Perry, Ulster County Community at San Antonio
University College David Woolbright, Columbus State
Ahmad Ghafarian, North Georgia Cornel Pokorny, California University
College & State University Polytechnic State University, Catherine Wyman, DeVry University
Rick Giles, Acadia University San Luis Obispo Arthur Yanushka, Christian Brothers
Stacey Grasso, College of San Mateo Roger Priebe, University of Texas, University
Jianchao Han, California State Austin Salih Yurttas, Texas A&M University
University, Dominguez Hills C. Robert Putnam, California State
Lisa Hansen, Western New England University, Northridge
College

bj5_fm_06.indd 14 11/6/12 9:23 PM


Visit https://testbankfan.com
now to explore a rich
collection of testbank or
solution manual and enjoy
exciting offers!
CONTENTS

Preface iii
Special Features xxii

Chapter 1 Introduction 1
1.1 Computer Programs 2
1.2 The Anatomy of a Computer 3
1.3 The Java Programming Language 6
1.4 Becoming Familiar with Your Programming Environment 8
1.5 Analyzing Your First Program 12
1.6 Errors 15
1.7 Problem Solving: Algorithm Design 16

Chapter 2 Using Objects 33

2.1 Objects and Classes 34


2.2 Variables 36
2.3 Calling Methods 43
2.4 Constructing Objects 48
2.5 Accessor and Mutator Methods 50
2.6 The API Documentation 52
2.7 Implementing a Test Program   55
2.8 Object References   57
2.9 Graphical Applications   61
2.10 Ellipses, Lines, Text, and Color   66

Chapter 3 Implementing Classes 81

3.1 Instance Variables and Encapsulation 82


3.2 Specifying the Public Interface of a Class 86
3.3 Providing the Class Implementation 93
3.4 Unit Testing   102
3.5 Problem Solving: Tracing Objects 105
3.6 Local Variables 107
3.7 The this Reference 109
3.8 Shape Classes   112

xv

bj5_fm_05.indd 15 10/18/12 3:25 PM


xvi Contents

Chapter 4 Fundamental Data Types 131


4.1 Numbers 132
4.2 Arithmetic 139
4.3 Input and Output 147
4.4 Problem Solving: First Do it By Hand 154
4.5 Strings 156

Chapter 5 Decisions 179


5.1 The if Statement 180
5.2 Comparing Values 186
5.3 Multiple Alternatives 196
5.4 Nested Branches 200
5.5 Problem Solving: Flowcharts 207
5.6 Problem Solving: Selecting Test Cases   210
5.7 Boolean Variables and Operators 213
5.8 Application: Input Validation 218

Chapter 6 Loops 241


6.1 The while Loop 242
6.2 Problem Solving: Hand-Tracing 249
6.3 The for Loop 254
6.4 The do Loop 262
6.5 Application: Processing Sentinel Values 263
6.6 Problem Solving: Storyboards 269
6.7 Common Loop Algorithms 272
6.8 Nested Loops 279
6.9 Application: Random Numbers and Simulations 283
6.10 Using a Debugger   286

Chapter 7 Arrays and Array Lists 311

7.1 Arrays 312


7.2 The Enhanced for Loop 321
7.3 Common Array Algorithms 322
7.4 Problem Solving: Adapting Algorithms 331
7.5 Problem Solving: Discovering Algorithms by Manipulating
Physical Objects 336
7.6 Two-Dimensional Arrays 340

bj5_fm_05.indd 16 10/18/12 3:25 PM


Contents xvii

7.7 Array Lists 347


7.8 Regression Testing   356

Chapter 8 Designing Classes 379

8.1 Discovering Classes 380


8.2 Designing Good Methods 381
8.3 Problem Solving: Patterns for Object Data 390
8.4 Static Variables and Methods 395
8.5 Packages 400
8.6 Unit Test Frameworks 407

Chapter 9 Inheritance 421


9.1 Inheritance Hierarchies 422
9.2 Implementing Subclasses 426
9.3 Overriding Methods 431
9.4 Polymorphism 437
9.5 Object: The Cosmic Superclass 448

Chapter 10 Interfaces 463

10.1 Using Interfaces for Algorithm Reuse 464


10.2 Working with Interface Variables 471
10.3 The Comparable Interface 473
10.4 Using Interfaces for Callbacks 477
10.5 Inner Classes 481
10.6 Mock Objects 483
10.7 Event Handling 484
10.8 Building Applications with Buttons 490
10.9 Processing Timer Events 494
10.10 Mouse Events 497

Chapter 11 Input/Output and Exception Handling 513

11.1 Reading and Writing Text Files 514


11.2 Text Input and Output 519
11.3 Command Line Arguments 527
11.4 Exception Handling 534
11.5 Application: Handling Input Errors 545

bj5_fm_05.indd 17 10/18/12 3:25 PM


xviii Contents

Chapter 12 Object-Oriented Design 559

12.1 Classes and Their Responsibilities 560


12.2 Relationships Between Classes 563
12.3 Application: Printing an Invoice 569

Chapter 13 RECURSION 587

13.1 Triangle Numbers 588


13.2 Recursive Helper Methods 596
13.3 The Efficiency of Recursion 598
13.4 Permutations 603
13.5 Mutual Recursion 608
13.6 Backtracking 614

Chapter 14 Sorting and searching 629

14.1 Selection Sort 630


14.2 Profiling the Selection Sort Algorithm 633
14.3 Analyzing the Performance of the Selection Sort Algorithm 636
14.4 Merge Sort 641
14.5 Analyzing the Merge Sort Algorithm 644
14.6 Searching 648
14.7 Problem Solving: Estimating the Running Time of an Algorithm 653
14.8 Sorting and Searching in the Java Library 658

Chapter 15 The Java Collections Framework 671

15.1 An Overview of the Collections Framework 672


15.2 Linked Lists 675
15.3 Sets 681
15.4 Maps 686
15.5 Stacks, Queues, and Priority Queues 692
15.6 Stack and Queue Applications 695

Chapter 16 Basic Data Structures 715

16.1 Implementing Linked Lists 716


16.2 Implementing Array Lists 731
16.3 Implementing Stacks and Queues 735
16.4 Implementing a Hash Table 741

bj5_fm_05.indd 18 10/18/12 3:25 PM


Contents xix

Chapter 17 tree Structures 761

17.1 Basic Tree Concepts 762


17.2 Binary Trees 766
17.3 Binary Search Trees 771
17.4 Tree Traversal 780
17.5 Red-Black Trees 786
17.6 Heaps 793
17.7 The Heapsort Algorithm 804

Chapter 18 Generic classes 819

18.1 Generic Classes and Type Parameters 820


18.2 Implementing Generic Types 821
18.3 Generic Methods 825
18.4 Constraining Type Parameters 827
18.5 Type Erasure 831

Chapter 19 Graphical User Interfaces 841

19.1 Layout Management 842


19.2 Processing Text Input 846
19.3 Choices 852
19.4 Menus 863
19.5 Exploring the Swing Documentation 869

Chapter 20 Streams and Binary Input/Output 881

20.1 Readers, Writers, and Streams 882


20.2 Binary Input and Output 883
20.3 Random Access 887
20.4 Object Streams 893

Chapter 21 Multithreading (WEB ONLY)

21.1 Running Threads


21.2 Terminating Threads
21.3 Race Conditions
21.4 Synchronizing Object Access
21.5 Avoiding Deadlocks
21.6 Application: Algorithm Animation

bj5_fm_05.indd 19 10/18/12 3:25 PM


Random documents with unrelated
content Scribd suggests to you:
celebrating the festival of Venus. And forthwith St. Trophimus—the
beloved friend of St. Paul—lifted up his voice and addressed the
laughing, dancing crowd, and suddenly, with a great crash, the
statue of the goddess fell to the earth, and the people were
converted. Encouraged by this rapid discomfiture of one of the most
powerful of the Olympians, the little band dispersed through the
country—St. Eutropius to Orange, St. Saturnin to Toulouse, and St.
Martha to Tarascon to reform the Tarasque, with what success we
shall presently know.
Perhaps it was because the weather had lost its brilliance that Arles
seemed to us a little sad. Its beautiful, poplar-bordered Aliscamps,
the famous avenue of tombs, was scarcely a cheering place to loiter
in at the close of a winter afternoon. It brought home too clearly the
Roman idea of death: sombre, cold, grim, merciless. Sometimes, not
very often, the tombs revealed regret for the dead that appeared
more than conventional; sometimes one seemed to discern,
breathing out of the damp-stained marble, a passion of grief that
was unbearably hopeless; human love beating, beating for ever, with
bleeding hands, against a hateful, unyielding doorway. One had to
hurry past those tombs....
LES ALISCAMPS, ARLES.
By Joseph Pennell.
This avenue is the sole remains of
what was once a very large Roman cemetery, destroyed when the
railway came to the city. Among the tombs was found one of Julia,
daughter of Lucius Tyrannus, proudly representing in sculpture all
the musical instruments on which she could play, among them an
organ, said to be the earliest example known. Marble sarcophagi are
ranged in rows beneath the poplars, leading the eye along the
solemn glade to the church of St. Honorat, another fine example of
Provençal Romanesque, with a bell tower built on lines almost purely
Roman.
St. Virgilius, under whose direction it was erected, had no little
trouble at the beginning of his work. The pillars of the church had
arrived, and were just going to be set up, when the workmen found
that they could not get them lifted, do what they would. The reason
was obvious. They found sitting solidly on the columns a very small
but very determined demon, and budge he would not. He sat there
square and firm, resolved that the obnoxious church should never be
completed if he had any say in the matter. At last, in despair, they
had to send for St. Virgilius, who was Bishop of Arles, and with holy-
water and various exorcisms the obstructive demon was driven away
and the columns triumphantly hoisted into their places, where one
can see them to this day. It seemed to us that that demon had not
altogether departed from the church. The place was gloomy,
uncanny, damp, and unwholesome, but undoubtedly a fine example
of its style.
St. Virgilius, no doubt on account of his saintship, was much beset
by demons and false appearances—a very discouraging feature in
the lives of the saints.
He was one night looking out over the lagoons, when he saw a
phantom ship, and a voice called out saying that the crew was
bound for Jerusalem and had come to take St. Virgilius with them.
But the wary saint replied, "No, thank you; not until I know who you
are!" And he made the sign of the cross, and instantly the ship
became a drift of mist, and rolled away across the water.
This is said to be a version of the legend of the "Flying Dutchman."
It is not surprising that Arles should have had so many splendid
Roman buildings, for not only did it become a Roman colony,[10] but
it was the residence of Roman emperors, and was nicknamed the
Rome of Gaul—Gallula Roma, Arelas.
The museum was rich in relics of the Imperial occupation. There is a
beautiful bust of the Empress Livia among the treasures, and one
exquisite little head of a boy, son of one of the Cæsars, a delicate,
pathetic little face, evidently an individual, not a type.
The collection also boasts a Phœnician tomb which looks as if it
were made yesterday, and some fine reliefs of dancing figures,
decorated foliage, instinct with that quality of beauty, lightness,
magic that the Gods have bestowed upon the art of Greece. This
quality comes into strong evidence in this museum, where there are
Pagan and Christian sarcophagi side by side in large numbers. Fine
as are the earlier Christian sculptures (that is, on tombs before the
withdrawal of protection from Christian cemeteries),[11] they are not
to be compared with the pure pagan work; and the later tombs of
Christian origin are "rude and childish in design and execution."
One can spend hours wandering about the nooks and corners of the
city, loitering by the river-side, where there are the wretched
remains, worse than ruined, of a palace of Constantine; lingering
about the silent theatre where the famous Venus of Arles was found.
Cyril, an enthusiastic deacon, had the building destroyed, knocked
down all the statues and all the noble pillars, of which only two sad
ones are now standing above the ruin.
One might sit for hours unmolested on some fragment of the seats
once so gaily filled with fashionable citizens of the Empire, for
though the ruins are surrounded by houses on three sides there is
little sign of life in those quiet and ancient dwellings of the citizens of
Arles. The fine tower of St. Trophime rises conspicuously behind
them, a true southern tower, square and solid, with the three stories
marked with flat arcading and round-topped windows: simple,
characteristic, with a grave charm which is almost impossible to
define, yet very obvious.

ARLES FROM THE RIVER.


By Joseph Pennell.
The parapet dividing the auditorium from the stage is still standing
here and there, and from this the two columns rise into the air,
supporting even yet a fragment of the entablature on their ornate
capitals.
Cyril, the iconoclastic deacon, had the place smashed up in
indignation at the levity of the performance.
There is little levity now at any rate to trouble any deacon, however
serious! One feels, looking at the desolation, and listening to the
silence—for it is a silence that throbs and cries more loudly than
ever the audience applauded in days gone by—one feels as if the
good Cyril need hardly have troubled himself to interfere so stormily
with the doings of the people. He could not stamp out "human
levity" by knocking down fine columns and statues. He might stamp
out human happiness and the sense of the beautiful, perhaps, and
help to make a coarser, duller race to inhabit the earth. But happily
the "levity" must survive in some form or other, devastate our
deacons never so wisely!

ROMAN THEATER, ARLES.


By E. M. Synge.
CHAPTER XI
SONG, DANCE, AND LEGEND
"At eventide it delighted him much to sit by the blazing fire of fagots
on the hearth and tell us tales of the Reign of Terror, when during the
Revolution he had dug a pit and had hidden there many a poor
fugitive. Then my mother would sing the sweet old Provençal songs,
La Bello Margountoud, L'aucen engabia....
"Ballads and stories would be told by her while I drank in with delight
the wild legends of Provence."—Mistral's Account of his Parents.

CHAPTER XI
SONG, DANCE, AND LEGEND
There are so many famous things connected with Provence that one
never comes to the end of them. There are dances and festivals and
fires on St. John's Eve in honour of Baal (as there are, or were till
quite lately, in Scotland). There are rich wines and the far-famed
bouillabaisse, a dish of fish of mixed sorts, boiled with saffron, and,
to feminine palates, extremely nasty!
Great was our delight to see, in passing a side-road leading to a
small hostelry, a sign-board with the mystic word printed in
triumphant letters. This was local colour indeed! Our enthusiasm
rose to boiling-point; I doubt if even our critical friend could have
chilled us at that moment.
Here was Provence and bouillabaisse; nothing disappointing; the
concoction not one whit less nauseous than one might have
expected!
Dumas writes with ardour about the dish:—
"While polenta and macaroni possess all the characteristics of
primitive and antediluvian simplicity, bouillabaisse is the result of the
most advanced state of culinary civilisation; comprising in itself a
whole epic of unexpected episodes and extraordinary incidents."

The celebrated wines of Chateauneuf-des-Papes, Sainte Baume, and


others I doubt if we tasted; but all the wines seemed ambrosial to
us; especially when it was "weather for singing the Peyrenolle," a
very ancient song of which only the name remains in this saying of
the people.
The dance of the farandole is of Greek origin and must be infinitely
graceful, but alas! we only heard of it, never saw it danced. The
dancers join hands to form chains, each chain led by a man or a
woman, who plays a merry air on the gaboulet. These chains,
following their leaders, then form into lines, passing rapidly before
one another in contrary directions—like divergent currents—dancing
in time to the music. And then they swing off into circles and dance
round and round maypoles and walnut-trees, till the whole place is
wild with merriment. On occasions of great rejoicing the people used
to dance the farandole through the streets, all joining in the whirling
circles, rich and poor. It was like a wind of joy flying through the
city!
The people of Provence have also some Saracen dances,
bequeathed to them by that marauding people when they lived in
the Mountains of the Moors, in their rock-set fortresses: Li Mouresco
and lis Ouliveto, which was danced after the olive harvest.
This pervasive characteristic of dance and song for which Provence is
so famous, doubtless springs from the fact that this people have
never ceased to be pagans.
The clergy of the Middle Ages in vain tried to suppress this element.
There are strange stories of the mingling of ancient customs and
diversions with Christian ceremonies: dancing and songs, the
antique chorus, and love-poems sung or recited in the very
churches; ecclesiastical discipline being far less stringent in the south
than in the north of France, where classic influences had been
weaker. Religion was associated in the minds of the Provençals with
gaiety and festivals; and the clergy, in order to attract and retain the
people, had found it necessary to recognise this pagan spirit which
took its origin in far-off generations when the Greeks founded
Marseilles and its numerous off-shoots; when for five and a half
centuries the Romans ruled and civilised the country. In the ninth
and tenth centuries, moreover, the clergy and the people of the
south were more or less closely assimilated, and this touch of
paganism in the priesthood made possible what at first sight
challenges belief.
At Limoges, for instance, during the feast of St. Martial, the people
used to substitute for the words of the Latin liturgy some original
couplets in the Romance tongue: "St. Martial, pray for us, and we
will dance for you," and they furthermore broke out into a dance in
the church, without the faintest sense of incongruity; for to these
people worship, song, and rhythmic movement were parts of one
and the same impulse.
And—if one comes to that—on what ground have they been
divorced?
The feast of Flora was celebrated in Provence till the sixteenth
century, when it was suppressed; the "mimes" and actors of
antiquity were familiar figures of the Middle Ages; among them a
class of women jongleurs who went about from city to city; and the
wild feast of the Lupercal is said to have had its mediæval
representative in this essentially pagan land.
This was the epoch when Latin had about ceased to be a living
tongue, and from its corpse, so to speak, had arisen a multitude of
dialects all over the Roman world, among them the Romance or
Provençal, the Langue d'Oc, in which poems and legends were now
written. Authors at this time were nearly always monks, but they
treated their subjects with much freedom, as, for instance, in the
Vision of St. Paul,[12] who descends to the Infernal Regions to visit
the "cantons of hell" and to see the luckless sinners in their misery,
each tormented appropriately according to the nature of their
transgression. The poem was evidently a crude forerunner of the
Divine Comedy.
From this popular literature the troubadour poetry of the next
centuries sprang, without, however, extinguishing its predecessors,
which continued to exist side by side with the new forms of art.
That character makes destiny is very clearly evidenced in Provençal
history. This rich, eventful, romantic story is just what a people
renowned for bonté d'esprit, grace, good looks, poetry, eloquence,
sentiment, passion, must inevitably weave for themselves in the
course of ages. From the time when paleolithic man was making
rude stone implements and living in caves or holes in the earth, this
country has been busily forming and developing the human body
and soul, perhaps in a more clear and visible sequence of progress
that can easily be traced elsewhere.
The variety and persistence of ancient legends and customs serves
to indicate the road of evolution from stage to stage with
picturesque vividness. The prehistoric is not far off in this land,
where Time loses its illusory quality and seems to assume the
character that all philosophers attribute to it when they speak of the
Eternal Now.
The mountains contiguous to the mountains of the Moors, the
beautiful Esterelles, so familiar to visitors on the Riviera, have a
legend of a fairy Estelle, or Esterella, who used to be worshipped
there and to receive sacrifices. The woodcutters dread the
apparition. Her smile is of such unearthly beauty that any man who
sees her is so fascinated that he is for ever drawn by a resistless
longing to find her again, and some "have spent years leaping from
crag to crag, while others have wandered away to lead the life of a
hermit in forest shades." Is this a myth typifying the search after the
Ideal and the Beautiful?
The Incourdoules have their Golden Goat which haunts the most
inaccessible fastnesses, living in a cavern full of precious stones and
treasure.[13]
One day a mysterious man appeared and began to build a
cabanoun, or hut, in a lonely spot. He wore a sheepskin, red turban,
and blue sash; and when a woodcutter spoke to him he laughed
mockingly and cried:—

"Taragnigna, Taragnigna!
Fai attension a la mouissara.
Vau a la vigna,
Vau a la vigna—
Vai-ti-pia!
Vai-ti-pia!
Taragnigna mia!"
("Cobweb! cobweb!
Mark that spy!
I am going to the vineyard.
I am going to the vineyard.
We are in danger—we are lost!
Cobweb mine!")

Whereupon an enormous black spider came swinging from the


branch of a pine, with menacing looks. The woodcutter said it was
as large as a tesa-negra (blackhead or linnet). He flees in horror, but
can't resist returning on the morrow to the mysterious cabanoun. He
feels a shivering feeling creep over him as he approaches, and is
again greeted by a burst of laughter. "Ha, ha, ha, mon vieux, toccan
li cique sardino ensen" ("Let us touch the five sardines together,
neighbour," i.e., shake hands—common Provençal expression).

"Taragnigna! Taragnigna!
Fai attension a moun Vesin!"

and the great spider fixed his eyes on Sieur Guizol, the woodcutter,
and ran nimbly down its silken cord. Then the strange host comes
down from among the rafters and begins to talk. Finally, he tells his
guest that he has come to seek the Cabro d'Or, and breaks out
again in a wild song—"Taragnigna, you and I are going to make our
fortunes."
"Barba Garibo, e giorno, leve vo!
Porte de zenzibo,
Dame do a tre mério.
Un ome come vo
Ch' ha vist tante cause
E ben giust che se repause
Che vos par d'aisso?
Barba Garibo! Barba Garibo!"

("Uncle Garibo! it is day, arouse thyself!


Bring dry raisins,
Two or three small new potatoes—
A man like you,
Who so many things hast seen,
It is most just he should repose himself.
What think you of it? What think you of it?
Uncle Garibo! Uncle Garibo!")

And the spider seemed to dance in a wild ecstasy, vibrating on his


line with immense impetus, quite close to Sieur Guizol's face.
Then Guizol asks if his host really believes in the Golden Goat, and
the man addresses the spider indignantly.
"Ha! dost thou hear him Taragnigna? He doubts that the Cabro d'Or
lives here! But he won't doubt when he gets some of his gold!"
And then he goes on to say that after that he will marry Guizol's
daughter, Rosette, and they will all go down to the woodcutter's
home, and the spider shall dance Li Mouresco every night.
"And thou shall give us lis Ouliveto," he adds, addressing the
formidable insect; "for the Sieur does not know perhaps that I am a
cornamousaire."
He draws out a bagpipe and commences to play.
"What, brave ome! art thou going to dance? Now let me see if you
have forgotten the farandole," and the musician lilted up a wild
fantastic tune, "and Sieur Guizol's feet began to keep time to the
music, and anon faster and faster as the player played, faster and
faster poor Guizol danced, while the spider swung about as though
in rapture."
Thus the poor woodcutter is drawn under the will of the recluse and
his spider, and night after night, against his better judgment, against
his wish, he goes to meet the sorcerer at the hole in the mountain
where the Golden Goat guards his treasure.

Guizol is set to work to excavate, the other watching and holding


aloft two pine-torches. Fortunately for Guizol, Gastoun, the lover of
Rosette, had followed him one night, wondering uneasily at his
regular absences from home. Suddenly the gold-seeker leaps up,
seeing a flag of stone.
"The treasure!" he yells. There is not a moment to lose, for if they
do not get the gold before the goat awakes, the chance is over.
"Oh, thou dear little bletta oulivié" (olive rod used for gold finding),
"thou didst not deceive me after all," the man shouts, pouncing on a
vase and other buried objects. They begin to find the gold, when the
sorcerer suddenly takes an iron bar and knocks down his companion
and thrusts him into the hole crying, "Gold, gold, all mine now!"
But Gastoun rushes in and the two engage in a death-wrestle in the
pitch darkness.
"Lo cabro d'or, lo dian!" screams the man and rushes away past his
foe, who is dressed in a goat-skin; and so finally the story ends
happily with the rescue of the stunned Guizol and the betrothal of
Gastoun and Rosette.
When Gastoun afterwards visited the cabanoun of the recluse, he
found it all burnt and a blackened skull lying among the stones. "A
rustling sound was heard and a huge black spider ran hastily across
the stones and climbed on the dead man's skull," fixing its eyes on
the intruder. Then it shot out its line and wafted itself to the few
half-burnt rafters, "and there it swung round and round in a perfect
gavotte." And for many a day after, as it was rumoured in the
mountains, there were strange sounds at nightfall from the ruined
cabanoun, and the peasants said they heard the drone and cry of
the cornemuse and saw a skeleton seated on a stone playing a
horrible dance.
This story—founded on a legend that is said to exist in some form or
other all over the world—affords a quick picture of the place and the
people; but it is further remarkable as a story which seems founded
on some case of mesmeric power, probably by no means uncommon
among these mountaineers, a Celtic people, it is said, and perhaps
for that reason especially sensitive to this mysterious force.
There is a version of the legend at Nice in which the treasure-
chamber is under the bed of the Paglion. On a round table a life-
sized gold goat and kid are watched over by an exemplary demon
who takes only an hour's sleep out of the twenty-four. If a bold
adventurer can then creep in and blow the golden trumpet that the
demon is so ill-advised as to keep handy for the purpose at his side,
that imprudent spirit is forced to remain fixed to the chair, while a
swarm of little goblins come trooping in to offer their services in
carrying the treasure to any spot that the seeker may decide.
The entrance to this treasure-chamber is the house of a magician
between the Tina dei Pagani (the Pagan's Wine-vat, or Roman
amphitheatre) and the temple of Apollo, at Cimiez. The district is
somewhat haunted by demons and the sort of society that they
frequent. The Witches' Rock, rising high beyond Mont Chauve in
inaccessible crags, was dear to the uncanny crew, and it was here
they danced their "unearthly reels."
On the Rocca di Dom at Avignon witches and wizards (masc and
masco) used to assemble in the far-off days when there were only a
few windmills built upon the rock.
The story of the Hunchback of the Rocca di Dom is told of other
places also, but it seems to suit this spot better than any. Duncan
Craig gives a picturesque version of it.
The hunchback wandered up one night when the mistral was
thundering over the hill, setting the sails of the windmills tearing
madly round. And the moonlight was shining on the rock, calm
through all the tumult. The man can have had no tendency to
insomnia, for he fell fast asleep in the uproar, and when he woke it
was to sounds of barbaric music and the clashing of cymbals. And
presently La Rocca was alive with a crowd of faces, high-crowned
conical hats, black satins and silks; and to the great scandalisation of
the watcher, grave and respected citizens of Avignon arm-in-arm
with the witches. And they were all dancing as hard as they could
dance, and the dust raised by the mistral whirled with them, and the
windmill sails tore round scrooping and creaking. New arrivals would
come on the scene, and these would receive strange salutations.
"Bon Vèspre, Cousin Chin!" ("Good evening, cousin dog.") "Bono
sero, Cousin Cat!" "Bono niue, Coumpaire Loup!" ("Good-night,
gossip Wolf.") "Coume vai, Misè Limace?" ("How are you, Mistress
Snail?") "Pas maw, pas maw, Cousin Jano."
And so they danced to their Saracenic music, and presently they
began to sing together a curious doggerel:—
"Dilun, Dimars e Demecre tres! Dilun, Dimars e Demecre tres!"
("Monday, Tuesday, and Wednesday, three.") And they sang it over
and over and over again.
At last this seems to have got upon the poor man's nerves, for
suddenly he starts up and shouts—
"Dijou, Divendre, e Dissate, sieis." ("Thursday, Friday, and Saturday,
six.")
"Oh, lou brave gibous!" shriek the witches in chorus. "The dear
hunchback has come up here to complete our verse for us; Zou, we
will make a man of him."
And they come towards him in a whirling circle, dancing round and
round him till he is dazed and dazzled and seems to lose
consciousness, when suddenly he finds himself breathless on the
rock alone and—straight as a pine!
Another hunchback, hearing of this strange cure, went up to La
Rocca on a night of storm, all ready to finish the witches' rhyme for
them. This time it was:—

"Dilun, Dimars, e Demecre tres,


Dijou, Divendre, e Dissate sieis."

"E Dimenche, set," cried the hunchback, with enthusiasm.


Whereupon there was an awful howl and a great shudder that
convulsed all the wicked crew.
"Who dares to speak of the Holy Day in these our revels?" a voice
asked.
"Es lou gibous, lou marrit gibous! Zou, la gibo, la gibo. Gibo davans,
gibo darriè!"
And the luckless man found that, so far from being cured, he was
now doubly deformed—the old hump on the back and a new one on
the chest—through the malicious sorcery of the witches of La Rocca.
Provence is full of proverbs and quaint sayings, many of them very
like our own country saws about the weather and so forth.

"Ne per Magio, ne per Magiàn,


Non te leva o pelicàn."

("Neither for May, nor for warmest May,


Your winter coat should you take away.")

"Se Febraro non febregia


Mars marsegia."

("If February be not cold


March will pierce the young and old.")

"Non est tout or che relus," is our old friend, "All is not gold that
glitters."
There is a Nizard proverb very neatly put. "Experience keeps a
school: and it is the only one where thoughtless men will learn."
Another saying expresses an all too common fate in a few words: "A
dou mau de la cabro de Moussu Sequin, que se bategue touto la
niue 'me lou loup, e piei lou matin, lou loup la manje."
("He had the bad fortune of Monsieur Sequin's goat, which fought all
night with the wolf, and then the wolf eat him in the morning.")
There are many madrigals and songs of all sorts, all of them
characteristic; most of them inexpressibly charming. Perhaps the
best known is Magali, a quaint and tender expression of undying
love which death itself cannot daunt. Magali persistently refuses and
flees from the love of her adorer, who declares he will follow her
even to the grave.
The following few quatrains taken here and there, will give the
character of the poem:—

"Less than the sound of wind that murmurs


Care I for thee or heed thy lay;
I'll be an eel, and in the ocean
Through the blue waters glide away."

"O Magali, if thou dost turn


Eel in the ocean,
Then 'tis a fisher I will be
And fish for thee."

"If in the sea thy net thou castest


And in its toils I fall a prey,
I'll be a bird, and to the forest
On my light pinions fly away."

"O Magali, if thou dost turn


Fowl in the forest,
Then 'tis a fowler I will be
And capture thee."

"Vain is thy passion, vain thy pursuit,


Never a moment shall I stay,
But in some oak's rough bark I'll guise me,
And in the dark woods hide away."
"O Magali, if thou dost turn
Oak in the forest,
Then 'tis the ivy I will be,
And cling to thee."
"Should'st thou once pass yon convent's portals,
Naught shalt thou find but lifeless clay;
Round me the white-veiled sisters weeping,
As in the grave my corpse they lay."

"O Magali, when thou, alas!


Art dead and silent,
I'll be the earth that buries thee:
Then mine thou'lt be."

"Now I believe no mocking mean'st thou;


Faithful thy vows; my heart they move,
Take from mine arm this crystal bangle,
Wear it in token of my love."

"O Magali, see how the stars


That bright were shining
Now thou art come, O Magali,
Turn pale and flee."[14]

It is most singular what an effect of song there is everywhere in this


country. The rivers seem to sing as they flow; the tall yellow reeds
sing as the wind stirs them; the olives have a little whispered canzo
of their own, and the mistral—even he roars a sort of rough baritone
in the general concert. No wonder the troubadours were born in this
most lyrical of lands.
They had songs for every possible occasion: the morning song or
aubade, the serena or evening song, the canzo or love-song, the
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!

ebookluna.com

You might also like