Sams Teach Yourself Java in 24 Hours (8Th Ed) 8Th Edition Rogers Cadenhead - Ebook PDF
Sams Teach Yourself Java in 24 Hours (8Th Ed) 8Th Edition Rogers Cadenhead - Ebook PDF
com
https://ebookluna.com/download/sams-teach-yourself-java-
in-24-hours-8th-ed-ebook-pdf/
OR CLICK BUTTON
DOWNLOAD NOW
https://ebookluna.com/download/teach-yourself-electricity-and-
electronics-seventh-edition-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/teach-yourself-electricity-and-
electronics-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/teach-yourself-electricity-and-
electronics-6e-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/cissp-passport-ebook-pdf/
ebookluna.com
(eBook PDF) Teach: Introduction to Education 4th Edition
https://ebookluna.com/product/ebook-pdf-teach-introduction-to-
education-4th-edition/
ebookluna.com
https://ebookluna.com/download/lawries-meat-science-8th-ed-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/understanding-operating-systems-8th-ed-
ebook-pdf/
ebookluna.com
https://ebookluna.com/product/ebook-pdf-learning-to-teach-by-gloria-
latham/
ebookluna.com
https://ebookluna.com/product/ebook-pdf-java-an-introduction-to-
problem-solving-and-programming-8th-edition/
ebookluna.com
Rogers Cadenhead
SamsTeach Yourself
Java
24
in
Hours
Eighth Edition
Sams Teach Yourself Java in 24 Hours, Eighth Edition
Copyright © 2018 by Pearson Education, Inc.
ISBN-13: 978-0-672-33794-9
ISBN-10: 0-672-33794-0
PART III: Working with Information Inheriting Behavior and Attributes 160
in New Ways Overriding Methods 161
Establishing Inheritance 161
HOUR 9: Storing Information with Arrays 111 Using this and super in a Subclass 162
Creating Arrays 112 Working with Existing Objects 163
Using Arrays 113 Storing Objects of the Same Class
Multidimensional Arrays 115 in Array Lists 164
Sorting an Array 116 Looping Through an Array List 166
Counting Characters in Strings 118 Creating a Subclass 168
HOUR 10: Creating Your First Object 125 PART IV: Moving into Advanced Topics
How Object-Oriented Programming
Works 125 HOUR 13: Storing Objects in
Objects in Action 127 Data Structures 173
What Objects Are 128 Array Lists 174
Understanding Inheritance 129 Hash Maps 180
HOUR 14: Handling Errors in a Program 187 Buttons 242
Exceptions 188 Labels and Text Fields 245
Catching Exceptions in a try-catch Check Boxes 246
Block 189 Combo Boxes 247
Catching Several Different Exceptions 192 Text Areas 248
Handling Something After an Panels 251
Exception 194
Creating Your Own Component 251
Throwing Exceptions 194
Ignoring Exceptions 196 HOUR 18: Laying Out a User Interface 259
Exceptions That Don’t Need catch 197 Using Layout Managers 259
Throwing and Catching Exceptions 197 The GridLayout Manager 261
The BorderLayout Manager 262
HOUR 15: Creating a Threaded Program 203
The BoxLayout Manager 263
Threads 203
Separating Components with Insets 264
Slowing Down a Program 204
Laying Out an Application 265
Creating a Thread 204
Working with Threads 208 HOUR 19: Responding to User Input 273
The class Declaration 209 Getting Your Programs to Listen 273
Setting Up Variables 209 Setting Up Components to Be Heard 274
The Constructor 210 Handling User Events 275
Catching Errors as You Set Up URLs 211 Check Box and Combo Box Events 276
Starting the Thread 211 Keyboard Events 276
Running the Thread 212 Enabling and Disabling Components 278
Handling Mouse Clicks 213 Completing a Graphical Application 279
Displaying Revolving Links 213
Stopping a Thread 216 PART VI: Writing Internet Applications
HOUR 17: Building a Simple User HOUR 21: Using Java 9’s New
Interface 237 HTTP Client 309
Swing and the Abstract Windowing Java Modules 309
Toolkit 237 Making an HTTP Request 310
Using Components 238 Saving a File from the Web 314
Windows and Frames 238 Posting Data on the Web 317
HOUR 22: Creating Java2D Graphics 325 Creating a New Project 400
Using the Font Class 325 Creating a New Java Class 402
Using the Color Class 326 Running the Application 404
Creating Custom Colors 327 Fixing Errors 404
Drawing Lines and Shapes 328
Drawing Lines 328 APPENDIX B: Where to Go from Here:
Drawing Rectangles 329 Java Resources 407
Drawing Ellipses and Circles 330 Other Books to Consider 407
Drawing Arcs 330 Oracle’s Official Java Site 408
Baking a Pie Graph 331 Java Class Documentation 408
Other Java Websites 408
HOUR 23: Creating Minecraft Mods This Book’s Official Site 408
with Java 341 Workbench 409
Setting Up a Minecraft Server 342 Slashdot 409
Fixing Problems Running the Server 344 Other Java Weblogs 409
Connecting to the Server 346 InformIT 409
Fixing a Server Connection Problem 347 Stack Overflow 409
Creating Your First Mod 348 JavaWorld Magazine 409
Teaching Zombies to Ride Horses 356 Developer.com’s Java Directory 410
Finding All Mobs (and Killing Them) 362 Java Meetings 410
Writing a Mod that Can Build Things 366 Job Opportunities 410
HOUR 24: Writing Android Apps 375 APPENDIX C: This Book’s Website 411
Introduction to Android 375
Creating an Android App 377 APPENDIX D: Fixing a Problem with the
Exploring a New Android Project 378 Android Studio Emulator 413
Creating an App 380 Problems Running an App 413
Setting Up an Android Emulator 382 Install HAXM in Android Studio 414
Running the App 383 Install HAXM on Your Computer 415
Designing a Real App 385 Checking BIOS Settings 417
Organizing Resources 386
APPENDIX E: Fixing Package Not
Configuring the App’s Manifest File 387
Visible Errors in NetBeans 419
Designing a User Interface 388
Adding Module Info 419
Writing Java Code 390
Index 421
APPENDIXES
Your purchase of this book in any format, print or electronic, includes access to the
corresponding Web Edition, which provides several special features to help you learn:
The Web Edition can be viewed on all types of computers and mobile devices with any
modern web browser that supports HTML5.
To get access to the Web Edition of Sams Teach Yourself Java in 24 Hours, Eighth Edition, all you
need to do is register this book:
1. Go to www.informit.com/register
The Web Edition will appear under the Digital Purchases tab on your Account page.
As the author of computer books, I spend a lot of time lurking in the computer section of
bookstores, observing the behavior of readers while I’m pretending to read the latest issue of Soap
Opera Digest magazine.
Because of my research, I’ve learned that if you have picked up this book and turned to this
introduction, I only have 13 more seconds before you put it down and head to the coffee bar for
a double-tall-decaf-skim-with-two-shots-of-vanilla-hold-the-whip latte.
So I’ll keep this brief: Computer programming with Java is easier than it looks.
I’m not supposed to tell you that because thousands of programmers have used their Java
skills to get high-paying jobs in software development, server programming, and Android
app creation. The last thing any programmer wants is for the boss to know that anyone with
persistence and a little free time can learn this language, the most popular programming
language on the planet. By working your way through each of the one-hour tutorials in Sams
Teach Yourself Java in 24 Hours, you’ll be able to learn Java programming quickly.
Anyone can learn how to write computer programs, even if you can’t program a DVR. Java
is one of the best programming languages to learn because it’s a useful, powerful, modern
technology that’s embraced by companies around the world.
This book is aimed at non-programmers, new programmers who think they hate this stuff, and
experienced programmers who want to get up to speed swiftly with Java. It uses Java 9, the latest
and greatest version of the language.
Java is an enormously popular programming language because of the things it makes possible.
You can create programs that feature a graphical user interface, connect to web services, run on
an Android phone or tablet, and more.
This language turns up in some amazing places. One of them is Minecraft, the gaming
phenomenon written entirely in Java. (In this book you learn how to create Java programs that
run in that game alongside creepers and zombie pigmen!)
This book teaches Java programming from the ground up. It introduces the concepts in English
instead of jargon with step-by-step examples of working programs you will create. Spend 24
hours with this book and you’ll be writing your own Java programs, confident in your ability
2 Introduction
to use the language and learn more about it. You also will have skills that are becoming
increasingly important—such as Internet computing, graphical user interface design, app
creation, and object-oriented programming.
These terms might not mean much to you now. In fact, they’re probably the kind of thing that
makes programming seem intimidating and difficult. However, if you can use a computer to
create a photo album on Facebook, pay your taxes, or work an Excel spreadsheet, you can learn
to write computer programs by reading Sams Teach Yourself Java in 24 Hours.
NOTE
At this point, if you would rather have coffee than Java, please reshelve this book with the front
cover facing outward on an endcap near a lot of the store’s foot traffic.
HOUR 1
Becoming a Programmer
You’ve probably heard that computer programming is insanely difficult. It requires a degree in
computer science, thousands of dollars in computer hardware and software, a keen analytical
mind, the patience of Job, and a strong liking for caffeinated drinks.
Aside from the part about caffeine, you heard wrong. Programming is easier than you might
think, despite what programmers have been telling people for years to make it easier for us to
land high-paying jobs.
This is a great time to learn programming. Countless programming tools are being made
available as free downloads on the Web, and thousands of programmers distribute their work
as open source so other people can examine how the software was written, fix errors, and
contribute improvements. In a recovering economy, many companies are hiring programmers.
It’s a great time to learn Java, because the language is everywhere. Billions of mobile devices use
Android, an operating system whose apps are all written in Java. If you have an Android phone,
you’ve been enjoying the work of Java programmers every time you look up a movie, rock out
on streaming radio, or sling an antagonistic avian at a poorly built fortress of swine.
2. Bitter beginners who tried programming but hated it like Lord Voldemort hates orphaned
British schoolchildren
3. Impatient intellectuals who know another programming language and want to get up to
speed quickly on Java
4 HOUR 1: Becoming a Programmer
To achieve this goal, this book uses the English language as much as possible instead of
technical jargon or obscure acronyms. All new programming terms are thoroughly explained as
they are introduced.
If I’ve succeeded, you will finish this book with enough programming skills to be a danger to
yourself and others. You’ll be able to write programs, plunge into programming classes and
books with more confidence, and learn new languages more easily. (Programming languages, to
be clear. This book won’t help you master Spanish, Esperanto, or Klingon.)
You also will have skills with Java, the most widely used programming language on the planet.
The first hour of this book provides an introduction to programming and guidance on setting up
your computer so you can use it to write and run Java programs.
Choosing a Language
If you’re comfortable enough with a computer to prepare a nice-looking résumé, balance a
checkbook, or share your vacation photos on Instagram, you can create computer software.
The key to learning how to program is to start with the right language. The programming
language you choose often depends on the tasks you want to accomplish. Each language has
strengths and weaknesses. Back in my day, young whippersnappers, people learned to program
with the BASIC language because it was created with beginners in mind.
NOTE
The BASIC language was invented to be easy for students to learn (the B in BASIC stands for
Beginner’s). The downside to using some form of BASIC is that it’s easy to fall into sloppy program-
ming habits with the language.
The most popular language that employs BASIC today is Visual Basic, a programming language
from Microsoft that has moved far beyond its roots. VB, as it also is called, is designed for
creating programs to run on computers and mobile devices that use the Windows operating
system. Another popular language is PHP, a scripting language for creating websites. Other
widely used languages you may have heard about include C++, Ruby, Javascript, and Python.
Each of these languages has its adherents, but the most widely taught in computer science
classes at the high school and collegiate level is Java.
The Java programming language, which is offered by Oracle, is more difficult to learn than
some other languages such as VB and PHP, but it’s a great starting place for several reasons.
One advantage of learning Java is that you can use it across a variety of operating systems and
computing environments. Java programs can be desktop software, web applications, web servers,
Choosing a Language 5
Android apps, and more, running on Windows, Mac, Linux, and other operating systems. This
versatility is referenced by the ambitious early Java slogan “Write once, run anywhere.”
NOTE
Early Java programmers had a less flattering slogan: “Write once, debug everywhere.” The language
has come a long way, baby, since the first version was released in 1996.
Another important advantage is that Java requires a highly organized approach for getting
programs to work. You must be particular about how you write programs and how they store
and alter data.
When you start writing Java programs, you might not see the language’s persnickety behavior
as an advantage. You could tire of writing a program and having several errors to fix before the
program even can be run. The benefit of this extra effort is that the software you create is more
reliable, useful, and error-free.
In the coming hours, you learn all of Java’s rules and the pitfalls to avoid.
Java was invented by the Canadian computer scientist James Gosling as a better way to create
computer programs. While working at Sun Microsystems in 1991, Gosling was unhappy with the
way the C++ programming language was performing on a project, so he created a new language
that did the job better. It’s a matter of contentious debate whether Java is superior to other
programming languages, of course, but the success of the language demonstrates the strength of
his initial design. Fifteen billion devices across the world are running Java, a number so amazing
I’m going to repeat it. Fifteen billion! More than 1,000 books have been published about the
language since its introduction. (This is my twentieth.)
Regardless of whether Java is the best language, it definitely is a great language to learn. You get
your first chance to try out Java during Hour 2, “Writing Your First Program.”
Learning one programming language makes it much easier to learn subsequent languages.
Many are similar to each other, so you aren’t starting from scratch when you plunge into a
new one. For instance, many C++ and Smalltalk programmers find it fairly easy to learn Java
because Java borrows ideas from those earlier languages. Similarly, C# adopts many ideas from
Java, so it’s easier to pick up for Java programmers.
NOTE
C++ is mentioned several times this hour, so you might be tripping over the term, wondering what it
means—and how it’s pronounced. C++ is pronounced “C-Plus-Plus,” and it’s a programming language
developed by Danish computer scientist Bjarne Stroustrop at Bell Laboratories. C++ is an enhance-
ment of the C programming language, hence the Plus-Plus part of the name. Why not just call it C+?
The Plus-Plus part is a computer programming joke you’ll understand later in this book.
6 HOUR 1: Becoming a Programmer
Computer programs are made up of a list of commands the computer handles in a specific order
when the program is run. Each command is called a statement.
If your house had its own butler and you were a control freak with a Type-A personality, you
could give your servant a detailed set of instructions to follow every day, like this:
Please take care of these errands for me while I’m out asking Congress for a bailout:
Item 3: Pick up soy sauce, wasabi, and as many California sushi rolls as you can carry.
Bertie Wooster
If you tell a human butler what to do, there’s a certain amount of leeway in how your requests
are fulfilled. If California rolls aren’t available, Jeeves could bring Boston rolls home instead.
Computers don’t do leeway. They follow instructions literally. The programs that you write are
followed precisely, one instruction at a time.
The following example is a three-line computer program, written in BASIC. Take a look at it, but
don’t worry too much about what each line is supposed to mean.
1 PRINT "Hey Tom, it's Bob from the office down the hall."
2 PRINT "It's good to see you buddy, how've you been?"
3 INPUT A$
Translated into English, this program is equivalent to giving a computer the following to-do list:
Item 1: Display the message, “Hey Tom, it’s Bob from the office down the hall.”
Item 2: Ask the question, “It’s good to see you buddy, how’ve you been?”
How Programs Work 7
Ima Coder
Each line in a computer program is called a statement. A computer handles each statement in a
program in a specific order, in the same way that a cook follows a recipe or Mr. Jeeves the butler
follows the orders of Bertie Wooster. In BASIC, the line numbers are used to put the statements in
the correct order. Other languages such as Java do not use line numbers, favoring different ways
to tell the computer how to run a program.
Because of the way programs function, you can’t blame the computer when something goes
wrong as your program runs. The computer is doing exactly what you told it to do, so the blame
for any errors usually lies with the programmer.
That’s the bad news. The good news is you can’t do any permanent harm. No computers will be
injured as you learn to program in Java.
Most computer programs are written in the same way that you write an email—by typing each
statement into a text window. Some programming tools come with their own source code editor
and others can be used with any text-editing software.
When you have finished writing a computer program, you save the file to disk. Computer
programs often have their own filename extension to indicate what type of file they are. Java
programs must have the extension .java, as in Calculator.java.
NOTE
Computer programs should be prepared as text files with no special formatting. Notepad, a text
editor that comes with Windows, saves all files as unformatted text. You also can use TextEdit on
Macs or the vi editor or emacs on Linux systems to create text files without formatting. An easier
solution is coming up later this hour.
To run a program you have saved as a file, you need some help. The kind of help required
depends on the programming language you’re using. Some languages require an interpreter to
run their programs. The interpreter examines each line of a computer program and executes
that line, then proceeds to the next line. Many versions of BASIC are interpreted languages.
8 HOUR 1: Becoming a Programmer
The biggest advantage of interpreted languages is that they are faster to test. When you are
writing a BASIC program, you can try it out immediately, fix errors, and try again. The primary
disadvantage is that interpreted languages run slower than other programs. Each line has to be
translated into instructions the computer can run, one line at a time.
Other programming languages require a compiler. The compiler takes a program and translates
it into a form that the computer can understand. It also makes the program run as efficiently as
possible. The compiled program can be run directly without the need for an interpreter.
Compiled programs run more quickly than interpreted programs but take more time to test. You
have to write your program and compile the whole thing before trying it out. If you find an error
and fix it, you must compile the program again.
Java is unusual because it requires both a compiler and an interpreter. The compiler converts
the statements that make up the program into bytecode. Once this bytecode has been created
successfully, it can be run by an interpreter called the Java Virtual Machine.
The Java Virtual Machine, also called a JVM, is the thing that makes it possible for the same
Java program to run without modification on different operating systems and different kinds
of computing devices. The virtual machine turns bytecode into instructions that a particular
device’s operating system can execute.
NOTE
Java 9 introduces a new tool called JShell that acts like an interpreter, running a Java statement
right when it is typed in. JShell works by putting the statement into a Java program, compiling that
program into bytecode, and running it. This is a useful tool for learning and testing.
As you begin writing your own programs, you become well acquainted with errors. They’re a
natural part of the process. Programming errors are called bugs, a term that dates back a century
or more to describe errors in technical devices.
The process of fixing errors also has its own term: debugging.
It’s no coincidence that there are so many ways to describe errors. You get a lot of debugging
experience as you learn programming—whether you want it or not.
Choosing a Java Programming Tool 9
NOTE
One of the first computer bugs was discovered in 1947 by a team that included the American com-
puter scientist Grace Hopper. Hopper was testing a computer at Harvard when a relay malfunctioned.
The cause wasn’t a software problem—it was an actual bug! A team member debugged the com-
puter by removing a dead moth and taped it into a logbook with the note, “First actual case of bug
being found.” The bug and logbook page can be viewed at www.doncio.navy.mil/CHIPS/ArticleDetails.
aspx?id=3489.
Whenever Oracle releases a new version of Java, the first tool that supports it is the Java
Development Kit (JDK).
To create the programs in this book, you must use JDK version 9 or a programming tool that
works on top of it. The JDK is a set of free command-line tools for creating Java software. It lacks
a graphical user interface, so if you have never worked in a non-graphical environment such as
the Windows command prompt or Linux command-line interface, you will find it challenging to
use the JDK.
The NetBeans IDE, also offered for free by Oracle, is a much easier way to write and test Java
code than the JDK. NetBeans includes a graphical user interface, source code editor, user
interface designer, and project manager. It works in complement to the JDK, running it behind
the scenes, so you must have both tools on your system when you begin developing Java
programs.
Most of the programs in this book were created with NetBeans, which you can download and
install separately from the JDK. You can use other Java tools as long as they support JDK 9.
NOTE
You don’t have to use NetBeans in this book. If you can use the JDK or another tool to create,
compile, and run a program, those tasks are all that most projects require. NetBeans is covered
because for readers of past editions it has proven easier than the JDK. I use NetBeans for most of
my Java programming.
10 HOUR 1: Becoming a Programmer
In Hour 24, “Writing Android Apps,” you will use the Android Studio IDE. Google, which
created Android, recommends that free tool to Java programmers who are creating programs for
Android.
You can’t do any of that percolating if you lack a Java programming tool on your computer.
If you already have installed a tool that supports Java, you can use it to develop the tutorial
programs in the next 23 hours. However, you already should have some familiarity with how to
use the tool. Learning Java and a complex IDE at the same time can be daunting.
The recommended choice for programming as you read this book is NetBeans, which is free from
Oracle’s website at http://netbeans.org. Though NetBeans has advanced features that take time
to learn, it makes it easy to create and run simple Java applications.
To find out how to download and install NetBeans, read Appendix A, “Using the NetBeans
Integrated Development Environment.”
Summary
During this hour, you were introduced to the concept of programming a computer—giving it a
set of instructions called statements that tell it what to do. You also learned why you made a
good call choosing to teach yourself Java instead of another programming language.
You also might have downloaded and installed a Java development tool to use on the programs
you create in the hours to come.
Ask 10 programmers for the best programming language and you may get 10 answers, complete
with “my language can beat up your language” taunts and “your source code is so bloated”
jokes. Java scores highly in such arguments because it is widely adopted, extremely versatile,
and smartly designed. You can accomplish a lot with this language, and it makes learning
others a little easier.
If you are still confused about programs, programming languages, or Java in general, don’t
panic. Everything will begin to make sense in the next hour, “Writing Your First Program,” which
gently steps through the process of creating a Java program.
Workshop 11
Workshop
Q&A
Q. BASIC? C++? Smalltalk? Java? What are the names of these languages supposed to mean?
A. BASIC gets its name from an acronym: Beginner’s All-purpose Symbolic Instruction Code.
C++ is a programming language that was created to be an improvement on the C language,
which itself was an improvement of the B programming language. Smalltalk is an innovative
object-oriented language developed in the 1970s that had numerous ideas adopted by Java.
Java goes against the tradition of naming a language with an acronym or other meaningful
term. It’s just the name that Java’s developers liked the best, beating out WebRunner, Silk,
Ruby, and others. (The Ruby programming language didn’t exist back then.)
When I create my own programming language, it will be named Salsa. Everybody loves salsa.
Q. Okay, what is the lowest score ever given on Dancing with the Stars?
A. The worst dance by a celebrity contestant on the hit ABC TV show in the United States was
performed by the rapper Master P during the second season in 2006. His paso doble with
professional dancer Ashly DelGrosso scored a lowest-ever 8. Judges Len Goodman and
Bruno Tonioli scored it a 2 and judge Carrie Ann Inaba a 4.
Tonioli’s take: “It was a nightmare. You looked like a child on the mall looking for his mother.”
Goodman: “I know viewers think they’re being kind by bringing you back. They’re not. They’re
being cruel—to Ashly, to the judges.”
Inaba: “I actually thought that that was your best dancing.”
Master P only trained 20 hours for the show, compared to 130 for the other contestants at
that point in the season. He also refused to wear dancing shoes and performed in basket-
ball sneakers. The dance was his last before being voted off.
The dance can be seen on YouTube, where one commenter writes, “Thumbs up if you’re
watching this just to see the 2 paddle.”
On Dancing with the Stars internationally, reality TV star Farmer Dave Graham got the lowest
possible score—a 1 from all four judges for a total of 4—in Australia in 2007. He shared
the performance on his YouTube account, writing, “Perhaps not the best claim to fame, but
you take your world records where you can.”
12 HOUR 1: Becoming a Programmer
Quiz
Test your knowledge of the material covered in this hour by answering the following questions.
1. Which of the following is NOT a reason that people think computer programming is painfully
difficult?
A. Programmers spread that rumor to improve our employment prospects.
B. Jargon and acronyms are all over the place.
C. People who find programming too difficult are eligible for a government bailout.
2. What kind of tool runs a computer program by figuring out one line at a time?
A. A slow tool
B. An interpreter
C. A compiler
3. Why did James Gosling hole up in his office and create Java?
A. He was unhappy with the language he was using on a project.
B. His rock band wasn’t getting any gigs.
C. When you can’t visit YouTube at work, the Internet is pretty dull.
Answers
1. C. Computer book authors didn’t get a bailout either.
2. B. Interpreters interpret one line at a time. Compilers figure out the instructions beforehand
so the program can run faster.
3. A. He was frustrated with C++. Back in 1991 when he created Java, YouTube was the place
that held YouToothpaste.
Activities
If you’d like to better introduce yourself to the subjects of Java and computer programming, do the
following activities:
u To learn more about why to learn Java, read this Oracle University blog post:
https://blogs.oracle.com/oracleuniversity/10-reasons-why-you-should-consider-learning-java.
u Using English sentences, write a set of instructions to convert a temperature from Celsius
to Fahrenheit. Break the instructions into as many short one-sentence lines as you can.
To see solutions to the activities at the end of each hour, visit the book’s website at
www.java24hours.com.
HOUR 2
Writing Your First Program
During this hour, you create your first Java program by entering it into a text editor. When that’s
done, you save the program, compile it, and test it out. Then you break it on purpose and fix it
again, just to show off.
With most programming languages, computer programs are written by entering text into a text
editor (also called a source code editor). Some programming languages come with their own
editor. NetBeans includes its own editor for writing Java programs.
Java programs are plain text files without any special formatting, such as centered text or
boldface text. The NetBeans source code editor functions like a simple text editor with some
useful enhancements for programmers. Text turns different colors as you type to identify
different elements of the language. NetBeans also indents lines properly and provides helpful
programming documentation inside the editor.
14 HOUR 2: Writing Your First Program
Because Java programs are text files, you can open and edit them with any text editor. You could
write a Java program with NetBeans, open it in Windows Notepad and make changes, and open
it again later in NetBeans without any problems.
To prepare for the first programming project in NetBeans, if you haven’t already done so, create
a new project called Java24 by following these steps:
1. Choose the menu command File, New Project. The New Project dialog opens.
2. Choose the project category Java and the project type Java Application and then click
Next.
3. Enter Java24 as the project’s name. (If you created a project with this name previously,
you see the error message “Project folder already exists and is not empty.”)
5. Click Finish.
The Java24 project is created in its own folder. You can use this project for the Java programs you
write as you progress through this book.
The Java24 project appears in the Projects pane next to a coffee cup icon and a + sign that can
be expanded to see the files and folders that the project contains.
To add a new Java program to the currently open project, choose File, New File. The New File
Wizard opens, as shown in Figure 2.1.
Beginning the Program 15
FIGURE 2.1
The New File Wizard.
The Categories pane lists the different kinds of Java programs you can create. Click the Java
folder in this pane to see the file types that belong to this category. For this first project, choose
the Empty Java File type (near the end in the File Types pane) and click Next.
A New Empty Java File dialog opens. Follow these steps to begin writing the program:
3. Click Finish.
So you can begin working right away on your program, an empty file named Saluton.java
opens in the source code editor. Using the editor, begin your Java programming career by
entering each line from Listing 2.1. These statements are called the program’s source code.
CAUTION
Don’t enter the line number and colon at the beginning of each line—these are used in this book to
reference specific line numbers.
16 HOUR 2: Writing Your First Program
Make sure to capitalize everything exactly as shown, and use your spacebar or Tab key to insert
the blank spaces in front of Lines 4–6. When you’re done, choose File, Save to save the file.
At this point, Saluton.java contains the bare bones of a Java program. You will create many
programs that start exactly like this one, except for the word Saluton on Line 3. This word
represents the name of your program and changes with each program you write. Line 5 should
make sense to you, because it’s a sentence in actual English. The rest is probably new to you.
A package is a way to group Java programs together. This line tells the computer to make
com.java24hours the package name of the program.
Translated into English, it means, “Computer, give my Java program the name Saluton.”
As you might recall from Hour 1, each instruction you give a computer is called a statement. The
class statement is the way you give your computer program a name. It’s also used to determine
other things about the program, as you will see later. The significance of the term class is that
Java programs also are called classes.
In this example, the program name Saluton matches the document’s filename, Saluton.
java. A Java program must have a name that matches the first part of its filename—the portion
before the “.” period character—and should be capitalized the same way.
If the program name doesn’t match the filename, you get an error when you try to compile
some Java programs, depending on how the class statement is being used to configure the
program.
Beginning the Program 17
This line tells the computer, “The main part of the program begins here.” Java programs are
organized into different sections, so there needs to be a way to identify the part of a program
that is executed first when the program is run.
The main statement is the entry point to most Java programs. The exceptions are applets,
programs that are run on a web page by a web browser; servlets, programs run by a web server;
and apps, programs run by a mobile device.
Most programs you write during upcoming hours of this book use main as their starting point.
That’s because you run them directly on your computer. Applets, apps, and servlets are run
indirectly by another program or device.
To differentiate them from these other types, the programs that you run directly are called
applications.
These groupings are called blocks. In Listing 2.1, the opening bracket on Line 3 is associated with
the closing bracket on Line 7, which makes your entire program a block. You use brackets in this
way to show the beginning and end of a program.
Blocks can be located inside other blocks (just as parentheses are used in this sentence (and a
second set is used here)). The Saluton program has brackets on Line 4 and Line 6 that establish
another block. This block begins with the main statement. The lines inside the main statement’s
block will be run when the program begins.
TIP
NetBeans can help you figure out where a block begins and ends. Click one of the brackets in the
source code of the Saluton program. The bracket you clicked turns yellow along with its corre-
sponding bracket. The Java statements enclosed within the two yellow brackets are a block. This tip
is not that useful on a short program like Saluton, but as you write much longer programs, it helps
you avoid looking like a blockhead.
18 HOUR 2: Writing Your First Program
The following statement is the only thing located inside the block:
// My first Java program goes here
This line is a placeholder. The // at the beginning of the line tells the computer to ignore this
line because it was put in the program solely for the benefit of humans who are looking at the
source code. Lines that serve this purpose are called comments.
Right now, you have written a complete Java program. It can be compiled, but if you run it,
nothing happens. The reason is that you haven’t told the computer to do anything yet. The
main statement block contains only a single comment, which is ignored by the computer. You
must add some statements inside the opening and closing brackets of the main block.
This statement tells the computer to store the text “Saluton mondo!” in a variable called
greeting.
In a Java program, you must tell the computer what type of information a variable will
hold. In this program, greeting is a string—a line of text that can include letters, numbers,
punctuation, and other characters. Putting String in the statement sets up the variable to hold
string values.
When you enter this statement into the program, a semicolon must be included at the end of
the line. Semicolons end each statement in a Java program. They’re like the period at the end
of a sentence. The computer uses them to determine when one statement ends and the next one
begins.
Putting only one statement on each line makes a program more understandable (for us
humans).
Insert another blank line in the Saluton program after the String greeting = "Saluton
mondo!" statement. Use that empty space to enter the following statement:
System.out.println(greeting);
This statement tells the computer to display the value stored in the greeting variable. The
System.out.println statement makes the computer display information on the system
output device—your monitor.
When the computer runs this program, it executes each of the statements in the main statement
block on Lines 5 and 6. Listing 2.3 shows what the program would look like if it was written in
the English language instead of Java.
Listing 2.4 shows what the program would look like if written in Klingon, the language of the
warrior race from Star Trek.
NetBeans compiles programs automatically as they are saved. If you typed everything as shown
in Listing 2.2, the program compiles successfully.
A compiled version of the program, a new file called Saluton.class, is created. All Java
programs are compiled into class files, which are given the file extension .class. A Java
program can be made up of several classes that work together, but in a simple program such as
Saluton only one class is needed.
The compiler turns Java source code into bytecode, a form that can be run by the Java Virtual
Machine (JVM).
NOTE
The Java compiler speaks up only when there’s an error to complain about. If you compile a program
successfully without any errors, nothing happens in response.
This is admittedly a bit anticlimactic. When I was starting out as a Java programmer, I was hoping
successful compilation would be met with a grand flourish of celebratory horns.
Fixing Errors
As you compose a program in the NetBeans source editor, errors are flagged with a red alert icon
to the left of the editor pane, as shown in Figure 2.2.
Fixing Errors 21
Alert Icon
FIGURE 2.2
Spotting errors in the source editor.
The icon appears on the line that triggered the error. You can click this icon to display an error
dialog that explains the compiler error with these details:
Here’s an example of an error dialog you might see when compiling the Saluton program:
cannot find symbol.
symbol : variable greting
location: class Saluton
The error message is the first line of the dialog: “cannot find symbol.” These messages often can
be confusing to new programmers. When the error message doesn’t make sense to you, don’t
spend much time trying to figure it out. Instead, look at the line where the error occurred and
check for the most obvious causes.
For instance, can you determine what’s wrong with the following statement?
System.out.println(greting);
22 HOUR 2: Writing Your First Program
The error is a typo in the variable name, which should be greeting instead of greting.
(Add this typo on purpose in NetBeans to see what happens.)
If you get error dialogs when creating the Saluton program, double-check that your program
matches Listing 2.2 and correct any differences you find. Make sure that everything is capitalized
correctly and all punctuation marks such as {,}, and ; are included.
Often, a close look at the line identified by the error dialog is enough to reveal the error
(or errors) that need to be fixed.
TIP
This book’s official website at www.java24hours.com includes source files for all programs you
create. If you can’t find any typos or other reasons for errors in the Saluton program but there are
still errors, go to the book’s website and download Saluton.java from the Hour 2 page. Try to run
that file instead.
FIGURE 2.3
Running your first Java program.
If you see the text “Saluton Mondo!” you have just written your first working Java program! Your
computer has just greeted the world—a tradition in the computer programming field that’s as
important to many of us as energy drinks, short-sleeved dress shirts, and League of Legends.
You might be asking yourself why “Saluton mondo!” is a traditional greeting. The phrase means
“Hello world!” in Esperanto, an artificial language created by Ludwig Zamenhof in 1887 to
facilitate international communication.
It’s only a traditional greeting in the sense that I’m trying to start that tradition.
Random documents with unrelated
content Scribd suggests to you:
This doubt, as my Northern friends well know, for I had habitually
assumed the opposite, in all previous discussions of the slavery
question, was unexpected and painful to me. I resisted it long, and it
was not till I had been more than twelve months in the South, with
my attention constantly fixed upon the point, that I ceased to
suspect that the circumstances which brought me to it were
exceptional and deceptive. It grew constantly stronger with every
opportunity I had of observing the condition, habits, and character
of slaves whom I could believe to present fair examples of the
working of the system with the majority of those subject to it upon
the large plantations.
The frequency with which the slaves use religious phrases of all
kinds, the readiness with which they engage in what are deemed
religious exercises, and fall into religious ecstacies, with the crazy,
jocular manner in which they often talk of them, are striking and
general characteristics. It is not at all uncommon to hear them refer
to conversations which they allege, and apparently believe
themselves to have had with Christ, the apostles, or the prophets of
old, or to account for some of their actions by attributing them to
the direct influence of the Holy Spirit, or of the devil. It seems to me
that this state of mind is fraught with more danger to their masters
than any to which they could possibly have been brought by general
and systematic education, and by the unrestricted study of the Bible,
even though this involved what is so much dreaded, but which is, I
suspect, an inevitable accompaniment of moral elevation, the birth
of an ambition to look out for themselves. Grossly ignorant and
degraded in mind, with a crude, undefined, and incomplete system
of theology and ethics, credulous and excitable, intensely
superstitious and fanatical, what better field could a cunning
monomaniac or a sagacious zealot desire in which to set on foot an
appalling crusade?
The African races, compared with the white, at least with the
Teutonic, have greater vanity or love of approbation, a stronger
dramatic and demonstrative character, more excitability, less exact or
analytic minds, and a nature more sensuous, though (perhaps from
want of cultivation) less refined. They take a real pleasure, for
instance, such as it is a rare thing for a white man to be able to feel,
in bright and strongly contrasting colours, and in music, in which
nearly all are proficient to some extent. They are far less adapted for
steady, uninterrupted labour than we are, but excel us in feats
demanding agility and tempestuous energy. A Mississippi steamboat
manned by negro deck-hands will wood up a third quicker than one
manned by the same number of whites; but white labourers of equal
intelligence and under equal stimulus will cut twice as much wood,
split twice as many rails, and hoe a third more corn in a day than
negroes. On many plantations, religious exercises are almost the
only habitual recreation not purely sensual, from steady dull labour,
in which the negroes are permitted to indulge, and generally all
other forms of mental enjoyment are discouraged. Religious
exercises are rarely forbidden, and a greater freedom to individual
impulse and talent is allowed while engaged in them than is ever
tolerated in conducting mere amusements or educational exercises.
Naturally and necessarily all that part of the negro’s nature which is
otherwise suppressed, bursts out with an intensity and vehemence
almost terrible to witness, in forms of religious worship and
communion; and a “profession” of piety which it is necessary to
make before one can take a very noticeable part in the customary
social exercises, is almost universal, except on plantations where the
ordinary tumultuous religious meetings are discouraged, or in towns
where other recreations are open to the slaves.[29]
Upon the value of the statistics of “coloured church membership,”
which are often used as evidence that the evils of slavery are fully
compensated by its influence in Christianizing the slaves, some light
is thrown by the following letter from the white pastor of a town
church in that part of the South in which the whites are most
numerous, and in which the negroes enjoy the most privileges.
“To the Editor of the Richmond (Virginia) Religious Herald.
* * * “The truth is, the teachings of the pulpit (at least
among Baptists) have nothing to do with the matter. Let
me furnish a case in proof. Of two churches which the
writer serves, his immediate predecessor was pastor for
about twenty-five years. It would be only necessary to
give his name, to furnish the strongest and most
satisfactory assurance that nothing which ever fell from
his lips could be construed into the support of ignorance,
superstition, or fanaticism. During the five or six years I
have served these churches, whatever may have been my
errors and failings (and I am ready to admit that they
have been numerous and grievous enough, in all
conscience), I know I have never uttered a sentiment
which could be tortured into the support of the
superstitions prevailing among the coloured people. And
yet in both these churches, the coloured members are as
superstitious and fanatical as they are elsewhere. Indeed,
this was to be expected, for I certainly claim no superiority
over my brethren in the ministry, and I am satisfied that
many of them are far better qualified than I am to expose
error and to root out superstition. This state of things,
then, is not due to the teachings of the pulpit. Nor is it the
result of private instructions by masters. Indeed, these
last have been afforded so sparingly, till within a few years
since, that they could produce but little effect of any sort.
And, besides, those who own servants, and are willing to
teach them, are far too intelligent to countenance
superstition in any way. I repeat the inquiry, then, Why is
it that so many of our coloured members are ignorant,
superstitious, and fanatical? It is the effect of instructions
received from leading men among themselves, and the
churches are responsible for this effect, in so far as they
receive into fellowship those who have listened to these
instructions, ground their hopes upon them, and guide
their lives by them. Whatever we may say against
superstition, so long as we receive into our churches those
who are its slaves, they will believe that we think them
Christians; and naturally relying on our judgment as
expressed by their reception, they will live deluded, and
die but to be lost.
“But some one will say, ‘We never receive coloured
persons when they manifest these superstitions—when
they talk of visions, dreams, sounds,’ etc. This is right as
far as it goes. In every such case they should be rejected.
But superstition of a fatal character often exists where
nothing is said about dreams and visions. It is just as
fatally superstitious to trust in prayers and feelings, as in
dreams and visions. And this is the sort of superstition
which now prevails among the coloured people. They have
found that sights and sounds will not answer before the
whites, and now (reserving these, perhaps, for some
chosen auditory of their own colour), they substitute
prayers and feelings. In illustration permit me to record, in
no spirit of levity, the stereotyped experience which
generally passes current, and, in ninety-nine cases out of
a hundred, introduces the coloured candidate into the
church. The pastor is informed, by one of the ‘coloured
deacons,’ that a man wishes to offer to the church with a
view to baptism. The fact is announced, a meeting of the
church called, and the candidate comes forward.
“Pastor.—‘Well, John, tell me in a few words, in your own
way, your religious experience. What have been your
feelings, and what are your present hopes and purposes?’
“John.—‘I see other people trying, and so I thought I
would try too, as I had a soul to save. So I went to pray,
and the more I pray the wus I felt; so I kept on praying,
and the more I pray the wus I felt. I felt heavy—I felt a
weight—and I kept on praying till at last I felt light—I felt
easy—I felt like I loved all Christian people—I felt like I
loved everybody,’
“Now this is positively the whole of the experience which
is generally related by coloured candidates for baptism.
There may be a slight variation of expression now and
then, but the sense is almost invariably the same. On this
experience, hundreds have been received into the
churches—I I have received many upon it myself. I am
somewhat curious to know how many of the seventy,
baptized by my good brother Bagby, told this tale. I’ll
warrant not less than fifty. Have any of us been right in
receiving persons on such a relation as this? In the whole
of it, there is not one word of gospel, not one word about
sorrow for sin, not one word about faith, not one word
about Christ. I know that all these things are subsequently
brought out by questions; and were this not the case, I
have no idea that the candidate would be in any instance
received. But that these questions may be understood,
they are made necessarily ‘leading questions,’ such as
suggest their answers; and consequently these answers
are of comparatively little value. * * * I am aware that,
as brother Bagby suggests, private instructions by masters
have been too much neglected. But these can accomplish
but little good, so long as they are counteracted by the
teachings of leading coloured members, in whose views,
after all our efforts, the coloured people will have most
confidence.”
Not the smallest suggestion, I observe, in all the long article from
which the above is derived, is ventured, that the negroes are
capable of education, or that their religious condition would improve
if their general enlightenment of mind were not studiously
prevented.
“I have often heard the remark made,” says the Rev. C. C. Jones, in
a treatise on the “Religious Instruction of Slaves,” printed at
Savannah, Georgia, 1842, “by men whose standing and office in the
churches afforded them abundant opportunity for observation, that
the more they have had to do with coloured members, the less
confidence they have been compelled to place in their Christian
professions.”
A portion of a letter written for publication by the wife of the pastor
of a church in the capital of Alabama, given below, naïvely reveals
the degree of enlightenment prevailing among the Christianized
Africans at a point where their means of instruction are a thousand
times better than they are on an average throughout the country.
“Having talked to him seriously, and in the strongest light
held up to him the enormity of the crime of forsaking his
lawful wife and taking another, Colly replied, most
earnestly, and not taking in at all the idea of guilt, but
deeply distressed at having offended his master:
“‘Lor, Massa Harry, what was I to do, sir? She tuk all I
could git, and more too, sir, to put on her back; and tellin’
de truf, sir, dress herself as no poor man’s wife hav’ any
right to. I ’monstrated wid her, massa, but to no purpose;
and den, sir, w’y I jis did all a decent man could do—lef
her, sir, for some oder nigger better off ’an I is.’
“’Twas no use. Colly could not be aroused to
conscientiousness on the subject.
“Not one in a thousand, I suppose, of these poor
creatures have any conception whatever of the sanctity of
marriage; nor can they be made to have; yet, strange to
say, they are perfect models of conjugal fidelity and
devotion while the temporary bondage lasts. I have
known them to walk miles after a hard day’s work, not
only occasionally, but every night, to see the old woman,
and cut her wood for her, etc. But to see the coolness with
which they throw off the yoke is diverting in the extreme.
“I was accosted one morning in my husband’s study by a
respectable-looking negro woman, who meekly inquired if
Mr. B. was at home.
“‘No, he is not. Is it anything particular you want?—
perhaps I can help you.’
“‘Yes, ma’am; it’s partickler business wid himself.’
“Having good reason to believe it was the old story of a
‘mountain in labour and brought forth a mouse,’ I pressed
the question, partly to save my better half some of the
petty annoyances to which he was almost daily subjected
by his sable flock, and partly, I own, to gratify a becoming
and laudable curiosity, after all this show of mystery.
Behold the answer in plain English, or rather nigger
English.
“‘I came to ask, please ma’am, if I might have another
husband.’
“Just at this crisis the oracle entered, who, having
authority by a few spoken words, to join together those
whom no man may put asunder, these poor people simply
imagine him gifted with equal power to annul the contract
with a breath of his mouth.
“I was heartily amused to find that this woman was really
no widow, as I had supposed, but merely from caprice, or
some reason satisfactory to herself, no doubt, took it into
her head to drop her present spouse and look out for
another. The matter was referred to the ‘Quarterly
Conference,’ where an amusing scene occurred, which
resulted in the discomfiture of the disconsolate petitioner,
who returned to her home rather crest-fallen.
“These Quarterly Conference debates, for flights of
oratory, and superlativeness of diction, beggar all
description. Be it understood, that negroes, as a class,
have more ‘business’ to attend to than any other people—
that is, provided they can thereby get a chance to ‘speak
’fore white folks.’ To make a speech is glory enough for
Sambo, if he happen to have the ‘gift of gab;’ and to
speak before the preacher is an honour unparalleled. And,
by the way, if the preacher have will and wit enough to
manage and control the discordant elements of a negro
Quarterly Conference, he will be abundantly rewarded
with such respect and gratitude as a man seldom may lay
claim to. They account him but a very little ‘lower than the
angels;’ and their lives, their fortunes, and their sacred
honour, are equally his at command. But wo be to the
unfortunate pastor who treats them with undue
indulgence; they will besiege him daily and hourly with
their petty affairs, and their business meetings will be
such a monopoly of his time and patience, that but for the
farcical character of the same, making them more like
dramatic entertainments than sober realities, he would be
in despair. Far into the short hours of morning will they
speechify and magnify, until nothing but the voice of stern
authority, in a tone of command not to be mistaken, can
stop the current.”
An Alabama gentleman whom I questioned with regard to the
chastity of the so-called pious slaves, confessed, that four negro
women had borne children in his own house, all of them at the time
members in good standing of the Baptist church, and none of them
calling any man husband. The only negro man in the house was also
a church member, and he believed that he was the father of the four
children. He said that he did not know of more than one negro
woman whom he could suppose to be chaste, yet he knew hosts
who were members of churches.[30]
A Northern clergyman who had been some years in another town in
Alabama, where also the means of instruction offered the slaves
were unusually good, answered my inquiry, What proportion of the
coloured members of the churches in the town had any clear
comprehension of the meaning of the articles of faith which they
professed? “Certainly not more than one in seven.”
The acknowledgment that “the coloured people will, in spite of all
our efforts, have more confidence in the views of leading coloured
members,” made by the writer of the letter taken from the “Religious
Herald,” has been generally made by all clergymen at the South with
whom I have conversed. A clergyman of the Episcopal Church, of
very frank and engaging manners, said in my presence that he had
been striving for seven years to gain the confidence of the small
number of Africans belonging to his congregation, and with extreme
humility he had been lately forced to acknowledge that all his
apparent success hitherto had been most delusive. When asked how
he accounted for it, he at once ascribed it to the negro’s habitual
distrust of the white race, and in discussing the causes of this
distrust he asked how, if he pretended to believe that the Bible was
the Word of God, addressed equally to all the human race, he could
explain to a negro’s satisfaction why he should fear to put it directly
into his hands and instruct him to read it and judge for himself of his
duty? A planter present, a member of his church, immediately
observed that these were dangerous views, and advised him to be
cautious in the expression of them. The laws of the country forbade
the education of negroes, and the church laws, and he trusted
always would remain, the bulwark of the laws. The clergyman
replied that he had no design to break the laws, but he must say
that he considered that the law which withheld the Bible from the
negro was unnecessary and papistical in character.[31]
The “Methodist Protestant,” a religious newspaper edited by a
clergyman, in Maryland, where the slave population is to the free
only in the ratio of one to twenty-five, lately printed an account of a
slave auction in Java (translated from a Dutch paper), at which the
father of a slave family was permitted to purchase his wife and
children at a nominal price, owing to the humanity of the spectators.
The account concluded as follows:—
“It would be difficult to describe the joy experienced by
these slaves on hearing the fall of the hammer which thus
gave them their liberty; and this joy was further
augmented by the presents given them by numbers of the
spectators, in order that they might be able to obtain a
subsistence till such time as they could procure
employment.
“These are the acts of a noble generosity that deserves to
be remembered, and which, at the same time, testify that
the inhabitants of Java begin to abhor the crying injustice
of slavery, and are willing to entertain measures for its
abolition.”
To give currency to such ideas, even in Maryland, would be fatal to
what ministers call their “influence,” and which they everywhere
value at a rather dangerous estimate; accordingly, in the editorial
columns prominence is given to the following salve to the outraged
sensibilities of the subscribers:
“SLAVE AUCTION IN JAVA.
“A brief article, with this head, appears on the fourth page
of our paper this week. It is of a class of articles we never
select, because they are very often manufactured by
paragraphists for a purpose, and are not reliable. It was
put in by our printer in place of something we had marked
out. We did not see this objectionable substitute until the
outside form was worked off, and are therefore not
responsible for it.”[32]
The habitual caution imposed on clergymen and public teachers
must, and obviously does have an important secondary effect,
similar to that usually attributed by Protestants to papacy, upon the
minds of all the people, discountenancing and retarding the free and
fearless exercise of the mind upon subjects of a religious or ethical
nature, and the necessity of accepting and apologizing for the
exceedingly low morality of the nominally religious slaves, together
with the familiarity with this immorality which all classes acquire,
renders the existence of a very elevated standard of morals among
the whites almost an impossibility.[33]
In spite of the constant denunciations by the Southern newspapers,
of those who continued to patronize Northern educational
institutions, I never conversed with a cultivated Southerner on the
effects of slavery, that he did not express a wish or intention to have
his own children educated where they should be free from
demoralizing association with slaves. That this association is almost
inevitably corrupting and dangerous, is very generally (I may say,
excepting by the extremest fanatics of South Carolina, universally)
admitted. Now, although the children of a few wealthy men may, for
a limited period, be preserved from this danger, the children of the
million cannot be. Indeed it requires a man of some culture, and
knowledge of the rest of the world, to appreciate the danger
sufficiently to guard at all diligently against it. If habitual intercourse
with a hopelessly low and immoral class is at all bad in its effects on
young minds, the people of the South are, as a people, educated
subject to this bad influence, and must bear the consequences. In
other words, if the slaves must not be elevated, it would seem to be
a necessity that the citizens should steadily degenerate.
Change and grow more marked in their peculiarities with every
generation, they certainly do, very obviously. “The South” has a
traditional reputation for qualities and habits in which I think the
Southern people, as a whole, are to-day more deficient than any
other nation in the world. The Southern gentleman, as we ordinarily
conceive him to be, is as rare a phenomenon in the South at the
present day as is the old squire of Geoffry Crayon in modern
England. But it is unnecessary to argue how great must be the
influence, upon people of a higher origin, of habitual association
with a race systematically kept at the lowest ebb of intellect and
morals. It has been elaborately and convincingly described by Mr.
Jefferson, from his personal experience and observation of his
neighbours. What he testified to be the effect upon the Virginians, in
his day, of owning and associating with slaves, is now to be
witnessed to a far greater and more deplorable extent throughout
the whole South, but most deplorably in districts where the slave
population predominates, and where, consequently, the action of
slavery has been most unimpeded.[34]
What proportion of the larger cotton plantations are resided upon by
their owners, I am unable to estimate with confidence. Of those
having cabin accommodations for fifty slaves each, which came
under my observation from the road, while I was travelling through
the rich cotton district bordering the Mississippi river, I think more
than half were unprovided with a habitation which I could suppose
to be the ordinary residence of a man of moderate wealth. I should
judge that a large majority of all the slaves in this district, were left
by their owners to the nearly unlimited government of hireling
overseers the greater part of the time. Some of these plantations are
owned by capitalists, who reside permanently and constantly in the
North or in Europe. Many are owned by wealthy Virginians and
Carolinians, who reside on the “show plantations” of those States—
country seats, the exhausted soil of which will scarcely produce
sufficient to feed and clothe the resident slaves, whose increase is
constantly removed to colonize these richer fields of the West.
A still larger number are merely occasional sojourning places of their
owners, who naturally enough prefer to live, as soon as they can
afford to do so, where the conveniences and luxuries belonging to a
highly civilized state of society are more easily obtained than they
can ever be in a country of large plantations. It is rare that a
plantation of this class can have a dozen intelligent families residing
within a day’s ride of it. Any society that a planter enjoys on his
estate must, therefore, consist in a great degree of permanent
guests. Hence the name for hospitality of wealthy planters. A large
plantation is necessarily a retreat from general society, and is used
by its owner, I am inclined to think, in the majority of cases, in
winter, as Berkshire villas and farms are in summer by rich people of
New York and Boston. I have never been on a plantation numbering
fifty field-hands, the owner of which was accustomed to reside
steadily through the year upon it. Still I am aware that there are
many such, and possibly it is a minority of them who are regularly
absent with their families from their plantations during any
considerable part of the year.
The summer visitors to our Northern watering places, and the
European tourists, from the South, are, I judge, chiefly of the
migratory, wealthy class. Such persons, it is evident are much less
influenced in their character and habits, by association with slaves,
than any other at the South.
The number of the very wealthy is, of course, small, yet as the chief
part of the wealth of these consists in slaves, no inconsiderable
proportion of all the slaves belong to men who deputize their
government in a great measure to overseers. It may be computed,
from the census of 1850, that about one half the slaves of Louisiana
and one third that of Mississippi, belong to estates of not less than
fifty slaves each, and of these, I believe, nine-tenths live on
plantations which their owners reside upon, if at all, but transiently.
The number of plantations of this class, and the proportion of those
employed upon them to the whole body of negroes in the country, is
as I have said, rapidly increasing. At the present prices of cotton the
large grower has such advantages over the small, that the owner of
a plantation of fifty slaves, favourably situated, unless he lives very
recklessly, will increase in wealth so rapidly and possess such a
credit that he may very soon establish or purchase other plantations,
so that at his death his children may be provided for without
reducing the effective force of negroes on any division of his landed
estate. The excessive credit given to such planters by negro dealers
and tradesmen renders this the more practicable. The higher the
price of cotton the higher is that of negroes, and the higher the price
of negroes the less is it in the power of men of small capital to buy
them. Large plantations of course pay a much larger per centage on
the capital invested in them than smaller ones; indeed the only
plausible economical defence of slavery is simply an explanation of
the advantages of associated labour, advantages which are
possessed equally by large manufacturing establishments in which
free labourers are brought together and employed in the most
effective manner, and which I can see no sufficient reason for
supposing could not be made available for agriculture did not the
good results flowing from small holdings, on the whole,
counterbalance them. If the present high price of cotton and the
present scarcity of labour at the South continues, the cultivation of
cotton on small plantations will by-and-by become unusual, for the
same reason that hand-loom weaving has become unusual in the
farm houses of Massachusetts.
But whatever advantages large plantations have, they accrue only to
their owners and to the buyers of cotton; the mass of the white
inhabitants are dispersed over a greater surface, discouraged and
driven toward barbarism by them, and the blacks upon them, while
rapidly degenerating from all that is redeeming in savage-life, are, it
is to be feared, gaining little that is valuable of civilization.
In the report of the Grand Jury of Richland District, South Carolina,
in eighteen hundred and fifty-four, calling for a re-establishment of
the African slave trade,[35] it is observed: “As to the moralty of this
question, it is scarcely necessary for us to allude to it; when the fact
is remarked that the plantations of Alabama, Mississippi, Louisiana,
and Texas have been and are daily settled by the removal of slaves
from the more northern of the Slave States, and that in consequence
of their having been raised in a more healthy climate and in most
cases trained to pursuits totally different, the mortality even on the
best-ordered farms is so great that in many instances the entire
income is expended in the purchase of more slaves from the same
source in order to replenish and keep up those plantations, while in
every case the condition of the slave, if his life is spared, is made
worse both physically and morally. * * * And if you look at the
subject in a religious point of view, the contrast is equally striking,
for when you remove a slave from the more northern to the more
southern parts of the slaveholding States, you thereby diminish his
religious opportunities.”
I believe that this statement gives an exaggerated and calumnious
report of the general condition of the slaves upon the plantations of
the States referred to—containing, as they do, nearly one half of the
whole slave population of the South—but I have not been able to
resist the conviction that in the districts where cotton is now grown
most profitable to the planters, the oppression and deterioration of
the negro race is much more lamentable than is generally supposed
by those who like myself have been constrained, by other
considerations, to accept it as a duty to oppose temperately but
determinately the modern policy of the South, of which this is an
immediate result. Its effect on the white race, I still consider to be
infinitely more deplorable.
CHAPTER VI.
SLAVERY AS A POOR-LAW SYSTEM.
In the year 1846 the Secretary of the Treasury of the United States
addressed a circular of inquiries to persons engaged in various
businesses throughout the country, to obtain information of the
national resources. In reply to this circular, forty-eight sugar-
planters, of St. Mary’s Parish, Louisiana, having compared notes,
made the following statement of the usual expenses of a plantation,
which might be expected to produce, one year with another, one
hundred hogsheads of sugar:—
Household and family expenses $1,000
Overseer’s salary 400
Food and clothing for 15 working hands, at $30 450
Food and clothing for 15 old negroes and children, at 225
$15
1½ per cent. on capital invested (which is about 600
$40,000), to keep it in repair
2,675
50 hogsheads sugar, at 4 cents per $2,000
pound (net proceeds)
25 hogsheads sugar, at 3 cents per 750
pound (net proceeds)
25 hogsheads sugar, at 2 cents per 500
pound (net proceeds)
4,000 gallons of molasses, at 10 cents 400
3,650
Leaving a profit of $975
Another gentleman furnished the following estimate of the expenses
of one of the larger class of plantations, working one hundred
slaves, and producing, per annum, four to five hundred hogsheads
of sugar:—
Overseer $1,500
Physician’s attendance (by contract, $3 a head, of all 300
ages)
Yearly repairs to engine, copper work, resetting of 900
sugar kettles, etc., at least
Engineer, during grinding season 200
Pork, 50 pounds per day—say, per annum, 90 1,080
hogsheads, at $12
Hoops 80
Clothing, two full suits per annum, shoes, caps, hats, 1,500
and 100 blankets, at least $15 per slave
Mules or horses, and cattle to replace, at least 500
Implements of husbandry, iron, nails, lime, etc., at 1,000
least
Factor’s commission, 2½ per cent. 500
$7,560
(It should be noticed that in this estimate the working force is
considered as being equal, in first-class hands, to but one-third of
the whole number of slaves.) — In the report of an Agricultural
Society, the work of one hand, on a well-regulated sugar-estate, is
put down at the cultivation of five acres—producing 5,000 pounds of
sugar, and 125 gallons of molasses; the former valued on the spot at
5½ cents per pound, and the latter at 18 cents per gallon—together,
$297.50. The annual expenses, per hand, including wages paid,
horses, mules, and oxen, physician’s bills, etc., $105. An estate of
eighty negroes annually costs $8,330. The items are as follows—Salt
meat and spirits, $830; clothing, $1,200; medical attendance and
medicines, $400; Indian corn, $1,090 (total for food and drink of
negroes, and other live stock, $24 per head of the negroes, per
annum. For clothing $15); overseer and sugar-maker’s salary,
$1,000; taxes $300. The capital invested in 1,200 acres of land, with
its stock of slaves, horses, mules, and working oxen, is estimated at
$147,200. One-third, or 400 acres, being cultivated annually in cane,
it is estimated, will yield 400,000 pounds, at 5½ cents, and 10,000
gallons molasses at 18 cents—together $23,800. Deduct annual
expense, as before, $8,330, an apparent profit remains of $15,470
or 10 3-7 per cent. interest on the investment. The crop upon which
these estimates were based, has been considered an uncommonly
fine one.
These estimates are all made by persons anxious to maintain the
necessity of protection to the continued production of sugar in the
United States, and who are, therefore, under strong temptation to
over-estimate expenditures.
In the first statement, the cost of clothing and boarding a first-rate,
hard-working man is stated to be $30 a year. A suit of winter
clothing and a pair of trousers for summer, a blanket for bedding, a
pair of shoes and a hat, must all at least be included under the head
of clothing; and these, however poor, could not certainly cost,
altogether, less than $10. For food, then, $20 a year is a large
estimate, which is 5½ cents. a day. This is for the best hands; light
hands are estimated at half this cost. Does the food of a first-rate
labourer, anywhere in the free world, cost less? The lowest price
paid by agricultural labourers in the Free States of America for board
is 21 cents a day, that is, $1.50 a week; the larger part probably pay
at least twice as much as this.
On most plantations, I suppose, but by no means on all, the slaves
cultivate “patches,” and raise poultry for themselves. The produce is
nearly always sold to get money to buy tobacco and Sunday finery.
But these additions to the usual allowance cannot be said to be
provided for them by their masters. The labour expended in this way
for themselves does not average half a day a week per slave; and
many planters will not allow their slaves to cultivate patches,
because it tempts them to reserve for and to expend in the night-
work the strength they want employed in their service during the
day, and also because the produce thus obtained is made to cover
much plundering of their master’s crops, and of his live stock.[36]
The free labourer also, in addition to his board, nearly always spends
something for luxuries—tobacco, fruit, and confections, to say
nothing of dress and luxuries and recreations.
The fact is, that ninety-nine in a hundred of our free labourers, from
choice and not from necessity—for the same provisions cost more in
Louisiana than they do anywhere in the Northern States—live, in
respect to food, at least four times as well as the average of the
hardest-worked slaves on the Louisiana sugar-plantations. And for
two or three months in the year I have elsewhere shown that these
are worked with much greater severity than free labourers at the
North ever are. For on no farm, and in no factory, or mine, even
when double wages are paid for night-work, did I ever hear of men
or women working regularly eighteen hours a day. If ever done, it is
only when some accident makes it especially desirable for a few
days.
I have not compared the comfort of the light hands, in which,
besides the aged and children, are evidently included most of the
females of the plantation, with that of factory girls and apprentices;
but who of those at the North was ever expected to find board at
four cents a day, and obliged to save money enough out of such an
allowance to provide him or herself with clothing? But that,
manifestly and beyond the smallest doubt of error (except in favour
of free labour), expresses the condition of the Louisiana slave. Forty-
eight of the most worthy planters of the State attest it in an official
document, published by order of Congress.
There is no reason for supposing that the slaves are much, if any,
better fed elsewhere than in Louisiana. I was expressly told in
Virginia that I should find them better fed in Louisiana than
anywhere else. In the same Report of Mr. Secretary Walker, a
gentleman in South Carolina testifies that he considers that the
“furnishing” (food and clothing) of “full-tasked hands” costs $15 a
year.[37]
The United States army is generally recruited from our labouring
class, and a well-conditioned and respectable labourer is not very
often induced to join it. The following, taken from an advertisement,
for recruits, in the Richmond Enquirer, shows the food provided:
“Daily Rations.—One and a quarter pounds of beef, one and three-
sixteenths pounds of bread; and at the rate of eight quarts of beans,
eight pounds of sugar, four pounds of coffee, two quarts of salt, four
pounds of candles, and four pounds of soap, to every hundred
rations.”
From an advertisement for slaves to be hired by the year, to work on
a canal, in the Daily Georgian:
“Weekly Allowance.—They will be provided with three and a half
pounds of pork or bacon, and ten quarts of gourd seed corn per
week, lodged in comfortable shanties, and attended by a skilful
physician.”
The expense of boarding, clothes, taxes, and so forth, of a male
slave, is estimated by Robert C. Hall, a Maryland planter, at $45 per
annum; this in a climate but little milder than that of New York, and
in a breeding state. By J. D. Messenger, Jerusalem, Virginia: “The
usual estimate for an able-bodied labourer—three barrels of corn,
and 250 pounds of well-cured bacon, seldom using beef or pork;
peas and potatoes substitute about one-third the allowance of
bread” (maize). By R. G. Morris, Amherst County, Va.: “Not much
beef is used on our estates; bacon, however, is used much more
freely, three pounds a week being the usual allowance. The quantity
of milk used by slaves is frequently considerable.”-Pat. Office Report,
1848.
On the most valuable plantation, with one exception, which I visited
in the South, no meat was regularly provided for the slaves, but a
meal of bacon was given them “occasionally.”
Louisiana is the only State in which meat is required, by law, to be
furnished the slaves. I believe the required ration is four pounds a
week, with a barrel of corn (flour barrel of ears of maize) per month,
and salt. (This law is a dead letter, many planters in the State
making no regular provision of meat for their force.) In North
Carolina the law fixes “a quart of corn per day” as the proper
allowance of food for a slave. In no other States does the law define
the quantity, but it is required, in general terms, to be sufficient for
the health of the slave; and I have no doubt that suffering from
want of food is rare. The food is everywhere, however, coarse,
crude, and wanting in variety; much more so than that of our prison
convicts.
Does argument, that the condition of free-labourers is, on the whole,
better than that of slaves, or that simply they are generally better
fed, and more comfortably provided, seem to any one to be
unnecessary? Many of our newspapers, of the largest circulation,
and certainly of great influence among people—probably not very
reflective, but certainly not fools—take the contrary for granted,
whenever it suits their purpose. The Southern newspapers, so far as
I know, do so, without exception. And very few Southern writers, on
any subject whatever, can get through a book, or even a business or
friendly letter, to be sent North, without, in some form or other,
asserting that Northern labourers might well envy the condition of
the slaves. A great many Southern gentlemen—gentlemen whom I
respect much for their moral character, if not for their faculties of
observation—have asserted it so strongly and confidently, as to shut
my mouth, and by assuring me that they had personally observed
the condition of Northern labourers themselves, and really knew that
I was wrong, have for a time half convinced me against my long
experience. I have, since my return, received letters to the same
effect: I have heard the assertion repeated by several travellers, and
even by Northerners, who had resided long in the South: I have
heard it publicly repeated in Tammany Hall, and elsewhere, by
Northern Democrats: I have seen it in European books and journals:
I have, in times past, taken its truth for granted, and repeated it
myself. Such is the effect of the continued iteration of falsehood.
Since my return I have made it a subject of careful and extended
inquiry. I have received reliable and unprejudiced information in the
matter, or have examined personally the food, the wages, and the
habits of the labourers in more than one hundred different farmers’
families, in every Free State (except California), and in Canada. I
have made personal observations and inquiries of the same sort in
Great Britain, Germany, France, and Belgium. In Europe, where
there are large landed estates, which are rented by lordly proprietors
to the peasant farmers, or where land is divided into such small
portions that its owners are unable to make use of the best modern
labour-saving implements, the condition of the labourer, as respects
food, often is as bad as that of the slave often is—never worse than
that sometimes is. But in general, even in France, I do not believe it
is generally or frequently worse; I believe it is, in the large majority
of cases, much better than that of the majority of slaves. And as
respects higher things than the necessities of life—in their
intellectual, moral, and social condition, with some exceptions on
large farms and large estates in England, bad as is that of the mass
of European labourers, the man is a brute or a devil who, with my
information, would prefer that of the American slave. As to our own
labourers, in the Free States, I have already said enough for my
present purpose.
But it is time to speak of the extreme cases, of which so much use
has been made, in the process of destroying the confidence of the
people of the United States in the freedom of trade, as applied to
labour.
In the year 1855, the severest winter ever known occurred at New
York, in conjunction with unprecedentedly high prices of food and
fuel, extraordinary business depression, unparalleled marine
disasters, and the failure of establishments employing large numbers
of men and women. At the same time, there continued to arrive,
daily, from five hundred to one thousand of the poorer class of
European peasantry. Many of these came, expecting to find the
usual demand and the usual reward for labour, and were quite
unprepared to support themselves for any length of time unless they
could obtain work and wages. There was consequently great
distress.
We all did what we thought we could, or ought, to relieve it; and
with such success, that not one single case of actual starvation is
known to have occurred in a close compacted population of over a
million, of which it was generally reported fifty thousand were out of
employment. Those who needed charitable assistance were, in
nearly every case, recent foreign immigrants, sickly people, cripples,
drunkards, or knaves taking advantage of the public benevolence, to
neglect to provide for themselves. Most of those who received
assistance would have thrown a slave’s ordinary allowance in the
face of the giver, as an insult; and this often occurred with more
palatable and suitable provisions. Hundreds and hundreds, to my
personal knowledge, during the worst of this dreadful season,
refused to work for money-wages that would have purchased them
ten times the slave’s ordinary allowance of the slave’s ordinary food.
In repeated instances, men who represented themselves to be
suffering for food refused to work for a dollar a day. A labourer,
employed by a neighbour of mine, on wages and board, refused to
work unless he was better fed. “What’s the matter,” said my
neighbour; “don’t you have enough?” “Enough; yes, such as it is.”
“You have good meat, good bread, and a variety of vegetables; what
do you want else?” “Why, I want pies and puddings, too, to be sure.”
Another labourer left another neighbour of mine, because, as he
alleged, he never had any meat offered him except beef and pork;
he “didn’t see why he shouldn’t have chickens.”
And these men went to New York, and joined themselves to that
army on which our Southern friends exercise their pity—of labourers
out of work—of men who are supposed to envy the condition of the
slave, because the “slave never dies for want of food.”[38]
In the depth of winter, a trustworthy man wrote us from Indiana:—
“Here, at Rensselaer, a good mechanic, a joiner or
shoemaker, for instance—and numbers are needed here—
may obtain for his labour in one week:
2 bushels of corn.
1 bushel of wheat.
5 pounds of sugar.
½ pound of tea.
10 pounds of beef.
25 pounds of pork.
1 good turkey.
3 pounds of butter.
1 pound of coffee.
1 bushel of potatoes.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookluna.com