0% found this document useful (0 votes)
28 views90 pages

Brief Java Early Objects 9th Edition Cay Horstmann Download

The document provides information about the book 'Brief Java Early Objects 9th Edition' by Cay Horstmann, which serves as an introduction to Java and computer programming for beginners. It emphasizes a gradual approach to learning object-oriented programming, with practical guidance, problem-solving strategies, and numerous exercises. The book is designed to engage students with interactive content and covers essential programming concepts while reinforcing sound engineering practices.

Uploaded by

kiongahavab
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)
28 views90 pages

Brief Java Early Objects 9th Edition Cay Horstmann Download

The document provides information about the book 'Brief Java Early Objects 9th Edition' by Cay Horstmann, which serves as an introduction to Java and computer programming for beginners. It emphasizes a gradual approach to learning object-oriented programming, with practical guidance, problem-solving strategies, and numerous exercises. The book is designed to engage students with interactive content and covers essential programming concepts while reinforcing sound engineering practices.

Uploaded by

kiongahavab
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/ 90

Brief Java Early Objects 9th Edition Cay

Horstmann download

https://ebookbell.com/product/brief-java-early-objects-9th-
edition-cay-horstmann-24009848

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Introduction To Java Programming Brief Version Eleventh Edition Liang

https://ebookbell.com/product/introduction-to-java-programming-brief-
version-eleventh-edition-liang-10818442

Introduction To Java Programming Brief Version With Access Code Tenth


Edition Brief Version Liang

https://ebookbell.com/product/introduction-to-java-programming-brief-
version-with-access-code-tenth-edition-brief-version-liang-21867588

Introduction To Java Programming Brief Version 9th Edition Y Daniel


Liang

https://ebookbell.com/product/introduction-to-java-programming-brief-
version-9th-edition-y-daniel-liang-4060200

Intro To Java Programming Brief Version 10th Edition Y Daniel Liang

https://ebookbell.com/product/intro-to-java-programming-brief-
version-10th-edition-y-daniel-liang-11124908
Common Java Cookbook Timothy M Obrien

https://ebookbell.com/product/common-java-cookbook-timothy-m-
obrien-1229234

Brief Supportive Psychotherapy A Treatment Manual And Clinical


Approach 1st Edition John C Markowitz

https://ebookbell.com/product/brief-supportive-psychotherapy-a-
treatment-manual-and-clinical-approach-1st-edition-john-c-
markowitz-44874682

Brief Behavioural Activation For Adolescent Depression Shirley


Reynolds

https://ebookbell.com/product/brief-behavioural-activation-for-
adolescent-depression-shirley-reynolds-46608492

Brief Interviews With Hideous Men David Foster Wallace

https://ebookbell.com/product/brief-interviews-with-hideous-men-david-
foster-wallace-46931056

Brief Interventions For Adolescent Alcohol And Substance Abuse 1st


Edition Peter M Monti

https://ebookbell.com/product/brief-interventions-for-adolescent-
alcohol-and-substance-abuse-1st-edition-peter-m-monti-47215740
9/e

Cay Horstmann

Brief Java
Early Objects
9/e

Brief Java
Early Objects

bbjeo_fm.indd 1 11/27/18 1:37 PM


bbjeo_fm.indd 2 11/27/18 1:37 PM
9/e

Brief Java Early Objects


© Jeremy Woodhouse/Holly Wilmeth/Getty Images.

Cay Horstmann
San Jose State University

bbjeo_fm.indd 3 11/27/18 1:37 PM


VICE PRESIDENT AND EXECUTIVE PUBLISHER Laurie Rosatone
EXECUTIVE EDITOR Joanna Dingle
PROJECT MANAGER/DEVELOPMENT EDITOR Cindy Johnson
EDITORIAL ASSISTANT Crystal Franks
LEAD PRODUCT DESIGNER Tom Kulesa
MARKETING MANAGER Michael MacDougald
PRODUCTION MANAGER Nichole Urban
PRODUCTION MANAGER Nicole Repasky
PRODUCTION MANAGEMENT SERVICES Cindy Johnson, Publishing Services
PHOTO EDITOR Anindita Adiyal
COVER DESIGNER Joanna Vieira
COVER PHOTOS (tiger) © ArtMediaFactory/Shutterstock;
(rhino) © GUDKOV ANDREY/Shutterstock;
(bird) © Jeremy Woodhouse/Holly Wilmeth/
Getty Images; (tree frog) © kuritafsheen/Getty
Images.

This book was set in 10.5/12 Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad
Graphics/Versailles. The cover was printed by Quad Graphics/Versailles.

Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more
than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is
built on a foundation of principles that include responsibility to the communities we serve and where we live
and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental,
social, economic, and ethical challenges we face in our business. Among the issues we are addressing are carbon
impact, paper specifications and procurement, ethical conduct within our business and among our vendors,
and community and charitable support. For more information, please visit our website: www.wiley.com/go/
citizenship.

This book is printed on acid-free paper. ∞

Copyright © 2019, 2016 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be repro-
duced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photo-
copying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United
States Copyright Act, without either the prior written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Dan-
vers, MA 01923, (978) 750-8400, fax (978) 646-8600, or on the Web at www.copyright.com. Requests to the
Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111
River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008.

Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at: www.wiley.com/go/returnlabel. If you have
chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy.
Outside of the United States, please contact your local representative.

ePUB ISBN 978-1-119-49913-8

Printed in the United States of America.

The inside back cover will contain printing identification and country of origin if omitted from this page. In
addition, if the ISBN on the back cover differs from the ISBN on this page, the one on the back cover is correct.

10 9 8 7 6 5 4 3 2 1
P R E FA C E

This book is an introduction to Java and computer programming that focuses on the
essentials—and on effective learning. The book is designed to serve a wide range of
student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program-
ming experience is required, and only a modest amount of high school algebra is
needed.
Here are the key features of this book:
Start objects early, teach object orientation gradually.
In Chapter 2, students learn how to use objects and classes from the standard library.
Chapter 3 shows the mechanics of implementing classes from a given specification.
Students then use simple objects as they master branches, loops, and arrays. Object-
oriented design starts in Chapter 8. This gradual approach allows students to use
objects throughout their study of the core algorithmic topics, without teaching bad
habits that must be un-learned later.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “How To” guides help students with
common programming tasks. Numerous Worked Examples demonstrate how to
apply chapter concepts to interesting problems.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode) • Solve a Simpler Problem First
• Tracing Objects • Adapting Algorithms
• First Do It By Hand (doing sample • Discovering Algorithms by
calculations by hand) Manipulating Physical Objects
• Flowcharts • Patterns for Object Data
• Selecting Test Cases • Thinking Recursively
• Hand-Tracing • Estimating the Running Time of
• Storyboards an Algorithm

Practice makes perfect.


Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. Each section con-
tains numerous exercises that ask students to carry out progressively more complex
tasks: trace code and understand its effects, produce program snippets from prepared
parts, and complete simple programs. Additional review and programming problems
are provided at the end of each chapter.

bbjeo_fm.indd 5 11/27/18 1:37 PM


vi Preface

A visual approach motivates the reader and eases navigation.


Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-by-
step figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate. Visual features help the reader
An encyclopedic coverage is not helpful for a begin- with navigation.
ning programmer, but neither is the opposite—
reducing the material to a list of simplistic bullet points. In this book, the essentials are
presented in digestible chunks, with separate notes that go deeper into good practices
or language features when the reader is ready for the additional information. You will
© Terraxplorer/iStockphoto.
not find artificial over-simplifications that give an illusion of knowledge.
Reinforce sound engineering practices.
A multitude of useful tips on software quality and common errors encourage the
development of good programming habits. The optional testing track focuses on
test-driven development, encouraging students to test their programs systematically.
Provide an optional graphics track.
Graphical shapes are splendid examples of objects. Many students enjoy writing pro-
grams that create drawings or use graphical user interfaces. If desired, these topics can
be integrated into the course by using the materials at the end of Chapters 2, 3, and 10.
Engage with optional science and business exercises.
End-of-chapter exercises are enhanced with problems from scientific and business
domains. Designed to engage students, the exercises illustrate the value of program-
ming in applied fields.

New to This Edition


Adapted to Java Versions 8 Through 11
This edition takes advantage of modern Java features when they are pedagogically
sensible. I continue to use “pure” interfaces with only abstract methods. Default,
static, and private interface methods are introduced in a Special Topic. Lambda
expressions are optional for user interface callback.
The “diamond” syntax for generic classes is introduced as a Special Topic in Chap-
ter 7 and used systematically starting with Chapter 15. Local type inference with the
var keyword is described in a Special Topic. Useful features such as the try-with-
resources statement are integrated into the text.

Interactive Learning
With this edition, interactive content is front and center. Immersive activities integrate
with this text and engage students in activities designed to foster in-depth learning.
Students don’t just watch animations and code traces, they work on generating
them. Live code samples invite the reader to experiment and to learn programming

bbjeo_fm.indd 6 11/27/18 1:37 PM


Preface vii

constructs first hand. The activities provide instant feedback to show students what
they did right and where they need to study more.

A Tour of the Book


The book can be naturally grouped into three parts, as illustrated by Figure 1. The
organization of chapters offers the same flexibility as the previous edition; dependen-
cies among the chapters are also shown in the figure.

Part A: Fundamentals (Chapters 1–7)


Chapter 1 contains a brief introduction to computer science and Java programming.
Chapter 2 shows how to manipulate objects of predefined classes. In Chapter 3,

1. Introduction

Fundamentals
2. Using Objects
Object-Oriented Design
Data Structures & Algorithms
e eText Chapters
3. Implementing
Classes

4. Fundamental
Data Types

5. Decisions

6. Loops

Sections 11.1 and 11.2


(text file processing) can be 7. Arrays
covered with Chapter 6. 6. Iteration
and Array Lists

11. Input/Output 8. Designing


13. Recursion
e
and Exception Classes
Handling

15. The Java 14. Sorting and


9. Inheritance
e
Collections Searching

e
Framework

10. Interfaces

Figure 1
Chapter 12. Object-
Oriented Design
Dependencies

bbjeo_fm.indd 7 11/27/18 1:37 PM


viii Preface

you will build your own simple classes from given specifications. Fundamental data
types, branches, loops, and arrays are covered in Chapters 4–7.

Part B: Object-Oriented Design (Chapters 8–12)


Chapter 8 takes up the subject of class design in a systematic fashion, and it intro-
duces a very simple subset of the UML notation. Chapter 9 covers inheritance and
polymorphism, whereas Chapter 10 covers interfaces. Exception handling and basic
file input/output are covered in Chapter 11. The exception hierarchy gives a useful
example for inheritance. Chapter 12 contains an introduction to object-oriented
design, including two significant case studies.

Part C: Data Structures and Algorithms (Chapters 13–15)


Chapters 13 through 15 (in the eText) contain an introduction to algorithms and
data structures, covering recursion, sorting and searching, and the Java Collections
Framework. These topics may be outside the scope of a one-semester course, but can
be covered as desired after Chapter 7 (see Figure 1). Recursion, in Chapter 13, starts
with simple examples and progresses to meaningful applications that would be dif-
ficult to implement iteratively. Chapter 14 covers quadratic sorting algorithms as well
as merge sort, with an informal introduction to big-Oh notation. Each data structure
is presented in the context of the standard Java collections library. You will learn the
essential abstractions of the standard library (such as iterators, sets, and maps) as well
as the performance characteristics of the various collections.

Appendices
Many instructors find it highly beneficial to require a consistent style for all assign-
ments. If the style guide in Appendix E conflicts with instructor sentiment or local
customs, however, it is available in electronic form so that it can be modified. Appen-
dices F–J are available in the eText.
A. The Basic Latin and Latin-1 Subsets of Unicode
B. Java Operator Summary
C. Java Reserved Word Summary
D. The Java Library
E. Java Language Coding Guidelines
F. Tool Summary
G. Number Systems
H. UML Summary
I. Java Syntax Summary
J. HTML Summary

Interactive eText Designed for Programming Students


Available online through wiley.com, vitalsource.com, or at your local bookstore, the
enhanced eText features integrated student coding activities that foster in-depth
learning. Designed by Cay Horstmann, these activities provide instant feedback to
show students what they did right and where they need to study more. Students do
more than just watch animations and code traces; they work on generating them right
in the eText environment. For a preview of these activities, check out http://wiley.
com/college/sc/horstmann.

bbjeo_fm.indd 8 11/27/18 1:37 PM


Preface ix

Customized formats are also available in both print and digital formats and pro-
vide your students with curated content based on your unique syllabus.
Please contact your Wiley sales rep for more information about any of these
options.

Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/go/bjeo7 to visit the online companion sites, which include

• Source code for all example programs in the book and its Worked Examples, plus
additional example programs.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• CodeCheck®, an innovative online service that allows instructors to design their
own automatically graded programming exercises.

bbjeo_fm.indd 9 11/27/18 1:37 PM


x Walkthrough

Walkthrough of the Learning Aids


The pedagogical elements in this book work together to focus on and reinforce key
concepts and fundamental principles of programming, with additional tips and detail
organized to support and deepen these fundamentals. In addition to traditional
features, such as chapter objectives and a wealth of exercises, each chapter contains
elements geared to today’s visual learner.

6.3 The for Loop 183

6.3 The for Loop


Throughout each chapter,
margin notes show where The for loop is used
when a value runs
It often happens that you want to execute a sequence of statements a given number of
times. You can use a while loop that is controlled by a counter, as in the following
new concepts are introduced from a starting point
to an ending point
example:
with a constant int counter = 5; // Initialize the counter
and provide an outline of key ideas. increment or while (counter <= 10) // Check the counter
decrement. {
sum = sum + counter;
counter++; // Update the counter
}

Because this loop type is so common, there is a spe-


cial form for it, called the for loop (see Syntax 6.2).
for (int counter = 5; counter <= 10; counter++)
{
sum = sum + counter;
}

Some people call this loop count-controlled. In con-


trast, the while loop of the preceding section can
be called an event-controlled loop because it exe-
cutes until an event occurs; namely that the balance
reaches the target. Another commonly used term for
a count-controlled loop is definite. You know from
the outset that the loop body will be executed a defi-
nite number of times; ten times in our example. In
© Enrico Fianchini/iStockphoto.
contrast, you do not know how many iterations it
takes to accumulate a target balance. Such a loop is You can visualize the for loop as
Annotated syntax boxes called indefinite. an orderly sequence of steps.

provide a quick, visual overview


of new language constructs. Syntax 6.2 for Statement

Syntax for (initialization; condition; update)


{
statements
}
These three
expressions should be related.
See Programming Tip 6.1.

Annotations explain required This initialization The condition is This update is


components and point to more happens once
before the loop starts.
checked before
each iteration.
executed after
each iteration.
information on common errors
for (int i = 5; i <= 10; i++)
or best practices associated The variable i is
{
sum = sum + i; This loop executes 6 times.
with the syntax. defined only in this for loop.
See Special Topic 6.1.
} See Programming Tip 6.3.

Analogies to everyday objects are


used to explain the nature and behavior
of concepts such as variables, data
Like a variable in a computer types, loops, and more.
program, a parking space has
an identifier and a contents.

bbjeo_fm.indd 10 11/27/18 1:37 PM


Walkthrough xi

Memorable photos reinforce


analogies and help students
remember the concepts.

In the same way that there can be a street named “Main Street” in different cities,
a Java program can have multiple variables with the same name.

Problem Solving sections teach


techniques for generating ideas and 7.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 333

evaluating proposed solutions, often Now how does that help us with our problem, switching the first and the second
using pencil and paper or other half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
artifacts. These sections emphasize Java programmers, we will say that we swap the coins in positions 0 and 4:

that most of the planning and problem


solving that makes students successful
happens away from the computer.

Next, we swap the coins in positions 1 and 5:

HOW TO 6.1 How To guides give step-by-step


Writing a Loop
guidance for common programming
This How To walks you through the process of
implementing a loop statement. We will illustrate the tasks, emphasizing planning and
steps with the following example problem.
Problem Statement Read twelve temperature
testing. They answer the beginner’s
values (one for each month) and display the num-
ber of the month with the highest temperature. For
question, “Now what do I do?” and
example, according to http://worldclimate.com, the
average maximum temperatures for Death Valley are
integrate key concepts into a
(in order by month, in degrees Celsius):
problem-solving sequence.
18.2 22.6 26.4 31.1 36.6 42.2
45.7 44.5 40.2 33.1 24.2 17.6
In this case, the month with the highest tempera-
ture (45.7 degrees Celsius) is July, and the program
should display 7. © Stevegeer/iStockphoto.

Step 1 Decide what work must be done inside the loop. Worked Examples apply
Every loop needs to do some kind of repetitive work, such as
• Reading another item. the steps in the How To to a
• Updating a value (such as a bank balance or total).
WORKED EXAMPLE 6.1 different example, showing
• Incrementing a counter.
Credit Card Processing
If you can’t figure out what needs to go inside the loop, start by writing down the steps that how they can be used to
you would take if you
howsolved
to use the problem by hand. Forfrom
example, with the temperature reading
problem, you
Learn
might See
number. write
a loop to remove spaces a credit
your eText or visit wiley.com/go/bjeo7.
card
plan, implement, and test
© MorePixels/iStockphoto. a solution to another
programming problem.
Table 1 Variable Declarations in Java
Variable Name Comment

int width = 20; Declares an integer variable and initializes it with 20.

int perimeter = 4 * width; The initial value need not be a fixed value. (Of course, width
must have been previously declared.)

String greeting = "Hi!"; This variable has the type String and is initialized with the
Example tables support beginners
string “Hi”. with multiple, concrete examples.
height = 30; Error: The type is missing. This statement is not a declaration
but an assignment of a new value to an existing variable—see These tables point out common
Section 2.2.5.
errors and present another quick
int width = "20"; Error: You cannot initialize a number with the string “20”.
(Note the quotation marks.) reference to the section’s topic.
int width; Declares an integer variable without initializing it. This can be a
cause for errors—see Common Error 2.1.
int width, height; Declares two integer variables in a single statement. In this
book, we will declare each variable in a separate statement.

bbjeo_fm.indd 11 11/27/18 1:37 PM


xii Walkthrough

Figure 3
Progressive figures trace code Execution of a
1 Initialize counter
for (int counter = 5; counter <= 10; counter++)
{
for Loop
segments to help students visualize counter = 5 }
sum = sum + counter;

the program flow. Color is used


consistently to make variables and
2 Check condition
for (int counter = 5; counter <= 10; counter++)
{

other elements easily recognizable. counter = 5 }


sum = sum + counter;

3 Execute loop body


for (int counter = 5; counter <= 10; counter++)
{
sum = sum + counter;
counter = 5 }

4 Update counter
for (int counter = 5; counter <= 10; counter++)
{
sum = sum + counter;
counter = 6 }
sec01/ElevatorSimulation.java
1 import java.util.Scanner; 5 Check condition again
for (int counter = 5; counter <= 10; counter++)
2 {
3 /** sum = sum + counter;
4 This program simulates an elevator panel that skips the 13th floor. counter = 6 }
5 */
6 public class ElevatorSimulation
7 {
8 public static void main(String[] args)
9 { The for loop neatly groups the initialization, condition, and update expressions
10 Scanner in = new Scanner(System.in); together. However, it is important to realize that these expressions are not executed
11 System.out.print("Floor: ");
together (see Figure 3).
12 int floor = in.nextInt();
13
• The initialization is executed once, before the loop is entered. 1
14 // Adjust floor if necessary
15 • The condition is checked before each iteration. 2 5
16 int actualFloor;
17 if (floor > 13) • The update is executed after each iteration. 4

Program listings are carefully


designed for easy reading, going
well beyond simple color coding.
Students can run and change the
same programs right in the eText.

Self-check exercises in the


eText are designed to engage
students with the new material
and check understanding before
they continue to the next topic.

•• Business E6.17 Currency conversion. Write a program


that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.

Optional science and business • Science P6.15 Radioactive decay of radioactive materials can be
modeled by the equation A = A0e-t (log 2/h), where A is
exercises engage students with the amount of the material at time t, A0 is the amount
realistic applications of Java. at time 0, and h is the half-life.
Technetium-99 is a radioisotope that is used in imaging
of the brain. It has a half-life of 6 hours. Your program
should display the relative amount A / A0 in a patient
body every hour for 24 hours after receiving a dose.

bbjeo_fm.indd 12 11/27/18 1:37 PM


Walkthrough xiii

Common Errors describe the kinds Common Error 7.4

of errors that students often make, Length and Size


Unfortunately, the Java syntax for determining the number of elements in an array, an array
with an explanation of why the errors list, and a string is not at all consistent. It is a common error to confuse these. You just have to
remember the correct syntax for every data type.
occur, and what to do about them.
Data Type Number of Elements

Array a.length

Array list a.size()

String a.length()

Programming Tip 5.5


Hand-Tracing
A very useful technique for understanding whether a program
works correctly is called hand-tracing. You simulate the pro-
gram’s activity on a sheet of paper. You can use this method with
pseudocode or Java code.
Get an index card, a cocktail napkin, or whatever sheet of
Programming Tips explain paper is within reach. Make a column for each variable. Have the
program code ready. Use a marker, such as a paper clip, to mark
good programming practices, the current statement. In your mind, execute statements one at a
time. Every time the value of a variable changes, cross out the old
and encourage students to be value and write the new value below the old one.
For example, let’s trace the getTax method with the data from © thomasd007/iStockphoto.

more productive with tips and the program run above. When the TaxReturn object is constructed,
the income instance variable is set to 80,000 and status is set to
Hand-tracing helps you
understand whether a
techniques such as hand-tracing. MARRIED. Then the getTax method is called. In lines 31 and 32 of Tax-
Return.java, tax1 and tax2 are initialized to 0.
program works correctly.

29 public double getTax()


30 {
31 double tax1 = 0; income status tax1 tax2
32 double tax2 = 0;
33 80000 MARRIED 0 0
Because status is not SINGLE, we move to the else
branch of the outer if statement (line 46).
34 if (status == SINGLE)
35 {
36 if (income <= RATE1_SINGLE_LIMIT)
37 {
38 tax1 = RATE1 * income;
39 }
40 else
41 {
42 tax1 = RATE1 * RATE1_SINGLE_LIMIT;
43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);

Special Topic 11.2


File Dialog Boxes

Special Topics present optional In a program with a graphical user interface, you will want to use a file dialog box (such as the
one shown in the figure below) whenever the users of your program need to pick a file. The
topics and provide additional JFileChooser class implements a file dialog box for the Swing user-interface toolkit.
The JFileChooser class has many options to fine-tune the display of the dialog box, but in its
explanation of others. most basic form it is quite simple: Construct a file chooser object; then call the showOpenDialog
or showSaveDialog method. Both methods show the same dialog box, but the button for select-
ing a file is labeled “Open” or “Save”, depending on which method you call.
For better placement of the dialog box on the screen, you can specify the user-interface
component over which to pop up the dialog box. If you don’t care where the dialog box pops
up, you can simply pass null. The showOpenDialog and showSaveDialog methods return either
JFileChooser.APPROVE_OPTION, if the user has chosen a file, or JFileChooser.CANCEL_OPTION, if the
user canceled the selection. If a file was chosen, then you call the getSelectedFile method to
obtain a File object that describes the file.
Here is a complete example:
JFileChooser chooser = new JFileChooser();
Scanner in = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{

Additional full code examples


File selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);

throughout the text provide }

complete programs for students EXAMPLE CODE See special_topic_2 of your eText or companion code for a program that demonstrates how to use a file
chooser.

to run and modify.

Computing & Society 1.1 Computers Are Everywhere


When computers The advent of ubiqui-
were first invented tous computing changed
in the 1940s, a computer filled an many aspects of our
entire room. The photo below shows lives. Factories used
the ENIAC (electronic numerical inte- to employ people to
grator and computer), completed in do repetitive assembly
1946 at the University of Pennsylvania. tasks that are today car-
The ENIAC was used by the military ried out by computer-

Computing & Society presents social


to compute the trajectories of projec- controlled robots, oper-
tiles. Nowadays, computing facilities ated by a few people
of search engines, Internet shops, and who know how to work
and historical topics on computing—for social networks fill huge buildings
called data centers. At the other end of
with those computers.
Books, music, and mov-
interest and to fulfill the “historical and the spectrum, computers are all around
us. Your cell phone has a computer
ies are nowadays often
consumed on com- This transit card contains a computer.
social context” requirements of the inside, as do many credit cards and fare
cards for public transit. A modern car
puters, and comput-
ers are almost always

ACM/IEEE curriculum guidelines. has several computers––to control the


engine, brakes, lights, and the radio.
involved in their production. The
book that you are reading right now
could not have been written without
computers.

bbjeo_fm.indd 13 11/27/18 1:37 PM


xiv Walkthrough

Interactive activities in the eText


engage students in active reading as they… Complete a program and
get immediate feedback

Trace through a code segment

Arrange code to fulfill a task

Build an example table

Create a memory diagram

Explore common algorithms

bbjeo_fm.indd 14 11/27/18 2:30 PM


Acknowledgments xv

Acknowledgments
Many thanks to Joanna Dingle, Crystal Franks, Graig Donini, and Michael Mac-
Dougald at John Wiley & Sons, and Vickie Piercey at Publishing Services for their
help with this project. An especially deep acknowledgment and thanks goes to Cindy
Johnson for her hard work, sound judgment, and amazing attention to detail.
Special thanks to Stephen Gilbert, Orange Coast College, for his excellent help
with the interactive exercises.
Many thanks to the individuals who worked through the many new activities in
this edition, reviewed the manuscript, made valuable suggestions, and brought errors
and omissions to my attention. They include:
Radhouane Chouchane, Columbus State University
Sussan Einakian, California Polytechnic State University
Jon Hanrath, Illinois Institute of Technology
Brian King, Bucknell University
Kathleen O’Brien, San Jose State University
Eman Saleh, University of Georgia
William Wei, New York Institute of Technology
Each new edition builds on the suggestions and experiences of prior reviewers, con-
tributors, and users. I am grateful for the invaluable contributions these individuals
have made:
Eric Aaron, Wesleyan University Jerry Cain, Stanford University
James Agnew, Anne Arundel Adam Cannon, Columbia University
Community College Michael Carney, Finger Lakes
Tim Andersen, Boise State University Community College
Ivan Bajic, San Diego State University Robin Carr, Drexel University
Greg Ballinger, Miami Dade College Christopher Cassa, Massachusetts
Ted Bangay, Sheridan Institute Institute of Technology
of Technology Nancy Chase, Gonzaga University
Ian Barland, Radford University Dr. Suchindran S. Chatterjee, Arizona
George Basham, Franklin University State University
Jon Beck, Truman State University Archana Chidanandan, Rose-Hulman
Sambit Bhattacharya, Fayetteville Institute of Technology
State University Vincent Cicirello, The Richard Stockton
Rick Birney, Arizona State University College of New Jersey
Paul Bladek, Edmonds Community Gerald Cohen, The Richard Stockton
College College of New Jersey
Matt Boutell, Rose-Hulman Institute of Teresa Cole, Boise State University
Technology Deborah Coleman, Rochester Institute
Joseph Bowbeer, Vizrea Corporation of Technology
Timothy A. Budd, Oregon State Tina Comston, Franklin University
University Lennie Cooper, Miami Dade College
John Bundy, DeVry University Chicago Jose Cordova, University of Louisiana,
Robert P. Burton, Brigham Young Monroe
University Valentino Crespi, California State
Frank Butt, IBM University, Los Angeles

bbjeo_fm.indd 15 11/27/18 1:37 PM


xvi Acknowledgments

Jim Cross, Auburn University Aaron Keen, California Polytechnic


Russell Deaton, University State University, San Luis Obispo
of Arkansas Mugdha Khaladkar, New Jersey Institute
Geoffrey Decker, Northern Illinois of Technology
University Gary J. Koehler, University of Florida
Suzanne Dietrich, Arizona State Elliot Koffman, Temple University
University,West Campus Ronald Krawitz, DeVry University
Mike Domaratzki, University of Norm Krumpe, Miami University Ohio
Manitoba Jim Leone, Rochester Institute
H. E. Dunsmore, Purdue University of Technology
Robert Duvall, Duke University Kevin Lillis, St. Ambrose University
Sherif Elfayoumy, University of Darren Lim, Siena College
North Florida Hong Lin, DeVry University
Eman El-Sheikh, University of Kathy Liszka, University of Akron
West Florida Hunter Lloyd, Montana State
Henry A. Etlinger, Rochester Institute of University
Technology Youmin Lu, Bloomsburg University
John Fendrich, Bradley University Peter Lutz, Rochester Institute of
David Freer, Miami Dade College Technology
John Fulton, Franklin University Kuber Maharjan, Purdue University
David Geary, Sabreware, Inc. College of Technology at Columbus
Margaret Geroch, Wheeling Jesuit John S. Mallozzi, Iona College
University John Martin, North Dakota State
Ahmad Ghafarian, North Georgia University
College & State University Jeanna Matthews, Clarkson University
Rick Giles, Acadia University Patricia McDermott-Wells, Florida
Stacey Grasso, College of San Mateo International University
Jianchao Han, California State Scott McElfresh, Carnegie Mellon
University, Dominguez Hills University
Lisa Hansen, Western New England Joan McGrory, Christian Brothers
College University
Elliotte Harold Carolyn Miller, North Carolina
Eileen Head, Binghamton University State University
Cecily Heiner, University of Utah Sandeep R. Mitra, State University
Guy Helmer, Iowa State University of New York, Brockport
Ed Holden, Rochester Institute Teng Moh, San Jose State University
of Technology Bill Mongan, Drexel University
Brian Howard, Depauw University John Moore, The Citadel
Lubomir Ivanov, Iona College Jose-Arturo Mora-Soto, Jesica Rivero-
Norman Jacobson, University of Espinosa, and Julio-Angel Cano-
California, Irvine Romero, University
Steven Janke, Colorado College of Madrid
Curt Jones, Bloomsburg University Faye Navabi, Arizona State University
Mark Jones, Lock Haven University of Parviz Partow-Navid, California State
Pennsylvania University, Los Angeles
Dr. Mustafa Kamal, University of George Novacky, University
Central Missouri of Pittsburgh

bbjeo_fm.indd 16 11/27/18 1:37 PM


Acknowledgments xvii

Kevin O’Gorman, California Stephanie Smullen, University of


Polytechnic State University, San Luis Tennessee, Chattanooga
Obispo Robert Strader, Stephen F. Austin
Michael Olan, Richard Stockton College State University
Mimi Opkins, California State Monica Sweat, Georgia Institute
University Long Beach of Technology
Derek Pao, City University of Peter Stanchev, Kettering University
Hong Kong Aakash Taneja, The Richard Stockton
Kevin Parker, Idaho State University College of New Jersey
Jim Perry, Ulster County Community Craig Tanis, University of Tennessee at
College Chattanooga
Cornel Pokorny, California Polytechnic Shannon Tauro, University of
State University, California, Irvine
San Luis Obispo Ron Taylor, Wright State University
Roger Priebe, University of Texas, Russell Tessier, University of
Austin Massachusetts, Amherst
C. Robert Putnam, California State Jonathan L. Tolstedt, North Dakota
University, Northridge State University
Kai Qian, Southern Polytechnic David Vineyard, Kettering University
State University Joseph Vybihal, McGill University
Cyndi Rader, Colorado School Xiaoming Wei, Iona College
of Mines Jonathan S. Weissman, Finger Lakes
Neil Rankin, Worcester Polytechnic Community College
Institute Todd Whittaker, Franklin University
Brad Rippe, Fullerton College Robert Willhoft, Roberts Wesleyan
Pedro I. Rivera Vega, University College
of Puerto Rico, Mayaguez Brent Wilson, George Fox University
Daniel Rogers, SUNY Brockport Katherine Winters, University of
Chaman Lal Sabharwal, Missouri Tennessee at Chattanooga
University of Science and Technology Lea Wittie, Bucknell University
Katherine Salch, Illinois Central College David Womack, University of Texas
John Santore, Bridgewater State College at San Antonio
Javad Shakib, DeVry University David Woolbright, Columbus State
Carolyn Schauble, Colorado State University
University Tom Wulf, University of Cincinnati
Brent Seales, University of Kentucky Catherine Wyman, DeVry University
Christian Shin, SUNY Geneseo Arthur Yanushka, Christian Brothers
Charlie Shu, Franklin University University
Jeffrey Six, University of Delaware Qi Yu, Rochester Institute of Technology
Don Slater, Carnegie Mellon University Salih Yurttas, Texas A&M University
Ken Slonneger, University of Iowa
Aurelia Smith, Columbus State
University
Donald Smith, Columbia College
Joslyn A. Smith, Florida International
University

bbjeo_fm.indd 17 11/27/18 1:37 PM


bbjeo_fm.indd 18 11/27/18 1:37 PM
CONTENTS

PREFACE v 2.4 Constructing Objects 38


SPECIAL FEATURES xxvi 2.5 Accessor and Mutator Methods 40
2.6 The API Documentation 41
1 INTRODUCTION 1 Browsing the API Documentation 41
Packages 43
1.1 Computer Programs 2 2.7 Implementing a Test Program 44
1.2 The Anatomy of a Computer 3 ST2 Testing Classes in an Interactive
1.3 The Java Programming Language 5 Environment 45
WE1 How Many Days Have You Been Alive? 46
1.4 Becoming Familiar with Your
WE2 Working with Pictures 46
Programming Environment 7
2.8 Object References 46
1.5 Analyzing Your First Program 11
2.9 Graphical Applications 49
1.6 Errors 13
Frame Windows 50
1.7 PROBLEM SOLVING Algorithm Design 15 Drawing on a Component 51
The Algorithm Concept 15 Displaying a Component in a Frame 53
An Algorithm for Solving an
Investment Problem 16
2.10 Ellipses, Lines, Text, and Color 54
Pseudocode 17 Ellipses and Circles 54
From Algorithms to Programs 18 Lines 55
HT1 Describing an Algorithm with Drawing Text 56
Pseudocode 18 Colors 56
WE1 Writing an Algorithm for Tiling a Floor 20
3 IMPLEMENTING CLASSES 61
2 USING OBJECTS 23
3.1 Instance Variables and Encapsulation 62
2.1 Objects and Classes 24 Instance Variables 62
Using Objects 24 The Methods of the Counter Class 64
Classes 25 Encapsulation 64

2.2 Variables 26 3.2 Specifying the Public Interface


Variable Declarations 26
of a Class 66
Types 28 Specifying Methods 66
Names 29 Specifying Constructors 67
Comments 30 Using the Public Interface 69
Assignment 30 Commenting the Public Interface 69
ST1 Variable Type Inference 33 3.3 Providing the Class Implementation 72
2.3 Calling Methods 33 Providing Instance Variables 72
The Public Interface of a Class 33 Providing Constructors 73
Method Arguments 34 Providing Methods 75
Return Values 35 HT1 Implementing a Class 78
Method Declarations 36 WE1 Making a Simple Menu 81

xix

bbjeo_fm.indd 19 11/27/18 1:37 PM


xx Contents

3.4 Unit Testing 81 5 DECISIONS 131


3.5 PROBLEM SOLVING Tracing Objects 84
5.1 The if Statement 132
3.6 Local Variables 86
ST1 The Conditional Operator 137
3.7 The this Reference 88
5.2 Comparing Values 137
ST1 Calling One Constructor from Another 90
Relational Operators 138
3.8 Shape Classes 90 Comparing Floating-Point Numbers 139
HT2 Drawing Graphical Shapes 94 Comparing Strings 140
Comparing Objects 141
Testing for null 141
4 FUNDAMENTAL DATA
HT1 Implementing an if Statement 143
TYPES 99
WE1 Extracting the Middle 146
4.1 Numbers 100 5.3 Multiple Alternatives 146
Number Types 100 ST2 The switch Statement 148
Constants 102 5.4 Nested Branches 149
ST1 Big Numbers 106 ST3 Block Scope 154
4.2 Arithmetic 107 ST4 Enumeration Types 155
Arithmetic Operators 107 5.5 PROBLEM SOLVING Flowcharts 156
Increment and Decrement 107
5.6 PROBLEM SOLVING Selecting Test
Integer Division and Remainder 108
Powers and Roots 109 Cases 159
Converting Floating-Point Numbers ST5 Logging 161
to Integers 110 5.7 Boolean Variables and Operators 161
ST2 Avoiding Negative Remainders 112 ST6 Short-Circuit Evaluation of Boolean
ST3 Combining Assignment and Arithmetic 113 Operators 165
ST4 Instance Methods and Static Methods 113 ST7 De Morgan’s Law 165
4.3 Input and Output 114 5.8 APPLICATION Input Validation 166
Reading Input 114
Formatted Output 115
6 LOOPS 171
HT1 Carrying Out Computations 118
WE1 Computing the Volume and Surface Area of 6.1 The while Loop 172
a Pyramid 121
6.2 PROBLEM SOLVING Hand-Tracing 179
4.4 PROBLEM SOLVING First Do it By Hand 121
6.3 The for Loop 183
WE2 Computing Travel Time 122
ST1 Variables Declared in a for Loop
4.5 Strings 122 Header 189
The String Type 122 6.4 The do Loop 190
Concatenation 123
String Input 124 6.5 APPLICATION Processing Sentinel
Escape Sequences 124 Values 192
Strings and Characters 124 ST2 Redirection of Input and Output 194
Substrings 125 ST3 The “Loop and a Half” Problem 194
ST5 Using Dialog Boxes for Input and ST4 The break and continue Statements 195
Output 128 6.6 PROBLEM SOLVING Storyboards 197
6.7 Common Loop Algorithms 199
Sum and Average Value 199
Counting Matches 200

bbjeo_fm.indd 20 11/27/18 1:37 PM


Contents xxi

Finding the First Match 200 7.6 Two-Dimensional Arrays 248


Prompting Until a Match is Found 201 Declaring Two-Dimensional Arrays 248
Maximum and Minimum 201 Accessing Elements 249
Comparing Adjacent Values 202 Locating Neighboring Elements 250
HT1 Writing a Loop 203 Accessing Rows and Columns 251
WE1 Credit Card Processing 206 Two-Dimensional Array Parameters 252
6.8 Nested Loops 206 WE2 A World Population Table 253
WE2 Manipulating the Pixels in an Image 209 ST3 Two-Dimensional Arrays with Variable
Row Lengths 254
6.9 APPLICATION Random Numbers and
ST4 Multidimensional Arrays 255
Simulations 209
7.7 Array Lists 255
Generating Random Numbers 210
The Monte Carlo Method 211 Declaring and Using Array Lists 255
Using the Enhanced for Loop with
6.10 Using a Debugger 213 Array Lists 258
HT2 Debugging 215 Copying Array Lists 259
WE3 A Sample Debugging Session 217 Wrappers and Auto-boxing 259
Using Array Algorithms with Array Lists 260
Storing Input Values in an Array List 261
7 ARRAYS AND ARRAY Removing Matches 261
LISTS 221 Choosing Between Array Lists and Arrays 262
ST5 The Diamond Syntax 264
7.1 Arrays 222
Declaring and Using Arrays 222 7.8 Regression Testing 264
Array References 225
Using Arrays with Methods 226
8 DESIGNING CLASSES 271
Partially Filled Arrays 226
ST1 Methods with a Variable Number of 8.1 Discovering Classes 272
Arguments 229
8.2 Designing Good Methods 273
7.2 The Enhanced for Loop 230
Providing a Cohesive Public Interface 273
7.3 Common Array Algorithms 232 Minimizing Dependencies 274
Filling 232 Separating Accessors and Mutators 275
Sum and Average Value 232 Minimizing Side Effects 276
Maximum and Minimum 232 ST1 Call by Value and Call by Reference 278
Element Separators 232 8.3 PROBLEM SOLVING Patterns for
Linear Search 233
Object Data 282
Removing an Element 234
Keeping a Total 282
Inserting an Element 234
Counting Events 283
Swapping Elements 236
Collecting Values 283
Copying Arrays 237
Managing Properties of an Object 284
Reading Input 238
Modeling Objects with Distinct States 284
ST2 Sorting with the Java Library 240
Describing the Position of an Object 285
7.4 PROBLEM SOLVING Adapting
8.4 Static Variables and Methods 286
Algorithms 240
ST2 Alternative Forms of Instance and Static
HT1 Working with Arrays 242 Variable Initialization 289
WE1 Rolling the Dice 245 ST3 Static Imports 290
7.5 PROBLEM SOLVING Discovering Algorithms by 8.5 PROBLEM SOLVING Solve a Simpler
Manipulating Physical Objects 245 Problem First 291

bbjeo_fm.indd 21 11/27/18 1:37 PM


xxii Contents

8.6 Packages 295 10.3 The Comparable Interface 350


Organizing Related Classes into Packages 295 ST3 The clone Method and the Cloneable
Importing Packages 296 Interface 352
Package Names 297 10.4 Using Interfaces for Callbacks 355
Packages and Source Files 297 ST4 Lambda Expressions 358
ST4 Package Access 298 ST5 Generic Interface Types 360
HT1 Programming with Packages 299
10.5 Inner Classes 360
8.7 Unit Test Frameworks 300
10.6 Mock Objects 361
10.7 Event Handling 363
9 INHERITANCE 305 Listening to Events 363
9.1 Inheritance Hierarchies 306 Using Inner Classes for Listeners 365

9.2 Implementing Subclasses 310 10.8 Building Applications with Buttons 368

9.3 Overriding Methods 314 10.9 Processing Timer Events 371


ST1 Calling the Superclass Constructor 318 10.10 Mouse Events 374
ST6 Keyboard Events 377
9.4 Polymorphism 319
ST7 Event Adapters 378
ST2 Dynamic Method Lookup and the Implicit
Parameter 322
ST3 Abstract Classes 323 11 INPUT/OUTPUT AND
ST4 Final Methods and Classes 324 EXCEPTION HANDLING 383
ST5 Protected Access 324
HT1 Developing an Inheritance Hierarchy 325 11.1 Reading and Writing Text Files 384
WE1 Implementing an Employee Hierarchy for ST1 Reading Web Pages 387
Payroll Processing 330 ST2 File Dialog Boxes 387
9.5 Object: The Cosmic Superclass 330 ST3 Character Encodings 388

Overriding the toString Method 330 11.2 Text Input and Output 389
The equals Method 332 Reading Words 389
The instanceof Operator 333 Reading Characters 390
ST6 Inheritance and the toString Method 335 Classifying Characters 390
ST7 Inheritance and the equals Method 336 Reading Lines 390
Scanning a String 392
Converting Strings to Numbers 392
10 INTERFACES 339
Avoiding Errors When Reading Numbers 392
10.1 Using Interfaces for Algorithm Mixing Number, Word, and Line Input 393
Formatting Output 394
Reuse 340
ST4 Regular Expressions 395
Discovering an Interface Type 340
ST5 Reading an Entire File 396
Declaring an Interface Type 341
Implementing an Interface Type 343 11.3 Command Line Arguments 396
Comparing Interfaces and Inheritance 345 HT1 Processing Text Files 399
ST1 Constants in Interfaces 346 WE1 Analyzing Baby Names 403
ST2 Nonabstract Interface Methods 347 11.4 Exception Handling 403
10.2 Working with Interface Variables 348 Throwing Exceptions 403
Converting from Classes to Interfaces 348 Catching Exceptions 405
Invoking Methods on Interface Variables 349 Checked Exceptions 407
Casting from Interfaces to Classes 349 Closing Resources 409
WE1 Investigating Number Sequences 350 Designing Your Own Exception Types 410

bbjeo_fm.indd 22 11/27/18 1:37 PM


Contents xxiii

ST6 Assertions 411 14 SORTING AND SEARCHING*


ST7 The try/finally Statement 412 (ETEXT ONLY) 477
11.5 APPLICATION Handling Input Errors 412
14.1 Selection Sort 478
14.2 Profiling the Selection Sort
12 OBJECT-ORIENTED
Algorithm 481
DESIGN 419
14.3 Analyzing the Performance of the
12.1 Classes and Their Responsibilities 420 Selection Sort Algorithm 484
Discovering Classes 420 ST1 Oh, Omega, and Theta 486
The CRC Card Method 421 ST2 Insertion Sort 487
12.2 Relationships Between Classes 423 14.4 Merge Sort 488
Dependency 423 14.5 Analyzing the Merge Sort Algorithm 491
Aggregation 424 ST3 The Quicksort Algorithm 493
Inheritance 425
14.6 Searching 495
HT1 Using CRC Cards and UML Diagrams in
Program Design 426 Linear Search 495
ST1 Attributes and Methods in UML Binary Search 497
Diagrams 426 14.7 PROBLEM SOLVING Estimating the Running
ST2 Multiplicities 427 Time of an Algorithm 500
ST3 Aggregation, Association, and Linear Time 500
Composition 427 Quadratic Time 501
12.3 APPLICATION Printing an Invoice 428 The Triangle Pattern 502
Requirements 429 Logarithmic Time 503
CRC Cards 429 14.8 Sorting and Searching in the Java
UML Diagrams 432 Library 504
Method Documentation 432
Sorting 504
Implementation 434
Binary Search 505
WE1 Simulating an Automatic Teller Machine 439 Comparing Objects 505
ST4 The Comparator Interface 506
13 RECURSION* ST5 Comparators with Lambda Expressions 507
(ETEXT ONLY) 443 WE1 Enhancing the Insertion Sort Algorithm 507

13.1 Triangle Numbers 444


HT1 Thinking Recursively 448
15 THE JAVA COLLECTIONS
WE1 Finding Files 452
FRAMEWORK*
(ETEXT ONLY) 511
13.2 Recursive Helper Methods 452
13.3 The Efficiency of Recursion 453 15.1 An Overview of the Collections
Framework 512
13.4 Permutations 459
15.2 Linked Lists 514
13.5 Mutual Recursion 463
The Structure of Linked Lists 515
13.6 Backtracking 469
The LinkedList Class of the Java Collections
WE2 Towers of Hanoi 475 Framework 516
List Iterators 516
15.3 Sets 520
Choosing a Set Implementation 520
Working with Sets 522

*See your eText or visit www.wiley.com/go/bjeo7.

bbjeo_fm.indd 23 11/27/18 1:37 PM


xxiv Contents

15.4 Maps 525 APPENDIX A THE BASIC LATIN AND LATIN-1 SUBSETS
ST1 Updating Map Entries 527 OF UNICODE A-1
HT1 Choosing a Collection 527 APPENDIX B JAVA OPERATOR SUMMARY A-5
WE1 Word Frequency 528 APPENDIX C JAVA RESERVED WORD SUMMARY A-7
ST2 Hash Functions 529 APPENDIX D THE JAVA LIBRARY A-9
15.5 Stacks, Queues, and Priority Queues 531 APPENDIX E JAVA LANGUAGE CODING
Stacks 531
GUIDELINES A-29
Queues 532 APPENDIX F TOOL SUMMARY (ETEXT ONLY)
Priority Queues 533 APPENDIX G NUMBER SYSTEMS (ETEXT ONLY)

15.6 Stack and Queue Applications 534 APPENDIX H UML SUMMARY (ETEXT ONLY)

Balancing Parentheses 534 APPENDIX I JAVA SYNTAX SUMMARY (ETEXT ONLY)


Evaluating Reverse Polish Expressions 535 APPENDIX J HTML SUMMARY (ETEXT ONLY)
Evaluating Algebraic Expressions 537
Backtracking 540 GLOSSARY G-1
ST3 Reverse Polish Notation 542 INDEX I-1
WE2 Simulating a Queue of Waiting
CREDITS C-1
Customers 543
QUICK REFERENCE C-3

*See your eText or visit www.wiley.com/go/bjeo7.

bbjeo_fm.indd 24 11/27/18 1:37 PM


Contents xxv

ALPHABETICAL LIST OF SYNTAX BOXES


Arrays 223
Array Lists 256
Assignment 31
Calling a Superclass Method 315
Cast 110
Catching Exceptions 406
Class Declaration 68
Comparisons 138
Constant Declaration 104
Constructor with Superclass Initializer 318
Declaring an Interface 342

for Statement 183


if Statement 134
Implementing an Interface 343
Importing a Class from a Package 43
Input Statement 115
Instance Variable Declaration 63
Java Program 12
Object Construction 39
Package Specification 296
Subclass Declaration 311
The Enhanced for Loop 231
The instanceof Operator 334
The throws Clause 408
The try-with-resources Statement 409
Throwing an Exception 403
Two-Dimensional Array Declaration 249
while Statement 173
Variable Declaration 27

bbjeo_fm.indd 25 11/27/18 1:37 PM


xxvi Special Features

How Tos
CH AP TE R Common and
Errors Worked Examples
© Steve Simzer/iStockphoto.

1 Introduction ©Omitting
John Bell/iStockphoto.
Semicolons 13 Describing an Algorithm
Misspelling Words 14 with Pseudocode 18
Writing an Algorithm for
Tiling a Floor 20

2 Using Objects Using Undeclared or How Many Days Have You


Uninitialized Variables 32 Been Alive? 46
Confusing Variable Declarations Working with Pictures 46
and Assignment Statements 32
Trying to Invoke a Constructor Like
a Method 40

3 Implementing Classes Declaring a Constructor as void 72 Implementing a Class 78


Ignoring Parameter Variables 77 Making a Simple Menu 81
Duplicating Instance Variables Drawing Graphical Shapes 94
in Local Variables 86
Providing Unnecessary
Instance Variables 87
Forgetting to Initialize Object
References in a Constructor 87

4 Fundamental Unintended Integer Division 111 Carrying out Computations 118


Unbalanced Parentheses 112 Computing the Volume and
Data Types Surface Area of a Pyramid 121
Computing Travel Time 122

5 Decisions A Semicolon After the Implementing an


if Condition 134 if Statement 143
Using == to Compare Strings 143 Extracting the Middle 146
The Dangling else Problem 152
Combining Multiple
Relational Operators 164
Confusing && and || Conditions 164

6 Loops Don’t Think “Are We There Yet?” 177 Writing a Loop 203
Infinite Loops 177 Credit Card Processing 206
Off-by-One Errors 178 Manipulating the Pixels
in an Image 209
Debugging 215
A Sample Debugging Session 217

bbjeo_fm.indd 26 11/27/18 2:12 PM


Special Features xxvii

Programming Special Topics Computing &


Tips Society
© Eric Isselé/iStockphoto. © Media Bakery.
© Eric Isselé/iStockphoto.
Backup Copies 10 Computers Are Everywhere 5

Choose Descriptive Variable Type Inference 33 Computer Monopoly 49


Variable Names 32 Testing Classes in an Interactive
Learn By Trying 37 Environment 45
Don’t Memorize—Use
Online Help 43

The javadoc Utility 72 Calling One Constructor Electronic Voting 83


from Another 90

Do Not Use Magic Numbers 106 Big Numbers 106 Bugs in Silicon 114
Spaces in Expressions 112 Avoiding Negative International Alphabets
Reading Exception Reports 127 Remainders 112 and Unicode 128
Combining Assignment
and Arithmetic 113
Instance Methods and
Static Methods 113
Using Dialog Boxes for Input
and Output 128

Brace Layout 135 The Conditional Operator 137 Dysfunctional Computerized


Always Use Braces 135 The switch Statement 148 Systems 145
Tabs 136 Block Scope 154 Artificial Intelligence 168
Avoid Duplication in Branches 136 Enumeration Types 155
Hand-Tracing 153 Logging 161
Make a Schedule and Make Time Short-Circuit Evaluation of
for Unexpected Problems 160 Boolean Operators 165
De Morgan’s Law 165

Use for Loops for Their Variables Declared in a Digital Piracy 182
Intended Purpose Only 188 for Loop Header 189 The First Bug 217
Choose Loop Bounds That Redirection of Input and Output 194
Match Your Task 188 The Loop-and-a-Half Problem 194
Count Iterations 189 The break and continue
Flowcharts for Loops 191 Statements 195

bbjeo_fm.indd 27 11/27/18 2:12 PM


xxviii Special Features

How Tos
CH AP TE R Common and
Errors
Worked Examples
© Steve Simzer/iStockphoto.

7 Arrays and Array Lists ©Bounds Errors


John Bell/iStockphoto. 227 Working with Arrays 242
Uninitialized and Rolling the Dice 245
Unfilled Arrays 227 A World Population Table 253
Underestimating the
Size of a Data Set 240
Length and Size 264

8 Designing Classes Trying to Access Instance Programming with Packages 299


Variables in Static Methods 288
Confusing Dots 298

9 Inheritance Replicating Instance Variables Developing an


from the Superclass 313 Inheritance Hierarchy 325
Confusing Super- and Implementing an
Subclasses 313 Employee Hierarchy for
Accidental Overloading 317 Payroll Processing 330
Forgetting to Use super
When Invoking a
Superclass Method 318
Don’t Use Type Tests 335

10 Interfaces Forgetting to Declare Investigating Number


Implementing Methods Sequences 350
as Public 346
Trying to Instantiate an Interface 346
Modifying Parameter Types
in the Implementing Method 367
Trying to Call Listener Methods 368
Forgetting to Attach a Listener 371
Forgetting to Repaint 373

11 Input/Output and Backslashes in File Names 386 Processing Text Files 399
Constructing a Scanner Analyzing Baby Names 403
Exception Handling with a String 386

bbjeo_fm.indd 28 11/27/18 2:12 PM


Special Features xxix

Programming Special Topics Computing &


Tips Society
© Eric Isselé/iStockphoto. © Media Bakery.
© EricArrays
Use Isselé/iStockphoto.
for Sequences of Methods with a Variable Computer Viruses 229
Related Items 228 Number of Arguments 229 Liability for Software
Make Parallel Arrays into Sorting with the Java Library 240 Malfunction 267
Arrays of Objects 228 Two-Dimensional Arrays
Batch Files and Shell Scripts 266 with Variable Row Lengths 254
Multidimensional Arrays 255
The Diamond Syntax 264

Consistency 277 Call by Value and Call Personal Computing 302


Minimize the Use of by Reference 278
Static Methods 289 Alternative Forms of Instance
and Static Variable Initialization 289
Static Imports 290
Package Access 298

Use a Single Class for Variation Calling the Superclass Who Controls the Internet? 337
in Values, Inheritance for Constructor 318
Variation in Behavior 309 Dynamic Method Lookup and
the Implicit Parameter 322
Abstract Classes 323
Final Methods and Classes 324
Protected Access 324
Inheritance and the
toString Method 335
Inheritance and the
equals Method 336

Comparing Integers and Floating- Constants in Interfaces 346 Open Source and
Point Numbers 351 Nonabstract Interface Methods 347 Free Software 379
The clone Method and the
Cloneable Interface 352
Lambda Expressions 358
Generic Interface Types 360
Keyboard Events 377
Event Adapters 378

Throw Early, Catch Late 411 Reading Web Pages 387 Encryption Algorithms 402
Do Not Squelch Exceptions 411 File Dialog Boxes 387 The Ariane Rocket Incident 417
Do Throw Specific Character Encodings 388
Exceptions 411 Regular Expressions 395
Reading an Entire File 396
Assertions 411
The try/finally Statement 412

bbjeo_fm.indd 29 11/27/18 2:12 PM


xxx Special Features

How Tos
CH AP TE R Common and
Errors
Worked Examples
© Steve Simzer/iStockphoto.

12 Object-Oriented Design © John Bell/iStockphoto. Using CRC Cards and


UML Diagrams in
Program Design 426
Simulating an Automatic
Teller Machine 439

13 Recursion* Infinite Recursion 447 Thinking Recursively 448


Tracing Through Recursive Finding Files 452
(eTEXT ONLY)
Methods 447 Towers of Hanoi 475

14 Sorting and Searching* The compareTo Method Can Enhancing the Insertion
Return Any Integer, Sort Algorithm 507
(eTEXT ONLY) Not Just –1, 0, and 1 506

15 The Java Collections Choosing a Collection 527


Word Frequency 528
Framework*
Simulating a Queue of
(eTEXT ONLY) Waiting Customers 543

*See your eText or visit www.wiley.com/go/bjeo7.

bbjeo_fm.indd 30 11/27/18 2:12 PM


Special Features xxxi

Programming Special Topics Computing &


Tips Society
© Eric Isselé/iStockphoto. © Media Bakery.
© Eric Isselé/iStockphoto. Attributes and Methods in Electronic Privacy 439
UML Diagrams 426
Multiplicities 427
Aggregation, Association,
and Composition 427

The Limits of Computation 461

Oh, Omega, and Theta 486 The First Programmer 499


Insertion Sort 487
The Quicksort Algorithm 493
The Comparator Interface 506
Comparators with
Lambda Expressions 507

Use Interface References to Updating Map Entries 527 Standardization 519


Manipulate Data Structures 524 Hash Functions 529
Reverse Polish Notation 542

*See your eText or visit www.wiley.com/go/bjeo7.

bbjeo_fm.indd 31 11/27/18 2:12 PM


bbjeo_fm.indd 32 11/27/18 1:37 PM
CHAPTER 1
INTRODUCTION

CHAPTER GOALS

To learn about computers


and programming
To compile and run your first
Java program © JanPietruszka/iStockphoto.

To recognize compile-time and


run-time errors
To describe an algorithm with pseudocode

CHAPTER CONTENTS

1.1 COMPUTER PROGRAMS 2 1.6 ERRORS 13


CE 2 Misspelling Words 14
1.2 THE ANATOMY OF A COMPUTER 3
C&S Computers Are Everywhere 5 1.7 PROBLEM SOLVING:
ALGORITHM DESIGN 15
1.3 THE JAVA PROGRAMMING
HT 1 Describing an Algorithm with
LANGUAGE 5
Pseudocode 18
1.4 BECOMING FAMILIAR WITH YOUR WE1 Writing an Algorithm for Tiling a Floor 20
PROGRAMMING ENVIRONMENT 7
PT 1 Backup Copies 10

1.5 ANALYZING YOUR FIRST


PROGRAM 11
SYN Java Program 12
CE 1 Omitting Semicolons 13

bjeo_ch01p.indd 1 11/21/18 5:11 PM


Just as you gather tools, study a project, and make a plan for
tackling it, in this chapter you will gather up the basics you
need to start learning to program. After a brief introduction
to computer hardware, software, and programming in
general, you will learn how to write and run your first
Java program. You will also learn how to diagnose and
fix programming errors, and how to use pseudocode to
describe an algorithm—a step-by-step description of how
to solve a problem—as you plan your computer programs.

© JanPietruszka/iStockphoto.

1.1 Computer Programs


Computers
You have probably used a computer for work or fun. Many people use computers for
execute very basic everyday tasks such as electronic banking or writing a term paper. Computers are
instructions in good for such tasks. They can handle repetitive chores, such as totaling up numbers
rapid succession.
or placing words on a page, without getting bored or exhausted.
The flexibility of a computer is quite an amazing phenomenon. The same machine
can balance your checkbook, lay out your term paper, and play a game. In contrast,
other machines carry out a much narrower range of tasks; a car drives and a toaster
toasts. Computers can carry out a wide range of tasks because they execute different
programs, each of which directs the computer to work on a specific task.
A computer program
The computer itself is a machine that stores data (numbers, words, pictures), inter-
is a sequence acts with devices (the monitor, the sound system, the printer), and executes programs.
of instructions A computer program tells a computer, in minute detail, the sequence of steps that
and decisions.
are needed to fulfill a task. The physical computer and peripheral devices are collec-
tively called the hardware. The programs the computer executes are called the
software.
Today’s computer programs are so sophisticated that it is hard to believe that they
are composed of extremely primitive instructions. A typical instruction may be one
of the following:
• Put a red dot at a given screen position.
• Add up two numbers.
• If this value is negative, continue the program at a certain instruction.
The computer user has the illusion of smooth interaction because a program contains
a huge number of such instructions, and because the computer can execute them at
great speed.
Programming is the
The act of designing and implementing computer programs is called program-
act of designing ming. In this book, you will learn how to program a computer—that is, how to direct
and implementing the computer to execute tasks.
computer programs.
To write a computer game with motion and sound effects or a word processor
that supports fancy fonts and pictures is a complex task that requires a team of many
highly-skilled programmers. Your first programming efforts will be more mundane.
The concepts and skills you learn in this book form an important foundation, and
you should not be disappointed if your first programs do not rival the sophisticated
software that is familiar to you. Actually, you will find that there is an immense thrill
even in simple programming tasks. It is an amazing experience to see the computer

bjeo_ch01p.indd 2 11/21/18 5:11 PM


1.2 The Anatomy of a Computer 3

precisely and quickly carry out a task that would take you hours of drudgery, to
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.

1.2 The Anatomy of a Computer


To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central
processing unit (CPU) (see Figure 1). The inside
wiring of the CPU is enormously complicated.
For example, the Intel Core processor (a popular
CPU for personal computers at the time of this
writing) is composed of several hundred million
structural elements, called transistors.
The central
The CPU performs program control and data
processing unit (CPU) processing. That is, the CPU locates and exe-
performs program cutes the program instructions; it carries out
control and
data processing.
arithmetic operations such as addition, subtrac-
tion, multiplication, and division; it fetches data
from external memory or devices and places © Amorphis/iStockphoto.
processed data into storage.
Storage devices
There are two kinds of storage. Primary stor- Figure 1 Central Processing Unit
include memory and age, or memory, is made from electronic circuits that can store data, provided they are
secondary storage. supplied with electric power. Secondary storage, usually a hard disk (see Figure 2)
or a solid-state drive, provides slower and less expensive storage that persists without
electricity. A hard disk consists of rotating platters, which are coated with a magnetic

© PhotoDisc, Inc./Getty Images, Inc.

Figure 2 A Hard Disk

bjeo_ch01p.indd 3 11/21/18 5:11 PM


4 Chapter 1 Introduction

material. A solid-state drive uses electronic components that can retain information
without power, and without moving parts.
To interact with a human user, a computer requires peripheral devices. The com-
puter transmits information (called output) to the user through a display screen,
speakers, and printers. The user can enter information (called input) for the computer
by using a keyboard or a pointing device such as a mouse.
Some computers are self-contained units, whereas others are interconnected
through networks. Through the network cabling, the computer can read data and
programs from central storage locations or send data to other computers. To the user
of a networked computer, it may not even be obvious which data reside on the com-
puter itself and which are transmitted through the network.
Figure 3 gives a schematic overview of the architecture of a personal computer.
Program instructions and data (such as text, numbers, audio, or video) reside in sec-
ondary storage or elsewhere on the network. When a program is started, its instruc-
tions are brought into memory, where the CPU can read them. The CPU reads and
executes one instruction at a time. As directed by these instructions, the CPU reads
data, modifies it, and writes it back to memory or secondary storage. Some program
instructions will cause the CPU to place dots on the display screen or printer or to
vibrate the speaker. As these actions happen many times over and at great speed, the
human user will perceive images and sound. Some program instructions read user
input from the keyboard, mouse, touch sensor, or microphone. The program ana-
lyzes the nature of these inputs and then executes the next appropriate instruction.

Printer

Mouse/Trackpad Disk
Ports controller

Secondary storage
Keyboard
CPU
Monitor
Microphone
Memory

Speakers
Video camera
Network
controller Internet

Figure 3 Schematic Design of a Personal Computer

bjeo_ch01p.indd 4 11/21/18 5:11 PM


1.3 The Java Programming Language 5

Computing & Society 1.1 Computers Are Everywhere


When computers were The advent of ubiqui-
first invented in the tous computing changed
© Media Bakery.
1940s, a computer filled an entire many aspects of our
room. The photo below shows the lives. Factories used
ENIAC (electronic numerical integrator to employ people to
and computer), completed in 1946 at do repetitive assembly
the University of Pennsylvania. The tasks that are today car-
ENIAC was used by the military to ried out by computer-
compute the trajectories of projectiles. controlled robots, oper-
Nowadays, computing facilities of ated by a few people
search engines, Internet shops, and who know how to
social networks fill huge buildings work with those com-
called data centers. At the other end of puters. Books, music,
the spectrum, computers are all around and movies nowadays © Maurice Savage/Alamy Limited.
us. Your cell phone has a computer are often consumed
inside, as do many credit cards and fare on computers, and This transit card contains a computer.
cards for public transit. A modern car computers are almost
has several computers––to control the always involved in their production. now could not have been written with-
engine, brakes, lights, and the radio. The book that you are reading right out computers.
Knowing about computers and
how to program them has become an
essential skill in many careers. Engi-
neers design computer-controlled cars
and medical equipment that preserve
lives. Computer scientists develop
programs that help people come
together to support social causes. For
example, activists used social net-
works to share videos showing abuse
by repressive regimes, and this infor-
mation was instrumental in changing
public opinion.
As computers, large and small,
become ever more embedded in
our everyday lives, it is increasingly
important for everyone to understand
how they work, and how to work with
them. As you use this book to learn
how to program a computer, you will
develop a good understanding of com-
puting fundamentals that will make
© UPPA/Photoshot. you a more informed citizen and, per-
haps, a computing professional.
The ENIAC

1.3 The Java Programming Language


In order to write a computer program, you need to provide a sequence of instructions
that the CPU can execute. A computer program consists of a large number of simple
CPU instructions, and it is tedious and error-prone to specify them one by one. For
that reason, high-level programming languages have been created. In a high-level

bjeo_ch01p.indd 5 11/29/18 3:53 PM


6 Chapter 1 Introduction

language, you specify the actions that your program should carry out. A compiler
translates the high-level instructions into the more detailed instructions (called
machine code) required by the CPU. Many different programming languages have
been designed for different purposes.
In 1991, a group led by James Gosling and Patrick
Naughton at Sun Microsystems designed a program-
ming language, code-named “Green”, for use in con-
sumer devices, such as intelligent television “set-top”
boxes. The language was designed to be simple, secure,
and usable for many different processor types. No cus-
tomer was ever found for this technology.
Java was originally
Gosling recounts that in 1994 the team realized,
designed for “We could write a really cool browser. It was one of the
programming few things in the client/server mainstream that needed
consumer devices,
but it was first
some of the weird things we’d done: architecture neu- © James Sullivan/Getty Images.
successfully used tral, real-time, reliable, secure.” Java was introduced to
to write Internet an enthusiastic crowd at the SunWorld exhibition in James Gosling
applets.
1995, together with a browser that ran applets—Java
code that can be located anywhere on the Internet.
The figure at right shows a typical example of an
applet.
Since then, Java has grown at a phenomenal rate.
Programmers have embraced the language because
it is easier to use than its closest rival, C++. In addi-
tion, Java has a rich library that makes it possible
to write portable programs that can bypass pro-
prietary operating systems—a feature that was
eagerly sought by those who wanted to be inde-
pendent of those proprietary systems and was bit-
terly fought by their vendors. A “micro edition” An Applet for Visualizing Molecules
and an “enterprise edition” of the Java library
allow Java programmers to target hardware ranging from smart cards to the largest
Internet servers.

Table 1 Java Versions (since Version 1.0 in 1996)


Version Year Important New Features Version Year Important New Features

1.1 1997 Inner classes 6 2006 Library improvements

1.2 1998 Swing, Collections framework 7 2011 Small language changes and library
improvements

1.3 2000 Performance enhancements 8 2014 Function expressions, streams, new


date/time library

1.4 2002 Assertions, XML support 9 2017 Modules

5 2004 Generic classes, enhanced for 10, 11 2018 Versions with incremental
loop, auto-boxing, improvements are released
enumerations, annotations every six months

bjeo_ch01p.indd 6 11/21/18 5:11 PM


1.4 Becoming Familiar with Your Programming Environment 7

Java was designed to


Because Java was designed for the Internet, it has two attributes that make it very
be safe and portable, suitable for beginners: safety and portability.
benefiting both Java was designed so that anyone can execute programs in their browser without
Internet users
and students.
fear. The safety features of the Java language ensure that a program is terminated if it
tries to do something unsafe. Having a safe environment is also helpful for anyone
learning Java. When you make an error that results in unsafe behavior, your program
is terminated and you receive an accurate error report.
Java programs
The other benefit of Java is portability. The same Java program will run, without
are distributed as change, on Windows, UNIX, Linux, or Macintosh. In order to achieve portability,
instructions for a the Java compiler does not translate Java programs directly into CPU instructions.
virtual machine,
making them
Instead, compiled Java programs contain instructions for the Java virtual machine, a
platform-independent. program that simulates a real CPU. Portability is another benefit for the beginning
student. You do not have to learn how to write programs for different platforms.
At this time, Java is firmly established as one of the most important languages for
general-purpose programming as well as for computer science instruction. However,
although Java is a good language for beginners, it is not perfect, for three reasons.
Because Java was not specifically designed for students, no thought was given to
making it really simple to write basic programs. A certain amount of technical machin-
ery is necessary to write even the simplest programs. This is not a problem for profes-
sional programmers, but it can be a nuisance for beginning students. As you learn how
to program in Java, there will be times when you will be asked to be satisfied with a
preliminary explanation and wait for more complete detail in a later chapter.
Java has been extended many times during its life—see Table 1. In this book, we
assume that you have Java version 8 or later.
Java has a very
Finally, you cannot hope to learn all of Java in one course. The Java language itself
large library. Focus is relatively simple, but Java contains a vast set of library packages that are required to
on learning those write useful programs. There are packages for graphics, user-interface design, cryp-
parts of the library
that you need for
tography, networking, sound, database storage, and many other purposes. Even
your programming expert Java programmers cannot hope to know the contents of all of the packages—
projects. they just use those that they need for particular projects.
Using this book, you should expect to learn a good deal about the Java language
and about the most important packages. Keep in mind that the central goal of this
book is not to make you memorize Java minutiae, but to teach you how to think
about programming.

1.4 Becoming Familiar with Your


Programming Environment
Set aside time to
Many students find that the tools they need as programmers are very different from the
become familiar with software with which they are familiar. You should spend some time making yourself
the programming familiar with your programming environment. Because computer systems vary widely,
environment that
you will use for your
this book can only give an outline of the steps you need to follow. It is a good idea to
class work. participate in a hands-on lab, or to ask a knowledgeable friend to give you a tour.
Step 1 Start the Java development environment.
Computer systems differ greatly in this regard. On many computers there is an inte-
grated development environment in which you can write and test your programs.

bjeo_ch01p.indd 7 11/21/18 5:11 PM


8 Chapter 1 Introduction

Figure 4
Running the
HelloPrinter
Program in an
Integrated Click to compile and run
Development Java program
Environment

Program output

An editor is a
On other computers you first launch an editor, a program that functions like a word
program for entering processor, in which you can enter your Java instructions; you then open a console
and modifying window and type commands to execute your program. You need to find out how to
text, such as a Java
program.
get started with your environment.
Step 2 Write a simple program.
The traditional choice for the very first program in a new programming language is
a program that displays a simple greeting: “Hello, World!”. Let us follow that tradi-
tion. Here is the “Hello, World!” program in Java:
public class HelloPrinter
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}

We will examine this program in the next section.


No matter which programming environment you use, you begin your activity by
typing the program statements into an editor window.
Create a new file and call it HelloPrinter.java, using the steps that are appropriate
for your environment. (If your environment requires that you supply a project name
in addition to the file name, use the name hello for the project.) Enter the program
instructions exactly as they are given above. Alternatively, locate the electronic copy
in this book’s companion code and paste it into your editor.
Java is case sensitive. As you write this program, pay careful attention to the various symbols, and keep
You must be careful
about distinguishing
in mind that Java is case sensitive. You must enter upper- and lowercase letters exactly
between upper- and as they appear in the program listing. You cannot type MAIN or PrintLn. If you are not
lowercase letters. careful, you will run into problems—see Common Error 1.2.

bjeo_ch01p.indd 8 11/21/18 5:11 PM


1.4 Becoming Familiar with Your Programming Environment 9

Figure 5 Running the HelloPrinter Program in a Console Window

Step 3 Run the program.


The process for running a program depends greatly on your programming environ-
ment. You may have to click a button or enter some commands. When you run the
test program, the message
Hello, World!

will appear somewhere on the screen (see Figure 4 and Figure 5).
The Java compiler
In order to run your program, the Java compiler translates your source files (that
translates source is, the statements that you wrote) into class files. (A class file contains instructions for
code into class the Java virtual machine.) After the compiler has translated your source code into
files that contain
instructions for the
virtual machine instructions, the virtual machine executes them. During execution,
Java virtual machine. the virtual machine accesses a library of pre-written code, including the implementa-
tions of the System and PrintStream classes that are necessary for displaying the
program’s output. Figure 6 summarizes the process of creating and running a Java
program. In some programming environments, the compiler and virtual machine are
essentially invisible to the programmer—they are automatically executed whenever
you ask to run a Java program. In other environments, you need to launch the com-
piler and virtual machine explicitly.
Step 4 Organize your work.
As a programmer, you write programs, try them out, and improve them. You store
your programs in files. Files are stored in folders or directories. A folder can contain

Virtual
Editor Compiler
Machine
Class files

Running
Source File Program

Library files

Figure 6 From Source Code to Running Program

bjeo_ch01p.indd 9 11/21/18 5:11 PM


10 Chapter 1 Introduction

files as well as other folders, which themselves can contain more files and folders (see
Figure 7). This hierarchy can be quite large, and you need not be concerned with all of
its branches. However, you should create folders for organizing your work. It is a
good idea to make a separate folder for your pro-
gramming coursework. Inside that folder, make a
separate folder for each program.
Some programming environments place your
programs into a default location if you don’t spec-
ify a folder yourself. In that case, you need to find
out where those files are located.
Be sure that you understand where your files are
located in the folder hierarchy. This information is
essential when you submit files for grading, and for
making backup copies (see Programming Tip 1.1). Figure 7 A Folder Hierarchy

Programming Tip 1.1


Backup Copies
You will spend many hours creating and improving Java programs.
© Eric Isselé/iStockphoto. It is easy to delete a file by accident, and occasionally files are lost
because of a computer malfunction. Retyping the contents of lost
Develop a strategy files is frustrating and time-consuming. It is therefore crucially
for keeping backup important that you learn how to safeguard files and get in the habit
copies of your work of doing so before disaster strikes. Backing up files on a memory © Tatiana Popova/iStockphoto.
before disaster
strikes.
stick is an easy and convenient storage method for many people. Another increasingly popular
form of backup is Internet file storage.
Here are a few pointers to keep in mind:
• Back up often. Backing up a file takes only a few seconds, and you will hate yourself if you
have to spend many hours recreating work that you could have saved easily. I recommend
that you back up your work once every thirty minutes.
• Rotate backups. Use more than one directory for backups, and rotate them. That is, first
back up onto the first directory. Then back up onto the second directory. Then use the
third, and then go back to the first. That way you always have three recent backups. If
your recent changes made matters worse, you can then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right—that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from a backup, you are
likely to be in an unhappy, nervous state. Take a deep breath and think through the
recovery process before you start. It is not uncommon for an agitated computer user to
wipe out the last backup when trying to restore a damaged file.

bjeo_ch01p.indd 10 11/21/18 5:11 PM


1.5 Analyzing Your First Program 11

1.5 Analyzing Your First Program


In this section, we will analyze the first Java program in detail. Here again is the
source code.

sec04/HelloPrinter.java
© Amanda Rohde/iStockphoto.

1 public class HelloPrinter


2 {
3 public static void main(String[] args)
4 {
5 // Display a greeting in the console window
6
7 System.out.println("Hello, World!");
8 }
© Amanda Rohde/iStockphoto. 9 }

The line
public class HelloPrinter

indicates the declaration of a class called HelloPrinter.


Classes are the
Every Java program consists of one or more classes. We will discuss classes in more
fundamental detail in Chapters 2 and 3.
building blocks of The word public denotes that the class is usable by the “public”. You will later
Java programs.
encounter private features.
In Java, every source file can contain at most one public class, and the name of the
public class must match the name of the file containing the class. For example, the
class HelloPrinter must be contained in a file named HelloPrinter.java.
The construction
public static void main(String[] args)
{
. . .
}

declares a method called main. A method contains a collection of programming


instructions that describe how to carry out a particular task.
Every Java
Every Java application must have a main method. Most Java programs contain
application contains other methods besides main, and you will see in Chapter 3 how to write other
a class with a main methods.
method. When the
application starts,
The term static is explained in more detail in Chapter 8, and the meaning of
the instructions in String[] args is covered in Chapter 11. At this time, simply consider
the main method
are executed.
public class ClassName
{
public static void main(String[] args)
{
. . .
}
}

Each class contains as a part of the “plumbing” that is required to create a Java program. Our first pro-
declarations of gram has all instructions inside the main method of the class.
methods. Each
method contains
The main method contains one or more instructions called statements. Each state-
a sequence ment ends in a semicolon (;). When a program runs, the statements in the main method
of instructions. are executed one by one.

bjeo_ch01p.indd 11 11/21/18 5:11 PM


12 Chapter 1 Introduction

In our example program, the main method has a single statement:


System.out.println("Hello, World!");

This statement prints a line of text, namely “Hello, World!”. In this statement, we call
a method which, for reasons that we will not explain here, is specified by the rather
long name System.out.println.
We do not have to implement this method—the programmers who wrote the Java
library already did that for us. We simply want the method to perform its intended
task, namely to print a value.
A method is called
Whenever you call a method in Java, you need to specify
by specifying the
method and
1. The method you want to use (in this case, System.out.println).
its arguments. 2. Any values the method needs to carry out its task (in this case, "Hello, World!").
The technical term for such a value is an argument. Arguments are enclosed in
parentheses. Multiple arguments are separated by commas.
A sequence of characters enclosed in quotation marks
"Hello, World!"

A string is a sequence
is called a string. You must enclose the contents of the string inside quotation marks
of characters so that the compiler knows you literally mean "Hello, World!". There is a reason for
enclosed in this requirement. Suppose you need to print the word main. By enclosing it in quota-
quotation marks.
tion marks, "main", the compiler knows you mean the sequence of characters m a i n,
not the method named main. The rule is simply that you must enclose all text strings in
quotation marks, so that the compiler considers them plain text and does not try to
interpret them as program instructions.
You can also print numerical values. For example, the statement
System.out.println(3 + 4);

evaluates the expression 3 + 4 and displays the number 7.

Syntax 1.1 Java Program

Every program contains at least one class.


Choose a class name that describes
the program action.
Every Java program public class HelloPrinter
contains a main method {
with this header. public static void main(String[] args)
{
System.out.println("Hello, World!"); Replace this
The statements inside the } statement when you
main method are executed } write your own
when the program runs. Each statement programs.
ends in a semicolon.
See Common Error 1.1.
Be sure to match the
opening and closing braces.

bjeo_ch01p.indd 12 11/21/18 5:11 PM


1.6 Errors 13

The System.out.println method prints a string or a number and then starts a new
line. For example, the sequence of statements
System.out.println("Hello");
System.out.println("World!");

prints two lines of text:


Hello
World!

There is a second method, System.out.print, that you can use to print an item without
starting a new line. For example, the output of the two statements
System.out.print("00");
System.out.println(3 + 4);

is the single line


007

EXAMPLE CODE See sec05 of your eText or companion code for a program that demonstrates print commands.

Common Error 1.1


Omitting Semicolons
© John Bell/iStockphoto.
In Java every statement must end in a semicolon. Forgetting to type a semicolon is a common
error. It confuses the compiler, because the compiler uses the semicolon to find where one
statement ends and the next one starts. The compiler does not use line breaks or closing braces
to recognize the end of statements. For example, the compiler considers
System.out.println("Hello")
System.out.println("World!");
a single statement, as if you had written
System.out.println("Hello") System.out.println("World!");
Then it doesn’t understand that statement, because it does not expect the word System follow-
ing the closing parenthesis after "Hello".
The remedy is simple. Scan every statement for a terminating semicolon, just as you would
check that every English sentence ends in a period. However, do not add a semicolon at the
end of public class Hello or public static void main. These lines are not statements.

1.6 Errors
Experiment a little with the HelloPrinter program. What happens if you make a typing
error such as
System.ou.println("Hello, World!");
System.out.println("Hello, Word!");

In the first case, the compiler will complain. It will say that it has no clue what you
mean by ou. The exact wording of the error message is dependent on your develop-
ment environment, but it might be something like “Cannot find symbol ou”. This is a
compile-time error. Something is wrong according to the rules of the language and
the compiler finds it. For this reason, compile-time errors are often called syntax
errors. When the compiler finds one or more errors, it refuses to translate the

bjeo_ch01p.indd 13 11/21/18 5:11 PM


14 Chapter 1 Introduction

program into Java virtual machine instructions, and as a consequence you have no
program that you can run. You must fix the error and compile again. In fact, the com-
piler is quite picky, and it is common to go through several rounds of fixing compile-
time errors before compilation succeeds for the first time.
A compile-time error
If the compiler finds an error, it will not simply
is a violation of stop and give up. It will try to report as many
the programming errors as it can find, so you can fix them all at once.
language rules that
is detected by
Sometimes, an error throws the compiler
the compiler. off track. Suppose, for example, you forget the
quotation marks around a string: System.out.
println(Hello, World!). The compiler will not
complain about the missing quotation marks.
Instead, it will report “Cannot find symbol
Hello”. Unfortunately, the compiler is not very
smart and it does not realize that you meant to © Martin Carlsson/iStockphoto.
use a string. It is up to you to realize that you Programmers spend a fair amount
need to enclose strings in quotation marks. of time fixing compile-time and
The error in the second line above is of a dif- run-time errors.
ferent kind. The program will compile and run,
but its output will be wrong. It will print
Hello, Word!

A run-time error
This is a run-time error. The program is syntactically correct and does something,
causes a program to but it doesn’t do what it is supposed to do. Because run-time errors are caused by
take an action that logical flaws in the program, they are often called logic errors.
the programmer did
not intend.
This particular run-time error did not include an error message. It simply pro-
duced the wrong output. Some kinds of run-time errors are so severe that they gen-
erate an exception: an error message from the Java virtual machine. For example, if
your program includes the statement
System.out.println(1 / 0);

you will get a run-time error message “Division by zero”.


During program development, errors are unavoidable. Once a program is longer
than a few lines, it would require superhuman concentration to enter it correctly
without slipping up once. You will find yourself omitting semicolons or quotation
marks more often than you would like, but the compiler will track down these prob-
lems for you.
Run-time errors are more troublesome. The compiler will not find them—in fact,
the compiler will cheerfully translate any program as long as its syntax is correct—
but the resulting program will do something wrong. It is the responsibility of the
program author to test the program and find any run-time errors.
EXAMPLE CODE See sec06 of your eText or companion code for three programs that illustrate errors.

Common Error 1.2


Misspelling Words
© John Bell/iStockphoto.
If you accidentally misspell a word, then strange things may happen, and it may not always be
completely obvious from the error messages what went wrong. Here is a good example of how
simple spelling errors can cause trouble:

bjeo_ch01p.indd 14 11/21/18 5:11 PM


1.7 Problem Solving: Algorithm Design 15

public class HelloPrinter


{
public static void Main(String[] args)
{
System.out.println("Hello, World!");
}
}
This class declares a method called Main. The compiler will not consider this to be the same as
the main method, because Main starts with an uppercase letter and the Java language is case sen-
sitive. Upper- and lowercase letters are considered to be completely different from each other,
and to the compiler Main is no better match for main than rain. The compiler will cheerfully
compile your Main method, but when the Java virtual machine reads the compiled file, it will
complain about the missing main method and refuse to run the program. Of course, the mes-
sage “missing main method” should give you a clue where to look for the error.
If you get an error message that seems to indicate that the compiler or virtual machine is on
the wrong track, check for spelling and capitalization. If you misspell the name of a symbol
(for example, ou instead of out), the compiler will produce a message such as “cannot find sym-
bol ou”. That error message is usually a good clue that you made a spelling error.

1.7 Problem Solving: Algorithm Design


You will soon learn how to program calculations and decision making in Java. But
before we look at the mechanics of implementing computations in the next chapter,
let’s consider how you can describe the steps that are necessary for finding the solu-
tion to a problem.

1.7.1 The Algorithm Concept


You may have run across advertisements that
encourage you to pay for a computerized service
that matches you up with a love partner. Think
how this might work. You fill out a form and
send it in. Others do the same. The data are pro-
cessed by a computer program. Is it reasonable to
assume that the computer can perform the task
of finding the best match for you? Suppose your
younger brother, not the computer, had all the
forms on his desk. What instructions could you
give him? You can’t say, “Find the best-looking © mammamaart/iStockphoto.
person who likes inline skating and browsing
the Internet”. There is no objective standard for Finding the perfect partner is not a
problem that a computer can solve.
good looks, and your brother’s opinion (or that
of a computer program analyzing the photos of prospective partners) will likely be
different from yours. If you can’t give written instructions for someone to solve the
problem, there is no way the computer can magically find the right solution. The
computer can only do what you tell it to do. It just does it faster, without getting
bored or exhausted.

bjeo_ch01p.indd 15 11/21/18 5:11 PM


16 Chapter 1 Introduction

For that reason, a computerized match-making service cannot guarantee to find


the optimal match for you. Instead, you may be presented with a set of potential part-
ners who share common interests with you. That is a task that a computer program
can solve.
In order for a computer program to provide an answer to a problem that computes
an answer, it must follow a sequence of steps that is
• Unambiguous
• Executable
• Terminating

An algorithm for
The step sequence is unambiguous when there are
solving a problem is precise instructions for what to do at each step and
a sequence of steps where to go next. There is no room for guesswork
that is unambiguous,
executable, and
or personal opinion. A step is executable when it
terminating. can be carried out in practice. For example, a com-
puter can list all people that share your hobbies,
but it can’t predict who will be your life-long part-
ner. Finally, a sequence of steps is terminating if it
will eventually come to an end. A program that
keeps working without delivering an answer is
clearly not useful.
A sequence of steps that is unambiguous, exe-
cutable, and terminating is called an algorithm.
© Claudiad/iStockphoto.
Although there is no algorithm for finding a part-
ner, many problems do have algorithms for solving An algorithm is a recipe for finding
them. The next section gives an example. a solution.

1.7.2 An Algorithm for Solving an Investment Problem


Consider the following investment problem:
You put $10,000 into a bank account that earns 5 percent interest per year. How many
years does it take for the account balance to be double the original?
Could you solve this problem by hand? Sure, you could. You figure out the balance
as follows:

year interest balance


0 10000
1 10000.00 x 0.05 = 500.00 10000.00 + 500.00 = 10500.00
2 10500.00 x 0.05 = 525.00 10500.00 + 525.00 = 11025.00
3 11025.00 x 0.05 = 551.25 11025.00 + 551.25 = 11576.25
4 11576.25 x 0.05 = 578.81 11576.25 + 578.81 = 12155.06

You keep going until the balance is at least $20,000. Then the last number in the year
column is the answer.
Of course, carrying out this computation is intensely boring to you or your
younger brother. But computers are very good at carrying out repetitive calcula-
tions quickly and flawlessly. What is important to the computer is a description of the

bjeo_ch01p.indd 16 11/21/18 5:11 PM


Other documents randomly have
different content
point, at least till the war should be ended. Some leading
Democrats, including ex-President Van Buren, have taken this
same view, as I understand them; and I adhered to it, and
acted upon it, until since I took my seat here; and I think I
should still adhere to it, were it not that the President and his
friends will not allow it to be so. Besides, the continual effort of
the President to argue every silent vote given for supplies into
an indorsement of the justice and wisdom of his conduct;
besides that singularly candid paragraph in his late message, in
which he tells us that Congress, with great unanimity (only two
in the Senate and fourteen in the House dissenting) had
declared that ‘by the act of the Republic of Mexico a state of
war exists between that Government and the United States;’
when the same journals that informed him of this, also informed
him that, when that declaration stood disconnected from the
question of supplies, sixty-seven in the House, and not fourteen,
merely, voted against it; besides this open attempt to prove by
telling the truth, what he could not prove by telling the whole
truth, demanding of all who will not submit to be
misrepresented, in justice to themselves, to speak out; besides
all this, one of my colleagues [Mr. Richardson], at a very early
day in the session, brought in a set of resolutions, expressly
indorsing the original justice of the war on the part of the
President. Upon these resolutions, when they shall be put on
their passage, I shall be compelled to vote; so that I can not be
silent if I would. Seeing this, I went about preparing myself to
give the vote understandingly, when it should come. I carefully
examined the President’s messages, to ascertain what he
himself had said and proved upon the point. The result of this
examination was to make the impression, that, taking for true
all the President states as facts, he falls far short of proving his
justification; and that the President would have gone further
with his proof, if it had not been for the small matter that the
truth would not permit him. Under the impression thus made I
gave the vote before mentioned. I propose now to give,
concisely, the process of the examination I made, and how I
reached the conclusion I did.
“The President, in his first message of May, 1846, declares
that the soil was ours on which hostilities were commenced by
Mexico; and he repeats that declaration, almost in the same
language, in each successive annual message​—​thus showing
that he esteems that point a highly essential one. In the
importance of that point I entirely agree with the President. To
my judgment, it is the very point upon which he should be
justified or condemned. In his message of December, 1846, it
seems to have occurred to him, as is certainly true, that title,
ownership to soil, or any thing else, is not a simple fact, but is a
conclusion following one or more simple facts; and that it was
incumbent upon him to present the facts from which he
concluded the soil was ours on which the first blood of the war
was shed.
“Accordingly, a little below the middle of page twelve, in the
message last referred to, he enters upon that task; forming an
issue and introducing testimony, extending the whole to a little
below the middle of page fourteen. Now, I propose to try to
show that the whole of this​—​issue and evidence​—​is, from
beginning to end, the sheerest deception. The issue, as he
presents it, is in these words: ‘But there are those who,
conceding all this to be true, assume the ground that the true
western boundary of Texas is the Nueces, instead of the Rio
Grande; and that, therefore, in marching our army to the east
bank of the latter river, we passed the Texan line, and invaded
the territory of Mexico.’ Now, this issue is made up of two
affirmatives and no negative. The main deception of it is, that it
assumes as true that one river or the other is necessarily the
boundary, and cheats the superficial thinker entirely out of the
idea that possibly the boundary is somewhere between the two,
and not actually at either. A further deception is, that it will let
in evidence which a true issue would exclude. A true issue made
by the President would be about as follows: ‘I say the soil was
ours on which the first blood was shed; there are those who say
it was not.’
“I now proceed to examine the President’s evidence, as
applicable to such an issue. When that evidence is analyzed it is
all included in the following propositions:
“1. That the Rio Grande was the western boundary of
Louisiana, as we purchased it of France in 1803.
“2. That the Republic of Texas always claimed the Rio
Grande as her western boundary.
“3. That, by various acts, she had claimed it on paper.
“4. That Santa Anna, in his treaty with Texas, recognized
the Rio Grande as her boundary.
“5. That Texas before, and the United States after
annexation, had exercised jurisdiction beyond the Nueces,
between the two rivers.
“6. That our Congress understood the boundary of Texas to
extend beyond the Nueces.
“Now for each of these in its turn:
“His first item is, that the Rio Grande was the western
boundary of Louisiana, as we purchased it of France in 1803;
and, seeming to expect this to be disputed, he argues over the
amount of nearly a page to prove it true; at the end of which he
lets us know that, by the treaty of 1819, we sold to Spain the
whole country, from the Rio Grande eastward to the Sabine.
Now, admitting for the present, that the Rio Grande was the
boundary of Louisiana, what, under heaven, had that to do with
the present boundary between us and Mexico? How, Mr.
Chairman, the line that once divided your land from mine can
still be the boundary between us after I have sold my land to
you, is, to me, beyond all comprehension. And how any man,
with an honest purpose only of proving the truth, could ever
have thought of introducing such a fact to prove such an issue,
is equally incomprehensible. The outrage upon common right, of
seizing as our own what we have once sold, merely because it
was ours before we sold it, is only equaled by the outrage on
common sense of any attempt to justify it.
“The President’s next piece of evidence is, that ‘The
Republic of Texas always claimed this river (Rio Grande) as her
western boundary.’ That is not true, in fact. Texas has claimed
it, but she has not always claimed it. There is, at least, one
distinguished exception. Her State Constitution​—​the public’s
most solemn and well-considered act; that which may, without
impropriety, be called her last will and testament, revoking all
others​—​makes no such claim. But suppose she had always
claimed it. Has not Mexico always claimed the contrary? So that
there is but claim against claim, leaving nothing proved until we
get back of the claims, and find which has the better
foundation.
“Though not in the order in which the President presents his
evidence, I now consider that class of his statements, which
are, in substance, nothing more than that Texas has by various
acts of her Convention and Congress, claimed the Rio Grande as
her boundary​—​on paper. I mean here what he says about the
fixing of the Rio Grande as her boundary, in her old Constitution
(not her State Constitution), about forming congressional
districts, counties, etc. Now, all this is but naked claim; and
what I have already said about claims is strictly applicable to
this. If I should claim your land by word of mouth, that certainly
would not make it mine; and if I were to claim it by a deed
which I had made myself, and with which you had nothing to
do, the claim would be quite the same in substance, or rather in
utter nothingness.
“I next consider the President’s statement that Santa Anna,
in his treaty with Texas, recognized the Rio Grande as the
western boundary of Texas. Besides the position so often taken
that Santa Anna, while a prisoner of war​—a​ captive​—​could not
bind Mexico by a treaty, which I deem conclusive; besides this, I
wish to say something in relation to this treaty so called by the
President, with Santa Anna. If any man would like to be amused
by a sight at that little thing, which the President calls by that
big name, he can have it by turning to Niles’ Register, volume
50, page 386. And if any one should suppose that Niles’
Register is a curious repository of so mighty a document as a
solemn treaty between nations, I can only say that I learned, to
a tolerable degree of certainty, by inquiry at the State
Department, that the President himself never saw it anywhere
else. By the way, I believe I should not err if I were to declare,
that during the first ten years of the existence of that
document, it was never by anybody called a treaty; that it was
never so called till the President, in his extremity, attempted, by
so calling it, to wring something from it in justification of himself
in connection with the Mexican war. It has none of the
distinguishing features of a treaty. It does not call itself a treaty.
Santa Anna does not therein assume to bind Mexico; he
assumes only to act as President, Commander-in-chief of the
Mexican army and navy; stipulates that the then present
hostilities should cease, and that he would not himself take up
arms, nor influence the Mexican people to take up arms, against
Texas, during the existence of the war of independence. He did
not recognize the independence of Texas; he did not assume to
put an end to the war, but clearly indicated his expectation of its
continuance; he did not say one word about boundary, and
most probably never thought of it. It is stipulated therein that
the Mexican forces should evacuate the territory of Texas,
passing to the other side of the Rio Grande; and in another
article it is stipulated, that to prevent collisions between the
armies, the Texan army should not approach nearer than five
leagues​—​of what is not said​—​but clearly, from the object
stated, it is of the Rio Grande. Now, if this is a treaty
recognizing the Rio Grande as a boundary of Texas, it contains
the singular feature of stipulating that Texas shall not go within
five leagues of her own boundary.
“Next comes the evidence that Texas before annexation,
and the United States afterward, exercising jurisdiction beyond
the Nueces, and between the two rivers. This actual exercise of
jurisdiction is the very class or quality of evidence we want. It is
excellent so far as it goes; but does it go far enough? He tells us
it went beyond the Nueces, but he does not tell us it went to
the Rio Grande. He tells us jurisdiction was exercised between
the two rivers, but he does not tell us it was exercised over all
the territory between them. Some simple-minded people think it
possible to cross one river and go beyond it, without going all
the way to the next; that jurisdiction may be exercised between
two rivers without covering all the country between them. I
know a man, not very unlike myself, who exercises jurisdiction
over a piece of land between the Wabash and the Mississippi;
and yet so far is this from being all there is between those
rivers, that it is just one hundred and fifty-two feet long by fifty
wide, and no part of it much within a hundred miles of either.
He has a neighbor between him and the Mississippi​—​that is,
just across the street, in that direction​—w ​ hom, I am sure, he
could neither persuade nor force to give up his habitation; but
which, nevertheless he could certainly annex, if it were to be
done, by merely standing on his own side of the street and
claiming it, or even sitting down and writing a deed for it.
“But next, the President tells us, the Congress of the United
States understood the State of Texas they admitted into the
Union to extend beyond the Nueces. Well, I suppose they did​—I​
certainly so understand it​—​but how far beyond? That Congress
did not understand it to extend clear to the Rio Grande, is quite
certain by the fact of their joint resolutions for admission
expressly leaving all questions of boundary to future
adjustment. And, it may be added, that Texas herself is proved
to have had the same understanding of it that our Congress
had, by the fact of the exact conformity of her new Constitution
to those resolutions.
“I am now through the whole of the President’s evidence;
and it is a singular fact, that if any one should declare the
President sent the army into the midst of a settlement of
Mexican people, who had never submitted, by consent or by
force to the authority of Texas or of the United States, and that
there, and thereby, the first blood of the war was shed, there is
not one word in all the President has said which would either
admit or deny the declaration. In this strange omission chiefly
consists the deception of the President’s evidence​—a ​ n omission
which, it does seem to me, could scarcely have occurred but by
design. My way of living leads me to be about the courts of
justice; and there I have sometimes seen a good lawyer,
struggling for his client’s neck, in a desperate case, employing
every artifice to work round, befog, and cover up with many
words some position pressed upon him by the prosecution,
which he dared not admit, and yet could not deny. Party bias
may help to make it appear so; but, with all the allowance I can
make for such bias, it still does appear to me that just such and
from just such necessity, are the President’s struggles in this
case.
“Some time after my colleague (Mr. Richardson) introduced
the resolutions I have mentioned, I introduced a preamble,
resolution, and interrogatories, intended to draw the President
out, if possible, on this hitherto untrodden ground. To show
their relevancy, I propose to state my understanding of the true
rule for ascertaining the boundary between Texas and Mexico. It
is, that wherever Texas was exercising jurisdiction was hers;
and wherever Mexico was exercising jurisdiction was hers: and
that whatever separated the actual exercise of jurisdiction of the
one from that of the other, was the true boundary between
them. If, as is probably true, Texas was exercising jurisdiction
along the western bank of the Nueces, and Mexico was
exercising it along the eastern bank of the Rio Grande, then
neither river was the boundary, but the uninhabited country
between the two was. The extent of our territory in that region
depended not on any treaty-fixed boundary (for no treaty had
attempted it), but on revolution. Any people anywhere, being
inclined and having the power, have the right to rise up and
shake off the existing government, and form a new one that
suits them better. This is a most valuable, a most sacred right​—​
a right which, we hope and believe, is to liberate the world. Nor
is this right confined to cases in which the whole people of an
existing government may choose to exercise it. Any portion of
such people that can may revolutionize, and make their own of
so much of their territory as they inhabit. More than this, a
majority of any portion of such people may revolutionize,
putting down a minority, intermingled with, or near about them,
who may oppose their movements. Such minority was precisely
the case of the Tories of our own Revolution. It is a quality of
revolutions not to go by old lines, or old laws; but to break up
both and make new ones. As to the country now in question,
we bought it of France in 1803, and sold it to Spain in 1819,
according to the President’s statement. After this, all Mexico,
including Texas, revolutionized against Spain; and still later,
Texas revolutionized against Mexico. In my view, just so far as
she carried her revolution, by obtaining the actual, willing or
unwilling submission of the people, so far the country was hers,
and no further.
“Now, sir, for the purpose of obtaining the very best
evidence as to whether Texas had actually carried her revolution
to the place where the hostilities of the present war
commenced, let the President answer the interrogatories I
proposed, as before mentioned, or some other similar ones. Let
him answer fully, fairly and candidly. Let him answer with facts,
and not with arguments. Let him remember he sits where
Washington sat; and, so remembering, let him answer as
Washington would answer. As a nation should not, and the
Almighty will not, be evaded, so let him attempt no evasion, no
equivocation. And if, so answering, he can show that the soil
was ours where the first blood of the war was shed​—​that it was
not within an inhabited country, or, if within such, that the
inhabitants had submitted themselves to the civil authority of
Texas, or of the United States, and that the same is true of the
site of Fort Brown​—​then I am with him for his justification. In
that case, I shall be most happy to reverse the vote I gave the
other day. I have a selfish motive for desiring that the President
may do this; I expect to give some votes, in connection with the
war, which, without his so doing, will be of doubtful propriety, in
my own judgment, but which will be free from the doubt if he
does so. But if he can not or will not do this,​—​if, on any
pretence, or no pretence, he shall refuse or omit it,​—​then I shall
be fully convinced, of what I more than suspect already, that he
is deeply conscious of being in the wrong; that he feels the
blood of this war, like the blood of Abel, is crying to heaven
against him; that he ordered General Taylor into the midst of a
peaceful Mexican settlement, purposely to bring on a war; that
originally having some strong motive​—w ​ hat I will not stop now
to give my opinion concerning​—​to involve the two countries in a
war, and trusting to escape scrutiny by fixing the public gaze
upon the exceeding brightness of military glory​—​that attractive
rainbow that rises in showers of blood​—​that serpent’s eye that
charms to destroy​—​he plunged into it, and has swept on and
on, till, disappointed in his calculation of the ease with which
Mexico might be subdued, he now finds himself he knows not
where. How like the half insane mumbling of a fever dream is
the whole war part of the late message! At one time telling us
that Mexico has nothing whatever that we can get but territory;
at another, showing us how we can support the war by levying
contributions on Mexico. At one time urging the national honor,
the security of the future, the prevention of foreign interference,
and even the good of Mexico herself, as among the objects of
the war; at another, telling us that, ‘to reject indemnity by
refusing to accept a cession of territory, would be to abandon all
our just demands, and to wage the war, bearing all its
expenses, without a purpose or definite object.’ So, then, the
national honor, security of the future, and everything but
territorial indemnity, may be considered the no purposes and
indefinite objects of the war! But having it now settled that
territorial indemnity is the only object, we are urged to seize, by
legislation here, all that he was content to take a few months
ago, and the whole province of Lower California to boot, and to
still carry on the war​—​to take all we are fighting for, and still
fight on. Again, the President is resolved, under all
circumstances, to have full territorial indemnity for the expenses
of the war; but he forgets to tell us how we are to get the
excess after those expenses shall have surpassed the value of
the whole of the Mexican territory. So, again, he insists that the
separate national existence of Mexico shall be maintained; but
he does not tell us how this can be done after we shall have
taken all her territory. Lest the question I here suggest be
considered speculative merely, let me be indulged a moment in
trying to show they are not.
“The war has gone on some twenty months; for the
expenses of which, together with an inconsiderable old score,
the President now claims about one-half of the Mexican
territory, and that by far the better half, so far as concerns our
ability to make any thing out of it. It is comparatively
uninhabited; so that we could establish land offices in it, and
raise some money in that way. But the other half is already
inhabited, as I understand it, tolerably densely for the nature of
the country; and all its lands, or all that are valuable, already
appropriated as private property. How, then, are we to make
any thing out of these lands with this incumbrance on them, or
how remove the incumbrance? I suppose no one will say that
we shall kill the people, or drive them out, or make slaves of
them, or even confiscate their property? How, then, can we
make much out of this part of the territory? If the prosecution
of the war has, in expenses, already equalled the better half of
the country, how long its future prosecution will be in equalling
the less valuable half is not a speculative but a practical
question, pressing closely upon us; and yet it is a question
which the President seems never to have thought of.
“As to the mode of terminating the war and securing peace,
the President is equally wandering and indefinite. First, it is to
be done by a more vigorous prosecution of the war in the vital
parts of the enemy’s country; and, after apparently talking
himself tired on this point, the President drops down into a half
despairing tone, and tells us, that ‘with a people distracted and
divided by contending factions, and a government subject to
constant changes, by successive revolutions, the continued
success of our arms may fail to obtain a satisfactory peace.’
Then he suggests the propriety of wheedling the Mexican
people to desert the counsels of their own leaders, and, trusting
in our protection, to set up a government from which we can
secure a satisfactory peace, telling us that ‘this may become the
only mode of obtaining such a peace.’ But soon he falls into
doubt of this too, and then drops back on to the already half
abandoned ground of ‘more vigorous prosecution.’ All this shows
that the President is in no wise satisfied with his own positions.
First, he takes up one, and, in attempting to argue us into it, he
argues himself out of it; then seizes another, and goes through
the same process; and then, confused at being able to think of
nothing new, he snatches up the old one again, which he has
some time before cast off. His mind, tasked beyond its power, is
running hither and thither, like some tortured creature on a
burning surface, finding no such position on which it can settle
down and be at ease.
“Again, it is a singular omission in this message, that it
nowhere intimates when the President expects the war to
terminate. At its beginning, General Scott was, by this same
President driven into disfavor, if not disgrace, for intimating that
peace could not be conquered in less than three or four months.
But now at the end of about twenty months, during which time
our arms have given us the most splendid successes​—​every
department, and every part, land and water, officers and
privates, regulars and volunteers, doing all that men could do,
and hundreds of things which it had ever before been thought
that men could not do; after all this, this same President gives
us a long message without showing us that as to the end, he
has himself even an imaginary conception. As I have before
said, he knows not where he is. He is a bewildered, confounded,
and miserably-perplexed man. God grant he may be able to
show that there is not something about his conscience more
painful than all his mental perplexity.”

* * * * *

SPEECH ON INTERNAL IMPROVEMENTS.


(In Committee of the Whole House, June 20, 1848.)

Mr. Lincoln said:

“Mr. Chairman:​—I​ wish at all times in no way to practice any


fraud upon the House or the Committee, and I also desire to do
nothing which may be very disagreeable to any of the members.
I therefore state, in advance, that my object in taking the floor
is to make a speech on the general subject of internal
improvements; and if I am out of order in doing so I give the
Chair an opportunity of so deciding, and I will take my seat.”
The Chair.​—​“I will not undertake to anticipate what the
gentleman may say on the subject of internal improvements. He
will, therefore, proceed in his remarks, and if any question of
order shall be made, the Chair will then decide it.”
Mr. Lincoln.​—​“At an early day of this session the President
sent to us what may properly be termed an internal
improvement veto message. The late Democratic Convention
which sat at Baltimore, and which nominated General Cass for
the Presidency, adopted a set of resolutions, now called the
Democratic platform, among which is one in these words:
“‘That the Constitution does not confer upon the General
Government the power to commence and carry on a general
system of internal improvements.’
“General Cass, in his letter accepting the nomination, holds
this language:
“‘I have carefully read the resolutions of the Democratic
National Convention, laying down the platform of our political
faith, and I adhere to them as firmly as I approve them
cordially.’
“These things, taken together, show that the question of
internal improvements is now more distinctly made​—​has
become more intense, than at any former period. It can no
longer be avoided. The veto message and the Baltimore
resolution I understand to be, in substance, the same thing; the
latter being the more general statement, of which the former is
the amplification​—​the bill of particulars. While I know there are
many Democrats, on this floor and elsewhere, who disapprove
that message, I understand that all who shall vote for General
Cass will thereafter be considered as having approved it, as
having indorsed all its doctrines. I suppose all, or nearly all, the
Democrats will vote for him. Many of them will do so, not
because they like his position on this question, but because they
prefer him, being wrong in this, to another, whom they consider
further wrong on other questions. In this way the internal
improvement Democrats are to be, by a sort of forced consent,
carried over, and arrayed against themselves on this measure of
policy. General Cass, once elected, will not trouble himself to
make a Constitutional argument, or, perhaps, any argument at
all, when he shall veto a river or harbor bill. He will consider it a
sufficient answer to all Democratic murmurs, to point to Mr.
Polk’s message, and to the “Democratic platform.” This being
the case, the question of improvements is verging to a final
crisis; and the friends of the policy must now battle, and battle
manfully, or surrender all. In this view, humble as I am, I wish
to review, and contest as well as I may, the general positions of
this veto message. When I say general positions, I mean to
exclude from consideration so much as relates to the present
embarrassed state of the Treasury, in consequence of the
Mexican war.
“Those general positions are: That internal improvements
ought not to be made by the General Government:
“1. Because they would overwhelm the treasury;
“2. Because, while their burdens would be general, their
benefits would be local and partial, involving an obnoxious
inequality;
“3. Because they would be unconstitutional;
“4. Because the States may do enough by the levy and
collection of tonnage duties; or, if not,
“5. That the Constitution may be amended.
“‘Do nothing at all, lest you do something wrong,’ is the sum
of these positions​—​is the sum of this message; and this, with
the exception of what is said about Constitutionality, applying as
forcibly to making improvements by State authority as by the
national authority. So that we must abandon the improvements
of the country altogether, by any and every authority, or we
must resist and repudiate the doctrines of this message. Let us
attempt the latter.
“The first position is, that a system of internal improvement
would overwhelm the treasury.
“That, in such a system, there is a tendency to undue
expansion, is not to be denied. Such tendency is founded in the
nature of the subject. A member of Congress will prefer voting
for a bill which contains an appropriation for his district, to
voting for one which does not; and when a bill shall be
expanded till every district shall be provided for, that it will be
too greatly expanded is obvious. But is this any more true in
Congress than in a State Legislature? If a member of Congress
must have an appropriation for his district, so a member of a
Legislature must have one for his county; and if one will
overwhelm the national treasury, so the other will overwhelm
the State treasury. Go where we will, the difficulty is the same.
Allow it to drive us from the halls of Congress, and it will just as
easily drive us from the State Legislatures. Let us, then, grapple
with it, and test its strength. Let us, judging of the future by the
past, ascertain whether there may not be, in the discretion of
Congress, a sufficient power to limit and restrain this expansive
tendency within reasonable and proper bounds. The President
himself values the evidence of the past. He tells us that at a
certain point of our history, more than two hundred millions of
dollars had been applied for, to make improvements, and this
he does to prove that the treasury would be overwhelmed by
such a system. Why did he not tell us how much was granted?
Would not that have been better evidence? Let us turn to it, and
see what it proves. In the message, the President tells us that
‘during the four succeeding years, embraced by the
administration of President Adams, the power not only to
appropriate money, but to apply it, under the direction and
authority of the General Government, as well to the construction
of roads as to the improvement of harbors and rivers, was fully
asserted and exercised.’
“This, then, was the period of greatest enormity. These, if
any, must have been the days of the two hundred millions. And
how much do you suppose was really expended for
improvements during those four years? Two hundred millions?
One hundred? Fifty? Ten? Five? No, sir, less than two millions.
As shown by authentic documents, the expenditures on
improvements during 1825, 1826, 1827 and 1828, amounted to
$1,879,627 01. These four years were the period of Mr. Adams’
administration, nearly, and substantially. This fact shows that
when the power to make improvements was ‘fully asserted and
exercised,’ the Congress did keep within reasonable limits; and
what has been done it seems to me, can be done again.
“Now for the second position of the message, namely, that
the burdens of improvements would be general, while their
benefits would be local and partial, involving an obnoxious
inequality. That there is some degree of truth in this position I
shall not deny. No commercial object of Government patronage
can be so exclusively general, as not to be of some peculiar
local advantage; but on the other hand, nothing is so local as
not to be of some general advantage. The navy, as I understand
it, was established, and is maintained, at a great annual
expense, partly to be ready for war, when war shall come, but
partly also, and perhaps chiefly, for the protection of our
commerce on the high seas. This latter object is, for all I can
see, in principle, the same as internal improvements. The
driving a pirate from the track of commerce on the broad ocean,
and the removing a snag from its more narrow path in the
Mississippi river, can not, I think, be distinguished in principle.
Each is done to save life and property, and for nothing else. The
navy, then, is the most general in its benefits of all this class of
objects; and yet even the navy is of some peculiar advantage to
Charleston, Baltimore, Philadelphia, New York and Boston,
beyond what it is to the interior towns of Illinois. The next most
general object I can think of, would be improvements on the
Mississippi river and its tributaries. They touch thirteen of our
States​—​Pennsylvania, Virginia, Kentucky, Tennessee, Mississippi,
Louisiana, Arkansas, Missouri, Illinois, Indiana, Ohio, Wisconsin,
and Iowa. Now, I suppose it will not be denied, that these
thirteen States are a little more interested in improvements on
that great river than are the remaining seventeen. These
instances of the navy, and the Mississippi river show clearly that
there is something of local advantage in the most general
objects. But the converse is also true. Nothing is so local as not
to be of some general benefit. Take, for instance, the Illinois
and Michigan canal. Considered apart from its effects, it is
perfectly local. Every inch of it is within the State of Illinois. That
canal was first opened for business last April. In a very few days
we were all gratified to learn, among other things, that sugar
had been carried from New Orleans, through the canal, to
Buffalo, in New York. This sugar took this route, doubtless,
because it was cheaper than the old route. Supposing the
benefit in the reduction of the cost of carriage to be shared
between seller and buyer, the result is, that the New Orleans
merchant sold his sugar a little dearer, and the people of Buffalo
sweetened their coffee a little cheaper than before; a benefit
resulting from the canal, not to Illinois, where the canal is, but
to Louisiana and New York, where the canal is not. In other
transactions Illinois will, of course, have her share, and perhaps
the larger share too, in the benefits of the canal; but the
instance of the sugar clearly shows that the benefits of an
improvement are by no means confined to the particular locality
of the improvement itself.
“The just conclusion from all this is, that if the nation refuse
to make improvements of the more general kind, because their
benefits may be somewhat local, a State may for the same
reason, refuse to make an improvement of a local kind, because
its benefits may be somewhat general. A State may well say to
the Nation: ‘If you will do nothing for me, I will do nothing for
you.’ Thus it is seen, that if this argument of ‘inequality’ is
sufficient anywhere, it is sufficient everywhere, and puts an end
to improvements altogether. I hope and believe, that if both the
Nation and the States would, in faith, in their respective
spheres, do what they could in the way of improvements, what
of inequality might be produced in one place might be
compensated in another and that the sum of the whole might
not be very unequal. But suppose, after all, there should be
some degree of inequality: inequality is certainly never to be
embraced for its own sake; but is every good thing to be
discarded which may be inseparably connected with some
degree of it? If so, we must discard all government. This Capitol
is built at the public expense, for the public benefit; but does
any one doubt that it is of some peculiar local advantage to the
property holders and business people of Washington? Shall we
remove it for this reason? And if so, where shall we set it down,
and be free from the difficulty? To make sure of our object shall
we locate it nowhere, and leave Congress hereafter to hold its
sessions as the loafer lodged, ‘in spots about?’ I make no
special allusion to the present President when I say, there are
few stronger cases in this world of ‘burden to the many, and
benefit to the few’​—​of ‘inequality’​—​than the Presidency itself is
by some thought to be. An honest laborer digs coal at about
seventy cents a day, while the President digs abstractions at
about seventy dollars a day. The coal is clearly worth more than
the abstractions, and yet what a monstrous inequality in the
prices! Does the President, for this reason, propose to abolish
the Presidency? He does not, and he ought not. The true rule,
in determining to embrace or reject any thing, is not whether it
have any evil in it, but whether it have more of evil than of
good. There are few things wholly evil or wholly good; almost
every thing, especially of government policy, is an inseparable
compound of the two; so that our best judgment of the
preponderance between them is continually demanded. On this
principle the President, his friends, and the world generally, act
on most subjects. Why not apply it, then, upon this question?
Why, as to improvements, magnify the evil, and stoutly refuse
to see any good in them?
“Mr. Chairman, on the third position of the message (the
Constitutional question) I have not much to say. Being the man
I am, and speaking when I do, I feel that in any attempt at an
original, Constitutional argument, I should not be, and ought
not to be, listened to patiently. The ablest and the best of men
have gone over the whole ground long ago. I shall attempt but
little more than a brief notice of what some of them have said.
In relation to Mr. Jefferson’s views, I read from Mr. Polk’s veto
message:
“‘President Jefferson, in his message to Congress in 1806,
recommended an amendment of the Constitution, with a view
to apply an anticipated surplus in the treasury ‘to the great
purposes of the public education, roads, rivers, canals, and such
other objects of public improvements as it may be thought
proper to add to the Constitutional enumeration of the Federal
powers.’ And he adds: ‘I suppose an amendment to the
Constitution, by consent of the States, necessary because the
objects now recommended are not among those enumerated in
the Constitution, and to which it permits the public moneys to
be applied.’ In 1825, he repeated, in his published letters, the
opinion that no such power had been conferred upon Congress.’
“I introduce this, not to controvert, just now, the
Constitutional opinion, but to show, that on the question of
expediency, Mr. Jefferson’s opinion was against the present
President​—​that this opinion of Mr. Jefferson, in one branch at
least, is, in the hands of Mr. Polk, like McFingal’s gun:

“‘Bears wide and kicks the owner over.’

“But, to the Constitutional question. In 1826, Chancellor


Kent first published his Commentaries on American Law. He
devoted a portion of one of the lectures to the question of the
authority of Congress to appropriate public moneys for internal
improvements. He mentions that the question had never been
brought under judicial consideration, and proceeds to give a
brief summary of the discussions it had undergone between the
legislative and executive branches of the Government. He shows
that the legislative branch had usually been for, and the
executive against, the power, till the period of Mr. J. Q. Adams’
administration; at which point he considers the executive
influence as withdrawn from opposition, and added to the
support of the power. In 1844, the Chancelor published a new
edition of his Commentaries, in which he adds some notes of
what had transpired on the question since 1826. I have not time
to read the original text, or the notes, but the whole may be
found on page 267, and the two or three following pages of the
first volume of the edition of 1844. As what Chancellor Kent
seems to consider the sum of the whole, I read from one of the
notes:
“‘Mr. Justice Story, in his Commentaries on the Constitution
of the United States, vol. 2, page 429–440, and again, page
519–538, has stated at large the arguments for and against the
proposition that Congress have a Constitutional authority to lay
taxes, and to apply the power to regulate commerce, as a
means directly to encourage and protect domestic
manufactures; and, without giving any opinion of his own on
the contested doctrine, he has left the reader to draw his own
conclusion. I should think, however, from the arguments as
stated, that every mind which has taken no part in the
discussions, and felt no prejudice or territorial bias on either
side of the question, would deem the arguments in favor of the
Congressional power vastly superior.’
“It will be seen, that in this extract, the power to make
improvements is not directly mentioned; but by examining the
context, both of Kent and of Story, it will appear that the power
mentioned in the extract and the power to make improvements,
are regarded as identical. It is not to be denied that many great
and good men have been against the power; but it is insisted
that quite as many, as great, and as good, have been for it; and
it is shown that, on a full survey of the whole, Chancelor Kent
was of opinion that the arguments of the latter were vastly
superior. This is but the opinion of a man; but who was that
man? He was one of the ablest and most learned lawyers of his
age, or of any other age. It is no disparagement to Mr. Polk, nor,
indeed, to any one who devotes much time to politics, to be
placed far behind Chancelor Kent as a lawyer. His attitude was
most favorable to correct conclusions. He wrote coolly and in
retirement. He was struggling to rear a durable monument of
fame; and he well knew that truth and thoroughly sound
reasoning were the only sure foundations. Can the party opinion
of a party President, on a law question, as this purely is, be at
all compared or set in opposition to that of such a man, in such
an attitude as Chancelor Kent?
“This Constitutional question will probably never be better
settled than it is, until it shall pass under judicial consideration;
but I do think that no man who is clear on this question of
expediency need feel his conscience much pricked upon this.
“Mr. Chairman, the President seems to think that enough
may be done in the way of improvements, by means of tonnage
duties, under State authority, with the consent of the General
Government. Now, I suppose this matter of tonnage duties is
well enough in its own sphere. I suppose it may be efficient,
and perhaps sufficient, to make slight improvements and repairs
in harbors already in use, and not much out of repair. But if I
have any correct general idea of it, it must be wholly inefficient
for any generally beneficent purposes of improvement. I know
very little, or rather nothing at all, of the practical matter of
levying and collecting tonnage duties; but I suppose one of its
principles must be, to lay a duty, for the improvement of any
particular harbor, upon the tonnage coming into that harbor. To
do otherwise​—​to collect money in one harbor to be expended in
improvements in another​—w ​ ould be an extremely aggravated
form of that inequality which the President so much deprecates.
If I be right in this, how could we make any entirely new
improvements by means of tonnage duties? How make a road,
a canal, or clear a greatly obstructed river? The idea that we
could, involves the same absurdity of the Irish bull about the
new boots: ‘I shall never git ‘em on,’ says Patrick, ’till I wear ’em
a day or two, and stretch ’em a little.’ We shall never make a
canal by tonnage duties, until it shall already have been made
awhile, so the tonnage can get into it.
“After all, the President concludes that possibly there may
be some great objects of improvements which can not be
effected by tonnage duties, and which, therefore, may be
expedient for the General Government to take in hand.
Accordingly, he suggests, in case any such be discovered, the
propriety of amending the Constitution. Amend it for what? If,
like Mr. Jefferson, the President thought improvements
expedient but not Constitutional, it would be natural enough for
him to recommend such an amendment; but hear what he says
in this very message:
“‘In view of these portentous consequences, I can not but
think that this course of legislation should be arrested, even
were there nothing to forbid it in the fundamental laws of our
Union.’
“For what, then, would he have the Constitution amended?
With him it is a proposition to remove one impediment, merely
to be met by others, which, in his opinion, can not be removed​
—​to enable Congress to do what, in his opinion, they ought not
to do if they could.”
[Here Mr. Meade, of Virginia, inquired if Mr. L. understood
the President to be opposed, on grounds of expediency, to any
and every improvement?]
To which Mr. Lincoln answered: “In the very part of his
message of which I am now speaking, I understand him as
giving some vague expressions in favor of some possible objects
of improvement; but, in doing so, I understand him to be
directly in the teeth of his own arguments in other parts of it.
Neither the President, nor any one, can possibly specify an
improvement, which shall not be clearly liable to one or another
of the objections he has urged on the score of expediency; I
have shown, and might show again, that no work​—​no object​—​
can be so general, as to dispense its benefits with precise
equality; and this inequality is chief among the ‘portentous
consequences’ for which he declares that improvements should
be arrested. No, sir; when the President intimates that
something in the way of improvements may properly be done
by the General Government, he is shrinking from the
conclusions to which his own arguments would force him. He
feels that the improvements of this broad and goodly land are a
mighty interest; and he is unwilling to confess to the people, or
perhaps to himself, that he has built an argument which, when
pressed to its conclusion, entirely annihilates this interest.
“I have already said that no one who is satisfied of the
expediency of making improvements need be much uneasy in
his conscience about its Constitutionality. I wish now to submit a
few remarks on the general proposition of amending the
Constitution. As a General rule, I think we would do much better
to let it alone. No slight occasion should tempt us to touch it.
Better not take the first step, which may lead to a habit of
altering it. Better rather habituate ourselves to think of it as
unalterable. It can scarcely be made better than it is. New
provisions would introduce new difficulties, and thus create and
increase appetite for further change. No, sir; let it stand as it is.
New hands have never touched it. The men who made it have
done their work, and have passed away. Who shall improve on
what they did?
“Mr. Chairman, for the purpose of reviewing this message in
the least possible time, as well as for the sake of distinctness, I
have analyzed its arguments as well as I could, and reduced
them to the propositions I have stated. I have now examined
them in detail. I wish to detain the committee only a little while
longer, with some general remarks on the subject of
improvements. That the subject is a difficult one, can not be
denied. Still, it is no more difficult in Congress than in the State
legislatures, in the counties or in the smallest municipal districts
which everywhere exist. All can recur to instances of this
difficulty in the case of county roads, bridges, and the like. One
man is offended because a road passes over his land; and
another is offended because it does not pass over his; one is
dissatisfied because the bridge, for which he is taxed, crosses
the river on a different road from that which leads from his
house to town; another can not bear that the county should get
in debt for these same roads and bridges; while not a few
struggle hard to have roads located over their lands, and then
stoutly refuse to let them be opened, until they are first paid the
damages. Even between the different wards and streets of
towns and cities, we find this same wrangling and difficulty.
Now, these are no other than the very difficulties against which,
and out of which, the President constructs his objections of
‘inequality,’ ‘speculation,’ and ‘crushing the Treasury.’ There is
but a single alternative about them​—​they are sufficient, or they
are not. If sufficient, they are sufficient out of Congress as well
as in it, and there is the end. We must reject them as
insufficient, or lie down and do nothing by any authority. Then,
difficulty though there be, let us meet and overcome it.

‘Attempt the end, and never stand to doubt;


Nothing so hard, but search will find it out.’

“Determine that the thing can and shall be done, and then
we shall find the way. The tendency to undue expansion is
unquestionably the chief difficulty. How to do something, and
still not to do too much, is the desideratum. Let each contribute
his mite in the way of suggestion. The late Silas Wright, in a
letter to the Chicago Convention, contributed his, which was
worth something; and I now contribute mine, which may be
worth nothing. At all events, it will mislead nobody, and
therefore will do no harm. I would not borrow money. I am
against an overwhelming, crushing system. Suppose that at
each session, Congress shall first determine how much money
can, for that year, be spared for improvements; then apportion
that sum to the most important objects. So far all is easy; but
how shall we determine which are the most important? On this
question comes the collision of interests. I shall be slow to
acknowledge that your harbor or your river is more important
than mine, and vice versa. To clear this difficulty, let us have
that same statistical information which the gentleman from Ohio
[Mr. Vinton] suggested at the beginning of this session. In that
information we shall have a stern, unbending basis of facts​—a ​
basis in nowise subject to whim, caprice, or local interest. The
pre-limited amount of means will save us from doing too much,
and the statistics will save us from doing what we do in wrong
places. Adopt and adhere to this course, and, it seems to me,
the difficulty is cleared.
“One of the gentlemen from South Carolina (Mr. Rhett) very
much deprecates these statistics. He particularly objects, as I
understand him, to counting all the pigs and chickens in the
land. I do not perceive much force in the objection. It is true,
that if every thing be enumerated, a portion of such statistics
may not be very useful to this object. Such products of the
country as are to be consumed where they are produced, need
no roads and rivers, no means of transportation, and have no
very proper connection with this subject. The surplus, that
which is produced in one place to be consumed in another; the
capacity of each locality for producing a greater surplus; the
natural means of transportation, and their susceptibility of
improvement; the hindrances, delays, and losses of life and
property during transportation, and the causes of each, would
be among the most valuable statistics in this connection. From
these it would readily appear where a given amount of
expenditure would do the most good. These statistics might be
equally accessible, as they would be equally useful, to both the
Nation and the States. In this way, and by these means, let the
nation take hold of the larger works, and the States the smaller
ones; and thus, working in a meeting direction, discreetly, but
steadily and firmly, what is made unequal in one place may be
equalized in another, extravagance avoided, and the whole
country put on that career of prosperity, which shall correspond
with its extent of territory, its natural resources, and the
intelligence and enterprise of its people.”

* * * * *

SPEECH ON THE PRESIDENCY AND GENERAL


POLITICS.
(Delivered in the House, July 27, 1848.)

GENERAL TAYLOR AND THE VETO POWER.

“Mr. Speaker:​—​Our Democratic friends seem to be in great


distress because they think our candidate for the Presidency
don’t suit us. Most of them can not find out that General Taylor
has any principles at all; some, however, have discovered that
he has one, but that that one is entirely wrong. This one
principle is his position on the veto power. The gentleman from
Tennessee (Mr. Stanton) who has just taken his seat, indeed,
has said there is very little if any difference on this question
between General Taylor and all the Presidents; and he seems to
think it sufficient detraction from General Taylor’s position on it,
that it has nothing new in it. But all others whom I have heard
speak assail it furiously. A new member from Kentucky (Mr.
Clarke) of very considerable ability, was in particular concern
about it. He thought it altogether novel and unprecedented for a
President, or a Presidential candidate, to think of approving bills
whose Constitutionality may not be entirely clear to his own
mind. He thinks the ark of our safety is gone, unless Presidents
shall always veto such bills as, in their judgment, may be of
doubtful Constitutionality. However clear Congress may be of
their authority to pass any particular act, the gentleman from
Kentucky thinks the President must veto it if he has doubts
about it. Now I have neither time nor inclination to argue with
the gentleman on the veto power as an original question; but I
wish to show that General Taylor, and not he, agrees with the
earliest statesmen on this question. When the bill chartering the
first Bank of the United States passed Congress, its
Constitutionality was questioned; Mr. Madison, then in the
House of Representatives, as well as others, had opposed it on
that ground. General Washington, as President, was called on to
approve or reject it. He sought and obtained, on the
Constitutional question, the separate written opinions of
Jefferson, Hamilton, and Edmund Randolph, they then being
respectively Secretary of State, Secretary of the Treasury, and
Attorney General. Hamilton’s opinion was for the power; while
Randolph’s and Jefferson’s were both against it. Mr. Jefferson, in
his letter dated February 15th, 1791, after giving his opinion
decidedly against the Constitutionality of that bill, closed with
the paragraph which I now read:
“‘It must be admitted, however, that unless the President’s
mind, on a view of every thing which is urged for and against
this bill, is tolerably clear that it is unauthorized by the
Constitution; if the pro and the con hang so even as to balance
his judgment, a just respect for the wisdom of the Legislature
would naturally decide the balance in favor of their opinion; it is
chiefly for cases where they are clearly misled by error,
ambition, or interest, that the Constitution has placed a check in
the negative of the President.’
“General Taylor’s opinion, as expressed in his Allison letter, is
as I now read:
“‘The power given by the veto is a high conservative power;
but, in my opinion, should never be exercised, except in cases
of clear violation of the Constitution, or manifest haste and want
of consideration by Congress.
“It is here seen that, in Mr. Jefferson’s opinion, if, on the
Constitutionality of any given bill, the President doubts, he is not
to veto it, as the gentleman from Kentucky would have him to
do, but is to defer to Congress and approve it. And if we
compare the opinions of Jefferson and Taylor, as expressed in
these paragraphs, we shall find them more exactly alike than we
can often find any two expressions having any literal difference.
None but interested fault-finders, can discover any substantial
variation.
“But gentlemen on the other side are unanimously agreed
that Gen. Taylor has no other principle. They are in utter
darkness as to his opinions on any of the questions of policy
which occupy the public attention. But is there any doubt as to
what he will do on the prominent question, if elected? Not the
least. It is not possible to know what he will or would do in
every imaginable case; because many questions have passed
away, and others doubtless will arise which none of us have yet
thought of; but on the prominent questions of currency, tariff,
internal improvements, and Wilmot proviso, General Taylor’s
course is at least as well defined as is General Cass’s. Why, in
their eagerness to get at General Taylor, several Democratic
members here have desired to know whether, in case of his
election, a bankrupt law is to be established. Can they tell us
General Cass’s opinion on this question? (Some member
answered, ‘He is against it.’) Aye, how do you know he is? There
is nothing about it in the platform, nor elsewhere, that I have
seen. If the gentleman knows any thing which I do not, he can
show it. But to return: General Taylor, in his Allison letter says:
“‘Upon the subject of the tariff, the currency, the
improvement of our great highways, rivers, lakes, and harbors,
the will of the people, as expressed through their
Representatives in Congress, ought to be respected and carried
out by the Executive.’
“Now, this is the whole matter​—​in substance, it is this: The
people say to General Taylor, ‘If you are elected shall we have a
National bank?’ He answers, ‘Your will, gentlemen, not mine.’
‘What about the tariff?’ ‘Say yourselves.’ ‘Shall our rivers and
harbors be improved?’ ‘Just as you please.’ ‘If you desire a bank,
an alteration of the tariff, internal improvements, any or all, I
will not hinder you; if you do not desire them, I will not attempt
to force them on you. Send up your members of Congress from
the various districts, with opinions according to your own, and if
they are for these measures, or any of them, I shall have
nothing to oppose; if they are not for them, I shall not, by any
appliances whatever, attempt to dragoon them into their
adoption.’ Now, can there be any difficulty in understanding
this? To you, Democrats, it may not seem like principle; but
surely you can not fail to perceive the position plain enough.
The distinction between it and the position of your candidate is
broad and obvious, and I admit you have a clear right to show it
is wrong, if you can; but you have no right to pretend you can
not see it at all. We see it, and to us it appears like principle,
and the best sort of principle at that​—​the principle of allowing
the people to do as they please with their own business. My
friend from Indiana (Mr. C. B. Smith) has aptly asked, ‘Are you
willing to trust the people?’ Some of you answered,
substantially, ‘We are willing to trust the people; but the
President is as much the representative of the people as
Congress.’ In a certain sense, and to a certain intent, he is the
representative of the people. He is elected by them, as well as
Congress is. But can he, in the nature of things, know the wants
of the people as well as three hundred other men coming from
all the various localities of the Nation? If so, where is the
propriety of having a Congress? That the Constitution gives the
President a negative on legislation, all know; but that this
negative should be so combined with platforms and other
appliances as to enable him, and, in fact, almost compel him, to
take the whole of legislation into his own hands, is what we
object to​—​is what General Taylor objects to​—a ​ nd is what
constitutes the broad distinction between you and us. To thus
transfer legislation is clearly to take it from those who
understand with minuteness the interests of the people, and
give it to one who does not and can not so well understand it. I
understand your idea, that if a Presidential candidate avow his
opinion upon a given question, or rather upon all questions, and
the people, with full knowledge of this, elect him, they thereby
distinctly approve all those opinions. This, though plausible, is a
most pernicious deception. By means of it measures are
adopted or rejected, contrary to the wishes of the whole of one
party, and often nearly half of the other. The process is this:
Three, four, or half a dozen questions are prominent at a given
time; the party selects its candidate, and he takes his position
on each of these questions. On all but one his positions have
already been indorsed at former elections, and his party fully
committed to them; but that one is new, and a large portion of
them are against it. But what are they to do? The whole are
strung together, and they must take all or reject all. They can
not take what they like and leave the rest. What they are
already committed to, being the majority, they shut their eyes
and gulp the whole. Next election, still another is introduced in
the same way. If we run our eyes along the line of the past, we
shall see that almost, if not quite, all the articles of the present
Democratic creed have been at first forced upon the party in
this very way. And just now, and just so, opposition to internal
improvements is to be established if Gen. Cass shall be elected.
Almost half the Democrats here are for improvements, but they
will vote for Cass, and if he succeeds, their votes will have aided
in closing the doors against improvements. Now, this is a
process which we think is wrong. We prefer a candidate who,
like Gen. Taylor, will allow the people to have their own way
regardless of his private opinion; and I should think the internal-
improvement Democrats at least, ought to prefer such a
candidate. He would force nothing on them which they don’t
want, and he would allow them to have improvements, which
their own candidate, if elected, will not.
“Mr. Speaker, I have said Gen. Taylor’s position is as well
defined as is that of Gen. Cass. In saying this, I admit I do not
certainly know what he would do on the Wilmot proviso. I am a
Northern man, or, rather, a Western free State man, with a
constituency I believe to be, and with personal feelings I know
to be, against the extension of slavery. As such, and with what
information I have, I hope, and believe, Gen. Taylor, if elected,
would not veto the proviso; but I do not know it. Yet, if I knew
he would, I still would vote for him. I should do so, because, in
my judgment, his election alone can defeat Gen. Cass; and
because, should slavery thereby go into the territory we now
have, just so much will certainly happen by the election of Cass;
and, in addition, a course of policy leading to new wars, new
acquisitions of territory, and still further extensions of slavery.
One of the two is to be President; which is preferable?
“But there is as much doubt of Cass on improvements as
there is of Taylor on the proviso. I have no doubt myself of Gen.
Cass on this question, but I know the Democrats differ among
themselves as to his position. My internal improvement
colleague (Mr. Wentworth) stated on this floor the other day,
that he was satisfied Cass was for improvements, because he
had voted for all the bills that he (Mr. W.) had. So far so good.
But Mr. Polk vetoed some of these very bills; the Baltimore
Convention passed a set of resolutions, among other things,
approving these vetoes, and Cass declares, in his letter
accepting the nomination, that he has carefully read these
resolutions, and that he adheres to them as firmly as he
approves them cordially. In other words, Gen. Cass voted for
the bills, and thinks the President did right to veto them; and his
friends here are amiable enough to consider him as being on
one side or the other, just as one or the other may correspond
with their own respective inclinations. My colleague admits that
the platform declares against the Constitutionality of a general
system of improvement, and that Gen. Cass indorses the
platform; but he still thinks Gen. Cass is in favor of some sort of
improvements. Well, what are they? As he is against general
objects, those he is for, must be particular and local. Now, this
is taking the subject precisely by the wrong end. Particularity​—​
expending the money of the whole people for an object which
will benefit only a portion of them, is the greatest real objection
to improvements, and has been so held by Gen. Jackson, Mr.
Polk, and all others, I believe, till now. But now, behold, the
objects most general, nearest free from this objection, are to be
rejected, while those most liable to it are to be embraced. To
return: I can not help believing that Gen. Cass, when he wrote
his letter of acceptance, well understood he was to be claimed
by the advocates of both sides of this question, and that he
then closed the door against all further expressions of opinion,
purposely to retain the benefits of that double position. His
subsequent equivocation at Cleveland, to my mind, proves such
to have been the case.
“One word more, and I shall have done with this branch of
the subject. You Democrats, and your candidate, in the main
are in favor of laying down, in advance, a platform​—a ​ set of
party positions, as a unit; and then of enforcing the people, by
every sort of appliance, to ratify them, however unpalatable
some of them may be. We, and our candidate, are in favor of
making Presidential elections and the legislation of the country
distinct matters; so that the people can elect whom they please,
and afterward legislate just as they please, without any
hindrance, save only so much as may guard against infractions
of the Constitution, undue haste, and want of consideration.
The difference between us is clear as noonday. That we are
right we can not doubt. We hold the true Republican position. In
leaving the people’s business in their hands we can not be
wrong. We are willing, and even anxious, to go to the people on
this issue.
“But I suppose I can not reasonably hope to convince you
that we have any principles. The most I can expect is, to assure
you that we think we have, and are quite contented with them.
The other day, one of the gentlemen from Georgia (Mr.
Iverson), an eloquent man, and a man of learning, so far as I
can judge, not being learned myself, came down upon us
astonishingly. He spoke in what the Baltimore American calls the
‘scathing and withering style.’ At the end of his second severe
flash I was struck blind, and found myself feeling with my
fingers for an assurance of my continued physical existence. A
little of the bone was left, and I gradually revived. He eulogized
Mr. Clay in high and beautiful terms, and then declared that we
had deserted all our principles, and had turned Henry Clay out,
like an old horse, to root. This is terribly severe. It can not be
answered by argument; at least, I can not so answer it. I
merely wish to ask the gentleman if the Whigs are the only
party he can think of, who sometimes turn old horses out to
root? Is not a certain Martin Van Buren an old horse which your
own party have turned out to root? and is he not rooting a little
to your discomfort about now? But in not nominating Mr. Clay,
we deserted our principles, you say. Ah! in what? Tell us, ye
men of principles what principle we violated? We say you did
violate principle in discarding Van Buren, and we can tell you
how. You violated the primary, the cardinal, the one great living
principle of all Democratic representative government​—​the
principle that the representative is bound to carry out the
known will of his constituents. A large majority of the Baltimore
Convention of 1844 were, by their constituents, instructed to
procure Van Buren’s nomination if they could. In violation, in
utter, glaring contempt of this, you rejected him​—​rejected him,
as the gentlemen from New York (Mr. Birdsall), the other day
expressly admitted, for availability​—​that same ‘general
availability’ which you charge upon us, and daily chew over
here, as something exceedingly odious and unprincipled. But
the gentleman from Georgia (Mr. Iverson), gave us a second
speech yesterday, all well considered and put down in writing, in
which Van Buren was scathed and withered a ‘few’ for his
present position and movements. I can not remember the
gentlemen’s precise language, but I do remember he put Van
Buren down, down, till he got him where he was finally to ‘stink’
and ‘rot.’
“Mr. Speaker, it is no business or inclination of mine to
defend Martin Van Buren. In the war of extermination now
waging between him and his old admirers, I say, devil take the
hindmost​—a ​ nd the foremost. But there is no mistaking the
origin of the breach; and if the curse of ‘stinking’ and ‘rotting’ is
to fall on the first and greatest violaters of principle in the
matter, I disinterestedly suggest, that the gentleman from
Georgia and his present co-workers are bound to take it upon
themselves.”

Mr. Lincoln then proceeded to speak of the objections against


Gen. Taylor as a mere military hero; retorting with effect, by citing
the attempt to make out a military record for Gen. Cass; and
referring, in a bantering way, to his own services in the Black Hawk
war, as already quoted. He then said:

“While I have Gen. Cass in hand, I wish to say a word about


his political principles. As a specimen, I take the record of his
progress on the Wilmot Proviso. In the Washington Union, of
March 2, 1847, there is a report of the speech of Gen. Cass,
made the day before in the Senate, on the Wilmot Proviso,
during the delivery of which, Mr. Miller, of New Jersey, is
reported to have interrupted him as follows, to wit:
“‘Mr. Miller expressed his great surprise at the change in the
sentiments of the Senator from Michigan, who had been
regarded as the great champion of freedom in the North-west of
which he was a distinguished ornament. Last year the Senator
from Michigan was understood to be decidedly in favor of the
Wilmot Proviso; and, as no reason had been stated for the
change, he (Mr. Miller) could not refrain from the expression of
his extreme surprise.’
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like