Instant ebooks textbook Java Programming 8th Edition Joyce Farrell download all chapters
Instant ebooks textbook Java Programming 8th Edition Joyce Farrell download all chapters
https://ebookultra.com
https://ebookultra.com/download/java-
programming-8th-edition-joyce-farrell/
https://ebookultra.com/download/java-programming-7th-edition-joyce-
farrell/
ebookultra.com
https://ebookultra.com/download/programming-logic-and-design-
comprehensive-6th-edition-joyce-farrell/
ebookultra.com
https://ebookultra.com/download/introduction-to-java-programming-
brief-8th-edition-edition-y-daniel-liang/
ebookultra.com
https://ebookultra.com/download/computer-programming-for-teens-1st-
edition-mary-e-farrell/
ebookultra.com
Advanced Java Game Programming Wallace Croft
https://ebookultra.com/download/advanced-java-game-programming-
wallace-croft/
ebookultra.com
https://ebookultra.com/download/core-java-volume-1-fundamentals-8th-
ed-edition-horstmann/
ebookultra.com
https://ebookultra.com/download/java-programming-10-minute-
solutions-1st-edition-mark-watson/
ebookultra.com
https://ebookultra.com/download/killer-game-programming-in-java-1st-
edition-andrew-davison/
ebookultra.com
https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/
ebookultra.com
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
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.
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.
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.
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
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
Examine
program output
No
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.
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.
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:
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
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.
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.
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
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
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
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
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
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.
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.
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
Table 1-3 Legal but unconventional and nonrecommended 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
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. }
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.
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.
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.
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.
*
**
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
*
**
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.
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 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:
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: