100% found this document useful (6 votes)
28 views

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF 2024 scribd download

Ebookluna.com offers seamless downloads for a variety of eBooks across different genres, including programming and business law. Users can access instant digital products in formats such as PDF, ePub, and MOBI. The document lists several titles available for download, including 'Java Programming' and 'Physics for Scientists and Engineers,' along with links to their respective eBook pages.

Uploaded by

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

Java Programming (MindTap Course List), 10th Edition Joyce Farrell - eBook PDF 2024 scribd download

Ebookluna.com offers seamless downloads for a variety of eBooks across different genres, including programming and business law. Users can access instant digital products in formats such as PDF, ePub, and MOBI. The document lists several titles available for download, including 'Java Programming' and 'Physics for Scientists and Engineers,' along with links to their respective eBook pages.

Uploaded by

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

Experience Seamless Full Ebook Downloads for Every Genre at ebookluna.

com

Java Programming (MindTap Course List), 10th


Edition Joyce Farrell - eBook PDF

https://ebookluna.com/download/java-programming-mindtap-
course-list-10th-edition-ebook-pdf/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://ebookluna.com


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

Java Programming 9th Edition Joyce Farrell - eBook PDF

https://ebookluna.com/download/java-programming-ebook-pdf/

ebookluna.com

Programming Logic & Design, Comprehensive 9th edition


Joyce Farrell - eBook PDF

https://ebookluna.com/download/programming-logic-design-
comprehensive-9th-edition-ebook-pdf/

ebookluna.com

Programming Logic and Design, Comprehensive 9th Edition


Joyce Farrell - eBook PDF

https://ebookluna.com/download/programming-logic-and-design-
comprehensive-9th-edition-ebook-pdf/

ebookluna.com

Introduction to Java Programming, Comprehensive Version


10th edition- eBook PDF

https://ebookluna.com/download/introduction-to-java-programming-
comprehensive-version-ebook-pdf/

ebookluna.com
Physics for Scientists and Engineers (MindTap Course List)
10th Edition Serway - eBook PDF

https://ebookluna.com/download/physics-for-scientists-and-engineers-
mindtap-course-list-ebook-pdf/

ebookluna.com

Business Law: Text & Exercises (MindTap Course List) 10th


Edition Roger Leroy Miller - eBook PDF

https://ebookluna.com/download/business-law-text-exercises-mindtap-
course-list-ebook-pdf/

ebookluna.com

Your Career: How to Make it Happen (MindTap Course List)


10th Edition Lisa Owens - eBook PDF

https://ebookluna.com/download/your-career-how-to-make-it-happen-
mindtap-course-list-ebook-pdf/

ebookluna.com

Interpersonal Conflict 10th Edition Joyce L. Hocker -


eBook PDF

https://ebookluna.com/download/interpersonal-conflict-ebook-pdf/

ebookluna.com

(eBook PDF) Murach's Java Programming 5th Edition by Joel


Murach

https://ebookluna.com/product/ebook-pdf-murachs-java-programming-5th-
edition-by-joel-murach/

ebookluna.com
Java
Programming
Tenth Edition

Joyce Farrell

Australia • Brazil • Canada • Mexico • Singapore • United Kingdom • United States

Copyright 2023 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 2023 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.
JavaTM Programming, Tenth Edition © 2023, © 2019, © 2016 Cengage Learning, Inc. WCN: 02-300
Joyce Farrell ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
may be reproduced or distributed in any form or by any means, except as
SVP, Higher Education Product Management: Erin
permitted by U.S. copyright law, without the prior written permission of the
Joyner
copyright owner.
VP, Product Management, Learning Experiences: Unless otherwise noted, all content is Copyright © Cengage Learning, Inc.
Thais Alencar
Unless otherwise noted, all screenshots are courtesy of Microsoft Corporation.
Product Director: Mark Santee
Microsoft is a registered trademark of Microsoft Corporation in the U.S.
Associate Product Manager: Tran Pham and/or other countries.

The names of all products mentioned herein are used for identification
Product Assistant: Ethan Wheel
purposes only and may be trademarks or registered trademarks of their
Learning Designer: Mary Convertino respective owners. Cengage Learning disclaims any affiliation, association,
connection with, sponsorship, or endorsement by such owners.
Senior Content Manager: Maria Garguilo

Associate Digital Delivery Quality Partner: David For product information and technology assistance, contact us at
O’Connor Cengage Customer & Sales Support, 1-800-354-9706
or support.cengage.com.
Technical Editor: John Freitas
For permission to use material from this text or product, submit all
Developmental Editor: Dan Seiter
requests online at www.copyright.com.

VP, Product Marketing: Jason Sakos


Library of Congress Control Number: 2021925780
Director, Product Marketing: April Danaë
ISBN: 978-0-357-67342-3
Portfolio Marketing Manager: Mackenzie Paine
Cengage
IP Analyst: Ann Hoffman
200 Pier 4 Boulevard
IP Project Manager: Integra Software Services Boston, MA 02210
USA
Production Service: Straive
Cengage is a leading provider of customized learning solutions with
Senior Designer: Erin Griffin employees residing in nearly 40 different countries and sales in more than
125 countries around the world. Find your local representative at
Cover Image Source: iStock.com/gremlin
www.cengage.com.

To learn more about Cengage platforms and services, register or access


your online learning solution, or purchase materials for your course, visit
www.cengage.com.

Notice to the Reader


Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with
any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and
include information other than that provided to it by the manufacturer. The reader is expressly warned to consider and adopt all safety
precautions that might be indicated by the activities described herein and to avoid all potential hazards. By following the instructions
contained herein, the reader willingly assumes all risks in connection with such instructions. The publisher makes no representations
or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any
such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to
such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from
the readers’ use of, or reliance upon, this material.

Printed in the United States of America


Print Number: 01   Print Year: 2022

Copyright 2023 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
PREFACEXI

CHAPTER 1 Creating Java Programs�������������������������������������������������������������������������������� 1


CHAPTER 2 Using Data���������������������������������������������������������������������������������������������������� 39
CHAPTER 3 Using Methods�������������������������������������������������������������������������������������������� 83
CHAPTER 4 Using Classes and Objects����������������������������������������������������������������������� 115
CHAPTER 5 Making Decisions�������������������������������������������������������������������������������������� 161
CHAPTER 6 Looping������������������������������������������������������������������������������������������������������� 201
CHAPTER 7 Characters, Strings, and the StringBuilder�������������������������������������� 237
CHAPTER 8 Arrays��������������������������������������������������������������������������������������������������������� 267
CHAPTER 9 Inheritance and Interfaces����������������������������������������������������������������������� 329
CHAPTER 10 Exception Handling��������������������������������������������������������������������������������� 393
CHAPTER 11 File Input and Output����������������������������������������������������������������������������� 441
CHAPTER 12 Recursion������������������������������������������������������������������������������������������������� 487
CHAPTER 13 Collections and Generics����������������������������������������������������������������������� 511
CHAPTER 14 Introduction to Swing Components���������������������������������������������������� 545
APPENDIX A Working with the Java Platform ����������������������������������������������������������� 587

APPENDIX B Data Representation ����������������������������������������������������������������������������� 591

APPENDIX C Formatting Output �������������������������������������������������������������������������������� 595

APPENDIX D Generating Random Numbers ������������������������������������������������������������ 603

APPENDIX E Javadoc ���������������������������������������������������������������������������������������������������� 607

APPENDIX F Using JavaFX and Scene Builder ����������������������������������������������������������� 613

GLOSSARY 625
INDEX 641

iii

Copyright 2023 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
PREFACEXI Key Terms 32
Review Questions 33
CHAPTER 1 Programming Exercises 34
Debugging Exercises 36
CREATING JAVA PROGRAMS 1
Game Zone 36
1.1 Learning Programming Terminology 1 Case Problems 37
1.2 Comparing Procedural and Object-
Oriented Programming Concepts 4
CHAPTER 2
Procedural Programming 4
Object-Oriented Programming 5 USING DATA 39
Understanding Classes, Objects, and Encapsulation 6
2.1 Declaring and Using Constants
Understanding Inheritance and Polymorphism 7
and Variables 39
1.3 Features of the Java Programming Declaring Variables 40
Language8
Declaring Named Constants 42
1.4 Analyzing a Java Application That The Scope of Variables and Constants 43
Produces Console Output 10
Concatenating Strings to Variables and
Understanding the Statement That Produces the Constants 43
Output10
Pitfall: Forgetting That a Variable Holds One
Understanding the First Class 12 Value at a Time 45
Understanding the main() Method 14
2.2 Learning About Integer Data
Indent Style 15
Types47
Saving a Java Class 16
2.3 Using the boolean Data Type 51
1.5 Compiling a Java Class and
Correcting Syntax Errors 18 2.4 Learning About Floating-Point
Compiling a Java Class 18 Data Types 52
Correcting Syntax Errors 19 2.5 Using the char Data Type 53
1.6 Running a Java Application and 2.6 Using the Scanner Class to
Correcting Logic Errors 23 Accept Keyboard Input 57
Running a Java Application 23 Pitfall: Using nextLine() Following One of the
Modifying a Compiled Java Class 23 Other Scanner Input Methods 59
Correcting Logic Errors 24
2.7 Using the JOptionPane Class to
1.7 Adding Comments to a Java Class 25 Accept GUI Input 64
1.8 Creating a Java Application That Using Input Dialog Boxes 64
Produces GUI Output 27 Using Confirm Dialog Boxes 66
1.9 Finding Help 29 2.8 Performing Arithmetic Using
Variables and Constants 68
Don’t Do It 30 Associativity and Precedence 69
Summary31 Writing Arithmetic Statements Efficiently 69

iv

Copyright 2023 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 v

Pitfall: Not Understanding Imprecision in Game Zone 113


Floating-Point Numbers 70 Case Problems 114
2.9 Understanding Type Conversion 72
Automatic Type Conversion 73 CHAPTER 4
Explicit Type Conversion 73
USING CLASSES AND OBJECTS 115
Don’t Do It 76 4.1 Learning About Classes
Summary 77 and Objects 115
Key Terms 77 4.2 Creating a Class 117
Review Questions 78
Programming Exercises 80
4.3 Creating Instance Methods
in a Class 119
Debugging Exercises 81
Game Zone 81 4.4 Declaring Objects and
Case Problems 82 Using Their Methods 124
Understanding Data Hiding 126

CHAPTER 3 4.5 Understanding That Classes


Are Data Types 128
USING METHODS 83 4.6 Creating and Using Constructors 131
3.1 Understanding Method Calls and Creating Constructors with Parameters 132
Placement83
4.7 Learning About the this
3.2 Understanding Method Reference134
Construction86 Using the this Reference to Make
Access Specifiers 86 Overloaded Constructors More Efficient 137
The static Modifier 87
4.8 Using static Fields 139
Return Type 87
Using Constant Fields 140
Method Name 87
Parentheses 88 4.9 Using Imported, Prewritten
Constants and Methods 143
3.3 Adding Parameters to Methods 91
The Math Class 144
Creating a Method That Receives a Single
Importing Classes That Are Not Imported
Parameter 91
Automatically 145
Creating a Method That Requires Multiple
Using the LocalDate Class 146
Parameters 94

3.4 Creating Methods That 4.10 U


 nderstanding Composition
Return Values 95 and Nested Classes 150
Composition 150
3.5 Understanding Blocks and Scope 99
Nested Classes 151
3.6 Overloading a Method 104
3.7 Learning about Ambiguity 107 Don’t Do It 153
Summary 153
Don’t Do It 108 Key Terms 154
Summary 108 Review Questions 154
Key Terms 109 Programming Exercises 156
Review Questions 109 Debugging Exercises 158
Programming Exercises 111 Game Zone 158
Debugging Exercises 113 Case Problems 159

Copyright 2023 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.
vi Contents

CHAPTER 5 CHAPTER 6
MAKING DECISIONS 161 LOOPING201
5.1 Planning Decision-Making Logic 161 6.1 Learning About the Loop
5.2 The if and if…else Statements 163 Structure201
The if Statement 163 6.2 Creating while Loops 202
Pitfall: Misplacing a Semicolon in an if Statement 164 Writing a Definite while Loop 202
Pitfall: Using the Assignment Operator Instead Pitfall: Failing to Alter the Loop Control Variable
of the Equivalency Operator 165 Within the Loop Body 204
Pitfall: Attempting to Compare Objects Using Pitfall: Unintentionally Creating a Loop with
the Relational Operators 165 an Empty Body 204
The if…else Statement 166 Altering a Definite Loop’s Control Variable 206
Writing an Indefinite while Loop 206
5.3 Using Multiple Statements in
if and if…else Clauses 168 Validating Data 208

5.4 Nesting if and if…else 6.3 Using Shortcut Arithmetic


Statements172 Operators210
5.5 Using Logical AND and OR 6.4 Creating a for Loop 214
Operators174 Variations in for Loops 215
The AND Operator 174 6.5 Learning How and When to Use
The OR Operator 175 a do…while Loop 217
Short-Circuit Evaluation 175 6.6 Learning About Nested Loops 220
5.6 Making Accurate and Efficient 6.7 Improving Loop Performance 223
Decisions178 Avoiding Unnecessary Operations 223
Making Accurate Range Checks 178 Considering the Order of Evaluation of
Making Efficient Range Checks 180 Short-Circuit Operators 224
Using && and || Appropriately 180 Comparing to Zero 224
5.7 Using switch  181 Employing Loop Fusion 226
Using the switch Expression 183 A Final Note on Improving Loop Performance 226

5.8 Using the Conditional and NOT


Operators186 Don’t Do It 228
Summary 228
Using the NOT Operator 187
Key Terms 229
5.9 Understanding Operator
Review Questions 229
Precedence187
Programming Exercises 232
5.10 M
 aking Constructors More Debugging Exercises 233
Efficient by Using Decisions in
Game Zone 234
Other Methods 189
Case Problems 235

Don’t Do It 193


Summary 193 CHAPTER 7
Key Terms 194
CHARACTERS, STRINGS, AND
Review Questions 194
THE StringBuilder 237
Programming Exercises 197
Debugging Exercises 198 7.1 Understanding String Data
Game Zone 199
Problems237
Case Problems 200 7.2 Using Character Class Methods 238

Copyright 2023 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 vii

7.3 Declaring and Comparing 8.8 Using Two-Dimensional and Other


String Objects 241 Multidimensional Arrays 300
Comparing String Values 241 Passing a Two-Dimensional Array to a Method 302
Empty and null Strings 245 Using the length Field with a Two-Dimensional
Array303
7.4 Using a Variety of String
Methods246 Understanding Jagged Arrays 304
Using Other Multidimensional Arrays 304
Converting String Objects to Numbers 249

7.5 Learning About the StringBuilder 8.9 Using the Arrays Class 307
and StringBuffer Classes 253 8.10 Creating Enumerations 311

Don’t Do It 257 Don’t Do It 316


Summary 258 Summary 317
Key Terms 258 Key Terms 318
Review Questions 258 Review Questions 318
Programming Exercises 260 Programming Exercises 320
Debugging Exercises 262 Debugging Exercises 323
Game Zone 263 Game Zone 323
Case Problems 264 Case Problems 327

CHAPTER 8 CHAPTER 9
ARRAYS267 INHERITANCE AND INTERFACES 329
8.1 Declaring an Array 267 9.1 Learning About the Concept of
8.2 Initializing an Array 271 Inheritance329
Inheritance Terminology 331
8.3 Using Variable Subscripts with an
Array273 9.2 Extending Classes 332
Using the Enhanced for Loop 275 9.3 Overriding Superclass Methods 336
Using Part of an Array 275 Using the @Override Annotation 337
8.4 Declaring and Using Arrays 9.4 Calling Constructors During
of Objects 277 Inheritance339
Using the Enhanced for Loop with Objects 279 Using Superclass Constructors That Require
Manipulating Arrays of Strings 279 Arguments 340

8.5 Searching an Array and Using 9.5 Accessing Superclass Methods 344
Parallel Arrays 284 Comparing this and super 345
Using Parallel Arrays 284
9.6 Employing Information Hiding 346
Searching an Array for a Range Match 286
9.7 Methods You Cannot Override 348
8.6 Passing Arrays to and Returning
Arrays from Methods 289 A Subclass Cannot Override static Methods
in Its Superclass 348
Returning an Array from a Method 291
A Subclass Cannot Override final Methods
8.7 Sorting Array Elements 292 in Its Superclass 350
Using the Bubble Sort Algorithm 293 A Subclass Cannot Override Methods in a final
Improving Bubble Sort Efficiency 295 Superclass 351
Sorting Arrays of Objects 295 9.8 Creating and Using Abstract
Using the Insertion Sort Algorithm 296 Classes352

Copyright 2023 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.
viii Contents

9.9 Using Dynamic Method Binding 359 10.7 T


 racing Exceptions Through the
Using a Superclass as a Method Parameter Type 360 Call Stack 415
9.10 C
 reating Arrays of Subclass 10.8 C
 reating Your Own Exception
Objects361 Classes419
9.11 U
 sing the Object Class and Its 10.9 Using Assertions 421
Methods364 10.10 Displaying the Virtual Keyboard 430
Using the toString() Method 364
Using the equals() Method 366 Don’t Do It 433
Overloading equals() 367 Summary 434
Overriding equals() 369 Key Terms 434
9.12 Creating and Using Interfaces 371 Review Questions 435
Creating Interfaces to Store Related Constants 374 Programming Exercises 437
Debugging Exercises 439
9.13 U
 sing records, Anonymous Inner
Classes, and Lambda Expressions 377 Game Zone 439

Using records 377 Case Problems 440

Using Anonymous Inner Classes 379


Using Lambda Expressions 380 CHAPTER 11
FILE INPUT AND OUTPUT 441
Don’t Do It 381
Summary 381
11.1 Understanding Computer Files 441
Key Terms 383 11.2 U
 sing the Path and Files
Review Questions 383 Classes443
Programming Exercises 385 Creating a Path 443
Debugging Exercises 389 Retrieving Information About a Path 444
Game Zone 390 Converting a Relative Path to an Absolute One 445
Case Problems 391 Checking File Accessibility 446
Deleting a Path 447
Determining File Attributes 448
CHAPTER 10
11.3 F
 ile Organization, Streams, and
EXCEPTION HANDLING 393 Buffers450
10.1 Learning About Exceptions 393 11.4 Using Java’s IO Classes 452
10.2 T
 rying Code and Catching Writing to a File 454
Exceptions397 Reading from a File 454
Using a try Block to Make Programs “Foolproof” 400 11.5 C
 reating and Using Sequential
Declaring and Initializing Variables in try…catch Data Files 457
Blocks 402
11.6 L
 earning About Random Access
10.3 T
 hrowing and Catching Multiple Files461
Exceptions404
11.7 W
 riting Records to a Random
10.4 Using the finally Block 408 Access Data File 463
10.5 U
 nderstanding the Advantages 11.8 R
 eading Records from a Random
of Exception Handling 410 Access Data File 468
10.6 S
 pecifying the Exceptions That Accessing a Random Access File Sequentially 468
a Method Can Throw 412 Accessing a Random Access File Randomly 470

Copyright 2023 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 ix

Don’t Do It 479 13.4 Using the LinkedList Class 524


Summary 479
13.5 Using Iterators 528
Key Terms 480
Review Questions 480
13.6 Creating Generic Classes 530
Programming Exercises 482 13.7 Creating Generic Methods 532
Debugging Exercises 484 Creating a Generic Method with More than One
Game Zone 484 Type Parameter 533

Case Problems 485


Don’t Do It 537

CHAPTER 12 Summary 538


Key Terms 538
RECURSION487 Review Questions 539

12.1 Understanding Recursion 487 Programming Exercises 541


Debugging Exercises 542
12.2 U
 sing Recursion to Solve
Game Zone 542
Mathematical Problems 489
Case Problems 543
Computing Sums 490
Computing Factorials 491
12.3 U
 sing Recursion to Manipulate CHAPTER 14
Strings495
INTRODUCTION TO Swing
Using Recursion to Separate a Phrase into Words 495
Using Recursion to Reverse the Characters in a
COMPONENTS545
String 496 14.1 U
 nderstanding Swing
12.4 U
 sing Recursion to Create Visual Components545
Patterns499 14.2 Using the JFrame Class 547
12.5 R
 ecursion’s Relationship to Customizing a JFrame’s Appearance 549
Iterative Programming 500 14.3 Using the JLabel Class 552
Changing a JLabel’s Font 553
Don’t Do It 503
14.4 Using a Layout Manager 555
Summary 503
Key Terms 504 14.5 Extending the JFrame Class 557
Review Questions 504 14.6 A
 dding JTextFields and
Programming Exercises 506 JButtons to a JFrame 559
Debugging Exercises 508 Adding JTextFields to a JFrame 559
Game Zone 509 Adding JButtons to a JFrame 560
Case Problems 510 14.7 L
 earning About Event-Driven
Programming563
CHAPTER 13 Preparing Your Class to Accept Event Messages 564
Telling Your Class to Expect Events to Happen 564
COLLECTIONS AND GENERICS 511 Telling Your Class How to Respond to Events 564
13.1 U
 nderstanding the Collection Writing an Event-Driven Program 565
Interface511 Using Multiple Event Sources 566
13.2 U
 nderstanding the List Using the setEnabled() Method 567
Interface513
14.8 U
 nderstanding Swing Event
13.3 Using the ArrayList Class 514 Listeners569

Copyright 2023 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.
x Contents

14.9 U
 sing the JCheckBox, APPENDIX C
ButtonGroup, and JComboBox
Classes572 FORMATTING OUTPUT  595
The JCheckBox Class 572
The ButtonGroup Class 574 APPENDIX D
The JComboBox Class 575
GENERATING RANDOM
Don’t Do It 580 NUMBERS 603
Summary 581
Key Terms 581 APPENDIX E
Review Questions 582
JAVADOC  607
Programming Exercises 584
Debugging Exercises 585
Game Zone 585
APPENDIX F
Case Problems 586 USING JAVAFX AND SCENE
BUILDER613
APPENDIX A
GLOSSARY 625
WORKING WITH THE INDEX 641
JAVA PLATFORM 587

APPENDIX B
DATA REPRESENTATION 591

Copyright 2023 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
Java Programming, Tenth Edition provides the beginning programmer with a guide to developing applications
using the Java programming language. Java is popular among professional programmers because it is object-
oriented, making complex problems easier to solve than in some other languages. Java is used for desktop
computing, mobile computing, game development, Web development, and numerical computing.

This course 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 also can be downloaded from the Cengage website, so
students easily can run the programs and experiment with changes to them.

The student using Java Programming, Tenth 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 course, 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, Tenth 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
Java courses. You create your first Java program in Chapter 1. Chapters 2, 3, and 4 increase your understanding
about 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 and 8.

Chapters 9 and 10 thoroughly cover inheritance, interfaces, and exception handling. Inheritance is the object-
oriented concept that allows you to develop new objects quickly by adapting the features of existing objects,
interfaces define common methods that must be implemented in all classes that use them, and exception
handling is the object-oriented approach to handling errors. All of these are important concepts in object-
oriented design. Chapter 11 provides information about handling files so you can store and retrieve program
output.

Chapter 12 explains recursion, and Chapter 13 covers Java collections and generics. Both are important
programming concepts, and Java provides excellent ways to implement and learn about them. Chapter 14
introduces GUI Swing components, which are used to create visually pleasing, user-friendly, interactive
applications.

xi

Copyright 2023 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.
xii Preface

New in This Edition


The following features are new for the Tenth Edition:

❯❯Java: All programs have been tested using Java 16.

❯❯Java help: Instructions on searching for Java help have been updated to avoid using specific URLs because new
Java versions are now being released twice a year.
❯❯Text blocks: Chapter 2 introduces text blocks—a new feature since Java 13.

❯❯Methods: Methods are covered thoroughly in Chapter 3, including topics such as overloading methods and
avoiding ambiguity. In previous editions, the material was split between chapters.
❯❯Classes and objects: Classes and objects are covered thoroughly in Chapter 4. In previous editions, the material
was split between chapters.
❯❯The switch expression: Chapter 5 includes the switch expression, which became a new feature in Java 14.

❯❯Arrays: Chapter 8 covers beginning and advanced array concepts. In previous editions, this content was split
between chapters.
❯❯Inheritance and interfaces: Chapter 9 covers inheritance and interfaces. In previous editions, this content was
split between chapters.
❯❯The record keyword: Chapter 9 also introduces the record keyword, which allows simple classes to be
developed more quickly because a constructor and methods to get and set fields are created automatically
based on field definitions.
❯❯Recursion: Chapter 12 is a new chapter on recursion. The chapter presents techniques to use to solve
mathematical problems, manipulate strings, and create visual patterns using recursion.
❯❯Collections and generics: Chapter 13 is a new chapter on collections and generics. The chapter covers the
Collection and List interfaces, the ArrayList and LinkedList classes, Iterators, and generic
classes and methods.

Additionally, Java Programming, Tenth 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 about a technique, or a common error to
avoid.
❯❯Emphasis on student research: The student frequently is advised to use the Web to investigate Java classes,
methods, and techniques. Computer languages evolve, and programming professionals must understand how to
find the latest language improvements.
❯❯Figures: Each chapter contains many figures. Code figures are most frequently 25 lines or fewer, illustrating one
concept at a time. Frequent screenshots 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 Cengage website. Most files contain the code
presented in the figures in each chapter; students can run the code for themselves, view the output, and make

Copyright 2023 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 xiii

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 almost every 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.
❯❯Summary: 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.
❯❯Key Terms: Each chapter includes a list of newly introduced vocabulary, shown in alphabetical order. The list of
key terms provides a short review of the major concepts in the chapter.
❯❯Review Questions: Each chapter includes 20 multiple-choice questions that serve as a review of chapter topics.

❯❯Programming Exercises: Multiple programming exercises are included with each chapter. These challenge
students to create complete Java programs that solve real-world problems.
❯❯Debugging Exercises: Four debugging exercises are included with each chapter. These are programs that
contain logic or syntax errors that the student must correct. Besides providing practice in deciphering error
messages and thinking about correct logic, these exercises provide examples of complete and useful Java
programs after the errors are repaired.
❯❯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; 50 game programs are suggested in the course.
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.
❯❯Glossary: A glossary contains definitions for all key terms in the course.

❯❯Appendices: This edition includes useful appendices on working with the Java platform, data representation,
formatting output, generating random numbers, creating Javadoc comments, and JavaFX.
❯❯Quality: Every program example, exercise, and game solution was tested by the author and then tested again by
a quality assurance team.

MindTap Instructor Resources


MindTap activities for Java Programming, Tenth Edition are designed to help students master the skills they need in
today’s workforce. Research shows employers need critical thinkers, troubleshooters, and creative problem-solvers
to stay relevant in our fast-paced, technology-driven world. MindTap helps you achieve this with assignments and
activities that provide hands-on practice and real-life relevance. Students are guided through assignments that help
them master basic knowledge and understanding before moving on to more challenging problems.

All MindTap activities and assignments are tied to defined unit learning objectives. MindTap provides the analytics and
reporting so you can easily see where the class stands in terms of progress, engagement, and completion rates. Use

Copyright 2023 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.
xiv Preface

the content and learning path as is or pick and choose how our materials will wrap around yours. You control what
the students see and when they see it. Learn more at http://www.cengage.com/mindtap/.

In addition to the readings, the Java Programming, Tenth Edition MindTap includes the following:

❯❯Gradeable assessments and activities: All assessments and activities from the readings will be available as
gradeable assignments within MindTap, including Review Questions, Game Zone, Case Problems, and Two
Truths & a Lie.
❯❯Videos: Each unit is accompanied by videos that help to explain important unit concepts and provide demos on
how students can apply those concepts.
❯❯Coding Snippets: These short, ungraded coding activities are embedded in the MindTap Reader and provide
students an opportunity to practice new programming concepts “in the moment.” The coding Snippets help
transition the students from conceptual understanding to application of Java code.
❯❯Coding labs: These assignments provide real-world application and encourage students to practice new coding
skills in a complete online IDE. Guided feedback provides personalized and immediate feedback to students as
they proceed through their coding assignments so that they can understand and correct errors in their code.
❯❯Interactive study aids: Flashcards and PowerPoint lectures help users review main concepts from the units.

Instructor and Student Resources


Additional instructor and student resources for this product are available online. Instructor assets include an
Instructor’s Manual, Educator’s Guide, PowerPoint® slides, Solution and Answer Guide, solutions, and a test bank
powered by Cognero®. Student assets include data files. Sign up or sign in at www.cengage.com to search for and access
this product and its online resources.

❯❯Instructor’s Manual: The Instructor’s Manual includes additional instructional material to assist in class
preparation, including sections such as Chapter Objectives, Complete List of Chapter Activities and
Assessments, Key Terms, What’s New In This Chapter, Chapter Outline, Discussion Questions, Suggested Usage
for Lab Activities, Additional Activities and Assignments, and Additional Resources. A sample syllabus also is
available.
❯❯PowerPoint presentations: The PowerPoint slides can be used to guide classroom presentations, to make
available to students for chapter review, or to print as classroom handouts.
❯❯Solution and Answer Guide: Solutions to all end-of-chapter assignments are provided along with feedback.

❯❯Solutions: Solutions to all programming exercises are available. If an input file is needed to run a programming
exercise, it is included with the solution file.
❯❯Test bank: Cengage Testing Powered by Cognero is a flexible, online system that allows you to:
■■ Author, edit, and manage test bank content from multiple Cengage solutions.
■■ Create multiple test versions in an instant.
■■ Deliver tests from your LMS, your classroom, or wherever you want.
❯❯Educator’s Guide: The Educator’s Guide contains a detailed outline of the corresponding MindTap course.

❯❯Transition Guide: The Transition Guide outlines information on what has changed from the Ninth Edition.

❯❯Data files: Data files necessary to complete some of the steps and projects in the course are available. The Data
Files folder includes Java files that are provided for every program that appears in a figure in the text.

Copyright 2023 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 xv

About the Author


Joyce Farrell has taught computer programming at McHenry County College, Crystal Lake, Illinois; the University of
Wisconsin, Stevens Point, Wisconsin; and Harper College, Palatine, Illinois. Besides Java, she has written books on
programming logic and design, C#, and C++ for Cengage.

Acknowledgments
I would like to thank all of the people who helped to make this project a reality, including Tran Pham, Associate Product
Manager; Mary Convertino, Learning Designer; Maria Garguilo, Senior Content Manager; Dan Seiter, Developmental
Editor, and John Freitas, Quality Assurance Tester. 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 course’s development,
including Dr. Ross Foultz, Coastal Carolina University; and Dr. Carl M. Rebman, Jr., University of San Diego. Also, thank
you to Charles W. Lively III, Ph.D. – Academic Faculty, Georgia Institute of Technology, who provided the appendix on
JavaFX.

Thanks, too, to my husband, Geoff, for his constant support, advice, and encouragement. Finally, this project is
dedicated to Norman Williams Peterson, who has brought a smile to my face every time I have seen him.

Joyce Farrell

Read This Before You Begin


The following information will help you as you prepare to complete this course.

To the User of the Data Files


To complete the steps and projects in this course, you need data files that have been created specifically for some of
the exercises. Your instructor will provide the data files to you. You also can obtain the files electronically by signing
up or signing in at www.cengage.com and then searching for and accessing this product and its online resources. Note
that you can use a computer in your school lab or your own computer to complete the exercises.

Using Your Own Computer


To use your own computer to complete the steps and exercises, you need the following:

❯❯Software: Java SE 16 or later, available from www.oracle.com/technetwork/java/index.html. Although almost


all of the examples in this course will work with earlier versions of Java, a few require Java 16 or later. You also
need a text editor, such as Notepad. A few exercises ask you to use a browser for research.
❯❯Hardware: For operating system requirements (memory and disk space), see http://java.com/en/download/
help.

Copyright 2023 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.
xvi Preface

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.

You Do It

These sections walk students through program development step by step.

These notes provide additional information—for example, a common error to watch out for or
Note background information on a topic.

Two Truths & a Lie

These quizzes appear after almost every chapter section, with answers provided. Each quiz contains three
statements based on the preceding 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 in MindTap.

Don’t Do It Icon
The Don’t Do It icon illustrates how NOT to do something—for example, having a dead code path in a program. These
icons provide a visual jolt to the student, emphasizing that particular practices are NOT to be emulated and making
students more likely to recognize problems in existing code.

import java.util.Scanner;
public class GetUserInfo2 Don’t Do It
{
public static void main(String[] args) If you accept numeric
{ input prior to string input,
String name; the string input is ignored
int age; unless you take special
Scanner inputDevice = new Scanner(System.in); action.
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}

Copyright 2023 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 xvii

Don’t Do It
These sections at the end of each chapter list advice for avoiding common programming errors.

Assessment

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

Programming Exercises
Programming Exercises provide opportunities to practice concepts. These exercises allow students to explore each
major programming concept presented in the chapter. Additional coding labs and snippets are available in MindTap.

Debugging Exercises
Debugging Exercises are included with each chapter because examining programs critically and closely is a crucial
programming skill. Students and instructors can download these exercises at www.cengage.com.

Game Zone
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.

Case Problems
Case Problems provide opportunities to build more detailed programs that continue to incorporate increasing
functionality throughout the course.

Copyright 2023 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 2023 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 Objectives
When you complete this chapter, you will be able to:

1.1 Define basic programming terminology


1.2 Compare procedural and object-oriented programming
1.3 Describe the features of the Java programming language
1.4 Analyze a Java application that produces console output
1.5 Compile a Java class and correct syntax errors
1.6 Run a Java application and correct logic errors
1.7 Add comments to a Java class
1.8 Create a Java application that produces GUI output
1.9 Identify and consult resources to help develop Java programming skills

1.1 Learning Programming Terminology


You see many computers every day. There might be a laptop on your desk, and there also are computers in
your phone, in your car, and perhaps in your thermostat, washing machine, and vacuum cleaner. When you
learn computer terminology and how to program a computer, you learn a bit about how these devices work,
you develop your critical thinking skills, and you learn to communicate more clearly. You will reap all these
benefits as you work through this course.

Computer systems consist of both hardware and software.

❯❯Computer equipment, such as a monitor or keyboard, is hardware.

❯❯Programs are software. A computer program (or simply, program) is a set of instructions that you write
to tell a computer what to do.

Copyright 2023 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.
2 Chapter 1 Creating Java Programs

Software can be divided into two broad categories:

❯❯A program that performs a task for a user (such as calculating and producing paychecks, word processing, or
playing a game) is application software. Programs that are application software are called applications, or apps
for short.
❯❯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 course describes how to develop the logic for application
software.

You can write computer programs in high- or low-level programming languages:

❯❯A high-level programming language such as Java, Visual Basic, C++, or C# allows you to use English-like, easy-
to-remember terms such as read, write, and add.
❯❯A low-level programming language corresponds closely to a computer’s circuitry and is not as easily read or
understood. Because they correspond to circuitry, low-level languages must be customized for every type of
machine on which a program runs.

All computer programs, even high-level language programs, ultimately are converted to the lowest-level language,
which is 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
Note 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.

Every programming 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 are learning the vocabulary and syntax for that language.

Using a programming language, programmers write a series of program statements, which are similar to English
sentences. The statements carry out the program’s tasks. Program statements are also known as commands because
they are orders to the computer, such as Output this word or Add these two numbers.

After the program statements are written in a high-level programming language, a computer program called a compiler
or interpreter translates the 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.

Whether you use a compiler or interpreter often depends on the programming language you use.
Note 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 technologies: a compiler to translate your programming statements and an interpreter to read the
compiled code line by line when the program executes (also called at run time).

Copyright 2023 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.
1.1 Learning Programming Terminology 3

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.

Figure 1-1 The program development process

Plan program logic

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

As Figure 1-1 shows, you might write a program that compiles successfully (that is, it contains no syntax errors), but
it still might not be a correct program because it might contain one or more 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
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 of syntax errors and execute while still

Copyright 2023 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.
4 Chapter 1 Creating Java Programs

retaining logic errors. Sometimes you can find logic errors by carefully examining the structure of your program (when
a group of programmers do this together, it is called a structured walkthrough), but sometimes 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,
Note suppose that a program should multiply two values entered by the user, that the user enters two 2s, and
that 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
Note 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 violate the rules of 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.

The false statement is #3. A language translator finds syntax errors, but logic errors can still exist in a program that
is free of syntax errors.

1.2 C
 omparing Procedural and Object-Oriented
Programming Concepts
All computer programmers must deal with syntax errors and logical errors in much the same way, but they might take
different approaches to the entire programming process. Procedural programming and object-oriented programming
describe two different approaches to writing computer programs.

Procedural Programming
Procedural programming is a style of programming in which operations are executed one after another in sequence.

Copyright 2023 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.
1.2 Comparing Procedural and Object-Oriented Programming Concepts 5

The typical procedural program defines and uses named computer memory locations; each of these named locations
that can hold data is called a variable. For example, data might be read from an input device and stored in a location
the programmer has named rateOfPay. The variable value might be used in an arithmetic statement, used as the
basis for a decision, sent to an output device, or have other operations performed with it. The data stored in a variable
can change, or vary, during a program’s execution.

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(). (As a
convention, this course will show parentheses following every procedure name.) As a procedural program executes
its statements, it can sometimes pause to call a procedure. When a program calls a procedure, the current logic is
temporarily suspended so that the procedure’s commands can execute. A single procedural program might contain any
number of 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 the following:

❯❯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


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

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
❯❯Graphical user interfaces (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 and controls traffic signals to help prevent 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. Early in this course, 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.

Copyright 2023 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.
6 Chapter 1 Creating Java Programs

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

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 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 2014 white Honda Civic, and another might be a 2021 red
Chevrolet Camaro. Similarly, your dog has the properties of all Dogs, including a breed, name, age, and whether the
dog’s 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 (words that describe a person, place, or thing), 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
Note that defines the attributes and methods of an automobile probably would be named Automobile, and
the class for dogs probably would be named Dog. This convention, however, is not required to produce a
workable program.

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

Copyright 2023 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.
1.2 Comparing Procedural and Object-Oriented Programming Concepts 7

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

Dog class definition Dog class instances (objects)

istock.com/GlobalP
istock.com/GlobalP

istock.com/olaser
Every Dog that is
created will have a:

Name

Age

Breed Ginger Bowser Roxy


6 2 1
Shot status Akita Retriever Beagle
Up to date Up to date Up to date

❯❯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 as you learn more about 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 value 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 that differentiates it from procedural 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, A
­ utomobile
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 other systems work because you realize that a convert-
ible is a type of automobile. Therefore, 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 (that does not exist in procedural programming terminology)
is polymorphism. Literally, polymorphism means many forms—it describes the feature of languages that allows the

Copyright 2023 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.
8 Chapter 1 Creating Java Programs

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, methods such as turn() and stop()
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
Note 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. Later in this course, you
will learn more about inheritance and polymorphism and how they are implemented in Java. Using Java,
you can write either procedural or object-oriented programs. In this course, you will learn about how to
do both.

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.

The false statement is #3. Inheritance 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.

1.3 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. In other words, unlike many other languages, you can use Java to write a program
that runs on any operating system (such as Windows, macOS, or Linux) or any 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 plain text editor
such as Notepad, or you can use a development environment such as Eclipse, NetBeans, or JDeveloper.
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.

Copyright 2023 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.
1.3 Features of the Java Programming Language 9

Figure 1-3 The Java environment

Java Source Code

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

When you write a Java program, the following steps take place:

❯❯The Java source code statements you write are saved in a file.

❯❯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 JVM.

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.

You can write two types of Java applications:

❯❯Console applications, which support character or text output to a computer screen

❯❯Windowed applications, which create a GUI with elements such as menus, toolbars, and dialog boxes

Copyright 2023 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.
10 Chapter 1 Creating Java Programs

Console applications are the easier applications to create; you start using them in the next section. You will create
your first simple GUI application later in this chapter.

Two Truths & a Lie   Features of the Java Programming Language

1. Java was developed to be architecturally neutral, which means that anyone can 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. You can create both console applications and windowed applications using Java.

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

1.4 A
 nalyzing 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.

Figure 1-4 The First class


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

In program code in figures in this course, Java keywords as well as true, false, and null are blue, and
Note 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 course is available in a set of student files you can
Note download so that you can execute the programs on your own computer.

Understanding the Statement That Produces the Output


Although the program in Figure 1-4 occupies several lines, it contains only one Java programming statement. This
statement does the actual work of the program:
System.out.println("First Java application");

Like all Java statements, this one ends with a semicolon. Most Java programming statements can be spread across as many
lines as you choose, as long as you place line breaks in appropriate places. For example, in the program in Figure 1-4, you
could place a line break immediately before or after the opening parenthesis, or immediately before or after the closing
parenthesis. However, you usually want to place a short statement on a single line.

Copyright 2023 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.
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Robinson Crusoëus
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Robinson Crusoëus

Author: Joachim Heinrich Campe


Daniel Defoe

Translator: François Joseph Goffaux

Release date: February 26, 2024 [eBook #73030]

Language: Latin

Original publication: Paris: F.J. Goffaux (self published), 1825

Credits: Aurēliānus Agricola

*** START OF THE PROJECT GUTENBERG EBOOK ROBINSON


CRUSOËUS ***
Important note : If during the Middle Ages Latin evolved
independently from its classical archetype, the humanists of the
Renaissance strove to restore the original language by drawing from
copies of the works of ancient authors. These copies being
imperfect, the spelling of certain words was impaired with folk
etymology and influenced by improper pronunciation, and the length
of the vowels, despite its importance in the classical language, was
and still is widely neglected. Only the rise of Indo-European studies,
especially after 1850, helped restoring and gradually spread the
original forms and sounds of the words. Older works, when they are
republished, may also benefit from the most recent spelling, and as
such show more useful to students who need to learn from the best
standards, or just provide a more pleasurable reading experience to
more advanced readers. Therefore, this work is offered to you in the
original version, but also in a renewed version, with better spelling if
applicable, and long vowels noted with macrons. On the other
hand, although the spelling has been modified, vocabulary, grammar
and syntax, fortunate or not, which belong to the author, were kept
as they were out of respect for the original work.

Access to the original version Access to the new version

ROBINSON CRUSOËUS
Latinè scripsit F. J. Goffaux, humaniorum litterarum olim professor
Quinta editio

Pueris dant crustula blandi


Doctores, elementa velint ut discere prima.
Hor. Sat. 1, v. 25.

Parisiis, et typis Augusti Delalain,

Bibliopolæ-Edit., in via Mathurinensium, nº.5.

1825.
Lectori.

S æpè animadversum est adolescentulis primum Latinarum


litterarum limen ingressis nonnihil, fastidii rerum gravitate
afferri. Itaque existimavi, non parùm ætati teneræ esse profuturum,
si quis susciperet aliquod ejusmodi opusculum, quod et doceret
simul et oblectaret. Atque is mihi visus est, qui finem hunc
assequeretur, scriptus apud Anglos de Robinsonis casibus liber, de
quo Russœus noster : Hunc primum leget Æmilius.

Cùm autem Robinsonis Anglici fabularis historia multâ


digressione luxuriet, atque in omnibus, quæ ad pueros pertinent,
satietati fastidioque sit occurrendum, placuit potissimùm seligere
optima ex simili de eodem [vi] Robinsone fabulâ, quam Germanicè
scripsit Henricus Campe. Hunc igitur auctorem eò lubentiùs secutus
fui, quòd ejus narratio aspersa sit sententiis quibus juvenum animi
ad pietatem, constantiam et sobrietatem informentur.

Habes itaque, Lector benevole, libellum nulla sanè aliâ laude


commendandum, nisi meo de juventute benè merendi studio. Quo
impulsus, in id præcipuè incubui, ut, aptato materiæ stylo,
grammaticas, quantùm fieri poterat, regulas inculcarem ; non
splendidâ gravique (res enim non ferebat), sed simplici et ad captum
legentium accommodatâ oratione. Quatenùs scopum attigerim,
judicabunt, qui exiguum hoc opus legere non dedignabuntur ; sed
oro meminerint me tironum gratiâ scripsisse.
Index capitum

I. Robinsonis ortus, indoles, educatio. — Cupido peregrinandi. —


Discessus à parentibus. — Profectio in Angliam. — Infausta initia.
— Tempestas. — Navis obruta fluctibus. — Robinson, aliâ
exceptus, advenit Londinum, unde solvit ad Guineam.
II. Robinson pergit iter. — Mala omina. — Navis incensa. — Alia
fluctibus jactata. — Advehitur ad insulas Canarias. — Descriptio
loci illius amœnissimi. — Inde profectus ad Americam naufragium
facit.
III. Sera Robinsonis pœnitentia. — Desperatio. — Vitam miserè
sustentat. — Habitat in speluncâ.
IV. Robinson reperit poma eximiæ magnitudinis. — Sibi conficit varia
instrumenta. — Funiculos. — Stratum. — Umbellam. — Peram. —
Calendarium.
V. Robinson insulam perlustrat. — Magnus terror. — In gaudium
vertitur. — Descriptio lamæ. — Unum occidit. — Sed igne caret. —
Carnem more Tartarorum coquit.
VI. Turbo ingens. — Tempestas, undè magnum Robinsoni
beneficium. — Tædium solitudinis. — Aranea.
VII. Præda ingens. — Deest res maximè necessaria. — Vota irrita. —
Ambulatio. — Natatio. — Res variæ.
VIII. Lama mansuefacta. — Pulli. — Res variæ.
IX. Terræ motus. — Mons ignivomus. — Lamæ vi aquarum abrepti.
— Spelunca Robinsonis diruta.
X. Robinson habitaculum reficit. — Parat sibi alimenta in hiemem. —
Imbribus continuis impeditus domi, fingit vasa. — Nectit rete. —
Arcum et sagittas conficit.
XI. Summæ Robinsonis miseriæ. — Ab insectis infestatur. — Vestes
ex pellibus sibi conficit. — Incidit in gravem morbum.
XII. Convalescit ex morbo. — Maximi luctus. — Parva gaudia. —
Psittacus.
XIII. Multus labor in excavandâ scaphâ. — Robinsonis constantia. —
Quomodò diem inter varias occupationes distribuit. — In bellicis
artibus se exercet.
XIV. Robinson insulam peragrat. — Vestigia hominum reperit. —
Summus terror. — Prospicit crania, ossa, manus, pedes. — Quod
territo et fugienti accidit.
XV. Epulæ atroces. — Prælium. — Fortitudo Robinsonis. — Vendredi
servatus.
XVI. Robinson paratus ad obsidionem ferendam. — Vendredi
describitur. — Quare sic appellatus.
XVII. Origo regiæ potestatis. — Robinson abundat opibus. — Habet
subditos. — Vendredi novo vivendi genere delectatur.
XVIII. Suspicio in lætitiam et admirationem versa. — Casus qui risum
legenti movebit. — Rebus secundis adversæ levantur.
XIX. Robinson habitaculum fossâ et palis munit. — Docet socium
Germanicè loqui. — Ambo scapham fabricare statuunt.
XX. Pluviarum tempus. — Socii nectunt stragulas, retia. — Cymba
conficitur.
XXI. Robinson et Vendredi, insulâ relictâ, mari se committunt. —
Summa pericula in quibus versantur.
XXII. Ambo è periculo se expediunt. — Reversi in insulam, hortum
colunt. — Piscantur ; natant ; venantur. — Novum iter suscipiunt.
XXIII. Res multæ et magnæ. — Tempestas. — Fragor tonitruum. —
Sonitus ænei tormenti. — Magna navis derelicta. — Vendredi ad
illam adnatat. — Ignota animalia. — Canis. — Capra. — Ratis.
XXIV. Multæ opes repertæ. — Cibi. — Supellex. — Instrumenta. —
Vestes. — Sclopeta. — Robinson repentè dives.
XXV. Vendredi servat Robinsonem. — Opes à littore domum advectæ
auxilio canis et lamarum. — Munimenta arci addita. — Robinson,
faber factus et agricola, vivit beatè.
XXVI. Adsunt ! adsunt ! — Arma inter socios dividuntur. — Paratur
bellum. — Duo viri adversùs quinquaginta. — Victoris clementia.
XXVII. Vendredi patrem suum invenit. — Hispanus narrat suos casus.
XXVIII. Concio advocata. — Legati missi. — Leges institutæ. —
Spelunca. — Monstrum.
XXIX. Navis anglica appulsa ad insulam. — Quo casu. — Magna
Robinsonis in præfectum merita. — Spes liberationis.
XXX. Fundata colonia. — Robinson relinquit insulam. — Quod accidit
in patriam redeunti. — Quomodo vitam deinde honestam et
beatam degit.

[1]

ROBINSON CRUSOËUS.
Caput primum.

Robinsonis ortus, indoles, educatio. — Cupido peregrinandi. —


Discessus à parentibus. — Profectio in Angliam. — Infausta initia. —
Tempestas. — Navis obruta fluctibus. — Robinson, aliâ exceptus,
advenit Londinum, unde solvit ad Guineam.

E rat Hamburgi, in urbe apud Germanos celeberrimâ, vir quidam,


cui nomen Robinson : suscepit ex uxore tres filios.

Maximus natu, armorum studiosior quàm librorum, tractare à


teneris gladios, or [2]dine militari pueros instruere, aures vicinorum
repetito tympani sonitu obtundere ; vixque adolescens factus, è fictis
certaminibus ad vera procurrens, militiæ nomen suum dedit.

Cùm ille didicisset per aliquot menses stare et sequi, vertere


corpus ad sinistram dexteramve, exarsit bellum Turcas inter et
Germanos, in quo cùm multa egregiè fecisset, cecidit adverso
confossus vulnere.

Alter, qui litteras in gymnasio discebat, ut causas in foro ageret,


sæpè principatum inter æquales in solitis concertationibus obtinebat.
Nec parva erat parentum magistrorumque de juvene exspectatio ;
sed cùm fortè in feriis septembralibus corpore adhuc calido aquam
frigidam imprudentiùs bibisset, in morbum incidit, et intra paucos
dies exstinctus est.

Jam nullus supererat præter minimum natu, qui Crusoe


appellabatur. Itaque suam in eo spem omnem ambo parentes
collocaverunt, quippe qui ipsis esset uni [3]cus. Nihil eo carius in
terris habebant ; sed amor eorum non erat rectæ rationi
consentaneus.

Cùm enim debuissent certam ei vivendi disciplinam tradere,


multaque utilia simul et jucunda eum docere, quæ ipsum olim
bonum et beatum effecissent, omnia filiolo indulserunt ; qui cùm
ludere quàm studere mallet, totam illam ætatem ; quæ bonis artibus
vacare poterat, in otio et nugis consumpsit.

Pater optabat ut ille mercaturæ se addiceret : quâquidem


proximè ab agriculturâ nihil melius, nihil fructuosius, nihil homine
libero dignius. Hoc verò minimè filio placuit ; se malle ait orbem
terrarum peragrare, ut multas res novas audire, multas videre
posset.

Jam annum ætatis decimum septimum attigerat, plurimùm verò


temporis triverat in otio. Quotidiè autem patrem urgebat, ut ab ipso
peregrinandi licentiam impetraret, quam ille nolebat concedere.
[4]Quâdam die, cùm more suo præter portum cursitaret, incidit in
unum ex æqualibus, navarchi cujusdam filium, qui in eo erat ut cum
patre Londinum navigaret.

Interrogavit eum sodalis an adjungere se socium itineris vellet :


« Libenter, ait Crusoeus ; vereor autem ut parentes id mihi
concedant. — Hui ! respondet alter, sine veniâ proficiscendum est.
Post tres hebdomades reduces erimus : parentibus verò nuntiandum
curabis, quònam terrarum migraveris. — Careo autem pecuniâ, ait
Crusoeus. — Nihil refert, alter excipit, siquidem hoc tibi constabit
gratis. »

Robinson noster, re paululum deliberatâ, ilico manum cum altero


jungens, « Euge, ô bone, exclamat ! ibo tecum ; sed confestim navem
conscendamus. » Tum mandat cuidam, ut horis aliquot elapsis
patrem conveniat, moneatque filium, ad Angliam invisendam
profectum, mox rediturum esse. Quibus peractis, ambo sodales
navem conscendunt.
[5]

Nec multò post nautæ solvunt anchoras, velaque vento


intendunt. Navis agi incipit ; navarchusque, tribus explosis tormentis
bellicis, urbi valedicit. Stabat Robinson in stegâ, et vix
præconceptam ex optato diù itinere lætitiam capiebat.

Cœlum serenum erat, ventusque adeò secundus, ut brevì


Hamburgum è conspectu abeuntium se subduxerit. Posterâ die, jam
eò devenerant ubi Albis in mare effluit, et nunc altum tenent. Quantâ
verò Robinson admiratione stupuit, cùm maris immensitatem
intuens, suprà se nihil præter cœlum, atque nihil ante, pone, circa se
nisi aquam conspexit !

Fuit per biduum aer serenus, ventusque bellè flavit


navigantibus ; tertio autem die cœlum nubibus tegi, ventusque
vehementior esse cœpit. Ac primò fulgura emicant, quasi totum
flammis cœlum arderet. Deindè ingruunt tenebræ veluti in altissimâ
nocte : tonitrua cum ingenti fragore resonare, imber de cœlo ruere
torrenti [6]similis, mare intumescens fluctus ciere. Navis modò ad
nubes tolli, modò præceps ferri in profundum. Quantus funium
strepitus ! quantus in navi tumultus ! quod nactus erat, quisque
complectebatur, ne dejiceretur ipse.

Robinson, insuetus maris adolescens, cùm jactationem maris


ferre non posset, nauseâ correptus est, et tam malè se habuit, ut
exspiranti similis videretur.

« Heu ! parentes optimi ! heu ! iterùm iterumque exclamavit,


nunquàm vos ego revisam. »

« Bone Deus ! exclamant nautæ pallidi desperantesque,


periimus ! abrepti sunt mali, navis aquâ undequaque completur. » His
auditis, Robinson, qui in cubili nautico sedebat, membris fluentibus,
retrò collapsus est. Cæteri ad antlias accurrere, ut navem, si fieri
possit, supra aquam retineant. Navarchus interim tormenta iterùm
iterùmque explosit, ut navibus, si quæ fortè non longè abessent,
si [7]gnificaret se magno in discrimine versari. Robinson, qui hujus
fragoris causam ignorabat, ratus omnia periisse, denuò exanimatus
est.

Et jam pro se quisque aquam exhaurire ; sed in infimo navis


tabulato crescebat aquæ altitudo.

Nihil præter mortem erat in exspectatione. Projiciuntur quidem


ad navem sublevandam tormenta, dolia, mercium sarcinæ ; sed nihil
hæc omnia proficiunt.

Intereà navis alia, audito sonitu tormentorum, quæ ad


significandum discrimen explosa fuerunt, scapham emiserat ad
servandos saltem navigantes ; sed æstus fluctuum obstabat,
quominus accederet. Attamen propiùs ita demum subiit, ut iis, qui in
navi essent, funis projiceretur. Cujus ope scapha tandem attracta
est, et in eam quisque desiliit, ut saluti consuleret. Robinson, qui
jacebat defuncto similis, à quibusdam nautis, quos adolescentuli
miserebat, in eamdem conjectus [8]est. Vix paululum à navi
recesserant, cùm illa ante oculos fluctibus obruta est. Et nunc feliciùs
contigit, ut tempestas paulatim sedaretur : aliter cymba, tot
hominibus onerata ipsa quoque fluctibus absorpta fuisset. Tandem,
post multa pericula, pervenit ad navem, quam omnes excepti sunt.

Navis illa Londinum tendebat. Quatuor elapsis diebus, ad ostium


Thamesis pervenit, quintâ verò in portu jecit anchoras. Mox quisque
in terram descendit, lætus quòd è periculo evasisset. Vix Robinson
pedem è nave extulerat, cùm eum incessit cupido visendæ immensæ
urbis Londini. Quidquid erat in oculis spectantem ita detinuit, ut
præteriti immemor de futuro quidem minimè curaret. Tandem suus
eum stomachus admonuit, Londini haud secùs ac alibi terrarum cibis
opus esse. Itaque adiit præfectum ejus navis quæ ipsum advexerat,
rogavitque ut liceret ipsius mensæ assidere. Ille verò lu [9]benter
juvenem excepit ; atque inter prandendum ab hospite quærit, quo
consilio et quid facturus hùc venerit ? Tum Robinson ingenuè
professus est, se animi recreandi causâ hoc iter suscepisse, atque
insciis parentibus ; jam autem se esse omninò inopem. « Insciis
parentibus tuis ? clamat nauta exterritus : bone Deus ! utinàm hoc
ego priùs rescivissem ! nunquam sanè à me impetrâsses, ut ego te in
navem meam admitterem. » Robinson, demissis oculis, vultuque
rubore suffuso, siluit. Nec desiit bonus nauta monere adolescentem,
quàm graviter peccavisset, addiditque illum nunquam aliquâ ex parte
beatum esse posse, donec à suis veniam oravisset. Robinson
commotus multùm flevit : « Sed quid agam nunc ? » rogat ille cum
singultu.
« Quid ages ? respondet alter : primam quamlibet navem, quæ
hinc Hamburgum tendit, sine morâ conscendes ; tunc re [10]versus ad
tuos peccati veniam piè rogabis, pollicitus te nunquam posteà in
simili culpâ fore. — Sed planè careo pecuniâ, ait Robinson. — En
quatuor guineas, excepit nauta, quas ego tibi commodabo, licèt ipse
parvo, quod mihi superest, ægrè caream. His tu adjutus ad portum
te confer ; sit Deus tibi magis propitius redeunti quàm nobis fuit
navigantibus. » His dictis, manum benevolè junxit, atque faustum
iter ipsi precatus est. Abiit Robinson.

Dùm ille portum peteret, varia secum in animo volvebat :


« Quomodò mei reducem me excipient ? Castigabunt sanè propter
tale delictum. Sodales verò, et tam multi alii me irridebunt, quòd tam
citò redierim. » Sic diù dubitans quidnam consilii caperet, ad portum
pergit ; sed ibi audiit, summâ quidem cum voluptate, nullam adesse
navem, quæ Hamburgum tenderet. Qui autem hâc de re eum
certiorem fecerat, unus è præfectis [11]earum navium erat, quæ ad
Guinean proficiscuntur.

Cùm Robinson inter confabulandum dixisset, se non dolere quòd


nulla sibi Hamburgum redeundi adesset opportunitas, quia mirâ
flagrabat cupiditate peregrinandi, præfectus navis ei auctor fuit
itineris ad Guineam faciendi. Quo audito, primùm Robinson
obstupuit. Sed cùm præfectus itineris ei declaravisset, iter hoc fore
jucundissimum, seque ut haberet ipse quîcum versaretur, gratìs eum
excepturum, ac prætereà rem eam esse undè quæstum ille non
mediocrem faceret, tum verò tanta eum invasit cupiditas
proficiscendi, ut subitò è memoriâ exciderit quidquid bonus nauta
Hamburgensis eum admonuerat.
Sed re paululum consideratâ, « Equidem, ait Robinson, quatuor
tantummodò guineas habeo. Ecquid ego commercii cum hâc exiguâ
re eo loco faciam, quò tu proficisceris ? — Sex insuper guineas ego
tibi commodabo, respondit præfectus. [12]Nec majore pecuniâ tibi
opus est ad emendum unde multas in Guineâ opes consequaris.
Quoties ab exiguis initiis res maximæ profectæ sunt !

« Sed quid ego his emam ? Robinson interrogat. — Meras nugas,


respondit præfectus ; vitres, torques, cultros, forfices, secures,
tænias, etc., quibus nigri Africæ incolæ tantopere gaudent, ut tibi
vim auri eborisque centies majorem pro iis daturi sint. »

Nec jam diutiùs sibi Robinson temperare potuit ; sed oblitus


parentum, amicorum, patriæ, exclamat : « En ego tibi comes itineris
præsto sum. — Agedum, » respondit præfectus, dextrisque junctis
rem paciscuntur.

Robinson itaque decem guineis dives ad urbem properat,


comparat varias merces, uti navarchus præceperat, comparatasque
in navem transportandas curat. Paucis diebus elapsis, vento favente,
præfectus navis anchoras solvi, atque vela ventis dari jussit.
[13]
Caput secundum.

Robinson pergit iter. — Mala omina. — Navis incensa. — Alia


fluctibus jactata. — Advehitur ad insulas Canarias. — Descriptio loci
illius amœnissimi. — Inde profectus ad Americam naufragium facit.

N ovum hoc Robinsonis iter faustissimum initium habuit. Jamque


incolumes fretum Calesium transierant, et in ipso Atlantico mari
versabantur : tum verò per plurimos dies continuos vento reflante
navis Americam versùs abrepta est.

At ecce vespere quodam gubernator declaravit se flammas


relucentes à longinquo conspicere ; cùmque inspectâ tabulâ nauticâ
intelligeret vel ad centum milliaria nihil terrarum esse, conjectabat
hunc [14]ignem nihil aliud esse nisi navem incendio flagrantem.

Vix hæc dixerat, cùm in auras tolli visa est navis, terribili cum
fragore, et mox tota undis obruta est. Cùm nox supervenisset, nihil
ampliùs cerni poterat. Primâ autem luce apparent duæ scaphæ, cum
fluctibus colluctantes, quæ remis pertinaciùs everberabant mare, ut
ad navem accederent. Extemplò præfectus vexillum nauticum
explicuit, significans se ad opem illis ferendam paratum esse. Navis
ipsa omnibus velis ad eos tendit, atque intra dimidium horæ ad
miseros pervenit.
Sexaginta erant, viri, mulieres et pueri, qui omnes nave excepti
sunt. Erat res omninò miserabilis, cùm infelices illi faucibus mortis se
ereptos viderent. Alii enim flere præ gaudio, alii clamare, quasi
periculum nunc primùm immineret ; illi exsultare saltu lymphatico, hi
verò pallidi manus torquere. Nonnulli stare muti et stupentibus
similes. Nemo quòque inter nau [15]tas tam ferreus, quin his
conspectis commotus ipse lacrymaretur.

Cùm eis paulatim rediisset animus, unus narravit quid miseris


accidisset :

« Navis incensa magna quædam navis erat mercatoria


Francorum, quæ ad insulam Martinicam tendebat. Exarserat ignis in
cubiculo gubernatoris, flammâ tam velociter grassante, ut nulla ejus
exstinguendæ spes adforet. Vix per tempus licebat se in cymbas
recipere, et ab incensâ nave paululùm discedere, cùm, flammâ
cameram, in quâ pulvis tormentarius sepositus est, corripiente,
discerpta navis dissiluit. »

Dum hæc narrarentur, sedebat in angulo Robinson silens,


pallidusque, similis homini quem malefacti remordet conscientia.
« Bone Deus ! ait ille secum, si cum hominibus illis, inter quos sunt
profectò quidam longè quàm ego meliores, tam malè agitur, heu !
quid mihi ex [16]spectandum, qui sic erga parentes peccaverim ? »

Cùm illi cibo aliquo refecti fuissent, tum unus qui dignitate
cæteris præstare videbatur, præfectum adiit, crumenamque aureis
nummis plenam porrigens, « Ego inquit, miseram illam navem
instruxi ; hoc solum eripui, oroque ut pignus grati pro salute animi
accipias. »
Tum verò fuit res spectaculo digna, certamen ambos inter viros,
uter hinc gratior, inde honestior foret.

« Absit sanè, respondet præfectus, ut munus tuum accipiam.


Cùm ego vobis opem tuli, nihil aliud egi quàm quod à naturâ homini
erga hominem præscriptum est, scilicet ut homo homini, quicumque
sit, consulat, ob eam causam quòd is homo sit. »

Frustrà ille præfectum urgere, ut oblatum munus acciperet ;


perseveranter negavit, rogans, ut rem planè dimitteret. [17]Tum
deliberatur, quònam servati homines essent vehendi. Duplex erat
causa cur ad Guineam non ducerentur. Primò quidem minimè opus
erat longum iter in eam regionem facere, nihil ibi negotii habentibus.

Nec deinde tanta aderat in nave ciborum copia, undè tot


navigantes in itinere victitarent.

Præfectus tandem statuit, omissâ propriâ utilitate, centum et


ampliùs milliaribus à viâ rectâ deflectere, eosque in Terram Novam
transportare, ubi sperabat fore, ut sese offerret opportunitas in
Galliam cum piscatoribus asellorum redeundi. Eò igitur cursum
direxit ; cùmque advenisset, naves Gallicas nactus est, quæ miseros
receperunt. His peractis, iter suum ad Guineam prosecutus est.

Tum navis celerrimo cursu, aquas secat ; quâ navigandi


velocitate Robinson noster mirè delectatus est. Post aliquot dies,
ecce magnam navem conspiciunt, ad se ten [18]dentem. Mox verò
audiunt sonitum tormentorum periculi instantis indicem, et
animadvertunt navem esse duobus malis orbatam. Cùm ad eam
propiùs accessissent, qui in eâ vehebantur, sublatis manibus,
miserabiliter exclamant : « Servate infelices quibus omnibus
pereundum est, nisi vos eorum miserebit. »
Tum ex iis quæsitum est quid mali accidisset ; quidam verò ex
illis sic orsus est :

« Angli sumus, ex insulâ Jamaica, sacchari vecturam inde


deportaturi. Ibi dum navis staret anchoris alligata, præfectus cum
gubernatore in terram descendit, ad merces aliquas insuper
emendas.

« Intereà exorta est tempestas, tanto turbine, ut, fune disrupto,


navis ex portu in altum propelleretur. Tempestas ista tres dies
noctesque sæviit : tum malis omnibus amissis, centum et plura
milliaria abrepti sumus. Accedit ad hanc nostram calamitatem, quòd
nemo nostrorum artis nauticæ peritus sit : novem jam [19]integras
hebdomades hinc et inde jactati, victum omnem consumpsimus, et
nostri plerique jacent fame exhausti. »

Bonus itaque præfectus statim cymbam exponi jussit,


assumptâque secum idoneâ ciborum copiâ, ipse cum Robinsone ad
navem accedit. Erat sanè lugenda prorsùs omnium conditio qui in illâ
vehebantur : universi inediâ quasi consumpti ; nonnulli vix poterant
pedibus stare.

Cùm autem cubiculum nauticum intrâssent, horrendum visu !


jacebant humi mater, filius et servula, qui omnes fame enecti
videbantur. Mox autem deprehensum est, reliquias in eis animæ
vitalis superesse. Postquam enim nonnullæ succi è carne expressi
guttæ in os cujusque instillatæ sunt, lucem oculis quærere
cœperunt.

Mater præ nimiâ virium imbecillitate nihil quidquam absorbere


poterat ; cùm autem innuisset, ut tantummodò filio suo consuleretur,
mox illa exspiravit.
[20]

Inter hæc duo reliqui animam receperant ; atque ut erant ætate


robustiores, præfecti diligentiâ feliciùs servati sunt. Cùm autem
juvenis, oculis in matrem conjectis, mortuam esse intellexisset,
tantus eum invasit dolor, ut deficientibus iterùm viribus ægrè ad
vitam revocari posset. Vicit tamen cura, atque ille cum servâ quoque
è faucibus mortis ereptus est. Deinde præfectus navem omni genere
alimentorum instruxit, malos à fabris suis reficiendos curavit,
ignarisque maris peritum nautam dedit, qui navem regeret ; atque ad
terram proximam ipse tendit, ut novam cibariorum comparationem
faceret. Hæc erat insula Madeira, una è Canariis. Robinson unà cum
præfecto in terram descendit, atque ibi lætissimo fortunatæ illius
insulæ adspectu satiari non potuit. Scilicet terra partim in planitiem
porrecta, partim in colliculos molliter assurgens, vernantem
frugiferarum arborum copiam explicat. Cœli admodum jucunda
temperies : nullus [21]enim hìc hiemis rigor ; ita vim omnem frigoris
retundunt clementiores solis radii mollesque favoniorum animæ,
quarum flabellis regio tota circumquàque ventilatur. Erant in oculis,
quàm longè patebat prospectus, segetes in agris benè pinguibus
diffusæ, juga montium continuis vitibus consita. Ut arridebant
Robinsoni nostro pendentes racemi ! Ô quales ille hausit delicias,
cùm præfectus ære dato impetravit, ut juveni liceret uvis pro libidine
satiari. Postquam ibi aliquantùm temporis moratus esset navis
reficiendæ causâ, anchoram solvit.

Per plures continuos dies felicissimo cursu usi sunt.

At ecce repentè vehemens tempestas ab austro oritur.


Spumabant fluctus, et in immensam surgebant altitudinem. Navis
tamen stetit invicta ; sed cùm sex dies continuos atrox tempestas
sæviisset, illa tam longè à viâ dejecta est, ut nec præfectus, nec
gubernator ampliùs intelligerent, quo [22]nam in loco versarentur.
Arbitrabantur tamen se ab insulis, quæ Caraïbæ vocantur, non
multum distare. Septimo autem die, cùm primùm illucesceret, è
nautis quidam, ingenti omnium lætitiâ, terram inclamat. Tum omnes
in stegam conscendere, visuri quænam sit terra illa ad quam
appulsuri sunt. Sed nunc lætitia in summum terrorem mutata est.
Ecce enim navis impingitur : quo ictu qui stabant in stegâ excussi
omnes planè corruerunt.

Scilicet navis in syrtem tam vehementi impetu allisa erat, ut


hæreret quasi affixa. Confestìm verò fluctus spumantes tantam vim
aquæ in stegam profuderunt, ut omnibus in cubiculo fuerit
confugiendum, ne ipsi abriperentur.

Tum flebilis nautarum oriri clamor ; tum ejulatus hinc Deum


orantium, inde clamantium : alii desperantes sibi crines avellere,
quidam jacere semianimi.

Hos inter Robinson erat exspiranti similis ; ac repentè exclamant


navem dehiscere. [23]Itaque in stegam omnes accurrere, et
demissam quàm celerrimè in scapham omnes desilire. Tanta autem
erat multitudo inconsultè ruentium, ut vix scapha palmæ latitudine
undas superaret. Cùm verò terra procul obesset, cuncti de orâ
unquàm assequendâ, sæviente adeò tempestate, desperabant.

At ecce ingens fluctus ad scapham volvi, montis instar : quo


omnes conspecto obstupescere, remosque dimittere. Nunc, nunc
instat periculum. Et jam aquæ mons scapham assequitur
subvertitque ; tum universi hauriuntur.
[24]
Caput tertium.

Sera Robinsonis pœnitentia. — Desperatio. — Vitam miserè


sustentat. — Habitat in speluncâ.

F elici fato contigit, ut ingens ille fluctus qui Robinsonem


absorpserat, idem vi magnâ reciprocans, hominem in vado
exspueret. Hic cùm præter exspectationem in sicco versaretur, tum
extremis viribus usus est, ut summam in oram adscenderet ; cùmque
eò pervenisset, cœpit circumspicere. Eheu ! qualia oculis
obversantur ! scapha, navis, socii, omnia demersa. Nihil omninò
reliquum præter avulsas tabulas, quæ fluctuantes ad terram
ferebantur. Unus ipse, unus mortem effugerat. Gaudio igitur et
terrore trepidans, [25]in genua procubuit, manibusque sublatis,
lacrymis perfusus, Deo pro salutis miraculo gratias egit. Cùm verò
nihil præter arbusta aut arbores deprehenderet, nec ulla vestigia,
unde intelligere posset hanc regionem ab hominibus incoli, jam
gravissimum illi videbatur vitam sic in solitudine degere. Venit
quoque in mentem esse fortè vagantes belluas, aut feros homines ;
tùm multò majori horrore perculsus est. Itaque primum præ timore
nec stare ausus, nec progredi, circumspectare omnia, et vel minimo
strepitu expavescere. Sed mox quâ ardebat sitis torporem istum
excussit ; quam cùm diutiùs tolerare non posset, fontem aut rivum
indagare cœpit, et sic vestiganti occurrit manans per herbas rivulus :
quem ille secutus, invenit fontem liquidissimum, quo valdè recreatus
est.

Nec illum fames tunc maximè urgebat ; quippe cui angor


terrorque omnem cibi appetitum exemerant. Sed erant adeò
ex [26]haustæ illius vires, ut multò magis requiescere optaret.
Attamen caput erat locum invenire, in quo tutus pernoctaret. Nulla
domus, nullum tugurium, nullum specus erat in conspectu. Sic diù
consilii inops flevit. Tandem aves imitari, hospitiumque in arbore
quærere statuit. Ac brevì unam prospexit tam densam opacamque,
ut commodè insidere dorsumque acclinare posset : hanc adscendit
reptando, pièque Deum precatus, cùm se composuisset, statim
obdormivit. Inter somnum, illius menti, ut erat curarum æstu jactata,
rerum earum, quæ pridiè vigilanti acciderant, recursabant imagines.
Videre sibi videbatur motum et agitationem fluctuum navem
haurientium, nautarumque ejulatus exaudire. Sibi in animo fingebat
parentes luctu ac mœrore confectos, qui filii vicem dolentes,
manibus ad cœlum sublatis, flebant, et omne prorsùs solatium
aversabantur. Tunc altâ voce exclamat, inter somniandum : « Adsum,
adsum, parentes [27]carissimi ! » Dumque amplexu matrem petit,
decidit ex arbore. Sed fortè quod ipsi faustum fuit, sedem in loco
non ita sublimi posuerat, solumque tam denso gramine vestitum
erat, ut ille casu non ita gravi decideret. Iterum arborem suam
conscendit, in quâ manibus retinens surculos circâ eminentes, ad
ortum solis remansit.

Primâ luce cœpit cogitare, quâ ratione victum sibi pararet.


Omnes verò arbores quas hactenus conspexerat, erant ex earum
genere quas campêche vocamus ; atque illæ folia quidem, sed
fructus ferunt omninò nullos.
Nec satis illi liquebat, quid sibi faciendum esset. Ex arbore
tamen descendit. Cùm autem pridiè nihil omnino comedisset, cœpit
fame sævissimâ laborare : itaque huc illuc per aliquot millia passuum
discurrit ; sed discurrendo nihil invenit, nisi arbores steriles et
gramina.

Tunc summo angore excruciatus famem [28]et ultima sibimet


ominabatur : « Pereundum mihi erit fame ! » exclamat, miserabiliter
ejulans. Desperanti verò necessitas satis animi viriumque adjecit, ut
se ad littus maris conferret, investigaretque diligentiùs, si quid fortè
alimenti inveniret. Sed sua eum spes fefellit. Hìc verò debilitatus
fractusque procubuit, facie in terram demissâ, flentemque miserè
pœnituit, quòd non fuisset fluctibus et ipse obrutus. Et jam statuerat
in hoc miserabili rerum articulo exspectare, dum lenta fames morte
omnium teterrimâ consumeret vitam, cùm fortè conversus, ecce
conspexit nonnullas in arenâ squamas ostrearum. Avidus itaque eò
accurrere, circumspicere, scrutari, num fortè plenas quasdam
reperiret, repertisque exsultare.

Ac primò quidem illas non sine difficultate aperuit ; sed inserto


plano eodemque acuto silice perfecit, ut triginta circiter haustis
ventrem paululùm placaret. [29]Cùm nunc certior esset, se posse
quamvis miserè sustentare vitam, jam maximè sollicitus erat, quò se
à feris hominibus aut bestiis tutum reciperet.

Tum in montem summum, ægrè, ut erat satis excelsus,


adscendit, unde quàm latissimè circumspicere poterat. Sed quantus
eum terror invasit, cùm vidisset se esse in insulâ, neque ullam
omninò, quàm longè aciem oculorum intendere posset, terram
apparere, præter tres parvas insulas, quæ, spatio aliquot milliarium
interjecto, ex æquore eminebant !
« Heu ! me miserum ! exclamat, manibus ad cœlum miserabiliter
sublatis. Me ne ab hominum commercio ita sejunctum esse, ut mihi
in hâc solitudine vivendum sit velut feræ bestiæ ! Heu ! parentes
optimi, nunquam igitur ego vos revisam ! Nunquam licebit culpæ
meæ veniam exorare ! »

Et sic dolens descendit de monte, cir [30]cumspiciens, ubi posset


in tuto se collocare. Diù autem frustrà indagavit ; tandem ad locum
editorem pervenit, ex adversâ parte, instar parietis, præruptum.
Cùm accuratiùs exploraret, locum invenit leviter excavatum, satis
angusto aditu. Hìc si uncum, si scalprum, aut alia quævis
instrumenta habuisset, facili negotio cavum in saxo excisum per
fragmenta habitaculo idoneum fecisset. Sed cùm hæc omnia
desideraret, huic inopiæ medendum erat.

Cùm diù multùmque deliberâsset, sic secum statuit : « Arbores,


quas hìc video, salicibus patriis similes sunt, quæ, si transferantur,
novas facilè radices agunt. Eruam igitur manibus satis magnam
earum copiam, quæ, ante cavum denso ordine consitæ, erunt pro
munimento ; cùm illæ radices egerint, ibi licebit clauso et securo mihi
quasi in domo dormire. »
[31]

Tunc felici hoc invento lætus, ad opus statim se accinxit. Sed


quanto majore gaudio exsultavit, cùm huic loco proximum fontem
liquidissimum prospexisset è monte exsilientem ! Eò statim
properavit, quia, cùm huc illuc fervente sole discurrisset, multùm
æstuabat.

Posteà verò cœpit manibus et multo sudore teneras aliquot


arbores exstirpare, quas eò transtulit, ubi sedem sibi destinaverat,
atque ibi quòque cavum fodere manibus oportuit, in quo arbores
insereret : hoc verò multum temporis requirente, vesper advenit, vix
quinque aut sex numero arboribus consitis. Fame compulsus, oram
maris rursùs petiit, ut novas conquireret ostreas. Sed cùm æstus
rediisset, totum littus occupaverant undæ : ægrè igitur unam aut
alteram reperit, et sic malè pastus cubitum ire coactus est. Reversus
est igitur ad arborem suam, ibi pernoctaturus, donec hospitium sibi
[32]tutum confecisset. Ne autem hâc nocte idem ipsi accideret quod
superiori, genualibus se ei ramo religavit, ad quem dorsum priùs
acclinaverat, cùmque summo rerum creatori se commendâsset,
tranquillè obdormivit.
[33]
Caput quartum.

Robinson reperit poma eximiæ magnitudinis. — Sibi conficit varia


instrumenta. — Funiculos. — Stratum. — Umbellam. — Peram. —
Calendarium.

H ac nocte Robinson non decidit ex arbore ; sed placidè usque ad


ortum solis quievit.

Primâ luce, littus petiit, ut, collectis ibi ostreis, ad opus


inchoatum reverteretur. Cùm eò aliâ viâ tenderet, eunti contigit
invenire arborem quæ poma inusitatæ magnitudinis ferebat. Etsi
eorum indolem ignorabat, sperans tamen ea fore quibus vesci
posset, unam ex iis decussit. Erat autem nux oblonga nec minor
capite [34]pueruli, quæ vulgò in Americæ insulis vocatur cocossa.
Erat nucleus quasi medulla et succus qui saporem olei ex dulci
amygdalâ expressi referebat, atque in medio lac exquisitum.

Cùm stomachum latrantem una non placaret, secundam, tertiam


quoque decussit, quibus abundè satiatus, tamen littus maris petiit ;
cùmque mare reddidisset terras paulò ante salo mersas, nonnullas
passim in sicco ostreas reperit. Magnam quoque et planam in littore
concham invenit, quâ pro spathâ usus est ; atque illud ipsi non
mediocri fuit adjumento. Nec multò post plantam deprehendit
fibroso caule, qualis est apud nos lini aut cannabis.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like