0% found this document useful (0 votes)
1K views78 pages

Sams Teach Yourself Java in 24 Hours (8th Ed) 8th Edition Rogers Cadenhead - Ebook PDF Download

Sams Teach Yourself Java in 24 Hours, Eighth Edition is a comprehensive guide designed to teach Java programming through a series of one-hour tutorials. The book covers fundamental concepts, object-oriented programming, graphical user interfaces, and internet applications, making it suitable for beginners. Additionally, it provides access to a Web Edition for further learning resources and updates.

Uploaded by

aubutbakkevu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views78 pages

Sams Teach Yourself Java in 24 Hours (8th Ed) 8th Edition Rogers Cadenhead - Ebook PDF Download

Sams Teach Yourself Java in 24 Hours, Eighth Edition is a comprehensive guide designed to teach Java programming through a series of one-hour tutorials. The book covers fundamental concepts, object-oriented programming, graphical user interfaces, and internet applications, making it suitable for beginners. Additionally, it provides access to a Web Edition for further learning resources and updates.

Uploaded by

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

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/

Download full version ebook from https://ebooksecure.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooksecure.com
to discover even more!

Teach Yourself Electricity and Electronics, Seventh


Edition Stan Gibilisco - eBook PDF

https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-seventh-edition-ebook-pdf/

Teach Yourself Electricity and Electronics 6th Edition


Stan Gibilisco - eBook PDF

https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-ebook-pdf/

Teach Yourself Electricity and Electronics, 6e 6th


Edition Stan Gibilisco - eBook PDF

https://ebooksecure.com/download/teach-yourself-electricity-and-
electronics-6e-ebook-pdf/

CISSP Passport 1st Edition Bobby E. Rogers - 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/

Lawrie's Meat Science, 8th ed 8th Edition Fidel Toldra


- eBook PDF

https://ebooksecure.com/download/lawries-meat-science-8th-ed-
ebook-pdf/

Understanding Operating Systems, 8th ed. 8th Edition


Ann Mchoes - eBook PDF

https://ebooksecure.com/download/understanding-operating-
systems-8th-ed-ebook-pdf/

(eBook PDF) Learning to Teach by Gloria Latham

http://ebooksecure.com/product/ebook-pdf-learning-to-teach-by-
gloria-latham/

(eBook PDF) Java: An Introduction to Problem Solving


and Programming 8th Edition

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

Library of Congress Control Number: 2017946911


Printed in the United States of America
Contents at a Glance
PART I GETTING STARTED
1 Becoming a Programmer ...............................................................................................3
2 Writing Your First Program ...........................................................................................13
3 Vacationing in Java .....................................................................................................27
4 Understanding How Java Programs Work ......................................................................41
PART II LEARNING THE BASICS OF PROGRAMMING
5 Storing and Changing Information in a Program ............................................................53
6 Using Strings to Communicate ....................................................................................71
7 Using Conditional Tests to Make Decisions ..................................................................83
8 Repeating an Action with Loops ...................................................................................99
PART III WORKING WITH INFORMATION IN NEW WAYS
9 Storing Information with Arrays ..................................................................................111
10 Creating Your First Object..........................................................................................125
11 Describing What Your Object Is Like ..........................................................................141
12 Making the Most of Existing Objects ..........................................................................159
PART IV MOVING INTO ADVANCED TOPICS
13 Storing Objects in Data Structures .............................................................................173
14 Handling Errors in a Program .....................................................................................187
15 Creating a Threaded Program ....................................................................................203
16 Using Inner Classes and Closures .............................................................................221
PART V PROGRAMMING A GRAPHICAL USER INTERFACE
17 Building a Simple User Interface................................................................................237
18 Laying Out a User Interface .......................................................................................259
19 Responding to User Input..........................................................................................273
PART VI WRITING INTERNET APPLICATIONS
20 Reading and Writing Files ..........................................................................................291
21 Using Java 9’s New HTTP Client ................................................................................309
22 Creating Java2D Graphics .........................................................................................325
23 Creating Minecraft Mods with Java ............................................................................341
24 Writing Android Apps.................................................................................................375
APPENDIXES
A Using the NetBeans Integrated Development Environment...........................................399
B Where to Go from Here: Java Resources ....................................................................407
C This Book’s Website .................................................................................................411
D Fixing a Problem with the Android Studio Emulator......................................................413
E Fixing Package Not Visible Errors in NetBeans ............................................................419
Contents

Introduction 1 HOUR 4: Understanding How Java


Programs Work 41
Creating an Application 41
PART I: Getting Started
Sending Arguments to Applications 43
The Java Class Library 45
HOUR 1: Becoming a Programmer 3
Trying Java Statements in JShell 49
Choosing a Language 4
Telling the Computer What to Do 6
How Programs Work 7 PART II: Learning the Basics of
When Programs Don’t Work 8 Programming
Choosing a Java Programming Tool 9
Installing a Java Development Tool 10 HOUR 5: Storing and Changing
Information in a Program 53
HOUR 2: Writing Your First Program 13 Statements and Expressions 53
What You Need to Write Programs 13 Assigning Variable Types 54
Creating the Saluton Program 14 Integers and Floating-Point Numbers 54
Beginning the Program 14 Characters and Strings 55
The class Statement 16 Other Numeric Variable Types 56
What the main Statement Does 17 The boolean Variable Type 57
Those Squiggly Bracket Marks 17 Naming Your Variables 58
Storing Information in a Variable 18 Storing Information in Variables 59
Displaying the Contents of a Variable 18 All About Operators 60
Saving the Finished Product 19 Incrementing and Decrementing a
Compiling the Program into a Class File 20 Variable 61
Fixing Errors 20 Operator Precedence 63
Running a Java Program 22 Using Expressions 64

HOUR 3: Vacationing in Java 27 HOUR 6: Using Strings to Communicate 71


First Stop: Oracle 27 Storing Text in Strings 71
A Brief History of Java 29 Displaying Strings in Programs 72
Going to School with Java 30 Using Special Characters in Strings 73
Lunch at Food Network 32 Pasting Strings Together 74
Watching the Skies at NASA 33 Using Other Variables with Strings 74
Getting Down to Business 34 Advanced String Handling 75
Stopping by SourceForge for Directions 35 Comparing Two Strings 76
Determining the Length of a String 77
Copying a String with a New Case 77 Building an Inheritance Hierarchy 130
Looking for a String 77 Converting Objects and Simple Variables 131
Presenting Credits 78 Casting Simple Variables 131
Casting Objects 132
HOUR 7: Using Conditional Tests to
Converting Simple Variables to
Make Decisions 83 Objects and Back 133
if Statements 84 Creating an Object 135
Less-Than and Greater-Than
Comparisons 84 HOUR 11: Describing What Your
Equal and Not Equal Comparisons 85 Object Is Like 141
Organizing a Program with Block Creating Variables 141
Statements 85
Creating Class Variables 143
if-else Statements 87
Creating Behavior with Methods 144
switch Statements 87
Declaring a Method 145
The Ternary Operator 90
Similar Methods with Different
Watching the Clock 91 Arguments 146
Constructors 147
HOUR 8: Repeating an Action with Loops 99 Class Methods 148
for Loops 99 Variable Scope within Methods 148
while Loops 102 Putting One Class Inside Another 149
do-while Loops 103 Using the this Keyword 151
Exiting a Loop 104 Using Class Methods and Variables 152
Naming a Loop 105
Complex for Loops 106 HOUR 12: Making the Most of
Testing Your Computer Speed 107 Existing Objects 159
The Power of Inheritance 159

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 16: Using Inner Classes and


HOUR 20: Reading and Writing Files 291
Closures 221
Streams 291
Inner Classes 222
Files 292
Anonymous Inner Classes 225
Reading Data from a Stream 293
Closures 229
Buffered Input Streams 297
Writing Data to a Stream 299
PART V: Programming a Graphical Reading and Writing Configuration
User Interface Properties 302

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

APPENDIX A: Using the NetBeans


Integrated Development Environment 399
Installing NetBeans 399
Accessing the Free Web Edition

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:

u The complete text of the book online

u Updates and corrections as they become available

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

2. Sign in or create a new account

3. Enter ISBN: 9780672337949

4. Answer the questions as proof of purchase

The Web Edition will appear under the Digital Purchases tab on your Account page.

Click the Launch link to access the product.


Introduction

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

This Hour’s To-Do List:


u Find out the reasons to learn Java.
u Discover how programs work.
u Select a Java development tool.
u Get ready to write your first program.

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.

This book aims to teach Java programming to three kinds of people:

1. Nervous novices who never tried to program before

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

Telling the Computer What to Do


A computer program, also called software, is a way to tell a computer to perform a task.
Everything that the computer does, from booting up to shutting down, is done by a program.
Mac OS X is a program; Minecraft is a program; the driver software that controls your printer is
a program; even the dreaded blue screen of death on a crashed Windows PC is a program.

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:

Dear Mr. Jeeves,

Please take care of these errands for me while I’m out asking Congress for a bailout:

Item 1: Vacuum the living room.

Item 2: Go to the store.

Item 3: Pick up soy sauce, wasabi, and as many California sushi rolls as you can carry.

Item 4: Return home.

Sincerely, your lord and master,

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:

Dear personal computer,

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

Item 3: Give the user a chance to answer the question.

Sincerely, your lord and master,

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.

How Programs Work


The collection of statements that make up a computer program is called its source code.

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.

When Programs Don’t Work


Many new programmers become discouraged when they start to test their programs. Errors
appear everywhere. Some of these are syntax errors, which are identified by the computer as it
looks at the program and becomes confused by the way a statement has been written. Other
errors are logic errors, which only are noticed by the programmer as the program is being tested
(or might be overlooked entirely). Logic errors often cause it to do something unintended.

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.

Choosing a Java Programming Tool


To start writing Java programs, you must have a Java programming tool. Several such programs
are available for Java, including the simple Java Development Kit and the more sophisticated
Eclipse, IntelliJ IDEA, and NetBeans. The latter three tools are each an integrated development
environment (IDE), a powerful tool used by professional programmers to get work done.

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.

Installing a Java Development Tool


Every hour of this book includes Java programming projects you can undertake to enhance your
knowledge of the subject matter while it percolates in your brain.

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. Why are interpreted languages slower than compiled ones?


A. They’re slower for the same reason that a person interpreting a live speech in a foreign
language is slower than a translator interpreting a printed speech. The live interpreter has
to think about each statement that’s being made as it happens, while the other interpreter
can work on the speech as a whole and take shortcuts to speed up the process. Compiled
languages can be much faster than interpreted languages because they do things to make
the program run more efficiently.

Q. Do you only answer questions about Java?


A. Not at all. Ask me anything.

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

This Hour’s To-Do List:


u Type a Java program into a text editor.
u Organize a program with bracket marks.
u Store information in a variable.
u Display the information stored in a variable.
u Save, compile, and run a program.

As you learned during Hour 1, “Becoming a Programmer,” a computer program is a set of


instructions that tells a computer what to do. These instructions are given to a computer using a
programming language.

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.

What You Need to Write Programs


As explained in Hour 1, to create Java programs, you must have a programming tool that
supports the Java Development Kit (JDK) such as the NetBeans integrated development
environment (IDE). You need a tool that can compile and run Java programs and a text editor to
write those programs.

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.

Creating the Saluton Program


The first Java program that you create will display a traditional greeting from the world of
computer science: “Saluton mondo!”

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

4. Deselect the Create Main Class check box.

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.

Beginning the Program


NetBeans groups relate programs together into a project. If you don’t have the Java24 project
open, here’s how to load it:

1. Choose File, Open Project. A file dialog appears.

2. Find and select the NetBeansProjects folder (if necessary).

3. Choose Java24 and click Open Project.

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:

1. In the Class Name field, enter Saluton.

2. In the Package field, enter com.java24hours.

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

LISTING 2.1 The Saluton Program


1: package com.java24hours;
2:
3: class Saluton {
4: public static void main(String[] arguments) {
5: // My first Java program goes here
6: }
7: }

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.

The class Statement


The first line of the program is the following:
package com.java24hours;

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.

After a blank line, the third line is this:


class Saluton {

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

What the main Statement Does


The next line of the program is the following:
public static void main(String[] arguments) {

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.

Those Squiggly Bracket Marks


In the Saluton program, Lines 3, 4, 6, and 7 contain a squiggly bracket mark of some kind—
either a { or a }. These brackets are a way to group lines of your program (in the same way that
parentheses are used in a sentence to group words). Everything between the opening bracket
{ and the closing bracket } is part of the same group.

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.

Storing Information in a Variable


In the programs you write, you need a place to store information for a brief period of time. You
can do this by using a variable, a storage place that can hold information such as integers,
floating-point numbers, true-false values, characters, and lines of text. The information stored in
a variable can change, which is how it gets the name variable.

In Saluton.java file, replace Line 5 with the following:


String greeting = "Saluton mondo!";

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

Displaying the Contents of a Variable


If you run the program at this point, it still seems like nothing happens. The command to store
text in the greeting variable occurs behind the scenes. To make the computer show that it is
doing something, you can display the contents of that variable.
Saving the Finished Product 19

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.

Now you’re getting somewhere.

Saving the Finished Product


Your program should now resemble Listing 2.2, although you might have used slightly different
spacing in Lines 5–6. Make any corrections that are needed and save the file (by choosing File,
Save).

LISTING 2.2 The Finished Version of the Saluton Program


1: package com.java24hours;
2:
3: class Saluton {
4: public static void main(String[] arguments) {
5: String greeting = "Saluton mondo!";
6: System.out.println(greeting);
7: }
8: }

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.3 A Line-by-Line Breakdown of the Saluton Program


1: Put this program in the com.java24hours package.
2:
3: The Saluton program begins here:
4: The main part of the program begins here:
5: Store the text "Saluton mondo!" in a String variable named greeting.
6: Display the contents of the variable greeting.
7: The main part of the program ends here.
8: The Saluton program ends here.
20 HOUR 2: Writing Your First Program

Listing 2.4 shows what the program would look like if written in Klingon, the language of the
warrior race from Star Trek.

LISTING 2.4 The Saluton Program in Klingon


1: This program belongs to the house of com.java2hours!
2:
3: Begin the Saluton program here if you know what's good for you!
4: The main part of the program begins here with honor!
5: Store the gibberish "Saluton mondo!" in a String variable called
greeting!
6: Display this gibberish from a tongue inferior to Klingon!
7: End the main part of the program here to avoid my wrath!
8: End the Saluton program now and be grateful you were spared!

Compiling the Program into a Class File


Before you can run a Java program, you must compile it. When you compile a program, the
instructions given to the computer in the program are converted into a form the computer can
better understand.

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:

u The name of the Java program

u The type of error

u The line where the error was found

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.

Running a Java Program


To see whether the Saluton program does what you want, run the class with the Java
interpreter. In NetBeans, choose the menu command Run, Run File. An Output pane opens
below the source code editor. In this pane, if there are no errors, the program displays the output,
as shown in Figure 2.3.

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:

1. Write the program with a text editor or a tool such as NetBeans.

2. Compile the program into a class file.

3. Tell the Java Virtual Machine to run the class.

4. Call your mother.

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.

Q. How can I visit Antarctica?


A. If you’re not willing to become a scientific researcher or a support staffer such as a cook,
electrician, or doctor, you can become one of the 10,000 people who visit the frozen conti-
nent annually as tourists.

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.

To see solutions to these activities, visit the book’s website at www.java24hours.com.


HOUR 3
Vacationing in Java

This Hour’s To-Do List:


u Discover the history of Java.
u Learn the benefits of using the language.
u See examples of Java at work.

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.

First Stop: Oracle


The Java vacation begins at www.java.com, a site published by Oracle, the company that
develops the Java language.

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

A Brief History of Java


Bill Joy, one of the executives at Sun Microsystems when the company created Java, called the
language “the end result of 15 years of work to produce a better, more reliable way to write
computer programs.” Java’s creation was a little more complicated than that.

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.0—The original release (1995)

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.3—Enhanced multimedia (2000)

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 6—The built-in Derby database and web services (2006)

u Java 7—Memory and resource management improvements and the Nimbus graphical
user interface (2011)

u Java 8—Closures (2014)

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.

Going to School with Java


The Web includes numerous resources for educators and schoolchildren. Because Java apps
can offer a more interactive experience than web pages, the language is a natural choice for
programs that enhance learning.
Going to School with Java 31

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

Lunch at Food Network


After working up an appetite on our first two stops, take a lunch break with Food Network in the
Kitchen, a free Java app created by the gustatory television channel.

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.

Watching the Skies at NASA


The first afternoon stop on the Java tour is a trip to space. NASA is a U.S. government agency
that makes extensive use of Java. One example is ISS Detector, a free app from the developer
RunaR that helps stargazers keep an eye out for the International Space Station and several
orbiting satellites.

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!

Getting Down to Business


At this point in your travels, you might have the impression that Java is primarily of use to
space buffs, amateur chefs, and elven warriors. The next stop on our trip shows an example of
Java getting down to business.

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:

u A quote object, which represents an individual stock quote

u A portfolio object, which holds a set of quotes for specific stocks

u A ticker object, which displays a portfolio

u An Internet object, a user object, and many others

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.

Stopping by SourceForge for Directions


This world tour of Java programs is being led by a professional who is well versed in the hazards
and highlights of app-based travel. You’ll be venturing out on your own trips soon, so it’s
worthwhile to learn the lay of the land at an incredibly useful site for programmers: SourceForge,
one of the best places to find complete examples of working programs written with Java (or any
other language). Find it at www.sourceforge.net.

SourceForge is an enormous website devoted to collaborative programming projects. If you have


an interest in working with others on a program you are developing, you can start a project on
SourceForge, share all its files, recruit others, and communicate with them. The 430,000-plus
projects on the site all are open source, which means that the programmers have shared all the
source code. In case you’re unfamiliar with the term, source code is another name for the text
files that are used to create computer programs. The Saluton.java file you developed during
Hour 2 is an example of source code.
36 HOUR 3: Vacationing in Java

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.

Unless you stopped reading this book to play Celtic Heroes.

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

There is a variety of man whose eye inevitably exaggerates, whose


ear inevitably hears more than the band plays, whose imagination
inevitably doubles and triples the news brought in by his five senses.
He is the enthusiast, the believer, the romantic. He is the sort of
fellow who, if he were a bacteriologist, would report the
streptococcus pyogenes to be as large as a St. Bernard dog, as
intelligent as Socrates, as beautiful as Beauvais Cathedral and as
respectable as a Yale professor.

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

Faith may be defined briefly as an illogical belief in the occurrence of


the improbable. Or, psychoanalytically, as a wish neurose. There is
thus a flavor of the pathological in it; it goes beyond the normal
intellectual process and passes into the murky domain of
transcendental metaphysics. A man full of faith is simply one who
has lost (or never had) the capacity for clear and realistic thought.
He is not a mere ass: he is actually ill. Worse, he is incurable, for
disappointment, being essentially an objective phenomenon, cannot
permanently affect his subjective infirmity. His faith takes on the
virulence of a chronic infection. What he usually says, in substance,
is this: “Let us trust in God, who has always fooled us in the past
.”

The Worker

All democratic theories, whether Socialistic or bourgeois, necessarily


take in some concept of the dignity of labor. If the have-not were
deprived of this delusion that his sufferings in the sweat-shop are
somehow laudable and agreeable to God, there would be little left in
his ego save a belly-ache. Nevertheless, a delusion is a delusion, and
this is one of the worst. It arises out of confusing the pride of
workmanship of the artist with the dogged, painful docility of the
machine. The difference is important and enormous. If he got no
reward whatever, the artist would go on working just the same; his
actual reward, in fact, is often so little that he almost starves. But
suppose a garment-worker got nothing for his labor: would he go on
working just the same? Can one imagine him submitting voluntarily
to hardship and sore want that he might express his soul in 200
more pairs of pantaloons?

The Physician

Hygiene is the corruption of medicine by morality. It is impossible to


find a hygienist who does not debase his theory of the healthful with
a theory of the virtuous. The whole hygienic art, indeed, resolves
itself into an ethical exhortation, and, in the sub-department of sex,
into a puerile and belated advocacy of asceticism. This brings it, at
the end, into diametrical conflict with medicine proper. The aim of
medicine is surely not to make men virtuous; it is to safeguard and
rescue them from the consequences of their vices. The true
physician does not preach repentance; he offers absolution.
6

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.

The Business Man

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 Average Man

It is often urged against the so-called scientific Socialists, with their


materialistic conception of history, that they overlook certain spiritual
qualities that are independent of wage scales and metabolism.
These qualities, it is argued, color the aspirations and activities of
civilized man quite as much as they are colored by his material
condition, and so make it impossible to consider him simply as an
economic machine. As examples, the anti-Marxians cite patriotism,
pity, the æsthetic sense and the yearning to know God. Unluckily,
the examples are ill-chosen. Millions of men are quite devoid of
patriotism, pity and the æsthetic sense, and have no very active
desire to know God. Why don’t the anti-Marxians cite a spiritual
quality that is genuinely universal? There is one readily to hand. I
allude to cowardice. It is, in one form or other, visible in every
human being; it almost serves to mark off the human race from all
the other higher animals. Cowardice, I believe, is at the bottom of
the whole caste system, the foundation of every organized society,
including the most democratic. In order to escape going to war
himself, the peasant was willing to give the warrior certain privileges
—and out of those privileges has grown the whole structure of
civilization. Go back still further. Property arose out of the fact that a
few relatively courageous men were able to accumulate more
possessions than whole hordes of cowardly men, and, what is more,
to retain them after accumulating them.
10

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

Nietzsche, in altering Schopenhauer’s will-to-live to will-to-power,


probably fell into a capital error. The truth is that the thing the
average man seeks in life is not primarily power, but peace; all his
struggle is toward a state of tranquillity and equilibrium; what he
always dreams of is a state in which he will have to do battle no
longer. This dream plainly enters into his conception of Heaven; he
thinks of himself, post mortem, browsing about the celestial
meadows like a cow in a safe pasture. A few extraordinary men
enjoy combat at all times, and all men are inclined toward it at
orgiastic moments, but the race as a race craves peace, and man
belongs among the more timorous, docile and unimaginative
animals, along with the deer, the horse and the sheep. This craving
for peace is vividly displayed in the ages-long conflict of the sexes.
Every normal woman wants to be married, for the plain reason that
marriage offers her security. And every normal man avoids marriage
as long as possible, for the equally plain reason that marriage
invades and threatens his security.

12
The Relative

The normal man’s antipathy to his relatives, particularly of the


second degree, is explained by psychologists in various tortured and
improbable ways. The true explanation, I venture, is a good deal
simpler. It lies in the plain fact that every man sees in his relatives,
and especially in his cousins, a series of grotesque caricatures of
himself. They exhibit his qualities in disconcerting augmentation or
diminution; they fill him with a disquieting feeling that this, perhaps,
is the way he appears to the world and so they wound his amour
propre and give him intense discomfort. To admire his relatives
whole-heartedly a man must be lacking in the finer sort of self-
respect.

13

The Friend

One of the most mawkish of human delusions is the notion that


friendship should be eternal, or, at all events, life-long, and that any
act which puts a term to it is somehow discreditable. The fact is that
a man of active and resilient mind outwears his friendships just as
certainly as he outwears his love affairs, his politics and his
epistemology. They become threadbare, shabby, pumped-up,
irritating, depressing. They convert themselves from living realities
into moribund artificialities, and stand in sinister opposition to
freedom, self-respect and truth. It is as corrupting to preserve them
after they have grown fly-blown and hollow as it is to keep up the
forms of passion after passion itself is a corpse. Every act and
attitude that they involve thus becomes an act of hypocrisy, an
attitude of dishonesty.... A prudent man, remembering that life is
short, gives an hour or two, now and then, to a critical examination
of his friendships. He weighs them, edits them, tests the metal of
them. A few he retains, perhaps with radical changes in their terms.
But the majority he expunges from his minutes and tries to forget,
as he tries to forget the cold and clammy loves of year before last.

XV. THE DISMAL SCIENCE

Every man, as the Psalmist says, to his own poison, or poisons, as


the case may be. One of mine, following hard after theology, is
political economy. What! Political economy, that dismal science?
Well, why not? Its dismalness is largely a delusion, due to the fact
that its chief ornaments, at least in our own day, are university
professors. The professor must be an obscurantist or he is nothing;
he has a special and unmatchable talent for dullness; his central aim
is not to expose the truth clearly, but to exhibit his profundity, his
esotericity—in brief, to stagger sophomores and other professors.
The notion that German is a gnarled and unintelligible language
arises out of the circumstance that it is so much written by
professors. It took a rebel member of the clan, swinging to the
antipodes in his unearthly treason, to prove its explicitness, its
resiliency, it downright beauty. But Nietzsches are few, and so
German remains soggy, and political economy continues to be
swathed in dullness. As I say, however, that dullness is only
superficial. There is no more engrossing book in the English
language than Adam Smith’s “The Wealth of Nations”; surely the
eighteenth century produced nothing that can be read with greater
ease to-day. Nor is there any inherent reason why even the most
technical divisions of its subject should have gathered cobwebs with
the passing of the years. Taxation, for example, is eternally lively; it
concerns ninetenths of us more directly than either smallpox or golf,
and has just as much drama in it; moreover, it has been mellowed
and made gay by as many gaudy, preposterous theories. As for
foreign exchange, it is almost as romantic as young love, and quite
as resistent to formulæ. Do the professors make an autopsy of it?
Then read the occasional treatises of some professor of it who is not
a professor, say, Garet Garrett or John Moody.
Unluckily, Garretts and Moodys are almost as rare as Nietzsches, and
so the amateur of such things must be content to wrestle with the
professors, seeking the violet of human interest beneath the
avalanche of their graceless parts of speech. A hard business, I
daresay, to one not practiced, and to its hardness there is added the
disquiet of a doubt. That doubt does not concern itself with the
doctrine preached, at least not directly. There may be in it nothing
intrinsically dubious; on the contrary, it may appear as sound as the
binomial theorem, as well supported as the dogma of infant
damnation. But all the time a troubling question keeps afloat in the
air, and that is briefly this: What would happen to the learned
professors if they took the other side? In other words, to what
extent is political economy, as professors expound and practice it, a
free science, in the sense that mathematics and physiology are free
sciences? At what place, if any, is speculation pulled up by a rule
that beyond lies treason, anarchy and disaster? These questions, I
hope I need not add, are not inspired by any heterodoxy in my own
black heart. I am, in many fields, a flouter of the accepted revelation
and hence immoral, but the field of economics is not one of them.
Here, indeed, I know of no man who is more orthodox than I am. I
believe that the present organization of society, as bad as it is, is
better than any other that has ever been proposed. I reject all the
sure cures in current agitation, from government ownership to the
single tax. I am in favor of free competition in all human enterprises,
and to the utmost limit. I admire successful scoundrels, and shrink
from Socialists as I shrink from Methodists. But all the same, the
aforesaid doubt pursues me when I plow through the solemn
disproofs and expositions of the learned professors of economics,
and that doubt will not down. It is not logical or evidential, but
purely psychological. And what it is grounded on is an unshakable
belief that no man’s opinion is worth a hoot, however well supported
and maintained, so long as he is not absolutely free, if the spirit
moves him, to support and maintain the exactly contrary opinion. In
brief, human reason is a weak and paltry thing so long as it is not
wholly free reason. The fact lies in its very nature, and is revealed by
its entire history. A man may be perfectly honest in a contention,
and he may be astute and persuasive in maintaining it, but the
moment the slightest compulsion to maintain it is laid upon him, the
moment the slightest external reward goes with his partisanship or
the slightest penalty with its abandonment, then there appears a
defect in his ratiocination that is more deep-seated than any error in
fact and more destructive than any conscious and deliberate bias. He
may seek the truth and the truth only, and bring up his highest
talents and diligence to the business, but always there is a specter
behind his chair, a warning in his ear. Always it is safer and more
hygienic for him to think one way than to think another way, and in
that bald fact there is excuse enough to hold his whole chain of
syllogisms in suspicion. He may be earnest, he may be honest, but
he is not free, and if he is not free, he is not anything.
Well, are the reverend professors of economics free? With the
highest respect, I presume to question it. Their colleagues of
archeology may be reasonably called free, and their colleagues of
bacteriology, and those of Latin grammar and sidereal astronomy,
and those of many another science and mystery, but when one
comes to the faculty of political economy one finds that freedom as
plainly conditioned, though perhaps not as openly, as in the faculty
of theology. And for a plain reason. Political economy, so to speak,
hits the employers of the professors where they live. It deals, not
with ideas that affect those employers only occasionally or only
indirectly or only as ideas, but with ideas that have an imminent and
continuous influence upon their personal welfare and security, and
that affect profoundly the very foundations of that social and
economic structure upon which their whole existence is based. It is,
in brief, the science of the ways and means whereby they have come
to such estate, and maintain themselves in such estate, that they
are able to hire and boss professors. It is the boat in which they sail
down perilous waters—and they must needs yell, or be more or less
than human, when it is rocked. Now and then that yell duly resounds
in the groves of learning. One remembers, for example, the trial,
condemnation and execution of Prof. Dr. Scott Nearing at the
University of Pennsylvania, a seminary that is highly typical, both in
its staff and in its control. Nearing, I have no doubt, was wrong in
his notions—honestly, perhaps, but still wrong. In so far as I heard
them stated at the time, they seemed to me to be hollow and of no
validity. He has since discharged them from the chautauquan stump,
and at the usual hinds. They have been chiefly accepted and
celebrated by men I regard as asses. But Nearing was not thrown
out of the University of Pennsylvania, angrily and ignominiously,
because he was honestly wrong, or because his errors made him
incompetent to prepare sophomores for their examinations; he was
thrown out because his efforts to get at the truth disturbed the
security and equanimity of the rich ignoranti who happened to
control the university, and because the academic slaves and
satellites of these shopmen were restive under his competition for
the attention of the student-body. In three words, he was thrown
out because he was not safe and sane and orthodox. Had his
aberration gone in the other direction, had he defended child labor
as ardently as he denounced it and denounced the minimum wage
as ardently as he defended it, then he would have been quite as
secure in his post, for all his cavorting in the newspapers, as
Chancellor Day was at Syracuse.
Now consider the case of the professors of economics, near and far,
who have not been thrown out. Who will say that the lesson of the
Nearing débâcle has been lost upon them? Who will say that the
potency of the wealthy men who command our universities—or most
of them—has not stuck in their minds? And who will say that, with
this sticking remembered, their arguments against Nearing’s so-
called ideas are as worthy of confidence and respect as they would
be if they were quite free to go over to Nearing’s side without
damage? Who, indeed, will give them full credit, even when they are
right, so long as they are hamstrung, nose-ringed and tied up in
gilded pens? It seems to me that these considerations are enough to
cast a glow of suspicion over the whole of American political
economy, at least in so far as it comes from college economists. And,
in the main, it has that source, for, barring a few brilliant journalists,
all our economists of any repute are professors. Many of them are
able men, and most of them are undoubtedly honest men, as
honesty goes in the world, but over practically every one of them
there stands a board of trustees with its legs in the stock market and
its eyes on the established order, and that board is ever alert for
heresy in the science of its being, and has ready means of punishing
it, and a hearty enthusiasm for the business. Not every professor,
perhaps, may be sent straight to the block, as Nearing was, but
there are plenty of pillories and guardhouses on the way, and every
last pedagogue must be well aware of it.
Political economy, in so far as it is a science at all, was not pumped
up and embellished by any such academic clients and ticket-of-leave
men. It was put on its legs by inquirers who were not only safe from
all dousing in the campus pump, but who were also free from the
mental timorousness and conformity which go inevitably with school-
teaching—in brief, by men of the world, accustomed to its free air, its
hospitality to originality and plain speaking. Adam Smith, true
enough, was once a professor, but he threw up his chair to go to
Paris, and there he met, not more professors, but all the current
enemies of professors—the Nearings and Henry Georges and Karl
Marxes of the time. And the book that he wrote was not orthodox,
but revolutionary. Consider the others of that bulk and beam:
Bentham, Ricardo, Mill and their like. Bentham held no post at the
mercy of bankers and tripe-sellers; he was a man of independent
means, a lawyer and politician, and a heretic in general practice. It is
impossible to imagine such a man occupying a chair at Harvard or
Princeton. He had a hand in too many pies: he was too rebellious
and contumacious: he had too little respect for authority, either
academic or worldly. Moreover, his mind was too wide for a
professor; he could never remain safely in a groove; the whole field
of social organization invited his inquiries and experiments. Ricardo?
Another man of easy means and great worldly experience—by
academic standards, not even educated. To-day, I daresay, such
meager diplomas as he could show would not suffice to get him an
instructor’s berth in a fresh-water seminary in Iowa. As for Mill, he
was so well grounded by his father that he knew more, at eighteen,
than any of the universities could teach him, and his life thereafter
was the exact antithesis of that of a cloistered pedagogue. Moreover,
he was a heretic in religion and probably violated the Mann act of
those days—an offense almost as heinous, in a college professor of
economics, as giving three cheers for Prince Kropotkin.
I might lengthen the list, but humanely refrain. The point is that
these early English economists were all perfectly free men, with
complete liberty to tell the truth as they saw it, regardless of its
orthodoxy or lack of orthodoxy. I do not say that the typical
American economist of to-day is not as honest, nor even that he is
not as diligent and competent, but I do say that he is not as free—
that penalties would come upon him for stating ideas that Smith or
Ricardo or Bentham or Mill, had he so desired, would have been free
to state without damage. And in that menace there is an
ineradicable criticism of the ideas that he does state, and it lingers
even when they are plausible and are accepted. In France and
Germany, where the universities and colleges are controlled by the
state, the practical effect of such pressure has been frequently
demonstrated. In the former country the violent debate over social
and economic problems during the quarter century before the war
produced a long list of professors cashiered for heterodoxy, headed
by the names of Jean Jaurès and Gustave Hervé. In Germany it
needed no Nietzsche to point out the deadening produced by this
state control. Germany, in fact, got out of it an entirely new species
of economist—the state Socialist who flirted with radicalism with one
eye and kept the other upon his chair, his salary and his pension.
The Nearing case and the rebellions of various pedagogues
elsewhere show that we in America stand within the shadow of a
somewhat similar danger. In economics, as in the other sciences, we
are probably producing men who are as good as those on view in
any other country. They are not to be surpassed for learning and
originality, and there is no reason to believe that they lack honesty
and courage. But honesty and courage, as men go in the world, are
after all merely relative values. There comes a point at which even
the most honest man considers consequences, and even the most
courageous looks before he leaps. The difficulty lies in establishing
the position of that point. So long as it is in doubt, there will remain,
too, the other doubt that I have described. I rise in meeting, I
repeat, not as a radical, but as one of the most hunkerous of the
orthodox. I can imagine nothing more dubious in fact and wobbly in
logic than some of the doctrines that amateur economists, chiefly
Socialists, have set afloat in this country during the past dozen
years. I have even gone to the trouble of writing a book against
them; my convictions and instincts are all on the other side. But I
should be a great deal more comfortable in those convictions and
instincts if I were convinced that the learned professors were really
in full and absolute possession of academic freedom—if I could
imagine them taking the other tack now and then without damnation
to their jobs, their lecture dates, their book sales and their hides.

XVI. MATTERS OF STATE

Le Contrat Social

All government, in its essence, is a conspiracy against the superior


man: its one permanent object is to police him and cripple him. If it
be aristocratic in organization, then it seeks to protect the man who
is superior only in law against the man who is superior in fact; if it
be democratic, then it seeks to protect the man who is inferior in
every way against both. Thus one of its primary functions is to
regiment men by force, to make them as much alike as possible and
as dependent upon one another as possible, to search out and
combat originality among them. All it can see in an original idea is
potential change, and hence an invasion of its prerogatives. The
most dangerous man, to any government, is the man who is able to
think things out for himself, without regard to the prevailing
superstitions and taboos. Almost inevitably he comes to the
conclusion that the government he lives under is dishonest, insane
and intolerable, and so, if he is romantic, he tries to change it. And
even if he is not romantic personally he is very apt to spread
discontent among those who are. Ludwig van Beethoven was
certainly no politician. Nor was he a patriot. Nor had he any
democratic illusions in him: he held the Viennese in even more
contempt than he held the Hapsburgs. Nevertheless, I am convinced
that the sharp criticism of the Hapsburg government that he used to
loose in the cafés of Vienna had its effects—that some of his ideas of
1818, after a century of germination, got themselves translated into
acts in 1918. Beethoven, like all other first-rate men, greatly disliked
the government he lived under. I add the names of Goethe, Heine,
Wagner and Nietzsche, to keep among Germans. That of Bismarck
might follow: he admired the Hohenzollern idea, as Carlyle did, not
the German people or the German administration. In his
“Errinerungen,” whenever he discusses the government that he was
a part of, he has difficulty keeping his contempt within the bounds of
decorum.
Nine times out of ten, it seems to me, the man who proposes a
change in the government he lives under, no matter how defective it
may be, is romantic to the verge of sentimentality. There is seldom,
if ever, any evidence that the kind of government he is unlawfully
inclined to would be any better than the government he proposes to
supplant. Political revolutions, in truth, do not often accomplish
anything of genuine value; their one undoubted effect is simply to
throw out one gang of thieves and put in another. After a revolution,
of course, the successful revolutionists always try to convince
doubters that they have achieved great things, and usually they
hang any man who denies it. But that surely doesn’t prove their
case. In Russia, for many years, the plain people were taught that
getting rid of the Czar would make them all rich and happy, but now
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about testbank and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebooksecure.com

You might also like