Immediate download Java Programming 7th Edition Joyce Farrell ebooks 2024
Immediate download Java Programming 7th Edition Joyce Farrell ebooks 2024
https://ebookultra.com
https://ebookultra.com/download/java-
programming-7th-edition-joyce-farrell/
https://ebookultra.com/download/java-programming-8th-edition-joyce-
farrell/
ebookultra.com
https://ebookultra.com/download/programming-logic-and-design-
comprehensive-6th-edition-joyce-farrell/
ebookultra.com
https://ebookultra.com/download/java-programs-to-accompany-
programming-logic-and-design-7th-edition-jo-ann-smith/
ebookultra.com
https://ebookultra.com/download/computer-programming-for-teens-1st-
edition-mary-e-farrell/
ebookultra.com
Advanced Java Game Programming Wallace Croft
https://ebookultra.com/download/advanced-java-game-programming-
wallace-croft/
ebookultra.com
https://ebookultra.com/download/java-programming-10-minute-
solutions-1st-edition-mark-watson/
ebookultra.com
https://ebookultra.com/download/killer-game-programming-in-java-1st-
edition-andrew-davison/
ebookultra.com
https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/
ebookultra.com
https://ebookultra.com/download/the-java-tm-programming-language-4th-
edition-ken-arnold/
ebookultra.com
Java Programming 7th Edition Joyce Farrell Digital
Instant Download
Author(s): Joyce Farrell
ISBN(s): 9781285081953, 1285081951
Edition: 7
File Details: PDF, 32.45 MB
Year: 2014
Language: english
Buy. Rent. Access.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
TM
JAVA PROGRAMMING
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
SEVENTH EDITION
TM
JAVA PROGRAMMING
JOYCE FARRELL
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Java Programming, © 2014 Course Technology, Cengage Learning
Seventh Edition
ALL RIGHTS RESERVED. No part of this work covered by the copyright
Joyce Farrell
herein may be reproduced, transmitted, stored, or used in any form or
Executive Editor: by any means—graphic, electronic, or mechanical, including but not
Kathleen McMahon limited to photocopying, recording, scanning, digitizing, taping, Web
distribution, information networks, or information storage and
Senior Product Manager: retrieval systems, except as permitted under Section 107 or 108 of the
Alyssa Pratt 1976 United States Copyright Act, without the prior written
Development Editor: Dan Seiter permission of the publisher.
Editorial Assistant: Sarah Ryan
Brand Manager: Kay Stefanski For product information and technology assistance, contact us at
Print Buyer: Julio Esperas Cengage Learning Customer & Sales Support, 1-800-354-9706
Art and Design Direction, For permission to use material from this text or product,
Production Management, and submit all requests online at www.cengage.com/permissions.
Composition: Integra Software
Further permissions questions can be emailed to
Services Pvt. Ltd.
permissionrequest@cengage.com.
Cover Designer: Lisa Kuhn/Curio
Press, LLC www.curiopress.com
Cover Photo: © Leigh Prather/Veer Library of Congress Control Number: 2012953690
Copyeditor: Mark Goodin Student Edition:
Proofreader: Pamela Hunt ISBN-13: 978-1-285-08195-3
Indexer: Alexandra Nickerson ISBN-10: 1-285-08195-1
Course Technology
20 Channel Center Street
Boston, MA 02210
USA
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial
review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to
remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous
editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by
ISBN#, author, title, or keyword for materials in your areas of interest.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Brief Contents
v
Preface . . . . . . . . . . . . . . . . . . . . . . xxi
CHAPTER 1 Creating Java Programs . . . . . . . . . . . . . . . . 1
CHAPTER 2 Using Data . . . . . . . . . . . . . . . . . . . . . 51
CHAPTER 3 Using Methods, Classes, and Objects . . . . . . . 117
CHAPTER 4 More Object Concepts . . . . . . . . . . . . . . . 179
CHAPTER 5 Making Decisions . . . . . . . . . . . . . . . . . 241
CHAPTER 6 Looping . . . . . . . . . . . . . . . . . . . . . 299
CHAPTER 7 Characters, Strings, and the StringBuilder . . . . . 349
CHAPTER 8 Arrays . . . . . . . . . . . . . . . . . . . . . . 397
CHAPTER 9 Advanced Array Concepts . . . . . . . . . . . . . 443
CHAPTER 10 Introduction to Inheritance . . . . . . . . . . . . . 499
CHAPTER 11 Advanced Inheri tance Concepts . . . . . . . . . . 547
CHAPTER 12 Exception Handling . . . . . . . . . . . . . . . . 603
CHAPTER 13 File Input and Output . . . . . . . . . . . . . . . 675
CHAPTER 14 Introduction to Swing Components . . . . . . . . 739
CHAPTER 15 Advanced GUI Topics . . . . . . . . . . . . . . . 801
CHAPTER 16 Graphics . . . . . . . . . . . . . . . . . . . . . 879
CHAPTER 17 Applets, Images, and Sound . . . . . . . . . . . . 945
APPENDIX A Working with the Java Platform . . . . . . . . . . . 993
APPENDIX B Learning About Data Representation . . . . . . . 1001
APPENDIX C Formatting Output . . . . . . . . . . . . . . . 1009
APPENDIX D Generating Random Numbers . . . . . . . . . . 1021
APPENDIX E Javadoc . . . . . . . . . . . . . . . . . . . . 1029
Glossary . . . . . . . . . . . . . . . . . . . . 1037
Index . . . . . . . . . . . . . . . . . . . . . . 1063
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents
vi
Preface . . . . . . . . . . . . . . . . . . xxi
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter Summary . . . . . . . . . . . . . . . . . . . . . . 44
Review Questions . . . . . . . . . . . . . . . . . . . . . . 45
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 47
Programming Exercises . . . . . . . . . . . . . . . . . . 47
Debugging Exercises . . . . . . . . . . . . . . . . . . . 49 vii
Game Zone . . . . . . . . . . . . . . . . . . . . . . . . 49
Case Problems . . . . . . . . . . . . . . . . . . . . . . 50
C H AP T E R 2 Using Data . . . . . . . . . . . . . . . . . 51
Declaring and Using Constants and Variables . . . . . . . . . . 52
Declaring Variables . . . . . . . . . . . . . . . . . . . . 53
Declaring Named Constants . . . . . . . . . . . . . . . . 54
The Scope of Variables and Constants . . . . . . . . . . . . 56
Concatenating Strings to Variables and Constants . . . . . . . 56
Pitfall: Forgetting That a Variable Holds One Value at a Time . . . 58
Learning About Integer Data Types . . . . . . . . . . . . . . 62
Using the boolean Data Type . . . . . . . . . . . . . . . . 67
Learning About Floating-Point Data Types . . . . . . . . . . . . 69
Using the char Data Type . . . . . . . . . . . . . . . . . . 70
Using the Scanner Class to Accept Keyboard Input . . . . . . . 76
Pitfall: Using nextLine() Following One of the
Other Scanner Input Methods . . . . . . . . . . . . . . 79
Using the JOptionPane Class to Accept GUI Input . . . . . . . 85
Using Input Dialog Boxes . . . . . . . . . . . . . . . . . . 85
Using Confirm Dialog Boxes . . . . . . . . . . . . . . . . 89
Performing Arithmetic . . . . . . . . . . . . . . . . . . . . 91
Associativity and Precedence . . . . . . . . . . . . . . . . 93
Writing Arithmetic Statements Efficiently . . . . . . . . . . . 94
Pitfall: Not Understanding Imprecision in
Floating-Point Numbers . . . . . . . . . . . . . . . . . 94
Understanding Type Conversion . . . . . . . . . . . . . . . . 99
Automatic Type Conversion . . . . . . . . . . . . . . . . . 99
Explicit Type Conversions . . . . . . . . . . . . . . . . 100
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 104
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 105
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 109
Review Questions . . . . . . . . . . . . . . . . . . . . . 109
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 112
Programming Exercises . . . . . . . . . . . . . . . . . 112
Debugging Exercises . . . . . . . . . . . . . . . . . . 115
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 115
viii Case Problems . . . . . . . . . . . . . . . . . . . . . 116
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
C H AP T E R 4 More Object Concepts . . . . . . . . . . . 179
Understanding Blocks and Scope . . . . . . . . . . . . . . 180
Overloading a Method . . . . . . . . . . . . . . . . . . . 188
Automatic Type Promotion in Method Calls . . . . . . . . . 190
Learning About Ambiguity . . . . . . . . . . . . . . . . . 195 ix
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
C H AP T E R 6 Looping . . . . . . . . . . . . . . . . . 299
Learning About the Loop Structure . . . . . . . . . . . . . . 300
Creating while Loops . . . . . . . . . . . . . . . . . . 301
Writing a Definite while Loop . . . . . . . . . . . . . . 301
Pitfall: Failing to Alter the Loop Control Variable Within
the Loop Body . . . . . . . . . . . . . . . . . . . . 303
Pitfall: Creating a Loop with an Empty Body . . . . . . . . . 304
Altering a Definite Loop’s Control Variable . . . . . . . . . . 305
Writing an Indefinite while Loop . . . . . . . . . . . . . 306
Validating Data . . . . . . . . . . . . . . . . . . . . . 308
Using Shortcut Arithmetic Operators . . . . . . . . . . . . . 312
Creating a for Loop . . . . . . . . . . . . . . . . . . . 317
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Learning How and When to Use a do … while Loop . . . . . . 321
Learning About Nested Loops . . . . . . . . . . . . . . . . 324
Improving Loop Performance . . . . . . . . . . . . . . . . 329
Avoiding Unnecessary Operations . . . . . . . . . . . . . 329
Considering the Order of Evaluation of Short-Circuit Operators . 330 xi
Comparing to Zero . . . . . . . . . . . . . . . . . . . 331
Employing Loop Fusion . . . . . . . . . . . . . . . . . . 332
Using Prefix Incrementing Rather than Postfix Incrementing . . 332
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 337
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 337
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 339
Review Questions . . . . . . . . . . . . . . . . . . . . . 339
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 342
Programming Exercises . . . . . . . . . . . . . . . . . 342
Debugging Exercises . . . . . . . . . . . . . . . . . . 346
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 346
Case Problems . . . . . . . . . . . . . . . . . . . . . 348
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
C H AP T E R 8 Arrays . . . . . . . . . . . . . . . . . . 397
Declaring Arrays . . . . . . . . . . . . . . . . . . . . . 398
Initializing an Array . . . . . . . . . . . . . . . . . . . . 403
Using Variable Subscripts with an Array . . . . . . . . . . . . 406
xii Using Part of an Array . . . . . . . . . . . . . . . . . . 408
Declaring and Using Arrays of Objects . . . . . . . . . . . . 410
Using the Enhanced for Loop with Objects . . . . . . . . . 412
Manipulating Arrays of Strings . . . . . . . . . . . . . 412
Searching an Array and Using Parallel Arrays . . . . . . . . . 418
Using Parallel Arrays . . . . . . . . . . . . . . . . . . . 418
Searching an Array for a Range Match . . . . . . . . . . . 421
Passing Arrays to and Returning Arrays from Methods . . . . . 425
Returning an Array from a Method . . . . . . . . . . . . . 429
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 431
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 431
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 432
Review Questions . . . . . . . . . . . . . . . . . . . . . 433
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 436
Programming Exercises . . . . . . . . . . . . . . . . . 436
Debugging Exercises . . . . . . . . . . . . . . . . . . 439
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 439
Case Problems . . . . . . . . . . . . . . . . . . . . . 441
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
C H AP T E R 1 6 Graphics . . . . . . . . . . . . . . . . . 879
Learning About the paint() and repaint() Methods . . . . 880
Using the setLocation() Method . . . . . . . . . . . . 882
Creating Graphics Objects . . . . . . . . . . . . . . . 884
Using the drawString() Method . . . . . . . . . . . . . 885
Using the setFont() and setColor() Methods . . . . . 886
Using Color . . . . . . . . . . . . . . . . . . . . . . 887
Drawing Lines and Shapes . . . . . . . . . . . . . . . . . 893
Drawing Lines . . . . . . . . . . . . . . . . . . . . . 893
Drawing Rectangles . . . . . . . . . . . . . . . . . . . 894
Creating Shadowed Rectangles . . . . . . . . . . . . . . 897
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Adding Sound to JApplets . . . . . . . . . . . . . . . . 977
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 980
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 980
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 981
Review Questions . . . . . . . . . . . . . . . . . . . . . 982 xix
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 985
Programming Exercises . . . . . . . . . . . . . . . . . 985
Debugging Exercises . . . . . . . . . . . . . . . . . . 987
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 988
Case Problems . . . . . . . . . . . . . . . . . . . . . 992
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
A PP E N D I X E Javadoc . . . . . . . . . . . . . . . . 1029
The Javadoc Documentation Generator . . . . . . . . . . . . 1030
Javadoc Comment Types . . . . . . . . . . . . . . . . . . 1030
Generating Javadoc Documentation . . . . . . . . . . . . . 1032
Specifying Visibility of Javadoc Documentation . . . . . . . . 1035
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 1036
Glossary . . . . . . . . . . . . . . . . 1037
Index . . . . . . . . . . . . . . . . . . 1063
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
xxi
Java Programming, Seventh Edition, provides the beginning programmer with a guide to
developing applications using the Java programming language. Java is popular among
professional programmers because it can be used to build visually interesting graphical user
interface (GUI) and Web-based applications. Java also provides an excellent environment for
the beginning programmer—a student can quickly build useful programs while learning the
basics of structured and object-oriented programming techniques.
This textbook assumes that you have little or no programming experience. This book
provides a solid background in good object-oriented programming techniques and introduces
terminology using clear, familiar language. The writing is nontechnical and emphasizes good
programming practices. The programming examples are business examples; they do not
assume a mathematical background beyond high-school business math. In addition, the
examples illustrate only one or two major points; they do not contain so many features
that you become lost following irrelevant and extraneous details. The explanations in this
textbook are written clearly in straightforward sentences, making it easier for native and
non-native English speakers alike to master the programming concepts. Complete, working
programs appear frequently in each chapter; these examples help students make the
transition from the theoretical to the practical. The code presented in each chapter can also
be downloaded from the publisher’s Web site, so students can easily run the programs and
experiment with changes to them.
The student using Java Programming, Seventh Edition, builds applications from the bottom
up rather than starting with existing objects. This facilitates a deeper understanding of the
concepts used in object-oriented programming and engenders appreciation for the existing
objects students use as their knowledge of the language advances. When students complete
this book, they will know how to modify and create simple Java programs, and they will have
the tools to create more complex examples. They also will have a fundamental knowledge of
object-oriented programming, which will serve them well in advanced Java courses or in
studying other object-oriented languages such as C++, C#, and Visual Basic.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE Features
Chapters 5 and 6 explore input and repetition structures, which are the backbone of
programming logic and essential to creating useful programs in any language. You learn the
special considerations of string and array manipulation in Chapters 7, 8, and 9.
Chapters 10, 11, and 12 thoroughly cover inheritance and exception handling. Inheritance is
the object-oriented concept that allows you to develop new objects quickly by adapting the
xxii
features of existing objects; exception handling is the object-oriented approach to handling
errors. Both are important concepts in object-oriented design. Chapter 13 provides
information on handling files so you can permanently store and retrieve program output.
Chapters 14 and 15 introduce GUI Swing components—Java’s visually pleasing, user-friendly
widgets—and their layout managers. Chapters 16 and 17 show you ways to provide
interactive excitement using graphics, applets, images, and sound.
Features
The following features are new for the Seventh Edition:
l YOU DO IT: In each chapter, step-by-step exercises help students create multiple working
programs that emphasize the logic a programmer uses in choosing statements to include.
These sections provide a means for students to achieve success on their own—even those
in online or distance learning classes. Previous editions of the book contained a long,
multipart “You Do It” section at the end of each chapter, but in this edition, more and
shorter sections follow important chapter topics so the student can focus on one new
concept at a time.
l CASES: Each chapter contains two running case problems. These cases represent projects
that continue to grow throughout a semester using concepts learned in each new chapter.
Two cases allow instructors to assign different cases in alternate semesters or to divide
students in a class into two case teams.
l PROGRAMMING EXERCISES: Each chapter concludes with meaningful programming
exercises that provide additional practice of the skills and concepts learned in the chapter.
These exercises vary in difficulty and are designed to allow exploration of logical
programming concepts. Each chapter contains several new programming exercises not
seen in previous editions.
l INCREASED EMPHASIS ON STUDENT RESEARCH: In this edition, the student frequently
is directed to the Java Web site to investigate classes and methods. Computer languages
evolve, and programming professionals must understand how to find the latest language
improvements. This book encourages independent research.
Additionally, Java Programming, Seventh Edition, includes the following features:
l OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that will
be presented in the chapter. In addition to providing a quick reference to topics covered,
this feature provides a useful study aid.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE Instructor Resources
l APPENDICES: This edition includes useful appendices on working with the Java platform,
data representation, formatting output, generating random numbers, and creating Javadoc
comments.
l QUALITY: Every program example, exercise, and game solution was tested by the author
and then tested again by a quality assurance team using Java Standard Edition (SE) 7, the
xxiv
most recent version available.
CourseMate
The more you study, the better the results. Make the most of your study time by accessing
everything you need to succeed in one place. Read your textbook, take notes, review
flashcards, watch videos, and take practice quizzes online. CourseMate goes beyond the book
to deliver what you need! Learn more at www.cengage.com/coursemate.
The Java Programming CourseMate includes:
l Debugging Exercises: Four error-filled programs accompany each chapter. By
debugging these programs, students can gain expertise in program logic in general and the
Java programming language in particular.
l Video Lessons: Each chapter is accompanied by at least three video lessons that help to
explain important chapter concepts. These videos were created and narrated by the
author.
l Interactive Study Aids: An interactive eBook, quizzes, flashcards, and more!
Instructors may add CourseMate to the textbook package, or students may purchase
CourseMate directly at www.CengageBrain.com.
Instructor Resources
The following teaching tools are available for download at our Instructor Companion Site.
Simply search for this text at login.cengage.com. An instructor login is required.
l Electronic Instructor’s Manual: The Instructor’s Manual that accompanies this
textbook includes additional instructional material to assist in class preparation, including
items such as Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class
Discussion Topics, Additional Projects, Additional Resources, and Key Terms. A sample
syllabus is also available. Additional exercises in the Instructor’s Manual include:
Tough Questions: Two or more fairly difficult questions that an applicant might
encounter in a technical job interview accompany each chapter. These questions are
often open-ended; some involve coding and others might involve research.
Up for Discussion: A few thought-provoking questions concerning programming in
general or Java in particular supplement each chapter. The questions can be used to
start classroom or online discussions, or to develop and encourage research, writing,
and language skills.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Acknowledgements
Acknowledgements
I would like to thank all of the people who helped to make this book a reality, including Dan
Seiter, Development Editor; Alyssa Pratt, Senior Product Manager; Sreejith Govindan,
Content Project Manager; and Chris Scriver and Serge Palladino, Quality Assurance Testers.
I am lucky to work with these professionals who are dedicated to producing high-quality
instructional materials.
I am also grateful to the reviewers who provided comments and encouragement during this
book’s development, including Lee Cottrell, Bradford School, Pittsburgh; Irene Edge, Kent
State University; Susan Peterson, Henry Ford Community College; and Jackie Turner, Central
Georgia Technical College.
Thanks, too, to my husband, Geoff, for his constant support and encouragement. Finally, this
book is dedicated to Ruth LaFreniere, who brought us Stella, and Bob LaFreniere, who let her.
Joyce Farrell
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Read This Before
xxvi
You Begin
The following information will help you as you prepare to use this textbook.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features
This text focuses on helping students become better programmers and understand
Java program development through a variety of key features. In addition to chapter
Objectives, Summaries, and Key Terms, these useful features will help students
regardless of their learning styles. xxvii
NOTES provide
additional information—
for example, another
location in the book that
expands on a topic, or a
common error to watch
out for.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
FEATURES
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Assessment
I find the flow of information superior
to [that of] other texts.
PROGRAMMING EXERCISES provide
—Susan Peterson,
opportunities to practice concepts. These xxix
Henry Ford Community College
exercises increase in difficulty and allow
students to explore each major
programming concept presented in the
chapter. Additional programming
exercises are available in the Instructor's
Resource Kit.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
ASSESSMENT
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1
Creating Java
Programs
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Whether you use a compiler or interpreter often depends on the programming language you use. For
example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of translator
has its supporters; programs written in compiled languages execute more quickly, whereas programs
written in interpreted languages are easier to develop and debug. Java uses the best of both technologies: a
compiler to translate your programming statements and an interpreter to read the compiled code line by line
when the program executes (also called at run time).
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Learning Programming Terminology
Compilers and interpreters issue one or more error messages each time they encounter an
invalid program statement—that is, a statement containing a syntax error, or misuse of the
language. Subsequently, the programmer can correct the error and attempt another
translation by compiling or interpreting the program again. Locating and repairing all syntax
errors is the first part of the process of debugging a program—freeing the program of all
errors. Figure 1-1 illustrates the steps a programmer takes while developing an executable 3
program. You will learn more about debugging Java programs later in this chapter.
Debugging process
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language
Debugging process
Can all statements No Examine list of
be successfully
syntax errors
translated?
Yes
Examine
program output
No
As Figure 1-1 shows, you might be able to use a computer language’s syntax correctly but still
have errors to correct. In addition to learning the correct syntax for a particular language,
a programmer must also understand computer programming logic. When you develop
a program of any significant size, you should plan its logic before you write any program
statements. Correct logic requires that all the right commands be issued in the appropriate
4 order. Examples of logical errors include multiplying two values when you meant to divide
them or producing output prior to obtaining the appropriate input.
Correcting logical errors is the second part of the debugging process and is much more
difficult than correcting syntax errors. Syntax errors are discovered when you compile a
program, but often you can identify logical errors only when you examine a program’s first
output. For example, if you know an employee’s paycheck should contain the value $5,000,
but you see that it holds $50 or $50,000 after you execute a payroll program, a logical error
has occurred. Tools that help you visualize and understand logic are presented in the chapter
Making Decisions.
Programmers call some logical errors semantic errors. For example, if you misspell a programming-
language word, you commit a syntax error, but if you use a correct word in the wrong context, you commit
a semantic error.
In each “Two Truths & a Lie” section, two of the numbered statements are true, and one
is false. Identify the false statement and explain why it is false.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Comparing Procedural and Object-Oriented Programming Concepts
Procedural Programming
Procedural programming is a style of programming in which operations are executed one
after another in sequence. In procedural applications, you create names for computer
memory locations that can hold values—for example, numbers and text—in electronic form.
The named computer memory locations are called variables because they hold values that
might vary. For example, a payroll program written for a company might contain a variable
named rateOfPay. The memory location referenced by the name rateOfPay might contain
different values (a different value for every employee of the company) at different times.
During the execution of the payroll program, each value stored under the name rateOfPay
might have many operations performed on it—the value might be read from an input device,
the value might be multiplied by another variable representing hours worked, and the
value might be printed on paper. For convenience, the individual operations used in
a computer program are often grouped into logical units called procedures. For
example, a series of four or five comparisons and calculations that together determine
a person’s federal withholding tax value might be grouped as a procedure named
calculateFederalWithholding. A procedural program defines the variable memory
locations and then calls a series of procedures to input, manipulate, and output the values
stored in those locations. When a program calls a procedure, the current logic is temporarily
abandoned so that the procedure’s commands can execute. A single procedural program
often contains hundreds of variables and procedure calls. Procedures are also called modules,
methods, functions, and subroutines. Users of different programming languages tend to use
different terms. As you will learn later in this chapter, Java programmers most frequently
use the term method.
Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you take
a slightly different approach to writing computer programs. Writing object-oriented
programs involves creating classes, which are blueprints for objects; creating objects from
those classes; and creating applications that use those objects. After creation, classes can be
reused repeatedly to develop new programs. Thinking in an object-oriented manner involves
envisioning program components as objects that belong to classes and that are similar to
concrete objects in the real world; then, you can manipulate the objects and have them
interrelate with each other to achieve a desired result.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Originally, object-oriented programming was used most frequently for two major types of
applications:
l Computer simulations, which attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world
processes operate
6
l Graphical user interfaces, or GUIs (pronounced “gooeys”), which allow users to interact
with a program in a graphical environment
Thinking about objects in these two types of applications makes sense. For example, a city
might want to develop a program that simulates traffic patterns to help prevent traffic tie-ups.
By creating a model with objects such as cars and pedestrians that contain their own data and
rules for behavior, the simulation can be set in motion. For example, each car object has a
specific current speed and a procedure for changing that speed. By creating a model of city
traffic using objects, a computer can create a simulation of a real city at rush hour.
Creating a GUI environment for users also is a natural use for object orientation. It is easy to
think of the components a user manipulates on a computer screen, such as buttons and scroll
bars, as similar to real-world objects. Each GUI object contains data—for example, a button
on a screen has a specific size and color. Each object also contains behaviors—for example,
each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but object-
oriented programming means more. Although many GUI programs are object oriented, do
not assume that all object-oriented programs use GUI objects. Modern businesses use object-
oriented design techniques when developing all sorts of business applications, whether they
are GUI applications or not.
Understanding object-oriented programming requires grasping three basic concepts:
l Encapsulation as it applies to classes as objects
l Inheritance
l Polymorphism
often differentiate instances of the same class from one another. For example, the class
Automobile describes what Automobile objects are like. Some properties of the Automobile
class are make, model, year, and color. Each Automobile object possesses the same attributes
but not, of course, the same values for those attributes. One Automobile might be a 2009
white Ford Taurus and another might be a 2014 red Chevrolet Camaro. Similarly, your dog
has the properties of all Dogs, including a breed, name, age, and whether his shots are current. 7
The values of the properties of an object are also referred to as the object’s state. In other
words, you can think of objects as roughly equivalent to nouns, and of their attributes as
similar to adjectives that describe the nouns.
When you understand an object’s class, you understand the characteristics of the object.
If your friend purchases an Automobile, you know it has a model name, and if your friend gets
a Dog, you know the dog has a breed. Knowing what attributes exist for classes allows you
to ask appropriate questions about the states or values of those attributes. For example,
you might ask how many miles the car gets per gallon, but you would not ask whether the
car has had shots. Similarly, in a GUI operating environment, you expect each component
to have specific, consistent attributes and methods, such as a window having a title bar and
a close button, because each component gains these properties as a member of the general
class of GUI components. Figure 1-2 shows the relationship of some Dog objects to the
Dog class.
By convention, programmers using Java begin their class names with an uppercase letter. Thus, the class
that defines the attributes and methods of an automobile would probably be named Automobile, and
the class for dogs would probably be named Dog. However, following this convention is not required to
produce a workable program.
Name
Age
Ginger Bowser Roxy
Breed 6 2 1
Akita Retriever Beagle
Shot status Up to date Up to date Up to date
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Besides defining properties, classes define methods their objects can use. A method is a self-
contained block of program code that carries out some action, similar to a procedure in a
procedural program. An Automobile, for example, might have methods for moving forward,
moving backward, being filled with gasoline, and being washed. Some methods can ascertain
certain attributes, such as the current speed of an Automobile and the status of its gas tank.
8 Similarly, a Dog can walk or run, eat food, and get a bath, and there are methods to determine
how hungry the Dog is or what its name is. GUI operating system components can be
maximized, minimized, and dragged. In other words, if objects are similar to nouns, then
methods are similar to verbs.
In object-oriented classes, attributes and methods are encapsulated into objects that are then
used much like real-world objects. Encapsulation refers to two closely related object-oriented
notions:
l Encapsulation is the enclosure of data and methods within an object. Encapsulation allows
you to treat all of an object’s methods and data as a single entity. Just as an actual dog
contains all of its attributes and abilities, so would a program’s Dog object.
l Encapsulation also refers to the concealment of an object’s data and methods from outside
sources. Concealing data is sometimes called information hiding, and concealing how
methods work is implementation hiding; you will learn more about both terms in the
chapter Using Methods, Classes, and Objects. Encapsulation lets you hide specific object
attributes and methods from outside sources and provides the security that keeps data and
methods safe from inadvertent changes.
If an object’s methods are well written, the user is unaware of the low-level details of how the
methods are executed, and the user must simply understand the interface or interaction
between the method and the object. For example, if you can fill your Automobile with
gasoline, it is because you understand the interface between the gas pump nozzle and the
vehicle’s gas tank opening. You don’t need to understand how the pump works mechanically
or where the gas tank is located inside your vehicle. If you can read your speedometer, it does
not matter how the displayed figure is calculated. As a matter of fact, if someone produces a
superior, more accurate speed-determining device and inserts it in your Automobile, you
don’t have to know or care how it operates, as long as your interface remains the same. The
same principles apply to well-constructed classes used in object-oriented programs—
programs that use classes only need to work with interfaces.
Inheritance helps you understand real-world objects. For example, the first time you
encounter a Convertible, you already understand how the ignition, brakes, door locks, and
other Automobile systems work. You need to be concerned only with the attributes and
methods that are “new” with a Convertible. The advantages in programming are the same—
you can build new classes based on existing classes and concentrate on the specialized
features you are adding. 9
polymorphism describes the ability to use one term to cause multiple actions.
attributes and methods of existing classes but with more specific features;
The false statement is #3. Inheritance is the ability to create classes that share the
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 Creating Java Programs
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Features of the Java Programming Language
Source code is
stored on a disk in
a file with a name 11
ending in .java
Java Compiler
Compiler creates
bytecode that
is stored on a
disk in a file with
a name ending in
Java Virtual Machine .class
Java Interpreter
Java also is simpler to use than many other object-oriented languages. Java is modeled after
C++. Although neither language is easy to read or understand on first exposure, Java does
eliminate some of the most difficult-to-understand features in C++, such as pointers and
multiple inheritance.
Copyright 2013 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Exploring the Variety of Random
Documents with Different Content
deux volumes de contes chrétiens d'Égypte. Les histoires populaires
qui servaient à Aristophane se retrouvent encore partiellement dans
les vies des saints russes.
Si on examine à ce point de vue la légende de Julien, on y reconnaît
aussitôt les caractères déterminants d'un conte populaire. Le thème
général est l'histoire d'un homme qui accomplit par destinée un
meurtre involontaire, et dans ce thème général sont compris trois
thèmes épisodiques: un oracle est prononcé par un animal; le héros
est condamné, en expiation de son crime, à devenir passeur sur une
rivière; un ange vient éprouver sa charité sous la forme d'un pauvre
ou d'un lépreux.
On sait que l'idée générale d'un conte populaire est exprimée par
différents thèmes épisodiques qui varient et se combinent
diversement suivant les temps, les nations ou les provinces.
Or, parmi les contes populaires que nous connaissons, aucun ne
reproduit la combinaison de thèmes qui se trouve dans l'histoire de
Julien. Mais il arrive souvent qu'un conte emprunte des thèmes à un
conte qui appartient à un autre cycle. M. Cosquin en a donné des
exemples dans sa belle étude du folklore de Lorraine.
Il suffira donc de comparer les épisodes de l'histoire de Julien à
d'autres épisodes recueillis parmi les cycles du folklore pour s'assurer
de l'origine populaire de cette admirable légende. Peut-être trouvera-
t-on plus tard dans la littérature orale une construction où les
épisodes du conte seront disposés dans le même ordre. Et comme
l'histoire de Julien devait être fort ancienne déjà, puisque son origine
était oubliée lorsqu'elle entra, au XIIIe siècle, dans le Speculum
historiale, on peut imaginer qu'elle représente pour nous un type
archaïque dont les éléments ont été plus tard démembrés. Elle
faisait sans doute partie d'un cycle d'autres contes analogues.
Enclavée dans la littérature religieuse, c'est l'unique variante qui
nous reste.
Le thème général du conte est absolument identique aux thèmes de
l'histoire d'Œdipe, du prince Agib, du troisième calandar des Mille et
une Nuits, et de la Belle au Bois dormant. Œdipe est contraint par
un oracle à tuer son père Laïos; on l'expose; on l'écarte du pays;
malgré toutes les précautions, il accomplit la prédiction à son insu.
Les astrologues ont annoncé au père d'un jeune homme que son fils
serait assassiné à l'âge de quinze ans par le prince Agib. Le vieillard
fait enfermer son enfant dans un souterrain, au milieu d'une île. Agib
aborde dans l'île, découvre la cachette, devient l'ami du jeune
homme; et, à l'heure assignée, le cinquantième jour, au moment où
il va prendre un couteau pour découper un melon au sucre, son pied
glisse, et il frappe l'enfant au cœur. Enfin, dans le conte de Perrault,
une fée prédit que la petite princesse se percera la main d'un
fuseau, et qu'il y aura de cruelles conséquences. Le roi interdit de
filer dans son royaume. Pourtant, la belle trouve une vieille femme
au rouet, dans un donjon, joue avec le fuseau, se blesse, et l'oracle
s'accomplit fatalement. C'est la forme affaiblie du même thème de
folklore: et on se souvient que la première fée annonce que la belle
mourra de sa blessure.
Dans l'histoire de Julien, l'oracle est prononcé par un animal et c'est
la caractéristique du premier épisode. Ici les rapprochements
seraient innombrables et oiseux. C'est l'inverse du thème que les
folkloristes ont coutume d'appeler le «thème des animaux
reconnaissants». Nous sentons bien que l'histoire de Julien est
mutilée à cet endroit, sous sa forme primitive. On ne nous dit point
que Julien commit une mauvaise action en allant à la chasse. Au
contraire, le texte sacré explique: cum Julianus quâdam die venationi
insisteret, ut juvenis et nobilis. Le cerf ne se plaint pas. Il se
retourne simplement, et dit: Tu me sequeris, qui patris et matris
tuae occisor eris?
Il faut donc supposer—puisque la cruauté de Julien ne saurait être
mise en cause—que dans le type archaïque du conte le cerf était un
homme métamorphosé. Car telle est l'apparence de tous les
animaux qui font de semblables prédictions dans les contes
populaires. Et on trouve là probablement l'influence d'une tradition
indoue et de nombreux apologues religieux qui illustrent la doctrine
de la métempsychose.
Après l'oracle, Julien se cache et s'enfuit, pour échapper au destin.
C'est l'épisode des précautions, qu'on retrouve avec des variantes
dans les contes grec, arabe et français.
L'oracle s'accomplit et Julien devient, par pénitence, passeur sur une
rivière. Nous reconnaissons là un épisode que nous retrouvons non
seulement dans la légende de saint Christophe, mais encore dans un
conte recueilli par les frères Grimm, le Diable aux trois cheveux d'or.
Le héros du conte trouve sur son chemin une grosse rivière qu'il lui
faut traverser. Le passeur lui explique qu'il est contraint de mener
incessamment sa barque de l'un à l'autre bord et le supplie de
vouloir bien le délivrer. Le héros fait interroger à ce sujet le diable.
La réponse, c'est qu'il suffira au passeur de placer sa gaffe dans la
main de son premier passager: alors il sera libre, et l'autre sera
damné à son tour. Grâce aux péripéties du conte, le premier
passager se trouve être un méchant roi. Le passeur fait ainsi qu'on
lui a dit; et «désormais, dit le conte, le roi est passeur sur la rivière
en punition de ses péchés».
Quant à la légende de saint Christophe, elle est formée d'éléments si
semblables à ceux dont fut composée celle de Julien qu'il faut citer
toute la partie commune. Voici l'admirable traduction de frère Jehan
du Vignay, publiée en 1554.
III
«Et voilà l'histoire de saint Julien l'Hospitalier, dit Gustave Flaubert,
telle à peu près qu'on la trouve sur un vitrail d'église dans mon
pays.»
C'est un vitrail de la cathédrale de Rouen, et M. Langlois en a publié
un dessin dans ses collections. Lorsque Flaubert donna la Légende
de saint Julien à son éditeur, il lui écrivit pour lui demander de
reproduire à la fin du livre la pieuse composition normande. Mais il
avait peu d'estime pour le vitrail de Rouen. Il voulait faire admirer au
lecteur l'extraordinaire différence qu'on trouve entre le conte orné
splendidement et la naïve image provinciale. L'éditeur ne put réaliser
le désir de Flaubert. Aujourd'hui encore nous avons peine à imaginer
la miraculeuse transformation d'art et de style qui habilla de pourpre
et d'or ces simples figures, qui suspendit à des parois de palais les
sanglantes tapisseries de chasses et de batailles, qui fit d'un lépreux
aux lèvres bleuâtres un saint aux yeux d'étoiles dont les narines
soufflaient l'odeur de la rose.
II
Les anciens ont saisi le double rôle de la terreur et de la pitié dans la
vie humaine. L'intérêt des autres passions semblait inférieur, tandis
que ces deux émotions extrêmes emplissaient l'âme entière. L'âme
devait être en quelque manière une harmonie, une chose symétrique
et équilibrée. Il ne fallait pas la laisser en état de trouble; on
cherchait à balancer la terreur par la pitié. L'une de ces passions
chassait l'autre, et l'âme redevenait calme; le spectateur sortait
satisfait. Il n'y avait pas de moralité dans l'art; il y avait à faire
l'équilibre dans l'âme. Le cœur, sous l'empire d'une seule émotion,
eût été trop peu artistique à leurs yeux.
La purgation des passions, ainsi que l'entendait Aristote, cette
purification de l'âme, n'était peut-être que le calme ramené dans un
cœur palpitant. Car il n'y avait dans le drame que deux passions, la
terreur et la pitié, qui devaient se faire contre-poids, et leur
développement intéressait l'artiste à un point de vue bien différent
du nôtre. Le spectacle que cherchait le poète n'était pas sur la
scène. mais dans la salle. Il se préoccupait moins de l'émotion
éprouvée par l'acteur que de ce que sa représentation soulevait dans
le spectateur. Les personnages étaient vraiment de gigantesques
marionnettes terrifiantes ou pitoyables. On ne raisonnait pas sur la
description des causes, mais on percevait l'intensité des effets.
Or, les spectateurs n'éprouvaient que les deux sentiments extrêmes
qui emplissent le cœur. L'égoïsme menacé leur donnait la terreur; la
souffrance partagée leur donnait la pitié. Ce n'était pas la fatalité
dans l'histoire d'Œdipe ou des Atrides qui occupait le poète, mais
l'impression de cette fatalité sur la foule.
Le jour où Euripide analysa l'amour sur la scène, on put l'accuser
d'immoralité; car on ne lui reprochait pas le développement de la
passion chez ses personnages, mais celle qui pourrait se développer
chez ceux qui les voyaient.
On aurait pu concevoir l'amour comme un mélange de ces deux
passions extrêmes qui se partageaient le théâtre. Car il y a en lui de
l'admiration, de l'attendrissement et du sacrifice, un sentiment du
sublime qui participe de la terreur, une commisération délicate, et un
désintéressement suprême qui viennent de la pitié; si bien que peut-
être les deux moitiés de l'amour se joignent avec une force
supérieure là où d'un côté il y a l'admiration la plus effrayée, où de
l'autre il y a la pitié qui se sacrifie le plus sincèrement.
Ainsi, l'amour perd son égoïsme exclusif qui fait des amants deux
centres d'attraction tour à tour: car l'amant doit être tout pour son
amante, comme l'amante doit être tout pour son amant. Il est
devenu l'alliance la plus noble d'un cœur plein de sublime avec un
cœur plein de désintéressement. Les femmes ne sont plus Phèdre ni
Chimène, mais Desdémone, Imogène, Miranda, ou Alceste.
L'amour a sa place entre la terreur et la pitié. Sa représentation est
le plus délicat passage d'une de ces passions à l'autre; et elle les
soulève toutes deux dans le spectateur, dont l'âme prend ainsi plus
d'intérêt que celle du personnage qui joue.
L'analyse des passions dans la description des héros ou dans le rôle
des acteurs est déjà une pénétration de l'art par la critique.
L'examen que la personne représentée fait d'elle-même provoque un
examen imité chez le spectateur. Il perd la sincérité de ses
impressions; il ratiocine, discute, compare; les femmes cherchent
parfois dans ces développements des moyens matériels pour
tromper, et les hommes des moyens moraux pour découvrir; la
déclamation rhétorique est vide; la déclamation psychologique est
pernicieuse.
Les passions représentées non plus pour l'acteur, mais pour le
spectateur, ont une haute portée morale. En entendant les Sept
contre Thèbes, dit Aristophane, on était plein d'Arès. La fureur
guerrière et la terreur des armes ébranlait tous les assistants. Puis
les deux frères se tuant, les deux sœurs les enterrant, malgré des
ordres cruels et une mort imminente, la pitié chassait la terreur; le
cœur se calmait, l'âme reprenait de l'harmonie.
A de semblables effets une composition spéciale est nécessaire. Le
drame implexe diffère systématiquement du drame complexe. La
situation dramatique tout entière est dans l'exposition d'un état
tragique, qui contient en puissance le dénouement. Cet état est
exposé symétriquement, avec une mise en place rigoureuse et
définie du sujet et de la forme. D'un côté ceci; de l'autre cela.
Il suffit de lire Eschyle avec quelque attention pour percevoir cette
permanente symétrie qui est le principe de son art. La fin des pièces
est pour lui une rupture de l'équilibre dramatique. La tragédie est
une crise, et sa solution une accalmie. En même temps, à Égine, un
peu plus tard à Olympie, des sculpteurs de génie, obéissant aux
mêmes principes d'art, ornaient les frontons des temples de figures
humaines et de compositions scéniques symétriquement groupées
des deux côtés d'une rupture d'harmonie centrale. Les crises des
attitudes, réelles mais immobiles, sont placées dans une composition
dont le total explique chacune des parties.
Phidias et Sophocle furent en art des révolutionnaires réalistes. Le
type humain qui nous paraît idéalisé dans leurs œuvres est la nature
même, telle qu'ils la concevaient. Le mouvement de la vie fut suivi
jusque dans ses courbes les plus molles. Au témoignage d'Aristote,
un acteur d'Eschyle reprochait à un acteur de Sophocle de singer la
nature, au lieu de l'imiter. Le drame implexe avait disparu de la
scène artistique. Le mouvement réaliste devait encore s'accentuer
avec Euripide.
La composition d'art cessa d'être la représentation d'une crise. La vie
humaine intéressa par son développement. L'Œdipe de Sophocle est
une sorte de roman. Le drame fut découpé en tranches successives;
la crise devint finale, au lieu d'être initiale; l'exposition, qui était dans
l'art antérieur la pièce elle-même, fut réduite pour permettre le jeu
de la vie.
Ainsi naquit l'art postérieur à Eschyle, à Polygnote, et aux maîtres
d'Égine et d'Olympie. C'est l'art qui est venu jusqu'à nous par le
théâtre et le roman.
Comme toutes les manifestations vitales, l'action, l'association et le
langage, l'art a passé par des périodes analogues qui se
reproduisent d'âge en âge. Les deux points extrêmes entre lesquels
l'art oscille semblent être la Symétrie et le Réalisme. Dans la
Symétrie, la vie est assujettie à des règles artistiques
conventionnelles; dans le Réalisme, la vie est reproduite avec toutes
ses inflexions les plus inharmoniques.
De la période symétrique du XIIe et du XIIIe siècle, l'art a passé à la
période psychologique, réaliste et naturiste des XIVe, XVe et XVIe
siècles. Sous l'influence des règles antiques au XVIIe, il s'est
développé un art conventionnel que le mouvement du XVIIIe et du
XIXe siècle a rompu. Nous touchons aujourd'hui, après le
romantisme et le naturalisme, à une nouvelle période de symétrie.
L'Idée qui est fixe et immobile semble devoir se substituer de
nouveau aux Formes Matérielles, qui sont changeantes et flexibles.
Au moment où se crée un art nouveau, il est utile de ne pas
s'attacher uniquement à la considération de la floraison
indépendante des Primitifs et des Préraphaélites; il ne faut pas
négliger les belles constructions des crises de l'âme et du corps
qu'ont exécutées Eschyle et les maîtres d'Égine et d'Olympie.
III
Avant d'examiner le rôle que peuvent jouer dans l'art ces crises de
l'âme et du corps, il n'est pas inutile de regarder derrière nous et
autour de nous la forme littéraire prépondérante dans les temps
modernes, c'est-à-dire le roman.
Sitôt que la vie humaine parut intéressante par son développement
même, qu'il fût intérieur ou extérieur, le roman était né. Le roman
est l'histoire d'un individu, qu'il soit Encolpe, Lucius, Pantagruel, Don
Quichotte, Gil Blas ou Tom Jones. L'histoire était extérieure plutôt
avant la fin du siècle dernier et Clarisse Harlowe; mais pour être
devenue intérieure, la trame de la composition n'a pas changé.
Historiola animæ, sed historiola.
Les tourments de l'âme avec Gœthe, Stendhal, Benjamin Constant,
Alfred de Vigny, devinrent prédominants. La liberté personnelle avait
été dégagée par la révolution américaine, par la révolution française.
L'homme libre avait toutes les aspirations. On sentait plus qu'on ne
pouvait. Un élève notaire se tua en 1810, et laissa une lettre où il
annonçait sa résolution, parce qu'à la suite de sérieuses réflexions il
avait reconnu qu'il était incapable de devenir aussi grand que
Napoléon. Tous éprouvaient ceci dans tous les rayons de l'activité
humaine. Le bonheur personnel devait être au fond des bissacs que
chacun de nous porte devant et derrière lui.
La maladie du siècle commença. On voulut être aimé pour soi-
même. Le cocuage devint triste. La vie aussi: c'était un tissu
d'aspirations excessives que chaque mouvement déchirait. Les uns
se jetèrent dans des mysticismes singuliers, chrétiens, extravagants,
ou immondes; les autres, poussés du démon de la perversité, se
scarifièrent le cœur, déjà si malade, comme on taquine une dent
gâtée. Les autobiographies vinrent au jour sous toutes les formes.
Alors la science du XIXe siècle, qui devenait géante, se mit à envahir
tout. L'art se fit biologique et psychologique. Il devait prendre ces
deux formes positives, puisque Kant avait tué la métaphysique. Il
devait prendre une apparence d'érudition. Le XIXe siècle est
gouverné par la naissance de la chimie, de la médecine et de la
psychologie, comme le XVIe est mené par la renaissance de Rome et
d'Athènes. Le désir d'entasser des faits singuliers et archéologiques y
est remplacé par l'aspiration vers les méthodes de liaison et de
généralisation.
Mais, par un recul étrange, les généralisations des esprits artistiques
ayant été trop hâtives, les lettres marchèrent vers la déduction,
tandis que la science marchait vers l'induction.
Il est singulier que, dans le temps où on parle synthèse, personne
ne sache en faire. La synthèse ne consiste pas à rassembler les
éléments d'une psychologie individuelle, ni à réunir les détails de
description d'un chemin de fer, d'une mine, de la Bourse ou de
l'Armée.
Ainsi entendue, la synthèse est de l'énumération; et si des
ressemblances que présentent les moments de la série l'auteur
cherche à tirer une idée générale, c'est une banale abstraction, qu'il
s'agisse de l'amour des salons ou du ventre de Paris. La vie n'est pas
dans le général, mais dans le particulier; l'art consiste à donner au
particulier l'illusion du général.
Présenter ainsi la vie des entités partielles de la société, c'est faire
de la science moderne à la façon d'Aristote. La généralité engendrée
par l'énumération complète des parties est une variété du
syllogisme. «L'homme, le cheval, le mulet vivent longtemps, écrit
Aristote.—Or, l'homme, le cheval et le mulet sont tous les animaux
sans fiel.—Donc tous les animaux sans fiel vivent longtemps.»
Ceci n'est pas une désespérante tautologie, mais c'est le syllogisme
énumératif, qui n'a aucune rigueur scientifique. Il repose en effet sur
une énumération complète; et il est impossible, dans la nature, de
parvenir à un tel résultat.
La monotone nomenclature des détails psychologiques ou
physiologiques ne peut pas servir à donner les idées générales de
l'âme et du monde; et cette manière d'entendre et d'appliquer la
synthèse est une forme de la déduction.
Ainsi le roman analyste et le roman naturaliste, en faisant usage de
ce procédé, pèchent contre la science qu'ils invoquent tous deux.
Mais s'ils emploient faussement la synthèse, ils appliquent aussi la
déduction en plein développement de la science expérimentale.
Le roman analyste pose la psychologie du personnage, la commente
finement et déduit de là une vie entière.
Le roman naturaliste pose la physiologie du personnage, décrit ses
instincts, son hérédité, et déduit de là l'ensemble de ses actions.
Cette déduction unie à la synthèse énumérative constitue la
méthode propre des romans analystes et naturalistes.
Car le romancier moderne prétend avoir une méthode scientifique,
réduire les lois naturelles et mathématiques en formules littéraires,
observer comme un naturaliste, expérimenter comme un chimiste,
déduire comme un algébriste.
L'art véritablement entendu semble au contraire se séparer de la
science par son essence même.
Dans la considération d'un phénomène de la nature, le savant
suppose le déterminisme, cherche les causes de ce phénomène et
ses conditions de détermination; il l'étudie au point de vue de
l'origine et des résultats; il se l'asservit à lui-même, pour le
reproduire, et l'asservit à l'ensemble des lois du monde pour l'y lier;
il en fait un déterminable et un déterminé.
L'artiste suppose la liberté, regarde le phénomène comme un tout, le
fait entrer dans sa composition avec ses causes rapprochées, le
traite comme s'il était libre, lui-même libre dans sa manière de le
considérer.
La science cherche le général par le nécessaire; l'art doit chercher le
général par le contingent; pour la science, le monde est lié et
déterminé; pour l'art, le monde est discontinu et libre; la science
découvre la généralité extensive; l'art doit faire sentir la généralité
intensive; si le domaine de la science est le déterminisme, le
domaine de l'art est la liberté.
Les êtres vivants, spontanés, libres, dont la synthèse psychologique
et physiologique, malgré certaines conditions déterminées, dépendra
des séries qu'ils rencontreront, des milieux qu'ils traverseront, tels
seront les objets de l'art. Ils ont des facultés de nutrition,
d'absorption et d'assimilation; mais il faut tenir compte du jeu
compliqué des lois naturelles et sociales, que nous appelons hasard,
que l'artiste n'a pas à analyser, qui est véritablement pour lui le
Hasard, et qui amène à l'organisme physique et conscient les choses
dont il peut se nourrir, qu'il peut absorber et s'assimiler.
Ainsi la synthèse sera celle d'un être vivant.
Si toutes les conditions de la vie humaine pouvaient être
déterminées ou prévues, a écrit Kant, on calculerait les actions des
hommes comme des éclipses.
La science des choses humaines n'a pas encore atteint la science des
choses célestes.
La physiologie et la psychologie ne sont malheureusement pas
beaucoup plus avancées que la météorologie; et les actions que
prédit la psychologie de nos romans sont d'ordinaire aussi faciles à
prévoir que la pluie pendant l'orage.
Mais il faut trouver le moyen de nourrir artistiquement l'être
physique et conscient des événements que le Hasard lui offre. On ne
peut pas donner de règles pour cette synthèse vivante. Ceux qui
n'en ont pas d'idée, et qui clament sans cesse à la synthèse,
retardent en art, comme Platon retardait en science.
«Quand j'ajoute un à un, disait Platon dans sa République, qu'est-ce
qui devient deux, l'unité à laquelle j'ajoute, ou celle qui est
ajoutée?»
Pour un esprit aussi profondément déductif, la série des nombres
devait naître analytiquement; le nouvel être deux devait être
enveloppé dans l'une des unités dont la jonction l'engendrait.
Nous disons que le nombre deux est produit synthétiquement, qu'il
intervient dans l'addition un principe différent de l'analyse; et Kant a
montré que la sériation des nombres était le résultat d'une synthèse
à priori.
Or, dans la vie la synthèse qui s'opère est aussi radicalement
différente de l'énumération générale des détails psychologiques et
physiologiques ou du système déductif.
Il y a peu d'exemples meilleurs de la représentation de la vie qu'un
passage d'Hamlet.
Deux actions dramatiques se partagent la pièce, l'une extérieure à
Hamlet, l'autre intérieure. A la première se rattache le passage des
troupes de Fortinbras (act. IV, sc. V) qui traversent le Danemark
pour attaquer la Pologne. Hamlet les voit passer. Comment l'action
intérieure à Hamlet se nourrira-t-elle de cet événement extérieur?
Voici; Hamlet s'écrie:
III
Imaginons donc un être dont le cerveau soit hanté de fantômes qui
ont une tendance à la réalité, comme les images ont une tendance
hallucinatoire, et qui, en même temps, ne soit pas encore doué de la
volonté nécessaire pour agir, ou pour projeter ses fantômes après
avoir lutté contre eux. Je pense que cet être n'est pas rare, et qu'il
représente même un moment de l'évolution intellectuelle de
beaucoup d'artistes de notre temps. L'intelligence et l'esthétique
intérieure se forment bien plus tôt que la volonté. Pour produire une
œuvre d'art, il faut que la volonté ait atteint son développement.
Auparavant les créations ou les fantômes de l'artiste, puisqu'il ne
peut pas encore les réaliser esthétiquement, s'interposeront entre lui
et la société, l'isoleront du monde, ou il les introduira dans l'univers,
à la manière de Don Quichotte, qui n'a point d'autre folie que celle-
là.
Cet être m'apparaît nettement dans l'Écornifleur de Jules Renard.
L'Écornifleur est un jeune homme dont le cerveau est peuplé de
littérature. Rien pour lui ne se présente comme un objet normal. Il
voit le XVIIIe siècle à travers Goncourt, les ouvriers à travers Zola, la
société à travers Daudet, les paysans à travers Balzac et
Maupassant, la mer à travers Michelet et Richepin. Il a beau
regarder la mer, il n'est jamais au niveau de la mer. S'il aime, il se
rappelle les amours littéraires. S'il viole, il s'étonne de ne pas violer
comme en littérature. Sa tête est pleine de fantômes.
Il apporte ces fantômes dans un ménage bourgeois. Jamais il ne
sera au niveau de ce ménage, ni le ménage au sien. Il veut
intéresser des gens qu'il voit déformés, et il les déforme pour les
obliger à l'intéresser. Il se doit à sa littérature de traiter le mari en
Homais, la femme en Mme Bovary, et de violer la nièce par un beau
jour d'été. Entre temps, il vit aux crochets de la famille—car
l'Écornifleur est pauvre de nature.
Mais la volonté manque à ses créations. Il est encore trop lui-même.
Il rencontre le même être que Peer Gynt. Il a pitié et peur du mari.
Le baiser soudain de la femme l'effare, et il se sent dans une action
réelle sans soutien littéraire. La jeune fille forcée pousse des cris,
souffre, se lamente—et les fantômes de son cerveau n'étaient pas
ainsi. L'Écornifleur cède devant lui-même; il ne sait pas réaliser dans
la vie les êtres fantastiques qui ont poussé dans sa tête; il faut qu'il
attende le jour où sa volonté formée les projettera dans l'art.
Un pouce de plus à son vouloir, et c'est Chambige. Un pouce de
moins, et c'est Poil-de-Carotte. Un peu plus d'énergie dans l'action,
et il est criminel. Un peu moins d'extériorisation, et le pauvre enfant
se plaint de ne pas être compris.
Et comme ce roman est bien celui des crises! L'être fantastique
conçu par l'Écornifleur est arrivé à sa pleine croissance, il voit la
femme qu'il se doit d'aimer; il va descendre à sa chambre, au milieu
de la nuit; déjà elle a les jambes levées. Mais l'aventure ne se
produit pas; la femme ne l'attend pas—elle dort—les portes seront
fermées—l'Écornifleur sera pieds nus et ridicule.—Il lit des vers en
élevant son âme jusqu'au fumivore; le miracle va se produire; on
écoutera ses poèmes comme il conçoit qu'on les écoute: le mari fait
vibrer son couteau dans une rainure de la table et dit: «C'est fini?»
Dans un roman fantastique comme Macbeth ou Hamlet, la crise
appelle l'aventure; l'état intérieur du personnage projette le fantôme
ou l'événement extérieur. Le pauvre Écornifleur ne trouve jamais les
aventures qu'il s'imaginait, quand elles étaient des crises.