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

Java Programming 8th Edition Joyce Farrell download

The document provides links to various programming textbooks, including 'Java Programming 8th Edition' by Joyce Farrell, available for instant download in multiple formats. It includes details about the content structure of the book, covering topics from creating Java programs to advanced GUI topics. Additionally, it mentions copyright information and the publisher's rights regarding the eBook content.

Uploaded by

linjujanryd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
10 views

Java Programming 8th Edition Joyce Farrell download

The document provides links to various programming textbooks, including 'Java Programming 8th Edition' by Joyce Farrell, available for instant download in multiple formats. It includes details about the content structure of the book, covering topics from creating Java programs to advanced GUI topics. Additionally, it mentions copyright information and the publisher's rights regarding the eBook content.

Uploaded by

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

Java Programming 8th Edition Joyce Farrell pdf

download

https://ebookgate.com/product/java-programming-8th-edition-joyce-
farrell/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


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

Java Programming 6th Edition Joyce Farrell

https://ebookgate.com/product/java-programming-6th-edition-joyce-
farrell/

ebookgate.com

Programming Logic and Design Comprehensive 8th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-8th-edition-joyce-farrell/

ebookgate.com

Programming Logic and Design Comprehensive 7th Edition


Joyce Farrell

https://ebookgate.com/product/programming-logic-and-design-
comprehensive-7th-edition-joyce-farrell/

ebookgate.com

Computer Programming for Teens 1st Edition Mary E. Farrell

https://ebookgate.com/product/computer-programming-for-teens-1st-
edition-mary-e-farrell/

ebookgate.com
Programming in Java 2nd edition Edition Choudhary

https://ebookgate.com/product/programming-in-java-2nd-edition-edition-
choudhary/

ebookgate.com

JXTA Java P2P Programming 1st Edition Daniel Brookshier

https://ebookgate.com/product/jxta-java-p2p-programming-1st-edition-
daniel-brookshier/

ebookgate.com

Java Network Programming Third Edition Elliotte Rusty


Harold

https://ebookgate.com/product/java-network-programming-third-edition-
elliotte-rusty-harold/

ebookgate.com

A Guide To Programming in Java Java 2 Platform Standard


Edition 5 Beth Brown

https://ebookgate.com/product/a-guide-to-programming-in-java-
java-2-platform-standard-edition-5-beth-brown/

ebookgate.com

Functional Programming in Java Harnessing the Power Of


Java 8 Lambda Expressions 1st Edition Venkat Subramaniam

https://ebookgate.com/product/functional-programming-in-java-
harnessing-the-power-of-java-8-lambda-expressions-1st-edition-venkat-
subramaniam/
ebookgate.com
TM

JAVA PROGRAMMING

Copyright 2016 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 2016 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.
EIGHTH EDITION

TM

JAVA PROGRAMMING

JOYCE FARRELL

Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States

Copyright 2016 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.

Important Notice: Media content referenced within the product description or the product text may not be available in the eBook version.

Copyright 2016 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, © 2016, 2014, 2012 Cengage Learning
Eighth Edition WCN: 02-200-203
Joyce Farrell
ALL RIGHTS RESERVED. No part of this work covered by the copyright
Product Director: herein may be reproduced, transmitted, stored, or used in any form or
Kathleen McMahon by any means graphic, electronic, or mechanical, including but not
Senior Content Developer: limited to photocopying, recording, scanning, digitizing, taping, Web
Alyssa Pratt distribution, information networks, or information storage and
retrieval systems, except as permitted under Section 107 or 108 of the
Development Editor: Dan Seiter
1976 United States Copyright Act, without the prior written
Marketing Manager: Eric LaScola permission of the publisher.
Manufacturing Planner:
Julio Esperas
For product information and technology assistance, contact us at
Art Director: Jack Pendleton Cengage Learning Customer & Sales Support, 1-800-354-9706
Production Management,
For permission to use material from this text or product,
Copyediting, Composition,
Proofreading, and Indexing: submit all requests online at www.cengage.com/permissions.
Integra Software Services Pvt. Ltd. Further permissions questions can be emailed to
Cover Photo: [email protected].
©Maram/Shutterstock.com

Library of Congress Control Number: 2014956152


ISBN: 978-1-285-85691-9
Cengage Learning
20 Channel Center Street
Boston, MA 02210
USA

Cengage Learning is a leading provider of customized learning


solutions with office locations around the globe, including Singapore,
the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your
local office at www.cengage.com/global.

Cengage Learning products are represented in Canada by Nelson


Education, Ltd.

All images © 2016 Cengage Learning®. All rights reserved.


To learn more about Cengage Learning Solutions, visit
www.cengage.com.
Purchase any of our products at your local college store
or at our preferred online store www.cengagebrain.com.

Printed in the U nited States of America


Print N umber: 01 Print Year: 2015

Copyright 2016 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 . . . . . . . . . . . . . . . . . . . . . 53
CHAPTER 3 Using Methods, Classes, and Objects . . . . . . . 119
CHAPTER 4 More Object Concepts . . . . . . . . . . . . . . . 183
CHAPTER 5 Making Decisions . . . . . . . . . . . . . . . . . 245
CHAPTER 6 Looping . . . . . . . . . . . . . . . . . . . . . 301
CHAPTER 7 Characters, Strings, and the StringBuilder . . . 353
CHAPTER 8 Arrays . . . . . . . . . . . . . . . . . . . . . . 393
CHAPTER 9 Advanced Array Concepts . . . . . . . . . . . . . 439
CHAPTER 10 Introduction to Inheritance . . . . . . . . . . . . . 491
CHAPTER 11 Advanced Inheritance Concepts . . . . . . . . . . 537
CHAPTER 12 Exception Handling . . . . . . . . . . . . . . . . 593
CHAPTER 13 File Input and Output . . . . . . . . . . . . . . . 665
CHAPTER 14 Introduction to Swing Components . . . . . . . . 729
CHAPTER 15 Advanced GUI Topics . . . . . . . . . . . . . . . 791
CHAPTER 16 Graphics . . . . . . . . . . . . . . . . . . . . . 861
APPENDIX A Working with the Java Platform . . . . . . . . . . . 919
APPENDIX B Data Representation . . . . . . . . . . . . . . . 925
APPENDIX C Formatting Output . . . . . . . . . . . . . . . . 931
APPENDIX D Generating Random Numbers . . . . . . . . . . . 941
APPENDIX E Javadoc . . . . . . . . . . . . . . . . . . . . . 949
Glossary . . . . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . . . . 979

Copyright 2016 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

CHAPT ER 1 Creating Java Programs . . . . . . . . . . . 1


Learning Programming Terminology . . . . . . . . . . . . . . 2
Comparing Procedural and Object-Oriented
Programming Concepts . . . . . . . . . . . . . . . . . . 6
Procedural Programming . . . . . . . . . . . . . . . . . . 6
Object-Oriented Programming . . . . . . . . . . . . . . . . 6
Understanding Classes, Objects, and Encapsulation . . . . . . 7
Understanding Inheritance and Polymorphism . . . . . . . . . 9
Features of the Java Programming Language . . . . . . . . . . 11
Java Program Types . . . . . . . . . . . . . . . . . . . . 12
Analyzing a Java Application that Produces Console Output . . . . 13
Understanding the Statement that Produces the Output . . . . . 14
Understanding the First Class . . . . . . . . . . . . . . . 15
Indent Style . . . . . . . . . . . . . . . . . . . . . . . 18
Understanding the main() Method . . . . . . . . . . . . . 19
Saving a Java Class . . . . . . . . . . . . . . . . . . . . 21
Compiling a Java Class and Correcting Syntax Errors . . . . . . . 23
Compiling a Java Class . . . . . . . . . . . . . . . . . . . 23
Correcting Syntax Errors . . . . . . . . . . . . . . . . . . 24
Running a Java Application and Correcting Logic Errors . . . . . . 29
Running a Java Application . . . . . . . . . . . . . . . . . 29
Modifying a Compiled Java Class . . . . . . . . . . . . . . 30
Correcting Logic Errors . . . . . . . . . . . . . . . . . . 31
Adding Comments to a Java Class . . . . . . . . . . . . . . . 32
Creating a Java Application that Produces GUI Output . . . . . . 35
Finding Help . . . . . . . . . . . . . . . . . . . . . . . . 38
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . . 39
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . 41

Copyright 2016 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 . . . . . . . . . . . . . . . . . . . . . . 45
Review Questions . . . . . . . . . . . . . . . . . . . . . . 46
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 48
Programming Exercises . . . . . . . . . . . . . . . . . . 48
Debugging Exercises . . . . . . . . . . . . . . . . . . . 50 vii
Game Zone . . . . . . . . . . . . . . . . . . . . . . . . 50
Case Problems . . . . . . . . . . . . . . . . . . . . . . 51

CHAPT ER 2 Using Data . . . . . . . . . . . . . . . . . 53


Declaring and Using Constants and Variables . . . . . . . . . . 54
Declaring Variables . . . . . . . . . . . . . . . . . . . . 55
Declaring Named Constants . . . . . . . . . . . . . . . . 56
The Scope of Variables and Constants . . . . . . . . . . . . 58
Concatenating Strings to Variables and Constants . . . . . . . 58
Pitfall: Forgetting that a Variable Holds
One Value at a Time . . . . . . . . . . . . . . . . . . . 60
Learning About Integer Data Types . . . . . . . . . . . . . . 64
Using the boolean Data Type . . . . . . . . . . . . . . . . . 70
Learning About Floating-Point Data Types . . . . . . . . . . . . 71
Using the char Data Type . . . . . . . . . . . . . . . . . . 72
Using the Scanner Class to Accept Keyboard Input . . . . . . . 78
Pitfall: Using nextLine() Following One of the
Other Scanner Input Methods . . . . . . . . . . . . . . 81
Using the JOptionPane Class to Accept GUI Input . . . . . . . 87
Using Input Dialog Boxes . . . . . . . . . . . . . . . . . . 87
Using Confirm Dialog Boxes . . . . . . . . . . . . . . . . 91
Performing Arithmetic . . . . . . . . . . . . . . . . . . . . 93
Associativity and Precedence . . . . . . . . . . . . . . . . 95
Writing Arithmetic Statements Efficiently . . . . . . . . . . . 96
Pitfall: Not Understanding Imprecision
in Floating-Point Numbers . . . . . . . . . . . . . . . . 96
Understanding Type Conversion . . . . . . . . . . . . . . . 101
Automatic Type Conversion . . . . . . . . . . . . . . . . 101
Explicit Type Conversions . . . . . . . . . . . . . . . . 102
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 106
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 107

Copyright 2016 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

Chapter Summary . . . . . . . . . . . . . . . . . . . . . 111


Review Questions . . . . . . . . . . . . . . . . . . . . . 111
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 114
Programming Exercises . . . . . . . . . . . . . . . . . 114
viii Debugging Exercises . . . . . . . . . . . . . . . . . . 116
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 117
Case Problems . . . . . . . . . . . . . . . . . . . . . 118

CHAPT ER 3 Using Methods, Classes, and Objects . . . . 119


Understanding Method Calls and Placement . . . . . . . . . . 120
Understanding Method Construction . . . . . . . . . . . . . 123
Access Specifiers . . . . . . . . . . . . . . . . . . . . 123
Return Type . . . . . . . . . . . . . . . . . . . . . . 124
Method Name . . . . . . . . . . . . . . . . . . . . . 125
Parentheses . . . . . . . . . . . . . . . . . . . . . . 125
Adding Parameters to Methods . . . . . . . . . . . . . . . 129
Creating a Method that Receives a Single Parameter . . . . . 130
Creating a Method that Requires Multiple Parameters . . . . . 133
Creating Methods that Return Values . . . . . . . . . . . . . 136
Chaining Method Calls . . . . . . . . . . . . . . . . . . 138
Learning About Classes and Objects . . . . . . . . . . . . . 142
Creating a Class . . . . . . . . . . . . . . . . . . . . . 145
Creating Instance Methods in a Class . . . . . . . . . . . . 147
Organizing Classes . . . . . . . . . . . . . . . . . . . 150
Declaring Objects and Using their Methods . . . . . . . . . . 154
Understanding Data Hiding . . . . . . . . . . . . . . . . 156
An Introduction to Using Constructors . . . . . . . . . . . . 159
Understanding that Classes Are Data Types . . . . . . . . . . 163
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 168
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 168
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 170
Review Questions . . . . . . . . . . . . . . . . . . . . . 171
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 174
Programming Exercises . . . . . . . . . . . . . . . . . 174
Debugging Exercises . . . . . . . . . . . . . . . . . . 177
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 178
Case Problems . . . . . . . . . . . . . . . . . . . . . 179

Copyright 2016 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.
CHAPT ER 4 More Object Concepts . . . . . . . . . . . 183
Understanding Blocks and Scope . . . . . . . . . . . . . . 184
Overloading a Method . . . . . . . . . . . . . . . . . . . 192
Automatic Type Promotion in Method Calls . . . . . . . . . 194
Learning About Ambiguity . . . . . . . . . . . . . . . . . 199 ix

Creating and Calling Constructors with Parameters . . . . . . . 200


Overloading Constructors . . . . . . . . . . . . . . . . 201
Learning About the this Reference . . . . . . . . . . . . . 205
Using the this Reference to Make Overloaded Constructors
More Efficient . . . . . . . . . . . . . . . . . . . . . 209
Using static Fields . . . . . . . . . . . . . . . . . . . 213
Using Constant Fields . . . . . . . . . . . . . . . . . . 215
Using Automatically Imported, Prewritten Constants
and Methods . . . . . . . . . . . . . . . . . . . . . . 220
The Math Class . . . . . . . . . . . . . . . . . . . . 221
Importing Classes that Are Not Imported Automatically . . . . 223
Using the LocalDate Class . . . . . . . . . . . . . . . 224
Understanding Composition and Nested Classes . . . . . . . . 230
Composition . . . . . . . . . . . . . . . . . . . . . . 230
Nested Classes . . . . . . . . . . . . . . . . . . . . . 232
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 234
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 234
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 236
Review Questions . . . . . . . . . . . . . . . . . . . . . 236
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 239
Programming Exercises . . . . . . . . . . . . . . . . . 239
Debugging Exercises . . . . . . . . . . . . . . . . . . 242
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 242
Case Problems . . . . . . . . . . . . . . . . . . . . . 243

CHAPT ER 5 Making Decisions . . . . . . . . . . . . . 245


Planning Decision-Making Logic . . . . . . . . . . . . . . . 246
The if and if…else Statements . . . . . . . . . . . . . . 248
The if Statement . . . . . . . . . . . . . . . . . . . . 248
Pitfall: Misplacing a Semicolon in an if Statement . . . . . . 249
Pitfall: Using the Assignment Operator Instead
of the Equivalency Operator . . . . . . . . . . . . . . 250

Copyright 2016 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

Pitfall: Attempting to Compare Objects


Using the Relational Operators . . . . . . . . . . . . . 251
The if…else Statement . . . . . . . . . . . . . . . . . 251
Using Multiple Statements in if and if…else Clauses . . . . 254
x Nesting if and if…else Statements . . . . . . . . . . . . 260
Using Logical AND and OR Operators . . . . . . . . . . . . 263
The AND Operator . . . . . . . . . . . . . . . . . . . . 263
The OR Operator . . . . . . . . . . . . . . . . . . . . 265
Short-Circuit Evaluation . . . . . . . . . . . . . . . . . . 266
Making Accurate and Efficient Decisions . . . . . . . . . . . 269
Making Accurate Range Checks . . . . . . . . . . . . . . 270
Making Efficient Range Checks . . . . . . . . . . . . . . 272
Using && and || Appropriately . . . . . . . . . . . . . . 273
Using the switch Statement . . . . . . . . . . . . . . . . 274
Using the Conditional and NOT Operators . . . . . . . . . . . 280
Using the NOT Operator . . . . . . . . . . . . . . . . . 281
Understanding Operator Precedence . . . . . . . . . . . . . 282
Adding Decisions and Constructors
to Instance Methods . . . . . . . . . . . . . . . . . . . 285
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 289
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 289
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 291
Review Questions . . . . . . . . . . . . . . . . . . . . . 291
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 294
Programming Exercises . . . . . . . . . . . . . . . . . 294
Debugging Exercises . . . . . . . . . . . . . . . . . . 297
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 297
Case Problems . . . . . . . . . . . . . . . . . . . . . 299

CHAPT ER 6 Looping . . . . . . . . . . . . . . . . . 301


Learning About the Loop Structure . . . . . . . . . . . . . . 302
Creating while Loops . . . . . . . . . . . . . . . . . . 303
Writing a Definite while Loop . . . . . . . . . . . . . . 303
Pitfall: Failing to Alter the Loop Control Variable
Within the Loop Body . . . . . . . . . . . . . . . . . 305
Pitfall: Unintentionally Creating a Loop with
an Empty Body . . . . . . . . . . . . . . . . . . . . 306

Copyright 2016 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.
Altering a Definite Loop’s Control Variable . . . . . . . . . . 307
Writing an Indefinite while Loop . . . . . . . . . . . . . 308
Validating Data . . . . . . . . . . . . . . . . . . . . . 310
Using Shortcut Arithmetic Operators . . . . . . . . . . . . . 314
Creating a for Loop . . . . . . . . . . . . . . . . . . . 319 xi
Unconventional for Loops . . . . . . . . . . . . . . . . 320
Learning How and When to Use a do…while Loop . . . . . . 325
Learning About Nested Loops . . . . . . . . . . . . . . . . 328
Improving Loop Performance . . . . . . . . . . . . . . . . 333
Avoiding Unnecessary Operations . . . . . . . . . . . . . 333
Considering the Order of Evaluation of Short-Circuit
Operators . . . . . . . . . . . . . . . . . . . . . . 334
Comparing to Zero . . . . . . . . . . . . . . . . . . . 334
Employing Loop Fusion . . . . . . . . . . . . . . . . . . 336
Using Prefix Incrementing Rather than Postfix
Incrementing . . . . . . . . . . . . . . . . . . . . . 337
A Final Note on Improving Loop Performance . . . . . . . . 338
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 342
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 342
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 344
Review Questions . . . . . . . . . . . . . . . . . . . . . 344
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 347
Programming Exercises . . . . . . . . . . . . . . . . . 347
Debugging Exercises . . . . . . . . . . . . . . . . . . 350
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 350
Case Problems . . . . . . . . . . . . . . . . . . . . . 352

CHAPT ER 7 Characters, Strings, and


the StringBuilder . . . . . . . . . . . . 353
Understanding String Data Problems . . . . . . . . . . . . . 354
Using Character Class Methods . . . . . . . . . . . . . . 355
Declaring and Comparing String Objects . . . . . . . . . . 359
Comparing String Values . . . . . . . . . . . . . . . . 359
Empty and null Strings . . . . . . . . . . . . . . . . . 363
Using Other String Methods . . . . . . . . . . . . . . . 365
Converting String Objects to Numbers . . . . . . . . . . 369

Copyright 2016 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

Learning About the StringBuilder


and StringBuffer Classes . . . . . . . . . . . . . . 374
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 381
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 382
xii Chapter Summary . . . . . . . . . . . . . . . . . . . . . 382
Review Questions . . . . . . . . . . . . . . . . . . . . . 383
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 385
Programming Exercises . . . . . . . . . . . . . . . . . 385
Debugging Exercises . . . . . . . . . . . . . . . . . . 388
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 388
Case Problems . . . . . . . . . . . . . . . . . . . . . 391

CHAPT ER 8 Arrays . . . . . . . . . . . . . . . . . . 393


Declaring Arrays . . . . . . . . . . . . . . . . . . . . . 394
Initializing an Array . . . . . . . . . . . . . . . . . . . . 399
Using Variable Subscripts with an Array . . . . . . . . . . . . 402
Using the Enhanced for Loop . . . . . . . . . . . . . . 403
Using Part of an Array . . . . . . . . . . . . . . . . . . 404
Declaring and Using Arrays of Objects . . . . . . . . . . . . 406
Using the Enhanced for Loop with Objects . . . . . . . . . 408
Manipulating Arrays of Strings . . . . . . . . . . . . . 408
Searching an Array and Using Parallel Arrays . . . . . . . . . 414
Using Parallel Arrays . . . . . . . . . . . . . . . . . . . 415
Searching an Array for a Range Match . . . . . . . . . . . 418
Passing Arrays to and Returning Arrays from Methods . . . . . 422
Returning an Array from a Method . . . . . . . . . . . . . 426
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 428
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 428
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 429
Review Questions . . . . . . . . . . . . . . . . . . . . . 430
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 433
Programming Exercises . . . . . . . . . . . . . . . . . 433
Debugging Exercises . . . . . . . . . . . . . . . . . . 435
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 435
Case Problems . . . . . . . . . . . . . . . . . . . . . 438

Copyright 2016 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.
CHAPT ER 9 Advanced Array Concepts . . . . . . . . . 439
Sorting Array Elements Using the Bubble Sort Algorithm . . . . 440
Using the Bubble Sort Algorithm . . . . . . . . . . . . . . 440
Improving Bubble Sort Efficiency . . . . . . . . . . . . . 442
Sorting Arrays of Objects . . . . . . . . . . . . . . . . . 443 xiii

Sorting Array Elements Using the Insertion Sort Algorithm . . . . 448


Using Two-Dimensional and Other Multidimensional Arrays . . . . 452
Passing a Two-Dimensional Array to a Method . . . . . . . . 454
Using the length Field with a Two-Dimensional Array . . . . 455
Understanding Ragged Arrays . . . . . . . . . . . . . . . 456
Using Other Multidimensional Arrays . . . . . . . . . . . . 456
Using the Arrays Class . . . . . . . . . . . . . . . . . . 459
Using the ArrayList Class . . . . . . . . . . . . . . . . 467
Creating Enumerations . . . . . . . . . . . . . . . . . . . 472
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 479
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 479
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 480
Review Questions . . . . . . . . . . . . . . . . . . . . . 481
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 484
Programming Exercises . . . . . . . . . . . . . . . . . 484
Debugging Exercises . . . . . . . . . . . . . . . . . . 486
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 487
Case Problems . . . . . . . . . . . . . . . . . . . . . 490

CHAPT ER 10 Introduction to Inheritance . . . . . . . . . 491


Learning About the Concept of Inheritance . . . . . . . . . . 492
Diagramming Inheritance Using the UML . . . . . . . . . . 492
Inheritance Terminology . . . . . . . . . . . . . . . . . 495
Extending Classes . . . . . . . . . . . . . . . . . . . . . 496
Overriding Superclass Methods . . . . . . . . . . . . . . . 502
Using the @Override Tag . . . . . . . . . . . . . . . . 504
Calling Constructors During Inheritance . . . . . . . . . . . . 507
Using Superclass Constructors that
Require Arguments . . . . . . . . . . . . . . . . . . 508
Accessing Superclass Methods . . . . . . . . . . . . . . . 513
Comparing this and super . . . . . . . . . . . . . . . 515
Employing Information Hiding . . . . . . . . . . . . . . . . 516

Copyright 2016 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

Methods You Cannot Override . . . . . . . . . . . . . . . . 518


A Subclass Cannot Override static Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 518
A Subclass Cannot Override final Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 522
xiv
A Subclass Cannot Override Methods
in a final Superclass . . . . . . . . . . . . . . . . 523
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 525
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 525
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 526
Review Questions . . . . . . . . . . . . . . . . . . . . . 527
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 530
Programming Exercises . . . . . . . . . . . . . . . . . 530
Debugging Exercises . . . . . . . . . . . . . . . . . . 533
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 534
Case Problems . . . . . . . . . . . . . . . . . . . . . 535

CHAPT ER 11 Advanced Inheritance Concepts . . . . . . . 537


Creating and Using Abstract Classes . . . . . . . . . . . . . 538
Using Dynamic Method Binding . . . . . . . . . . . . . . . 547
Using a Superclass as a Method Parameter Type . . . . . . 549
Creating Arrays of Subclass Objects . . . . . . . . . . . . . 551
Using the Object Class and Its Methods . . . . . . . . . . . 554
Using the toString() Method . . . . . . . . . . . . . 556
Using the equals() Method . . . . . . . . . . . . . . . 559
Using Inheritance to Achieve Good Software Design . . . . . . 564
Creating and Using Interfaces . . . . . . . . . . . . . . . . 565
Creating Interfaces to Store Related Constants . . . . . . . 570
Creating and Using Packages . . . . . . . . . . . . . . . . 574
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 580
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 580
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 581
Review Questions . . . . . . . . . . . . . . . . . . . . . 582
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 585
Programming Exercises . . . . . . . . . . . . . . . . . 585
Debugging Exercises . . . . . . . . . . . . . . . . . . 589
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 590
Case Problems . . . . . . . . . . . . . . . . . . . . . 590
Copyright 2016 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.
CHAPT ER 12 Exception Handling . . . . . . . . . . . . 593
Learning About Exceptions . . . . . . . . . . . . . . . . . 594
Trying Code and Catching Exceptions . . . . . . . . . . . . 599
Using a try Block to Make Programs “Foolproof” . . . . . . 604
Declaring and Initializing Variables in try…catch Blocks . . . 606 xv

Throwing and Catching Multiple Exceptions . . . . . . . . . . 609


Using the finally Block . . . . . . . . . . . . . . . . . 615
Understanding the Advantages of Exception Handling . . . . . . 618
Specifying the Exceptions that a Method Can Throw . . . . . . 621
Tracing Exceptions Through the Call Stack . . . . . . . . . . 626
Creating Your Own Exception Classes . . . . . . . . . . . 630
Using Assertions . . . . . . . . . . . . . . . . . . . . . 634
Displaying the Virtual Keyboard . . . . . . . . . . . . . . . 650
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 653
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 654
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 655
Review Questions . . . . . . . . . . . . . . . . . . . . . 656
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 659
Programming Exercises . . . . . . . . . . . . . . . . . 659
Debugging Exercises . . . . . . . . . . . . . . . . . . 662
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 662
Case Problems . . . . . . . . . . . . . . . . . . . . . 663

CHAPT ER 13 File Input and Output . . . . . . . . . . . . 665


Understanding Computer Files . . . . . . . . . . . . . . . 666
Using the Path and Files Classes . . . . . . . . . . . . . 667
Creating a Path . . . . . . . . . . . . . . . . . . . . . 668
Retrieving Information About a Path . . . . . . . . . . . . 669
Converting a Relative Path to an Absolute One . . . . . . . . 670
Checking File Accessibility . . . . . . . . . . . . . . . . 671
Deleting a Path . . . . . . . . . . . . . . . . . . . . . 673
Determining File Attributes . . . . . . . . . . . . . . . . 674
File Organization, Streams, and Buffers . . . . . . . . . . . . 678
Using Java’s IO Classes . . . . . . . . . . . . . . . . . . 680
Writing to a File . . . . . . . . . . . . . . . . . . . . . 683
Reading from a File . . . . . . . . . . . . . . . . . . . 685

Copyright 2016 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

Creating and Using Sequential Data Files . . . . . . . . . . . 687


Learning About Random Access Files . . . . . . . . . . . . 693
Writing Records to a Random Access Data File . . . . . . . . 697
Reading Records from a Random Access Data File . . . . . . . 704
xvi Accessing a Random Access File Sequentially . . . . . . . . 704
Accessing a Random Access File Randomly . . . . . . . . . 705
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 719
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 719
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 720
Review Questions . . . . . . . . . . . . . . . . . . . . . 721
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 724
Programming Exercises . . . . . . . . . . . . . . . . . 724
Debugging Exercises . . . . . . . . . . . . . . . . . . 726
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 727
Case Problems . . . . . . . . . . . . . . . . . . . . . 727

CHAPT ER 14 Introduction to Swing Components . . . . . 729


Understanding Swing Components . . . . . . . . . . . . . 730
Using the JFrame Class . . . . . . . . . . . . . . . . . . 731
Customizing a JFrame’s Appearance . . . . . . . . . . . 734
Using the JLabel Class . . . . . . . . . . . . . . . . . . 738
Changing a JLabel’s Font . . . . . . . . . . . . . . . . 740
Using a Layout Manager . . . . . . . . . . . . . . . . . . 743
Extending the JFrame Class . . . . . . . . . . . . . . . . 746
Adding JTextFields, JButtons, and Tool Tips to a
JFrame . . . . . . . . . . . . . . . . . . . . . . . . 748
Adding JTextFields . . . . . . . . . . . . . . . . . . 748
Adding JButtons . . . . . . . . . . . . . . . . . . . 750
Using Tool Tips . . . . . . . . . . . . . . . . . . . . . 752
Learning About Event-Driven Programming . . . . . . . . . . 755
Preparing Your Class to Accept Event Messages . . . . . . . 756
Telling Your Class to Expect Events to Happen . . . . . . . 757
Telling Your Class How to Respond to Events . . . . . . . . 757
An Event-Driven Program . . . . . . . . . . . . . . . . . 757
Using Multiple Event Sources . . . . . . . . . . . . . . . 759
Using the setEnabled() Method . . . . . . . . . . . . 761
Understanding Swing Event Listeners . . . . . . . . . . . . 764

Copyright 2016 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.
Using the JCheckBox, ButtonGroup, and JComboBox
Classes . . . . . . . . . . . . . . . . . . . . . . . . 767
The JCheckBox Class . . . . . . . . . . . . . . . . . 767
The ButtonGroup Class . . . . . . . . . . . . . . . . 771
The JComboBox Class . . . . . . . . . . . . . . . . . 772 xvii
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 780
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 780
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 781
Review Questions . . . . . . . . . . . . . . . . . . . . . 783
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 785
Programming Exercises . . . . . . . . . . . . . . . . . 785
Debugging Exercises . . . . . . . . . . . . . . . . . . 787
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 787
Case Problems . . . . . . . . . . . . . . . . . . . . . 788

CHAPT ER 15 Advanced GUI Topics . . . . . . . . . . . 791


Understanding the Content Pane . . . . . . . . . . . . . . 792
Using Color . . . . . . . . . . . . . . . . . . . . . . . 795
Learning More About Layout Managers . . . . . . . . . . . . 797
Using BorderLayout . . . . . . . . . . . . . . . . . 798
Using FlowLayout . . . . . . . . . . . . . . . . . . . 800
Using GridLayout . . . . . . . . . . . . . . . . . . . 802
Using CardLayout . . . . . . . . . . . . . . . . . . . 803
Using Advanced Layout Managers . . . . . . . . . . . . . 805
Using the JPanel Class . . . . . . . . . . . . . . . . . . 813
Creating JScrollPanes . . . . . . . . . . . . . . . . . 821
A Closer Look at Events and Event Handling . . . . . . . . . . 824
An Event-Handling Example: KeyListener . . . . . . . . 827
Using AWTEvent Class Methods . . . . . . . . . . . . . . 830
Understanding x- and y-Coordinates . . . . . . . . . . . . 832
Handling Mouse Events . . . . . . . . . . . . . . . . . . 832
Using Menus . . . . . . . . . . . . . . . . . . . . . . . 837
Using Specialized Menu Items . . . . . . . . . . . . . . . 841
Using addSeparator() . . . . . . . . . . . . . . . . 843
Using setMnemonic() . . . . . . . . . . . . . . . . . 843
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 848
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 849

Copyright 2016 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

Chapter Summary . . . . . . . . . . . . . . . . . . . . . 850


Review Questions . . . . . . . . . . . . . . . . . . . . . 851
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 853
Programming Exercises . . . . . . . . . . . . . . . . . 853
xviii Debugging Exercises . . . . . . . . . . . . . . . . . . 855
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 855
Case Problems . . . . . . . . . . . . . . . . . . . . . 859

CHAPT ER 16 Graphics . . . . . . . . . . . . . . . . . 861


Learning About Rendering Methods . . . . . . . . . . . . . 862
Drawing Strings . . . . . . . . . . . . . . . . . . . . . . 865
Repainting . . . . . . . . . . . . . . . . . . . . . . . 867
Setting a Font . . . . . . . . . . . . . . . . . . . . . 869
Using Color . . . . . . . . . . . . . . . . . . . . . . 870
Drawing Lines and Shapes . . . . . . . . . . . . . . . . . 874
Drawing Lines . . . . . . . . . . . . . . . . . . . . . 874
Drawing Unfilled and Filled Rectangles . . . . . . . . . . . 875
Drawing Clear Rectangles . . . . . . . . . . . . . . . . 875
Drawing Rounded Rectangles . . . . . . . . . . . . . . . 876
Drawing Shadowed Rectangles . . . . . . . . . . . . . . 878
Drawing Ovals . . . . . . . . . . . . . . . . . . . . . 879
Drawing Arcs . . . . . . . . . . . . . . . . . . . . . . 880
Creating Polygons . . . . . . . . . . . . . . . . . . . . 881
Copying an Area . . . . . . . . . . . . . . . . . . . . 883
Using the paint() Method with JFrames . . . . . . . . . 883
Learning More About Fonts . . . . . . . . . . . . . . . . . 891
Discovering Screen Statistics . . . . . . . . . . . . . . . 893
Discovering Font Statistics . . . . . . . . . . . . . . . . 894
Drawing with Java 2D Graphics . . . . . . . . . . . . . . . 898
Specifying the Rendering Attributes . . . . . . . . . . . . 899
Setting a Drawing Stroke . . . . . . . . . . . . . . . . . 901
Creating Objects to Draw . . . . . . . . . . . . . . . . . 902
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 910
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 911
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 911
Review Questions . . . . . . . . . . . . . . . . . . . . . 912
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 915

Copyright 2016 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.
Programming Exercises . . . . . . . . . . . . . . . . . 915
Debugging Exercises . . . . . . . . . . . . . . . . . . 916
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 916
Case Problems . . . . . . . . . . . . . . . . . . . . . 918
xix
APPENDIX A Working with the Java Platform . . . . . . . 919
Learning about the Java SE Development Kit . . . . . . . . . 920
Configuring Windows to Use the JDK . . . . . . . . . . . . . 920
Finding the Command Prompt . . . . . . . . . . . . . . . 921
Command Prompt Anatomy . . . . . . . . . . . . . . . . 921
Changing Directories . . . . . . . . . . . . . . . . . . 921
Setting the class and classpath Variables . . . . . . . 922
Changing a File’s Name . . . . . . . . . . . . . . . . . 922
Compiling and Executing a Java Program . . . . . . . . . . . 923
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 923

APPENDIX B Data Representation . . . . . . . . . . . . 925


Understanding Numbering Systems . . . . . . . . . . . . . 926
Representing Numeric Values . . . . . . . . . . . . . . . . 927
Representing Character Values . . . . . . . . . . . . . . . 929
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 930

APPENDIX C Formatting Output . . . . . . . . . . . . . 931


Rounding Numbers . . . . . . . . . . . . . . . . . . . . 932
Using the printf() Method . . . . . . . . . . . . . . . . 933
Specifying a Number of Decimal Places to
Display with printf() . . . . . . . . . . . . . . . . 936
Specifying a Field Size with printf() . . . . . . . . . . . 937
Using the Optional Argument Index with printf() . . . . . 938
Using the DecimalFormat Class . . . . . . . . . . . . . 939
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 940

APPENDIX D Generating Random Numbers . . . . . . . . 941


Understanding Computer-Generated Random Numbers . . . . . 942
Using the Math.random() Method . . . . . . . . . . . . . 943
Using the Random Class . . . . . . . . . . . . . . . . . . 944
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 947

Copyright 2016 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

APPENDIX E Javadoc . . . . . . . . . . . . . . . . . 949


The Javadoc Documentation Generator . . . . . . . . . . . . 950
Javadoc Comment Types . . . . . . . . . . . . . . . . . . 950
Generating Javadoc Documentation . . . . . . . . . . . . . 952
xx Specifying Visibility of Javadoc Documentation . . . . . . . . 955
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 956

Glossary . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . 979

Copyright 2016 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, Eighth 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. It provides a solid
background in good object-oriented programming techniques and introduces terminology
using clear, familiar language. 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. 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, Eighth 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.

Organization and Coverage


Java Programming, Eighth Edition, presents Java programming concepts, enforcing good
style, logical thinking, and the object-oriented paradigm. Objects are covered right from the
beginning, earlier than in many other textbooks. You create your first Java program in
Chapter 1. Chapters 2, 3, and 4 increase your understanding of how data, classes, objects,
and methods interact in an object-oriented environment.
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.

Copyright 2016 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 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
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.
xxii
Chapters 14, 15, and 16 introduce GUI Swing components (Java’s visually pleasing,
user-friendly widgets), their layout managers, and graphics.

Features
The following features are new for the Eighth Edition:
JAVA 8E: All programs have been tested using Java 8e, the newest edition of Java.
WINDOWS 8.1: All programs have been tested in Windows 8.1, and all screen shots have
been taken in this new environment.
DATE AND TIME CLASSES: This edition provides thorough coverage of the java.time
package, which is new in Java 8e.
ON-SCREEN KEYBOARD: This edition provides instructions for displaying and using an
on-screen keyboard with either a touch screen or a standard screen.
MODERNIZED GRAPHICS OUTPUT: The chapter on graphics (Chapter 16) has been
completely rewritten to focus on Swing component graphics production using the
paintComponent() method.

MODERNIZED OVERRIDING: The @Override tag is introduced.


EXPANDED COVERAGE OF THE EQUALS() METHOD: The book provides a thorough
explanation of the difference between overloading and overriding the equals() method.
PROGRAMMING EXERCISES: Each chapter contains several new programming exercises
not seen in previous editions. All exercises and their solutions from the previous edition
that were replaced in this edition are still available in the Instructor’s Resource Kit.
Additionally, Java Programming, Eighth Edition, includes the following features:
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.
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.
NOTES: These highlighted tips provide additional information—for example, an
alternative method of performing a procedure, another term for a concept, background
information on a technique, or a common error to avoid.

Copyright 2016 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

EMPHASIS ON STUDENT RESEARCH: 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.
FIGURES: Each chapter contains many figures. Code figures are most frequently 25 lines
xxiii
or fewer, illustrating one concept at a time. Frequent screen shots show exactly how
program output appears. Callouts appear where needed to emphasize a point.
COLOR: The code figures in each chapter contain all Java keywords in blue. This helps
students identify keywords more easily, distinguishing them from programmer-selected
names.
FILES: More than 200 student files can be downloaded from the publisher’s Web site. Most
files contain the code presented in the figures in each chapter; students can run the code for
themselves, view the output, and make changes to the code to observe the effects. Other
files include debugging exercises that help students improve their programming skills.
TWO TRUTHS & A LIE: A short quiz reviews each chapter section, with answers provided.
This quiz contains three statements based on the preceding section of text—two
statements are true and one is false. Over the years, students have requested answers to
problems, but we have hesitated to distribute them in case instructors want to use
problems as assignments or test questions. These true–false quizzes provide students with
immediate feedback as they read, without “giving away” answers to the multiple-choice
questions and programming exercises.
DON’T DO IT: This section at the end of each chapter summarizes common mistakes and
pitfalls that plague new programmers while learning the current topic.
KEY TERMS: Each chapter includes a list of newly introduced vocabulary, shown in the
order of appearance in the text. The list of key terms provides a short review of the major
concepts in the chapter.
SUMMARIES: Following each chapter is a summary that recaps the programming
concepts and techniques covered in the chapter. This feature provides a concise means for
students to check their understanding of the main points in each chapter.
REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve as a
review of chapter topics.
GAME ZONE: Each chapter provides one or more exercises in which students can create
interactive games using the programming techniques learned up to that point; 70 game
programs are suggested in the book. The games are fun to create and play; writing them
motivates students to master the necessary programming techniques. Students might
exchange completed game programs with each other, suggesting improvements and
discovering alternate ways to accomplish tasks.
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.
Copyright 2016 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

GLOSSARY: This edition contains an alphabetized list of all key terms identified in the
book, along with their definitions.
APPENDICES: This edition includes useful appendices on working with the Java platform,
data representation, formatting output, generating random numbers, and creating Javadoc
comments.
xxiv
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) 8, the
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:
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.
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.
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 sso.cengage.com. An instructor login is required.
Electronic Instructor’s Manual: The Instructor’s Manual that accompanies this
textbook contains 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.

Copyright 2016 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.
Acknowledgments

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.
Programming Exercises and Solutions: Each chapter is accompanied by several
xxv
programming exercises to supplement those offered in the text. Instructors can use
these exercises as additional or alternate assignments, or as the basis for lectures.
Test Bank: Cengage Learning Testing Powered by Cognero is a flexible, online system
that allows you to:
Author, edit, and manage test bank content from multiple Cengage Learning
solutions.
Create multiple test versions in an instant.
Deliver tests from your LMS, your classroom, or anywhere you want.
PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides may be used to guide classroom presentations, to make available to
students for chapter review, or to print as classroom handouts. Files are provided for every
figure in the text. Instructors may use the files to customize PowerPoint slides, illustrate
quizzes, or create handouts.
Solutions: Solutions to “You Do It” exercises and all end-of-chapter exercises are
available. Annotated solutions are provided for some of the multiple-choice Review
Questions. For example, if students are likely to debate answer choices or not understand
the choice deemed to be the correct one, a rationale is provided.

Acknowledgments
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 Content Developer; Carmel Isaac, Content
Project Manager; and Chris Scriver and Danielle Shaw, 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 Bernice Cunningham, Wayne County Community College
District; Bev Eckel, Iowa Western Community College; John Russo, Wentworth Institute of
Technology; Leslie Spivey, Edison Community College; and Angeline Surber, Mesa
Community College.
Thanks, too, to my husband, Geoff, for his constant support and encouragement. Finally, this
book is dedicated to the newest Farrell, coming March 2015. As this book goes to production,
I don’t know your name or even your gender, but I do know that I love you.
Joyce Farrell

Copyright 2016 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.

To the User of the Data Files


To complete the steps and projects in this book, you need data files that have been created
specifically for this book. Your instructor will provide the data files to you. You also can
obtain the files electronically from www.CengageBrain.com. Find the ISBN of your title on the
back cover of your book, then enter the ISBN in the search box at the top of the Cengage
Brain home page. You can find the data files on the product page that opens. Note that
you can use a computer in your school lab or your own computer to complete the exercises
in this book.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you need the following:
Software: Java SE 8, available from www.oracle.com/technetwork/java/index.html. Although
almost all of the examples in this book will work with earlier versions of Java, this book was
created using Java 8. The book clearly points out the few cases when an example is based on
Java 7 and will not work with earlier versions of Java. You also need a text editor, such as
Notepad. A few exercises ask you to use a browser for research.
Hardware: If you are using Windows 8, the Java Web site suggests at least 128 MB of
memory and at least 181 MB of disk space. For other operating system requirements, see
http://java.com/en/download/help.

Copyright 2016 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

YOU DO IT sections walk


students through program
development step by step.

NOTES provide
additional information—
for example, another
location in the book that
expands on a topic, or a
common error to watch
out for.

The author does an awesome


job: the examples, problems,
VIDEO LESSONS help
and material are very easy to
explain important chapter
understand!
concepts. Videos are part
—Bernice Cunningham, of the text’s enhanced
Wayne County Community
CourseMate site.
College District
Copyright 2016 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

TWO TRUTHS & A LIE quizzes appear


after each chapter section, with
answers provided. The quiz contains
three statements based on the preceding
xxviii section of text—two statements are
true and one is false. Answers give
immediate feedback without “giving away”
answers to the multiple-choice questions
and programming problems later in
the chapter. Students also have the option
to take these quizzes electronically
through the enhanced CourseMate site.

DON'T DO IT sections at the end


of each chapter list advice for
avoiding common programming errors.

THE DON’T DO IT ICON illustrates


how NOT to do something—for
example, having a dead code
path in a program. This icon
provides a visual jolt to the student,

are NOT to be emulated and making


students more careful to recognize
problems in existing code.

Copyright 2016 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 found the author’s explanation of
difficult topics to be very clear and
thorough. PROGRAMMING EXERCISES provide
opportunities to practice concepts. These xxix
—Leslie Spivey,
exercises increase in difficulty and allow
Edison Community College
students to explore each major
programming concept presented in the
chapter. Additional programming
exercises are available in the Instructor's
Resource Kit.

REVIEW QUESTIONS test


student comprehension of the
major ideas and techniques
presented. Twenty questions
follow each chapter.

Copyright 2016 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

DEBUGGING EXERCISES are


xxx included with each chapter because
examining programs critically and
closely is a crucial programming skill.
Students can download these exercises
at www.CengageBrain.com and through
the CourseMate available for this text.
These files are also available to
instructors through sso.cengage.com.

CASE PROBLEMS provide opportunities


to build more detailed programs that
continue to incorporate increasing
functionality throughout the book.

GAME ZONE EXERCISES are included


at the end of each chapter. Students can
create games as an additional entertaining
way to understand key programming
concepts.

Copyright 2016 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

In this chapter, you will:

Define basic programming terminology


Compare procedural and object-oriented programming
Describe the features of the Java programming language
Analyze a Java application that produces console output
Compile a Java class and correct syntax errors
Run a Java application and correct logic errors
Add comments to a Java class
Create a Java application that produces GUI output
Find help

Copyright 2016 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

Learning Programming Terminology


A computer program is a set of instructions that you write to tell a computer what to do.
Computer equipment, such as a monitor or keyboard, is hardware, and programs are
software. A program that performs a task for a user (such as calculating and producing
2 paychecks, word processing, or playing a game) is application software; a program that
manages the computer itself (such as Windows or Linux) is system software. The logic
behind any computer program, whether it is an application or system program, determines
the exact order of instructions needed to produce desired results. Much of this book describes
how to develop the logic to create application software.
All computer programs ultimately are converted to machine language. Machine language,
or machine code, is the most basic set of instructions that a computer can execute. Each type
of processor (the internal hardware that handles computer instructions) has its own set of
machine language instructions. Programmers often describe machine language using 1s and
0s to represent the on-and-off circuitry of computer systems.
The system that uses only 1s and 0s is the binary numbering system. Appendix B describes the binary
system in detail. Later in this chapter, you will learn that bytecode is the name for the binary code created
when Java programs are converted to machine language.

Machine language is a low-level programming language, or one that corresponds closely to a


computer processor’s circuitry. Low-level languages require you to use memory addresses for
specific machines when you create commands. This means that low-level languages are
difficult to use and must be customized for every type of machine on which a program runs.
Fortunately, programming has evolved into an easier task because of the development of
high-level programming languages. A high-level programming language allows you to use
a vocabulary of reasonable terms, such as read, write, or add, instead of the sequences of
1s and 0s that perform these tasks. High-level languages also allow you to assign single-word,
intuitive names to areas of computer memory where you store data. This means you can use
identifiers such as hoursWorked or rateOfPay, rather than having to remember their memory
locations. Currently, over 2,000 high-level programming languages are available to
developers; Java is one of them.
Each high-level language has its own syntax, or rules about how language elements are
combined correctly to produce usable statements. For example, depending on the specific
high-level language, you might use the verb print or write to produce output. All languages
have a specific, limited vocabulary (the language’s keywords) and a specific set of rules for
using that vocabulary. When you are learning a computer programming language, such as
Java, C++, or Visual Basic, you really are learning the vocabulary and syntax for that language.
Using a programming language, programmers write a series of program statements, similar
to English sentences, to carry out the tasks they want the program to perform. Program
statements are also known as commands because they are orders to the computer, such as
“output this word” or “add these two numbers.”

Copyright 2016 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

After the program statements are written, high-level language programmers use a computer
program called a compiler or interpreter to translate their language statements into machine
language. A compiler translates an entire program before carrying out any statements, or
executing them, whereas an interpreter translates one program statement at a time,
executing a statement as soon as it is translated.
3
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 can be easier to develop and debug. Java uses the best of both technolo-
gies: 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).

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. Examples of syntax errors include misspelling a keyword or omitting a word that a
statement requires. When a syntax error is detected, the programmer can correct the error
and attempt another translation. Repairing all syntax errors is the first part of the process
of debugging a program—freeing the program of all flaws or errors, also known as bugs.
Figure 1-1 illustrates the steps a programmer takes while developing an executable program.
You will learn more about debugging Java programs later in this chapter.

Copyright 2016 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

Plan program logic

4
Write program language statements
that correspond to the logic

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

Execute the program

Examine
program output

Are there runtime Yes


or output errors?

No

Figure 1-1 The program development process

As Figure 1-1 shows, you might write a program with correct syntax that still contains logic
errors. A logic error is a bug that allows a program to run, but that causes it to operate
incorrectly. Correct logic requires that all the right commands be issued in the appropriate
order. Examples of logic errors include multiplying two values when you meant to divide

Copyright 2016 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

them or producing output prior to obtaining the appropriate input. When you develop a
program of any significant size, you should plan its logic before you write any program
statements.
Correcting logic errors is much more difficult than correcting syntax errors. Syntax errors are
discovered by the language translator when you compile a program, but a program can be free 5
of syntax errors and execute while still retaining logic errors. Often you can identify logic
errors only when you examine a program’s output. For example, if you know an employee’s
paycheck should contain the value $4,000, but when you examine a payroll program’s output
you see that it holds $40, then a logic error has occurred. Perhaps an incorrect calculation was
performed, or maybe the hours worked value was output by mistake instead of the net pay
value. When output is incorrect, the programmer must carefully examine all the statements
within the program, revise or move the offending statements, and translate and test the
program again.
Just because a program produces correct output does not mean it is free from logic errors. For example,
suppose that a program should multiply two values entered by the user, that the user enters two 2s, and the
output is 4. The program might actually be adding the values by mistake. The programmer would discover
the logic error only by entering different values, such as 5 and 7, and examining the result.

Programmers call some logic 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.

TWO TRUTHS & A LIE


Learning Programming Terminology

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.

1. Unlike a low-level programming language, a high-level programming language


allows you to use a vocabulary of reasonable terms instead of the sequences of
on-and-off switches that perform the corresponding tasks.
2. A syntax error occurs when you misuse a language; locating and repairing all
syntax errors is part of the process of debugging a program.
3. Logic errors are fairly easy to find because the software that translates a program
finds all the logic errors for you.

can usually be discovered only by examining a program’s output.


The false statement is #3. A language translator finds syntax errors, but logic errors

Copyright 2016 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

Comparing Procedural and Object-Oriented


Programming Concepts
Two popular approaches to writing computer programs are procedural programming and
object-oriented programming.
6

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 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—for example, the value might be read from an input device,
be multiplied by another variable representing hours worked, and 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, which are specific instances of those classes
Creating applications that manipulate or use those objects

Programmers use OO as an abbreviation for object-oriented; it is pronounced “oh oh.” Object-oriented


programming is abbreviated OOP, and pronounced to rhyme with soup.

Copyright 2016 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

Originally, object-oriented programming was used most frequently for two major types of
applications:
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
7
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.
Programmers would create classes for objects such as cars and pedestrians that contain their
own data and rules for behavior. For example, each car has a speed and a method for changing
that speed. The specific instances of cars could be set in motion to create a simulation of a real
city at rush hour.
Creating a GUI environment for users is also 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, not
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. In the first 13 chapters of this book, you will learn object-oriented
techniques that are appropriate for any program type; in the last chapters, you will apply what
you have learned about those techniques specifically to GUI applications.
Understanding object-oriented programming requires grasping three basic concepts:
Encapsulation as it applies to classes as objects
Inheritance
Polymorphism

Understanding Classes, Objects, and Encapsulation


In object-oriented terminology, a class is a term that describes a group or collection of
objects with common properties. In the same way that a blueprint exists before any houses
are built from it, and a recipe exists before any cookies are baked from it, a class definition
exists before any objects are created from it. A class definition describes what attributes its
objects will have and what those objects will be able to do. Attributes are the characteristics
that define an object; they are properties of the object. When you learn a programming
language such as Java, you learn to work with two types of classes: those that have already
been developed by the language’s creators and your own new, customized classes.

Copyright 2016 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

An object is a specific, concrete instance of a class. Creating an instance is called


instantiation. You can create objects from classes that you write and from classes written by
other programmers, including Java’s creators. The values contained in an object’s properties
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
8 class are make, model, year, and color. Each Automobile object possesses the same attributes,
but not necessarily the same values for those attributes. One Automobile might be a 2010
white Ford Taurus and another might be a 2015 red Chevrolet Camaro. Similarly, your dog
has the properties of all Dogs, including a breed, name, age, and whether its shots are current.
The values of the properties of an object are 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.

Dog class definition Dog class instances (objects)

Every Dog that is


created will have
a:

Name

Age
Ginger Bowser Roxy
Breed 6 2 1
Akita Retriever Beagle
Shot status Up to date Up to date Up to date

Figure 1-2 Dog class definition and some objects created from it

Copyright 2016 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

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, and determining the status of its gas tank. Similarly, a Dog might have
methods for walking, eating, and determining its name, and a program’s GUI components
might have methods for maximizing and minimizing them as well as determining their size. 9
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.
Encapsulation refers to two closely related object-oriented notions:

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.
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 can be 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.

Understanding Inheritance and Polymorphism


An important feature of object-oriented program design is inheritance—the ability to create
classes that share the attributes and methods of existing classes, but with more specific
features. For example, Automobile is a class, and all Automobile objects share many traits and
abilities. Convertible is a class that inherits from the Automobile class; a Convertible is a
type of Automobile that has and can do everything a “plain” Automobile does—but with an
added ability to lower its top. (In turn, Automobile inherits from the Vehicle class.)
Convertible is not an object—it is a class. A specific Convertible is an object—for example,
my1967BlueMustangConvertible.

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

Copyright 2016 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

other systems work because you realize that a convertible is a type of automobile, so 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.
A final important concept in object-oriented terminology is polymorphism. Literally,
10
polymorphism means “many forms”—it describes the feature of languages that allows the
same word or symbol to be interpreted correctly in different situations based on the context.
For example, although the classes Automobile, Sailboat, and Airplane all inherit from
Vehicle, turn and stop methods work differently for instances of those classes. The
advantages of polymorphism will become more apparent when you begin to create GUI
applications containing features such as windows, buttons, and menu bars. In a GUI application,
it is convenient to remember one method name, such as setColor or setHeight, and have it
work correctly no matter what type of object you are modifying.
When you see a plus sign (+) between two numbers, you understand they are being added.
When you see it carved in a tree between two names, you understand that the names are
linked romantically. Because the symbol has diverse meanings based on context, it is
polymorphic. Chapters 10 and 11 provide more information about inheritance and
polymorphism and how they are implemented in Java.

Watch the video Object-Oriented Programming.

TWO TRUTHS & A LIE


Comparing Procedural and Object-Oriented
Programming Concepts

1. An instance of a class is a created object that possesses the attributes and


methods described in the class definition.
2. Encapsulation protects data by hiding it within an object.
3. Polymorphism is the ability to create classes that share the attributes and methods
of existing classes, but with more specific features.

polymorphism describes the ability to use one term to cause multiple actions.
the 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

Copyright 2016 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

Features of the Java Programming Language


Java was developed by Sun Microsystems as an object-oriented language for general-purpose
business applications and for interactive, World Wide Web-based Internet applications.
(Sun was later acquired by Oracle Corporation.) Some of the advantages that make Java
a popular language are its security features and the fact that it is architecturally neutral: 11
Unlike other languages, you can use Java to write a program that runs on any operating
system (such as Windows, Mac OS, or Linux) or device (such as PCs, phones, and tablet
computers).
Java can be run on a wide variety of computers and devices because it does not execute
instructions on a computer directly. Instead, Java runs on a hypothetical computer known as
the Java Virtual Machine (JVM). When programmers call the JVM hypothetical, they mean it
is not a physical entity created from hardware, but is composed only of software.
Figure 1-3 shows the Java environment. Programming statements written in a high-level
programming language are source code. When you write a Java program, you first
construct the source code using a text editor such as Notepad or a development
environment and source code editor such as jGRASP, which you can download from the
Web for free. A development environment is a set of tools that help you write programs by
providing such features as displaying a language’s keywords in color. The statements are
saved in a file; then, the Java compiler converts the source code into a binary program of
bytecode. A program called the Java interpreter then checks the bytecode and
communicates with the operating system, executing the bytecode instructions line by line
within the Java Virtual Machine. Because the Java program is isolated from the operating
system, it is also insulated from the particular hardware on which it is run. Because of this
insulation, the JVM provides security against intruders accessing your computer’s hardware
through the operating system. Therefore, Java is more secure than other languages.
Another advantage provided by the JVM means less work for programmers—when using
other programming languages, software vendors usually have to produce multiple versions
of the same product (a Windows version, Macintosh version, UNIX version, Linux version,
and so on) so all users can run the program. With Java, one program version runs on all
these platforms. “Write once, run anywhere” (WORA) is the slogan developed by Sun
Microsystems to describe the ability of one Java program version to work correctly on
multiple platforms.
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 2016 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

Java Source Code

Source code is
stored on a disk in
12 a file with a name
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

JVM (named java.exe)


performs security checks
and translates bytecode to
machine language, which
Computer Operating
executes
System

Figure 1-3 The Java environment

Java Program Types


You can write two kinds of programs using Java:
Applets are programs that are embedded in a Web page. You can read about applets in a
special section at the end of this chapter.
Java applications are stand-alone programs. Java applications can be further subdivided
into console applications, which support character or text output to a computer screen,
and windowed applications, which create a GUI with elements such as menus, toolbars,
and dialog boxes. Console applications are the easier applications to create; you start using
them in the next section.

Copyright 2016 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.
Analyzing a Java Application that Produces Console Output

TWO TRUTHS & A LIE


Features of the Java Programming Language

1. Java was developed to be architecturally neutral, which means that anyone can 13
build an application without extensive study.
2. After you write a Java program, the compiler converts the source code into a binary
program of bytecode.
3. Java programs that are embedded in a Web page are called applets, while stand-
alone programs are called Java applications.

means that you can use Java to write a program that will run on any platform.
The false statement is #1. Java was developed to be architecturally neutral, which

Analyzing a Java Application that Produces


Console Output
At first glance, even the simplest Java application involves a fair amount of confusing syntax.
Consider the application in Figure 1-4. This program is written on seven lines, and its only
task is to display “First Java application” on the screen.

public class First


{
public static void main(String[] args)
{
System.out.println("First Java application");
}
}

Figure 1-4 The First class

In program code in figures in this book, Java keywords as well as true, false, and null are blue, and all
other program elements are black. A complete list of Java keywords is shown later in this chapter.

The code for every complete program shown in this book is available in a set of student files you can
download so that you can execute the programs on your own computer.

Copyright 2016 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.
Other documents randomly have
different content
BOOK V
Who is there that by energy of mind
Could build a poem worthy of our theme’s
Majesty and of these discoveries?
Or who has such a mastery of words
As to devise praises proportionate
To his deserts, who to us has bequeathed
Such prizes, earned by his own intellect?
No man, I think, formed of a mortal body.
For if we are to speak as the acknowledged
Majesty of our theme demands, a god
Was he, most noble Memmius, a god,
Who first found out that discipline of life
Which now is called philosophy, and whose skill
From such great billows and a gloom so dark
Delivered life, and steered it into a calm
So peaceful and beneath so bright a light.
For compare the divine discoveries
Of others in old times. ’Tis told that Ceres
First revealed corn to men, Liber the juice
Of grape-born wine; though life without these things
Might well have been sustained; and even now
’Tis said there are some people that live so.
But to live happily was not possible
Without a serene mind. Therefore more justly
Is this man deemed by us a god, from whom
Came those sweet solaces of life, which now
Already through great nations spread abroad
Have power to soothe men’s minds. Should you suppose
Moreover that the deeds of Hercules
Surpass his, then yet further will you drift
Out of true reason’s course. For what harm now
Would those great gaping jaws of Nemea’s lion
Do to us, and the bristly Arcadian boar?
What could the bull of Crete, or Lerna’s pest
The Hydra fenced around with venomous snakes,
And threefold Gerion’s triple-breasted might,
Or those brazen-plumed birds inhabiting
Stymphalian swamps, what injury so great
Could they inflict upon us, or the steeds
Of Thracian Diomede, with fire-breathing nostrils
Ranging Bistonia’s wilds and Ismarus?
Also the serpent, guardian of the bright
Gold-gleaming apples of the Hesperides,
Fierce and grim-glancing, with huge body coiled
Round the tree’s stem, how were it possible
He could molest us by the Atlantic shore
And those lone seas, where none of us sets foot,
And no barbarian ventures to draw near?
And all those other monsters which likewise
Have been destroyed, if they had not been vanquished,
What harm, pray, could they do, though now alive?
None, I presume: for the earth even now abounds
With wild beasts to repletion, and is filled
With shuddering terror throughout its woods, great mountains
And deep forests, regions which we have power
For the most part to avoid. But if the heart
Has not been purged, what tumults then, what dangers
Must needs invade us in our own despite!
What fierce anxieties, offspring of desire,
Rend the distracted man, what mastering fears!
Pride also, sordid avarice, and violence,
Of what calamities are not they the cause!
Luxury too, and slothfulness! He therefore
Who could subdue all these, and banish them
Out of our minds by force of words, not arms,
Is it not right we should deem such a man
Worthy to be numbered among the gods?
The more that he was wont in beautiful
And godlike speech to utter many truths
About the immortal gods themselves, and set
The whole nature of things in clear words forth.
I, in his footsteps treading, follow out
His reasonings and expound in my discourse
By what law all things are created, how
They are compelled to abide within that law,
Without power to annul the immutable
Decrees of time; and first above all else
The mind’s nature was found to be composed
Of a body that had birth, without the power
To endure through a long period unscathed:
For it was found to be mere images
That are wont to deceive the mind in sleep,
Whenever we appear to behold one
Whom life has abandoned. Now, for what remains,
The order of my argument has brought me
To the point where I must show both how the world
Is composed of a body which must die,
Also that it was born; and in what way
Matter once congregating and uniting
Established earth sky sea, the stars, the sun,
And the moon’s globe: also what living creatures
Rose from the earth, and which were those that never
At any time were born: next in what way
Mankind began to employ varied speech
One with another by giving names to things:
Then for what causes that fear of the gods
Entered their breasts, and now through the whole world
Gives sanctity to shrines, lakes and groves,
Altars and images of gods. Moreover
I will make plain by what force and control
Nature pilots the courses of the sun
And the wanderings of the moon, lest we perchance
Deem that they traverse of their own free will
Their yearly orbits between heaven and earth,
Obsequiously furthering the increase
Of crops and living things, or should suppose
Th t th ll d b th d ’d i
That they roll onwards by the gods’ design.
For those who have learnt rightly that the gods
Lead a life free from care, if yet they wonder
By what means all things can be carried on,
Such above all as are perceived to happen
In the ethereal regions overhead,
They are borne back again into their old
Religious fears, and adopt pitiless lords,
Whom in their misery they believe to be
Almighty; for they are ignorant of what can
And what cannot exist; in fine they know not
Upon what principle each thing has its powers
Limited, and its deep-set boundary stone.

But now, lest I detain you with more promises,


In the first place consider, Memmius,
The seas, the land, the sky, whose threefold nature,
Three bodies, three forms so dissimilar,
And three such wondrous textures, a single day
Shall give to destruction, and the world’s vast mass
And fabric, for so many years upheld,
Shall fall to ruin. Nor am I unaware
How novel and strange, when first it strikes the mind,
Must appear this destruction of earth and heaven
That is to be, and for myself how difficult
It will prove to convince you by mere words,
As happens when one brings to a man’s ears
Some notion unfamiliar hitherto,
If yet one cannot thrust it visibly
Beneath his eyes, or place it in his hands;
For the paved highway of belief through touch
And sight leads straightest into the human heart
And the precincts of the mind. Yet none the less
I will speak out. Reality itself
It may be will bring credence to my words,
And in a little while you will behold
The earth terribly quaking and all things
The earth terribly quaking, and all things
Shattered to ruins. But may pilot fortune
Steer far from us such disaster, and may reason
Convince us rather than reality
That the whole universe may well collapse,
Tumbling together with a dread crash and roar.

But before I attempt concerning this


To announce fate’s oracles in more holy wise,
And with assurance far more rational
Than doth the Pythoness, when from the tripod
And laurel wreath of Phoebus her voice sounds,
Many consolatories will I first
Expound to you in learned words, lest haply
Curbed by religion’s bit you should suppose
That earth and sun and sky, sea, stars and moon,
Their substance being divine, must needs abide
Eternally, and should therefore think it just
That all, after the manner of the giants,
Should suffer penance for their monstrous guilt
Who by their reasoning shake the world’s firm walls,
And fain would quench the glorious sun in heaven,
Shaming with mortal speech immortal things;
Though in fact such objects are so far removed
From any share in divine energy,
And so unworthy to be accounted gods,
That they may be considered with more reason
To afford us the conception of what is quite
Devoid of vital motion and of sense.
For truly by no means can we suppose
That the nature and judgment of the mind
Can exist linked with every kind of body,
Even as in the sky trees cannot exist,
Nor clouds in the salt waters, nor can fish
Live in the fields, neither can blood be found
In wood, nor sap in stones: but where each thing
Can dwell and grow is determined and ordained
Can dwell and grow, is determined and ordained.
Even so the nature of mind cannot be born
Alone without a body, nor exist
Separated from sinews and from blood.
But if (for this is likelier by far)
The mind’s force might reside within the head
Or shoulders, or be born down in the heels,
Or in any part you will, it would at least
Inhabit the same man and the same vessel.
But since even in our body it is seen
To be determined and ordained where soul
And mind can separately dwell and grow,
All the more must it be denied that mind
Cannot have being quite outside a body
And a living form, in crumbling clods of earth,
In the sun’s fire, or water, or aloft
In the domains of ether. Such things therefore
Are not endowed with divine consciousness,
Because they cannot be quickened into life.

This too you cannot possibly believe,


That there are holy abodes of deities
Anywhere in the world. For so tenuous
Is the nature of gods, and from our senses
So far withdrawn, that hardly can the mind
Imagine it. And seeing that hitherto
It has eluded touch or blow of hands,
It must touch nothing which for us is tangible:
For naught can touch that may not itself be touched.
So even their abodes must be unlike
Our own, tenuous as their bodies are.
All this hereafter I will prove to you
By plentiful argument. Further, to say
That for the sake of mankind the gods willed
To frame the wondrous nature of the world,
And that on this account we ought to extol
Their handiwork as worthy of all praise,
y p ,
And to believe that it will prove eternal
And indestructible, and to think it sin
Ever by any effort to disturb
What by the ancient wisdom of the gods
Has been established everlastingly
For mankind’s benefit, or by argument
To assail and overthrow it utterly
From top to bottom, and to invent besides
Other such errors—all this, Memmius,
Is folly. For what advantage could our thanks
Bestow upon immortal and blessed beings
That for our sakes they should bestir themselves
To perform any task? Or what new fact
Could have induced them, tranquil hitherto,
After so long to change their former life?
For it seems fitting he should take delight
In a new state of things, to whom the old
Was painful: but for him whom in past times,
While he was living in felicity,
No evil had befallen, for such a one
What could have kindled a desire for change?
Must we imagine that their life lay prostrate
In darkness and in misery, till the birth
And origin of things first dawned upon them?
Besides, what evil had it been to us
Not to have been created? For whoever
Has once been born, must wish to abide in life
So long as luring pleasure bids him stay:
But one who has never tasted the love of life,
Nor even been numbered in life’s ranks, what harm
Were it for him not to have been created?
Again whence first was implanted in the gods
A pattern for begetting things? Whence too
The preconception of what men should be,
So that they knew and imaged in their minds
What they desired to make? And by what means
y y
Could they have ever ascertained the energy
Latent in primal atoms, or what forms
Might be produced by changes in their order,
Unless Nature herself had given them first
A sample of creation? For indeed
These primal atoms in such multitudes
And in so many ways, through infinite time
Impelled by blows and moved by their own weight,
Have been borne onward so incessantly,
Uniting in every way and making trial
Of every shape they could combine to form,
That ’tis not strange if they have also fallen
Into such grouping, and acquired such motions
As those whereby the present sum of things
Is carried on and ceaselessly renewed.

But even were I ignorant how things


Were formed of primal elements, yet this
Would I have ventured to affirm, and prove
Not only from the system of the heavens,
But from much other evidence, that nature
Has by no means been fashioned for our benefit
By divine power; so great are the defects
Which are its bane. First, of the whole space
Covered by the enormous reach of heaven,
A greedy portion mountains occupy
And forests of wild beasts; rocks and waste swamps
Possess it, or the wide land-sundering sea.
Besides, well nigh two-thirds are stolen from men
By burning heat and frost ceaselessly falling.
All that is left for husbandry, even that
The force of Nature soon would overspread
With thorns, unless resisted by man’s force,
Ever wont for his livelihood to groan
Over the strong hoe, and with down-pressed plough
To cleave the earth. For if we do not turn
The fertile clods with coulters, and subduing
The soil of earth, summon the crops to birth,
They could not of their own accord spring up
Into the bright air. Even then sometimes,
When answering our long toil throughout the land
Every bud puts forth its leaves and flowers,
Either the sun in heaven scorches them
With too much heat, or sudden gusts of rain
Or nipping frosts destroy them, or wind-storms
Shatter them with impetuous whirling blasts.
Furthermore why does Nature multiply
And nourish terrible tribes of savage beasts
By land and sea, dangerous to mankind?
Why does untimely death range to and fro?
Then again, like a mariner cast ashore
By raging waves, the human infant lies
Naked upon the ground, speechless, in want
Of every help needful for life, when first
Nature by birth-throes from his mother’s womb
Thrusts him into the borders of the light,
So that he fills the room with piteous wailing,
As well he may, whose fate in life will be
To pass through so much misery. But flocks
And herds of divers kind, and the wild beasts,
These, as they grow up, have no need of rattles:
To none of them a foster-nurse must utter
Fond broken speech: they seek not different dresses
To suit each season: no, nor do they need
Weapons nor lofty walls whereby to guard
What is their own, since all things for them all
The Earth herself brings forth abundantly,
And Nature, the creatress manifold.

First of all, since the substance of the earth,


Moisture, and the light breathings of the air,
And burning heats, of which this sum of things
Is seen to be composed, have all been formed
Of a body that was born and that will die,
Of such a body must we likewise deem
That the whole nature of the world was made.
For things whose parts and members we see formed
Of a body that had birth and shapes that die,
These we perceive are themselves always mortal,
And likewise have been born. Since then we see
That the chief parts and members of the world
Decay and are reborn, it is no less certain
That once for heaven and earth there was a time
Of origin, and will be of destruction.

Herein lest you should think that without proof


I have seized this vantage, in that I have assumed
Earth and fire to be mortal, and have not doubted
That moisture and air perish, but maintained
That these too are reborn and grow afresh,
Consider first how no small part of the earth
Ceaselessly baked by the sun’s rays and trampled
By innumerable feet, gives off a mist
And flying clouds of dust, which the strong winds
Disperse through the whole atmosphere. Part too
Of the earth’s soil is turned to swamp by rains,
While scouring rivers gnaw their banks away.
Furthermore whatsoever goes to augment
Some other thing, is in its turn restored;
And since beyond all doubt the all-mother Earth
Is seen to be no less the general tomb,
You thus may see how she is ever lessened,
Yet with new growth increases evermore.

Next, that the sea, the rivers and the springs


Are always amply fed by new supplies
Of moisture oozing up perennially,
It needs no words to explain. The vast down-flow
Of waters from all sides is proof of this
Of waters from all sides is proof of this.
But as the water that is uppermost
Is always taken away, it comes to pass
That on the whole there is no overflow;
Partly because strong winds, sweeping the seas,
Diminish them, and the sun in heaven unweaves
Their fabric with his rays; partly because
The water is distributed below
Throughout all lands. For the salt is strained off,
And the pure fluid matter, oozing back,
Gathers together at the river-heads,
Thence in fresh current streams over the land,
Wherever it finds a channel ready scooped
To carry down its waves with liquid foot.

Now must I speak of air, which every hour


Is changed through its whole body in countless ways.
For always whatsoever flows from things
Is all borne into the vast sea of air:
And if it were not in its turn to give
Particles back to things, recruiting them
As they dissolve, all would have been long since
Disintegrated, and so changed to air.
Therefore it never ceases to be born
Out of things, and to pass back into things,
Since, as we know, all are in constant flux.

Likewise that bounteous fountain of clear light,


The sun in heaven, ceaselessly floods the sky
With fresh brightness, and momently supplies
The place of light with new light: for each former
Emission of his radiance perishes,
On whatsoever spot it falls. This truth
You may thus learn. So soon as clouds begin
To pass below the sun, and as it were
To break off the light’s rays, their lower part
Forthwith perishes wholly, and the earth
p y,
Is shadow-swept, wherever the clouds move.
Thus you may know that things have ever need
Of fresh illumination, and that each
Former discharge of radiance perishes,
Nor in any other way could things be seen
In sunlight, if the fountain-head itself
Did not send forth a perpetual supply.
Also those lights we use here upon earth
At night-time, hanging lamps, and torches bright
With darting beams, rich with abundant smoke,
Are in haste in like fashion to supply
New radiance with ministering fire;
The very flames seem eager, eager to flicker;
Nor does the still unbroken stream of light
One instant quit the spots whereon it played,
So suddenly is its perishing concealed
By the swift birth of flame from all these fires.
It is thus then you must think sun moon and stars
Shoot forth their light from ever fresh supplies,
And that they always lose whatever beams
Come foremost; lest perchance you should believe
Their energy to be indestructible.

Again, is it not seen that even stones


By time are vanquished, that tall towers fall
And rocks crumble away, that shrines and idols
Of gods grow worn out and dilapidate,
Nor may the indwelling holiness prolong
The bounds of destiny, or strive against
The laws of Nature? Then do we not see
The monuments of men, fallen to ruin,
Ask for themselves whether you would believe
That they also grow old?[F] See we not rocks
Split off from mountain heights fall crashing down
Unable more to endure the powerful stress
Of finite years? Surely they would not fall
y y y
Thus suddenly split off, if through the lapse
Of infinite past years they had withstood
All the assaults of time, without being shattered.
Now contemplate that which around and above
Compasses the whole earth with its embrace.
If it begets all things out of itself,
As some have told us, and receives them back
When they have perished, then the whole sky is made
Of a body that had birth and that must die.
For whatsoever nourishes and augments
Other things from itself, must needs be minished,
And be replenished, when it receives them back.

Moreover, if there never was a time


Of origin when earth and heaven were born,
If they have always been from everlasting,
Why then before the Theban war and Troy’s
Destruction, have not other poets sung
Of other deeds as well? Whither have vanished
So many exploits of so many men?
Why are they nowhere blossoming engrafted
On the eternal monuments of fame?
But in truth, as I think, this sum of things
Is in its youth: the nature of the world
Is recent, and began not long ago.
Wherefore even now some arts are being wrought
To their last polish, some are still in growth.
Of late many improvements have been made
In navigation, and musicians too
Have given birth to new melodious sounds.
Also this theory of the nature of things
Has been discovered lately, and I myself
Have only now been found the very first
Able to turn it into our native words.
Nevertheless, if you perchance believe
That long ago these things were just the same,
But that the generations of mankind
Perished by scorching heat, or that their cities
Fell in some great convulsion of the world,
Or else that flooded by incessant rains
Devouring rivers broke forth over the earth
And swallowed up whole towns, so much the more
Must you admit that there will come to pass
A like destruction of earth and heaven too.
For when things were assailed by such great maladies
And dangers, if some yet more fatal cause
Had whelmed them, they would then have been dissolved
In havoc and vast ruin far and wide.
And in no other way do we perceive
That we are mortal, save that we all alike
In turn fall sick of the same maladies
As those whom Nature has withdrawn from life.

Again, whatever things abide eternally,


Must either, because they are of solid body,
Repulse assaults, nor suffer anything
To penetrate them, which might have the power
To disunite the close-locked parts within:
(Such are those bodies whereof matter is made,
Whose nature we have shown before:) or else
They must be able to endure throughout
All time, because they are exempt from blows,
As void is, which abides untouched, nor suffers
One whit from any stroke: or else because
There is no further space surrounding them,
Into which things might as it were depart
And be dissolved; even as the sum of sums
Is eternal, nor is there any space
Outside it, into which its particles
Might spring asunder, nor are there other bodies
That could strike and dissolve them with strong blows.
But neither, as I have shown, is this world’s nature
S lid i h i id i d i hi
Solid, since there is void mixed up in things;
Nor yet is it like void; nor verily
Are atoms lacking that might well collect
Out of the infinite, and overwhelm
This sum of things with violent hurricane,
Or threaten it with some other form of ruin;
Nor further is there any want of room
And of deep space, into which the world’s walls
Might be dispersed abroad; or they may perish
Shattered by any other force you will.
Therefore the gates of death are never closed
Against sky, sun or earth, or the deep seas;
But they stand open, awaiting them with huge
Vast-gaping jaws. So you must needs admit
That all these likewise once were born: for things
Of mortal body could not until now
Through infinite past ages have defied
The strong powers of immeasurable time.

Again, since the chief members of the world


So mightily contend together, stirred
By unhallowed civil warfare, see you not
That some end may be set to their long strife?
It may be when the sun and every kind
Of heat shall have drunk all the moisture up,
And gained the mastery they were struggling for,
Though they have failed as yet to achieve their aim:
So vast are the supplies the rivers bring,
Threatening in turn to deluge every land
From out the deep abysses of the ocean;
All in vain, since the winds, sweeping the seas,
Diminish them, and the sun in heaven unweaves
Their fabric with his rays; and ’tis their boast
That they are able to dry all things up,
Before moisture can achieve its end.
So terrible a war do they breathe out
On eq al terms stri ing one ith another
On equal terms, striving one with another
For mighty issues: though indeed fire once
Obtained the mastery, so the fable tells,
And water once reigned supreme in the fields.
For fire prevailing licked up and consumed
Many things, when the ungovernable might
Of the Sun’s horses, swerving from their course,
Through the whole sky and over every land
Whirled Phaëthon. But then the almighty Father,
Stirred to fierce wrath, with sudden thunder-stroke
Dashed great-souled Phaëthon from his team to the earth,
And as he fell the Sun-god meeting him
Caught from him the world’s everlasting lamp,
And brought back tamed and trembling to the yoke
The scattered steeds; then on their wonted course
Guiding them, unto all things gave fresh life.
Thus verily the old Greek poets sang,
Though straying from true reason all too far.
For fire can only gain the mastery
When an excess of fiery particles
Have flocked together out of infinite space;
And then its strength fails, vanquished in some way,
Or else things perish, utterly consumed
By scorching gusts. Likewise moisture once
Gathering together, as the story tells,
Strove for the mastery, when it overwhelmed
Many cities of mankind. But afterwards,
When all that force, which out of infinite space
Had gathered itself up, was by some means
Diverted and withdrew, the rains ceased then,
And the violence of the rivers was abated.

But in what ways matter converging once


Established earth and heaven and the sea’s deeps,
The sun’s course and the moon’s, I will set forth
In order. For in truth not by design
Did the primordial particles of things
Did the primordial particles of things
Arrange themselves each in its own right place
With provident mind, nor verily have they bargained
What motions each should follow; but because
These primal atoms in such multitudes
And in so many ways through infinite time
Impelled by blows and moved by their own weight,
Have been borne onward so incessantly,
Uniting in every way and making trial
Of every shape they could combine to form,
Therefore it is that after wandering wide
Through vast periods, attempting every kind
Of union and of motion, they at last
Collect into such groups as, suddenly
Flocking together, oftentimes become
The rudiments of mighty things, of earth,
Sea and sky, and the race of living creatures.

At that time neither could the disk of the sun


Be seen flying aloft with bounteous light,
Nor the stars of great heaven, nor sea, nor sky,
Nor yet earth nor the air, nor anything
Resembling those things which we now behold,
But only a sort of strange tempest, a mass
Gathered together out of primal atoms
Of all kinds, which discordantly waged war
Disordering so their interspaces, paths,
Connections, weights, collisions, meetings, motions,
Since with their unlike forms and varied shapes,
They could not therefore all remain united,
Nor move among themselves harmoniously.
Thereupon parts began to fly asunder,
And like things to unite with like, and so
To separate off the world, and to divide
Its members, portioning out its mighty parts;
That is, to mark off the high heaven from earth,
And the sea by itself, that it might spread
And the sea by itself, that it might spread
With unmixed waters, and likewise the fires
Of aether by themselves, pure and unmixed.

Now first the several particles of earth,


Since they were heavy and close-packed, all met
Together in the middle, and took up
The lowest places: and the more they met
In close-packed throngs, the more did they squeeze out
Those particles which were to form sea, stars,
Sun and moon, and the walls of the great world.
For all these are of smoother rounder seeds,
And of much smaller elements than earth.
So first through porous openings in the soil
The fire-laden aether here and there
Bursting forth rose and lightly carried off
Many fires with it, much in the same way
As often we may see when first the beams
Of the radiant sun with golden morning light
Blush through the grasses gemmed with dew, and lakes
And ever-flowing rivers exhale mist,
While earth itself is sometimes seen to smoke;
And when floating aloft these vapours all
Unite on high, then taking bodily shape
As clouds, they weave a veil beneath the heavens.
Thus then the light diffusive aether once
Took bodily shape, and, arched round on all sides,
Far into every quarter spreading out,
So with its greedy embrace hemmed in all else.
Next came the rudiments of sun and moon,
Whose globes turn in the air midway between
Aether and earth; for neither did the earth
Nor the great aether claim them for itself,
Since they were not so heavy as to sink
And settle down, nor so light as to glide
Along the topmost borders: yet their course
Between the two is such, that as they roll
, y
Their lifelike bodies onward, they are still
Parts of the whole world; even as with us
Some of our members may remain at rest,
While at the same time others may be in motion.
So when these things had been withdrawn, the earth,
Where now the ocean’s vast blue region spreads,
Sank suddenly down, and flooded with salt surge
Its hollow parts. And day by day the more
The encircling aether’s heats and the sun’s rays
Compressed the earth into a closer mass
By constant blows upon its outer surface
From every side, so that thus beaten upon
It shrank and drew together round its centre,
The more did the salt sweat squeezed from its body
Increase by its oozings the sea’s floating plains,
And the more did those many particles
Of heat and air escaping fly abroad,
And far away from the earth condensing, form
The lofty glittering mansions of the sky.
The plains sank lower, the high mountains grew
Yet steeper; for the rocks could not sink down,
Nor could all parts subside to one same level.

Thus then the earth’s ponderous mass was formed


With close-packed body, and all the slime of the world
Slid to the lowest plane by its own weight,
And at the bottom settled down like dregs.
Then the sea, then the air, then the fire-laden
Aether itself, all these were now left pure
With liquid bodies. Some indeed are lighter
Than others, and most liquid and light of all
Over the airy currents aether floats,
Not blending with the turbulent atmosphere
Its liquid substance. All below, it suffers
To be embroiled by violent hurricanes,
Suffers all to be tossed with wayward storms,
While itself gliding on with changeless sweep
Bears its own fires along. For, that the aether
May stream on steadily with one impulse,
The Pontos demonstrates, that sea which streams
With an unchanging tide, unceasingly
Preserving as it glides one constant pace.

Now let us sing what cause could set the stars


In motion. First, if the great globe of heaven
Revolves, then we must needs maintain that air
Presses upon the axis at each end,
And holds it from outside, closing it in
At both poles; also that there streams above
Another current, moving the same way,
In which the stars of the eternal world
Roll glittering onward; or else that beneath
There is another stream, that drives the sphere
Upwards the opposite way, just as we see
Rivers turn mill-wheels with their water-scoops.
It likewise may well be that the whole sky
Remains at rest, yet that the shining signs
Are carried onwards; either because within them
Are shut swift tides of aether, that whirl round
Seeking a way out, and so roll their fires
On all sides through the sky’s nocturnal mansions;
Or else that from some other source outside
An air-stream whirls and drives the fires along;
Or else they may be gliding of themselves,
Moving whithersoever the food of each
Calls and invites them, nourishing everywhere
Their flaming bodies throughout the whole sky.
For it is hard to affirm with certainty
Which of these causes operates in this world:
But what throughout the universe both can
And does take place in various worlds, created
On various plans, this I teach, and proceed
T d h di i
To expound what divers causes may exist
Through the universe for the motion of the stars:
And one of these in our world too must be
The cause which to the heavenly signs imparts
Their motive vigour: but dogmatically
To assert which this may be, is in no wise
The function of those advancing step by step.

Now in order that the earth should be at rest


In the world’s midst, it would seem probable
That its weight gradually diminishing
Should disappear, and that the earth should have
Another nature underneath, conjoined
And blent in union from its earliest age
With those aerial portions of the world
Wherein it lives embodied. For this cause
It is no burden, nor weighs down the air,
Just as to a man his own limbs are no weight,
Nor is the head a burden to the neck,
Nor do we feel that the whole body’s weight
Rests on the feet: yet a much smaller burden
Laid on us from outside, will often hurt us.
Of such great moment is it what each thing’s
Function may be. Thus then the earth is not
An alien body intruded suddenly,
Nor thrust from elsewhere into an alien air,
But was conceived together with the world
At its first birth as a fixed portion of it,
Just as our limbs are seen to be of us.
Moreover the earth, when shaken suddenly
With violent thunder, by its trembling shakes
All that is over it; which in no wise
Could happen, if it were not closely bound
With the world’s airy parts, and with the sky.
For they all, as though by common roots, cohere
One with another, from their earliest age
Conjoined and blent in nion See o not too
Conjoined and blent in union. See you not too
That heavy as our body’s weight may be,
Yet the soul’s force, though subtle exceedingly,
Sustains it, being so closely joined and blent
In union with it? Also what has power
To lift the body with a nimble leap,
Except the mind’s force that controls the limbs?
Do you not now perceive how great the power
May be of a subtle nature, when ’tis joined
With a heavy body, even as with the earth
The air is joined, and the mind’s force with us?

Also the sun’s disk cannot be much larger,


Nor its heat be much less, than to our sense
They appear to be. For from whatever distance
Fires can fling light, and breathe upon our limbs
Their warming heat, these intervening spaces
Take away nothing from the body of flame;
The fire is not shrunken visibly.
So since the sun’s heat and the light it sheds
Both reach our senses and caress our limbs,
The form also and contour of the sun
Must needs be seen from the earth in their true scale,
With neither addition nor diminishment.
Also the moon, whether it moves along
Illuminating earth with borrowed light,
Or throws out its own rays from its own body,
Howe’er that be, moves with a shape no larger
Than seems that shape which our eyes contemplate.
For all things which we look at from far off
Through much air, seem to our vision to grow dim
Before their contours lessen. Therefore the moon,
Seeing that it presents a clear aspect
And definite shape, must needs by us on earth
Be seen on high in its defining outline
Just as it is, and of its actual size.
Lastly consider all those fires of aether
Lastly consider all those fires of aether
You see from the earth. Since fires, which here below
We observe, for so long as their flickering
Remains distinct, and their heat is perceived,
Are sometimes seen to change their size to less
Or greater to some very slight extent
According to their distance, you may thence
Know that the fires of aether can be smaller
Only by infinitesimal degrees,
Or larger by the tiniest minute fraction.

This also is not wonderful, how the sun


Small as it is, can shed so great a light,
As with its flood to fill all seas and lands
And sky, with warm heat bathing everything.
For from this spot perhaps a single well
For the whole world may open and gush out,
Shooting forth an abundant stream of light,
Because from everywhere throughout the world
In such wise do the particles of heat
Gather together, and their united mass
Converges in such wise, that blazing fire
Streams forth here from a single fountain-head.
See you not too how wide a meadow-land
One little spring of water sometimes floods,
Overflowing whole fields? It may be also
That from the sun’s flame, though it be not great,
Heat pervades the whole air with scorching fires,
Should the air chance to be susceptible
And ready to be kindled, when it is struck
By tiny heat-rays. Then we sometimes see
A wide-spread conflagration from one spark
Catch fields of corn or stubble. Perhaps too
The sun shining on high with ruddy torch
May be surrounded by much fire and heats
Invisible, fire which no radiance
Reveals, but laden with heat it does no more
Reveals, but laden with heat it does no more
Than reinforce the stroke of the sun’s rays.

Nor is there any single theory,


Certain and obvious, of how the sun
Out of his summer stations passing forth
Approaches the midwinter turning-point
Of Capricorn, and how coming back thence
He bends his course to the solstitial goal
Of Cancer; then too how the moon is seen
To traverse every month that space, whereon
The journeying sun spends a year’s period.
For these events, I say, no single cause
Can be assigned. It seems most probable
That the august opinion of Democritus
Should be the truth; the nearer to the earth
The several constellations move, the less
Can they be borne on with the whirl of heaven:
For in the lower portions of this whirl
He says its speed and energy diminish
And disappear; so that little by little
The sun is outstripped by the signs that follow,
Since he is far beneath the burning stars.
And the moon, so he says, more than the sun.
The lower and the further from the sky
Her course is, and the nearer to the earth,
The less can she keep even with the signs.
For the more languid is the whirl whereby
She is borne along, being lower than the sun,
The more do all the signs around her path
Overtake and pass by her. Thus it is
That she seems to move backward to each sign
More quickly, because the signs come up to her.
It may be also that two streams of air
Cross the sun’s path at fixed times, each in turn
Flowing from opposite quarters of the world,
Whereof the first may thrust the sun away
y y
Out of the summer signs, until he comes
To his winter turning-point and the icy frost;
While the other from the freezing shades of cold
Sweeps him right back to the heat-laden regions
And the torrid constellations. And just so
We must suppose that the moon and the planets,
Which roll in their huge orbits through huge years,
May move on streams of air alternately
From opposite quarters. Do you not also see
How clouds are shifted by opposing winds,
The lower in directions contrary
To those above? Why should not yonder stars
Be likewise carried by opposing currents
Upon their mighty orbits through the sky?
But night covers the earth with vast darkness
Either when after his long course the sun
Has entered on the uttermost parts of heaven,
And now grown languid has breathed forth his fires,
Exhausted by their journey, and worn out
By traversing much air; or else because
That same force which has borne his orb along
Above the earth, compels him now to turn
Backward his course and pass beneath the earth.

Likewise at a fixed time Matuta spreads


The rosy dawn abroad through the sky’s borders,
And opens out her light; either because
The same sun, travelling back below the earth,
Seizes the sky beforehand, and is fain
To kindle it with his rays; or else because
Fires meet together, and many seeds of heat
Are wont at a fixed time to stream together
Causing new sunlight each day to be born.
Even so ’tis told that from the mountain heights
Of Ida at daybreak scattered fires are seen;
These then unite as if into one globe
And make up the sun’s orb. Nor yet herein
Should it cause wonder that these seeds of fire
Can stream together at a time so fixed,
Repairing thus the radiance of the sun.
For everywhere we see many events
Happening at fixed times. Thus trees both flower
And shed their blossoms at fixed times; and age
At a time no less fixed bids the teeth drop,
And the boy clothe his features with the down
Of puberty, and let a soft beard fall
From either cheek. Lastly lightning and snow,
Rains, clouds and winds happen at more or less
Regular yearly seasons. For where causes
From the beginning have remained the same,
And things from the first origin of the world
Have so fallen out, they still repeat themselves
In regular sequence after a fixed order.

The cause too why days lengthen and nights wane,


While daylight shortens as the nights increase,
May either be because the same sun, journeying
Underneath and above the earth in curves
Of unlike length, parts the celestial regions
And into unequal halves divides his orbit:
Whatever he has subtracted from one half,
Just so much does he add, when he comes round,
On to the other half, till he has reached
That sign of heaven where the year’s node makes
The night’s shade equal to the light of day.
For in the sun’s mid course between the blasts
Of south wind and of north, the heaven holds
His turning-points apart at distances
Now equalised, since such is the position
Of the whole starry circle, to glide through which
The sun takes up the period of a year,
Lighting the earth and sky with slanting rays,
A i h b h f h
As is shown by the arguments of those
Who have mapped out all the quarters of the sky,
Adorned with their twelve signs spaced out in order.
Or else because the air in certain parts
Is thicker, therefore the trembling lamp of fire
Is hindered in its course beneath the earth,
And cannot easily force a passage through
And emerge at the place where it should rise.
So in winter-time the nights are long and lingering,
Ere the day’s radiant oriflamme comes forth.
Or else again those fires which cause the sun
To rise from a fixed point, for a like reason
Are wont to stream together slower or quicker
In alternating periods of the year.
So those would seem to speak the truth who hold
That every morning a new sun is born.
It may be the moon shines because she is struck
By the sun’s rays, and turns towards our eyes
A larger portion of this light each day,
The further she recedes from the sun’s orb,
Until over against him with full light
She has shone forth, and as she rises up
Has looked upon his setting from on high.
Thereafter in her gradual backward course
In the same manner she must hide her light,
The nearer she now glides to the sun’s fire
Travelling through the circle of the signs
From an opposite direction: as those hold
Who fancy that the moon is like a ball,
And moves along a course below the sun.
It is also possible that she revolves
With her own light, and yet shows varying
Phases of brightness: for there may well be
Another body which glides on beside her,
Obstructing and occulting her continually,
And yet cannot be seen, because it moves
Wi h li h O h h d
Without light. Or perhaps she may turn round
Like a ball, let us say, whose sphere is tinged
With glowing light over one-half its surface;
And as she turns her sphere, she may present
Varying phases, till she has turned that side
Which glows with fire towards our gazing eyes;
Then she twists gradually back once more
And hides the luminous half of her round ball:
As the Chaldean sages seek to prove,
Refuting with their Babylonian doctrine
The opposing science of the astronomers;
Just as though what each sect is fighting for
Might not be true, or there were any reason
Why you should risk embracing the one creed
Less than the other. Again why every time
There should not be created a fresh moon,
With fixed succession of phases and fixed shapes,
So that each day this new-created moon
Would perish, and another in its stead
Be reproduced, this were no easy task
To prove by argument convincingly,
Since there can be so many things created
In fixed succession. Thus Spring goes its way,
And Venus, and the wingèd harbinger
Of Venus leads them on; while treading close
On Zephyr’s footsteps, mother Flora strews
The path before them, covering it all over
With every loveliest colour and rich scent.
Next in procession follows parching heat,
With dusty Ceres in its company,
And the Etesian blasts of the North winds.
After these Autumn comes, and by its side
Advances Euhius Euan,[G] following whom
The other Seasons with their winds appear,
Volturnus thundering on high, and Auster
Terrible with its lightnings. Then at length
December brings snow and renews numb frost.
Winter follows with teeth chattering for cold.
Wherefore it seems less wonderful that the moon
Should be begotten and destroyed again
At fixed times, seeing that so many things
Can come to pass at times so surely fixed.

Likewise the occultations of the sun


And the moon’s vanishings you must suppose
May be produced by many different causes.
For why should the moon be able to shut out
The earth from the sun’s light, and lift her head
On high to obstruct him from the earthward side,
Blocking his fiery beams with her dark orb,
And yet at the same time some other body
Gliding on without light continually
Should be supposed unable to do this?
Why too should not the sun at a fixed time
Grow faint and lose his fires, and then again
Revive his light, when he has had to pass
Through tracts of air so hostile to his flames
That awhile his fires are quenched by them and perish?
And why should the earth have power in turn to rob
The moon of light, and likewise keep the sun
Suppressed, while in her monthly course the moon
Glides through the clear-cut shadows of the cone,
And yet at the same time some other body
Should not have power to pass under the moon,
Or glide above the sun’s orb, breaking off
The beams of light he sheds? And furthermore,
If the moon shines with her own radiance,
Why in a certain region of the world
Might she not grow faint, while she makes her way
Through tracts that are unfriendly to her light?

Now since I have demonstrated how each thing


Might come to pass throughout the azure spaces
Might come to pass throughout the azure spaces
Of the great heaven, how we may know what force
Can cause the varying motions of the sun,
And wanderings of the moon, and in what way
Their light being intercepted they might vanish
Covering with darkness the astonished earth,
When as it were they close their eye of light,
And opening it again, survey all places
Radiant with shining brightness,—therefore now
I will go back to the world’s infancy
And the tender age of the world’s fields, and show
What in their first fecundity they resolved
To raise into the borders of the light
And give in charge unto the wayward winds.

In the beginning the Earth brought forth all kinds


Of plants and growing verdure on hillsides
And over all the plains: the flowering meadows
Shone with green colour: next to the various trees
Was given a mighty emulous impulse
To shoot up into the air with unchecked growth.
As feathers, hairs and bristles first are born
On limbs of quadrupeds and on the bodies
Of winged fowl, so the new Earth then put forth
Grasses and brushwood first, and afterwards
Gave birth to all the breeds of mortal things,
That sprang up many in number, in many modes
And divers fashions. For no animals
Can have dropped from the sky, nor can land-creatures
Have issued from the salt pools. Hence it is
That with good reason the Earth has won the name
Of Mother, since from the Earth all things are born.
And many living creatures even now
Rise from the soil, formed by rains, and the sun’s
Fierce heat. Therefore the less strange it appears
If then they arose more numerous and more large
Fostered by a new earth and atmosphere
Fostered by a new earth and atmosphere.
So first of all the varied families
And tribes of birds would leave their eggs, hatched out
In the spring season, as now the cicadas
In summer-time leave of their own accord
Their filmy skins in search of food and life.
Then was the time when first the Earth produced
The race of mortal men. For in the fields
Plenteous heat and moisture would abound,
So that wherever a fit place occurred,
Wombs would grow, fastened to the earth by roots:
And when the warmth of the infants in due time,
Avoiding moisture and demanding air,
Had broken these wombs open, then would Nature
Turn to that place the porous ducts of the Earth,
Compelling it to exude through open veins
A milk-like liquid, just as nowadays
After child-bearing every woman is filled
With sweet milk; for with her too the whole flow
Of nutriment sets streaming towards her breasts.
Earth to these children furnished food, the heat
Clothing, the grass a bed, well lined with rich
Luxuriance of soft down. Moreover then
The world in its fresh newness would give rise
Neither to rigorous cold nor extreme heat,
Nor violent storms of wind, for in a like
Proportion all things grow and gather strength.

Therefore again and yet again I say


That with good reason the Earth has won and keeps
The name of Mother, since she of herself
Gave birth to humankind, and at a period
Well nigh determined shed forth every beast
That roams o’er the great mountains far and wide,
Likewise the birds of air, many in shape.
But because she must have some limit set
To her time of bearing, she ceased, like a woman
g, ,
Worn out by lapse of years. For Time transforms
The whole world’s nature, and all things must pass
From one condition to another: nothing
Continues like itself. All is in flux:
Nature is ever changing and compelling
All that exists to alter. For one thing
Moulders and wastes away grown weak with age,
And then another comes forth into light,
Issuing from obscurity. So thus Time
Changes the whole world’s nature, and the Earth
Passes from one condition to another:
So that what once it bore it can no longer,
And now can bear what it did not before.

And many monsters too did the Earth essay


To produce in those days, creatures arising
With marvellous face and limbs, the Hermaphrodite,
A thing of neither sex, between the two,
Differing from both: some things deprived of feet;
Others again with no hands; others dumb
Without mouths, or else blind for lack of eyes,
Or bound by limbs that everywhere adhered
Fast to their bodies, so that they could perform
No function, nor go anywhere, nor shun
Danger, nor take what their need might require.
Many such monstrous prodigies did Earth
Produce, in vain, since Nature banned their increase,
Nor could they reach the coveted flower of age,
Nor find food, nor be joined in bonds of love.
For we see numerous conditions first
Must meet together, before living things
Can beget and perpetuate their kind.
First they must have food, then a means by which
The seeds of birth may stream throughout the frame
From the relaxed limbs; also that the male
And female may unite, they must have that
Whereby each may exchange mutual joys.

And many breeds of creatures in those days


Must have died out, being powerless to beget
And perpetuate their kind. For those which now
You see breathing the breath of life, ’tis craft,
Or courage, or else speed, that from its origin
Must have protected and preserved each race.
Moreover many by their usefulness
Commended to us, continue to exist
Favoured by our protection. The fierce breed
Of lions first, and the other savage beasts,
Their courage has preserved, foxes their craft,
Stags their swift flight. But the light-slumbering hearts
Of faithful dogs, and the whole family
Born from the seed of burden-bearing beasts,
Also the woolly flocks and horned herds,
All these by man’s protection are preserved.
For their desire has always been to shun
Wild beasts and to live peaceably, supplied
Without toil of their own with food in plenty,
Which to reward their services we give them.
But those whom Nature has not thus endowed
With power either to live by their own means
Or else to render us such useful service
That in return we allow their race to feed
And dwell in safety beneath our guardianship,
All these, ’tis plain, would lie exposed a prey
To others, trammelled in their own fatal bonds,
Till Nature had extinguished that whole kind.

But Centaurs there have never been, nor yet


Ever can things exist of twofold nature
And double body moulded into one
From limbs of alien kind, whose faculties
And functions cannot be on either side
S ffi i tl lik Th t thi i
Sufficiently alike. That this is so,
The dullest intellect may be thus convinced.
Consider first that a horse after three years
Is in his flower of vigour, but a boy
By no means so: for often in sleep even then
Will he seek milk still from his mother’s breasts
Afterwards, when the horse’s lusty strength
Fails him in old age, and his limbs grow languid
As life ebbs, then first for a boy begins
The flowering time of youth, and clothes his cheeks
With soft down. Do not then believe that ever
From man’s and burden-bearing horse’s seed
Centaurs can be compounded and have being;
Nor yet Scyllas with half-fish bodies girdled
With raging dogs, and other suchlike things,
Whose limbs we see discordant with themselves,
Since neither do they reach their flower together,
Nor acquire bodily strength, nor in old age
Lose it at the same time: dissimilar
In each the love that burns them, and their modes
Of life incongruous: nor do the same things give
Their bodies pleasure. Thus we may often see
Bearded goats thrive on hemlock, which for man
Is virulent poison. Since moreover flame
Is wont to scorch and burn the tawny bodies
Of lions no less than every other kind
Of flesh and blood on earth, how could it be
That one, yet with a triple body, in front
A lion, behind a serpent, in the midst
Its goat’s self, a Chimaera should breathe forth
From such a body fierce flame at the mouth?
Therefore he who can fable that when earth
Was new and the sky young, such animals
Could have been propagated, resting alone
Upon this vain term, newness, he no doubt
Will babble out many follies in like fashion,
Will th t i th th h t th th
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like