100% found this document useful (2 votes)
55 views

Instant ebooks textbook Java Programming 8th Edition Joyce Farrell download all chapters

Farrell

Uploaded by

esaqbezar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
55 views

Instant ebooks textbook Java Programming 8th Edition Joyce Farrell download all chapters

Farrell

Uploaded by

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

Download the full version of the ebook at

https://ebookultra.com

Java Programming 8th Edition Joyce Farrell

https://ebookultra.com/download/java-
programming-8th-edition-joyce-farrell/

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


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Java Programming 7th Edition Joyce Farrell

https://ebookultra.com/download/java-programming-7th-edition-joyce-
farrell/

ebookultra.com

Programming Logic and Design Comprehensive 6th Edition


Joyce Farrell

https://ebookultra.com/download/programming-logic-and-design-
comprehensive-6th-edition-joyce-farrell/

ebookultra.com

Introduction to Java Programming Brief 8th Edition Edition


Y. Daniel Liang

https://ebookultra.com/download/introduction-to-java-programming-
brief-8th-edition-edition-y-daniel-liang/

ebookultra.com

Computer programming for teens 1st Edition Mary E. Farrell

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

ebookultra.com
Advanced Java Game Programming Wallace Croft

https://ebookultra.com/download/advanced-java-game-programming-
wallace-croft/

ebookultra.com

Core Java Volume 1 Fundamentals 8th ed Edition Horstmann

https://ebookultra.com/download/core-java-volume-1-fundamentals-8th-
ed-edition-horstmann/

ebookultra.com

Java Programming 10 Minute Solutions 1st Edition Mark


Watson

https://ebookultra.com/download/java-programming-10-minute-
solutions-1st-edition-mark-watson/

ebookultra.com

Killer Game Programming in Java 1st Edition Andrew Davison

https://ebookultra.com/download/killer-game-programming-in-java-1st-
edition-andrew-davison/

ebookultra.com

Introduction to Programming with Java 3rd Edition John


Dean

https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/

ebookultra.com
Java Programming 8th Edition Joyce Farrell Digital
Instant Download
Author(s): Joyce Farrell
ISBN(s): 9781285856919, 1285856910
Edition: 8th
File Details: PDF, 15.03 MB
Year: 2016
Language: english
EIGHTH EDITION

JAVA PROGRAMMING

JOYCE FARRELL
Java Programming,
Eighth Edition
Joyce Farrell

© 2016, 2014, 2012 Cengage Learning


WCN: 02-200-203

Library of Congress Control Number: 2014956152


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

Printed in the U nited States of America


Print N umber: 01 Print Year: 2015
Brief Contents
Preface . . . . . . . . . . . . . . . . . . . . . . xxi
CHAPTER 1 Creating Java Programs . . . . . . . . . . . . . . . . 1
CHAPTER 2 Using Data . . . . . . . . . . . . . . . . . . . . . 53
CHAPTER 3 Using Methods, Classes, and Objects . . . . . . . 119
CHAPTER 4 More Object Concepts . . . . . . . . . . . . . . . 183
CHAPTER 5 Making Decisions . . . . . . . . . . . . . . . . . 245
CHAPTER 6 Looping . . . . . . . . . . . . . . . . . . . . . 301
CHAPTER 7 Characters, Strings, and the StringBuilder . . . 353
CHAPTER 8 Arrays . . . . . . . . . . . . . . . . . . . . . . 393
CHAPTER 9 Advanced Array Concepts . . . . . . . . . . . . . 439
CHAPTER 10 Introduction to Inheritance . . . . . . . . . . . . . 491
CHAPTER 11 Advanced Inheritance Concepts . . . . . . . . . . 537
CHAPTER 12 Exception Handling . . . . . . . . . . . . . . . . 593
CHAPTER 13 File Input and Output . . . . . . . . . . . . . . . 665
CHAPTER 14 Introduction to Swing Components . . . . . . . . 729
CHAPTER 15 Advanced GUI Topics . . . . . . . . . . . . . . . 791
CHAPTER 16 Graphics . . . . . . . . . . . . . . . . . . . . . 861
APPENDIX A Working with the Java Platform . . . . . . . . . . . 919
APPENDIX B Data Representation . . . . . . . . . . . . . . . 925
APPENDIX C Formatting Output . . . . . . . . . . . . . . . . 931
APPENDIX D Generating Random Numbers . . . . . . . . . . . 941
APPENDIX E Javadoc . . . . . . . . . . . . . . . . . . . . . 949
Glossary . . . . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . . . . 979
Contents
Preface . . . . . . . . . . . . . . . . . . xxi

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


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

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


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

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


Understanding Method Calls and Placement . . . . . . . . . . 120
Understanding Method Construction . . . . . . . . . . . . . 123
Access Specifiers . . . . . . . . . . . . . . . . . . . . 123
Return Type . . . . . . . . . . . . . . . . . . . . . . 124
Method Name . . . . . . . . . . . . . . . . . . . . . 125
Parentheses . . . . . . . . . . . . . . . . . . . . . . 125
Adding Parameters to Methods . . . . . . . . . . . . . . . 129
Creating a Method that Receives a Single Parameter . . . . . 130
Creating a Method that Requires Multiple Parameters . . . . . 133
Creating Methods that Return Values . . . . . . . . . . . . . 136
Chaining Method Calls . . . . . . . . . . . . . . . . . . 138
Learning About Classes and Objects . . . . . . . . . . . . . 142
Creating a Class . . . . . . . . . . . . . . . . . . . . . 145
Creating Instance Methods in a Class . . . . . . . . . . . . 147
Organizing Classes . . . . . . . . . . . . . . . . . . . 150
Declaring Objects and Using their Methods . . . . . . . . . . 154
Understanding Data Hiding . . . . . . . . . . . . . . . . 156
An Introduction to Using Constructors . . . . . . . . . . . . 159
Understanding that Classes Are Data Types . . . . . . . . . . 163
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 168
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 168
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 170
Review Questions . . . . . . . . . . . . . . . . . . . . . 171
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 174
Programming Exercises . . . . . . . . . . . . . . . . . 174
Debugging Exercises . . . . . . . . . . . . . . . . . . 177
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 178
Case Problems . . . . . . . . . . . . . . . . . . . . . 179
CHAPT ER 4 More Object Concepts . . . . . . . . . . . 183
Understanding Blocks and Scope . . . . . . . . . . . . . . 184
Overloading a Method . . . . . . . . . . . . . . . . . . . 192
Automatic Type Promotion in Method Calls . . . . . . . . . 194
Learning About Ambiguity . . . . . . . . . . . . . . . . . 199
Creating and Calling Constructors with Parameters . . . . . . . 200
Overloading Constructors . . . . . . . . . . . . . . . . 201
Learning About the this Reference . . . . . . . . . . . . . 205
Using the this Reference to Make Overloaded Constructors
More Efficient . . . . . . . . . . . . . . . . . . . . . 209
Using static Fields . . . . . . . . . . . . . . . . . . . 213
Using Constant Fields . . . . . . . . . . . . . . . . . . 215
Using Automatically Imported, Prewritten Constants
and Methods . . . . . . . . . . . . . . . . . . . . . . 220
The Math Class . . . . . . . . . . . . . . . . . . . . 221
Importing Classes that Are Not Imported Automatically . . . . 223
Using the LocalDate Class . . . . . . . . . . . . . . . 224
Understanding Composition and Nested Classes . . . . . . . . 230
Composition . . . . . . . . . . . . . . . . . . . . . . 230
Nested Classes . . . . . . . . . . . . . . . . . . . . . 232
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 234
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 234
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 236
Review Questions . . . . . . . . . . . . . . . . . . . . . 236
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 239
Programming Exercises . . . . . . . . . . . . . . . . . 239
Debugging Exercises . . . . . . . . . . . . . . . . . . 242
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 242
Case Problems . . . . . . . . . . . . . . . . . . . . . 243

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


Planning Decision-Making Logic . . . . . . . . . . . . . . . 246
The if and if…else Statements . . . . . . . . . . . . . . 248
The if Statement . . . . . . . . . . . . . . . . . . . . 248
Pitfall: Misplacing a Semicolon in an if Statement . . . . . . 249
Pitfall: Using the Assignment Operator Instead
of the Equivalency Operator . . . . . . . . . . . . . . 250
Pitfall: Attempting to Compare Objects
Using the Relational Operators . . . . . . . . . . . . . 251
The if…else Statement . . . . . . . . . . . . . . . . . 251
Using Multiple Statements in if and if…else Clauses . . . . 254
Nesting if and if…else Statements . . . . . . . . . . . . 260
Using Logical AND and OR Operators . . . . . . . . . . . . 263
The AND Operator . . . . . . . . . . . . . . . . . . . . 263
The OR Operator . . . . . . . . . . . . . . . . . . . . 265
Short-Circuit Evaluation . . . . . . . . . . . . . . . . . . 266
Making Accurate and Efficient Decisions . . . . . . . . . . . 269
Making Accurate Range Checks . . . . . . . . . . . . . . 270
Making Efficient Range Checks . . . . . . . . . . . . . . 272
Using && and || Appropriately . . . . . . . . . . . . . . 273
Using the switch Statement . . . . . . . . . . . . . . . . 274
Using the Conditional and NOT Operators . . . . . . . . . . . 280
Using the NOT Operator . . . . . . . . . . . . . . . . . 281
Understanding Operator Precedence . . . . . . . . . . . . . 282
Adding Decisions and Constructors
to Instance Methods . . . . . . . . . . . . . . . . . . . 285
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 289
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 289
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 291
Review Questions . . . . . . . . . . . . . . . . . . . . . 291
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 294
Programming Exercises . . . . . . . . . . . . . . . . . 294
Debugging Exercises . . . . . . . . . . . . . . . . . . 297
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 297
Case Problems . . . . . . . . . . . . . . . . . . . . . 299

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


Learning About the Loop Structure . . . . . . . . . . . . . . 302
Creating while Loops . . . . . . . . . . . . . . . . . . 303
Writing a Definite while Loop . . . . . . . . . . . . . . 303
Pitfall: Failing to Alter the Loop Control Variable
Within the Loop Body . . . . . . . . . . . . . . . . . 305
Pitfall: Unintentionally Creating a Loop with
an Empty Body . . . . . . . . . . . . . . . . . . . . 306
Altering a Definite Loop’s Control Variable . . . . . . . . . . 307
Writing an Indefinite while Loop . . . . . . . . . . . . . 308
Validating Data . . . . . . . . . . . . . . . . . . . . . 310
Using Shortcut Arithmetic Operators . . . . . . . . . . . . . 314
Creating a for Loop . . . . . . . . . . . . . . . . . . . 319
Unconventional for Loops . . . . . . . . . . . . . . . . 320
Learning How and When to Use a do…while Loop . . . . . . 325
Learning About Nested Loops . . . . . . . . . . . . . . . . 328
Improving Loop Performance . . . . . . . . . . . . . . . . 333
Avoiding Unnecessary Operations . . . . . . . . . . . . . 333
Considering the Order of Evaluation of Short-Circuit
Operators . . . . . . . . . . . . . . . . . . . . . . 334
Comparing to Zero . . . . . . . . . . . . . . . . . . . 334
Employing Loop Fusion . . . . . . . . . . . . . . . . . . 336
Using Prefix Incrementing Rather than Postfix
Incrementing . . . . . . . . . . . . . . . . . . . . . 337
A Final Note on Improving Loop Performance . . . . . . . . 338
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 342
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 342
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 344
Review Questions . . . . . . . . . . . . . . . . . . . . . 344
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 347
Programming Exercises . . . . . . . . . . . . . . . . . 347
Debugging Exercises . . . . . . . . . . . . . . . . . . 350
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 350
Case Problems . . . . . . . . . . . . . . . . . . . . . 352

CHAPT ER 7 Characters, Strings, and


the StringBuilder . . . . . . . . . . . . 353
Understanding String Data Problems . . . . . . . . . . . . . 354
Using Character Class Methods . . . . . . . . . . . . . . 355
Declaring and Comparing String Objects . . . . . . . . . . 359
Comparing String Values . . . . . . . . . . . . . . . . 359
Empty and null Strings . . . . . . . . . . . . . . . . . 363
Using Other String Methods . . . . . . . . . . . . . . . 365
Converting String Objects to Numbers . . . . . . . . . . 369
Learning About the StringBuilder
and StringBuffer Classes . . . . . . . . . . . . . . 374
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 381
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 382
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 382
Review Questions . . . . . . . . . . . . . . . . . . . . . 383
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 385
Programming Exercises . . . . . . . . . . . . . . . . . 385
Debugging Exercises . . . . . . . . . . . . . . . . . . 388
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 388
Case Problems . . . . . . . . . . . . . . . . . . . . . 391

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


Declaring Arrays . . . . . . . . . . . . . . . . . . . . . 394
Initializing an Array . . . . . . . . . . . . . . . . . . . . 399
Using Variable Subscripts with an Array . . . . . . . . . . . . 402
Using the Enhanced for Loop . . . . . . . . . . . . . . 403
Using Part of an Array . . . . . . . . . . . . . . . . . . 404
Declaring and Using Arrays of Objects . . . . . . . . . . . . 406
Using the Enhanced for Loop with Objects . . . . . . . . . 408
Manipulating Arrays of Strings . . . . . . . . . . . . . 408
Searching an Array and Using Parallel Arrays . . . . . . . . . 414
Using Parallel Arrays . . . . . . . . . . . . . . . . . . . 415
Searching an Array for a Range Match . . . . . . . . . . . 418
Passing Arrays to and Returning Arrays from Methods . . . . . 422
Returning an Array from a Method . . . . . . . . . . . . . 426
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 428
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 428
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 429
Review Questions . . . . . . . . . . . . . . . . . . . . . 430
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 433
Programming Exercises . . . . . . . . . . . . . . . . . 433
Debugging Exercises . . . . . . . . . . . . . . . . . . 435
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 435
Case Problems . . . . . . . . . . . . . . . . . . . . . 438
CHAPT ER 9 Advanced Array Concepts . . . . . . . . . 439
Sorting Array Elements Using the Bubble Sort Algorithm . . . . 440
Using the Bubble Sort Algorithm . . . . . . . . . . . . . . 440
Improving Bubble Sort Efficiency . . . . . . . . . . . . . 442
Sorting Arrays of Objects . . . . . . . . . . . . . . . . . 443
Sorting Array Elements Using the Insertion Sort Algorithm . . . . 448
Using Two-Dimensional and Other Multidimensional Arrays . . . . 452
Passing a Two-Dimensional Array to a Method . . . . . . . . 454
Using the length Field with a Two-Dimensional Array . . . . 455
Understanding Ragged Arrays . . . . . . . . . . . . . . . 456
Using Other Multidimensional Arrays . . . . . . . . . . . . 456
Using the Arrays Class . . . . . . . . . . . . . . . . . . 459
Using the ArrayList Class . . . . . . . . . . . . . . . . 467
Creating Enumerations . . . . . . . . . . . . . . . . . . . 472
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 479
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 479
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 480
Review Questions . . . . . . . . . . . . . . . . . . . . . 481
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 484
Programming Exercises . . . . . . . . . . . . . . . . . 484
Debugging Exercises . . . . . . . . . . . . . . . . . . 486
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 487
Case Problems . . . . . . . . . . . . . . . . . . . . . 490

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


Learning About the Concept of Inheritance . . . . . . . . . . 492
Diagramming Inheritance Using the UML . . . . . . . . . . 492
Inheritance Terminology . . . . . . . . . . . . . . . . . 495
Extending Classes . . . . . . . . . . . . . . . . . . . . . 496
Overriding Superclass Methods . . . . . . . . . . . . . . . 502
Using the @Override Tag . . . . . . . . . . . . . . . . 504
Calling Constructors During Inheritance . . . . . . . . . . . . 507
Using Superclass Constructors that
Require Arguments . . . . . . . . . . . . . . . . . . 508
Accessing Superclass Methods . . . . . . . . . . . . . . . 513
Comparing this and super . . . . . . . . . . . . . . . 515
Employing Information Hiding . . . . . . . . . . . . . . . . 516
Methods You Cannot Override . . . . . . . . . . . . . . . . 518
A Subclass Cannot Override static Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 518
A Subclass Cannot Override final Methods in
Its Superclass . . . . . . . . . . . . . . . . . . . . 522
A Subclass Cannot Override Methods
in a final Superclass . . . . . . . . . . . . . . . . 523
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 525
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 525
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 526
Review Questions . . . . . . . . . . . . . . . . . . . . . 527
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 530
Programming Exercises . . . . . . . . . . . . . . . . . 530
Debugging Exercises . . . . . . . . . . . . . . . . . . 533
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 534
Case Problems . . . . . . . . . . . . . . . . . . . . . 535

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


Creating and Using Abstract Classes . . . . . . . . . . . . . 538
Using Dynamic Method Binding . . . . . . . . . . . . . . . 547
Using a Superclass as a Method Parameter Type . . . . . . 549
Creating Arrays of Subclass Objects . . . . . . . . . . . . . 551
Using the Object Class and Its Methods . . . . . . . . . . . 554
Using the toString() Method . . . . . . . . . . . . . 556
Using the equals() Method . . . . . . . . . . . . . . . 559
Using Inheritance to Achieve Good Software Design . . . . . . 564
Creating and Using Interfaces . . . . . . . . . . . . . . . . 565
Creating Interfaces to Store Related Constants . . . . . . . 570
Creating and Using Packages . . . . . . . . . . . . . . . . 574
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 580
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 580
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 581
Review Questions . . . . . . . . . . . . . . . . . . . . . 582
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 585
Programming Exercises . . . . . . . . . . . . . . . . . 585
Debugging Exercises . . . . . . . . . . . . . . . . . . 589
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 590
Case Problems . . . . . . . . . . . . . . . . . . . . . 590
CHAPT ER 12 Exception Handling . . . . . . . . . . . . 593
Learning About Exceptions . . . . . . . . . . . . . . . . . 594
Trying Code and Catching Exceptions . . . . . . . . . . . . 599
Using a try Block to Make Programs “Foolproof” . . . . . . 604
Declaring and Initializing Variables in try…catch Blocks . . . 606
Throwing and Catching Multiple Exceptions . . . . . . . . . . 609
Using the finally Block . . . . . . . . . . . . . . . . . 615
Understanding the Advantages of Exception Handling . . . . . . 618
Specifying the Exceptions that a Method Can Throw . . . . . . 621
Tracing Exceptions Through the Call Stack . . . . . . . . . . 626
Creating Your Own Exception Classes . . . . . . . . . . . 630
Using Assertions . . . . . . . . . . . . . . . . . . . . . 634
Displaying the Virtual Keyboard . . . . . . . . . . . . . . . 650
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 653
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 654
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 655
Review Questions . . . . . . . . . . . . . . . . . . . . . 656
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 659
Programming Exercises . . . . . . . . . . . . . . . . . 659
Debugging Exercises . . . . . . . . . . . . . . . . . . 662
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 662
Case Problems . . . . . . . . . . . . . . . . . . . . . 663

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


Understanding Computer Files . . . . . . . . . . . . . . . 666
Using the Path and Files Classes . . . . . . . . . . . . . 667
Creating a Path . . . . . . . . . . . . . . . . . . . . . 668
Retrieving Information About a Path . . . . . . . . . . . . 669
Converting a Relative Path to an Absolute One . . . . . . . . 670
Checking File Accessibility . . . . . . . . . . . . . . . . 671
Deleting a Path . . . . . . . . . . . . . . . . . . . . . 673
Determining File Attributes . . . . . . . . . . . . . . . . 674
File Organization, Streams, and Buffers . . . . . . . . . . . . 678
Using Java’s IO Classes . . . . . . . . . . . . . . . . . . 680
Writing to a File . . . . . . . . . . . . . . . . . . . . . 683
Reading from a File . . . . . . . . . . . . . . . . . . . 685
Creating and Using Sequential Data Files . . . . . . . . . . . 687
Learning About Random Access Files . . . . . . . . . . . . 693
Writing Records to a Random Access Data File . . . . . . . . 697
Reading Records from a Random Access Data File . . . . . . . 704
Accessing a Random Access File Sequentially . . . . . . . . 704
Accessing a Random Access File Randomly . . . . . . . . . 705
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 719
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 719
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 720
Review Questions . . . . . . . . . . . . . . . . . . . . . 721
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 724
Programming Exercises . . . . . . . . . . . . . . . . . 724
Debugging Exercises . . . . . . . . . . . . . . . . . . 726
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 727
Case Problems . . . . . . . . . . . . . . . . . . . . . 727

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


Understanding Swing Components . . . . . . . . . . . . . 730
Using the JFrame Class . . . . . . . . . . . . . . . . . . 731
Customizing a JFrame’s Appearance . . . . . . . . . . . 734
Using the JLabel Class . . . . . . . . . . . . . . . . . . 738
Changing a JLabel’s Font . . . . . . . . . . . . . . . . 740
Using a Layout Manager . . . . . . . . . . . . . . . . . . 743
Extending the JFrame Class . . . . . . . . . . . . . . . . 746
Adding JTextFields, JButtons, and Tool Tips to a
JFrame . . . . . . . . . . . . . . . . . . . . . . . . 748
Adding JTextFields . . . . . . . . . . . . . . . . . . 748
Adding JButtons . . . . . . . . . . . . . . . . . . . 750
Using Tool Tips . . . . . . . . . . . . . . . . . . . . . 752
Learning About Event-Driven Programming . . . . . . . . . . 755
Preparing Your Class to Accept Event Messages . . . . . . . 756
Telling Your Class to Expect Events to Happen . . . . . . . 757
Telling Your Class How to Respond to Events . . . . . . . . 757
An Event-Driven Program . . . . . . . . . . . . . . . . . 757
Using Multiple Event Sources . . . . . . . . . . . . . . . 759
Using the setEnabled() Method . . . . . . . . . . . . 761
Understanding Swing Event Listeners . . . . . . . . . . . . 764
Using the JCheckBox, ButtonGroup, and JComboBox
Classes . . . . . . . . . . . . . . . . . . . . . . . . 767
The JCheckBox Class . . . . . . . . . . . . . . . . . 767
The ButtonGroup Class . . . . . . . . . . . . . . . . 771
The JComboBox Class . . . . . . . . . . . . . . . . . 772
Don’t Do It . . . . . . . . . . . . . . . . . . . . . . . . 780
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 780
Chapter Summary . . . . . . . . . . . . . . . . . . . . . 781
Review Questions . . . . . . . . . . . . . . . . . . . . . 783
Exercises . . . . . . . . . . . . . . . . . . . . . . . . 785
Programming Exercises . . . . . . . . . . . . . . . . . 785
Debugging Exercises . . . . . . . . . . . . . . . . . . 787
Game Zone . . . . . . . . . . . . . . . . . . . . . . . 787
Case Problems . . . . . . . . . . . . . . . . . . . . . 788

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


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

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


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

APPENDIX A Working with the Java Platform . . . . . . . 919


Learning about the Java SE Development Kit . . . . . . . . . 920
Configuring Windows to Use the JDK . . . . . . . . . . . . . 920
Finding the Command Prompt . . . . . . . . . . . . . . . 921
Command Prompt Anatomy . . . . . . . . . . . . . . . . 921
Changing Directories . . . . . . . . . . . . . . . . . . 921
Setting the class and classpath Variables . . . . . . . 922
Changing a File’s Name . . . . . . . . . . . . . . . . . 922
Compiling and Executing a Java Program . . . . . . . . . . . 923
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 923

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


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

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


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

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


Understanding Computer-Generated Random Numbers . . . . . 942
Using the Math.random() Method . . . . . . . . . . . . . 943
Using the Random Class . . . . . . . . . . . . . . . . . . 944
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 947
APPENDIX E Javadoc . . . . . . . . . . . . . . . . . 949
The Javadoc Documentation Generator . . . . . . . . . . . . 950
Javadoc Comment Types . . . . . . . . . . . . . . . . . . 950
Generating Javadoc Documentation . . . . . . . . . . . . . 952
Specifying Visibility of Javadoc Documentation . . . . . . . . 955
Key Terms . . . . . . . . . . . . . . . . . . . . . . . . 956

Glossary . . . . . . . . . . . . . . . . . 957
Index . . . . . . . . . . . . . . . . . . . 979
Preface
Java Programming, Eighth Edition, provides the beginning programmer with a guide to
developing applications using the Java programming language. Java is popular among
professional programmers because it can be used to build visually interesting graphical user
interface (GUI) and Web-based applications. Java also provides an excellent environment for
the beginning programmer—a student can quickly build useful programs while learning the
basics of structured and object-oriented programming techniques.
This textbook assumes that you have little or no programming experience. It provides a solid
background in good object-oriented programming techniques and introduces terminology
using clear, familiar language. The programming examples are business examples; they do not
assume a mathematical background beyond high-school business math. In addition, the
examples illustrate only one or two major points; they do not contain so many features that
you become lost following irrelevant and extraneous details. Complete, working programs
appear frequently in each chapter; these examples help students make the transition from the
theoretical to the practical. The code presented in each chapter can also be downloaded from
the publisher’s Web site, so students can easily run the programs and experiment with
changes to them.
The student using Java Programming, Eighth Edition, builds applications from the bottom up
rather than starting with existing objects. This facilitates a deeper understanding of the
concepts used in object-oriented programming and engenders appreciation for the existing
objects students use as their knowledge of the language advances. When students complete
this book, they will know how to modify and create simple Java programs, and they will have
the tools to create more complex examples. They also will have a fundamental knowledge of
object-oriented programming, which will serve them well in advanced Java courses or in
studying other object-oriented languages such as C++, C#, and Visual Basic.

Organization and Coverage


Java Programming, Eighth Edition, presents Java programming concepts, enforcing good
style, logical thinking, and the object-oriented paradigm. Objects are covered right from the
beginning, earlier than in many other textbooks. You create your first Java program in
Chapter 1. Chapters 2, 3, and 4 increase your understanding of how data, classes, objects,
and methods interact in an object-oriented environment.
Chapters 5 and 6 explore input and repetition structures, which are the backbone of
programming logic and essential to creating useful programs in any language. You learn the
special considerations of string and array manipulation in Chapters 7, 8, and 9.
Chapters 10, 11, and 12 thoroughly cover inheritance and exception handling. Inheritance is
the object-oriented concept that allows you to develop new objects quickly by adapting the
features of existing objects; exception handling is the object-oriented approach to handling
errors. Both are important concepts in object-oriented design. Chapter 13 provides
information on handling files so you can permanently store and retrieve program output.
Chapters 14, 15, and 16 introduce GUI Swing components (Java’s visually pleasing,
user-friendly widgets), their layout managers, and graphics.

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

MODERNIZED OVERRIDING: The @Override tag is introduced.


EXPANDED COVERAGE OF THE EQUALS() METHOD: The book provides a thorough
explanation of the difference between overloading and overriding the equals() method.
PROGRAMMING EXERCISES: Each chapter contains several new programming exercises
not seen in previous editions. All exercises and their solutions from the previous edition
that were replaced in this edition are still available in the Instructor’s Resource Kit.
Additionally, Java Programming, Eighth Edition, includes the following features:
OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that will
be presented in the chapter. In addition to providing a quick reference to topics covered,
this feature provides a useful study aid.
YOU DO IT: In each chapter, step-by-step exercises help students create multiple working
programs that emphasize the logic a programmer uses in choosing statements to include.
These sections provide a means for students to achieve success on their own—even those
in online or distance learning classes.
NOTES: These highlighted tips provide additional information—for example, an
alternative method of performing a procedure, another term for a concept, background
information on a technique, or a common error to avoid.
EMPHASIS ON STUDENT RESEARCH: The student frequently is directed to the Java Web
site to investigate classes and methods. Computer languages evolve, and programming
professionals must understand how to find the latest language improvements. This book
encourages independent research.
FIGURES: Each chapter contains many figures. Code figures are most frequently 25 lines
or fewer, illustrating one concept at a time. Frequent screen shots show exactly how
program output appears. Callouts appear where needed to emphasize a point.
COLOR: The code figures in each chapter contain all Java keywords in blue. This helps
students identify keywords more easily, distinguishing them from programmer-selected
names.
FILES: More than 200 student files can be downloaded from the publisher’s Web site. Most
files contain the code presented in the figures in each chapter; students can run the code for
themselves, view the output, and make changes to the code to observe the effects. Other
files include debugging exercises that help students improve their programming skills.
TWO TRUTHS & A LIE: A short quiz reviews each chapter section, with answers provided.
This quiz contains three statements based on the preceding section of text—two
statements are true and one is false. Over the years, students have requested answers to
problems, but we have hesitated to distribute them in case instructors want to use
problems as assignments or test questions. These true–false quizzes provide students with
immediate feedback as they read, without “giving away” answers to the multiple-choice
questions and programming exercises.
DON’T DO IT: This section at the end of each chapter summarizes common mistakes and
pitfalls that plague new programmers while learning the current topic.
KEY TERMS: Each chapter includes a list of newly introduced vocabulary, shown in the
order of appearance in the text. The list of key terms provides a short review of the major
concepts in the chapter.
SUMMARIES: Following each chapter is a summary that recaps the programming
concepts and techniques covered in the chapter. This feature provides a concise means for
students to check their understanding of the main points in each chapter.
REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve as a
review of chapter topics.
GAME ZONE: Each chapter provides one or more exercises in which students can create
interactive games using the programming techniques learned up to that point; 70 game
programs are suggested in the book. The games are fun to create and play; writing them
motivates students to master the necessary programming techniques. Students might
exchange completed game programs with each other, suggesting improvements and
discovering alternate ways to accomplish tasks.
CASES: Each chapter contains two running case problems. These cases represent projects
that continue to grow throughout a semester using concepts learned in each new chapter.
Two cases allow instructors to assign different cases in alternate semesters or to divide
students in a class into two case teams.
GLOSSARY: This edition contains an alphabetized list of all key terms identified in the
book, along with their definitions.
APPENDICES: This edition includes useful appendices on working with the Java platform,
data representation, formatting output, generating random numbers, and creating Javadoc
comments.
QUALITY: Every program example, exercise, and game solution was tested by the author
and then tested again by a quality assurance team using Java Standard Edition (SE) 8, the
most recent version available.

CourseMate
The more you study, the better the results. Make the most of your study time by accessing
everything you need to succeed in one place. Read your textbook, take notes, review
flashcards, watch videos, and take practice quizzes online. CourseMate goes beyond the book
to deliver what you need! Learn more at www.cengage.com/coursemate.
The Java Programming CourseMate includes:
Debugging Exercises: Four error-filled programs accompany each chapter. By
debugging these programs, students can gain expertise in program logic in general and
the Java programming language in particular.
Video Lessons: Each chapter is accompanied by at least three video lessons that help to
explain important chapter concepts. These videos were created and narrated by the
author.
Interactive Study Aids: An interactive eBook, quizzes, flashcards, and more!
Instructors may add CourseMate to the textbook package, or students may purchase
CourseMate directly at www.CengageBrain.com.

Instructor Resources
The following teaching tools are available for download at our Instructor Companion Site.
Simply search for this text at sso.cengage.com. An instructor login is required.
Electronic Instructor’s Manual: The Instructor’s Manual that accompanies this
textbook contains additional instructional material to assist in class preparation,
including items such as Overviews, Chapter Objectives, Teaching Tips, Quick
Quizzes, Class Discussion Topics, Additional Projects, Additional Resources, and Key
Terms. A sample syllabus is also available. Additional exercises in the Instructor’s
Manual include:
Tough Questions: Two or more fairly difficult questions that an applicant
might encounter in a technical job interview accompany each chapter. These
questions are often open-ended; some involve coding and others might involve
research.
Up for Discussion: A few thought-provoking questions concerning programming in
general or Java in particular supplement each chapter. The questions can be used to
start classroom or online discussions, or to develop and encourage research, writing,
and language skills.
Programming Exercises and Solutions: Each chapter is accompanied by several
programming exercises to supplement those offered in the text. Instructors can use
these exercises as additional or alternate assignments, or as the basis for lectures.
Test Bank: Cengage Learning Testing Powered by Cognero is a flexible, online system
that allows you to:
Author, edit, and manage test bank content from multiple Cengage Learning
solutions.
Create multiple test versions in an instant.
Deliver tests from your LMS, your classroom, or anywhere you want.
PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides may be used to guide classroom presentations, to make available to
students for chapter review, or to print as classroom handouts. Files are provided for every
figure in the text. Instructors may use the files to customize PowerPoint slides, illustrate
quizzes, or create handouts.
Solutions: Solutions to “You Do It” exercises and all end-of-chapter exercises are
available. Annotated solutions are provided for some of the multiple-choice Review
Questions. For example, if students are likely to debate answer choices or not understand
the choice deemed to be the correct one, a rationale is provided.

Acknowledgments
I would like to thank all of the people who helped to make this book a reality, including Dan
Seiter, Development Editor; Alyssa Pratt, Senior Content Developer; Carmel Isaac, Content
Project Manager; and Chris Scriver and Danielle Shaw, quality assurance testers. I am lucky to
work with these professionals who are dedicated to producing high-quality instructional
materials.
I am also grateful to the reviewers who provided comments and encouragement during this
book’s development, including Bernice Cunningham, Wayne County Community College
District; Bev Eckel, Iowa Western Community College; John Russo, Wentworth Institute of
Technology; Leslie Spivey, Edison Community College; and Angeline Surber, Mesa
Community College.
Thanks, too, to my husband, Geoff, for his constant support and encouragement. Finally, this
book is dedicated to the newest Farrell, coming March 2015. As this book goes to production,
I don’t know your name or even your gender, but I do know that I love you.
Joyce Farrell
Read This Before
You Begin
The following information will help you as you prepare to use this textbook.

To the User of the Data Files


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

Using Your Own Computer


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

In this chapter, you will:

Define basic programming terminology


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

Learning Programming Terminology


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

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


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

After the program statements are written, high-level language programmers use a computer
program called a compiler or interpreter to translate their language statements into machine
language. A compiler translates an entire program before carrying out any statements, or
executing them, whereas an interpreter translates one program statement at a time,
executing a statement as soon as it is translated.
3
Whether you use a compiler or interpreter often depends on the programming language you use. For
example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of translator
has its supporters; programs written in compiled languages execute more quickly, whereas programs
written in interpreted languages can be easier to develop and debug. Java uses the best of both technolo-
gies: a compiler to translate your programming statements and an interpreter to read the compiled code line
by line when the program executes (also called at run time).

Compilers and interpreters issue one or more error messages each time they encounter an
invalid program statement—that is, a statement containing a syntax error, or misuse of the
language. Examples of syntax errors include misspelling a keyword or omitting a word that a
statement requires. When a syntax error is detected, the programmer can correct the error
and attempt another translation. Repairing all syntax errors is the first part of the process
of debugging a program—freeing the program of all flaws or errors, also known as bugs.
Figure 1-1 illustrates the steps a programmer takes while developing an executable program.
You will learn more about debugging Java programs later in this chapter.
CHAPTER 1 Creating Java Programs

Plan program logic

4
Write program language statements
that correspond to the logic

Debugging process
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language

Debugging process
Can all statements No Examine list of
be successfully
syntax errors
translated?

Yes

Execute the program

Examine
program output

Are there runtime Yes


or output errors?

No

Figure 1-1 The program development process

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

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

Programmers call some logic errors semantic errors. For example, if you misspell a programming
language word, you commit a syntax error, but if you use a correct word in the wrong context, you commit a
semantic error.

TWO TRUTHS & A LIE


Learning Programming Terminology

In each “Two Truths & a Lie” section, two of the numbered statements are true, and one
is false. Identify the false statement and explain why it is false.

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


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

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


The false statement is #3. A language translator finds syntax errors, but logic errors
CHAPTER 1 Creating Java Programs

Comparing Procedural and Object-Oriented


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

Procedural Programming
Procedural programming is a style of programming in which operations are executed one
after another in sequence. In procedural applications, you create names for computer
memory locations that can hold values—for example, numbers and text—in electronic
form. The named computer memory locations are called variables because they hold values
that might vary. For example, a payroll program might contain a variable named rateOfPay.
The memory location referenced by the name rateOfPay might contain different values
(a different value for every employee of the company) at different times. During the execution
of the payroll program, each value stored under the name rateOfPay might have many
operations performed on it—for example, the value might be read from an input device,
be multiplied by another variable representing hours worked, and be printed on paper.
For convenience, the individual operations used in a computer program are often grouped
into logical units called procedures. For example, a series of four or five comparisons and
calculations that together determine a person’s federal withholding tax value might be
grouped as a procedure named calculateFederalWithholding. A procedural program
defines the variable memory locations and then calls a series of procedures to input,
manipulate, and output the values stored in those locations. When a program calls a
procedure, the current logic is temporarily abandoned so that the procedure’s commands can
execute. A single procedural program often contains hundreds of variables and procedure
calls. Procedures are also called modules, methods, functions, and subroutines. Users of
different programming languages tend to use different terms. As you will learn later in this
chapter, Java programmers most frequently use the term method.

Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you take
a slightly different approach to writing computer programs. Writing object-oriented
programs involves:

Creating classes, which are blueprints for objects


Creating objects, which are specific instances of those classes
Creating applications that manipulate or use those objects

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


programming is abbreviated OOP, and pronounced to rhyme with soup.
Comparing Procedural and Object-Oriented Programming Concepts

Originally, object-oriented programming was used most frequently for two major types of
applications:
Computer simulations, which attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world
processes operate
7
Graphical user interfaces, or GUIs (pronounced “gooeys”), which allow users to interact
with a program in a graphical environment
Thinking about objects in these two types of applications makes sense. For example, a city
might want to develop a program that simulates traffic patterns to help prevent traffic tie-ups.
Programmers would create classes for objects such as cars and pedestrians that contain their
own data and rules for behavior. For example, each car has a speed and a method for changing
that speed. The specific instances of cars could be set in motion to create a simulation of a real
city at rush hour.
Creating a GUI environment for users is also a natural use for object orientation. It is easy to
think of the components a user manipulates on a computer screen, such as buttons and scroll
bars, as similar to real-world objects. Each GUI object contains data—for example, a button
on a screen has a specific size and color. Each object also contains behaviors—for example,
each button can be clicked and reacts in a specific way when clicked. Some people consider
the term object-oriented programming to be synonymous with GUI programming, but object-
oriented programming means more. Although many GUI programs are object oriented, not
all object-oriented programs use GUI objects. Modern businesses use object-oriented design
techniques when developing all sorts of business applications, whether they are GUI
applications or not. In the first 13 chapters of this book, you will learn object-oriented
techniques that are appropriate for any program type; in the last chapters, you will apply what
you have learned about those techniques specifically to GUI applications.
Understanding object-oriented programming requires grasping three basic concepts:
Encapsulation as it applies to classes as objects
Inheritance
Polymorphism

Understanding Classes, Objects, and Encapsulation


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

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


instantiation. You can create objects from classes that you write and from classes written by
other programmers, including Java’s creators. The values contained in an object’s properties
often differentiate instances of the same class from one another. For example, the class
Automobile describes what Automobile objects are like. Some properties of the Automobile
8 class are make, model, year, and color. Each Automobile object possesses the same attributes,
but not necessarily the same values for those attributes. One Automobile might be a 2010
white Ford Taurus and another might be a 2015 red Chevrolet Camaro. Similarly, your dog
has the properties of all Dogs, including a breed, name, age, and whether its shots are current.
The values of the properties of an object are referred to as the object’s state. In other words,
you can think of objects as roughly equivalent to nouns, and of their attributes as similar to
adjectives that describe the nouns.
When you understand an object’s class, you understand the characteristics of the object. If
your friend purchases an Automobile, you know it has a model name, and if your friend gets a
Dog, you know the dog has a breed. Knowing what attributes exist for classes allows you to ask
appropriate questions about the states or values of those attributes. For example, you might
ask how many miles the car gets per gallon, but you would not ask whether the car has had
shots. Similarly, in a GUI operating environment, you expect each component to have
specific, consistent attributes and methods, such as a window having a title bar and a close
button, because each component gains these properties as a member of the general class of
GUI components. Figure 1-2 shows the relationship of some Dog objects to the Dog class.
By convention, programmers using Java begin their class names with an uppercase letter. Thus, the class
that defines the attributes and methods of an automobile would probably be named Automobile, and the
class for dogs would probably be named Dog. However, following this convention is not required to produce
a workable program.

Dog class definition Dog class instances (objects)

Every Dog that is


created will have
a:

Name

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

Figure 1-2 Dog class definition and some objects created from it
Comparing Procedural and Object-Oriented Programming Concepts

Besides defining properties, classes define methods their objects can use. A method is a
self-contained block of program code that carries out some action, similar to a procedure in a
procedural program. An Automobile, for example, might have methods for moving forward,
moving backward, and determining the status of its gas tank. Similarly, a Dog might have
methods for walking, eating, and determining its name, and a program’s GUI components
might have methods for maximizing and minimizing them as well as determining their size. 9
In other words, if objects are similar to nouns, then methods are similar to verbs.
In object-oriented classes, attributes and methods are encapsulated into objects.
Encapsulation refers to two closely related object-oriented notions:

Encapsulation is the enclosure of data and methods within an object. Encapsulation allows
you to treat all of an object’s methods and data as a single entity. Just as an actual dog
contains all of its attributes and abilities, so would a program’s Dog object.
Encapsulation also refers to the concealment of an object’s data and methods from outside
sources. Concealing data is sometimes called information hiding, and concealing how
methods work is implementation hiding; you will learn more about both terms in the
chapter “Using Methods, Classes, and Objects.” Encapsulation lets you hide specific object
attributes and methods from outside sources and provides the security that keeps data and
methods safe from inadvertent changes.
If an object’s methods are well written, the user can be unaware of the low-level details of how
the methods are executed, and the user must simply understand the interface or interaction
between the method and the object. For example, if you can fill your Automobile with
gasoline, it is because you understand the interface between the gas pump nozzle and the
vehicle’s gas tank opening. You don’t need to understand how the pump works mechanically
or where the gas tank is located inside your vehicle. If you can read your speedometer, it does
not matter how the displayed figure is calculated. As a matter of fact, if someone produces a
superior, more accurate speed-determining device and inserts it in your Automobile, you
don’t have to know or care how it operates, as long as your interface remains the same.
The same principles apply to well-constructed classes used in object-oriented programs—
programs that use classes only need to work with interfaces.

Understanding Inheritance and Polymorphism


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

Inheritance helps you understand real-world objects. For example, the first time you
encounter a convertible, you already understand how the ignition, brakes, door locks, and
CHAPTER 1 Creating Java Programs

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

Watch the video Object-Oriented Programming.

TWO TRUTHS & A LIE


Comparing Procedural and Object-Oriented
Programming Concepts

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


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

polymorphism describes the ability to use one term to cause multiple actions.
the attributes and methods of existing classes, but with more specific features;
The false statement is #3. Inheritance is the ability to create classes that share
Features of the Java Programming Language

Features of the Java Programming Language


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

Java Source Code

Source code is
stored on a disk in
12 a file with a name
ending in .java

Java Compiler

Compiler creates
bytecode that
is stored on a
disk in a file with
a name ending in
Java Virtual Machine .class

Java Interpreter

JVM (named java.exe)


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

Figure 1-3 The Java environment

Java Program Types


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

TWO TRUTHS & A LIE


Features of the Java Programming Language

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

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

Analyzing a Java Application that Produces


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

public class First


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

Figure 1-4 The First class

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

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

Understanding the Statement that Produces the Output


Although the program in Figure 1-4 occupies several lines, it contains only one Java
programming statement. The statement System.out.println("First Java
application"); does the actual work in this program. Like all Java statements, this one
14 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 before or after the
opening parenthesis, or before or after the closing parenthesis. However, you usually
want to place a short statement on a single line.
The text “First Java application” is a literal string of characters—a series of characters that
will appear in output exactly as entered. Any literal string in Java is written between
double quotation marks. In Java, a literal string cannot be broken and placed on multiple
lines. Figure 1-5 labels this string and the other parts of the statement.

"First Java application"


out is a property of the is a literal string that is the argument
System is a class. System class. to the println() method.

System.out.println("First Java application");

Dots separate classes, println() is a method. Every Java statement ends


objects, and methods. Method names are always with a semicolon.
followed by parentheses.

Figure 1-5 Anatomy of a Java statement

The string “First Java application” appears within parentheses because the string is an
argument to a method, and arguments to methods always appear within parentheses.
Arguments are pieces of information that are sent into a method. The act of sending
arguments to a method is called passing arguments to the method. As an analogy, consider
placing a catalog order with a company that sells sporting goods. Processing a catalog order is
a method that consists of a set of standard procedures—recording the order, checking the
availability of the item, pulling the item from the warehouse, and so on. Each catalog order
also requires a set of data items, such as which item number you are ordering and the
quantity of the item desired; these data items can be considered the arguments to the
order-processing method. If you order two of item 5432 from a catalog, you expect different
results than if you order 1,000 of item 9008. Likewise, if you pass the argument “Happy
Holidays” to a Java display method, you expect different results than if you pass the argument
“First Java application”.
Analyzing a Java Application that Produces Console Output

Within the statement System.out.println("First Java application");, the method to


which you are passing "First Java application" is named println(). The Java methods
println() and print() both produce output. With println(), after the output is displayed,
the insertion point moves to the following line so that subsequent output appears on a
new line. With print(), however, the insertion point does not advance to a new line, so
subsequent output appears at the end of the current line. 15

When you call a method, you always use parentheses following the method name. In this
book, you will learn about many methods that require arguments between their parentheses,
and many others for which you leave the parentheses empty. The println() method can be
used with no arguments when you want to output a blank line. Later in this chapter, you will
learn about a method named showMessageDialog() that requires two arguments. Other
methods require more.
Within the statement System.out.println("First Java application");, out is an object
that is a property of the System class that refers to the standard output device for a system,
normally the monitor. The out object itself is an instance of the PrintStream class, which
contains several methods, including println(). Technically, you could create the out object
and write the instructions within the println()method yourself, but it would be time
consuming, and the creators of Java assumed you frequently would want to display output on
a screen. Therefore, the System and PrintStream classes, the out object, and the println()
method were created as a convenience to the programmer.
Within the statement System.out.println("First Java application");, System is a class.
Therefore, System defines attributes for System objects, just as the Dog class defines the
attributes for Dog objects. One of the System attributes is out. (You can probably guess that
another attribute is in and that it represents an input device.)
The dots (periods) in System.out.println() are used to separate the names of the
components in the statement. You will use this format repeatedly in your Java programs.
Java is case sensitive; the class named System is a completely different class from one named
system, SYSTEM, or even sYsTeM, and out is a different object from one named Out or OUT. You
must pay close attention to using correct uppercase and lowercase values when you write Java
programs.
So, the statement that displays the string “First Java application” contains a class, an object
reference, a method call, a method argument, and a statement-ending semicolon, but the
statement cannot stand alone; it is embedded within a class, as shown in Figure 1-4.

Understanding the First Class


Everything that you use within a Java program must be part of a class. When you write
public class First, you are defining a class named First. You can define a Java class using
any name or identifier you need, as long as it meets the following requirements:
A Java identifier must begin with a letter of the English alphabet, a non-English letter
(such as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
A Java identifier can contain only letters, digits, underscores, or dollar signs.
CHAPTER 1 Creating Java Programs

A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1
for a list of reserved keywords.)
A Java identifier cannot be one of the following values: true, false, or null. These are not
keywords (they are primitive values), but they are reserved and cannot be used.

16 Java is based on Unicode, which is an international system of character representation. The term letter
indicates English-language letters as well as characters from Arabic, Greek, and other alphabets. You can
learn more about Unicode in Appendix B.

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Table 1-1 Java reserved keywords

Although const and goto are reserved as keywords, they are not used in Java programs, and they have no
function. Both words are used in other languages and were reserved in case developers of future versions of
Java wanted to implement them.

It is a Java standard, although not a requirement, to begin class identifiers with an uppercase
letter and employ other uppercase letters as needed to improve readability. (By contrast,
method identifiers, like println(), conventionally begin with a lowercase letter.) The style
that joins words in which each word begins with an uppercase letter is called Pascal casing,
or sometimes upper camel casing. You should follow established conventions for Java so
your programs will be easy for other programmers to interpret and follow. This book uses
established Java programming conventions.
Table 1-2 lists some valid and conventional class names that you could use when writing
programs in Java. Table 1-3 provides some examples of class names that could be used in Java
(if you use these class names, the class will compile) but that are unconventional and not
recommended. Table 1-4 provides some class name examples that are illegal.
Analyzing a Java Application that Produces Console Output

Class Name Description


Employee Begins with an uppercase letter
UnderGradStudent Begins with an uppercase letter, contains no spaces, and emphasizes each
new word with an initial uppercase letter
17
InventoryItem Begins with an uppercase letter, contains no spaces, and emphasizes the
second word with an initial uppercase letter
Budget2016 Begins with an uppercase letter and contains no spaces

Table 1-2 Some valid class names in Java

Class Name Description


Undergradstudent New words are not indicated with initial uppercase letters, making this
identifier difficult to read
Inventory_Item Underscore is not commonly used to indicate new words
BUDGET2016 Using all uppercase letters for class identifiers is not conventional
budget2016 Conventionally, class names do not begin with a lowercase letter

Table 1-3 Legal but unconventional and nonrecommended class names in Java

Class Name Description


Inventory Item Space character is illegal in an identifier
class class is a reserved word

2016Budget Class names cannot begin with a digit


phone# The number symbol ( # ) is illegal in an identifier

Table 1-4 Some illegal class names in Java

In Figure 1-4 (and again in Figure 1-6), the line public class First is the class header; it
contains the keyword class, which identifies First as a class. The reserved word public is an
access specifier. An access specifier defines the circumstances under which a class can be
accessed and the other classes that have the right to use a class. Public access is the most
liberal type of access; you will learn about public access and other types of access in the
chapter “Using Methods, Classes, and Objects.”
CHAPTER 1 Creating Java Programs

The keyword class


public is an access identifies First as First is the name of
specifier. a class. the class.

18 This line is
public class First
the class
header. {
public static void main(String[] args)
Everything {
between the System.out.println("First Java application");
curly braces is }
the class body. }

Figure 1-6 The parts of a typical class

After the class header, you enclose the contents of a class within curly braces ({ and }); any data
items and methods between the curly braces make up the class body. A class body can be
composed of any number of data items and methods. In Figure 1-4 (and again in Figure 1-6),
the class First contains only one method within its curly braces. The name of the method is
main(), and the main() method, like the println() method, includes its own set of
parentheses. The main() method in the First class contains only one statement—the
statement that uses the println() method. The main() method does not contain any other
methods, but it calls the println() method.

Indent Style
In general, whitespace is optional in Java. Whitespace is any combination of nonprinting
characters. You use whitespace to organize your program code and make it easier to read.
You can insert whitespace between words or lines in your program code by typing spaces,
tabs, or blank lines because the compiler ignores these extra spaces. However, you cannot use
whitespace within an identifier or keyword, or surrounding the dots in any class-object-
method combination.
For every opening curly brace ({) in a Java program, there must be a corresponding closing
curly brace (}), but the placement of the opening and closing curly braces is not important to
the compiler. For example, the following class executes in exactly the same way as the one
shown in Figure 1-4. The only difference is the layout of the braces—the line breaks occur in
different locations.
public class First{
public static void main(String[] args){
System.out.println("First Java application");
}
}

The indent style shown in the preceding example, in which opening braces do not stand alone
on separate lines, is known as the K & R style and is named for Kernighan and Ritchie, who
wrote the first book on the C programming language. The indent style shown in Figure 1-4
Analyzing a Java Application that Produces Console Output

and used throughout this book, in which curly braces are aligned and each occupies its own
line, is called the Allman style and is named for Eric Allman, a programmer who popularized
the style. Java programmers use a variety of indent styles, and all can produce workable Java
programs. When you write your own code, you should develop a consistent style. In school,
your instructor might have a preferred style, and when you get a job as a Java programmer,
your organization most likely will have a preferred style. With many development 19
environments, indentations are made for you automatically as you type.
Most programmers indent a method’s statements a few spaces more than its curly braces.
Some programmers indent two spaces, some three, and some four. Some programmers use
the Tab key to create indentations, but others are opposed to this practice because the Tab
key can indicate different indentation sizes on different systems. Some programmers don’t
care whether tabs or spaces are used, as long as you don’t mix them in the same program. The
Java compiler does not care how you indent. Again, the most important rule is to develop a
consistent style of which your organization approves.

Understanding the main() Method


The method header for the main() method is quite complex. Figure 1-7 shows the parts of
the main() method.

static means this method works without


instantiating an object of the class.

public is an access specifier. void is the method’s return type.

public class First


{
This line is the public static void main(String[] args)
method header.
{
System.out.println("First Java application");
Everything between
}
the curly braces is the
method body.
}

String is a class. Any The square brackets mean the args is the identifier of the array of
arguments to this method argument to this method is an Strings that is the argument to
must be String objects. array of Strings. Chapters 8 this method.
and 9 provide more information
about Strings and arrays.

Figure 1-7 The parts of a typical main() method


CHAPTER 1 Creating Java Programs

The meaning and purpose of each of the terms used in the method header will become clearer
as you complete this textbook; a brief explanation will suffice for now.
In the method header public static void main(String[] args), the word public is an
access specifier, just as it is when you use it to define the First class.
20 In Java, the reserved keyword static means that a method is accessible and usable even
though no objects of the class exist.
The keyword void used in the main() method header indicates that the main() method
does not return any value when it is called. This doesn’t mean that main() doesn’t
produce output—in fact, the method in Figure 1-4 (and in Figure 1-7) does. It only means
that the main() method does not send any value back to any other method that might use
it. You will learn more about return values in the chapter “Methods, Classes, and Objects.”
The name of the method is main(). As is the convention with Java methods, its identifier
begins with a lowercase letter. Not all classes have a main() method; in fact, many do not.
All Java applications, however, must include a class containing a public method named
main(), and most Java applications have additional classes and methods. When you
execute a Java application, the JVM always executes the main() method first.
In the method header public static void main(String[] args), the contents between
the parentheses, String[] args, represent the type of argument that can be passed to the
main() method, just as the string "First Java application" is an argument passed to the
println() method. String is a Java class that can be used to hold character strings
(according to Java convention, it begins with an uppercase letter, like other classes). The
identifier args is used to hold any String objects that might be sent to the main()
method. The main() method could do something with those arguments, such as display
them, but in Figure 1-4, the main() method does not actually use the args identifier.
Nevertheless, you must place an identifier within the main() method’s parentheses. The
identifier does not need to be named args—it could be any legal Java identifier—but the
name args is traditional.
In this book, you won’t pass any arguments to the main() method, but when you run a program, you could.
Even though you pass no arguments, the main() method must contain String[] and a legal identifier
(such as args) within its parentheses. When you refer to the String class in the main() method header,
the square brackets indicate an array of String objects. You will learn more about the String class and
arrays in Chapters 7, 8, and 9.

The simple application shown in Figure 1-4 has many pieces to remember. However, for now
you can use the Java code shown in Figure 1-8 as a shell, in which you replace AnyClassName
with a class name you choose and the line /******/ with any statements that you want to
execute.

Watch the video A Java Program.


Analyzing a Java Application that Produces Console Output

public class AnyClassName


{
public static void main(String[] args)
{
/******/
} 21
}

Figure 1-8 Shell code

Saving a Java Class


When you write a Java class, you must save it using a writable storage medium such as a disk,
DVD, or USB device. In Java, if a class is public (that is, if you use the public access specifier
before the class name), you must save the class in a file with exactly the same name and a .java
extension. For example, the First class must be stored in a file named First.java. The class
name and filename must match exactly, including the use of uppercase and lowercase
characters. If the extension is not .java, the Java compiler does not recognize the file as
containing a Java class. Appendix A contains additional information on saving a Java
application.

TWO TRUTHS & A LIE


Analyzing a Java Application that Produces Console Output

1. In the method header public static void main(String[] args), the word
public is an access specifier.

2. In the method header public static void main(String[] args), the word
static means that a method is accessible and usable, even though no objects
of the class exist.
3. In the method header public static void main(String[] args), the word
void means that the main() method is an empty method.

return any value when it is called.


void main(String[] args), the word void means that the main() method does not
The false statement is #3. In the method header public static
Exploring the Variety of Random
Documents with Different Content
En este valle y líquida laguna,
Si he de decir verdad como hombre honrado,
Jamás me sucedió cosa ninguna.

Así es que Homero, guiado por su instinto divino é infalible, no describe,


y si describe, la descripción se vuelve acción. No se para Homero á
describir las armas de Aquiles, sino que nos lleva á la fragua, y vemos á
Vulcano con el martillo y las tenazas; y vemos el oro y el bronce que se
derriten, y los fuelles que soplan, y el fuego que arde; y vemos trabajar al
dios, y salir de entre sus manos ágiles, y de su maravillosa mente de artista,
la fuerte coraza, el penachudo morrión y el estupendo escudo, en cuyas
cinco zonas el dios va esculpiendo á nuestra vista, llena de grato asombro,
cuanto hay de más hermoso en el cielo y en la tierra.
Con el Tequendama ocurre lo mismo que con el Niágara. Cualquiera
descripción en prosa, la de Humboldt, la del matemático Caldas, la del
barón de Japurá, dan más cumplida idea que los mejores versos. La masa de
agua que se precipita es muy inferior, pero cae de un lugar cerca de cuatro
veces más alto. El agua además choca primero contra un banco de piedra, y
allí revienta; hierve y se lanza de nuevo en plumas divergentes hacia el
abismo. En el fondo es más terrible el choque y no puede mirarse sin horror.
Las plumas de agua, las puntas de lanzas, que tal parecen, se despeñan con
increíble rapidez y se suceden unas á otras. Al llegar al fondo, cuando no
antes, en virtud de su vertiginoso descenso, se desmenuza el agua y se
pulveriza, y asciende luego en forma de nubes, que el sol dora y adorna con
el iris. Se diría que el Bogotá, acostumbrado á correr por las regiones
elevadas de los Andes, baja á pesar suyo á aquella profundidad y quiere otra
vez elevarse orgulloso en difusos vapores. Estos vapores asegura Humboldt
que se ven desde la ciudad de Bogotá á cinco leguas de distancia.
Después de esto, ¿qué podrá añadir la poetisa; qué ponderación realzará
en sus versos la pintura de la catarata? La impresión propia, el vuelo de su
espíritu, su humano pensamiento y su elevada fantasía, que entrevé á Dios
en el horrendo arco que forma el agua.
Después prosigue la poetisa:
¿Qué buscas en lo ignoto?
¿Cómo, adónde, por quién vas empujado?
Envuelto en los profusos torbellinos
De la hervidora tromba de tu espuma,
E irisado en fantástico espejismo
Con frenesí de ciego terremoto,
Entre tu aérea clámide de bruma,
Te lanzas despeñado,
Gigante volador, sobre el abismo.
Se irgue á tu paso murallón inmoble
Cual vigilante esfinge del Leteo;
Mas de tu ritmo bárbaro al redoble
Vacila con medroso bamboleo.
Y en tanto al pie del pavoroso salto,
Que desgarra sus senos al basalto,
Con tórrida opulencia
En el sonriente y pintoresco valle
Abren las palmas florecida calle.
..................
La indiana piña de la ardiente vega,
Adorada del sol, de ámbar y de oro,
Sus amarillos búcaros despliega.
Sus ánforas de jugo nectarino
Te ofrece hospitalaria
La guanábana en traje campesino,
A la par que su rica vainillera
El tamarindo tropical desgrana,
Y la silvestre higuera
Reviste al alba su lujosa grana.
Bate del aura al caprichoso giro
Sus granadillas de oro mejicano
Con su plumaje de ópalo y zafiro
La pasionaria en el palmar del llano;
Y el cámbulo deshoja reverente
Sus cálices de fuego en tu corriente.
Miro á lo alto. En la sien de la montaña
Su penacho imperial gozosa baña
La noble águila fiera;
Y espejándose en tu arco de topacio,
Que adereza la luz de cien colores,
Se eleva majestuosa en el espacio
Llevándose un jirón de tus vapores.
Yl il i d i
Y las mil ignoradas resonancias
Del antro y la floresta,
Y místicas estancias
Do urden alados silfos blanda orquesta,
Como final tributo de reposo
¡Oh émulo del destino!
Ofrece á tu suicidio de coloso
La tierra engalanada en tu camino.

Todo esto es bello; pero en el fondo del cuadro, la figura principal es la


misma poetisa. El Tequendama es el pedestal ingente sobre el cual se pone
su espíritu

A retocar sus desteñidos sueños.

El desaliento que se apodera del espíritu en presencia de tan grande


escena, hace concebir mejor su magnificencia que la descripción más
atinada y exacta.
Manzoni, cantando á Napoleón, que al fin era un hombre como él, y por
la elevación del pensamiento mucho menor que él, puede decir, sin que nos
ofenda la jactancia, que va á entonar un cántico que forse non morrà.
Simónides, reviviendo en los versos de Leopardi, puede pedir para sus
versos la misma inmortalidad que da la gloria á los trescientos héroes que
los versos celebran; pero ante el espectáculo solemne de aquella fuerza
ciega, fatal y sin término, el ánimo se apoca. Es además una mujer la que
canta, y yo veo algo de amable y de muy delicado en la timidez y
desconfianza con que la poetisa predice, engañada por su modestia, que su
canto va á morir; que

Así como se pierden á lo lejos,


Blancos al alba y al morir bermejos,
En nívea blonda de la errante nube,
O en chal de la colina,
Los velos primorosos
De tu sutil neblina,
Va en tus ondas mi cántico arrollado
Bajo tu insigne mole confundido,
E, inermes ante el hado,
Canto y cantor sepultará el olvido.
No es de recelar que tal suceda, porque los versos son hermosos y
muestran el arte de la poetisa, su viva imaginación y el buen gusto para la
dicción poética. Tal vez el bamboleo con que, alucinada ella por un
momento, cree que se estremecen y vacilan las inmobles rocas al rudo golpe
del agua, parezca á alguien palabra sobrado vulgar; pero es gráfica y está
realzada por el epíteto medroso.
La pintura de la vegetación tropical, que se extiende al pie del Salto, no
es inferior á la de D. Andrés Bello, que la poetisa recordó é imitó, y aun se
puede afirmar que hace más impresión que la de Bello, porque no habla en
general de las plantas y flores de la zona tórrida, sino que describe lo que
está viendo allí mismo.
No es Agripina Montes la única poetisa de nota que el Parnaso
Colombiano nos da á conocer. Hay otras que llaman mucho la atención y se
ganan el aprecio y las simpatías de los lectores.
Yo me figuro que en Colombia no deben de ocurrir las varias causas que
en España, y sobre todo en Madrid, influyen para que las mujeres no
escriban versos. Nuestros padres y abuelos, hartos de los discreteos, latines
y tiquis-miquis de las damas de Calderón, condenaron el saber en las
mujeres, denigraron á las mujeres sabias con los apodos de licurgas y
marisabidillas, y pusieron el ideal femenino en la más crasa ignorancia. Mas
tarde, y ya bien entrado este siglo de las luces, volvió la mujer á querer
saber y á saber; pero en muchas partes, y sobre todo en Madrid, en las
clases elegantes y abastadas, la educación de la mujer fué exótica: en
colegios, ingleses ó franceses, con ayas inglesas ó alemanas. De aquí que el
castellano fuese en boca de muchas damas la lengua del vulgo, sólo
aristocratizada por la pronunciación gangosa de las erres. Si la dama salía
aficionada á leer, leía á Musset ó á Lamartine ó á los poetas británicos, y lo
español le parecía tonto y cursi, aunque no lo dijese ella. Cuando la dama
no salía muy aficionada á leer, como esta vida de Madrid, la high life, es un
torbellino de fiestas, toros, bailes y paseos, no había para qué leer ni
siquiera por pasatiempo. Al teatro se iba á oir música, y de la dama comm’il
faut, si por acaso se allanaba á ir á la comedia, se podía decir lo que ya
Iriarte decía de las currutacas de su tiempo:
Aplauden cuando más al tramoyista;
Oyen tal cual chulada del sainete,
Y sirve lo demás de sonsonete,
Mientras que están haciendo una conquista.

De aquí que, con relación á la gracia, chiste, despejo y portentosa


facundia de la mujer española, hayan sido muy pocas las que han escrito y
han ganado alta fama escribiendo. Y estas pocas han venido casi siempre á
este centro, desde el fondo de alguna apartada ciudad de provincia. Así la
Avellaneda, de Cuba; Carolina Coronado, de una villa de Extremadura;
María Mendoza y Josefa Barrientos, de Málaga; y de la Coruña, doña
Emilia Pardo Bazán.
En toda mujer que se lanza en España á ser autora, hay que suponer una
valentía superior á la valentía de la Monja-Alférez ó á la de la propia
Pentesilea. Cada dandy, si por acaso la encuentra, será contra ella un
Aquiles, más para matarla, que para llorar su hermosura después de haberla
muerto. Quiero decir, dejando mitologías á un lado, que en la literata suelen
ver los solteros algo de anormal y de vitando, de desordenado y de
incorrecto, por donde crecen las dificultades para una buena boda, etc., etc.
De aquí que, si una jovencita sale aficionada á literatear ó á versificar, ella
misma lo oculta como un defecto ó impedimento dirimente, cuando no es la
propia familia la que procura ocultarlo. Sólo la más ardiente y firme
vocación y un extraordinario mérito pueden sobreponerse á tanto cúmulo de
inconvenientes.
Una pícara sentencia de Horacio, cuya falsedad é injusticia, perdóneme
Horacio, ofenden al recto juicio, viene á hacer más penosa la situación de
toda poetisa: la medianía en versos no la sufren ni los postes. De modo que
sufrimos la medianía en la cocinera (y ojalá que la mía fuese siquiera
mediana), en la planchadora, en la que borda, en la que dibuja, en la que
canta, y sólo para versos es menester que los haga una mujer mejor que
Safo, ó que no los haga. Yo declaro esto absurdo. Yo declaro que sufro
mejor, no ya un mediano soneto, sino una oda mala, que una camisa mal
planchada, que un caldo mal hecho, que un aria mal cantada, ó que una
melodía de Chopin chapuceramente tocada en el piano ó en el arpa. Si por
temor de hacer mal una cosa no se ha de hacer, la misma razón hay para que
una mujer no haga versos, que para que no cante, ó baile, ó toque el piano.
En verso se pueden decir tonterías: esto es verdad; pero ¿acaso hablando en
prosa no pueden también decirse tonterías? ¿Y hemos de anudar ó cortar la
lengua de las mujeres para que no las digan? No niego yo que una tontería,
dicha en verso, adquiere cierta consistencia, compromete más, es más
solemne, resonante y repercutiente, que en prosa; pero, en cambio, debemos
convenir en que, por facilidad que se tenga para hacer versos, y por malos y
flojos que los versos sean, no se improvisan tanto, ni salen, ni manan con
tanta fluidez y copiosa vena como las tonterías en prosa desatada.
Otro argumento tengo yo en favor de los versos. Reflexiónese bien y no
se me rechace por sutil: es muy fundado. Todos, hombres y mujeres,
tenemos cierta dosis ó capital de tonterías, que gastamos ó difundimos
durante nuestra vida mortal. Ellas han de brotar de nosotros como la flor de
la planta. ¿No es mejor, pues, que se digan que no que se hagan? Y al
decirlas, ¿no es mejor decirlas con rima y con metro? No niego que así
subirá más alto, pero también será más delgada la tontería, como cuando en
el caño de la fuente que se desborda ponemos un apretado y más angosto
canuto, por donde sube más el surtidor, pero sale también menos líquido.
Es indudable que, en la mujer, el hacer versos presenta otra dificultad
más grave; pero yo la allano ó salto por cima. La poesía, la lírica sobre
todo, siendo sincera como debe ser para ser buena, es autobiografía del
corazón y de la mente: es exhibir el alma al público en su desnudez; y esto
parece que lastima algo el pudor y la modestia. ¿Cómo enterar á todo el
género humano de tus afectos y pasiones? Pues peor es todavía que le
engañes y que supongas lo que no eres. Entonces harás una mala acción, y
harás además, de seguro, muy malos versos. La mentira del sentimiento es
adversa á toda estética.
No hay más remedio que decir la verdad. ¿Y por qué ha de ser tan
costoso é incómodo decirla? ¿A qué, en este punto, el misterio y el recato?
Seamos positivistas, como mi amigo Juan Enrique Lagarrigue, en cuya
Religión de la Humanidad es el Mandamiento III ó IV, no lo recuerdo bien,
vivre au grand jour.
No crea Ud. que es impertinente esta digresión. La traigo aquí para
hablar de la sinceridad, de la noble franqueza, de la verdadera poesía íntima
y honda que noto y admiro en algunos versos de sus paisanas de Ud., y por
cima de todos, en los de Mercedes Flórez. Dicen y afirman cuantos la
conocen que es hermosísima mujer; pero á mí, aunque fuese fea, me sería
simpática, por la limpia hermosura de su alma y por su candidez generosa.
Sus versos sí que son versos íntimos, sentidos y vividos. La palabra casera,
que aplicada á la poesía fué hasta hoy despreciativa, tiene, por causa de la
poesía de Mercedes Flórez, que adquirir un valor encomiástico.
Los versos caseros y la vida casera de Mercedes Flórez se confunden y
son un idilio de verdad. El mismo año que ella, el año de 1859, nació su
novio Leonidas. Ella y él se amaron mucho. Como eran pobres ambos, los
padres se oponían á la boda; pero ellos prescindieron de todo y se casaron.
Leonidas Flórez es también poeta, y compuso entonces unos lindos y
graciosos versos, que se titulan Regalos de boda, y que empiezan:

Nos hemos de casar, pese al demonio.


Ya han agotado todos sus consejos
Nuestros padres contra este matrimonio.
Así son las chocheces de los viejos.

Como toda la oposición se fundaba en la pobreza del novio, éste prueba


que es riquísimo, haciendo brillante enumeración de los espléndidos regalos
que trae á Mercedes.
Nada falta allí: estrellas, perlas, diamantes, palacios y jardines que
brotan del tesoro inagotable de su fantasía. Y no contento con probar que él
es rico, prueba el novio además que es riquísima ella:

Tú también eres rica y generosa;


Tu regalo es el colmo de mi anhelo:
Me entregas tu belleza, eres mi esposa:
Vale eso más que regalarme un cielo.

Él matrimonio ha sido y es dichosísimo, á pesar de esta única riqueza,


que no se cotiza en la Bolsa. Y una de sus dichas ha sido la de inspirar las
sencillas y tiernas poesías de Mercedes, humilde Victoria Colonna
americana.
Después de llamar esclavitud al matrimonio, exclama ella:

Mas ¡oh bendita esclavitud que adoro,


En que se reina al par que se obedece!
Cadenas tiene, mas cadenas de oro.....
¡Déjame en mi entusiasmo que las bese!
Mercedes sólo tiene un pesar: tiene celos de la gloria y de la ambición de
su marido.

La adoras, sí; lo leo en tu mirada;


En tus noches de insomnio lo confiesas,
Y quizá mientras duermo confiada,
Tú en tus sueños la abrazas y la besas.

Entonces procura ella demostrar la vanidad de la gloria, ó bien se queja


diciendo:

Ama á la gloria, pues. Vé hasta la altura;


Sube como el condor hasta los cielos,
En tanto que yo ahorro mi amargura
Amándote y muriéndome de celos.

En otra ocasión se afana ella por disuadirle de que sea ambicioso, y le


dice:

No busques oro y seda y pedrería,


Ni rico hogar ni deslumbrante coche;
Te bastarán tus libros en el día,
Te bastarán mis cuentos en la noche.

Pero donde Mercedes Flórez es divina y despierta envidia de su marido


en todo corazón de hombre, es en unos versos que compuso en Diciembre
de 1883, cuando ella tenía veinticuatro años y veinticuatro años él, y
cuando acababa su marido de salir de una enfermedad que le tuvo á la
muerte. Los versos se titulan En la agonía, y la refieren como si estuviera
pasando: son admirables de verdad y de afecto; son la poesía natural del
corazón que trae lágrimas á los ojos:
¡No, no! ¡Tú me amas mucho para dejarme sola!
¡No, no! ¡Yo te amo mucho para dejarte ir!
Llévame en ese viaje pesado de ultratumba,
O quédate conmigo: aun somos harto jóvenes
Para poner, amándonos, á nuestra vida fin.

Estréchame en tus brazos, amado mío, bésame;


Mis labios, nueva vida te volverán y ardor.
Lucha contra la muerte: véncela en el combate:
No me abandones, mi ídolo, que hoy te amo más que nunca.....
Conmuévante mis lágrimas..... ¡no lances ese adiós!
.......................
.......................
Aquí hay laureles muchos aún para tus sienes:
Yo con mis propias manos las tengo de adornar.
Amante de tu gloria, yo quiero que no trunques
Tu espléndida carrera, y de tu vida á lo último
El genio te dé aureolas haciéndote inmortal.

¡Dios mío! Mira tu obra: la flor abre sus pétalos;


El águila ya altiva levanta el vuelo audaz;
¿Y tú permitir puedes que el cierzo la marchite,
Y que cobarde flecha alcance el nido íntimo
Y rompa las entrañas del águila real?

¡Dios mío, tu justicia es grande cual tú mismo,


Y mi esperanza toda de hoy más cifraré en ti!
¡No arranques de mi cielo este lucero fúlgido
Que no hace falta al tuyo! Escucha..... En su delirio
Dice que me ama tanto..... ¡que no quiere morir!

Dispense Ud. y dispense el público, á quien confío estas cartas, á Ud.


dirigidas, que sea yo largo en ésta. Ya abreviaré en adelante.

*
**

17 de Septiembre de 1888.

V
Mi distinguido amigo: Por más que me amonesto y me excito á ser
breve, tengo aún tanto que decir, que, sobreponiéndome al temor de cansar,
acabaré por decirlo. La floreciente literatura castellana, ó en castellano, de
esa república, me complace tanto como si yo soñase que á una persona
querida, á quien antes del sueño le hubiesen cortado ó tratasen de cortarle
los brazos, le brotasen alas de repente.
Diré á Ud., para que se entere de esta mi visión alegórica, que en gran
parte de España, por un lado en Cataluña y por otro en Galicia, ha entrado
la manía á no pocos valerosos y fecundos ingenios de privar de sus frutos al
habla de Castilla y de escribir sus mejores obras en prosa ó en verso, en
catalán ó en gallego. Á mí, que soy muy patriota, en literatura como en
todo, me aflige esto bastante; pero me consuela que ustedes, desde tan lejos,
nos den como rica compensación lo que dentro de la Península nos quitan
nuestros compatriotas.
Tengo además otras razones para extenderme, aunque peque de prolijo.
Los sabios está claro que lo saben todo, y yo no descubro ningún
palimpsesto para hablar de ustedes; pero al fin no faltan personas poco
sabias, entre las cuales nada se sabe de Uds., y yo puedo contarles cosas
casi tan interesantes y amenas como el crimen de la calle de Fuencarral.
Me remuerde la conciencia de haber elogiado sólo á Mercedes Flórez y á
Agripina Montes y de no mentar siquiera á otras poetisas. En muchas de
ellas noto el mismo candor, la misma sencillez y no menor pasión delicada
que la que tan simpática me hace á la hermosa Mercedes.
Así, por ejemplo, Bertilda Samper, hija del doctor del mismo nombre y
de doña Soledad Acosta, ilustres escritores ambos. Esta poetisa se complace
en la solitaria vida del campo, donde se deleita su alma en la contemplación
de la naturaleza y en el devoto y ferviente amor de Dios. Sus versos tienen
singular dulzura religiosa. La parábola del sembrador es muy bella, y en
las Cartas de una campesina hay trozos que no son inferiores.
Citaré, por último, á otra notable poetisa y escritora colombiana, aunque
no lo es por nacimiento, sino por adopción. Hablo de la dama irlandesa
María Juana Christie, que casó con don Juan E. Serrano, á la cual he tenido
el gusto y la honra de tratar en Nueva York, y á la cual Núñez de Arce y yo
debemos estar y estamos muy agradecidos. La señora de Serrano ha
traducido al inglés, con singular maestría, venciendo á otros traductores y
satisfaciendo el gusto difícil de los críticos de la casa de Appleton, mi
novela Pepita Jiménez: ha traducido y publicado también mi diálogo Gopa,
y ha puesto en hermosos versos ingleses, con general aplauso, no pocos de
los que contienen los Gritos del combate.
Esta señora, sobre su llaneza de buen tono y natural modestia, está
dotada de muy agudo ingenio y de elevado entendimiento, cuyo cultivo ha
sido esmeradísimo. Habla el castellano tan bien como el inglés, y posee
además el alemán, el italiano y las lenguas clásicas griega y latina.
De obras originales no sé que haya publicado más la señora de Serrano
que un tomito de versos titulado Destiny and other poems, en Nueva York,
en 1883; pero este tomito, hasta donde yo soy capaz de comprender el
mérito de la poesía inglesa, me parece que no se perderá en el inmenso
cúmulo de dicha poesía, y que algo de lo que el tomito encierra figurará
como muestra, adorno y gala en las futuras Antologías británicas.
La señora de Serrano, á quien estiman y quieren mucho en la sociedad
más distinguida de Nueva York y de Washington; que es hermosa, y que
tiene una hija ya casadera, en quien ve renovarse su hermosura, no debiera
estar muy melancólica, ni tener blue devils; pero los males de su patria,
Irlanda, el ejemplo de Byron y de Shelley, y la filosofía pesimista alemana,
hoy tan en moda, influyen poderosamente en ella, en lo teórico al menos, ó
sea cuando toma la lira y canta. De ordinario, no me parece la señora de
Serrano ni desesperada ni siquiera cejijunta, sino llena de afabilidad y de
agrado.
Sea como sea, no sé si lamentar su sombría tristeza, meramente
especulativa, como la supongo, y que produce tan magníficos versos.
Algunos, traducidos al español por D. Rafael Pombo, vienen insertos en el
Parnaso Colombiano; pero no bastan estos versos, y sería menester estudiar
con atención todo el tomo, en inglés, para penetrar bien en el vacilante
espíritu de la poetisa y determinar hasta qué extremo llega su pesimismo, y
cómo ella le contradice y vence por virtud de ciertas vagas creencias en
palingenesias en otros astros, donde la felicidad no es tan difícil, ya que no
imposible, como en este en que vivimos ahora.
Necesitaría yo hacer especial estudio del extenso poema Destiny para
aquilatar bien el mérito y la originalidad de la señora de Serrano, y hasta
qué punto se deja influir por la celebrada y eminente poetisa Isabel
Browning, su compatriota. En las obrillas cortas de la señora de Serrano se
nota la impresión del momento. En algunas, como en Despondency, Días de
otoño é Invocación á la muerte, hay la más negra y completa desesperación;
en otras brillan esperanzas vagas ultramundanas, y en otras, por último, hay
yo no sé qué enigmático remedio de todos los males, que la poetisa posee y
disfruta, aun en esta vida mortal, pero que no sabe, ó no debe, ó no quiere
descubrir en qué consiste. Así es que habla de su panacea como
proponiendo un acertijo y ofreciendo premio al que le declare. Yo, aunque
mal y torpemente, he traducido, ó mejor diré, he adaptado al español este
acertijo, riddle. Allá va: adivínele quien pueda.
Es mi tesoro una joya
Que en áureo cerco no brilla:
Me la dió Naturaleza
En su forma primitiva.
Mas quien de joyas entiende,
Si llega á mirar la mía,
Su inmenso valor pondera
Y palidece de envidia.
En clara noche de estío,
Del mundo en la edad florida,
Cuando la tierra con lágrimas
Regado el hombre no había,
Pues deslumbraba sus ojos
La luz de fáciles dichas,
Cayó mi joya del cielo
Sin que su luz fuese vista.
Vino más tarde el dolor,
Que sueños calman y alivian,
Y quien alivio buscaba
Mi joya en sueños veía.
Danzas entonces tejiendo
En una selva, á la tibia
Claridad de las estrellas,
Y en el césped escondida,
Encontró un hada mi joya
Y la puso en su varita.
Protectora se hizo el hada
De mucha inocente niña,
Y trocó en sedas y encajes
Los harapos que vestía,
Y se la llevó en volandas
A dar, en fiestas magníficas,
A los príncipes amor
Y á las princesas envidia.
Luego empeoró nuestra raza,
Y las hadas afligidas
Huyeron sin que se sepa
A qué región ni á qué clima.
Antes de huir sepultaron
La joya en profunda sima,
Porque no la profanase
Ninguna mirada indigna.
S b t i d i
Sobre esta piedra preciosa
Harto los sabios cavilan,
Y filosofal la llaman
Y estudian por descubrirla.
Mas, como nunca penetran
Bastante en la esencia íntima
De naturaleza, en balde
Ver la joya solicitan.
Así permaneció siempre
Blanco oculto á toda mira,
Hasta que en una mañana
De primavera, yo misma
Con mis lisonjas la atraje
Por mis conjuros cautiva.
En mi seno, desde entonces,
La joya está, do mitiga
Toda pena, y donde todo
Vano deseo amortigua:
Que hay en su centro brillante
Misteriosa hechicería
Y recuerdos de aquel sitio
Que abandonó en su caída.
Al contemplarla mi alma,
Mi alma á los cielos aspira,
Sin que en afanes diarios
La joya no valga y sirva,
Pues humildad y pobreza
No la avergüenzan ni humillan:
Y con rosicler de aurora
Baña su luz peregrina
Mejor que el alcázar regio
Las modestas alquerías.
Al sabio que de esta joya
Sepa el nombre, y dé noticias
Y explicación del encanto
Que en su talismán se cifra,
Tendré yo por el más sabio
Mortal que en el mundo viva,
Y también por el más rico,
Y, aunque nada anhele y pida,
A mi muerte ha de ganar
Esta joya por albricias.
Volviendo ahora á los poetas, que por admirar á las poetisas habíamos
abandonado, seré breve por varias razones.
Hay tres ó cuatro poetas en el Parnaso Colombiano de quienes es mejor
limitarse á citar los nombres que decir poco sin haber estudiado todas sus
obras y sin conocer bien su vida.
Así, por ejemplo, Rafael Núñez, actual presidente de la república. Núñez
es autor de un libro titulado Ensayos de crítica social y también de muchas
poesías, que no sé si ha publicado en tomo. Las que inserta el Parnaso son
originalísimas por su fondo filosófico y por su forma concisa, enérgica y
sentenciosa. La primera, que es la más encomiada y que merece serlo, deja
pasmado á quien la lee, sobre todo al considerar que es el autor un hombre
político, presidente de la república nada menos. Nosotros casi no podemos
comprender la franqueza de Núñez. Entre nosotros no diré yo que un jefe de
partido, un eminente hombre de Estado tenga por fuerza que creer en alguna
cosa. Bien puede no creer en ninguna; pero se guardará de decirlo. Decirlo
sería descarrilar: hacer mal su papel. Tendrá, pues, su Credo ó Símbolo,
redactado por artículos; artículos de fe, de cada uno de los cuales no
renegará, aunque le descuarticen. Así serán ó aparecerán todos los políticos.
Este creerá en la soberanía del pueblo y en el sufragio universal; aquel, en
el derecho divino de los reyes y en la constitución interna; uno será
librecambista, proteccionista otro; pero todos se mostrarán muy firmes en
sus creencias y harán de las opiniones dogmas, y de la profana política algo
como religión ultrasagrada, y llamarán comunión ó iglesia á su bandería ó
pandilla, y correligionarios á sus parciales, y pondrán en su martirologio á
cualquiera de estos correligionarios, cuyo suelto en los periódicos haya
sido denunciado.
Acostumbrados nosotros á esta severidad dogmática, y dichosos
poseedores de una ciencia ó de una creencia, ¿cómo no maravillarnos de los
versos del Sr. Núñez, que se titulan, con la frase de Montaigne, Que sais-
je?, y donde el autor viene á declarar que no cree en nada y que no sabe
nada? El Sr. Núñez no está seguro de

Si es la ciencia dudosa que aquí hallamos


Escala vacilante en que pasamos
De un error á otro error.

Así es que termina exclamando:


¡Oh confusión! ¡Oh caos! ¡Quién pudiera
Del sol de la verdad la lumbre austera
Y pura en este limbo hacer brillar!
De lo cierto y lo incierto, ¡quién un día
Y del bien y del mal conseguiría
Los límites fijar!

Otros varios poetas figuran en el Parnaso Colombiano, de quienes no se


debe aquí decir nada. Sería menester escribir un largo artículo sobre cada
uno. Hay que hacerse cargo de que el Parnaso Colombiano es un
muestrario de toda una rica literatura contemporánea.
Tal vez un día, si sigo yo escribiendo estas cartas, hable extensamente y
como ellos merecen, de José María Samper, poeta, novelista, dramaturgo,
filósofo, político y el más fecundo escritor de Colombia; de Julio Arboleda,
lírico famoso y autor de un poema ó leyenda cuyo título es Alvaro de Oyón;
de José María Marroquín, sabio filólogo y discreto poeta, lleno á veces de
chiste; de Gregorio Gutiérrez González, gran pintor de la naturaleza de su
tierra, y cuyo poema sobre el cultivo del maíz acaso compite con la sublime
Destrucción de las florestas del brasileño Araujo Porto-Alegre; de los
Caros, padre é hijo, de quienes he dicho tan poco, y de otros más.
Por lo pronto, aunque no baste esta carta y tenga yo que escribir la sexta
para terminar mi trabajo, he de decir algo todavía de varios poetas que me
parecen muy originales, y de otros, jóvenes los más, que, sin dejar de ser
originales, siguen algo en la forma y en la manera, ya á Campoamor, ya á
Bécquer, que son, á par de Núñez de Arce, los poetas españoles del día más
populares y celebrados hoy en Colombia.
Justo es decir que, entre estos jóvenes poetas, Bécquer es más seguido é
imitado que Campoamor, y que su escuela está también mejor representada.
Verdad es que Bécquer tiene á Heine por auxiliar, y el auxiliar de
Campoamor no acude ó no se ve tan claro.
Como muestras de estos becqueristas citaré de Emilio Antonio Escobar
las siguientes composiciones, que él llama Rimas, como llama Bécquer á las
suyas:
Allá en el fondo de la tumba fría,
Del cadáver los átomos inertes
Se transforman, se buscan y palpitan
En las auroras de un eterno génesis.....
Y aquí en mi pecho un corazón vacila
Y el hielo horrible del sepulcro tiene.....
Allá se siente palpitar la vida,
Aquí se siente palpitar la muerte.

Cada vez que tu mano, al despedirme,
Estrecho conmovido entre las mías;
Cada vez que me dices: «Hasta luego»,
Fijando en mí tus húmedas pupilas,
Oigo un eco lejano que repite
Dolorosa y eterna despedida,
Y siento que una lágrima que oculto
Me cae al corazón pesada y fría.

Ya en la iglesia de los cielos
Alguien enciende los cirios,
Y el órgano de los vientos
Suspira ya sus registros;
Largos nubarrones negros
Enlutan el infinito.....
Se va á cantar el entierro
De nuestro amor muerto niño.

En todo esto hay lo más lastimoso de Bécquer y de Heine: olor de


cementerio y cancamurria de gori-gori.
Muy superior me parece otro becquerista de veintitrés años: Joaquín
González Camargo, médico y literato. Sus versos Viaje de la luz son
becqueristas; pero, ¿yo no sé?, me siento inclinado á decir que me gustan
más que los mejores de Bécquer y de Heine. Y dicen los versos:
Empieza el sueño á acariciar mis sienes:
Vapor de adormideras en mi estancia;
Los informes recuerdos en la sombra
Cruzan como fantasmas.
Por la angosta rendija de la puerta
Rayo furtivo de la luna avanza,
Ilumina los átomos del aire:
Se detiene en mis armas.
Se cerraron mis ojos, y la mente,
Entre los sueños, á lo ignoto se alza:
Meciéndose en los rayos de la luna,
Da formas á la nada.
Y ve surgir las ondulantes costas,
Las eminencias de celeste Atlántida,
Donde viven los Genios y se anida
Del porvenir el águila.
Allí rima la luz y el canto alumbra,
Aire de eternidad alienta el alma,
Y los poetas del futuro templan
Las cristalinas harpas.
Auroras boreales de los siglos
Allí se encuentran, recogida el ala;
Como una antelia vese el pensamiento
Que gigantesco se alza.
Allí los Prometeos sin cadenas
Y de Jacob la luminosa escala;
Allí la fruta del Edén perdida,
La que el saber entraña.
Y el libro apocalíptico, sin sellos,
Suelta á la luz sus misteriosas páginas,
Y el Tabor del espíritu su cima
De entre la niebla saca.
Y allí el Horeb de donde brota puro
El casto amor que con lo eterno acaba:
Allá está lo ideal, allá boguemos.....
Dad impulso á la barca.
Despertéme azorado..... ¿Y ese mundo?
Para volar á él ¿en dónde hay alas?
Interrogué á las sombras del pasado,
Y las sombras callaban.
Pero el rayo de luna ya subía
Del viejo estante á las polvosas tablas,
Yl i d l l d l lib
Y lamiendo los lomos de los libros,
En sus títulos de oro se miraba.

Y ahora que acabo de copiar los versos del señor Camargo,


comprendiéndolos bien, no vacilo ni dudo. Digo, parodiando al Duque de
Rivas, que, en esta ocasión,

No el padre guardián, el lego


Tuvo la revelación.

El discípulo Camargo se adelanta aquí á sus dos maestros, al español y al


alemán, y hace una linda poesía, sobria de palabras, rica de pensamientos,
llena de imágenes y de galanura.
Y baste por hoy. Prometo que la próxima carta será mi última sobre este
asunto.

*
**

8 de Octubre de 1888.

VI
Mi distinguido amigo: Ya habrá Ud. notado que en la rápida y poco
ordenada reseña que de los poetas de esa república voy haciendo, hay un
espíritu que, por lo mismo que es muy español, propende más á poner de
realce lo original que lo imitado. Sin duda que algo lisonjea el amor propio
nacional percibir en región tan remota la resonancia ó el eco de Quintana,
de Bécquer, de Campoamor y de Núñez de Arce, que son hoy los poetas de
esta Península más populares ahí; pero si todo es uno, según mi teoría; si
Uds. no han proclamado la independencia literaria, ni nosotros la hemos
reconocido tampoco; si no conviene además esta independencia, y si toda la
riqueza nuestra y de Uds. debe seguir pro indiviso, creo yo que nos trae más
cuenta que todo sea diverso dentro de la grande unidad, que no tener
doublettes ó ejemplares dobles en nuestro tesoro común intelectual ó
biblioteca castellana.
Por dicha, la realidad viene en Colombia á colmar la medida de mi
deseo. Son Uds. todo lo originales que deben ser, sin caer en la
extravagancia, buscando la originalidad, y sin imitar demasiado á los
franceses é ingleses por no imitar á los españoles.
Poco hay que pueda calificarse en Colombia de campoamoresco ó de
quintanesco. Sólo abunda el becquerismo; pero más bien el remedo es en el
corte ó traza, que no en el fondo y la esencia.
Un cubano, Rafael Merchán, que ha ido á vivir y á escribir entre Uds., ha
emitido, en uno de sus más bellos artículos, un juicio de Bécquer,
atinadísimo, en mi sentir. Para Merchán, como para nosotros, Bécquer es
excelente poeta: de lo mejor que España ha tenido en el siglo XIX. El fondo
de su poesía es rico y vario; pero casi siempre están sus composiciones
como vaciadas en el mismo molde ó cortadas por el mismo patrón. Esto es
lo que constituye la manera, que no niego yo que induce á la imitación.
Cuando el poeta imitador adquiere, tal vez sin darse cuenta de ello, la
habilidad, el arte ó procedimiento de la manera, hasta sin querer suele
seguirla.
Así es como se nota el sabor becquerista en los ya citados versos de
Camargo y de Escobar, en otros que no citamos, y (¿por qué no declararlo?)
en los que de Ud. colecciona el Sr. Añez, aunque la imitación en ellos es
más indecisa y vaga.
En los versos de Ud. se ve que el poeta, ilustrado su entendimiento por
no escasa doctrina y por el saber de varias literaturas, no se deja llevar por
determinado maestro, y la inspiración sacude todo yugo y se levanta libre
de remedo, mostrando su valer propio. Yo, por las pocas muestras que de
sus versos de Ud. da el señor Añez, y en vista de la mocedad de Ud., me
atrevo á saludarle como buen poeta, augurándole brillantes triunfos en lo
futuro. La composición de Ud. titulada Lo que es un nido suscita el
recuerdo de La iglesia perdida, de Uhland, aunque en la conclusión, la de
Ud. es racionalista y algo panteísta, y la de Uhland fervorosamente
cristiana. Á veces, en los instantes de mayor rapto lírico-filosófico, va Ud.
más allá de lo justo en los atrevimientos de expresión, influído acaso por
Víctor Hugo. Así, por ejemplo:
Y ansiando apocalípticos asombros,
Subí de lo infinito las escalas,
Y asombrado sentí que en mis dos hombros
Se agitaban dos alas,
Y volé como fuera de mí mismo.....
Y crucé los espacios estelares.....
Y comulgué la luz en el abismo
De incógnitos altares.

La peregrinación de su espíritu de Ud. por el éter, su comunión de luz en


el abismo, etc., nada está de sobra al considerar que Ud. se propone
descubrir dónde se oculta el verbo; pero á la verdad que es triste lo
infructuoso de la caminata y lo hondo de la caída, cuando, al volver Ud. de
su éxtasis, ve un nido de golondrinas, que será á lo más uno de los mil
millones de efectos del verbo, pero que no es el verbo, ni le explica, ni
explica nada.
La composición de Ud., Idea y forma, está muy inspirada por Bécquer.
En la otra composición, que se titula Confidencia, hay cierta vaguedad
misteriosa, que podrá tener hechizo para algunos, pero que á otros los podrá
inducir en la creencia de que el poeta no está muy seguro de nada, y de que
nada le ha pasado, y de que todo es sueño ó dislate, cuando él mismo ignora
si se le ha muerto la novia ó si se le ha casado con otro. Hay en estos versos
anhelo de sencillez y naturalidad de lenguaje, que yo apruebo, porque la
sencillez y la naturalidad hacen que los versos de amor parezcan más
sentidos y vividos; pero, cuando en este estilo sencillo viene á interpolarse
alguna palabra ó frase, ó muy ambiciosa ó muy técnica del tecnicismo
filosófico, ocurren disonancias de efecto pésimo. Así, por ejemplo, cuando
dice Ud. que ella sepulta la frente en el pañuelo, y peor aún cuando
pregunta usted si ella le piensa aún con amor.

¿Y cómo entonces con amor me piensas?

Sin duda que, en lenguaje filosófico, las cosas se piensan ó son


pensadas; pero, en estilo sencillo y de amores, el amante piensa en su
amada y la amada en su amante, y si ambos piensan algún ser, este ser,
aunque utilísimo, es muy inferior al ser humano.
Piénselo Ud. bien, y convendrá conmigo en que no debemos desear que
las muchachas bonitas nos piensen, sino que piensen en nosotros.
A fin de no hacer interminables estas cartas, voy á prescindir de multitud
de poetas de quienes hay obras selectas en el Parnaso, y á citar, como
remate, á los cuatro ó cinco que me parecen más inspirados y más llenos de
originalidad.
Empezaré por Rafael Pombo, cuyas obras completas siento no conocer.
Mi opinión acerca de Pombo tiene también que ser poco fundada; esto es,
tiene que fundarse sobre datos muy insuficientes. Hay mil cosas que
despiertan la curiosidad al leer sus poesías, y que yo no podría averiguar á
no escribir pidiendo noticias, ó á Colombia, ó á París, donde hay muchos
colombianos. La romanza del rey Asuero y el aria de don Rodrigo, en las
óperas Ester y Florinda, implican que existen estas óperas, y un compositor
colombiano, que se llama el maestro Ponce de León, é implican que Pombo
ha escrito enteros ambos librettos. Yo sé, porque lo dice el señor Añez, que
Pombo ha publicado Cuentos pintados y Cuentos morales para niños, y que
son tan populares y famosos, que se los saben de memoria casi todos los
niños de la América española. Y si esto es así, yo me pregunto: ¿cómo es
que en España, donde tan pobre es esta clase de literatura para niños, no han
penetrado los tales cuentos y no se ha hecho de ellos alguna edición?
Colócase también á Rafael Pombo entre los mejores traductores de
Horacio. Dice Añez que el eminente Menéndez Pelayo da gran valer á su
traducción, pero no nos dice si es ó no completa. Yo lo ignoro, y buscando
además en el Horacio en España lo que dice Menéndez de Pombo, nada he
hallado. Tal vez sea una edición posterior á la que yo tengo. En la que yo
tengo, aun no conocía Menéndez sino poquísimo de la poesía hispano-
americana contemporánea, lamentándose de que no exista historia de la
literatura de la América española, ni aun colección de poetas americanos
medianamente hecha. Se ve que entonces aún no había leído Menéndez sino
el tomito, publicado en Leipzig por Brockhaus, que encierra, en su harto
severo sentir, «piezas detestables que no pueden pasar por buenas ni en
América ni en parte alguna del mundo civilizado».
Volviendo á Pombo, diré que, como otros varios americanos de nuestra
raza, ha ejercido muchas profesiones en su vida de acción, y en su vida
especulativa ha estudiado y escrito de todo. Pombo es ingeniero civil; ha
sido militar, y profesor, y diplomático, y periodista; y como escritor, es
polígrafo. Contraigámonos aquí á hablar de él sólo como poeta. Su lira
posee todas las cuerdas y todos los tonos: es mística, erótica, elegíaca,
jocosa, satírica y descriptiva; pero ni siquiera conocemos una muestra de
cada género.
En lo que conocemos hay originalidad, naturalidad y gracia. Sus
redondillas al bambuco, que llegan á ochenta, muestran cuán fácil y
abundante es el autor, sin pecar de pesado ni de rastrero. La música y la
danza del bambuco están muy bien calificadas, y ponderadas con chiste
todas sus excelencias y la desapoderada afición que le tienen los
colombianos:
Porque ha fundido aquel aire
La indiana melancolía
Con la africana ardentía
Y el guapo andaluz donaire.
Su ritmo vago y traidor
Desespera á los maestros;
Pero acá nacemos diestros
Y con patente de autor.
.............
Hay en él más poesía,
Riqueza, verdad, ternura,
Que en mucha docta obertura
Y mística sinfonía.
Y así respóndele fiel
El corazón donde llega:
Con él el alegre juega
Y el triste llora con él.
Mágico el más obediente,
Camaleón musical,
Siempre el mismo original,
Pero siempre diferente.
Eterna variación
En que hallamos por instinto
Acento propio y distinto
Para cada sensación.
.............
Y si ordenase un tirano
La abolición del bambuco,
Pronto viera cuán caduco
Es todo poder humano.

Aun es más linda, en la misma composición, la pintura de una fiesta


popular al aire libre, en que se baila el bambuco.
Era una noche de aquellas
Noches de la patria mía
Que bien pudiera ser día
Donde no hay noches como ellas.
El terciopelo mejor
Al del cielo no igualaba;
Ni estrella alguna faltaba
A la gran cita de amor.
Oíanse los bramidos
Del Cauca y sus reventones
Como enjambre de leones
Celosos y mal dormidos.
Y el aura circunvolante
Embalsamaba el lugar
De albahaca y de azahar
Y de jazmín embriagante.
Yapangas que por modelo
Las quisiera un escultor,
Giraban al resplandor
De las lámparas del cielo.
De indianas y de españolas
Las perfecciones lucían,
Tan lindas que parecían
Enamorarse ellas solas.
Bajo una gran cabellera
Un blanco busto imperial.
Y una forma amplia y cabal
Cuanto elástica y ligera.
Rica tez, mórbido pecho,
Nada de afeite ó falsía:
Que el arte no enmendaría
Lo que hizo Dios tan bien hecho.

Los versos, bien hechos también y sin afeite ni falsía como las yapangas,
siguen adelante; pero yo no puedo citarlos todos. Dejemos, pues, bailar á las
yapangas, que

Ya evitan á su mitad
Y ya le buscan festivas,
Provocadoras ó esquivas
Como la felicidad,
y cambiemos de escena. Pasemos volando, desde las orillas del Cauca á las
del Hudson, y pongámonos en la Broadway ó Calle Ancha de Nueva York.
Nuestro poeta se entusiasma más aún, si cabe, que por las yapangas, por
todas las misses yankees que por allí se pasean. Verdad es que empieza por
ensalzar á las españolas bonitas de Ambos Mundos. Ni pueden quejarse las
limeñas, en cuyos ojos dan aún los hombres culto al astro de Manco Capac,
ni las sirenas de Maracaibo, ni las sílfides de Cuba, ni las huríes de Chile,
de corazón volcánico; ni las argentinas, tremendas en toda lid; ni otras
muchas, de diversos países, á quienes el poeta, con tino, gala y primor, va
calificando. Pero todo esto se olvida, porque el hombre es ingrato, y la
sangre española es pólvora, y las yankees, que pasean en la Broadway,
forman una legión fulminante, que prende fuego á los corazones, y se los
anexiona, y quema todos los títulos de propiedad, memorias, y demás
documentos y compromisos.

Los que no me creáis, los que entre lágrimas


Eterno amor jurasteis al partir
A la que, ondeando el pañuelito, cándida
Desde la playa os quiso bendecir,
Venid, llegad, y bajo el níveo pórtico
Del imperial Saint Nicholas Hotel,
Donde se alivia el trovador nostálgico
Y se llora la ausencia última vez,
Ved desfilar el majestuoso ejército
Que anida en sus cuarteles Nueva York.....

En la pintura del tal ejército, Pombo se muestra sinceramente inspirado.


Allá van algunas estrofas, aunque sea saltando:
Para ataviar á esta legión seráfica,
Todo el mundo, Este, Oeste, Norte y Sur,
Viene á verter la copa de sus dádivas
Que puja el oro en arrogante albur.
Blondas que teje para reinas Bélgica
Realzando senos de alabastro van,
Y nido á cuellos de nevada tórtola
Da con sus chales la opulenta Iram.
Ondas de seda de Damasco espléndida,
Que el musnud no ajaría en el harem,
Barren el polvo..... haciendo aquella música
Que suspiran las aguas del Zemzem.
Y para estos cabellos, á sus náyades
Robó tan ricas perlas Panamá,
Y á sus zafíreas mariposas fúlgidas
Sus lechos de esmeraldas Bogotá.
.............
¡Ah! cada hermosa es un amable autócrata,
Ley su sonrisa, sus palabras ley,
Y una marcha triunfal entre sus súbditos
Cada excursión por la imperial Broadway.
Los fieros amos de la Gran República
Son sus siervos humildes: ¡ya se ve!
¿Quién no lo fuera de tan lindos déspotas?
¿Y quién podrá decir no lo seré?

Los versos serios de Pombo son aún más bellos que los ligeros y
jocosos. En Preludio de primavera, ni imita el poeta á nadie, ni parece que
lleva ninguna intención literaria. Se diría que canta sin querer, excitado por
sentimientos dulcísimos y por las primeras auras vernales, después de un
invierno rigoroso de Nueva York.
¡Oh qué brisa tan dulce! Va diciendo:
«Yo traeré miel al cáliz de las flores:
Y á su rico festín ya irán viniendo
Mis veraneros huéspedes cantores.»
¡Qué luz tan deliciosa! Es cada rayo
Larga mirada intensa de cariño;
Sacude el cuerpo su letal desmayo,
Y el corazón se siente otra vez niño.
Esta es la luz que rompe generosa
Sus cadenas de hielo á los torrentes
Y devuelve su plática armoniosa
Y su alba espuma á las dormidas fuentes.
Esta es la luz que pinta los jardines
Y en ricas tintas la creación retoca;
La que devuelve al rostro los carmines
Y las francas sonrisas á la boca.
.............
Al fin soltó su garra áspera y fría
El concentrado y taciturno invierno,
Y entran en comunión de simpatía
Nuestro mundo interior y el mundo externo.
Como ágil prisionero pajarillo
Se nos escapa el corazón cantando,
Y otro como él, y un verde bosquecillo
En alegre inquietud anda buscando.
.............
Tú, que aun eres feliz; tú, en cuyo seno
Preludia el corazón su Abril florido,
Vaso edenal sin gota de veneno,
Alma que ignoras decepción y olvido;
Deja, oh paloma, el nido acostumbrado
Enfrente de la inútil chimenea;
Ven á mirar el sol resucitado
Y el milagro de luz que nos rodea.
Ven á ver cómo entre su blanca y pura
Nieve, imagen de ti resplandeciente,
También á par de ti la gran Natura
Su dulce Abril con júbilo presiente.
No verás flores. Tus hermanas bellas
Luego vendrán, cuando en el campo jueguen
Los niños coronándose con ellas;
Cuando á beber su miel las aves lleguen.
V á l li i i fi it
Verás un campo azul, limpio, infinito,
Y otro á sus pies de tornasol de plata,
Donde, como en tu frente, angel bendito,
La gloria de los cielos se retrata.

En toda esta composición, de que citamos trozos, sería tan fácil cuanto
ingrata tarea señalar algunos defectos; pero todo se perdona en gracia de la
espontaneidad y del sincero, puro y profundo sentir con que está el asunto
comprendido y expresado. Lo que sobre todo es de admirar en Pombo es la
sencillez, al parecer al menos sin arte, con que dice cosas muy bellas, que
por lo mismo que están dichas tan sencillamente parecen más bellas y
penetran mejor y más hondo en el alma. En París, sin duda, aunque el poeta
no lo declara, compuso unos versos á una joven que se suicidó arrojándose
en el Sena. La sacan muerta del río y exclama el poeta:

¡Ni una burla, ni un agravio


Le hagan mente, ó tacto, ó labio!
Pensad de ella como hermanos,
Como débiles humanos;
Pensad sólo en sus angustias
Y sus manchas olvidad.
¿Qué hay en esas formas mustias
Que no implore caridad?
No hagáis honda, cruel pesquisa
Del conflicto que insumisa
La encontró con el deber:
Ya la muerte en su torrente
Llevó el fango, y solamente
Queda el oro de su ser.

Es singular que otro poeta colombiano, Hermógenes Saravia, haya


tratado muy bien, aunque por diverso estilo, un asunto semejante. Es una
actriz, en su primera juventud, María Herrera, española tal vez, que va á
Colombia y allí se envenena. Allí, como le dice el poeta:
De tu guirnalda destrozando el lazo,
Levantas ¡ay! la copa del suicida,
Y el don horrible de la amarga vida
Llorando vas á devolver á Dios.
La composición está llena de bellos sentimientos e ideas briosamente
expresados:

En el concierto de las leves auras,


En el rumor de la onda estremecida,
¿No hubo un consuelo para tu alma herida?
¿No hubo una nota para ti de amor?
¡Cuando en la alegre y bulliciosa escena
De flores coronada aparecías,
En vano tus sollozos comprimías,
Pobre proscrita de un sonado Edén!
Del pecho herido por el vil engaño
Se adivinaba la honda pesadumbre
En tu mirada, triste cual la lumbre
Que deja el sol al esconder su sien.
.............
Yo no te execro, niña infortunada,
Ya que cercada de siniestras brumas,
Cual ave herida, tus deshechas plumas
Viniste en los desiertos á dejar.

Están, por último, noble y poéticamente exigidas á las mujeres honradas


y felices la piedad y la compasión hacia la pobre suicida:

No condenéis á la infeliz criatura


Que de la muerte en el piadoso lecho,
Cruzando ya las manos sobre el pecho,
Como final recurso se adurmió.
Jamás pudierais sospechar siquiera
Todo el supremo horrible desencanto,
Todo el raudal de contenido llanto
Que amontonar su corazón debió.

Aquí pensaba yo terminar esta carta y todo lo que había de decir sobre el
Parnaso Colombiano. Las tristes poesías sobre mujeres que mueren
víctimas de un amor desventurado, me recuerdan el admirable y tremendo
canto de Olivia, de Olivero Goldsmith:

You might also like