100% found this document useful (4 votes)
34 views

Brief Java Early Objects 9th Edition Cay Horstmann download pdf

The document provides information about the 'Brief Java Early Objects 9th Edition' by Cay Horstmann, including download links and details about the book's content and structure. It emphasizes the book's focus on teaching Java programming fundamentals, object-oriented design, and problem-solving strategies through a gradual and interactive approach. Additional resources and related ebooks are also mentioned for further exploration.

Uploaded by

selefikaite
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
100% found this document useful (4 votes)
34 views

Brief Java Early Objects 9th Edition Cay Horstmann download pdf

The document provides information about the 'Brief Java Early Objects 9th Edition' by Cay Horstmann, including download links and details about the book's content and structure. It emphasizes the book's focus on teaching Java programming fundamentals, object-oriented design, and problem-solving strategies through a gradual and interactive approach. Additional resources and related ebooks are also mentioned for further exploration.

Uploaded by

selefikaite
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/ 72

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Brief Java Early Objects 9th Edition Cay


Horstmann

_____ Click the link below to download _____


https://ebookultra.com/download/brief-java-early-
objects-9th-edition-cay-horstmann/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Java concepts 5th Edition Cay S. Horstmann

https://ebookultra.com/download/java-concepts-5th-edition-cay-s-
horstmann/

Java Concepts 5 Pap/Onl Edition Cay Horstmann

https://ebookultra.com/download/java-concepts-5-pap-onl-edition-cay-
horstmann/

Big Java Compatible with Java 5 6 and 7 4th Edition Cay S.


Horstmann

https://ebookultra.com/download/big-java-compatible-with-
java-5-6-and-7-4th-edition-cay-s-horstmann/

Python for Everyone 2nd Edition Cay Horstmann. Rance


Necaise

https://ebookultra.com/download/python-for-everyone-2nd-edition-cay-
horstmann-rance-necaise/
Java How to Program Early Objects 10th ed Edition Deitel

https://ebookultra.com/download/java-how-to-program-early-
objects-10th-ed-edition-deitel/

Starting Out with Java Early Objects 5th Edition Tony


Gaddis

https://ebookultra.com/download/starting-out-with-java-early-
objects-5th-edition-tony-gaddis/

Starting out with C Early objects 9th Global edition


Edition Gaddis

https://ebookultra.com/download/starting-out-with-c-early-objects-9th-
global-edition-edition-gaddis/

Starting Out with Java Early Objects 5 E 5th Edition Tony


Gaddis

https://ebookultra.com/download/starting-out-with-java-early-
objects-5-e-5th-edition-tony-gaddis/

Core Java Volume 1 Fundamentals 8th ed Edition Horstmann

https://ebookultra.com/download/core-java-volume-1-fundamentals-8th-
ed-edition-horstmann/
Brief Java Early Objects 9th Edition Cay Horstmann
Digital Instant Download
Author(s): Cay Horstmann
ISBN(s): 9781119499138, 1119499135
Edition: 9
File Details: PDF, 31.67 MB
Year: 2019
Language: english
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


Another Random Scribd Document
with Unrelated Content
[437] Bened. Paullinus Petrocorius, de vita B. Martini, IV vrss. 216
seurr., juttelee:

"Cum subito pavefacta metu, graviore periclo,


Auxilintores pateretur Gallia Chunos.
Nam socium quis ferre queat, qui durior hoste
Exstet et adnexum foedus feritate repellat?
220. Horam unus stimulis furiosi dæmonis actus
Irrupit sacram Domini, prædo improbus, ædem."

Rosvo, joka ryöstää Tours'in suojelus-pyhän temppeliä,


rangaistaan muka sokeudella, mutta annettuaan ryöstämänsä
takasin, saapi näkönsä jälleen. Gregorio Turonensi juttelee saman
ihme-työn, mutta hänen kirjassaan luetaan: "Thimus quidam", joka
epäilemättä on ymmärrettävä: "Chunus quidam." — Sidonius
Apollinaris, Panegyr. Avito Augusto socero, vrss. 246 seurr., kertoilee,
kuinka samat Hunni-joukot karkasivat Auvergne'n maakuntaan ja
kuiuka maan-asukkaat tekivät miehuullista vastarintaa:

"Litorius Scythicos equites tum forte, subacto


Celsus Aremorico, Geticum rapiebat in agmen
Per terras, Arverne, tuas: qui proxima quæque
Discursu, flammis, ferro, feritate, rapinis
250. Delebant, pacis fallentes nomen inane." —

Näiden joukkojen lopullista kohtaloa sodassa Länsi-göthejä


vastaan, mainitsee Idatii Chron. (vuodella 439): "Litorius Romanus
dux inconsultius cum auxiliari manu irruens, cæsis his, ipse
vulneratus capitur et post dies paucos occiditur"; vert. Jornand., de
reb. Get. 34.
[438] Aetion käytös-tapaa valaisee erinomaisen hyvin pari riviä
Prosper Tyronin kronikasta (vuodella 442): "Alani, quibus terræ
Galliæ ulterioris cum incolis dividendæ a patricio Aetio traditæ
fuerant, resistentes armis subigunt, et expulsis dominis terræ,
possessionem vi adipiscuntur."

[439] Ks. Zosimus, V 22; Philostorg. XI 8. — Tuo kapinallinen


kenraali oli Göthiläinen Gainas, joka yritti paeta Tonavan pohjois-
puolelle. Uldes panetti hänen päänsä suolaan, ja palkittiin rikkailla
lahjoilla.

[440] Ks. Sozomen. IX 5. — Useat Hunnilaiset ali-päälliköt


houkuteltiin menemään Roman palvelukseen, ja Uldes pelasti töin-
tuskin itsensä ja muun sota-joukkonsa takasin Tonavan yli,
kadottaen paljon väkeä, varsinkin Skirejä.

[441] Ks. Socrat. VII 43; Theodorit. V 36. — Mitä tämän retken
lopusta juttelevat, että muka salama tappoi Ruaan ja rutto hänen
väkensä, on perätöntä; sillä Ruas kuoli vasta 434 (ks. Prosp. Tyro,
Chron.).

[442] Ks. Fotion otteet Olympiodoron historiasta [Exc. de Legat.,


ed. Bonn., siv. 455]: — — "και όπως όρκω Δονάτος απατηθείς,
εκθέσμως αποσφάζεται και όπως Χαράτων ό των ρηγών πρώτος επί
τό φόνω εις θυμόν ανάπτεται, όπως τε πάλιν βασιλικοις δώροις
διαπραύνεται και ήσυγάζει."

[443] Ks. Romulon juttu Priskon historiassa [Exc. de Legat., ed.


Bonn., sivv. 199, 200]: — — "ουδε Ούννους απείρους τής οδού
ταύτης είναι, αλλά πάλαι ες αυτήν (την γήν τών Μήδων)
εμβεβληκέναι, λιμού τε την χώραν κρατήσαντος, και Ρωμαίων διά
τον τότε συνιστάμενον πόλεμον μη συμβαλλόντων παρεληλυθέναι δε
ες τηήν Μήδων τόν τε Βασίχ και Κουρσιχ τους ύστερον ες την Ρώμην
εληλυθότας εις ομαιχμίαν, άνδρας τών βασιλείων Σκυθών και πολλού
πλήθους άργoντας." — Lause: "Ρωμαίων — — — μη συμβαλλόντων",
on himmeä ja usein väärin ymmärretty. Bonnin painos kääntää
latinaksi: "cum Romani propter bellum, quod tunc temporis
gerebant, minime cum illis proelio decertarent." Tämä ei anna
mitään järjellistä käsitystä. Oikeammilla jäljillä on mielestäni Am.
Thierry (Hist. d'Attila, I siv. 110): — "sans qu'ils (les Huns) pussent
tirer des subsistances de l'empire Romain"; mutta kun hän lisää:
"parcequ'ils etaient en guerre avec lui", syntyy taas nähtävästi väärä
käsitys; sillä jos Hunnit olisivat sodassa olleet Roman kanssa,
olisihan heillä juuri paras syy ollutkin karata Roman alueesen, joko
Tonavan yli tai tuttua tietään Syriaan.

[444] Samatekkuin Germanilaiset Taciton aikana (ks. Tacit. Germ.


24), antautuivat Hunnitkin huimasti peliin. Niin kumminkin juttelee
Pyhä Ambrosio; ks. Liber de Thobia XI [S. Ambros. Op., Paris 1661,
II siv. 590]: "ferunt Hunnorum populos omnibus bellum inferre
nationibus, feneratoribus tamen esse subjectos, et cum sine legibus
vivant, aleæ solius legibus obedire, in procinctu ludere, tesseras
simul et arma portare, et plures suis quam hostilibus ictibus interire.
— — Ideo nunquam belli studia deponere, quod ricti aleæ ludo, cum
totius prædæ munus amiserint, ludendi subsidia requirunt bellandi
periculo." — Attilan esimerkistä näemme, että Hunneilla oli moni-
vaimoisuus; "innumerabiles uxores, ut mos erat gentis illius", sanoo
Jornandes, de reb. Get. 49. Sama tapa löytyy Taciton
Germaneillakin, ja vielä 6:nnen vuosis. lopulla ei ole monivaimoisuus
Anglo-saxeilta varsin kielletty; ks. Tacit. Germ. 18; Mignet, Mémoires
hist., 3:ème ed., siv. 21. Guizot'in arvelu, että Attila olisi nainut oman
tyttärensäkin (Hist. de la civilis. en France, III siv. 59), näyttää
perättömältä. Priskon sanat kuuluvat: "γαμείν θυγατέρα Εσκαμ
έβούλετο, πλείστας μεν έχων γαμετάς, αγόμενος δε και ταύτην κατά
νόμον τον Σκυθικόν",; ks. Exc. de Legat., siv. 183. Tämä epäilemättä
merkitsee, että hän nai "Eskamin tyttären", eikä "Eskam-nimisen
tyttärensä."

[445] Tosin Pyhä Hieronymo sanoo v. 398 paik.: "Hunni discunt


Psalterium, Scythiæ frigora fervent calore fidei"; ks. Epist. 57
(vanhojen painosten 7) [Opera omn., ed. Bened. IV II, siv. 591].
Mutta tämä nähtävästi ei ole muuta kuin puheen-kaunistusta. —
Kuin kirkko-historioitsija Sozomeno mainitsee näiltä aioin erään
pispan Tomissa, nimeltä Theotimo Skythes, "όν αγάμενοι της αρετής
οι περί τον ʹΙστρον Ούννοι βάρβαροι, θεόν Ρωμαίων ωνόμαζον", ja
juttelee, että hän nämä Hunnit, "φυσει θηριώδεις όντας, εις
ήμερότητα μετέβαλεν, εστιών τε και δώροις φιλοφρονούμενος", ei
nä'y tulleen kertojan mieleenkään, että näitä barbaria olisi ollut
mahdollinen kristin-uskoon käännyttää; ks. Sozom. VII 26. —
Hunnien omasta uskonnosta ei mitään puhuta. Epäilemättä se oli
Shamanisuutta eli loihto-uskoa. Jornandes sanoo, että Attila ennen
Châlons'in tappelua "statuit per haruspices futura inquirere. Qui
more solito nunc pecorum fibras, nunc quasdam venas in abrasis
ossibus intuentes, Hunnis infausta denunciant"; ks. de reb. Get. 37.

[446] Ks. Salvianus, de Gubernatione Dei, lib. IV: "Gens Saxonum


fera est, Francorum infidelis, Gepidarum inhumana et Hunnorum
impudica. Omnium denique gentium vita vitiosa. Sed numquid
eundem reatum habent illorum vitia quem nostra? numquid tam
vitiosa est Hunnorum impudicitia quam nostra? numquid tam
accusabilis Francorum perfidia quam nostra? aut tam reprehensabilis
ebrietas Alemanni quam ebrietas Christiani? — — Si fallat Hunnue
vel Gepida, quid mirum est? qui culpam falsitatis penitus ignorat. Si
perjuret Francus, quid ni faceret? qui perjurium ipsum sermonis
genus putat esse, non criminis"; — lib. VII: "Gothorum gens perfida,
sed pudica est; Alanorum impudica, sed minus perfida; Franci
mendaces, sed hospitales; Saxones efferi, sed castitate venerandi."

[447] Ks. Fotion otteet Olympiodoron historiasta [Exc. de Legat.,


ed. Bonn., siv. 455]: "'Οτι διαλαμβάνει περί Δονάτου, και περί τών
Ούννων, και περί τών ρηγών αυτών της ευφυεστάτης τοξείας" — —.
"Χαράτων ό τών ρηγών πρώτος." — Ρήξ käytetään samassa
merkityksessä knin latinainen sana: regulus.

[448] Ruas (Ρούας, Ρούγας) mainitaan jo v. 426; ks. Socrat. VII


43. — Uptar (Ούπταρος) nimitetään vasta kuollessansa v. 430; ks.
Socrat. VII 30. Hän on sama kuin Jornandeen "Octar", ja nimitetään
"Subthar" eräässä Attilan elämäkerrassa, minkä Dalmatialainen
Juveneus Coelius Calanus 11:nnellä vuosis. teki muinais-tarujen
mukaan. — Että olivat Attilan setiä, sanoo Jornandes, de reb. Get.
35: "Is namque Attila patre genitus Mundzucco, cuius fuere germani
Octar et Roas, qui ante Attilam regnum Hunnorum tenuisse
narrantur, quamvis non omnino cunctorum, quorum ipse." —
"Mundzuccus" on Jornandeen omituista kirjoitustapaa, samatekkuin
"Scania" ja "Burgunzones." Prisko [Exc. de Legat., siv. 150] kirjoittaa
Μουνδίoυχος. — Vielä neljäskin veljes Ωηβάρσιος mainitaan Priskon
historiassa (siv. 208); tämä eli Attilan hovissa vielä v. 448, mutta ei
lie koskaan hallitsijana ollut.

[449] Ks. Jornandes, de reb. Get. 35: "Bleda enim fratre fraudibus
perempto, qui magna parti regnabat Hunnorum, universum sibi
populum adunavit."

[450] Niinpä Alarik katsotaan: "ο των Γότθων φύλαρχος" (Exc. de


Legat., siv. 448); Thenderik Suuri: "ό των βαρβάρων αρχηγός" (Esc.
de Legat., siv. 234); Uldes: "ό την Ούννων έγων ήγεμονίαν" (Zosim.
V 22), eli: "ό ήγούμενος τών περί τον ʹΙστρον βαρβάρων" (Sozomen.
IX 5); Kharatoni: "ό τώτ ρηγών πρώτος" (Exc. de Legat., siv. 455);
Ruas: "ό έπαρχος" (Socrat. VII 43). Mutta jo Uptar nimitetään: "ό
βασιλεύς τών Ούννων" (Socrat. VII 30), ja Attilalle annetaan
ainoastaan tämmöinen arvonimi, joka asettaa hänen keisarin tasalle;
ks. esim. Friskon hist. [Exc. de Legat. siv. 141]: "Οτι επί Θεοδοσίου
του Μικρού βασιλέως Αττήλας ό τών Ούννων βασιλεύς τον οικείον
στρατόν άγείρας γράμματα πέμπει παρά τον βασιλέα." Mainittava
kuitenkin on, että Frisko antaa saman arvo-niinen myös Frankien ja
Akazirien kuninkaille; ks. Exc. de Legat., sivv. 152, 181.

[451] Nämä Prisko nimittää: "Αμιλζούροις και Ιτιμάροις και


Τονώσουρσι και Βοΐσκοις και έτέροις έθνεσι προσοικούσι τον
ʹIστρον"; Exc. de Legat., siv. 166. Ne ovat samoja, jotka Jornandes
mainitsee, puhuessaan Balamberin tulosta: "Nam mox ingentem
illam paludem transiere, illico Alipzuros, Alcidzuros, Itimaros,
Tuncassos et Boiscos, qui ripæ istius Scythiæ insidebant, quasi
quidam turbo gentium rapuere"; ks. Jornand., de reb. Get. 24.

[452] Prosper Tyronin kronikassa tosin luetaan (vuodella 434):


"Rugila rex Chunnorum, cum quo pax firmata, moritur; cui Bleda
succedit." Tämä saattaisi olla joku toinen rauhan-teko Länsi-Roman
kanssa. Mutta luultavampi on, että tarkoitetaan se sovinto, mikä nyt
tehtiin Itä-Roman kanssa, vaikka vasta Ruaan kuoltua.

[453] Ks. Prisc. Hist. [Exc. de Legat., ed. Bonn.], sivv. 167, 168.
Muutamat pakolaiset, jotka olivat kuninkaallista sukua, tulivat kohta
ristiin-naulituiksi.

[454] Ks. esim. Priskon historiassa [Exc. de Legat., sivv. 181, 182]
kertomus, kuinka Romalainen hallitus koetti vetää Akazirien eli
Katsarien heimokunnat puolellensa.
[455] Ks. Exc. de Legat., sivv. 141, 169. Ainoastaan Margon pispan
sovinnossa, siv. 140, mainitaan monikossa "οι τών Σκυθών βασιλείς."

[456] Ks. Prisc. Hist. [Exc, de Legat.] sivv. 140, 141, 169. —
Prosp. Aquit. Chron. mainitsee vuodella 442: "Chunis Thracias et
Illyricum saeva populatione vastantibus, exercitus, qui in Sicilia
morabatur, ad defensionem Orientalium provinciarum revertitur."

[457] Ks. Prosp. Tyr. Chron. (vuodella 445): "Thracia Hunnorum


incursione concutitur." — (vuodella 447) "Nova iterum Orienti
consurgit ruina" —.

[458] Ks. Exc. de Legat., ed. Bonn., siv. 142: "ταύτας


προσεποιούντο μεν εθελονται Ρωμαίοι τάς συνθήκας τίθεσθαι αναγχη
δε ύπερβάλλοντι δέει" — —.

[459] Ks. Exc. de Legat. siv. 146. — Toisinaan eivät lähettiläät


tytyneet tavallisiin lahjoihin, vaan tinkivät itsilleen Konstantinopolin
rikkaita naisia aviokseen, ja Attila valvoi tarkasti, että näitä lupauksia
heille täytettiin. Jos naitavat olivat vastahakoisia, lupasi Attila tulla
keisaria auttamaan, ellei muka keisari itse osaisi omia orjiansa
hallita. Ks. juttu Attilan käsikirjoittajasta Konstantiosta, Exc. de
Legat., sivv. 151, 208, 209, 213, 214.

[460] Ks. Exc. de Legat., ed. Bonn., sivv. 146-150, 169-212, 150,
151. Ranskannettuna löytyy tämä matka-kertomus Guizot'n
teoksessa: Histoire de la civilisation en France, III. Kerrottuna koko
laveudessaan tapaamme samat asiat Amedée Thierry'n kirjassa:
Histoire d'Attila et de ses successeurs, I sivv. 64 seurr.

[461] Niinpä esim. Onegesio, Attilan etevin neuvon-antaja, lausui:


"Luulevatko Romalaiset voivansa rukoilemalla minua siihen taivuttaa,
että herraani pettäisin, ja halveksien Hunnilaisen kasvatukseni sekä
vaimot ja lapset, en pitäisi parempana olla Attilan orjana kuin
pohattana Romalaisten luona." Ks. Exc. de Legat., siv. 196.

[462] Ks. esim. juttu Sirmion kirkon kulta-astioista; Exc. de Legat.,


siv. 186. — Aetion oli tapa toimittaa Attilalle kirja-miehiä, jotka
saattoivat häntä palvella käsi-kirjoittajina ja tulkkeina.

[463] Ks. Exe. de Legat., ed. Bonn., siv. 151-153; Jornand., de reb.
Get., 42.

[464] Ks. Chron. Paschale, ed. Bonn., siv. 587: "και εδήλωσεν διά
Γότθου ενός πρεσβευτού Ουαλεντινιανώ βασιλεί Ρώμης, Εκέλευσέ
σοι διʹ εμού ό δεσπότης μου και δεσπότης σου Αττίλας, ίνα
ευτρεπίσης αυτό παλάτιν, ομοίως δε και Θεοδοσίω βασιλεί τα αυτά
εν Κωνσταντινουπόλει εδήλωσεν διʹ ενός Γότθου πρεσβευτού" —
Joannis Malalæ; Chronogr., ed. Bonn., siv. 358, kertoo asian melkein
samoilla sanoilla, mutta käsky kuuluu vielä jäykemmältä: "ίνα
ευτρεπίσης αυτώ το παλάτιόν σου."

[465] Prisko, joka mainitsee Attilan punninneen mielessänsä,


kumpaseen keisarikuntaan hän ensin tekisi rynnäkkönsä, sanoo: "και
έχειν αυτώ έδόκεν καλώς τέως επί τον μείζονα τρέπεσθαι πόλεμον
και ες την έσπέραν στρατεύεσθαι" ks. Exc. de Legat., ed. Bonn., siv.
152.

[466] Ks. Jornand., de reb. Get 36; Exc. de Legat., siv. 152.

[467] Ks. Exc. de Leg., siv. 152.

[468] Tästä ja seuraavan vuoden retkistä, ks. Amedée Thierry'n


kuvallista kertomasta: Hist. d'Attila et de ses successeurs, 1 sivv. 128
seurr.

[469] Ks. Jornand., de reb. Get. 49: "placatus precibus, annuum


vectigal accepit."

[470] Ks. Jornand., de reb. Get., 43: "ad Orientis principem


Marcianum legatos dirigit provinciarum testans vastationem, quod
sibi promissum a Theodosio quondam imperatore minime
persolveret."

[471] Ks. Jornand., de reb. Get. 38: "Reliqua autem, si dici fas est,
turba regum diversarumque nationum ductores, ac si satellites,
nutibus Attilæ attendebant, et ubi oculo annuisset, absque aliqua
murmuratione cum timore et tremore unusquisque astabat, aut
certe, quod jussus fuerat, exsequebatur."

[472] Kun Sidonio Apollinari kertoilee Hunnilaisen Hormidakin


retkeä Tonavan etelä-rannalle v. 466, hän sen rinnalla halveksimalla
mainitsee edellistä Göthiläis-sotaa: — — "sed omittimus istos

Ut populatores; belli magis acta revolvo,


Quod bellum non parva manus, neque carcere fracto
Ad gladiaturam tu, Spartace vincte, parasti,
Sed Scyticæ vaga turba plagæ" — — —.

Ks. Panegyr. Authemio, vrss 235-239. — Kuinka Hunneja näinä


Attilan jälkeisinä aikoina otettiin Itä-Roman sota-palvelukseen,
kuinka siellä nousivat mahtaviin arvoihin, ja kuinka Konstantinopolin
keikkarit apinoitsivat heidän tapojansa ja vaate-parttansa, juttelee
Amedee Thierry, Hist. d'Attila, I sivv. 286 seurr.
[473] "Tu es flagellum Dei", mainitaan hänelle sanoneen
Gallialainen erakko päivänä ennen Châlons'in tappelua. — "En ego
malleus orbis!" antaa tarina hänen itse lausua. Ks. Am. Thierry, Hist.
d'Attila, II, sivv. 249, 251.

[474] Unkarin Tarinoista tässä kohden, ks. Am. Thierry, Hist.


d'Attila, II, sivv. 359 seurr.

[475] Ks. Jornand., de reb. Get. 50.

[476] Ks. Am. Thierry, Histoire d'Attiia, I sivv. 255 seurr.

[477] Prokopion Κουτούργουροι, Menandron Κοντρίγουροι,


Agathiaan Κοτρίγουροι, Theophaneen Κότραγοι.

[478] Prokopion Ουτούργουροι, Menandron ja Agathiaan


Ούτίγουροι.

[479] Utigurien hallitsija sanoo r. 558 Kutrigureista: "μήποτε


ομόγλωσσοί τέ εισι και ομόσκενοι ήμίν, κα ομοία χρώνται στολή και
διαίτα, αλλ' ότι και συγγενείς και έτέροις τισι τετάχαται ήγεμόσιν."
[non solum eadem nobiscum lingua et vivendi ratione utuntur, sed
etiam sunt nostri consanguinei, quamvis aliis ducibus parent]; ks.
Menandri hist. [Exc. de Legat., ed. Bonn.], siv. 345.

[480] Ks. Prisci Hist. [Exc. de Legat.] siv. 158; Jomand., de reb.
Get. 5.; Nimitön Ravennalainen sanoo: "juxta mare Ponticum patria,
quæ dicitur Onogoria, qaam subtilius Livanius Philosophus vicinam
paludis Mæotidæ summitatis esse decernit."

[481] Ks. Neumann, die Völker des südl. Russl., siv. 92.
[482] Theofanes kutsuu ne Bulgarit, jotka perustivat valtansa
etelä-puolella Tonavaa: "Ονογούνδουροι, Βούλγαροι και Κότραγοι";
ks. Chronogr., siv. 5-15. Konstantino Porfyrogenito sanoo heistä vain:
"πρότερον γαρ Ονογουνδούρους αυτούς εκάλονν".

[483] Ks. ylempänä sivv. 152-151.

[484] Ks. ylempänä siv. 145, ja vertaa siihen Theophan. Chronogr.,


ed. Bonn., siv. 339: "(οι Βούλγαροι) εσώκισαν αυτούς φεύγοντας —
—. ό μεν Γοδίλλας μετά του παραμηρίου αυτού κόψας τον σωκόν,
εξήλασεν, ό δε Κωνσταντίνος συν τώ Ακούμ συνελήφθησαν ζώντες."
Tämä oli v. 531.

[485] Jornandes, de reb. Get. 49, sanoo Attilan kuolemasta:


"Tunc, ut illius gentis mos est, crinium parte truncata informes facies
cavis turpavere vulneribus, ut proeliator eximius non femineis
lamentationibus et lacrimis, sed sanguine lugeretur virili." — Varsin
samaa kertoo Agathias, V 20, Zaberganin joukoista, kun Belisario oli
heidät lyönyt: "ξιφιδίοις τας παρειας καταξαίνοντες, ώλοφύροντο
κατά τον πάτριον νόμον."

[486] Ks. Exc. de Eeg., ed. Bonn., sivv. 158, 161. Avarit (Αβάρεις)
asuivat muka valtameren rannalla, josta tavattomat sumut ja suuri
Gripien paljous heidät karkoitti! — Akazirit kirjoitetaan tässä
Ακατίροι, Ακαττίροι.

[487] Näistä retkeistä ks. Am. Thierry, Hist. d'Attila, sivv. 306-393.

[488] Ks. Agathias V 12.

[489] Ks. Procop., Bell. Goth. IV 18; Menandri hist. [Exc. de Leg.],
sivv. 344, 345; Agathias V 25.
[490] Ks. K. Pr. Neumann, Die Völker des südl. Russl., 2:te Aufl.,
sivv. 86, 112. — Vertaa ylempänä siv. 141.

[491] Ks, Theophyl. Simoc. VII 7, ed. Bonn., siv. 282: "ό Χαγάνος
ό μέγας δεσπότης επτά γενών και κύριος κλιμάτων της οικουμένης
επτά."

[492] Ks. Theophyl. Simoo. VII 7, 8: "'Ογώρ", "Ουάρ και Χουννί";


"Ούτοι Αβάρους εαυτούς ονομάσαντες τον ήγεμόνα τή του Χαγάνου
προσηγορία φαιδρύνουσιν." Theofylakto itse nimittää heidät
Ψευδάβαροι, Suotta-avarit. Että tässä jutussa on perää, nähdään
Turkkilaisen Turxanthin lauseesta, jossa heitä nimitetään
Ούαρχωνίται ja mainitaan Turkkilaisten paenneiksi alamaisiksi; ks.
Menandri hist. [Exc. de Legat., ed. Bonn.], siv. 401. — Tbeofylakton
"Σαρσέλτ", jonka Nikeforo Kallista kirjoittaa "Βαρσέλτ", olen
ymmärtänyt Katsareiksi; ks. Vivien de Saint-Martin, Nouv. Annales
des Voyages, 1851, II sivv. 134-136. — Missä Til lienee, ei ilmoiteta.

[493] Ks. Menandri hist. [Exc. de Legat.], sivv. 282.

[494] Ks. Theophan. Chronogr., ed. Bonn., siv. 359: "είχον γαρ τας
κόμας όπισθεν μακράς πάνυ δεδεμένας πρανδίοις και πεπλεγμένας, ή
δε λοιπή φορεσία αυτών όμοία των λοιπών Ούννων."

[495] Ks. Menandri hist. [Exc. de Legat.], sivv. 282-287.

[496] Ks. Pauli. Diac., II 10: "comperta morte Chlotarii regis, Huni,
qui et Avares, super Sigisbertum ejus filium irruunt. Quibus ille in
Thuringia occurrens, eos juxta Albim fluvium potentissime superavit,
eisque petentibus pacem dedit. — Rursum Avares cum Sigisberto in
loco ubi et prius pugnantes, Francorum proterentes exercitum,
Victoriani sunt adepti." Vert. Greg. Turon. hist. IV 23 29; Menandri
hist., ed. Bonn., siv. 302.

[497] Ks. Menandri hist., siv. 299: "αμφί τας είκοσιν χιλιάδας."

[498] Ks. Theophyl. Simoc. VII 8: "οι Ταρνιάχ", "οι Κοτζαγηροί",


"οι Ζαβενδέρ." "ή δε γεγονυία επίθετος δύναμις τους Αβάροις εις
δέκα χιλιάδας ήκρίβωτο."
[499] Ks. Menandri hist. [Exc. de Legat.], siv. 401; vertaa sivv.
399, 404.

[500] Ks. Poeta Saxo [Pertz, Monum. I siv. 247].

[501] Ks. Zeuss, die Deutschen, siv. 739. — "Caganus et Jugurrus


principes Hunorum."

[502] "Πανάθεος χαγάνος" on Byzantiolaisilla tavallinen


sananparsi. Muutoin puhutaan Avarien taikuuksista: "magicis artibus
instructi, diversas phantasias ostendunt"; ks. Gregor. Turon. IV 29.
Erään loitsija-papin, Avarin kielellä "Bokolabra", mainitsee
Theofylakto (I 8).

[503] Ks. Menandri hist. [Exc. de Legat.], siv. 335: "τον επί του
ουρανού θεον πύρ"

[504] Avarien historiaa varten ks. Amedèe Thierry, Hist. d'Attila, II


siv. 3 seurr.; vertaa Zeuss, die Deutschen, sivv. 727-742. Mainittavin
kaikista heidän sota-retkistään on Konstantinopolin piiritys Heraklion
aikana v. 626.

[505] Ks. Fredegarii Chron. 48; Pauli. Diac. IV 40; Schlözer, Nestor,
II siv. 113; vertaa Schafarik, Slaw. Altherth., II siv. 59.

[506] Ks. Theophan. Chronogr., ed. Bonn., sivv. 485 seurr.: "οι
Χαζάροι", "οι Χαζάρεις." Arapialaisilla nimi kuului: "Khasar",
Slavilaisilla: "Kosar." — Että ovat samaa kuin entiset Akazirit todistaa
selvillä sanoilla Nimetön Ravennalainen [ed. Pinder et Parthey, siv.
168]: "quos Chazaros Iordanis (s.o. Jornandes) Agaziros vocat."

[507] Ks. ylempänä siv. 155.


[508] Ks. Schafarik, Slaw. Alterth., II sivv. 165 seurr. — Schlözer,
Nestor, II siv. 112.

[509] Ks. Zeuss, die Deutschen, siv. 726; D'Ohsson, des Peuples
du Caucase, siv. 217; Frähn, de Chazaris.

[510] Ks. Schafarik, Slaw. Alterth., II sivv. 63, 64.

[511] Ks. Theophan. Chronogr., ed. Bonn., sivv. 571, 575.

[512] Ks. Theophan. Chronogr., siv. 631: "Τούτω τώ έτει Λέων ό


βασιλεύς την θυγατέρα Χαγάνου του τών Σκυθών δυνάστου τώ υιώ
Κωνσταντίνω ενυμφεύσατο, ποιήσας αυτήν χριστιανήν, και
ονομάσας αυτήν Ειρήνην, ήτις εκμαθούσα τα ιερά γράμματα
διέπρεξεν εν ευσεβεία, ελέγχουσα την τούτων (Leonin ja
Konstantinon) δυσσέβειαν."

[513] Ks. Constant. Porphyr., De Admin. Imp., 13 (ed. Bonn. sivv.


86). Siinä kuitenkin sanotaan, että Leoni itse nai khakaanin tyttären.

[514] Ks. Constant. Porphyr., de Cærem., II 48: "Προς τον (ό


δείνα) εύγενέστατον, περιφανέστατον χαγάνoν Χαζαρίας."

[515] Ks. ylempänä siv. 157; Constant. Porphyr., de Adm. Imp. 42.

[516] Ks. Schlözer, Nestor, III siv. 154.

[517] Tabary mainitsee, että Hisham khalifin hallitessa (vv. 724-


743) Katsarien khakaani niin ahdistettiin, että hänen täytyi rauhaa
saadakseen mennä Muhammedin uskoon; ks. Dorn, Tabary's
Nachricht über die Chazaren [Mem. de l'Acad. de St. Pétersb., 6:ième
serie, VI], siv. 486; vertaa D'Ohsson, siv. 66.
[518] Semmoinen Siainen oli arvattavasti se Ziebel, joka yhtyi
keisari Heraklion kanssa v. 626: "οι Χαζάρεις — — συν τώ εαυτών
στρατηγώ Ζιεβήλ, δευτέρω όντι του Χαγάνου τή αξία", ks.
Theophan. Chronogr., siv. 486. — Constant. Porphyr., de Adm. Imp.
42, sanoo: "ό γαρ Χαγάνος εκείνος, ό και Πεχ Χαζαρίας —
ήτήσαντο".

[519] Ks. Neumann, die Völker des südl. Russl., siv. 89.

[520] Ks. Frähn, de Chasaris, excerpta ex scriptoribus Arabicis,


Petrop. 1822. [Mem. de l'Acad. de St. Pétersb. VIII, sivv. 577 seurr.];
— vertaa: D'Ohsson, sivv. 30 seurr., 190 seurr.; Nouv. Annales des
Voyages 1851, II sivv. 129 seurr., III siv. 5 seurr.; Neumann, sivv. 99
seurr.; vihdoinpa tämän kirjan sivv. 156, 157. — Etevimmät
Arabialaiset lähteet ovat: Ibn-Foszlau, joka vv. 921 ja 922 kävi
Muktadir khalifin lähettiläänä Bulgarien maassa; Abu-Ishak Faresi,
liika-nimellä Istakhri (s.o. Persepolilainen), joka v. 951 oli käynyt
Katsarien maassa; ja Ibn-Haukal, kauppamies Mosulista
loppupuolelta samaa vuosisataa. — Juutalainen Rabbi Khasdai oli
lääkärinä Andalusialaisen hallitsijan tykönä v. 958 paik. ja oli kuullut
hoettavan Juutalaisesta valtakunnasta pohjan seuduilla, jonka
tähden kirjoitti sinne kirjeen, saadaksensa tarkempia tietoja. Tämän
kirjeen ja Joseph kuninkaan vastauksen löysi eräs Juutalainen v.
1562 Levantista, ja julkaisi v. 1577 nimellä Kaul-Mubesser (iloinen
sanoma). Buxtorf, esipuheessaan kirjaan: Liber Cosri, Basel 1660,
painatti hebrealaisen tekstin ja latinaisen käännöksen.
Ranskannuksen antaa Carmoly, Récueil d'itineraires à la terre Sainte,
Bruxelles 1847, ja saksannuksen Selig Cassel, Magyarische Alterth.,
Berlin 1848. Kirjeensä alussa kuningas eli khakaani lausuu: "Tiedä,
että olemme Jafetin jälkeisiä ja lähteneet hänen poiastaan
Togarmasta." Togarmalla oli muka 10 poikaa: Aghior (Ugor?), Tiros,
Avir, Ughin, Bisal (Barsel?), Tarna, Kasar, Zanor, Balgad (? Bulgar),
Savir. Eräs kuningas, nimeltä Bulan, kääntyi ensin Moseksen uskoon;
hänen seuraajansa, joita luetellaan 12, kantavat kaikki Hebrealaisia
nimiä.

[521] Mahdollista on, että Kristinusko oli tullut Bulgarien sekaan jo


siihen aikaan, kun oleskelivat keisarikunnan rajoilla. Nikeforo
Patriarka mainitsee vuodella 618, kuinka heidän kuninkansa (ό τών
Ούννων του έθνους κύριος) ylimyksineen tuli Konstantinopoliin ja
siellä kastettiin.

[522] Ks. Frähn, Drei Münzen der Wolga-Bulgharen; ja Die


ältesten Arabischen Nachrichten über die Wolga-Bulgharen aus Ibn-
Foszlan's Reiseberichte [Mem. de l'Acad. de St. Pétersb., 6:ième
serie I]; D'Ohsson, sivv. 72 seurr. — Bulgar, joka oli noin 6 virstaa
Wolgan rannasta, arvataan olleen nykyisen Spask'in seuduilla, ei
kaukana Kaman suusta. — Mitä Ibn-Foszlan kertoo, että Bulgarit
hirttivät jokaisen, jolla erinomainen äly oli, koska muka semmoisen
piti paraiten kelvata itse Jumalalle palvelijaksi, on vaikeata
ymmärtää. Frähn arvelee, eikö siinä tarkoitettane tietäjiä ja noitia.

[523] Ks. ylempänä siv. 64.

[524] Ks. Frähn, Ibn-Foszlan und Anderer Berichte über die


Russen,
Pietarissa 1823; sekä Frähn, de Baschkiris [Mem. de l'Acad. de St.
Pétersb., 1822, VIII sivv. 621 seurr.]; D'Ohsson, des peuples du
Caucase, sivv. 81 seurr., 129 seurr.

[525] Että Bashkirit ja Unkarilaiset alkuperäänsä olivat yhtä


kansaa, seisoo niin monituisten todistusten nojassa, että epäilyksen
siaa ei ole: I. Unkarilaisten oma muinaistaru antaa heidän tulla
Dentumoger'ista, läheltä Bashkirien maata; "Scythicam regionem
una cingi comprehensione, sed in tria regna, Bostardiam
(Bascardiam) scilicet ac Dentiam et Magariam dividi", sanoo
Thwroczi. "Dentia et Magaria" on Belan Notarion "Dentumoger", ja
moger on sama kuin Magyar. — II. Selvemmän todistuksen antavat
13:nnen vuosis. matkustajat. Rubruk [Récueil de Voyages, IV, siv.
274] lausuu: "Postquam iveramus XII diebus ab Etilia (s.o. Wolga),
invenimus magnum flumen quod vocant Jagat (s.o. Jaik), et venit ab
aquilone de terra Paskatur (s.o. Bashkirien maa), descendeus in
prædictum mare. Ydioma Pascatur et Ungariorum idem est, et sunt
pastores sine civitate aliqua et contiguatur Majori Bulgarie ab
occidente. Ab illa terra versus orientem, in latere illo aquilonari, non
est amplius aliqua civitas. Unde Bulgaria Major est ultima regio
habens civitatem. De illa regione Pascatur exierunt Huni, qui postea
Hungari, unde est ipsa Major Bulgaria." Hän lisää [siv. 275]: "Hoc
quod dixi de terra Pascatur scio per fratres prædicatores, qui iverant
illuc ante adventum Tartarorum." — Carpini, Hist. Mongalorum
[Récueil de Voyages, IV siv. 677] sanoo: "Inde [e terra
Morduanorum Tartari] procedentes contra Bileros, id est Bulgariam
Magnam, et ipsam destruxerunt omnino. Inde procedentes ad
aquilonem adhuc contra Bascart, id est Hungariam Magnam, et eos
etiam devicerunt." — Muita yhtäläisiä todistuksia mainitaan samoilta
aioilta. Niinpä eräs käsikirjoitus Vatikanissa kertoo, että munkki
Juliano v. 1240 tapasi Wolgan tykönä kansan, joka vielä tiesi
Unkarilaisten muinoin heistä lähteneen, ja jonka kieli vielä oli varsin
Unkarilainen. Aeneas Sylvio taas kertoo, että eräs munkki Veronasta
oli tavannut, ei kaukana Tanaista, kansan, "jonka kieli oli sama kuin
Pannoniassa asuvaisten Hunkarilaisten." Bonfini'n mukaan oli
myöskin Mathias Korvino kauppamiehiltä kuullut, että niillä seuduin
löytyi hänen kansalaisiaan; hän aikoi kutsua ne Unkariin, mutta
kuoli. Lähetys-saarnaaja Joh. Schell kertoo, että eräs Jesuiitta,
Magyari synnyltään, joutui Turkkilaisten vangiksi ja myytiin orjaksi
Wolgan seuduille, josta Romaan kirjoitti joutuneensa oikeaan isäinsä
maahan, koska muka oli löytänyt muukalaisia, jotka puhuivat samaa
kieltä kuin Unkarissa puhutaan, ja joista silminnähtävästi Unkarilaiset
olivat lähteneet. — III. Vihdoin Arapialaiset antavat Unkarinkin
kansalle nimen Bashgurd, ja puhuvat selvästi kahdesta sen-nimisestä
kansasta; ks. D'Ohsson, des peuples du Caucase, sivv. 117 seur.,
257.

[526] Vertaa ylempänä siv. 154.

[527] Ne mainitaan kaikkein ensinnä keisari Theofilon aikana (vv.


829-842) Tonavan Bulgarien takana ja nimitetään silloin sekä
Ούγγροι, että Τούρκοι ja Ούννοι; ks. Leo Gramm., Chronogr., ed.
Bonn., sivv. 231, 232. — Vuodella 862 sanoo Hinkmar (Remens.
Annal.): "Hostes antea illis populis inexperti, qui Ungri vocantur,
regnum ejusdem (Saksan kuninkaan Lutvikin) populantur;" ks.
Pertz., Monum. Germ., I siv. 458.

[528] Ks. Constant. Porphyr., de Adm. Imp. 37. — Jaik kirjoitetaan


Γεήχ. — Yksi osa Unkarilaisia lohkesi muka itään päin ja asettui
Persian seuduille, luultavasti Kaukasoon. Eräästä Magyar-nimisestä
(vaikk'ei Magyarin-kielisestä) kansasta Kubanin laaksossa, ks. Besse,
Voyage au Caucase; vert. Amedée Thierry, Hist. d'Attila, II siv. 440
seurr.

[529] Ks. Constant. Porphyr., de Adm. Imp. 38-40. Näistä


heimokunnista yksi kantaa nimen Μεγέρη,, joka arvattavasti on sana
"Magyar." Notar. Belæ (c. 1) mainitsee seitsemän päämiestä, joista
Almus Arpadin isä on yksi, ja nimittää ne "Hetumoger" (seitsen-
magyarit).
[530] Ks. Constant. Porphyr., de Adm. Imp. 39: "όθεν και την τών
Χαζάρων γλώσσαν αυτοϊς τοϊς Τούρκοις (οι Καβαροι) εδίδαξαν, και
μέχρι τού νύν την αυτήν διάλεκτον έχουσιν έχουσι δε και την τών
Τούρκων έτέραν γλώτταν." Vaikea on sanoa, onko sana έχoυσι
ymmärrettävä Kabareista vai Unkarilaisista; pääjohto on, että
molemmat oppivat toistensa kieltä.

[531] Ks. Leo Gramm., Chronogr., ed. Bonn., sivv. 267, 268;
Constant. Forph., Adm. Imp. 40.

[532] Ks. Reginonis Chron. vuodella 889 [Pertz, Monum., I siv.


599]: "Pannoniorum et Avarum solitudines". Kuningas Alfredin
sanoilla aioin nimittää erämaaksi koko alan Karinthian ja Bulgarian
välillä.

[533] Ks. Constant. Porph., Adm. Imp. 38, 42 (sivv. 170, 177).

[534] Vielä v. 873 mainitaan Avarilais-jäänöksiä, jotka Saksan


kuninkaan veron-alaisina asuivat entisessä maassaan; ks. Zeuss, siv.
741. Zekelit Transsilvaniassa arvelee Unkarin muinais-taru Attilan
Hunnien jälkeisiksi: "Siculi, qui primo erant populi Athilæ regis"
(Notar. Belæ, 50). Nimi Székely merkitsee vain: rajavartia.

[535] Notar. Belæ (e. 57) sanoo: "de terra Bular venerunt quidam
nobilissimi domini cum magna multitudine Hismahelitarum, quorum
nomina fuerunt Billa et Bocsu. — — Et eodem tempore de eodem
regione venit quidam nobilissimus miles nomine Heten". Nimi
Hismaelitæ ilmoittaa, että olivat Muhammedin uskoa, ja todella
mainitaankin sen-uskoisia Unkarin lakiloissa. Arapialaisen Jakutin
kertomus 13:nnelta vuosisadalta antaa tähän vahvistusta [ks. Frähn,
de Bashkiris]: "ego vero offendi in urbe Haleb magno numero genus
hominum, qui Bashgurdi audiebant, crinibus et facie valde rubicundis
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like