Sams Teach Yourself Java in 24 Hours (8th Ed) 8th Edition Rogers Cadenhead - Ebook PDF Download
Sams Teach Yourself Java in 24 Hours (8th Ed) 8th Edition Rogers Cadenhead - Ebook PDF Download
https://ebooksecure.com/download/sams-teach-yourself-java-
in-24-hours-8th-ed-ebook-pdf/
https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-seventh-edition-ebook-pdf/
https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-ebook-pdf/
https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-6e-ebook-pdf/
https://ebooksecure.com/download/cissp-passport-ebook-pdf/
(eBook PDF) Teach: Introduction to Education 4th
Edition
http://ebooksecure.com/product/ebook-pdf-teach-introduction-to-
education-4th-edition/
https://ebooksecure.com/download/lawries-meat-science-8th-ed-
ebook-pdf/
https://ebooksecure.com/download/understanding-operating-
systems-8th-ed-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-learning-to-teach-by-
gloria-latham/
http://ebooksecure.com/product/ebook-pdf-java-an-introduction-to-
problem-solving-and-programming-8th-edition/
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.
Workshop 23
TIP
Oracle offers comprehensive documentation for the Java language on the Web. You don’t need it to
read this book, because each topic is discussed fully as it is introduced, but this reference comes in
handy when you want to expand your knowledge and write your own programs.
The documentation can be downloaded, but it’s more convenient to browse as needed on Oracle’s
website. The most up-to-date Java documentation is available at http://download.java.net/jdk9/
docs/api.
Summary
During this hour, you got your first chance to create a Java program. You learned that in order
to develop a Java program, you need to complete these four basic steps:
Along the way, you were introduced to some basic computer programming concepts such as
compilers, interpreters, blocks, statements, and variables. These will become clearer to you in
successive hours. As long as you got the Saluton program to work during this hour, you’re
ready to proceed.
(The fourth step has nothing to do with Java programming. It’s just something my mother
suggested I put in the book.)
Workshop
Q&A
Q. How important is it to put the right number of blank spaces on a line in a Java program?
A. It’s completely unimportant as far as the computer is concerned. Spacing is strictly for the
benefit of people looking at a computer program—the Java compiler couldn’t care less. You
could have written the Saluton program without including blank spaces or using the Tab
key to indent lines, and it would compile successfully.
Although the number of spaces in front of lines isn’t important to the computer, you should
use consistent spacing and indentation in your Java programs anyway. Why? Because spac-
ing makes it easier for you to see how a program is organized and to which programming
block a statement belongs.
24 HOUR 2: Writing Your First Program
The programs you write must be understandable to other programmers, including yourself
when you look at the code weeks or months later to fix a bug or make an enhancement.
Consistency in spacing and indentation are part of what’s called a programming style. Good
programmers adopt a style and practice it in all their work.
Q. A Java program has been described as a class and as a group of classes. Which is it?
A. Both. The simple Java programs you create during the next few hours are compiled into a
single file with the extension .class. You can run these with the Java Virtual Machine.
Java programs also can be made up of a set of classes that work together. This topic is
fully explored during Hour 10, “Creating Your First Object.”
Q. If semicolons are needed at the end of each statement, why does the comment line
// My first Java program goes here not end with a semicolon?
A. Comments are completely ignored by the compiler. If you put // on a line in your program,
this tells the Java compiler to ignore everything to the right of the // on that line. The
following example shows a comment on the same line as a statement:
System.out.println(greeting); // hello, world!
Q. I couldn't find any errors in the line where the compiler noted an error. What can I do?
A. The line number displayed with the error message isn’t always the place where an error needs
to be fixed. Examine the statements that are directly above the error message to see whether
you can spot any typos or other bugs. The error usually is within the same programming block.
Flyovers are available from Australia, New Zealand, and South America and cost around
$1,000 per person.
Several cruise ships visit for a trip lasting from 10 days to three weeks, the most expensive
of which is around $25,000. Some cruises offer a chance to kayak or hike among pen-
guins, visit icebergs, and even camp overnight.
The Polar Cruises website at www.polarcruises.com provides more information for prospec-
tive Antarctica visitors.
The British Antarctic Survey offers a piece of advice for visitors: “Do not walk onto glaciers
or large snowfields unless properly trained.”
Workshop 25
Quiz
Test your knowledge of the material covered in this hour by answering the following questions.
1. When you compile a Java program, what are you doing?
A. Saving it to a disk
B. Converting it into a form the computer can better understand
C. Adding it to your program collection
2. What is a variable?
A. Something that wobbles but doesn’t fall down
B. Text in a program that the compiler ignores
C. A place to store information in a program
3. What is the process of fixing errors called?
A. Defrosting
B. Debugging
C. Decomposing
Answers
1. B. Compiling a program converts a .java file into a .class file or a set of .class files.
2. C. Variables are one place to store information; later you learn about others such as arrays
and constants. Weebles wobble but they don’t fall down, and comments are text in a pro-
gram that the compiler ignores.
3. B. Because errors in a computer program are called bugs, fixing those errors is called
debugging. Some programming tools come with a tool called a debugger that helps you fix
errors. NetBeans has one of debest debuggers.
Activities
If you’d like to explore the topics covered in this hour a little more fully, try the following activities:
u You can translate the English phrase “Hello world!” into other languages using the Google
Translator at http://translate.google.com. Write a program that enables your computer to
greet the world in a language such as French, Italian, or Portuguese.
u Go back to the Saluton program and add one or two errors. For example, take a semi-
colon off the end of a line or change the text println on one line to print1n (with a
number 1 instead of the letter L). Save the program and try to compile it; then compare the
error messages you see to the errors you caused.
Before you venture further into Java programming, it’s worthwhile to learn more about the
language and see what programmers are doing with it today. Though Java has long outgrown
its origins as a language focused on web browser programs, you can find millions of examples of
how Java is used in mobile apps.
During this hour, we look at sites that feature Java programs, apps written in the language, and
the history and development of the language.
To go on this vacation, you need a phone or tablet that runs Java programs.
Power up your device of choice, put on your best batik shirt, and get ready to take a vacation.
You won’t be leaving your house, and you won’t experience the simpler pleasures of tourism,
such as exotic locales, exotic locals, exotic food, exotic locals with food, and so on.
Look on the bright side though: no traveler’s check hassles, no passports, and no worries about
the water.
A Java program that runs on a mobile device is called an app. Apps in Java appear primarily
on Android devices. Java also appears on the Web: Desktop programs written in Java can be
launched from a web browser, Java servlets are run by web servers to deliver web applications,
and Java applets appear on web pages in browsers.
28 HOUR 3: Vacationing in Java
Figure 3.1 shows Celtic Heroes, a massively multiplayer online game powered by Java on
Android. You can play the game for free by installing the app on Google Play or your device’s
app store.
FIGURE 3.1
The Java-powered app game Celtic Heroes.
When you run it, the game loads within seconds and you can create a character and explore a
fantasy world.
Oracle’s Java division leads the development of the Java language. Java Magazine, an
online magazine available for free from Oracle at Java.com, showcases how Java is being
used on Android phones, websites, and other platforms. Billions of devices run programs
written with Java.
Oracle also offers a more technically oriented website for Java programmers at www.oracle.com/
technetwork/java. This site is the place to find the latest released versions of NetBeans and the
Java Development Kit along with other programming resources.
This trip around Java begins in Android because that has become the most thriving place for the
language to be used. After you learn Java, you can apply your skills developing your own apps
using the Android Software Development Kit (SDK), a free programming toolkit that runs on
Windows, Mac OS, and Linux.
First Stop: Oracle 29
More than 300,000 apps have been created for Android phones and other devices that run
the mobile operating system. You learn more about how to create them in Hour 24, “Writing
Android Apps.”
Java was developed in 1990 by James Gosling as a language that would serve as the brains for
smart appliances (interactive TVs, omniscient ovens, time-traveling Terminators, SkyNet military
satellites that enslave mankind, and so on). Gosling was unhappy with the results he was
getting by writing programs with a programming language called C++. In a burst of inspiration,
he holed up in his office and wrote a new language to better suit his needs.
Gosling named his new language Oak after a tree he could see from his office window. The
language was part of his company’s strategy to make a fortune when interactive TV became a
multimillion-dollar industry. That still hasn’t happened today (though Amazon, Apple, Roku,
and others are making a game attempt), but something completely different took place for
Gosling’s new language. Just as Oak was about to be scrapped, the Web became popular.
In a fortuitous circumstance, many qualities that made Gosling’s language good on its appliance
project made it suitable for adaptation to the Web. His team devised a way for programs to be
run safely from web pages, and a catchy new name was chosen to accompany the language’s
new purpose: Java.
NOTE
You might have heard that Java is an acronym that stands for Just Another Vague Acronym. You also
might have heard that it was named for Gosling’s love of coffee.
The story behind Java’s naming contains no secret messages or declarations of liquid love. Java
was chosen as the name for the same reason that the comedian Jerry Seinfeld likes to say the word
salsa: It just sounds cool.
Although Java can be used for many other things, the Web provided the original showcase it
needed to seize the attention of the world’s software developers. When the language rose to
prominence, you had to be in solitary confinement or a long-term orbital mission to avoid
hearing about it.
30 HOUR 3: Vacationing in Java
There have been 10 major releases of the Java language, each with some essential new features.
Here are the first nine:
u Java 1.1—Java Database Connectivity (JDBC), improved graphical user interfaces (1997)
u Java 2 version 1.2—Inner classes, the Java Plug-in for web browsers, and data
structures (1998)
u Java 2 version 1.4—Improved Internet support, XML processing, and assertions (2002)
u Java 5—Generics, new for loops, annotations, and automatic data conversion (2005)
u Java 7—Memory and resource management improvements and the Nimbus graphical
user interface (2011)
The current release, Java 9, came out in 2017. Three years in the making, this new version
introduces improvements to interfaces and closures, an advanced feature you learn about during
Hour 16, “Using Inner Classes and Closures.” There’s also an HTTP client for receiving and
sending data over the Web, as covered in Hour 21, “Using Java 9’s New HTTP Client.”
If you don’t know what all these things are—such as inner classes, generics, or HTTP—don’t
freak out. You’ll learn about them over the next 21 hours.
NOTE
Are you wondering why Java’s versions are numbered so strangely, skipping from 2 to 6, calling the
seventh version Java 6, and including an integer and decimal number in some versions? Me, too!
Java’s major domos made some odd decisions along the way as new versions were released.
Fortunately, the numbering scheme has made more sense since 2006, with each new release an
integer one higher than the last.
For one such example, install the FreeBalls app to access a free particle motion simulator created
by Ivan Maklyakov, a computer programmer in Russia. The program uses Java to demonstrate
physics-based animation of thousands of particles made out of a solid or liquid. The motion is
controlled by tilting the screen. Figure 3.2 shows the colorful result.
FIGURE 3.2
A physics simulator can be experienced interactively using a Java app.
Numerous educational programs are available for many operating systems, but one thing that
makes this program stand out is its availability. The simulator can run on any Android device.
You can run Java programs on any computer that has a Java Virtual Machine (JVM).
The JVM loaded by a mobile device or web browser is the same you used to run the Saluton
application during Hour 2, “Writing Your First Program.”
A Java program, such as the physics simulator, does not have to be written for a specific
operating system. Because operating systems like Windows also are called platforms, this
advantage is called platform independence. Java was created to work on multiple systems.
Java’s developers believed it needed to be multiplatform because it would be used on a variety of
appliances and other electronic devices.
Users can run the programs you write with Java on a variety of systems without requiring any
extra work from you. Under the right circumstances, Java can remove the need to create specific
versions of a program for different operating systems and devices.
32 HOUR 3: Vacationing in Java
For each of the star chefs on the channel, Food Network in the Kitchen offers recipes, cooking
notes, user comments, and videos. One of the advantages of the app format is that it can include
interactive features in conjunction with articles. Figure 3.3 shows Giada de Laurentiis’s recipe
for pan-seared branzino that accompanies a video tutorial explaining how it was prepared.
Remember to use your fish spatula!
FIGURE 3.3
A recipe in the Food Network in the Kitchen app.
An app store like the one where Food Network in the Kitchen was found contains thousands of
programs for users to try. Because these programs come from many developers, safeguards must
be in place to protect users and their devices. One issue that has been hotly debated since Java’s
introduction is whether the language is secure.
Security is important because of the way Java programs work when they are delivered as apps.
The apps you try during this hour are downloaded to your phone or tablet. When the program is
finished downloading, it can be run.
Unless you know a whole lot of people, most apps you use are published by strangers. In terms
of security, running their programs isn’t a lot different than letting the general public come
over and borrow your computer. If the Java language did not have safeguards to prevent abuse,
Watching the Skies at NASA 33
its programs could introduce viruses onto your system, delete files, play the spoken-word song
performances of William Shatner, and do other unspeakable things.
Java includes several kinds of security to make sure that its programs are safe when run from
apps or web pages.
The language generally has been considered safe enough to be usable over the Web, but security
holes exploited in recent years have led some security experts to recommend that users turn off
Java entirely in their browsers. Most of the leading browsers today discourage users from running
Java applets on websites.
Java is more commonly encountered by users on mobile apps, server programs, and desktop
software. That’s why this hour is being spent running apps instead of applets.
ISS Detector superimposes the current location and path of the ISS and satellites—over the night
sky. In Figure 3.4, the app shows the Iridium 96 satellite (GALEX) making a path through the
Eastern sky past Venus and Uranus beginning at 1:43 a.m.
FIGURE 3.4
The ISS Detector app monitors the location and path of orbiting satellites, a boon to metal birdwatchers.
34 HOUR 3: Vacationing in Java
The app redraws the position of each tracked satellite as it runs and changes the orientation of
the sky map based on the direction the user is facing. This kind of real-time update is possible
because the Java language is multithreaded. Multithreading is a way for the computer to do
more than one thing at the same time. One part of a program takes care of one task, another
part takes care of a different task, and the two parts can pay no attention to each other. Each
part of a program in this example is called a thread.
In a program such as ISS Detector, each satellite could run in its own thread. If you use an
operating system such as Windows 10, you’re using a type of this behavior when you run more
than one program at the same time. If you’re at work playing Minecraft in one window while
running a company sales report in another window and making a long-distance call to a friend,
congratulate yourself—you’re multithreading!
Install the Realtime Stock Quotes Java app from uInvest Studio which displays updated
stock prices for a user’s holdings. Figure 3.5 shows the current data for ticker symbol GOOG
(Google’s parent company Alphabet Inc.).
FIGURE 3.5
Stock market data presented in a uInvest Studio Java app.
Stopping by SourceForge for Directions 35
You can think of a program like this stock ticker app in several ways. One is to think of a
program as an object—something that exists in the world, takes up space, and has certain things
it can do. Object-oriented programming (OOP), which Java uses, as you discover in Hour 10,
“Creating Your First Object,” is a way of creating computer programs as a group of objects. Each
object handles a specific job and knows how to speak to other objects. For example, a stock ticker
program could be set up as the following group of objects:
Under that model, the stock ticker software is a collection of all the objects necessary to get
work done.
OOP is a powerful way to create programs, and it makes the programs you write more useful.
Consider the stock software. If the programmer wants to use the quote capabilities of that
program with some other software, the quote object can be used with the new program. No
changes need to be made.
Programs created with objects are easier to maintain because they are better organized. An
object contains the data necessary to do its job and the code required to do that work. Objects
also make a program more extensible. A new object can be patterned after an existing one and
enhanced with new capabilities.
If you use the search box atop the SourceForge home page to search for Java, you’ll find more
than 61,000 listings in the site’s directory of projects.
One of the programs on SourceForge is JSoko, a Java version of the Japanese warehouse keeper
game Sokoban (see Figure 3.6). The puzzle game features animation, graphics, keyboard control,
and sound. To download the application and view its Java source code, visit https://sourceforge.
net/projects/jsokoapplet to download the source code.
FIGURE 3.6
Source code for Java programs such as the open source Sokoban game JSoko can be found on SourceForge.
Java includes an enormous library of classes you can use in your own programs. JSoko
employs the library’s Image class (in java.awt) to display graphics such as boxes and its
AudioInputStream class (in javax.sound.sampled) to play sounds as the truck moves and
boxes are placed.
One reason so many programs are created with Java—on SourceForge and elsewhere—is because
the language was designed to be easier to learn despite its powerful functionality.
Workshop 37
An original design goal for the language was to make it quicker to master than C++, the
language Gosling was having fits with on his smart-appliance project back in the 1990s. Much
of Java is based on C++, so programmers who have learned to use that language find it easier to
learn Java. However, some of the elements of C++ that are the hardest to learn and use correctly
are not present in Java.
For people learning programming for the first time, Java is easier to learn than C++. Some
languages are created to make it easier for experienced programmers to harness the capabilities
of the computer in their programs. These languages include shortcuts and other features that
programming veterans easily understand.
Java does not use some of these features, preferring to make the language as simple as an object-
oriented programming language can be. Java was created to be easy to learn, easy to debug,
and easy to use. Java includes numerous enhancements that make it a worthy competitor to
other languages.
Summary
Now that the hour-long vacation is over, it’s time to put away your luggage and get ready for a
return to actual Java programming.
During the next 21 hours, you will master the basic building blocks of the Java language, learn
how to create your own objects to accomplish tasks in object-oriented programming, design
graphical user interfaces, and much more.
Workshop
Q&A
Q. Why are Java applets no longer popular?
A. When the Java language was introduced in the mid-1990s, most people were learning the
language to write applets. Java was the only way to create interactive programs that ran in a
web browser. Over the years, alternatives emerged. Macromedia Flash, Microsoft Silverlight,
and the new web publishing HTML5 standard all offer ways to put programs on web pages.
Applets were hampered by poor loading times, slow support for new versions of Java by
browser developers, and security holes exploited by hackers. Though applets are disappear-
ing from the web, Java has outgrown its origins as a web browser enhancement and is now
a sophisticated general-purpose programming language.
38 HOUR 3: Vacationing in Java
Q. What’s the difference between Java SE (Java Standard Edition) and Java EE (Java Enterprise
Edition)? Does Java EE cost money?
A. Java Enterprise Edition is an expansion of the Java Standard Edition that includes packages
to support advanced technology such as Enterprise JavaBeans, XML processing, and the
development of servlets—Java programs that run on a web server. Java EE also includes an
application server, a sophisticated environment for executing Java software that’s tailored
for corporations and other large organizations with heavy computing needs. The Java EE
development kit can be downloaded at no cost from Oracle at www.oracle.com/technet-
work/java/javaee.
Q. What’s a Chris Steak House, and why does Ruth have one?
A. Ruth’s Chris Steak House, the chain of more than 130 upscale steak restaurants across
the United States and a handful of other countries, has an odd two-first-name name that
reveals its humble origins and the stubborn streak of its founder.
The chain was founded in 1965 as a solitary New Orleans restaurant owned by Ruth Fertel,
a single mother of two sons. Fertel saw a classified ad offering a restaurant for sale and
took out a $22,000 home mortgage to buy it (equivalent to around $150,000 in present
dollars).
She reached a deal to keep the name Chris Steak House with original owner Chris Matulich,
but later had to relocate after a kitchen fire.
Fertel’s contract did not permit her to use the Chris Steak House name anywhere but the
original location, so she renamed it Ruth’s Chris Steak House. Though she had no restau-
rant or culinary expertise, the business was so successful that she began offering it as a
franchise within 12 years. She disregarded several suggestions over the years to change
the name to broaden its appeal.
“I’ve always hated the name,” she once told a reporter for Fortune magazine, “but we’ve
always managed to work around it.”
Fertel, who died in 2002, was born on February 5, 1927—the same day that Matulich
opened the original steakhouse.
Quiz
If your mind hasn’t taken a vacation by this point, test your knowledge of this hour with the
following questions.
1. How did object-oriented programming get its name?
A. Programs are considered to be a group of objects working together.
B. People often object because it’s hard to master.
C. Its parents named it.
Another Random Scribd Document
with Unrelated Content
Beluchistan. There are zealots for long division, experts in the
multiplication table, lunatic worshipers of the binomial theorem. But
the system has them in its grip. It combats their natural enthusiasm
diligently and mercilessly. It tries to convert them into mere
technicians, clumsy machines. It orders them to teach, not by the
process of emotional osmosis which worked in the days gone by, but
by formulæ that are as baffling to the pupil as they are paralyzing to
the teacher. Imagine what would happen to one of them who
stepped to the blackboard, seized a piece of chalk, and engrossed a
bird that held the class spell-bound—a bird with a thousand flowing
feathers, wings bursting with parabolas and epicycloids, and long
ribbons streaming from its bill! Imagine the fate of one who began
“Honesty is the best policy” with an H as florid and—to a child—as
beautiful as the initial of a mediæval manuscript! Such a teacher
would be cashiered and handed over to the secular arm; the very
enchantment of the assembled infantry would be held as damning
proof against him. And yet it is just such teachers that we should try
to discover and develop. Pedagogy needs their enthusiasm, their
naïve belief in their own grotesque talents, their capacity for
communicating their childish passion to the childish.
But this would mean exposing the children of the Republic to contact
with monomaniacs, half-wits, defectives? Well, what of it? The vast
majority of them are already exposed to contact with half-wits in
their own homes; they are taught the word of God by half-wits on
Sundays; they will grow up into Knights of Pythias, Odd Fellows, Red
Men and other such half-wits in the days to come. Moreover, as I
have hinted, they are already face to face with half-wits in the actual
schools, at least in three cases out of four. The problem before us is
not to dispose of this fact, but to utilize it. We cannot hope to fill the
schools with persons of high intelligence, for persons of high
intelligence simply refuse to spend their lives teaching such banal
things as spelling and arithmetic. Among the teachers male we may
safely assume that 95 per cent. are of low mentality, else they would
depart for more appetizing pastures. And even among the teachers
female the best are inevitably weeded out by marriage, and only the
worst (with a few romantic exceptions) survive. The task before us,
as I say, is not to make a vain denial of this cerebral inferiority of the
pedagogue, nor to try to combat and disguise it by concocting a
mass of technical hocus-pocus, but to search out and put to use the
value lying concealed in it. For even stupidity, it must be plain, has
its uses in the world, and some of them are uses that intelligence
cannot meet. One would not tell off a Galileo or a Pasteur to drive an
ash-cart or an Ignatius Loyola to be a stockbroker, or a Brahms to
lead the orchestra in a Broadway cabaret. By the same token, one
would not ask a Herbert Spencer or a Duns Scotus to instruct
sucklings. Such men would not only be wasted at the job; they
would also be incompetent. The business of dealing with children, in
fact, demands a certain childishness of mind. The best teacher, until
one comes to adult pupils, is not the one who knows most, but the
one who is most capable of reducing knowledge to that simple
compound of the obvious and the wonderful which slips easiest into
the infantile comprehension. A man of high intelligence, perhaps,
may accomplish the thing by a conscious intellectual feat. But it is
vastly easier to the man (or woman) whose habits of mind are
naturally on the plane of a child’s. The best teacher of children, in
brief, is one who is essentially child-like.
I go so far with this notion that I view the movement to introduce
female bachelors of arts into the primary schools with the utmost
alarm. A knowledge of Bergsonism, the Greek aorist, sex hygiene
and the dramas of Percy MacKaye is not only no help to the teaching
of spelling, it is a positive handicap to the teaching of spelling, for it
corrupts and blows up that naïve belief in the glory and
portentousness of spelling which is at the bottom of all successful
teaching of it. If I had my way, indeed, I should expose all
candidates for berths in the infant grades to the Binet-Simon test,
and reject all those who revealed the mentality of more than fifteen
years. Plenty would still pass. Moreover, they would be secure
against contamination by the new technic of pedagogy. Its vast
wave of pseudo-psychology would curl and break against the hard
barrier of their innocent and passionate intellects—as it probably
does, in fact, even now. They would know nothing of cognition,
perception, attention, the subconscious and all the other half-
fabulous fowl of the pedagogic aviary. But they would see in reading,
writing and arithmetic the gaudy charms of profound and esoteric
knowledge, and they would teach these ancient branches, now so
abominably in decay, with passionate gusto, and irresistible
effectiveness, and a gigantic success.
II
Two great follies corrupt the present pedagogy, once it gets beyond
the elementals. One is the folly of overestimating the receptivity of
the pupil; the other is the folly of overestimating the possible
efficiency of the teacher. Both rest upon that tendency to put too
high a value upon mere schooling which characterizes democratic
and upstart societies—a tendency born of the theory that a young
man who has been “educated,” who has “gone through college,” is in
some subtle way more capable of making money than one who
hasn’t. The nature of the schooling on tap in colleges is but
defectively grasped by the adherents of the theory. They view it, I
believe, as a sort of extension of the schooling offered in elementary
schools—that is, as an indefinite multiplication of training in such
obviously valuable and necessary arts as reading, writing and
arithmetic. It is, of course, nothing of the sort. If the pupil, as he
climbs the educational ladder, is fortunate enough to come into
contact with a few Huxleys or Ludwigs, he may acquire a great deal
of extremely sound knowledge, and even learn how to think for
himself. But in the great majority of cases he is debarred by two
things: the limitations of his congenital capacity and the limitations
of the teachers he actually encounters. The latter is usually even
more brilliantly patent than the former. Very few professional
teachers, it seems to me, really know anything worth knowing, even
about the subjects they essay to teach. If you doubt it, simply
examine their contributions to existing knowledge. Several years
ago, while engaged upon my book, “The American Language,” I had
a good chance to test the matter in one typical department, that of
philology. I found a truly appalling condition of affairs. I found that
in the whole United States there were not two dozen teachers of
English philology—in which class I also include the innumerable
teachers of plain grammar—who had ever written ten lines upon the
subject worth reading. It was not that they were indolent or
illiterate: in truth, they turned out to be enormously diligent. But as I
plowed through pyramid after pyramid of their doctrines and
speculations, day after day and week after week, I discovered little
save a vast laboring of the obvious, with now and then a bold flight
into the nonsensical. A few genuinely original philologians revealed
themselves—pedagogues capable of observing accurately and
reasoning clearly. The rest simply wasted time and paper. Whole
sections of the field were unexplored, and some of them appeared
to be even unsuspected. The entire life-work of many an industrious
professor, boiled down, scarcely made a footnote in my book, itself a
very modest work.
This tendency to treat the superior pedagogue too seriously—to view
him as, ipso facto, a learned man, and one thus capable of
conveying learning to others—is supported by the circumstance that
he so views himself, and is, in fact, very pretentious and even
bombastic. Nearly all discussions of the educational problem, at least
in the United States, are carried on by schoolmasters or ex-
schoolmasters—for example, college presidents, deans, and other
such magnificoes—and so they assume it to be axiomatic that such
fellows are genuine bearers of the enlightenment, and hence
capable of transmitting it to others. This is true sometimes, as I have
said, but certainly not usually. The average high-school or college
pedagogue is not one who has been selected because of his
uncommon knowledge; he is simply one who has been stuffed with
formal ideas and taught to do a few conventional intellectual tricks.
Contact with him, far from being inspiring to any youth of alert
mentality, is really quite depressing; his point of view is
commonplace and timorous; his best thought is no better than that
of any other fourth-rate professional man, say a dentist or an
advertisement writer. Thus it is idle to talk of him as if he were a
Socrates, an Aristotle, or even a Leschetizky. He is actually much
more nearly related to a barber or a lieutenant of marines. A worthy
man, industrious and respectable—but don’t expect too much of
him. To ask him to struggle out of his puddle of safe platitudes and
plunge into the whirlpool of surmise and speculation that carries on
the fragile shallop of human progress—to do this is as absurd as to
ask a neighborhood doctor to undertake major surgery.
In the United States his low intellectual status is kept low, not only
by the meager rewards of his trade in a country where money is
greatly sought and esteemed, but also by the democratic theory of
education—that is, by the theory that mere education can convert a
peasant into an intellectual aristocrat, with all of the peculiar
superiorities of an aristocrat—in brief, that it is possible to make
purses out of sow’s ears. The intellectual collapse of the American
Gelehrten during the late war—a collapse so nearly unanimous that
those who did not share it attained to a sort of immortality overnight
—was perhaps largely due to this error. Who were these bawling
professors, so pathetically poltroonish and idiotic? In an enormous
number of cases they were simply peasants in frock-coats—oafs
from the farms and villages of Iowa, Kansas, Vermont, Alabama, the
Dakotas and other such backward states, horribly stuffed with
standardized learning in some fresh-water university, and then set to
teaching. To look for a civilized attitude of mind in such Strassburg
geese is to look for honor in a valet; to confuse them with scholars is
to confuse the Knights of Pythias with the Knights Hospitaller. In
brief, the trouble with them was that they had no sound tradition
behind them, that they had not learned to think clearly and decently,
that they were not gentlemen. The youth with a better background
behind him, passing through an American university, seldom
acquires any yearning to linger as a teacher. The air is too thick for
him; the rewards are too trivial; the intrigues are too old-maidish
and degrading. Thus the chairs, even in the larger universities, tend
to be filled more and more by yokels who have got themselves what
is called an education only by dint of herculean effort. Exhausted by
the cruel process, they are old men at 26 or 28, and so, hugging
their Ph.D’s, they sink into convenient instructorships, and end at 60
as ordentliche Professoren. The social status of the American
pedagogue helps along the process. Unlike in Europe, where he has
a secure and honorable position, he ranks, in the United States,
somewhere between a Methodist preacher and a prosperous brick-
yard owner—certainly clearly below the latter. Thus the youth of
civilized upbringings feels that it would be stooping a bit to take up
the rattan. But the plow-hand obviously makes a step upward, and is
hence eager for the black gown. Thereby a vicious circle is formed.
The plow-hand, by entering the ancient guild, drags it down still
further, and so makes it increasingly difficult to snare apprentices
from superior castes.
A glance at “Who’s Who in America” offers a good deal of support
for all this theorizing. There was a time when the typical American
professor came from a small area in New England—for generations
the seat of a high literacy, and even of a certain austere civilization.
But to-day he comes from the region of silos, revivals, and saleratus.
Behind him there is absolutely no tradition of aristocratic aloofness
and urbanity, or even of mere civilized decency. He is a bind by birth,
and he carries the smell of the dunghill into the academic grove—
and not only the smell, but also some of the dung itself. What one
looks for in such men is dullness, superficiality, a great credulity, an
incapacity for learning anything save a few fly-blown rudiments, a
passionate yielding to all popular crazes, a malignant distrust of
genuine superiority, a huge megalomania. These are precisely the
things that one finds in the typical American pedagogue of the new
dispensation. He is not only a numskull; he is also a boor. In the
university president he reaches his heights. Here we have a so-called
learned man who spends his time making speeches before
chautauquas, chambers of commerce and Rotary Clubs, and
flattering trustees who run both universities and street-railways, and
cadging money from such men as Rockefeller and Carnegie.
III
The same educational fallacy which fills the groves of learning with
such dunces causes a huge waste of energy and money on lower
levels—those, to wit, of the secondary schools. The theory behind
the lavish multiplication of such schools is that they outfit the
children of the mob with the materials of reasoning, and inculcate in
them a habit of indulging in it. I have never been able to discover
any evidence in support of that theory. The common people of
America—at least the white portion of them—are rather above the
world’s average in literacy, but there is no sign that they have
acquired thereby any capacity for weighing facts or comparing ideas.
The school statistics show that the average member of the American
Legion can read and write after a fashion, and is able to multiply
eight by seven after four trials, but they tell us nothing about his
actual intelligence. The returns of the Army itself, indeed, indicate
that he is stupid almost beyond belief—that there is at least an even
chance that he is a moron. Is such a fellow appreciably superior to
the villein of the Middle Ages? Sometimes I am tempted to doubt it.
I suspect, for example, that the belief in witchcraft is still almost as
widespread among the plain people of the United States, at least
outside the large cities, as it was in Europe in the year 1500. In my
own state of Mary-land all of the negroes and mulattoes believe
absolutely in witches, and so do most of the whites. The belief in
ghosts penetrates to quite high levels. I know very few native-born
Americans, indeed, who reject it without reservation. One constantly
comes upon grave defenses of spiritism in some form or other by
men theoretically of learning; in the two houses of Congress it would
be difficult to muster fifty men willing to denounce the thing publicly.
It would not only be politically dangerous for them to do so; it would
also go against their consciences.
What is always forgotten is that the capacity for knowledge of the
great masses of human blanks is very low—that, no matter how
adroitly pedagogy tackles them with its technical sorceries, it
remains a practical impossibility to teach them anything beyond
reading and writing, and the most elementary arithmetic. Worse, it is
impossible to make any appreciable improvement in their
congenitally ignoble tastes, and so they devote even the paltry
learning that they acquire to degrading uses. If the average
American read only the newspapers, as is frequently alleged, it
would be bad enough, but the truth is that he reads only the most
imbecile parts of the newspapers. Nine-tenths of the matter in a
daily paper of the better sort is almost as unintelligible to him as the
theory of least squares. The words lie outside his vocabulary; the
ideas are beyond the farthest leap of his intellect. It is, indeed, a
sober fact that even an editorial in the New York Times is probably
incomprehensible to all Americans save a small minority—and not,
remember, on the ground that it is too nonsensical but on the
ground that it is too subtle. The same sort of mind that regards
Rubinstein’s Melody in F as too “classical” to be agreeable is also
stumped by the most transparent English.
Like most other professional writers I get a good many letters from
my customers. Complaints, naturally, are more numerous than
compliments; it is only indignation that can induce the average man
to brave the ardors of pen and ink. Well, the complaint that I hear
most often is that my English is unintelligible—that it is too full of
“hard” words. I can imagine nothing more astounding. My English is
actually almost as bald and simple as the English of a college yell.
My sentences are short and plainly constructed: I resolutely cultivate
the most direct manner of statement; my vocabulary is deliberately
composed of the words of everyday. Nevertheless, a great many of
my readers in my own country find reading me an uncomfortably
severe burden upon their linguistic and intellectual resources. These
readers are certainly not below the American average in intelligence;
on the contrary, they must be a good deal above the average, for
they have at least got to the point where they are willing to put out
of the safe harbor of the obvious and respectable, and to brave the
seas where more or less novel ideas rage and roar. Think of what
the ordinary newspaper reader would make of my compositions!
There is, in fact, no need to think; I have tried them on him. His
customary response, when, by mountebankish devices, I forced him
to read—or, at all events, to try to read—, was to demand resolutely
that the guilty newspaper cease printing me, and to threaten to
bring the matter to the attention of the Polizei. I do not exaggerate
in the slightest; I tell the literal truth.
It is such idiots that the little red school-house operates upon, in the
hope of unearthing an occasional first-rate man. Is that hope ever
fulfilled? Despite much testimony to the effect that it is, I am
convinced that it really isn’t. First-rate men are never begotten by
Knights of Pythias; the notion that they sometimes are is due to an
optical delusion. When they appear in obscure and ignoble circles it
is no more than a proof that only an extremely wise sire knows his
own son. Adultery, in brief, is one of nature’s devices for keeping the
lowest orders of men from sinking to the level of downright simians:
sometimes for a few brief years in youth, their wives and daughters
are comely—and now and then the baron drinks more than he ought
to. But it is foolish to argue that the gigantic machine of popular
education is needed to rescue such hybrids from their environment.
The truth is that all the education rammed into the average pupil in
the average American public school could be acquired by the v larva
of any reasonably intelligent man in no more than six weeks of
ordinary application, and that where schools are unknown it actually
is so acquired. A bright child, in fact, can learn to read and write
without any save the most casual aid a great deal faster than it can
learn to read and write in a class-room, where the difficulties of the
stupid retard it enormously and it is further burdened by the crazy
formulæ invented by pedagogues. And once it can read and write, it
is just as well equipped to acquire further knowledge as ninetenths
of the teachers it will subsequently encounter in school or college.
IV
I know a good many men of great learning—that is, men born with
an extraordinary eagerness and capacity to acquire knowledge. One
and all, they tell me that they can’t recall learning anything of any
value in school. All that schoolmasters managed to accomplish with
them was to test and determine the amount of knowledge that they
had already acquired independently—and not infrequently the
determination was made clumsily and inaccurately. In my own
nonage I had a great desire to acquire knowledge in certain limited
directions, to wit, those of the physical sciences. Before I was ever
permitted, by the regulations of the secondary seminary I was
penned in, to open a chemistry book I had learned a great deal of
chemistry by the simple process of reading the texts and then going
through the processes described. When, at last, I was introduced to
chemistry officially, I found the teaching of it appalling. The one aim
of that teaching, in fact, seemed to be to first purge me of what I
already knew and then refill me with the same stuff in a formal,
doltish, unintelligible form. My experience with physics was even
worse. I knew nothing about it when I undertook its study in class,
for that was before the days when physics swallowed chemistry.
Well, it was taught so abominably that it immediately became
incomprehensible to me, and hence extremely; distasteful, and to
this day I know nothing about it. Worse, it remains unpleasant to
me, and so I am shut off from the interesting and useful knowledge
that I might otherwise acquire by reading.
One extraordinary teacher I remember who taught me something: a
teacher of mathematics. I had a dislike for that science, and knew
little about it. Finally, my neglect of it brought me to bay: in
transferring from one school to another I found that I was
hopelessly short in algebra. What was needed, of course, was not an
actual knowledge of algebra, but simply the superficial smattering
needed to pass an examination. The teacher that I mention,
observing my distress, generously offered to fill me with that
smattering after school hours. He got the whole year’s course into
me in exactly six lessons of half an hour each. And how? More
accurately, why? Simply because he was an algebra fanatic—because
he believed that algebra was not only a science of the utmost
importance, but also one of the greatest fascination. He was the
penmanship professor of years ago, lifted to a higher level. A likable
and plausible man, he convinced me in twenty minutes that
ignorance of algebra was as calamitous, socially and intellectually, as
ignorance of table manners—that acquiring its elements was as
necessary as washing behind the ears. So I fell upon the book and
gulped it voraciously, greatly to the astonishment of my father,
whose earlier mathematical teaching had failed to set me off
because it was too pressing—because it bombarded me, not when I
was penned in a school and so inclined to make the best of it, but
when I had got through a day’s schooling, and felt inclined to play.
To this day I comprehend the binomial theorem, a very rare
accomplishment in an author. For many years, indeed, I was
probably the only American newspaper editor who knew what it was.
Two other teachers of that school I remember pleasantly as fellows
whose pedagogy profited me—both, it happens, were drunken and
disreputable men. One taught me to chew tobacco, an art that has
done more to give me an evil name, perhaps, than even my
Socinianism. The other introduced me to Shakespeare, Congreve,
Wycherly, Marlowe and Sheridan, and so filled me with that taste for
coarseness which now offends so many of my customers, lay and
clerical. Neither ever came to a dignified position in academic circles.
One abandoned pedagogy for the law, became involved in causes of
a dubious nature, and finally disappeared into the shades which
engulf third-rate attorneys. The other went upon a fearful drunk one
Christmastide, got himself shanghaied on the water-front and is
supposed to have fallen overboard from a British tramp, bound east
for Cardiff. At all events, he has never been heard from since. Two
evil fellows, and yet I hold their memories in affection, and believe
that they were the best teachers I ever had. For in both there was
something a good deal more valuable than mere pedagogical skill
and diligence, and even more valuable than correct demeanor, and
that was a passionate love of sound literature. This love, given
reasonably receptive soil, they knew how to communicate, as a man
can nearly always communicate whatever moves him profoundly.
Neither ever made the slightest effort to “teach” literature, as the
business is carried on by the usual idiot schoolmaster. Both had a
vast contempt for the textbooks that were official in their school, and
used to entertain the boys by pointing out the nonsense in them.
Both were full of derisory objections to the principal heroes of such
books in those days: Scott, Irving, Pope, Jane Austen, Dickens,
Trollope, Tennyson. But both, discoursing in their disorderly way
upon heroes of their own, were magnificently eloquent and
persuasive. The boy who could listen to one of them intoning
Whitman and stand unmoved was a dull fellow indeed. The boy who
could resist the other’s enthusiasm for the old essayists was
intellectually deaf, dumb and blind.
I often wonder if their expoundings of their passions and prejudices
would have been half so charming if they had been wholly
respectable men, like their colleagues of the school faculty. It is not
likely. A healthy boy is in constant revolt against the sort of men who
surround him at school. Their puerile pedantries, their Christian
Endeavor respectability, their sedentary pallor, their curious
preference for the dull and uninteresting, their general air of so
many Y. M. C. A. secretaries—these things infallibly repel the youth
who is above milksoppery. In every boys’ school the favorite teacher
is one who occasionally swears like a cavalryman, or is reputed to
keep a jug in his room, or is known to receive a scented note every
morning. Boys are good judges of men, as girls are good judges of
women. It is not by accident that most of them, at some time or
other, long to be cowboys or ice-wagon drivers, and that none of
them, not obviously diseased in mind, ever longs to be a Sunday-
school superintendent. Put that judgment to a simple test. What
would become of a nation in which all of the men were, at heart,
Sunday-school superintendents—or Y. M. C. A. secretaries, or
pedagogues? Imagine it in conflict with a nation of cowboys and ice-
wagon drivers. Which would be the stronger, and which would be
the more intelligent, resourceful, enterprising and courageous?
XIV. TYPES OF MEN
The Romantic
The Skeptic
No man ever quite believes in any other man. One may believe in an
idea absolutely, but not in a man. In the highest confidence there is
always a flavor of doubt—a feeling, half instinctive and half logical,
that, after all, the scoundrel may have something up his sleeve. This
doubt, it must be obvious, is always more than justified, for no man
is worthy of unlimited reliance—his treason, at best, only waits for
sufficient temptation. The trouble with the world is not that men are
too suspicious in this direction, but that they tend to be too
confiding—that they still trust themselves too far to other men, even
after bitter experience. Women, I believe, are measurably less
sentimental, in this as in other things. No married woman ever trusts
her husband absolutely, nor does she ever act as if she did trust
him. Her utmost confidence is as wary as an American pick-pocket’s
confidence that the policeman on the beat will stay bought.
3
The Believer
The Worker
The Physician
The Scientist
The value the world sets upon motives is often grossly unjust and
inaccurate. Consider, for example, two of them: mere insatiable
curiosity and the desire to do good. The latter is put high above the
former, and yet it is the former that moves some of the greatest men
the human race has yet produced: the scientific investigators. What
animates a great pathologist? Is it the desire to cure disease, to save
life? Surely not, save perhaps as an afterthought. He is too
intelligent, deep down in his soul, to see anything praiseworthy in
such a desire. He knows by life-long observation that his discoveries
will do quite as much harm as good, that a thousand scoundrels will
profit to every honest man, that the folks who most deserve to be
saved will probably be the last to be saved. No man of self-respect
could devote himself to pathology on such terms. What actually
moves him is his unquenchable curiosity—his boundless, almost
pathological thirst to penetrate the unknown, to uncover the secret,
to find out what has not been found out before. His prototype is not
the liberator releasing slaves, the good Samaritan lifting up the
fallen, but the dog sniffing tremendously at an infinite series of rat-
holes. And yet he is one of the greatest and noblest of men. And yet
he stands in the very front rank of the race.
It is, after all, a sound instinct which puts business below the
professions, and burdens the business man with a social inferiority
that he can never quite shake off, even in America. The business
man, in fact, acquiesces in this assumption of his inferiority, even
when he protests against it. He is the only man who is forever
apologizing for his occupation. He is the only one who always seeks
to make it appear, when he attains the object of his labors, i. e., the
making of a great deal of money, that it was not the object of his
labors.
The King
Perhaps the most valuable asset that any man can have in this world
is a naturally superior air, a talent for sniffishness and reserve. The
generality of men are always greatly impressed by it, and accept it
freely as a proof of genuine merit. One need but disdain them to
gain their respect. Their congenital stupidity and timorousness make
them turn to any leader who offers, and the sign of leadership that
they recognize most readily is that which shows itself in external
manner. This is the true explanation of the survival of monarchism,
which invariably lives through its perennial deaths. It is the popular
theory, at least in America, that monarchism is a curse fastened
upon the common people from above—that the monarch saddles it
upon them without their consent and against their will. The theory is
without support in the facts. Kings are created, not by kings, but by
the people. They visualize one of the ineradicable needs of all third-
rate men, which means of nine men out of ten, and that is the need
of something to venerate, to bow down to, to follow and obey.
The king business begins to grow precarious, not when kings reach
out for greater powers, but when they begin to resign and renounce
their powers. The czars of Russia were quite secure upon the throne
so long as they ran Russia like a reformatory, but the moment they
began to yield to liberal ideas, i. e., by emancipating the serfs and
setting up constitutionalism, their doom was sounded. The people
saw this yielding as a sign of weakness; they began to suspect that
the czars, after all, were not actually superior to other men. And so
they turned to other and antagonistic leaders, all as cocksure as the
czars had once been, and in the course of time they were stimulated
to rebellion. These leaders, or, at all events, the two or three most
resolute and daring of them, then undertook to run the country in
the precise way that it had been run in the palmy days of the
monarchy. That is to say, they seized and exerted irresistible power
and laid claim to infallible wisdom. History will date their downfall
from the day they began to ease their pretensions. Once they
confessed, even by implication, that they were merely human, the
common people began to turn against them.
The Truth-Seeker
The man who boasts that he habitually tells the truth is simply a
man with no respect for it. It is not a thing to be thrown about
loosely, like small change; it is something to be cherished and
hoarded, and disbursed only when absolutely necessary. The
smallest atom of truth represents some man’s bitter toil and agony;
for every ponderable chunk of it there is a brave truth-seeker’s grave
upon some lonely ash-dump and a soul roasting in hell.
11
The Pacifist
12
The Relative
13
The Friend
Le Contrat Social
ebooksecure.com