Skip to main content

Full text of "Big Java Late Objects, 1st Edition"

See other formats


CAY HORSTMANN 


i ee 


‘Late Obiects 


























pe 
covowocenst CE ae 
soocvascnassssess PLUS FP resneewoneeee 
socceeveccssessssi 445 bE IIIS 


www.wileyplus.com 


WileyPLUS is a research-based online environment 
for effective teaching and learning. 


WileyPLUS builds students’ confidence because it takes the guesswork 
out of studying by providing students with a clear roadmap: 


¢ what to do 
e how to do it 
e if they did it right 


It offers interactive resources along with a complete digital textbook that help 
students learn more. With WileyPLUS, students take more initiative so you'll have 
greater impact on their achievement in the classroom and beyond. 





\nstructors 
Y LEARN use 


For more information, visit www.wileyplus.com 


WILEY nnees 


PLUS Beir iscszceccccosce 


www.wileyplus.com 








vy) \ \ \ \ ee 


ALL THE HELP, RESOURCES, AND PERSONAL 
SUPPORT YOU AND YOUR STUDENTS NEED! 
www.wileyplus.com/resources 








DAY AS SS TU S 
"9 Sano! PLUs 
ooo AND Student Partner Progra 
2-Minute Tutorials and all Student support from an Collaborate with your colleagues, 
of the resources you and your experienced student user find a mentor, attend virtual and live 
students need to get started events, and view resources 


www. WhereFacultyConnect.com 


PLI 
PLUS 





PLU ouickstart 
Pre-loaded, ready-to-use Technical Support 24/7 Your WileyPLUS Account Manager, 
assignments and presentations FAQs, online chat, providing personal training 
created by subject matter experts and phone support and support 


www. wileyplus.com/support 





CAY HORSTMANN 


San Jose State University 


WILEY 
John Wiley & Sons, Inc. 


VICE PRESIDENT AND EXECUTIVE PUBLISHER Don Fowley 





EXECUTIVE EDITOR Beth Lang Golub 
CONTENT MANAGER Kevin Holm 
SENIOR PRODUCTION EDITOR John Curley 
EXECUTIVE MARKETING MANAGER Christopher Ruel 
CREATIVE DIRECTOR Harry Nolan 
SENIOR DESIGNER Madelyn Lesure 
SENIOR PHOTO EDITOR Lisa Gee 
PRODUCT DESIGNER Thomas Kulesa 
CONTENT EDITOR Wendy Ashenberg 
EDITORIAL PROGRAM ASSISTANT Elizabeth Mills 
MEDIA SPECIALIST Lisa Sabatini 
PRODUCTION SERVICES Cindy Johnson 
COVER PHOTOS © Robbie Taylor/Alamy; 


© FLPA/John Holmes/Age Fotostock; 
© frans lemmens/Alamy 


This book was set in Stempel Garamond by Publishing Services, and printed and bound by R.R. Donnelley & 
Sons Company. The cover was printed by R.R. Donnelley & Sons, Jefferson City. 


This book is printed on acid-free paper. 2% 


Copyright © 2013, 2010 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be 
reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, 
photocopying, 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, Danvers, MA 01923, website 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, website www.wiley.com/go/permissions. 


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. Outside of the 
United States, please contact your local representative. 


Library of Congress Cataloging-in-Publication Data: 
Horstmann, Cay S., 1959- 
Big Java : late objects / Cay Horstmann. 
p.cm. 
Includes index. 
ISBN 978-1-118-08788-6 (pbk. : acid-free paper) 
1. Java (Computer program language) I. Title. 
QA76.73.J38H67 2012 
005.2'762--de23 
2011043315 


ISBN 978-1-118-08788-6 (Main Book) 
ISBN 978-1-118-12942-5 (Binder-Ready Version) 


Printed in the United States of America 


10987654321 





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: 


Present fundamentals first. 


The book takes a traditional route, first stressing control structures, methods, pro- 
cedural decomposition, and arrays. Objects are used when appropriate in the early 
chapters. Students start designing and implementing their own classes in Chapter 8. 


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. “Problem Solving” sections stress the 
importance of design and planning. “How To” guides help students with common 
programming tasks. Additional Worked Examples are available online. 


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. This book contains 
a substantial number of self-check questions at the end of each section. “Practice It” 
pointers suggest exercises to try after each section. And additional practice opportu- 
nities, including code completion questions, guided lab exercises, and skill-oriented 
multiple-choice questions are available online. 


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 prac- 
tices or language features when the reader is ready for the additional information. 
You will not find artificial over-simplifications that give an illusion of knowledge. 


vi Preface 


__ATourofthe Book 


This book is intended for a two-semester introduction to programming that may also 
include algorithms, data structures, and/or applications. 

The first seven chapters follow a traditional approach to basic programming 
concepts. Students learn about control structures, stepwise refinement, and arrays. 
Objects are used only for input/output and string processing. Input/output is cov- 
ered in Chapter 7, but Sections 7.1 and 7.2 can be covered with Chapter 4; in that way, 
students can practice writing loops that process text files. Chapter 4 also provides an 


Fundamentals 

SS} Object-Oriented Design 
mz Graphical User Interfaces 
PY) pata structures & Algorithms 
= Applied Topics 


@ Web / WileyPLUS 









Figure 1 
Chapter 
Dependencies 


Preface vii 


optional introduction to programming drawings that consist of lines, rectangles, and 
ovals, with an emphasis on reinforcing loops. 

After students have gained a solid foundation, they are ready to tackle the imple- 
mentation of classes in Chapter 8. Chapter 9 covers inheritance and interfaces. A 
simple methodology for object-oriented design is presented in Chapter 12. Object- 
oriented design may also be covered immediately after Chapter 9 by omitting the 
GUI versions of the sample programs. By the end of these chapters, students will be 
able to implement programs with multiple interacting classes. 

Graphical user interfaces are presented in Chapters 10 and 11. The first of these 
chapters enables students to write programs with buttons, text components, and sim- 
ple drawings. If you want to go deeper, you will find layout management and addi- 
tional user-interface components in the second chapter. 

Chapters 13-18 cover algorithms and data structures at a level suitable for begin- 
ning students. Recursion, in Chapter 13, starts with simple examples and progresses 
to meaningful applications that would be difficult to implement iteratively. Chapter 
14 covers quadratic sorting algorithms as well as merge sort, with an informal intro- 
duction to big-Oh notation. In Chapter 15, the Java Collections Framework is pre- 
sented from the perspective of a library user, without revealing the implementations 
of lists and maps. You can cover this chapter anytime after Chapter 8. In Chapters 16 
and 17, students learn how to implement linear and tree-based data structures, and 
how to analyze the efficiency of operations on these data structures. Finally, Chapter 
18 covers programming with Java generics. 

Chapters 19-24 feature applied topics: binary input/output, concurrent program- 
ming, networking, database programming, XML processing, and the development of 
web applications. Chapters 20-24 are available in electronic form on the Web and in 
WileyPLUS. 

Any subset of these chapters can be incorporated into a custom print version of 
this text; ask your Wiley sales representative for details. 


Problem Solving Strategies 


This book provides practical, step-by-step illustrations of techniques that can 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: 


e Algorithm Design (with pseudocode) ¢ Adapting Algorithms 
e First Do It By Hand (doing sample e Discovering Algorithms by 


calculations by hand) Manipulating Physical Objects 
e Flowcharts e Tracing Objects (identifying state and 
e Test Cases behavior) 
¢ Hand-Tracing e Patterns for Object Data 
¢ Storyboards e Thinking Recursively 
e Reusable Methods e Estimating the Running Time of an 
Algorithm 


e Stepwise Refinement 


Optional Science and Business Exercises 


End-of-chapter exercises include problems from scientific and business domains. 
Designed to engage students, the exercises illustrate the value of programming in 


applied fields. 


viii Preface 


Appendices 


Many instructors find it highly beneficial to require a consistent style for all assign- 
ments. If the style guide in Appendix L conflicts with instructor sentiment or local 


customs, however, it is available in electronic form so that it can be modified. 


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 Syntax Summary 

F. HTML Summary 

G. Tool Summary 

H. Javadoc Summary 

|. Number Systems 

J. Bit and Shift Operations 

K. UML Summary 

L. Java Language Coding Guidelines 


Web Resources 


This book is complemented by a complete suite of online resources and a robust 
WileyPLUS course. Go to ww.wiley.com/college/horstmann to visit the online compan- 


ion sites, which include 


¢ Source code for all example programs in the book and in online examples. 


e¢ Worked Examples that apply the problem-solving steps in the book to other 


realistic examples. 


e Video Examples in which the author explains the steps he is taking and shows his 


work as he solves a programming problem. 


e Lab exercises that apply chapter concepts (with solutions for instructors only). 


e Lecture presentation slides (in PowerPoint format). 


¢ Solutions to all review and programming exercises (for instructors only). 


e A test bank that focuses on skills, not just terminology (for instructors only). 


WileyPLUS 


WileyPLUS is an online teaching and learning environment that integrates the digital 


textbook with instructor and student resources. See pages xiii—xiv for details. 










VIDEO EXAMPLE 4.2 Drawing a Spiral 


(sate In this Video Example, you will see how to develop a program 
LUS that draws a spiral. 


te UY? 










Pointers in the book 
describe what students 
will find on the Web. 












ONLINE EXAMPLE 

@ Aprogram using 
common loop 

algorithms. 







Walkthrough ix 


4 Walktl oti! Pore 


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. 









4.2 The forLoop 135 


Throughout each chapter, 
. i It often happens that you want to execute a sequence of statements a given number 
The for | PP! y' q 8) 
marg In notes s h OW W h ene ised whens " of times. You can use awhile loop that is controlled by a counter, as in the following 





. value runs from a : 
new concepts are introduced saree tal _ 

: ‘ : ending point with a int counter = 1; // Initialize the counter 
and provide an outline of key ideas. onsianuiccramant aie (counter <= 10) // Check the counter 


System. out.printIn(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 4.2). 


for (int counter = 1; counter <= 10; counter++) 
{ 


Additional online example code 
provides complete programs for 
students to run and modify. 


System. out.printn(counter) ; 










GN EIN ETE AMEE Some people call this loop count-controlled. In con- 
QVanosanicing trast, the white loop of the preceding section can be 
common loop called an event-controlled loop because it executes 
algorithms. 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 definite number of times; ten times in our exam- 
ple. In contrast, you do not know how many itera- 
tions it takes to accumulate a target balance. Such a You can visualize the for loop as 

loop is called indefinite. an orderly sequence of steps. 














Annotated syntax boxes 
provide a quick, visual overview 
of new language constructs. 






Syntax 4.2 for Statement 






Syntax for (initialization; condition; update) 
{ 
Statements 


These three 
expressions should be related. 


2 See page 163. 





Annotations explain required oe, ws A 
components and point to more aie. nearer panleeghi 


before the loop starts. each iteration. each iteration. 


information on common errors 
or best practices associated Be Ue Petre 


j The variable 7 is sum = sum + ij This I 6 times, 
with the syntax. Garaicieren + roe 


See page 161. 

























Analogies to everyday objects are 
used to explain the nature and behavior 
of concepts such as variables, data 

types, loops, and more. 


% 







Like a variable in a computer - 
program, a parking space has : ly 
an identifier and a contents. i 












x Walkthrough 





Memorable photos reinforce 
analogies and help students 


remember the concepts. 








pie(fruit) s pie(fruit) 


A recipe for a fruit pie may say to use any kind of fruit. 
Here, “fruit” is an example of a parameter variable. 
Apples and cherries are examples of arguments. 














Problem Solving sections teach 
techniques for generating ideas and 
evaluating proposed solutions, often 
using pencil and paper or other 


artifacts. These sections emphasize 
that most of the planning and problem 
solving that makes students successful 
happens away from the computer. 








6.5 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 


277 


Now how does that help us with our problem, switching the first and the second 
half of the array? 

Let’s put the first coin into place, by swapping it with the fifth coin. However, as 
Java programmers, we will say that we swap the coins in positions 0 and 4: 


@ | _ 
{ 


*, 


@ee0@ e@ee 


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















HOW TO 1.1 Describing an Algorithm with Pseudocode 


pseudocode: a sequence of precise steps formulated in English. 

For example, consider this problem: You have the choice of 
buying two cars. One is more fuel efficient than the other, but 
also more expensive. You know the price and fuel efficiency (in 
miles per gallon, mpg) of both cars. You plan to keep the car for 
ten years. Assume a price of $4 per gallon of gas and usage of 
15,000 miles per year. You will pay cash for the car and not 
worry about financing costs. Which car is the better deal? 


Step 1 Determine the inputs and outputs. 


In our sample problem, we have these inputs: 


This is the first of many “How To” sections in this book that give you step-by-step proce- 
dures for carrying out important tasks in developing computer programs. 

Before you are ready to write a program in Java, you need to develop an algorithm—a 
method for arriving at a solution for a particular problem. Describe the algorithm in 






















How To guides give step-by-step 
guidance for common programming 
tasks, emphasizing planning and 
testing. They answer the beginner's 
question, “Now what do | do?” and 
integrate key concepts into a 
problem-solving sequence. 


© purchase price! and fuel efficieney1, the price and fuel efficiency (in mpg) of the first car 
© purehase priceZ and fuel efficiency2, the price and fuel efficiency of the second car 
We simply want to know which car is the better buy. That is the desired output. 






Worked Examples and 
Video Examples apply the 


















WORKED EXAMPLE 1.1 






Writing an Algorithm for Tiling a Floor 






o 


This Worked Example shows how to develop an algorithm for laying 
tile in an alternating pattern of colors. 





int cans = 6; 


© otttes = 1; 


‘int bottles; 





Variable Name 


‘int total = cans + bottles; 


© int botttes = "10"; 


‘int cans, bottles; 


Table 1 Variable Declarations in Java 


Comment 
Declares an integer variable and initializes it with 6. 


The initial value need not be a constant. (Of course, cans and bottles 
must have been previously declared.) 


Error: The type is missing. This statement is not a declaration but an 
assignment of a new value to an existing variable—see Section 2.1.4. 


Error: You cannot initialize a number with a string. 


Declares an integer variable without initializing it. This can be a 
cause for errors—see Common Error 2.1 on page 37. 


Declares two integer variables in a single statement. In this book, we 
will declare each variable in a separate statement. 















steps in the How To toa 
different example, showing 
how they can be used to 
plan, implement, and test 
a solution to another 
programming problem. 






Example tables support beginners 
with multiple, concrete examples. 
These tables point out common 


errors and present another quick 
reference to the section’s topic. 





Walkthrough xi 





Figure 3 


ee @ Initialize counter Gas int counter = 1; counter <= 10; counter++) Prog ressive figures trace code 
segments to help students visualize 
the program flow. Color is used 


System. out.printIn(counter) ; 
t 





© Check condition Besar =a anise =D ence consistently to make variables and 


py pieacg nema other elements easily recognizable. 





for (int counter = 1; counter <= 10; counter++) 





{ 
System. out.printn(counter) ; @ Method call 
ai 
double result = cubeVolume(2); 
© Update counter for Cint counter = 1; counter <= 10; counter++) 
a 


Vcounter= 2 a pystam-OUe Pui inCcounten): @ Initializing method parameter variable 


double result1 = cubeVolume(2); 


© Check condition again for Cint counter = 1; counter <= 10; counter++) 
{ 


System. out.print1n(counter) ; © About to return to the caller 














double volume = sideLength * sideLength * sideLength; 
return volume; 





© After method call 
double resultl = cubeVolume(2); 





Figure 3 Parameter Passing 
Students can view animations 
of key concepts on the Web. 


© The parameter variable sideLength of the cubeVolume method is created when the 
method is called. @ 
¢ The parameter variable is initialized with the value of the argument that was 
Onn! fam passed in the call. In our case, sideLength is set to 2. @ 
Parameter Passing» ‘The method computes the expression sideLength * sideLength * sideLength, which 


| t \ has the value 8. That value is stored in the variable volume. @ 
‘ 





¢ The method returns. All of its variables are removed. The return value is trans- 
ferred to the caller, that is, the method calling the cubeVolume method. The caller 
puts the return value in the result1 variable. @ 





Self-check exercises at the 

end of each section are designed 7. How many numbers does this loop print? 

to make students think through for Cine n= 10; n> 0; &-) 

the new material—and can ,_Svstet-out.println(ns 

spark discussion in lectu Sa 8. Write a for loop that prints all even numbers between 10 and 20 (inclusive). 


9, Write a for loop that computes the sum of the integers from 1 to n. 


6. Write the for loop of the InvestmentTable. java program as a while loop. 


10. How would you modify the for loop of the InvestmentTable. java program to 
print all balances until the investment has doubled? 








O pt i ona | science and bu Ss i hess == Science P6.32 Sounds can be represented by an array of “sample 








. 5 values” that describe the intensity of the sound at a 
exercises en g ag e stu d ents wit h point in time. The program ch06/sound/Soundeffect. 
Se 5 a java reads a sound file (in WAV format), calls a 
realistic applications of Java. method process for processing the sample values, and 





saves the sound file. Your task is to implement the 
process method by introducing an echo. For each 





























== Business P9.21 Implementa superclass Appointment and sub- 
» a classes Onetime, Daily, and Monthly. An appoint- 

Section-1/Doubleinvestmentjava ment has a description (for example, “see the 

NR A ‘ 5 dentist”) and a date and time. Write a method 

2 This program computes the time required to double an investment. occursOn(int year, int month, int day) that checks 

el af i : 

ramus cletase inoue letnvercnent whether the appointment occurs on that date. 

a8 For example, for a monthly appointment, you 

6 public static void main(String[] args) must check whether the day of the month 2 

z { asta matches. Then fill an array of Appointment objects 7 

inal double RATE = 5; ‘ . F : ree 

ie Final. double: INITIAL, BALANCE: = 10000; witha mirrare of appointments. Have the user enter a date and print out all appoint: 

0 final double TARGET = 2 * INITIAL_BALANCE; ments that occur on that date. 

1 








double balance = INITIAL_BALANCE; 
int year = 0; 


// Count the years required for the investment to double 


Program listings are carefully 


while (balance < TARGET) 


{ designed for easy reading, 
oe ; ; 
Die faite siete going well beyond simple 

} color coding. Methods are set 


System.out.printIn("The investment doubled after 
+ year +" years.")j 


off by a subtle outline. 

















Walkthrough 









Common Error 6.4 


Common Errors describe the kinds 
of errors that students often make, 
with an explanation of why the errors 
occur, and what to do about them. 






Length and Size 


Unfortunately, the Java syntax for 
determining the number of elements 
in an array, an array list, and a string 
is not at all consistent. It is a com- 
mon error to confuse these. You just 
have to remember the correct syntax 


Data Type Number of Elements 
Array a.length 

Array list a.size() 
String a. length() 






for every data type. 





Lace] 














Programming Tips explain 
good programming practices, 
and encourage students to be 
more productive with tips and 
techniques such as hand-tracing. 





Hand-Tracing 


A very useful technique for understanding whether a pro- 
gram works correctly is called hand-tracing. You simulate 
the program’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 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 the current statement. In your mind, 
execute statements one at a time. Every time the value of a 
variable changes, cross out the old value and write the new 
value below the old one. 

For example, let’s trace the tax program with the data 
fromtheprogramrunon page 102. Inlines 15 and 16,taxland 
tax2 are initialized to 0. 


8 public static void main(String[] args) 
of 


10 final double RATE1 = 0.10; 
11 final double RATE2 = 0.25; 
12 final double RATE1 SINGLE LIMIT = 32000; 
13. final double RATE1_MARRIED_LINIT = 64000; 











Hand-tracing helps you 
understand whether a 
program works correctly. 








15 double tax’ 
16 — double taxi 





In lines 22 and 25, income and maritalStatus are 
initialized by input statements. 
20 — Scanner in = new Scanner (System.in); 


21 System.out.print("Please enter your income: 
22 double income = in.nextDouble(); 





24 — Systen.out.print("Please enter s for single, m for married 
String maritalStatus = in.next(); 













































Special Topics present optional 
topics and provide additional 
explanation of others. New 
features of Java 7 are also 
covered in these notes. 


o 


Special Topic 7.2 


File Dialog Boxes 


ONLINE EXAMPLE 
A program that 
demonstrates how to 
use a file chooser. 





Ina 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 
IFileChooser 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 
most basic form it is quite simple: Construct a file chooser object; then call the show0penDialog 
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 nu11. The show0penDialog 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(nul1) == JFileChooser.APPROVE_OPTION) 
{ 
File selectedFile = chooser.getSelectedFileQ; 
in = new Scanner(selectedFile); 


} 
Open x 
Call with 
show0penDialog Look Ine (Capi | (ca) (ss) (co) [ee ]e- 
method —————— 
[5 index-tites [) allctasses-noframe.tumt [) overview-summe 
Oywa [) constant-values.numt —[") overview-tree.tiu 
Cjavax D deprecated-tistnumt —_) package-tist 
Gorn [) netp-docnumt D) sertatizea- forma 


(resources 1 indexes 0) stytesneeness 


f a x ates fienene heend 














Random Facts provide historical and 
social information on computing—for 
interest and to fulfill the “historical and 


social context” requirements of the 
ACM/IEEE curriculum guidelines. 











Random Fact 4.1 The First Bug 


According to legend, 
the first bug was 
found in the Mark II, a huge electrome- 
chanical computer at Harvard Univer- 
sity. It really was caused by a bug—a 
moth was trapped in a relay switch. 
Actually, from the note that the 
operator left in the log book next to 
the moth (see the figure), it appears as 
if the term “bug” had already been in 
active use at the time. 


The First Bug 


The pioneering computer scientist 
Maurice Wilkes wrote, “Somehow, at 
the Moore School and afterwards, one 
had always assumed there would be 
no particular difficulty in getting pro- 





grams right. | can remember the exact 
instant in time at which it dawned on 
me that a great part of my future life 
would be spent finding mistakes in 
my own programs.” 





Thee (Sine <hexhl 











Walkthrough xiii 


WileyPL 


WileyPLUS is an online environment that supports students and instructors. This 
book’s WileyPLUS course can complement the printed text or replace it altogether. 


For Students 


Different learning styles, different levels of proficiency, different levels of prepara- 
tion—each student is unique. Wiley PLUS empowers all students to take advantage 
of their individual strengths. 


Integrated, multi-media resources— including audio and visual exhibits and demon- 
stration problems — encourage active learning and provide multiple study paths to 
fit each student’s learning preferences. 


¢ Worked Examples apply the problem-solving steps in the book to another realis- 
tic example. 


e Video Examples present the author explaining the steps he is taking and showing 
his work as he solves a programming problem. 


e Animations of key concepts allow students to replay dynamic explanations that 
instructors usually provide on a whiteboard. 


Self-assessments are linked to relevant portions of the text. Students can take control 
of their own learning and practice until they master the material. 

e Practice quizzes can reveal areas where students need to focus. 

e “Learn by doing” lab exercises can be assigned for self-study or for use in the lab. 


¢ “Code completion” questions enable students to practice programming skills by 
filling in small code snippets and getting immediate feedback. 


For Instructors 


WileyPLUS includes all of the instructor resources found on the companion site, 
and more. 

WileyPLUS gives you tools for identifying those students who are falling behind, 
allowing you to intervene accordingly, without having to wait for them to come to 
office hours. 


e Practice quizzes for pre-reading assessment, self-quizzing, or additional practice 
can be used as-is or modified for your course needs. 


e Multi-step laboratory exercises can be used in lab or assigned for extra student 
practice. 


WileyPLUS simplifies and automates student performance assessment, making 
assignments, and scoring student work. 


e Anextensive set of multiple-choice questions for quizzing and testing have been 
developed to focus on skills, not just terminology. 

e “Code completion” questions can also be added to online quizzes. 

¢ Solutions to all review and programming exercises are provided. 


To order Big Java, Late Objects, with its WileyPLUS course for your students, use ISBN 978-1-118-28906-8. 


xiv Walkthrough 


With WileyPLUS ... 


and cross-linking. 


Instructors can assign drill-and-practice 
questions to check that students did 


their reading and grasp basic concepts. 








Test Bank (Web) 7.107 What is the Error in this Array Code Fragment? 


What is the error in this code fragment? 





Out-of-bounds error 













Students can read the book online 
and take advantage of searching 





WileyPLUS 


highestvalue = nextvalue; 
RighestHenth = currentHenth. 
} 


} 
Systen.cut .printin(highestnoath); 


ow 


21 What total is computed when no user input is provided in the algorithm in Section 45.1? 






22 How do you compute the total of all positive inputs? 
23. What are the values of position and ch when 00 match it found in the algerithen in Section 4.5.57 ¢ 
24 What is wrong with the following loop for finding the fies lowercase character in a sing? 






boolean found = false; 
fez (int position = 0; !found 66 position < str.length(); positiont+) 

















date not initislized 
A two-dimensional array ts required 


A castis required 


Question Attempts: 0 of 1 used 












Students can practice programming 
by filling in small code snippets 
and getting immediate feedback. 





‘Animation: Tracing a Loop 


int i«#1; 
ints = 0; 
while (i <= 10) 















@ WileyPius LabRat 





Configure Java 





Students can play and replay 
dynamic explanations of 
concepts and program flow. 




















| ch04.flv 








Computes @ sum of even integers 

@peram a the lower bound (may be odd or even) 

@param a the lower bound (may be odd or even) 

@return the sum of even mntegers between a and b (inclusive). 
. 


public int evenSurn{int a, int b) 








Development Kit a ee a 

Instructions Displayed below is the partial code required for this problem. Complete the code to make a fully functioning 

View Problem program that will solve this problem by editing directly in the text box below. When you are finished, you may click 
View/Edit Code “Next” and LebRet will compile and run your code and generate @ preliminary grade report. O la) ty) 

Cheek Your Work - ka 

View Report public dass Numbers 3) 

‘Submit To Gradebook . 

Finish 







Drawing a Spiral 


J| Write a program that draws a spiral. like this: 


(x22) 








_-{- (xy) 


Start with this class. Do not look at the nain method—it contains code to show a window. Place your code in 
Une row rmethod, You unly rwed ty knww cow drawing cunmmand, The call 














Students can watch and listen as the author 
solves a problem step-by-step. 


[Wie drowned, Whe a2 2h 












Graves a fw from (x2, x2) to (y1, y2). 


Star at (aL, y2) = (100, 200), Thre first Cwrw linne sergerowenits otruuld bee Lene palantts ary. Oram 40 seeyermenits, 











Acknowledgments xv 


Acknowledgments 


Many thanks to Beth Lang Golub, Don Fowley, Elizabeth Mills, Thomas Kulesa, 
Wendy Ashenberg, Lisa Gee, Andre Legaspi, Kevin Holm, and John Curley at John 
Wiley & Sons, and Vickie Piercey at Publishing Services for their help with this proj- 
ect. An especially deep acknowledgment and thanks goes to Cindy Johnson for her 
hard work, sound judgment, and amazing attention to detail. 

I am grateful to Jose Cordova, University of Louisiana, Monroe, Rick Giles, Aca- 
dia University, Amitava Karmaker, University of Wisconsin, Stout, Khaled Mansour, 
Washtenaw Community College, Patricia McDermott-Wells, Florida International 
University, Brent Seales, University of Kentucky, Donald Smith, Columbia College, 
and David Woolbright, Columbus State University, for their excellent work on the 
supplemental material. Thank you also to Jose-Arturo Mora-Soto, Jesica Rivero- 
Espinosa, and Julio-Angel Cano-Romero of the University of Madrid for their con- 
tribution of business exercises. 

Many thanks to the individuals who provided feedback, reviewed the manuscript, 
made valuable suggestions, and brought errors and omissions to my attention. They 


include: 


Lynn Aaron, SUNY Rockland 
Community College 

Karen Arlien, Bismarck State College 

Jay Asundi, University of Texas, Dallas 

Eugene Backlin, DePaul University 

William C. Barge, Trine University 

Bruce J. Barton, Suffolk County 
Community College 

Sanjiv K. Bhatia, University of Missouri, 
St. Louis 

Anna Bieszczad, California State 
University, Channel Islands 

Jackie Bird, Northwestern University 

Eric Bishop, Northland Pioneer College 

Paul Bladek, Edmonds Community 
College 

Paul Logasa Bogen II, Texas AEM 
University 

Irene Bruno, George Mason University 

Paolo Bucci, Ohio State University 

Joe Burgin, College of Southern 
Maryland 

Robert P. Burton, Brigham Young 
University 

Leonello Calabresi, University of 
Maryland University College 


Martine Ceberio, University of Texas, 
El Paso 


Uday Chakraborty, University of 
Missouri, St. Louis 

Suchindran Chatterjee, Arizona State 
University 

Xuemin Chen, Texas Southern 
University 

Haiyan Cheng, Willamette University 

Chakib Chraibi, Barry University 

Ta-Tao Chuang, Gonzaga University 

Vincent Cicirello, Richard Stockton 
College 

Mark Clement, Brigham Young 
University 

Gerald Cohen, St. Joseph’s College 

Ralph Conrad, San Antonio College 

Dave Cook, Stephen E Austin State 
University 

Rebecca Crellin, Community College 
of Allegheny County 

Leslie Damon, Vermont Technical 
College 

Geoffrey D. Decker, Northern Illinois 
University 

Khaled Deeb, Barry University, School 
of Adult and Continuing Education 

Akshaye Dhawan, Ursinus College 

Julius Dichter, University of Bridgeport 

Mike Domaratzki, University of 
Manitoba 


Acknowledgments 


Philip Dorin, Loyola Marymount 
University 

Anthony J. Dos Reis, SUNY New Paltz 

Elizabeth Drake, Santa Fe College 

Tom Duffy, Norwalk Community 
College 

Michael Eckmann, Skidmore College 

Sander Eller, California State 
Polytechnic University, Pomona 

Amita Engineer, Valencia Community 
College 

Dave Evans, Pasadena Community 
College 

James Factor, Alverno College 

Chris Fietkiewicz, Case Western 
Reserve University 

Terrell Foty, Portland Community 
College 

Valerie Frear, Daytona State College 

Ryan Garlick, University of North Texas 

Aaron Garrett, Jacksonville State 
University 

Stephen Gilbert, Orange Coast College 

Peter van der Goes, Rose State College 

Billie Goldstein, Temple University 

Michael Gourley, University of Central 
Oklahoma 

Grigoriy Grinberg, Montgomery 
College 

Linwu Gu, Indiana University 

Sylvain Guinepain, University of 
Oklahoma, Norman 

Bruce Haft, Glendale Community 
College 

Nancy Harris, James Madison 
University 

Allan M. Hart, Minnesota State 
University, Mankato 

Ric Heishman, George Mason 
University 

Guy Helmer, Jowa State University 

Katherin Herbert, Montclair State 
University 

Rodney Hoffman, Occidental College 

May Hou, Norfolk State University 

John Houlihan, Loyola University 


Andree Jacobson, University of New 
Mexico 

Eric Jiang, University of San Diego 

Christopher M. Johnson, Guilford 
College 

Jonathan Kapleau, New Jersey Institute 
of Technology 

Amitava Karmaker, University of 
Wisconsin, Stout 

Rajkumar Kempaiah, College of Mount 
Saint Vincent 

Mugdha Khaladkar, New Jersey 
Institute of Technology 

Richard Kick, Newbury Park High 
School 

Julie King, Sullivan University, 
Lexington 

Samuel Kohn, Touro College 

April Kontostathis, Ursinus College 

Ron Krawitz, DeVry University 

Nat Kumaresan, Georgia Perimeter 
College 

Debbie Lamprecht, Texas Tech 
University 

Jian Lin, Eastern Connecticut State 
University 

Hunter Lloyd, Montana State 
University 

Cheng Luo, Coppin State University 

Kelvin Lwin, University of California, 
Merced 

Frank Malinowski, Dalton College 

John S. Mallozzi, Jona College 

Khaled Mansour, Washtenaw 
Community College 

Kenneth Martin, University of North 
Florida 

Deborah Mathews, J. Sargeant 
Reynolds Community College 

Louis Mazzucco, State University of 
New York at Cobleskill and 
Excelsior College 

Drew McDermott, Yale University 

Hugh McGuire, Grand Valley State 
University 

Michael L. Mick, Purdue University, 


Calumet 


Jeanne Milostan, University of 
California, Merced 

Sandeep Mitra, SUNY Brockport 

Michel Mitri, James Madison University 

Kenrick Mock, University of Alaska 
Anchorage 

Namdar Mogharreban, Southern 
Illinois University 

Shamsi Moussavi, Massbay Community 
College 

Nannette Napier, Georgia Gwinnett 
College 

Tony Tuan Nguyen, De Anza College 

Michael Ondrasek, Wright State 
University 

K. Palaniappan, University of Missouri 

James Papademas, Oakton Community 
College 

Gary Parker, Connecticut College 

Jody Paul, Metropolitan State College 
of Denver 

Mark Pendergast, Florida Gulf Coast 
University 

James T. Pepe, Bentley University 

Jeff Pittges, Radford University 

Tom Plunkett, Virginia Tech 

Linda L. Preece, Southern Illinois 
University 

Vijay Ramachandran, Colgate 
University 

Craig Reinhart, California Lutheran 
University 

Jonathan Robinson, Touro College 

Chaman Lal Sabharwal, Missouri 
University of Science & Technology 

Katherine Salch, //linois Central 
College 

Namita Sarawagi, Rhode Island College 

Ben Schafer, University of Northern 
Iowa 

Walter Schilling, Milwaukee School of 
Engineering 

Jeffrey Paul Scott, Blackhawk Technical 
College 

Amon Seagull, NOVA Southeastern 
University 

Linda Seiter, John Carroll University 


Acknowledgments xvii 

Kevin Seppi, Brigham Young University 

Ricky J. Sethi, UCLA, USC ISI, and 
DeVry University 

Ali Shaykhian, Florida Institute of 
Technology 

Lal Shimpi, Saint Augustine’s College 

Victor Shtern, Boston University 

Rahul Simha, George Washington 
University 

Jeff Six, University of Delaware 

Donald W. Smith, Columbia College 

Derek Snow, University of Southern 
Alabama 

Peter Spoerri, Fairfield University 

David R. Stampf, Suffolk County 
Community College 

Peter Stanchev, Kettering University 

Ryan Stansifer, Florida Institute of 
Technology 

Stu Steiner, Eastern Washington 
University 

Robert Strader, Stephen F. Austin 
State University 

David Stucki, Otterbein University 

Ashok Subramanian, University of 
Missouri, St Louis 

Jeremy Suing, University of Nebraska, 
Lincoln 

Dave Sullivan, Boston University 

Vaidy Sunderam, Emory University 

Hong Sung, University of Central 
Oklahoma 

Monica Sweat, Georgia Tech University 

Joseph Szurek, University of Pittsburgh, 
Greensburg 

Jack Tan, University of Wisconsin 

Cynthia Tanner, West Virginia 
University 

Russell Tessier, University of 
Massachusetts, Amherst 

Krishnaprasad Thirunarayan, Wright 
State University 

Megan Thomas, California State 
University, Stanislaus 

Timothy Urness, Drake University 

Eliana Valenzuela-Andrade, University 
of Puerto Rico at Arecibo 


xviii Acknowledgments 


Tammy VanDeGrift, University of Chen Ye, University of Illinois, Chicago 
Portland Wook-Sung Yoo, Fairfield University 
Philip Ventura, Broward College Steve Zale, Middlesex County College 
David R. Vineyard, Kettering Bahram Zartoshty, California State 
University University, Northridge 
Qi Wang, Northwest Vista College Frank Zeng, Indiana Wesleyan 
Jonathan Weissman, Finger Lakes University 
Community College Hairong Zhao, Purdue University 
Reginald White, Black Hawk Calumet 
Community College Stephen Zilora, Rochester Institute of 
Ying Xie, Kennesaw State University Technology 
Arthur Yanushka, Christian Brothers 
University 


And a special thank you to our class testers: 


Eugene Backlin and the students of DePaul University, Loop 

Debra M. Duke and the students of J. Sargeant Reynolds Community College 
Gerald Gordon and the students of DePaul University, Loop 

Mike Gourley and the students of the University of Central Oklahoma 
Mohammad Morovati and the students of the College of DuPage 
Mutsumi Nakamura and the students of Arizona State University 
George Novacky and the students of the University of Pittsburgh 

Darrin Rothe and the students of the Milwaukee School of Engineering 
Paige Rutner and the students of Georgia Southern University 
Narasimha Shashidhar and the students of Sam Houston State University 
Mark Sherriff and the students of the University of Virginia 

Frank Zeng and the students of Indiana Wesleyan University 





PREFACE v 
SPECIAL FEATURES xxvi 


~ cuapTeRT INTRODUCTION 1 


] 
] 
] 
] 
] 
] 
] 


NOUBA WDN = 


Computer Programs 2 

The Anatomy of a Computer 3 

The Java Programming Language 5 

Becoming Familiar with Your Programming Environment 
Analyzing Your First Program 12 

Errors 15 

Problem Solving: Algorithm Design 16 


oo eapTeR2=) «FUNDAMENTAL DATATYPES 29 


2] 
Zee 
23 
2.4 
2.5 


Variables 30 

Arithmetic 41 

Input and Output 48 

Problem Solving: First Do It By Hand 57 
Strings 59 


(eeaPTRS) DECISIONS 81 


3.1 
3.2 
33 
3.4 
325 
3.6 
Saf 
3.8 


The if Statement 82 

Comparing Numbers and Strings 88 
Multiple Alternatives 96 

Nested Branches 100 

Problem Solving: Flowcharts 105 
Problem Solving: Test Cases 108 
Boolean Variables and Operators 111 
Application: Input Validation 116 


eiarrera) Loops 139 


4.1 
4.2 
4.3 
4.4 
4.5 


The while Loop 140 

Problem Solving: Hand-Tracing 147 

The for Loop 150 

The do Loop 156 

Application: Processing Sentinel Values 158 





xx Contents 


4.6 
4.7 
4.8 
4.9 


Problem Solving: Storyboards 162 

Common Loop Algorithms 165 

Nested Loops 172 

Application: Random Numbers and Simulations 176 


~ capTeRs = METHODS 201 


5.1] 
5.2 
5.3 
5.4 
39 
5.6 
card 
5.8 
59 


Methods as Black Boxes 202 

Implementing Methods 204 

Parameter Passing 207 

Return Values 210 

Methods Without Return Values 214 
Problem Solving: Reusable Methods 215 
Problem Solving: Stepwise Refinement 218 
Variable Scope 225 

Recursive Methods (Optional) 228 


Oo eapTERG > «ARRAYS AND ARRAY LISTS 249 


6.1 
6.2 
6.3 
6.4 
6.5 
6.6 


6.7 
6.8 


Arrays 250 

The Enhanced for Loop 257 

Common Array Algorithms 258 

Using Arrays with Methods 268 

Problem Solving: Adapting Algorithms 272 

Problem Solving: Discovering Algorithms by Manipulating 
Physical Objects 279 

Two-Dimensional Arrays 282 

Array Lists 289 


oo enapteR7 >) «= INPUT/OUTPUT AND EXCEPTION HANDLING 317 


7.1 
7.2 
73 
7.4 
ie, 


Reading and Writing Text Files 318 
Text Input and Output 323 

Command Line Arguments 330 
Exception Handling 337 

Application: Handling Input Errors 347 


or aPTER'S) «OBJECTS AND CLASSES 361 


8.1 
8.2 
8.3 
8.4 


Object-Oriented Programming 362 
Implementing a Simple Class 364 

Specifying the Public Interface of a Class 367 
Designing the Data Representation 371 


o.5 
8.6 
8.7 
8.8 
8.9 
8.10 
8.11 


Contents xxi 


Implementing Instance Methods 372 
Constructors 375 

Testing a Class 380 

Problem Solving: Tracing Objects 386 
Problem Solving: Patterns for Object Data 388 
Object References 395 

Static Variables and Methods 400 


Oo eaPTeR'9) INHERITANCE AND INTERFACES 415 


9,1 
92 
9.3 
9.4 
5.5 
9:6 


Inheritance Hierarchies 416 
Implementing Subclasses 420 
Overriding Methods 424 
Polymorphism 430 

Object: The Cosmic Superclass 441 
Interface Types 448 


HAPTER TO) §=GRAPHICAL USER INTERFACES 465 


LO] 
10.2 
10.3 
10.4 


Frame Windows 466 

Events and Event Handling 470 
Processing Text Input 481 
Creating Drawings 487 


Oo eaPTER TT) ADVANCED USER INTERFACES 507 


11.1 
11.2 
113 
11.4 
Iles 
11.6 


Layout Management 508 

Choices 510 

Menus 521 

Exploring the Swing Documentation 528 
Using Timer Events for Animations 533 
Mouse Events 536 


( coaPTER12) “OBJECT-ORIENTED DESIGN 549 


12.1 
l2s2 
1233 
12.4 


Classes and Their Responsibilities 550 
Relationships Between Classes 554 
Application: Printing an Invoice 562 
Packages 574 


xxii Contents 


(pypemarrers) RECURSION 585 


13.1 Triangle Numbers Revisited 586 

13.2 Problem Solving: Thinking Recursively 590 
13.3 Recursive Helper Methods 594 

13.4 The Efficiency of Recursion 596 

13.5 Permutations 601 

13.6 Mutual Recursion 606 

13.7 Backtracking 612 


© cHaAPTER 14.) SORTINGAND SEARCHING 627 


14.1 Selection Sort 628 

14.2 Profiling the Selection Sort Algorithm 631 

14.3 Analyzing the Performance of the Selection Sort Algorithm 634 
14.4 Merge Sort 639 

14.5 Analyzing the Merge Sort Algorithm 642 

14.6 Searching 646 

14.7 Problem Solving: Estimating the Running Time of an Algorithm 651 
14.8 Sorting and Searching in the Java Library 656 


(charters) THE JAVA COLLECTIONS FRAMEWORK 669 


15.1 An Overview of the Collections Framework 670 
15.2 Linked Lists 672 

15.3 Sets 679 

15.4 Maps 684 

15.5 Stacks, Queues, and Priority Queues 690 

15.6 Stack and Queue Applications 693 


"CHAPTER 16— «BASIC DATASTRUCTURES 713 


16.1 Implementing Linked Lists 714 

16.2 Implementing Array Lists 728 

16.3. Implementing Stacks and Queues 733 
16.4 Implementing a Hash Table 739 


/ CHAPTER17— ~TREESTRUCTURES 759 


17.1 Basic Tree Concepts 760 
17.2 Binary Trees 764 
17.3 Binary Search Trees 769 


Contents xxiii 


17.4 Tree Traversal 778 

17.5 Red-Black Trees 784 

17.6 Heaps 791 

17.7 The Heapsort Algorithm 802 


~ cHapTeRt8 GENERIC CLASSES 817 


18.1 Generic Classes and Type Parameters 818 
18.2 Implementing Generic Types 819 

18.3 Generic Methods 823 

18.4 Constraining Type Parameters 825 

18.5 Type Erasure 829 


Oo eaPteRI9») STREAMS AND BINARY INPUT/OUTPUT 839 


19.1 Readers, Writers, and Streams 840 
19.2 Binary Input and Output 841 

19.3. Random Access 845 

19.4 Object Streams 851 


MULTITHREADING (WEBONLY) © 


20.1 Running Threads 

20.2 Terminating Threads 

20.3 Race Conditions 

20.4 Synchronizing Object Access 
20.5 Avoiding Deadlocks 

20.6 Application: Algorithm Animation 


INTERNET NETWORKING (WEBONLY) © 


21.1 The Internet Protocol 

21.2 Application Level Protocols 
21.3 AClient Program 

21.4 AServer Program 

21.5 URL Connections 


RELATIONAL DATABASES (WEBONLY) @ 


22.1 Organizing Database Information 
22.2 Queries 
22.3 Installing a Database 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


xxiv Contents 


22.4 Database Programming in Java 
22.5 Application: Entering an Invoice 


234 


XML (WEBONLY) © 


XML Tags and Documents 


23.2 Parsing XML Documents 
23.3 Creating XML Documents 
23.4 Validating XML Documents 


WEB APPLICATIONS 


24.1 


(WEBONLY) @ 


The Architecture of a Web Application 


24.2 The Architecture of aJSF Application 
24.3 JavaBeans Components 

24.4 Navigation Between Pages 

24.5 JSF Components 

24.6 A Three-Tier Application 


APPENDIX A 
APPENDIX B 
APPENDIX C 
APPENDIX D 
APPENDIX E 
APPENDIX F 
APPENDIX G 
APPENDIX H 
APPENDIX | 

APPENDIX J 

APPENDIX K 
APPENDIX L 


GLOSSARY 
INDEX 
CREDITS 


THE BASIC LATIN AND LATIN-1 SUBSETS OF UNICODE 861 
JAVA OPERATOR SUMMARY 865 
JAVA RESERVED WORD SUMMARY 
THE JAVA LIBRARY 869 

JAVA SYNTAX SUMMARY 913 
HTML SUMMARY 925 
TOOLSUMMARY 931 

JAVADOC SUMMARY 933 
NUMBER SYSTEMS 935 

BIT AND SHIFT OPERATIONS 941 
UML SUMMARY 943 

JAVA LANGUAGE CODING GUIDELINES 947 


867 


955 


969 
1011 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


Contents Xxxv 


ALPHABETICAL LISTOF ~— SYNTAX BOXES 


Arrays 251 
Array Lists 290 
Assignment 34 


Cast 44 
Catching Exceptions 341 
Comparisons 89 


Constant Declaration 35 
Constructor with Superclass Initializer 430 
Constructors 376 


Declaring a Generic Class 820 
Declaring a Generic Method 824 


for Statement 152 


if Statement 84 

Input Statement 49 

Instance Methods 373 

Instance Variable Declaration 365 
Interface Types 449 


Java Program i3 


Static Method Declaration 205 
Subclass Declaration 422 


The Enhanced for Loop 258 

The finally Clause 344 

The instanceof Operator 445 

The throws Clause 343 

Throwing an Exception 338 
Two-Dimensional Array Declaration 283 


while Statement 14] 


Variable Declaration 3] 


xxvi Special Features 


v, )) How Tos 


Vale | 





1 Introduction 


2 Fundamental 
Data Types 


3 Decisions 


4 Loops 


5 Methods 


Omitting Semicolons 14 
Misspelling Words 16 


Using Undeclared or 


Uninitialized Variables 337 
Overflow 38 
Roundoff Errors 38 
Unintended Integer Division 46 
Unbalanced Parentheses 46 


A Semicolon After the 


if Condition 86 
Exact Comparison of 
Floating-Point Numbers 91 


Using ==to Compare Strings 92 
The Dangling else Problem 104 
Combining Multiple 


Relational Operators 113 
Confusing && and | | 
Conditions 114 


Don’t Think “Are We 


There Yet?” 144 
Infinite Loops 145 
Off-by-One Errors 145 


Missing Return Value a2 


Trying to Modify Arguments 209 


Worked Examples 


Describing an Algorithm 


with Pseudocode 20 
Compiling and Running 

a Program +t) 
Writing an Algorithm for 

Tiling a Floor t) 


Dividing Household Expenses @ 


Using Integer Division +) 
Carrying out Computations 54 
Computing the Cost 

of Stamps +) 
Computing Travel Time +) 
Computing Distances on Earth @ 


Implementing an 
if Statement 
Extracting the Middle 
Computing the Plural of 
an English Word 
The Genetic Code 


OO 68 


Evaluating aCellPhone Plan © 


Writing a Loop 169 
Credit Card Processing +) 
Manipulating the Pixels 

inanlmage +t) 
Drawing a Spiral oO 
Implementing a Method A\l2 
Generating Random 

Passwords +) 
Calculating a CourseGrade @ 
Debugging @ 
Thinking Recursively 231 
Fully Justified Text +) 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


























Special Features xxvii 
jg 
rf \ acorere-Vaavaniiale| ; : 
| é SY ol -Xelf-1 eo) 0) (3 
 s © 
Backup Copies 11 The ENIAC and the Dawn 
of Computing 5) 
Choose Descriptive Variable Numeric Types in Java 39 The Pentium 
Names 38 Big Numbers 40 Floating-Point Bug 48 
Do Not Use Magic Numbers 39 Combining Assignment International Alphabets 
Spaces in Expressions 47. and Arithmetic 47 and Unicode 66 
Use the API Documentation 53 Instance Methods and 
Static Methods 64 
Using Dialog Boxes for Input 
and Output 65 
Brace Layout 86 The Conditional Operator 87 The Denver Airport 
Always Use Braces 86 Lexicographic Ordering Luggage Handling System 95 
Tabs 87 ‘of Strings 92 Artificial Intelligence 119 
Avoid Duplication in Branches 88 The switch Statement 99 
Hand-Tracing 103 Enumeration Types 105 
Make a Schedule and Make Logging 110 
Time for Unexpected Short-Circuit Evaluation 
Problems 109 of Boolean Operators 114 
De Morgan’s Law Ss 
Use for Loops for Their The Loop-and-a-Half Problem The First Bug 146 
Intended Purpose Only [5 and the break Statement 160 Software Piracy 182 
Choose Loop Bounds That Redirection of Input 
Match Your Task 155 and Output 161 
Count Iterations 156 Drawing GraphicalShapes 179 
Method Comments 207 The Explosive Growth of 
Do Not Modify Parameter Personal Computers 232 
Variables 209 
Keep Methods Short 223} 
Tracing Methods Das 
Stubs 224 




















@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


xxviii Special Features 


@, ») How Tos 
X Flare 





6 Arrays and Array Lists 


7 Input/Output and 
Exception Handling 


8 Objects and Classes 


9 Inheritance and 
Interfaces 





Bounds Errors 255) 
Uninitialized Arrays 255) 
Underestimating the Size 

of a Data Set 267 
Length and Size 299 


Backslashes in FileNames 321 


Constructing a Scanner with 
a String 321 


Forgetting to Initialize 

Object References 

in a Constructor 378 
Trying to Calla Constructor 379 
Declaring a Constructor 

as void 379 


Replicating Instance Variables 


from the Superclass 423 
Confusing Super- and 

Subclasses 424 
Accidental Overloading 428 


Forgetting to Use super 
When Invoking a 


Superclass Method 429 
Don’t Use Type Tests 446 
Forgetting to Declare Implement- 

ing Methods as Public 453 


Worked Examples 


Working with Arrays 2 
Rolling the Dice 


Removing Duplicates from 
an Array 


A World Population Table 
Game of Life 


SOO Ga 


Computing a Document’s 
Readability 


Processing Text Files 3333) 
Analyzing Baby Names tr) 
Detecting Accounting Fraud © 


Implementing a Class 382 


Implementing a 
Bank Account Class 


Paying Off a Loan 


Modeling a Robot Escaping 
from a Maze 


+) 
+] 


Developing an 
Inheritance Hierarchy 436 


Implementing an 
Employee Hierarchy for 
Payroll Processing 


Building a Discussion Board © 
Drawing Geometric Shapes oO 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


ign 
re \ iacorela-Vaalanl are) 





Sy ol Kel [Um ke) 0) (a) 


Special Features xxix 









































Variation in Behavior 420 








Dynamic Method Lookup and 


the Implicit Parameter 433 
Abstract Classes 434 
Final Methods and Classes 435 
Protected Access 436 
Inheritance and the 

toString Method 446 
Inheritance and the 

equals Method 447 
Constants in Interfaces 453 
Function Objects 454 


st — 
Use Arrays for Sequences Sorting with the Java Library 267 An Early Internet Worm 256 
of Related Items 256 Binary Search 267 
Reading Exception Reports 274 Methods witha Variable 
Number of Parameters 272 
Two-Dimensional Arrays with 
Variable Row Lengths 288 
Multidimensional Arrays 289 
The Diamond Syntax in 
Java 7 299 
Throw Early, Catch Late 345 Reading Web Pages 321 Encryption Algorithms 336 
Do Not Squelch Exceptions 345 File Dialog Boxes 321 TheAriane Rocket Incident 347 
Do Not Use catch and finally Reading and Writing 
inthe Same try Statement 346 Binary Data 322 
Regular Expressions 330 
Automatic Resource 
Management in Java 7 346 
All Data Variables Should The javadoc Utility 370 Electronic Voting Machines 394 
Be Private; Most Methods Overloading 380 OpenSource and 
Should Be Public 374 Calling One Constructor Free Software 402 
from Another 399 
Use a Single Class for Variation Calling the Superclass 
in Values, Inheritance for Constructor 429 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


xxx Special Features 





10 


12 


13 


14 


15 


—— Parameter Types 
in the Implementing 


Graphical User 


Interfaces eae 478 
Forgetting to Attach 

a Listener 478 

Forgetting to Repaint 496 


By Default, Components Have 


Zero Width and Height 497 
Advanced User 
Interfaces 
Object-Oriented Design 
Recursion rane Recursion 590 
Sorting and Searching The compareTo Method Can 
Return Any Integer, 
Not Just—1, 0, and 1 658 


The Java Collections 
Framework 


») How Tos 
EVaye| 


@ 


Worked Examples ~~ + 


Drawing Graphical Shapes 497 
Coding a Bar Chart Creator +t) 
Solving Crossword Puzzles +) 


Laying Out a User Interface 518 
Programming a Working 

Calculator 
Adding Mouse and 

Keyboard Support to the 

Bar Chart Creator +) 
Designing a Baby 

Naming Program +) 
Using CRC Cards and 

UML Diagrams in 

Program Design 558 
Simulating an Automatic 

Teller Machine t) 
Finding Files +) 
Towers of Hanoi +) 
Enhancing the Insertion Sort 

Algorithm +t) 
Choosing a Collection 686 
Word Frequency +) 
Simulating a Queue of 

Waiting Customers +) 


Building a Table of Contents © 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


Special Features Xxxxi 





aetere-lVanlaalia TRO 
og g Special Topics Random Facts 
Tips =? 
Don’t Use a Frame Adding the main Method to the 
as a Listener 478 Frame Class 470 
Local Inner Classes 479 


Anonymous Inner Classes 480 


Use a GUI Builder 520 Keyboard Events 539 
Event Adapters 540 
Make Parallel Arrays into Attributes and Methods in 
Arrays of Objects 561 UML Diagrams S58) 
Consistency 562 Multiplicities 560 
Aggregation, Association, 
and Composition 560 
The Limits of Computation 604 
Oh, Omega, and Theta 636 The First Programmer 650 
Insertion Sort 637 


The Quicksort Algorithm 644 


The Parameterized 
Comparable Interface 658 


The Comparator Interface 659 


Use Interface References to Hash Functions 688 Standardization 678 
Manipulate Data Structures 683 Reverse Polish Notation 701 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


XXxii 





16 


17 


18 


19 


20 


21 


22 


23 


24 


Special Features 


Basic Data Structures 


Tree Structures 


Generic Classes 


Streams and Binary 
Input/Output 


Multithreading 
(WEBONLY) © 


Internet Networking 
(WEBONLY) © 


Relational Databases 
(WEBONLY) @ 


XML 
(WEB ONLY) @ 
Web Applications 


(WEB ONLY) © 


8} How Tos 
EVaye| 


g, 


Worked Examples 


Implementing a 
Doubly-Linked List 


Building a Huffman Tree 


Implementing a 
Red-Black Tree 


Genericity and Inheritance 827 Making a Generic Binary 
The Array Store Exception 827 Search Tree Class 
Using Generic Types ina 

Static Context 832 
Negative byte Values 845 Choosing a File Format 
Calling await Without 

Calling signalA11 +) 


Calling signalAl1 Without 
Locking the Object 


Designing Client/Server 
Programs 


Joining Tables Without 
Specifying a Link Condition 

Constructing Queries from 
Arbitrary Strings 


Programming a Bank 
+) Database 


XML Elements Describe 
Objects, Not Classes +t) 


Designing an XML 
Document Format 


Writing an XML Document 
Writing aDTD 


Designing a Managed Bean 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


854 


Go| OOO 


Special Features Xxxiii 


ecole e-laavaniiare) 


ecTaveke) gam atclel as 





__ Tips 
Static Classes 728 
Open Addressing 747 
Wildcard Types 828 
Reflection 832 
Use the Runnable Interface @_ Thread Pools @ Embedded Systems +) 
Check for Thread Interruptions Object Locks and 
in the run Method Synchronized Methods +) 
of a Thread @ The Java Memory Model ° 
Use High-Level Libraries +) 
Stick with the Standard @ Primary Keys and Indexes @ Databases and Privacy +t) 
Avoid Unnecessary Data Transactions +t) 
Replication © Object-Relational Mapping @ 
Don’t Replicate Columns 
in a Table t) 
Don’t Hardwire Database 
Connection Parameters 
into Your Program +) 
Let the Database Do the Work © 
Prefer XML Elements over Schema Languages @ Word Processing and 
Attributes @ other XML Technologies @ ‘Typesetting Systems +t) 
Avoid Children with Mixed Grammars, Parsers, and 
Elements and Text +) Compilers +) 


Session State and Cookies 
AJAX 


Ooo 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


CHAPTER GOALS 






To learn about computers 
and programming 


To compile and run your first Java program 
To recognize compile-time and run-time errors 


To describe an algorithm with pseudocode 


CHAPTER CONTENTS 


1.1 COMPUTER PROGRAMS 2 1.6 ERRORS 15 
1.2 THE ANATOMY OF A COMPUTER 3 Common Error 1.2: Misspelling Words 16 
Random Fact 1.1: The ENIAC and the Dawn of 1.7 PROBLEM SOLVING: 

Computing 5 ALGORITHM DESIGN 16 
1.3 THE JAVA PROGRAMMING How To 1.1: Describing an Algorithm with 

Pseudocode 20 
LANGUAGE 5 age ; 
Worked Example 1.1: Writing an Algorithm for 

1.4 BECOMING FAMILIAR WITH YOUR Tiling a Floor @ 

PROGRAMMING ENVIRONMENT 8 Video Example 1.2: Dividing Household 
Programming Tip 1.1: Backup Copies 11 Expenses +) 
Video Example 1.1: Compiling and Running 

a Program o 


1.5 ANALYZING YOUR FIRST 
PROGRAM 12 

Syntax 1.1: Java Program 13 

Common Error 1.1: Omitting Semicolons 14 





1.1] m 


Computers execute 
very basic 
instructions in 
rapid succession. 


A computer program 
is a sequence 

of instructions 

and decisions. 


Programming is the 
act of designing and 
implementing 
computer programs. 





r Program 


You have probably used a computer for work or fun. Many people use computers 
for everyday tasks such as electronic banking or writing a term paper. Computers are 
good for such tasks. They can handle repetitive chores, such as totaling up numbers 
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 ona specific task. 

The computer itself is a machine that stores data (numbers, words, pictures), inter- 
acts with devices (the monitor, the sound system, the printer), and executes programs. 
A computer program tells a computer, in minute detail, the sequence of steps that are 
needed to fulfill a task. The physical computer and peripheral devices are collectively 
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: 


e Puta red dot ata given screen position. 
e Add up two numbers. 


e Ifthis 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. 

The act of designing and implementing computer programs is called program- 
ming. In this book, you will learn how to program a computer—that is, how to direct 
the computer to execute tasks. 

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 
precisely and quickly carry out a task that would take you hours of drudgery, to 


1.2. The Anatomy ofaComputer 3 


make small changes in a program that lead to immediate improvements, and to see the 
computer become an extension of your mental powers. 


1. What is required to play music on a computer? 
2. Why is a CD player less flexible than a computer? 


3. What does a computer user need to know about programming in order to play a 
video game? 


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. 
Sa ee The CPU performs program control and data processing. That is, the CPU locates 
processing unit (CPU) and executes the program instructions; it carries out arithmetic operations such as 
performs program addition, subtraction, multiplication, and division; it fetches data from external mem- 
ue ane ory or devices and places processed data into storage. 
ata processing. : Q . ; 
There are two kinds of storage. Primary storage is made from memory chips: 
electronic circuits that can store data, provided they are supplied with electric power. 
eae ee a Secondary storage, usually a hard disk (see Figure 2), provides slower and less 
secondary storage. expensive storage that persists without electricity. A hard disk consists of rotating 
platters, which are coated with a magnetic material, and read/write heads, which can 
detect and change the magnetic flux on the platters. 
The computer stores both data and programs. They are located in secondary stor- 
age and loaded into memory when the program starts. The program then updates the 
data in memory and writes the modified data back to secondary storage. 





ad. 
me 
os OF 
tv 
0 


cm 





Figure 1 Central Processing Unit Figure 2. A Hard Disk 


4 Chapter 1 Introduction 





eo 


Printer “a 
a eal 
=~ Hard disk 














ouse i Disk 
eel is 
Ports) «>| —~ <—— 
Controller <—_ 
——— 











Keyboard CD/DVD drive 

CPU ~~ | 2 Graphics =t _ = 

card 
Monitor 
Memory ~—> —— Sousa ~ - aly 

card 
Speakers 

Network 

<3 <4 aia Internet 

card 





SELF CHECK 


Practice It 











Figure 3 Schematic Design of a Personal Computer 


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) are stored on 
the hard disk, on a compact disk (or DVD), or elsewhere on the network. When a 
program is started, it is brought into memory, where the CPU can read it. The CPU 
reads the program one instruction at a time. As directed by these instructions, the 
CPU reads data, modifies it, and writes it back to memory or the hard disk. Some pro- 
gram 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 or mouse. The program analyzes the nature of these inputs 
and then executes the next appropriate instruction. 


4. Where is a program stored when it is not currently running? 


5. Which part of the computer carries out arithmetic operations, such as addition 
and multiplication? 


Now you can try these exercises at the end of the chapter: R1.2, R1.3. 


The ENIAC (electronic 
numerical integrator 
and computer) was 
the first usable electronic computer. It 
was designed by J. Presper Eckert and 


1.3. The Java Programming Language 5 


one must find the numerical solu- 
tions of certain differential equations; 
hence the name “numerical integra- 
tor’. Before machines like the ENIAC 


were developed, humans did this kind 


Random Fact 1.1 The ENIAC and the Dawn of Computing 


of work, and until the 1950s the word 
“computer” referred to these people. 
The ENIAC was later used for peace- 
ful purposes, such as the tabulation of 
U.S. Census data. 


John Mauchly at the University of Penn- 
sylvania and was completed in 1946— 
two years before transistors were 
invented. The computer was housed in 
a large room and consisted of many 
cabinets containing about 18,000 vac- 
uum tubes (see Figure 4). Vacuum 
tubes burned out at the rate of several 
tubes per day. An attendant with a 
shopping cart full of tubes constantly 
made the rounds and replaced defec- 
tive ones. The computer was_ pro- 
grammed by connecting wires on pan- 
els. Each wiring configuration would 
set up the computer for a particular 
problem. To have the computer work 
ona different problem, the wires had to 
be replugged. 

Work on the ENIAC was supported 
by the U.S. Navy, which was interested 
in computations of ballistic tables that 
would give the trajectory of a projec- 
tile, depending on the wind resistance, 
initial velocity, and atmospheric con- 
ditions. To compute the trajectories, 





Figure 4 The ENIAC 


1.3 Th va Programming Lan 


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 language, you specify 
the actions that your program should carry out. A 
compiler translates the high-level instructions into 
the more detailed instructions 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 





James Gosling 


6 Chapter 1 


Java was originally 
designed for 
programming 
consumer devices, 
but it was first 
successfully used 
to write Internet 
applets. 


Java was designed to 
be safe and portable, 
benefiting both 
Internet users 

and students. 


Introduction 


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

Gosling recounts that in 1994 the team realized, “We could write a really cool 
browser. It was one of the few things in the client/server mainstream that needed 
some of the weird things we’d done: architecture neutral, real-time, reliable, secure.” 
Java was introduced to an enthusiastic crowd at the SunWorld exhibition in 1995, 
together with a browser that ran applets —Java code that can be located anywhere on 
the Internet. Figure 5 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 addition, 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 independent of those proprietary systems and was bitterly fought by their ven- 
dors. A “micro edition” and an “enterprise edition” of the Java library allow Java 
programmers to target hardware ranging from smart cards and cell phones to the 
largest Internet servers. 

Because Java was designed for the Internet, it has two attributes that make it very 
suitable for beginners: safety and portability. 

The safety features of the Java language make it possible to run Java programs in 
a browser without fear that they might attack your computer. As an added benefit, 
these features also help you to learn the language faster. When you make an error that 
results in unsafe behavior, you receive an accurate error report. 

The other benefit of Java is portability. The same Java program will run, without 
change, on Windows, UNIX, Linux, or Macintosh. In order to achieve portability, 
the Java compiler does not translate Java programs directly into CPU instructions. 
Instead, compiled Java programs contain instructions for the Java virtual machine, 


| o | Jmol Applet - Mozilla x 
, Elle Edit View Go Bookmarks Tools Window Help 
Q, 6) (G) ) ® http/jmol.sourceforge.nct/applet’ 








rewind prev neat play revplay 


6: GB ei 








Figure 5 An Applet for Visualizing Molecules Running in 
a Browser Window (http://jmol.sourceforge.net/) 


Java programs are 
distributed as 
instructions fora 
virtual machine, 
making them 
platform- 
independent. 


Java has a very large 
library. Focus on 
learning those parts 
of the library that 
you need for your 
programming 
projects. 


1.3. ThejJava Programming Language 7 


a 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 
machinery is necessary in Java to write even the simplest programs. This is not a prob- 
lem for professional 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 5 or later. 

Finally, you cannot hope to learn all of Java in one course. The Java language itself 
is relatively simple, but Java contains a vast set of library packages that are required 
to write useful programs. There are packages for graphics, user-interface design, 
cryptography, networking, sound, database storage, and many other purposes. Even 
expert Java programmers cannot hope to know the contents of all of the packages — 
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. 


Table 1 Java Versions 


Version Year Important New Features 

EO 1996 

ili 1997 Inner classes 

2 1998 Swing, Collections framework 

13} 2000 Performance enhancements 

1.4 2002 Assertions, XML support 
5 2004 Generic classes, enhanced for loop, auto-boxing, enumerations, annotations 
6 2006 Library improvements 
7 2011 Small language changes and library improvements 







Practice It 


SELF CHECK 


6. What are the two most important benefits of the Java language? 


7. How long does it take to learn the entire Java library? 


Now you cantry this exercise at the end of the chapter: R1.5. 


8 Chapter 1 


Introduction 


1.4 Becoming Familiar with Your 


Set aside some time 
to become familiar 
with the 
programming 
environment that 
you will use for your 
class work. 


An editor isa 
program for entering 
and modifying text, 
suchasa 

Java program. 


<fistio, Worlal> 
~/JavaForEveryone/ch@l/hellos ff 


p ig Env 


Many students find that the tools they need as programmers are very different from 
the software with which they are familiar. You should spend some time making your- 
self familiar with your programming environment. Because computer systems vary 
widely, this book can only give an outline of the steps you need to follow. It is a good 
idea to 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. 
On other computers you first launch an editor, a program that functions like a word 
processor, in which you can enter your Java instructions; you then open a console 
window and type commands to execute your program. You need to find out how to 
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.printIn("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 He11oPrinter. 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. 


Terminal —|0)|x 
File Edit View Terminal Help 
~/JavaForEveryone$ cd ch01/hello/ 
~/JavaForEveryone/ch0l/hello$ javac HelloPrinter. java 
~/JavaForEveryone/ch0l/hello$ java HelloPrinter 














Figure6 Running the HelloPrinter Program in a Console Window 


Figure 7 
Running the 
HelloPrinter 
Program in an 
Integrated 
Development 
Environment 


Java is case sensitive. 


You must be careful 

about distinguishing 
between upper- and 

lowercase letters. 


The Java compiler 
translates source 
code into class files 
that contain 
instructions for the 
Java virtual machine. 


Editor 


1.4 Becoming Familiar with Your Programming Environment 


| Java - hello/src/HelloPrinter.java - Eclipse Platform |_|olx' 





File Edit Refactor Source Navigate Search Project Prolog Run Window Help 


























v = (default package) 


b @AJRE System Library [jdk1.6.0_13 22 


} 


system.out.printin("Hello, world!"); 
t 


tS~ &6\/\@6e2/\/* 0-Q-|S # G|@SG H es | #java oS 
Plas |v Hy & 
{8 Package E 5% \_ {2 Hierarchy) * © | [9 HelloPrinter.java 52 =" (a 
es I) v public class HelloPrinter —_ ~ 
. { 
v Ghello = public static void main(String[] args) 
v @src { 














| 
+ 


=" [a 


| | im 
[& Problems | @ Javadoc |[2, Declaration| E Console 2 
<terminated> HelloPrinte 


Hello, World! 


mw > m 


Writable 















































tha Smart Insert Lise 








As you write this program, pay careful attention to the various symbols, and keep 
in mind that Java is case sensitive. You must enter upper- and lowercase letters exactly 
as they appear in the program listing. You cannot type MAIN or PrintLn. If you are not 


careful, you will run into problems—see Common Error 1.2 on page 16. 


Step 3. Runthe 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 Figures 6 and 7). 


In order to run your program, the Java compiler translates your source code (that 
is, the statements that you wrote) into class files. (A class file contains instructions for 
the Java virtual machine.) After the compiler has translated your program into virtual 
machine instructions, the virtual machine executes them. Figure 8 summarizes the 
process of creating and running a Java program. In some programming environments, 


9 


Net, 
Compiler vied oa a 
Machine 
—— Class files a ‘i 
Running 
Source File Program 


Figure 8 From Source Code to Running Program 


10. Chapter 1 






m 
ANIMATION 
Compilation Process 


f' 


Introduction 


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 envi- 
ronments, you need to launch the compiler 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 
files as well as other folders, which themselves can contain more files and folders (see 
Figure 9). 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 programming class. Inside that folder, 
make a separate folder for each program. 

Some programming environments place your programs into a default location if 
you don’t specify 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). 


(@ cho1 
Vv @ section 4 
_*) HelloPrinter.java 
v (=; section_5 
i PrintTester.java 
Vv @ section 6 
|) Errorl.java 
(4 Error2.java 
_*) Error3.java 
(@ cho2 
Ye how_to_1 
|") VendingMachine.java 
v e@ section_1 
|‘) Volumel.java 
Vv @ section 2 
_*) Price.java 
v @ section 3 
|") Volume2.java 
Vv @ section 4 
|) Tiles.java 
Vv @ section_5 
|) Initials.java 














Figure9 A Folder Hierarchy 


1.4 Becoming Familiar with Your Programming Environment 11 





8. Where is the HelloPrinter. java file stored on your computer? 


9. What do you do to protect yourself from data loss when you work on program- 


SELF CHECK . 
rc ming projects? 


f 





Practice It Now youcantry this exercise at the end of the chapter: R1.6. 


Programming Tip 1.1 Backup Copies 


You will spend many hours creating and improving Java pro- 
grams. It is easy to delete a file by accident, and occasionally files 
are lost because of a computer malfunction. Retyping the contents 
of lost files is frustrating and time-consuming. It is therefore cru- 
cially important that you learn how to safeguard files and get in 


the habit of doing so before disaster strikes. Backing up files on a 
memory stick is an easy and convenient storage method for many Cm 
people. Another increasingly popular form of backup is Internet “ 


file storage. Here are a few pointers to keep in mind: 





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


e Rotate backups. Use more than one directory for backups, and Develop a strategy 


rotate them. That is, first back up onto the first directory. Then for keeping backup 
back up onto the second directory. Then use the third, and then copies of your 
go back to the first. That way you always have three recent work before 


disaster strikes. 
backups. If your recent changes made matters worse, you can 


then go back to the older version. 


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


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





VIDEO EXAMPLE 1.1 Compiling and Running a Program —— 


(To This Video Example shows how to compile and run a simple Java = AZZ 
PLUS 


program. 


12 Chapter 1 


Classes are the 
fundamental 
building blocks of 
Java programs. 


Every Java 
application contains 
aclass with a main 
method. When the 
application starts, 
the instructions in 
the main method 
are executed. 


Each class contains 
declarations of 
methods. Each 
method contains 

a sequence 

of instructions. 





Introduction 


1.5 Analvzing Your First 


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


section_5/HelloPrinter.java 


1 public class HelloPrinter 
ae 
3 public static void main(String[] args) 
4 { 
5 System.out.printInC'Hello, World!"); 
6 } 
if 
The line 


public class HelloPrinter 


indicates the declaration of a class called He11oPrinter. 

Every Java program consists of one or more classes. Classes are the fundamental 
building blocks of Java programs. You will have to wait until Chapter 8 for a full 
explanation of classes. 

The word public denotes that the class is usable by the “public”. You will later 
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 Hel1oPrinter. 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 application 
must have a main method. Most Java programs contain other methods besides main, 
and you will see in Chapter 5 how to write other methods. 

The term static is explained in more detail in Chapter 8, and the meaning of 
String[] args is covered in Chapter 7. At this time, simply consider 


public class ClassName 


{ 
public static void main(String[] args) 
{ 
} 

} 


as a part of the “plumbing” that is required to create a Java program. Our first pro- 
gram has all instructions inside the main method of the class. 

The main method contains one or more instructions called statements. Each state- 
ment ends ina semicolon (;). When a program runs, the statements in the main method 
are executed one by one. 


Syntax 1.1 


Every Java program 


1.5 Analyzing Your First Program 13 


Java Program 


Every program contains at least one class. 
Choose a class name that describes 
the program action. 


public class HelloPrinter 


contains a main method fi 


with this header. 





A method is called 
by specifying the 
method and 

its arguments. 


A string is a sequence 
of characters 
enclosed in 
quotation marks. 


public static void main(String[] args) 


{ 


System.out.printInC"Hello, World!"); Replace this 
The statements inside the = ees statement when you 


main method are executed } 
when the program runs. Each statement programs. 
ends in a semicolon. 


A See page 14. 


write your own 


Be sure to match the 
opening and closing braces. 


In our example program, the main method has a single statement: 
System.out.printIn("Hello, World!"); 


This statement prints a line of text, namely “Hello, World!”. In this statement, we call 
a method which, for reasons that we will not explain here, is specified by the rather 
long name System. out.printIn. 

We do not have to implement this method —the programmers who wrote the Java 
library already did that for us. We simply want the method to perform its intended 
task, namely to print a value. 

Whenever you call a method in Java, you need to specify 


1. The method you want to use (in this case, System. out .print1n). 


2. Any values the method needs to carry out its task (in this case, "Hello, World!"). 
The technical term for such a value is an argument. Arguments are enclosed in 
parentheses. Multiple arguments are separated by commas. 


A sequence of characters enclosed in quotation marks 
"Hello, World!" 


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


System.out.printIn(3 + 4); 


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


14 Chapter] Introduction 


The System. out.printin method prints a string or a number and then starts a new 
line. For example, the sequence of statements 


System.out.printIn("Hello"); 
System.out.printIn("World!"); 


prints two lines of text: 


Hello 
World! 
There is a second method, System. out.print, that you can use to print an item without 
@ Aprogram to starting a new line. For example, the output of the two statements 
demonstrate print . oe 
commands. System.out.print("00"); 


System.out.printIn(3 + 4); 
is the single line 
007 


10. How do you modify the HelloPrinter program to greet you instead? 


11. How would you modify the He11oPrinter program to print the word “Hello” 
vertically? 





12. Would the program continue to work if you replaced line 5 with this statement? 
System.out.printIn(Hello); 


13. What does the following set of statements print? 


System.out.print("My lucky number is"); 
System.out.printin(3 + 4 + 5); 


14. What do the following statements print? 


System.out.printIn("Hello"); 
System.out.printIn(""); 
System.out.printIn("World") ; 


Practice It Now youcantry these exercises at the end of the chapter: R1.7, R1.8, P1.5, P1.7. 


Common Error 1.1 Omitting Semicolons 


In Java every statement must end in a semicolon. Forgetting to type a semicolon is a common 
error. It confuses the compiler, because the compiler uses the semicolon to find where one 
statement ends and the next one starts. The compiler does not use line breaks or closing braces 
to recognize the end of statements. For example, the compiler considers 


System. out.printIn("Hello") 
System.out.printInC"World!"); 


a single statement, as if you had written 
System.out.printIn("Hello") System.out.printInC"World!"); 


Then it doesn’t understand that statement, because it does not expect the word System follow- 
ing the closing parenthesis after "Hello". 

The remedy is simple. Scan every statement for a terminating semicolon, just as you would 
check that every English sentence ends in a period. 


1.6 Errors 15 


GG Errors 


Experiment a little with the HelloPrinter program. 
What happens if you make a typing error such as 


System.ou.printIn("Hello, World!"); 
System.out.printInC"Hello, Word!"); 


Bae In the first case, the compiler will complain. It will 
A compile-time error 





is a violation of say that it has no clue what you mean by ou. The 
the programming exact wording of the error message is dependent 
language Tules that on your development environment, but it might 
is detected by ; . “« » 
fe cenpilee be something like “Cannot find symbol ou”. 


This is a compile-time error. Something is wrong Rrolnaumers spend atairawaunt 
according to the rules of the language and the com- og time fixing compile-time and run- 
piler finds it. For this reason, compile-time errors _ time errors. 

are often called syntax errors. When the compiler 

finds one or more errors, it refuses to translate the program into Java virtual machine 
instructions, and as a consequence you have no program that you can run. You must 
fix the error and compile again. In fact, the compiler is quite picky, and it is common 
to go through several rounds of fixing compile-time errors before compilation suc- 
ceeds for the first time. 

If the compiler finds an error, it will not simply stop and give up. It will try to 
report as many errors as it can find, so you can fix them all at once. 

Sometimes, an error throws the compiler off track. Suppose, for example, you 
forget the quotation marks around a string: System.out.printIn(Hello, World!). The 
compiler will not complain about the missing quotation marks. Instead, it will report 
“Cannot find symbol Hello”. Unfortunately, the compiler is not very smart and it 
does not realize that you meant to use a string. It is up to you to realize that you need 
to enclose strings in quotation marks. 

The error in the second line above is of a different kind. The program will compile 
and run, but its output will be wrong. It will print 


Hello, Word! 
ee eee This is a run-time error. The program is syntactically correct and does something, 
causes a program to but it doesn’t do what it is supposed to do. Because run-time errors are caused by 
take an action that logical flaws in the program, they are often called logic errors. 


the programmer did 


This particular run-time error did not include an error message. It simply pro- 
not intend. 


duced the wrong output. Some kinds of run-time errors are so severe that they gen- 
erate an exception: an error message from the Java virtual machine. For example, if 
your program includes the statement 


System.out.printIn(1 / 0); 


you will get a run-time error message “Division by zero”. 
During program development, errors are unavoidable. Once a program is longer 
@ Three programs to than a few lines, it would require superhuman concentration to enter it correctly 
State TE Or >: without slipping up once. You will find yourself omitting semicolons or quotation 
marks more often than you would like, but the compiler will track down these prob- 

lems for you. 

Run-time errors are more troublesome. The compiler will not find them —in fact, 
the compiler will cheerfully translate any program as long as its syntax is correct— 


16 Chapter 1 Introduction 





Practice It 


(@foyaalaacelam=laae) amie 





| PP aa 2 a 


but the resulting program will do something wrong. It is the responsibility of the 
program author to test the program and find any run-time errors. 


15. Suppose you omit the "" characters around Hello, World! from the He1loPrinter. 
java program. Is this a compile-time error or a run-time error? 


16. Suppose you change printin to printline in the Hel1oPrinter. java program. Is this 
a compile-time error or a run-time error? 


17. Suppose you change main to hello in the He11oPrinter. java program. Is this a 
compile-time error or a run-time error? 


18. When you used your computer, you may have experienced a program that 
“crashed” (quit spontaneously) or “hung” (failed to respond to your input). Is 
that behavior a compile-time error or a run-time error? 


19. Why can’t you test a program for run-time errors when it has compiler errors? 


Now you can try these exercises at the end of the chapter: R1.9, R1.10, R1.11. 


Misspelling Words 


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


public class HelloPrinter 


{ 
public static void Main(String[] args) 
{ 
System.out.printIn("Hello, World!"); 
} 
t 


This class declares a method called Main. The compiler will not consider this to be the same as 
the main method, because Main starts with an uppercase letter and the Java language is case sen- 
sitive. Upper- and lowercase letters are considered to be completely different from each other, 
and to the compiler Main is no better match for main than rain. The compiler will cheerfully 
compile your Main method, but when the Java virtual machine reads the compiled file, it will 
complain about the missing main method and refuse to run the program. Of course, the mes- 
sage “missing main method” should give you a clue where to look for the error. 

If you get an error message that seems to indicate that the compiler or virtual machine is on 
the wrong track, it is a good idea to check for spelling and capitalization. If you misspell the 
name of a symbol (for example, ou instead of out), the compiler will produce a message such as 
“cannot find symbol ou”. That error message is usually a good clue that you made a spelling 
error. 


lving: Algorithm D 


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


1.7 Problem Solving: Algorithm Design 17 


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

For that reason, a computerized match-making service cannot guarantee to find 
the optimal match for you. Instead, you may be presented with a set of potential part- 
ners who share common interests with you. That is a task that a computer program 
can solve. 

Now consider the following investment problem: 





You put $10,000 into a bank account that earns 5 percent interest per year. How many 
years does it take for the account balance to be double the original? 


Could you solve this problem by hand? Sure, you could. You figure out the balance 
as follows: 





interest balance 
10000 
10000.00 x 0.09 = 500.00 10000.00 + 500.00 = 10500.00 
10500.00 x 0.05 = 525.00 10500.00 + 525.00 = 11025.00 
11029.00 x 0.09 = 991.25 11029.00 + 991.25 = 11976.25 
11976.25 x 0.09 = 9738.81 11976.25 + 578.81 = 12199.06 























You keep going until the balance is at least $20,000. Then the last number in the year 
column is the answer. 

Of course, carrying out this computation is intensely boring to you or your 
younger brother. But computers are very good at carrying out repetitive calcula- 
tions quickly and flawlessly. What is important to the computer is a description of the 
steps for finding the solution. Each step must be clear and unambiguous, requiring no 
guesswork. Here is such a description: 


Start with a year value of 0, a column for the interest, and a balance of #10,000. 


year interest balance 


0 10000 








18 Chapter 1 


Pseudocode is an 
informal description 
of a sequence of 
steps for solving 

a problem. 


Introduction 


Repeat the following steps while the balance is less than #20,000 
Add 1 to the year value. 
Compute the interest as balance x 0.09 (ie. 9 percent interest). 
Add the interest to the balance. 








r 


year interest balance 
0 10000 
1 500.00 10500.00 














14 | 942.82 | 19799.32 
45) | 939.96 | 20789.28 























Report the final year value as the answer. 


course, these steps are not yet in a language that a computer can understand, bu 
Of these step t yet ina language that put derstand, but 
you will soon learn how to formulate them in Java. This informal description is called 
pseudocode. 


There are no strict requirements for pseudocode because it is read by human read- 


ers, not a computer program. Here are the kinds of pseudocode statements that we 
will use in this book: 


Use statements such as the following to describe how a value is set or changed: 


total cost = purchase price + operating cost 
Multiply the balance value by 1.09. 
Remove the first and last character from the word. 


You can describe decisions and repetitions as follows: 


If total cost 1 < total cost Z 
While the balance is less than ¢Z0,000 
For each picture in the sequence 


Use indentation to indicate which statements should be selected or repeated: 


For each car 
operating cost = 10 x annual fuel cost 
total cost = purchase price + operating cost 


Here, the indentation indicates that both statements should be executed for 
each car. 


Indicate results with statements such as: 


Choose car 1. 
Report the final year value as the answer. 


The exact wording is not important. What is important is that pseudocode describes 
a sequence of steps that is 


Unambiguous 
Executable 


Terminating 


An algorithm for 
solving a problem is 
a sequence of steps 
that is unambiguous, 
executable, and 
terminating. 


Understand 
the problem 


Develop and 
describe an 
algorithm 


Test the 
algorithm with 
simple inputs 


Translate 
the algorithm 
into Java 


Compile and test 
your program 





1.7 Problem Solving: Algorithm Design 


The step sequence is unambiguous when there are 
precise instructions for what to do at each step and 
where to go next. There is no room for guesswork 
or personal opinion. A step is executable when it 
can be carried out in practice. Had we said to use iA 
the actual interest rate that will be charged in years f) 
to come, and not a fixed rate of 5 percent per year, 

that step would not have been executable, because | 
there is no way for anyone to know what that 

interest rate will be. A sequence of steps is termi- ~ 
nating if it will eventually come to an end. In our “ ii 
example, it requires a bit of thought to see that the = i 
sequence will not go on forever: With every step, An algorithm is a recipe for 
the balance goes up by at least $500, so eventually finding a solution. 

it must reach $20,000. 


19 





A sequence of steps that is unambiguous, executable, and terminating is called an 
algorithm. We have found an algorithm to solve our investment problem, and thus 
we can find the solution by programming a computer. The existence of an algorithm 
is an essential prerequisite for programming a task. You need to first discover and 
describe an algorithm for the task that you want to solve before you start program- 


ming (see Figure 10). 


Figure 10 The Software Development Process 


20. Suppose the interest rate was 20 percent. How long would it take for the invest- 


ment to double? 


21. Suppose your cell phone carrier charges you $29.95 for up to 300 minutes of 


calls, and $0.45 for each additional minute, plus 12.5 percent taxes and fees. Give 


an algorithm to compute the monthly charge from a given number of minutes. 


22. Consider the following pseudocode for finding the most attractive photo froma 


sequence of photos: 


Pick the first photo and call it “the best so far". 
For each photo in the sequence 
If it is more attractive than the “best so far" 
Discard “the best so far". 
Call this photo “the best so far’. 
The photo called “the best so far" is the most attractive photo in the sequence. 


Is this an algorithm that will find the most attractive photo? 


20 Chapter 1 Introduction 


Practice It 





HOW TO 1.1 


Step 1 


Step 2 


23. Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find- 
ing the most expensive photo. 


24. Suppose you have a random sequence of black and white marbles and want to 
rearrange it so that the black and white marbles are grouped together. Consider 
this algorithm: 


Repeat until sorted 
Locate the first black marble that is preceded by a white marble, and switch them. 


What does the algorithm do with the sequence O®O@®@? Spell out the steps 
until the algorithm stops. 


25. Suppose you have a random sequence of colored marbles. Consider this pseudo- 
code: 


Repeat until sorted 
Locate the first marble that is preceded by a marble of a different color, and switch them. 


Why is this not an algorithm? 


Now you can try these exercises at the end of the chapter: R1.15, R1.17, P1.4. 


Describing an Algorithm with Pseudocode 


This is the first of many “How To” sections in this book that give you step-by-step proce- 
dures for carrying out important tasks in developing computer programs. 

Before you are ready to write a program in Java, you need to develop an algorithm—a 
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo- 
code: a sequence of precise steps formulated in English. 

For example, consider this problem: You have the choice of 
buying two cars. One is more fuel efficient than the other, but 
also more expensive. You know the price and fuel efficiency (in 
miles per gallon, mpg) of both cars. You plan to keep the car 
for ten years. Assume a price of $4 per gallon of gas and usage 
of 15,000 miles per year. You will pay cash for the car and not 
worry about financing costs. Which car is the better deal? 





Determine the inputs and outputs. 


In our sample problem, we have these inputs: 

© purchase price! and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car 
© purchase priceZ and fuel efficiencyZ, the price and fuel efficiency of the second car 

We simply want to know which car is the better buy. That is the desired output. 


Break down the problem into smaller tasks. 


For each car, we need to know the total cost of driving it. Let’s do this computation separately 
for each car. Once we have the total cost for each car, we can decide which car is the better deal. 


The total cost for each car is purchase price * operating cost. 


We assume a constant usage and gas price for ten years, so the operating cost depends on the 
cost of driving the car for one year. 


The operating cost is 10 x annual fuel cost. 
The annual fuel cost is price per gallon x annual fuel consumed. 


1.7 Problem Solving: Algorithm Design 21 


The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car 
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons. 


Step 3 Describe each subtask in pseudocode. 


In your description, arrange the steps so that any intermediate values are computed before 
they are needed in other computations. For example, list the step 


total cost = purchase price + operating cost 


after you have computed operating cost. 
Here is the algorithm for deciding which car to buy: 


For each car, compute the total cost as follows: 
annual fuel consumed = annual miles driven / fuel efficiency 
annual fuel cost = price per gallon x annual fuel consumed 
operating cost = 10 x annual fuel cost 
total cost = purchase price + operating cost 

If total cost! < total costZ 
Choose car. 

Else 
Choose carZ. 


Step 4 Test your pseudocode by working a problem. 
We will use these sample values: 


Car 1: $25,000, 50 miles/gallon 
Car 2: $20,000, 30 miles/gallon 


Here is the calculation for the cost of the first car: 


annual fuel consumed = annual miles driven / fuel efficiency = 19000 / 90 = 300 
annual fuel cost = price per gallon x annual fuel consumed = 4 x 300 = 1200 
operating cost = 10 x annual fuel cost = 10 x 1200 = 12000 

total cost = purchase price + operating cost = 29000 + 12000 = 37000 


Similarly, the total cost for the second car is $40,000. Therefore, the output of the algorithm is 
to choose car 1. 





WORKED EXAMPLE 1.1 Writing an Algorithm for Tiling a Floor 


+ This Worked Example shows how to develop an algorithm for laying 
tile in an alternating pattern of colors. 





VIDEO EXAMPLE 1.2 Dividing Household Expenses 


(To This Video Example shows how to develop an algorithm for 
PLUS 


dividing household expenses among roommates. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


22 Chapter] Introduction 


Define “computer program” and programming. 


¢ Computers execute very basic instructions in rapid succession. 
e A computer program is a sequence of instructions and decisions. 
¢ Programming is the act of designing and implementing computer programs. 


Describe the components of a computer. 


¢ The central processing unit (CPU) performs program control and data 
processing. 


¢ Storage devices include memory and secondary storage. 


Describe the process of translating high-level languages to machine code. 


¢ Java was originally designed for programming consumer devices, but it was first 
successfully used to write Internet applets. 


¢ Java was designed to be safe and portable, benefiting both Internet users and 
students. 


¢ Java programs are distributed as instructions for a virtual machine, making them 
plattorm-independent. 


© Java has a very large library. Focus on learning those parts of the library that you 
need for your programming projects. 


Become familiar with your Java programming environment. 


¢ Set aside some time to become familiar with the programming environment that 
you will use for your class work. 


¢ Aneditor is a program for entering and modifying text, such as a Java program. 

¢ Java is case sensitive. You must be careful about distinguishing between upper- 
and lowercase letters. 

¢ The Java compiler translates source code into class files that contain instructions 
for the Java virtual machine. 

¢ Develop a strategy for keeping backup copies of your 
work before disaster strikes. 





Describe the building blocks of a simple program. 


¢ Classes are the fundamental building blocks of Java programs. 


e Every Java application contains a class with a main method. When the application 
starts, the instructions in the main method are executed. 


¢ Each class contains declarations of methods. Each method contains a sequence of 
instructions. 


e A method is called by specifying the method and its arguments. 





e A string is a sequence of characters enclosed in quotation marks. 


Review Exercises 23 


Classify program errors as compile-time and run-time errors. 


¢ A compile-time error is a violation of the programming language rules that is 





detected by the compiler. 


e A run-time error causes a program to take an action that the programmer did not 
intend. 


Write pseudocode for simple algorithms. 


¢ Pseudocode is an informal description of a sequence of steps 


for solving a problem. 


e Analgorithm for solving a problem is a sequence of steps that 
is unambiguous, executable, and terminating. 





java.io.PrintStream java. lang.System 
print out 
printin 


# R11 


#RI1.2 
#R1.3 


aoe R14 


#RI1.5 
ot R1.6 


aa R17 


Explain the difference between using a computer program and programming a 
computer. 


Which parts of a computer can store program code? Which can store user data? 


Which parts of a computer serve to give information to the user? Which parts take 
user input? 


A toaster is a single-function device, but a computer can be programmed to carry out 
different tasks. Is your cell phone a single-function device, or is ita programmable 
computer? (Your answer will depend on your cell phone model.) 


Explain two benefits of using Java over machine code. 
On your own computer or ona lab computer, find the exact location (folder or 
directory name) of 

a. The sample file HelloPrinter. java, which you wrote with the editor 

b. The Java program launcher java.exe or java 

c. The library file rt. jar that contains the run-time library 


What does this program print? 


public class Test 


{ 


public static void main(String[] args) 
{ 
System.out.printin("39 + 3"); 
System.out.printin(39 + 3); 


} 


24 Chapter 1 


Introduction 


##R1.8 What does this program print? Pay close attention to spaces. 


at R1.9 


ot RI 


#RI 
oe RI 


see Rl 


see R] 


ae Ri 


oe RI 


#RI 


see Rl 


10 


11 
12 


13 


14 


5 


16 


17 


18 


public class Test 


{ 
public static void main(String[] args) 
{ 
System.out.print("Hello"); 
System.out.printInC"World"); 
} 
} 
What is the compile-time error in this program? 
public class Test 
{ 
public static void main(String[] args) 
{ 
System.out.printIn("Hello", "World!"); 
} 
} 


Write three versions of the He11oPrinter. java program that have different compile- 
time errors. Write a version that has a run-time error. 


How do you discover syntax errors? How do you discover logic errors? 


Write an algorithm to settle the following question: A bank account starts out with 
$10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per 
month). Every month, $500 is withdrawn to meet college expenses. After how many 
years is the account depleted? 


Consider the question in Exercise R1.12. Suppose the numbers ($10,000, 6 percent, 
$500) were user selectable. Are there values for which the algorithm you developed 
would not terminate? If so, change the algorithm to make sure it always terminates. 


In order to estimate the cost of painting a house, a painter needs to know the surface 
area of the exterior. Develop an algorithm for computing that value. Your inputs are 
the width, length, and height of the house, the number of windows and doors, and 
their dimensions. (Assume the windows and doors have a uniform size.) 


You want to decide whether you should drive your car to work or take the train. 
You know the one-way distance from your home to your place of work, and the 
fuel efficiency of your car (in miles per gallon). You also know the one-way price of 
a train ticket. You assume the cost of gas at $4 per gallon, and car maintenance at 5 
cents per mile. Write an algorithm to decide which commute is cheaper. 


You want to find out which fraction of your car’s use is for commuting to work, 

and which is for personal use. You know the one-way distance from your home to 
work. For a particular period, you recorded the beginning and ending mileage on the 
odometer and the number of work days. Write an algorithm to settle this question. 


In How To 1.1, you made assumptions about the price of gas and annual usage to 
compare cars. Ideally, you would like to know which car is the better deal without 
making these assumptions. Why can’t a computer program solve that problem? 


The value of a can be computed according to the following formula: 





at R119 


= Business R1.20 


Programming Exercises 25 


Write an algorithm to compute a. Because the formula is an infinite series and an 
algorithm must stop after a finite number of steps, you should stop when you have 
the result determined to six significant digits. 


Suppose you put your younger brother in charge of backing up your work. Write a 
set of detailed instructions for carrying out his task. Explain how often he should do 
it, and what files he needs to copy from which folder to which location. Explain how 
he should verify that the backup was carried out correctly. 


Imagine that you and a number of friends go to a luxury restaurant, and when you 
ask for the bill you want to split the amount and the tip (15 percent) between all. 
Write pseudocode for calculating the amount of money that everyone has to pay. 
Your program should print the amount of the bill, the tip, the total cost, and the 
amount each person has to pay. It should also print how much of what each person 
pays is for the bill and for the tip. 


=o Pl.1 


aa P1,2 
aa P1.3 


oa P14 


=» P15 


one P1.6 


ua P1,7 


oa P18 


Write a program that prints a greeting of your choice, perhaps ina language other 
than English. 


Write a program that prints the sum of the first ten positive integers, 1+2+...+10. 


Write a program that prints the product of the first ten positive integers, 1 x 2x... x 
10. (Use * to indicate multiplication in Java.) 


Write a program that prints the balance of an account after the first, second, and 
third year. The account has an initial balance of $1,000 and earns 5 percent interest 
per year. 


Write a program that displays your name inside a box on the screen, like this: 





Dave 











Do your best to approximate lines with characters such as | - +. 


Write a program that prints your name in large letters, such as 
ek at were ot a 
Bow  * &  * * & & & 
wiki ok eo teweieg wie 
wow kw ok ok * 


* ko ko * 8 * * 


Write a program that prints a face similar to (but different from) the following: 


//11/ 


+ + 


(| oo |) 


Write a program that prints an imitation of a Piet Mondrian painting. (Search the 
Internet if you are not familiar with his paintings.) Use character sequences such as 
@@@ or ::: to indicate different colors, and use - and | to form lines. 


26 Chapter 1 Introduction 


## P1.9 Write a program that prints a house that looks exactly like the following: 


se#P1.10 Write a program that prints an animal speaking a greeting, similar to (but different 
from) the following: 


NWI\ no 
(‘’ ) / Hello \' 
( - ) < Junior | 
| | | \ Coder!/ 
CJ) 


» P1.11 Write a program that prints three items, such as the names of your three best friends 
or favorite movies, on three separate lines. 


» P1.12 Write a program that prints a poem of your choice. If you don’t have a favorite 
poem, search the Internet for “Emily Dickinson” or “e e cummings”. 


s= P1.13 Write a program that prints the United States flag, using * and = characters. 


e# P1.14 Type inand run the following program: 


import javax.swing.JOptionPane; 


public class DialogViewer 


{ 
public static void main(String[] args) 
{ 
JOptionPane.showMessageDialog(null, "Hello, World!"); 
} 
} 


Then modify the program to show the message “Hello, your name!”. 


## P1.15 Type inand run the following program: 


import javax.swing.JOptionPane; 


public class DialogViewer 


{ 
public static void main(String[] args) 
{ 
String name = JOptionPane.showInputDialog("What is your name?"); 
System.out.printIn(name) ; 
} 
} 


Then modify the program to print “Hello, zame!”, displaying the name that the user 
typed in. 


su P1.16 Modify the program from Exercise P1.15 so that the dialog continues with the mes- 
sage “My name is Hal! What would you like me to do?” Discard the user’s input and 
display a message such as 


I'm sorry, Dave. I'm afraid I can't do that. 


Replace Dave with the name that was provided by the user. 


Answers to Self-Check Questions 27 


## P1.17 Type inand run the following program: 


import java.net.URL; 
import javax.swing.ImagelIcon; 
import javax.swing.JOptionPane; 


public class Test 
{ 
public static void main(String[] args) throws Exception 
{ 
URL imageLocation = new URL( 
"http: //horstmann. com/java4everyone/duke. gif"); 
JOptionPane.showMessageDialog(null, "Hello", "Title", 
JOptionPane.PLAIN_MESSAGE, new ImageIcon(imageLocation)) ; 
} 
} 


Then modify it to show a different greeting and image. 


=» Business P1.18 Write a program that prints a two-column list of your friends’ birthdays. In the 
first column, print the names of your best friends; in the second column, print their 


birthdays. 


=» Business P1.19 Inthe United States there is no federal sales tax, so every state may impose its own 
sales taxes. Look on the Internet for the sales tax charged in five U.S. states, then 
write a program that prints the tax rate for five states of your choice. 


Sales Tax Rates 


Alaska: 0% 
Hawaii: 4% 


=» Business P1.20 To speak more than one language is a valuable skill in the labor market today. One of 
the basic skills is learning to greet people. Write a program that prints a two-column 
list with the greeting phrases shown in the following table; in the first column, print 
the phrase in English, in the second column, print the phrase in a language of your 
choice. If you don’t speak any language other than English, use an online translator 
or ask a friend. 


List of Phrases to Translate 
Good morning. 
It is a pleasure to meet you. 
Please call me tomorrow. 


Have a nice day! 


ANSWERS TO SELF-CHECK QUESTIONS 


1. A program that reads the data on the CD and 3. Nothing. 


sends output to the speakers and the screen. 4. Insecondary storage, typically a hard disk. 


2. ACD player can do one thing—play music 


5. The central processing unit. 
CDs. It cannot execute programs. 


28 


NO 


11. 


12. 


13. 


14. 


15. 


16. 


ire 


18. 


19. 


20. 


Chapter 1 Introduction 


Safety and portability. 


No one person can learn the entire library —it 
is too large. 

The answer varies among systems. A typical 
answer might be /home/dave/cs1/hel1o/Hel1o- 
Printer. java or c:\Users\Dave\Workspace\hello\ 
HelloPrinter. java 


You back up your files and folders. 


. Change World to your name (here, Dave): 


System.out.printIn("Hello, Dave!"); 


System. 
System. 
System. 
System. 
System. 


out.printin("H") ; 


out.printin("e"); 
out.printin("1"); 
out.printin("1"); 


out.printin("o"); 


No. The compiler would look for an 
item whose name is Hello. You need to 
enclose He11o in quotation marks: 


System.out.printIn("Hello"); 


The printout is My lucky number is12. It would 
be a good idea to add a space after the is. 


Hello 


a blank line 
World 


This is a compile-time error. The compiler will 
complain that it does not know the meanings 
of the words Hello and world. 


This is a compile-time error. The compiler 
will complain that System.out does not have a 
method called printline. 


This is a run-time error. It is perfectly legal to 
give the name he11o to a method, so the com- 
piler won’t complain. But when the program 
is run, the virtual machine will look for a main 
method and won’t find one. 


Itis a run-time error. After all, the program 
had been compiled in order for you to run it. 


When a program has compiler errors, no class 
file is produced, and there is nothing to run. 


4 years: 

0 10,000 
1 12,000 
2 14,400 
3 17,280 
4 20,736 


21. 


22. 


23. 


24. 


25. 


Is the number of minutes at most 300? 
a. If so, the answer 1s $29.95 x 1.125 = $33.70. 
b. If not, 


1. Compute the difference: (number of 
minutes) — 300. 

2. Multiply that difference by 0.45. 

3. Add $29.95. 

4. Multiply the total by 1.125. That is the 


answer. 


No. The step If it is more attractive than the “best 

so far" is not executable because there is no 
objective way of deciding which of two photos 
is more attractive. 


Pick the first photo and call it "the most expensive so far". 
For each photo in the sequence 
If it is more expensive than "the most expensive so far" 
Discard “the most expensive so far". 
Call this photo “the most expensive so far". 
The photo called “the most expensive so far" is the most 
expensive photo in the sequence. 


The first black marble that is preceded by a 


white one is marked in blue: 

08088 

Switching the two yields 

@00008 

The next black marble to be switched is 
@00088 

yielding 

@0008 

The next steps are 

@@008 

@@08@0 

@@@00 

Now the sequence is sorted. 

The sequence doesn’t terminate. Consider the 


input O@O@O. The first two marbles keep 
getting switched. 


TTS 2 
FUNDAMENTAL 
DATA TYPES 


CHAPTER GOALS 


To declare and initialize variables 
and constants 





To understand the properties and limitations of integers and floating-point numbers 
To appreciate the importance of comments and good code layout 

To write arithmetic expressions and assignment statements 

To create programs that read and process inputs, and display the results 


To learn how to use the Java String type 


CHAPTER CONTENTS 


2.1 VARIABLES 30 Random Fact 2.1: The Pentium 
Syntax 2.1: Variable Declaration 31 Floating-Point Bug 48 
Syntax 2.2: Assignment 34 2.3 INPUTAND OUTPUT 48 


Syntax 2.3: Constant Declaration 35 

Common Error 2.1: Using Undeclared or 
Uninitialized Variables 37 

Programming Tip 2.1: Choose Descriptive 
Variable Names 38 

Common Error 2.2: Overflow 38 


Syntax 2.5: Input Statement 49 

Programming Tip 2.4: Use the API 
Documentation 53 

How To 2.1: Carrying out Computations 54 

Worked Example 2.1: Computing the Cost 


of Stamps @ 
Common Error 2.3: Roundoff Errors 38 
Programming Tip 2.2: Do Not Use 2.4 PROBLEM SOLVING: FIRST 
Magic Numbers 39 DOITBY HAND 57 
Special Topic 2.1: Numeric Types inJava 39 Worked Example 2.2: Computing Travel Time © 


Special Topic 2.2: Big Numbers 40 2.5 STRINGS 59 


2.2 ARITHMETIC 41 Special Topic 2.4: Instance Methods and 

Syntax 2.4: Cast 44 Static Methods 64 

Common Error 2.4: Unintended Special Topic 2.5: Using Dialog Boxes for 
Integer Division 46 Input and Output 65 

Common Error 2.5: Unbalanced Parentheses 46 Video Example 2.2: Computing Distances 

Programming Tip 2.3: Spaces in Expressions 47 on Earth @ 

Special Topic 2.3: Combining Assignment Random Fact 2.2: International Alphabets 
and Arithmetic 47 and Unicode 66 


Video Example 2.1: Using Integer Division @ 





Numbers and character strings (such as the ones on this 
display board) are important data types in any Java program. 
In this chapter, you will learn how to work with numbers 
and text, and how to write simple programs that perform 
useful tasks with them. 


2.1 Variables 


Avariable is a 
storage location 
with a name. 


30 


When your program carries out computations, you will want to store values so that 
you can use them later. In a Java program, you use variables to store values. In this 
section, you will learn how to declare and use variables. 

To illustrate the use of variables, we 
will develop a program that solves the 
following problem. Soft drinks are sold 
in cans and bottles. A store offers a six- 
pack of 12-ounce cans for the same price 
as a two-liter bottle. Which should you 
buy? (Twelve fluid ounces equal approx- 
imately 0.355 liters.) 

In our program, we will declare vari- 
ables for the number of cans per pack 
and for the volume of each can. Then we 
will compute the volume of a six-pack in What contains more soda? A six-pack of 
liters and print out the answer. 12-ounce cans or a two-liter bottle? 





2.1.1 Variable Declarations 


The following statement declares a variable named cansPerPack: 
int cansPerPack = 6; 


A variable is a storage location in a computer program. Each variable has a name and 
holds a value. 

A variable is similar to a parking space in a parking garage. The parking space has 
an identifier (such as “J 053”), and it can hold a vehicle. A variable has a name (such as 
cansPerPack), and it can hold a value (such as 6). 


Like a variable in a computer 
program, a parking space has 
an identifier and a contents. 





2.1 Variables 31 


Syntax 2.1 Variable Declaration 


typeName variableName = value; 


or 
typeName variableName; 


See page 33 for rules and 
examples of valid names. 


Types introduced in 

: A variable declaration ends 
this chapter are a int cansPerPack = 6; -——_ with a semicolon. 
the number types 
int and double \ 
(page 32) 
a String type Supplying an initial value is optional, 
(page 59). Use a descriptive but it is usually a good idea. 


variable name. Ap See page 37. 
See page 38. 





Whendecuabas When declaring a variable, you usually want to initialize it. That is, you specify the 
variable, you value that should be stored in the variable. Consider again this variable declaration: 


usually specify an 


initial Value int cansPerPack = 6; 
The variable cansPerPack is initialized with the value 6. 


WitoDeennee Like a parking space that is restricted to a certain type of vehicle (such as a compact 


variable, you also car, motorcycle, or electric vehicle), a variable in Java stores data of a specific type. 
ea the type of Java supports quite a few data types: numbers, text strings, files, dates, and many oth- 
its values. 


ers. You must specify the type whenever you declare a variable (see Syntax 2.1). 

The cansPerPack variable is an integer, a whole number without a fractional part. In 
Java, this type is called int. (See the next section for more information about number 
types in Java.) 

Note that the type comes before the variable name: 

int cansPerPack = 6; 

After you have declared and initialized a variable, you can use it. For example, 


int cansPerPack = 6; 
System.out.printIn(cansPerPack) ; 


int cansPerCrate = 4 * cansPerPack; 


Table 1 shows several examples of variable 
declarations. 


Each parking space is suitable for a particular type of vehicle, 
just as each variable holds a value of a particular type. 





32 Chapter 2 Fundamental Data Types 


Table 1 Variable Declarations in Java 


Variable Name 


int cans = 6; 


jnt total = cans + bottles; 


OQ bottles 


= Is 


OQ int volume = "2"; 


int cansPerPack; 


int dollars, cents; 


Use the int type 
for numbers that 
cannot havea 
fractional part. 


Comment 


Declares an integer variable and initializes it with 6. 


The initial value need not be a fixed value. (Of course, cans and 
bottles must have been previously declared.) 


Error: The type is missing. This statement is not a declaration but an 
assignment of a new value to an existing variable —see Section 2.1.4. 


Error: You cannot initialize a number with a string. 


Declares an integer variable without initializing it. This can be a 
cause for errors—see Common Error 2.1 on page 37. 


Declares two integer variables in a single statement. In this book, we 


will declare each variable in a separate statement. 


2.1.2 Number Types 


In Java, there are several different types of numbers. You use the int type to denote a 
whole number without a fractional part. For example, there must be an integer num- 


ber of cans in any pack of cans—you cannot have a fraction of a can. 


When a fractional part is required (such as in the number 0.335), we use floating- 
point numbers. The most commonly used type for floating-point numbers in Java is 
called double. (If you want to know the reason, read Special Topic 2.1 on page 39.) Here 


is the declaration of a floating-point variable: 
double canVolume = 0.335; 


Number 


0.5 
1.0 


1E6 


2 lB 22 


9S 100,000 
9S Sip: 


Table 2 Number Literals in Java 


Type 
jnt 
int 
jnt 

double 

double 


double 





double 


Comment 
An integer has no fractional part. 
Integers can be negative. 
Zero is an integer. 
A number with a fractional part has type double. 
An integer with a fractional part .0 has type double. 


A number in exponential notation: 1 x 10° or 1000000. 
Numbers in exponential notation always have type double. 


Negative exponent: 2.96 x 10-7 = 2.96 / 100 = 0.0296 
Error: Do not use acomma as a decimal separator. 


Error: Do not use fractions; use decimal notation: 3.5 


Use the double 
type for floating- 
point numbers. 


By convention, 
variable names 
should start witha 
lowercase letter. 


Variable Name 


canVolume1 


O can volume 
OQ double 
OQ WieeAr ll n@ye 


2.1 Variables 33 


When a value such as 6 or 0.335 occurs ina Java program, it is called a number literal. 
Ifa number literal has a decimal point, it is a floating-point number; otherwise, it is an 
integer. Table 2 shows how to write integer and floating-point literals in Java. 


2.1.3 Variable Names 


When you declare a variable, you should pick a name that explains its purpose. For 
example, it is better to use a descriptive name, such as canVolume, than a terse name, 
such as cv. 

In Java, there are a few simple rules for variable names: 


1. Variable names must start with a letter or the underscore (_) character, and the 
remaining characters must be letters, numbers, or underscores. (Technically, 
the $ symbol is allowed as well, but you should not use it—it is intended for 
names that are automatically generated by tools.) 


2. You cannot use other symbols such as ? or %. Spaces are not permitted inside 
names either. You can use uppercase letters to denote word boundaries, as in 
cansPerPack. This naming convention is called camel 
case because the uppercase letters in the middle of the 
name look like the humps of a camel.) 


3. Variable names are case sensitive, that is, canVolume and 
canvolume are different names. 





4. You cannot use reserved words such as double or class 
as names; these words are reserved exclusively for their 
special Java meanings. (See Appendix C for a listing of all reserved words in 
Java.) 


It is a convention among Java programmers that variable names should start with a 
lowercase letter (such as canVolume) and class names should start with an uppercase 
letter (such as He11oPrinter). That way, it is easy to tell them apart. 

Table 3 shows examples of legal and illegal variable names in Java. 


Table 3 Variable Names in Java 
Comment 
Variable names consist of letters, numbers, and the underscore character. 


In mathematics, you use short variable names such as x or y. This is legal in Java, but not 
very common, because it can make programs harder to understand (see Programming Tip 
2.1 on page 38). 


Caution: Variable names are case sensitive. This variable name is different from canVolume, 
and it violates the convention that variable names should start with a lowercase letter. 


Error: Variable names cannot start with a number. 
Error: Variable names cannot contain spaces. 
Error: You cannot use a reserved word as a variable name. 


Error: You cannot use symbols such as / or. 


34 Chapter 2 Fundamental Data Types 


An assignment 
statement stores a 
new value ina 
variable, replacing 
the previously 
stored value. 





hm 
PA a ed 
Variable Initialization 
and Assignment 


iy 


The assignment 
operator = does not 
denote mathematical 
equality. 


Syntax 2.2 





2.1.4 The Assignment Statement 


You use the assignment statement to place a new value into a variable. Here is an 
example: 


cansPerPack = 8; 


The left-hand side of an assignment statement consists of a variable. The right-hand 
side is an expression that has a value. That value is stored in the variable, overwriting 
its previous contents. 

There is an important difference between a variable declaration and an assignment 


statement: 


; Variable declaration 
int cansPerPack = 6; 


cansPerPack = 8; Assignment statement 


The first statement is the declaration of cansPerPack. It is an instruction to create a 
new variable of type int, to give it the name cansPerPack, and to initialize it with 6. The 
second statement is an assignment statement: an instruction to replace the contents of 
the existing variable cansPerPack with another value. 

The = sign doesn’t mean that the left-hand side is equal to the right-hand side. The 
expression on the right is evaluated, and its value is placed into the variable on the left. 

Do not confuse this assignment operation with the = used in algebra to denote 
equality. The assignment operator is an instruction to do something — namely, place a 
value into a variable. The mathematical equality states that two values are equal. 

For example, in Java, it is perfectly legal to write 


totalVolume = totalVolume + 2; 


It means to look up the value stored in the variable totalVolume, add 2 to it, and place 
the result back into totalVolume. (See Figure 1.) The net effect of executing this state- 
ment is to increment totalVolume by 2. For example, if totalVolume was 2.13 before 
execution of the statement, it is set to 4.13 afterwards. Of course, in mathematics it 
would make no sense to write that x = x + 2. No value can equal itself plus 2. 


Assignment 


Syntax  variableName = value; 


This is an initialization double total = 0; This is an assignment. 


of a new variable, 


NOT an assignment. 
bottles * BOTTLE_VOLUME; 


.< / 
na 





The name of a previously 


definedivariable The expression that replaces the previous value 


total = total + cans * CAN_VOLUME; 


The same name 
can occur on both sides. 
See Figure 1. 


totalVolume = 


You cannot change 
the value of a 
variable that is 
defined as final. 


Syntax 2.3 


2.1 Variables 35 


: 2) 


2.13 — — totalVolume = 4.13 
XS totalVolume + 2 


totalVolume + 2 


apis) 


Figure 1 Executing the Assignment totalVolume = totalVolume + 2 


2.1.5 Constants 


When a variable is defined with the reserved word final, its value can never change. 
Constants are commonly written using capital letters to distinguish them visually 
from regular variables: 


final double BOTTLE_VOLUME = 2; 


It is good programming style to use named constants in your program to explain the 
meanings of numeric values. For example, compare the statements 


double totalVolume = bottles * 2; 
and 
double totalVolume = bottles * BOTTLE_VOLUME; 


A programmer reading the first statement may not understand the significance of the 
number 2. The second statement, with a named constant, makes the computation 
much clearer. 


Constant Declaration 


Syntax final typeName variableName = expression; 


The final reserved word final double CAN_VOLUME = 0.355; // Liters ina 12-ounce can 


indicates that this value ——_ 


cannot be modified. 





a This comment explains how 


Use uppercase letters for constants. the valve for the constant 
was determined. 


2.1.6 Comments 


As your programs get more complex, you should add comments, explanations for 
human readers of your code. For example, here is a comment that explains the value 
used in a variable initialization: 


final double CAN_VOLUME = 0.355; // Liters ina 12-ounce can 


This comment explains the significance of the value 0.355 to a human reader. The 
compiler does not process comments at all. It ignores everything from a // delimiter 
to the end of the line. 


36 Chapter 2 Fundamental Data Types 


Use comments to add 
explanations for 
humans who read 
your code. The 
compiler ignores 
comments. 


It is a good practice to provide comments. This helps programmers who read your 
code understand your intent. In addition, you will find comments helpful when you 
review your own programs. 

You use the // delimiter for short comments. If you have a longer comment, 
enclose it between /* and */ delimiters. The compiler ignores these delimiters and 
everything in between. For example, 


/* 
There are approximately 0.335 liters in a 12-ounce can because one ounce 
equals 0.02957353 liter; see The International Systems of Units (SI) - Conversion 
Factors for General Use (NIST Special Publication 1038). 

*/ 


Finally, start a comment that explains the purpose of a program with the /** delimiter 
instead of /*. Tools that analyze source files rely on that convention. For example, 


This program computes the volume (in liters) of a six-pack of soda cans. 


#/ 


The following program shows the use of variables, constants, and the assignment 
statement. The program displays the volume of a six-pack of cans and the total vol- 
ume of the six-pack and a two-liter bottle. We use constants for the can and bottle 
volumes. The totalVolume variable is initialized with the volume of the cans. Using an 
assignment statement, we add the bottle volume. As you can see from the program 
output, the six-pack of cans contains over two liters of soda. 


section_1/Volumel.java 


1 [** 

2 This program computes the volume (in liters) of a six-pack of soda 
3 cans and the total volume of a six-pack and a two-liter bottle. 

4 */ 

5 public class Volumel 

6 { 

7 public static void main(String[] args) 

8 { 

9 int cansPerPack = 6; 

10 final double CAN_VOLUME = 0.355; // Liters ina 12-ounce can 
11 double totalVolume = cansPerPack * CAN VOLUME; 

12 

13 System.out.print("A six-pack of 12-ounce cans contains "); 
14 System.out.print(totalVolume) ; 

15 System.out.printIn(' liters."); 

16 

17 final double BOTTLE_VOLUME = 2; // Two-liter bottle 

18 

19 totalVolume = totalVolume + BOTTLE_VOLUME; 
20 
21 System.out.print("A six-pack and a two-liter bottle contain "); 
22 System.out.print(totalVolume) ; 
23 System.out.printIn(' liters."); 
24 } 
25 } 


Program Run 


A six-pack of 12-ounce cans contains 2.13 liters. 
A six-pack and a two-liter bottle contain 4.13 liters. 





Practice It 


(@leyaalankelam=aae) aya 








2.1 Variables 37 


Just as a television commentator explains the news, | 
you use comments in your program to explain its behavior. \ / 





. Declare a variable suitable for holding the number of bottles in a case. 


. What is wrong with the following variable declaration? 


int ounces per liter = 28.35 


. Declare and initialize two variables, unitPrice and quantity, to contain the unit 


price of a single bottle and the number of bottles purchased. Use reasonable 
initial values. 


. Use the variables declared in Self Check 3 to display the total purchase price. 


5. Some drinks are sold in four-packs instead of six-packs. How would you change 


9. 


the Volume1. java program to compute the total volume? 


. What is wrong with this comment? 


double canVolume = 0.355; /* Liters ina12-ounce can // 


. Suppose the type of the cansPerPack variable in Volume1. java was changed from int 


to double. What would be the effect on the program? 


. Why can’t the variable totalVolume in the Volume1. java program be declared as 


final? 


How would you explain assignment using the parking space analogy? 


Now you can try these exercises at the end of the chapter: R2.1, R2.2, P2.1. 


Using Undeclared or Uninitialized Variables 


You must declare a variable before you use it for the first time. For example, the following 
sequence of statements would not be legal: 


double canVolume = 12 * literPerOunce; // ERROR: literPerOunce is not yet declared 
double literPerOunce = 0.0296; 


In your program, the statements are compiled in order. When the compiler reaches the first 
statement, it does not know that 1iterPerOunce will be declared in the next line, and it reports 
an error. The remedy is to reorder the declarations so that each variable is declared before it is 
used. 


38 Chapter 2 Fundamental Data Types 





Programming Tip 2.1 


(olnalancelan aac) ay aw 


-: 
AR 


(@foyaalankelaM alae) ayaa) 





A related error is to leave a variable uninitialized: 


int bottles; 
int bottleVolume = bottles * 2; // ERROR: bottles is not yet initialized 


The Java compiler will complain that you are using a variable that has not yet been given a 
value. The remedy is to assign a value to the variable before it is used. 


Choose Descriptive Variable Names 


We could have saved ourselves a lot of typing by using shorter variable names, as in 
double cv = 0.355; 


Compare this declaration with the one that we actually used, though. Which one is easier to 
read? There is no comparison. Just reading canVolume is a lot less trouble than reading cv and 
then figuring out it must mean “can volume”. 

In practical programming, this is particularly important when programs are written by 
more than one person. It may be obvious to you that cv stands for can volume and not cur- 
rent velocity, but will it be obvious to the person who needs to update your code years later? 
For that matter, will you remember yourself what cv means when you look at the code three 
months from now? 


Overflow 


Because numbers are represented in the computer with a limited number of digits, they cannot 
represent arbitrary numbers. 

The int type has a limited range: It can represent numbers up to a little more than two bil- 
lion. For many applications, this is not a problem, but you cannot use an int to represent the 
world population. 

If a computation yields a value that is outside the int range, the result overflows. No error is 
displayed. Instead, the result is truncated, yielding a useless value. For example, 


int fiftyMillion = 50000000; 
System.out.print]n(100 * fiftyMillion); // Expected: 5000000000 


displays 705032704. 
In situations such as this, you can switch to double values. However, read Common Error 
2.3 for more information about a related issue: roundoff errors. 


Roundoff Errors 


Roundoff errors are a fact of life when calculating with floating-point numbers. You probably 
have encountered that phenomenon yourself with manual calculations. If you calculate 1/3 to 
two decimal places, you get 0.33. Multiplying again by 3, you obtain 0.99, not 1.00. 

In the processor hardware, numbers are represented in the binary number system, using 
only digits 0 and 1. As with decimal numbers, you can get roundoff errors when binary digits 
are lost. They just may crop up at different places than you might expect. 


racoleleclaalaaliale mil oy 44 





Special Topic 2.1 








2.1 Variables 39 


Here is an example: 


double price = 4.35; 

double quantity = 100; 

double total = price * quantity; // Should be 100 * 4.35 = 435 
System.out.printIn(total); // Prints 434.99999999999999 


In the binary system, there is no exact representation for 4.35, just as there is no exact repre- 
sentation for 1/3 in the decimal system. The representation used by the computer is just a 
little less than 4.35, so 100 times that value is just a little less than 435. 

You can deal with roundoff errors by rounding to the nearest integer (see Section 2.2.5) or 
by displaying a fixed number of digits after the decimal separator (see Section 2.3.2). 


Do Not Use Magic Numbers 


A magic number is a numeric constant that appears in your code without explanation. For 
example, 


totalVolume = bottles * 2; 


Why 2? Are bottles twice as voluminous as cans? No, the reason is that every bottle contains 2 
liters. Use a named constant to make the code self-documenting: 


final double BOTTLE_VOLUME = 
totalVolume = bottles * BOTTLE_VOLUME; 


There is another reason for using named constants. Suppose cir- 
cumstances change, and the bottle volume is now 1.5 liters. If 
you used a named constant, you make a single change, and you 
are done. Otherwise, you have to look at every value of 2 in your 
program and ponder whether it meant a bottle volume, or some- 
thing else. In a program that is more than a few pages long, that 
is incredibly tedious and error-prone. 





We prefer programs that 


Even the most reasonable cosmic constant is going to change are easy to understand 
one day. You think there are seven days per week? Your cus- over those that appear 
tomers on Mars are going to be pretty unhappy about your silly —_to work by magic. 


prejudice. Make a constant 
final int DAYS_PER_WEEK = 7; 


Numeric Types in Java 


In addition to the int and double types, Java has several other numeric types. 

Java has two floating-point types. The float type uses half the storage of the double type 
that we use in this book, but it can only store about 7 decimal digits. (In the computer, num- 
bers are represented in the binary number system, using digits 0 and 1.) Many years ago, when 
computers had far less memory than they have today, float was the standard type for floating- 
point computations, and programmers would indulge in the luxury of “double precision” 
only when they needed the additional digits. Today, the float type is rarely used. 

By the way, these numbers are called “floating-point” because of their internal representa- 
tion in the computer. Consider numbers 29600, 2.96, and 0.0296. They can be represented in 
avery similar way: namely, as a sequence of the significant digits —296—and an indication of 
the position of the decimal point. When the values are multiplied or divided by 10, only the 


40 Chapter 2 Fundamental Data Types 


Special Topic 2.2 





position of the decimal point changes; it “floats”. Computers use base 2, not base 10, but the 
principle is the same. 

In addition to the int type, Java has integer types byte, short, and long. Their ranges are 
shown in Table 4. (Their strange-looking limits are related to powers of 2, another conse- 
quence of the fact that computers use binary numbers.) 


Table 4 Java Number Types 
Type Description Size 


int The integer type, with range 4 bytes 
~2,147,483,648 (Integer .MIN_VALUE) ... 2,147,483,647 
(Integer .MAX_VALUE, about 2.14 billion) 


byte The type describing a single byte consisting of 8 bits, 1 byte 
with range —-128... 127 

short The short integer type, with range 32,768 ... 32,767 2 bytes 

long The long integer type, with about 19 decimal digits 8 bytes 

double The double-precision floating-point type, 8 bytes 


with about 15 decimal digits and a range of about +1078 
float The single-precision floating-point type, 4 bytes 
with about 7 decimal digits and a range of about +10°8 


char The character type, representing code units in the 2 bytes 
Unicode encoding scheme (see Random Fact 2.2) 


Big Numbers 


If you want to compute with really large numbers, you can use big number objects. Big num- 
ber objects are objects of the BigInteger and BigDecimal classes in the java.math package. Unlike 
the number types such as int or double, big number objects have essentially no limits on their 
size and precision. However, computations with big number objects are much slower than 
those that involve number types. Perhaps more importantly, you can’t use the familiar arith- 
metic operators such as (+ - *) with them. Instead, you have to use methods called add, sub- 
tract, and multiply. Here is an example of how to create a BigInteger object and how to call the 
multiply method: 


BigInteger oneHundred = new BigInteger("100") ; 
BigInteger fiftyMillion = new BigInteger("50000000") ; 
System.out.println(oneHundred.multiply(fiftyMillion)); // Prints 5000000000 


The BigDecimal type carries out floating-point computations without roundoff errors. For 
example, 


BigDecimal price = new BigDecimal ("4.35"); 
BigDecimal quantity = new BigDecimal ("100"); 
BigDecimal total = price.multiply(quantity) ; 
System.out.printIn(total); // Prints 435.00 





Mixing integers and 
floating-point values 
in an arithmetic 
expression yields a 
floating-point value. 


The ++ operator adds 
1 to a variable; the -- 
operator subtracts 1. 


2.2 Arithmetic 41 





In the following sections, you will learn how to carry out arithmetic calculations 
in Java. 


2.2.1 Arithmetic Operators 


Java supports the same four basic arithmetic operations as a calculator—addition, 
subtraction, multiplication, and division—but it uses different symbols for multipli- 
cation and division. 

You must write a * b to denote multiplication. Unlike in mathematics, you cannot 
write a b, a- b, or ax b. Similarly, division is always indicated with a /, never a + ora 


fraction bar. 
at+b 





For example, becomes (a + b) / 2. 


The combination of variables, literals, operators, and/or method calls is called an 
expression. For example, (a + b) / 2 isan expression. 

Parentheses are used just as in algebra: to indicate in which order the parts of the 
expression should be computed. For example, in the expression (a + b) / 2, the sum 
a + bis computed first, and then the sum is divided by 2. In contrast, in the expression 


atb/2 


only b is divided by 2, and then the sum of aand b / 2is formed. As in regular algebraic 
notation, multiplication and division have a higher precedence than addition and sub- 
traction. For example, in the expression a + b / 2, the /is carried out first, even though 
the + operation occurs further to the left. 

If you mix integer and floating-point values in an arithmetic expression, the result 
is a floating-point value. For example, 7 + 4.0 is the floating-point value 11.0. 


2.2.2 Increment and Decrement 


Changing a variable by adding or subtracting 1 is so common that there is a special 
shorthand for it. The ++ operator increments a variable—see Figure 2: 


counter++; // Adds 1 to the variable counter 
Similarly, the -- operator decrements a variable: 


counter--; // Subtracts 1 from counter 











counter = 4 


counter + 1 
counter + 1 


aS 


Figure 2 Incrementing a Variable 


42 Chapter 2 Fundamental Data Types 


If both arguments 
of / are integers, 
the remainder 

is discarded. 


The % operator 
computes the 
remainder of an 
integer division. 


2.2.3 Integer Division and Remainder 


Division works as you would expect, as long as at least 
one of the numbers involved is a floating-point number. 


That is, 


7.0 / 4.0 

7 / 4.0 

7.0/4 
all yield 1.75. However, if both numbers are integers, 
then the result of the division is always an integer, with 
the remainder discarded. That is, 





7/4 Integer division and the % 


es ; : : operator yield the dollar and 
evaluates to 1 because 7 divided by 4 is 1 with aremain- cent values of a piggybank 


der of 3 (which is discarded). This can be a source of full of pennies. 
subtle programming errors—see Common Error 2.4. 
If you are interested in the remainder only, use the % operator: 
7% 4 
is 3, the remainder of the integer division of 7 by 4. The % symbol has no analog in alge- 
bra. It was chosen because it looks similar to /, and the remainder operation is related 
to division. The operator is called modulus. (Some people call it modulo or mod.) It 
has no relationship with the percent operation that you find on some calculators. 
Here isa typical use for the integer / and % operations. Suppose you have an amount 
of pennies in a piggybank: 


int pennies = 1729; 


You want to determine the value in dollars and cents. You obtain the dollars through 
an integer division by 100: 


int dollars = pennies / 100; // Sets dollars to 17 
The integer division discards the remainder. To obtain the remainder, use the % operator: 
int cents = pennies % 100; // Sets cents to 29 


See Table 5 for additional examples. 


Table 5 Integer Division and Remainder 


Sena Value Comment 
n % 10 9 n% 10 is always the last digit of n. 
n/ 10 172. ~—‘ This is always n without the last digit. 
n % 100 29 The last two digits of n. 
n / 10.0 172.9 Because 10.0 is a floating-point number, the fractional part is not discarded. 
-n % 10 -9 Because the first argument is negative, the remainder is also negative. 
n% 2 1 n % 2is Oif nis even, 1 or—1 if nis odd. 


The Java library 
declares many 
mathematical 
functions, such as 
Math. sqrt (square 
root) and Math. pow 


(raising to a power). 


2.2 Arithmetic 43 


2.2.4 Powers and Roots 


In Java, there are no symbols for powers and roots. To compute them, you must call 
methods. To take the square root of a number, you use the Math.sqrt method. For 
example, Vx is written as Math. sqrt(x). To compute x”, you write Math. pow(x, 1). 

In algebra, you use fractions, exponents, and roots to arrange expressions in a 
compact two-dimensional form. In Java, you have to write all expressions in a linear 
arrangement. For example, the mathematical expression 


n 
bx(1+ 5] 
100 


Figure 3 shows how to analyze such an expression. Table 6 shows additional mathe- 
matical methods. 


becomes 
b * Math.pow(1 + r / 100, n) 


b * Math.pow(1 + r / 100, n) 








n 
Figure 3 bxj1+ a 
100 


Analyzing an Expression 


Table 6 Mathematical Methods 


Method Returns 
Math. sqrt (x) Square root of x (20) 
Math.pow(x, y) x? (x >0, orx =O and y>0, orx <0 and y is an integer) 
Math. sin(x) Sine of x (x in radians) 
Math. cos (x) Cosine of x 
Math. tan(x) Tangent of x 


Math.toRadians(x) | Convert x degrees to radians (i.e., returns x - 1/180) 
Math.toDegrees(x) | Convert x radians to degrees (i.e., returns x - 180/z) 
x 


Math. exp(x) e 


Math. 1og(x) Natural log (In(x), x > 0) 


44 Chapter 2 Fundamental Data Types 


You use a cast 
(typeName) to 
convert a value toa 
different type. 


Syntax 2.4 





Table 6 Mathematical Methods 


Method Returns 
Math. 10g10(x) Decimal log (log19 (x), x > 0) 
Math. round (x) Closest integer to x (as a long) 

Math.abs (x) Absolute value |x| 
Math.max(x, y) The larger of x and y 
Math.min(x, y) The smaller of x and y 


2.2.5 Converting Floating-Point Numbers to Integers 


Occasionally, you have a value of type double that you need to convert to the type int. 
It is an error to assign a floating-point value to an integer: 


double balance = total + tax; 
int dollars = balance; // Error: Cannot assign double to int 


The compiler disallows this assignment because it is potentially dangerous: 


¢ The fractional part is lost. 

e The magnitude may be too large. (The largest integer is about 2 billion, but a 
floating-point number can be much larger.) 

You must use the cast operator (int) to convert a convert floating-point value to an 

integer. Write the cast operator before the expression that you want to convert: 


double balance = total + tax; 
int dollars = (int) balance; 


The cast (int) converts the floating-point value balance to an integer by discarding the 
fractional part. For example, if balance is 13.75, then dollars is set to 13. 

When applying the cast operator to an arithmetic expression, you need to place the 
expression inside parentheses: 


int dollars = (int) (total + tax); 


Cast 


Syntax — (typeName) expression 


This is the type of the expression after casting. 


NE) Sbataniee 00) Use parentheses here if 
These parentheses are a ge the cast is applied to an expression 
part of the cast operator. with arithmetic operators. 


ONLINE EXAMPLE 


@ Aprogram 
demonstrating casts, 
rounding, and the 
% operator. 


2.2 Arithmetic 45 


Discarding the fractional part is not always appropriate. If you want to round a 
floating-point number to the nearest whole number, use the Math. round method. This 
method returns a long integer, because large floating-point numbers cannot be stored 
inan int. 


long rounded = Math. round(balance) ; 


If balance is 13.75, then rounded is set to 14. 
If you know that the result can be stored in an int and does not require a long, you 


can use a Cast: 


int rounded = (int) Math. round(balance); 


Table 7 Arithmetic Expressions 





Practice It 





Mathematical Java 
; : Comments 
Expression Expression 
x+y (x+y) /2 The parentheses are required; 
2 x + y / 2computes x + oe 
2 
xy my fz Parentheses are not required; operators with 
2 the same precedence are evaluated left to right. 


. J Math.pow(1 + r / 100, n) UseMath.pow(x, n) to compute x”. 


Math.sqrt(a * a+b *b) a* aissimplerthanMath.pow(a, 2). 


i+jtk G+j+k) / 3.0 Ifi,j, and k are integers, using a denominator 
B of 3.0 forces floating-point division. 
1 Math. PI Math. PI is a constant declared in the Math class. 
10. A bank account earns interest once per year. In Java, how do you compute the 


11. 


12. 


13. 
14. 


interest earned in the first year? Assume variables percent and balance of type 
double have already been declared. 


In Java, how do you compute the side length of a square whose area is stored in 
the variable area? 


The volume of a sphere is given by 


V= aa 
3 


If the radius is given by a variable radius of type double, write a Java expression 
for the volume. 


What is the value of 1729 / 10 and 1729 % 10? 
If nis a positive number, what is (n / 10) % 10? 


Now you can try these exercises at the end of the chapter: R2.3, R2.5, P2.4, P2.25. 


46 Chapter 2 Fundamental Data Types 


(@foyaalaakeal =a ne) ay anes 





(@lo}aalankeal=iaae) mayan) 


Unintended Integer Division 


It is unfortunate that Java uses the same symbol, namely /, for both integer and floating-point 
division. These are really quite different operations. It is a common error to use integer divi- 
sion by accident. Consider this segment that computes the average of three integers. 


int scorel = 10; 
int score2 
int score3 


ou 
of 


double average = (scorel + score2 + score3) / 3; // Error 
System.out.printIn("Average score: " + average); // Prints 7.0, not 7.666666666666667 


What could be wrong with that? Of course, the average of scorel, score2, and score3 is 


scorel+score2+score3 


3 


Here, however, the / does not mean division in the mathematical sense. It denotes integer divi- 
sion because both score1 + score2 + score3 and 3 are integers. Because the scores add up to 23, 
the average is computed to be 7, the result of the integer division of 23 by 3. That integer 7 is 
then moved into the floating-point variable average. The remedy is to make the numerator or 
denominator into a floating-point number: 





double total = scorel + score2 + score3; 
double average = total / 3; 


or 


double average = (scorel + score2 + score3) / 3.0; 


Unbalanced Parentheses 


Consider the expression 
(a+b) *t/2* 1 - t) 


What is wrong with it? Count the parentheses. There are three ( and two ). The parenthe- 
ses are unbalanced. This kind of typing error is very common with complicated expressions. 
Now consider this expression. 


(a+b) *t) /@Q* (1 - t) 


This expression has three ( and three ), but it still is not correct. In the middle of the 
expression, 


(a+b) *t)/(2* A - t) 
t 
there is only one ( but two ), which is an error. In the middle of an expression, the count of ( 
must be greater than or equal to the count of ), and at the end of the expression the two counts 
must be the same. 

Here is a simple trick to make the counting easier without using 
pencil and paper. It is difficult for the brain to keep two counts 
simultaneously. Keep only one count when scanning the expres- 
sion. Start with 1 at the first opening parenthesis, add 1 whenever 
you see an opening parenthesis, and subtract one whenever you 
see a closing parenthesis. Say the numbers aloud as you scan the 





acolo leclaalaaliale mil oy) 





NY oJ-Kel f-1 Ko) 0) (enya 








VIDEO EXAMPLE 2.1 Using Integer Division 


2.2 Arithmetic 47 


expression. If the count ever drops below zero, or is not zero at the end, the parentheses are 
unbalanced. For example, when scanning the previous expression, you would mutter 


(a+b) *t)/@Q* (1 - t) 
al 0 -2 


and you would find the error. 


Spaces in Expressions 


It is easier to read 
= (-b + Math.sqrt(b * b- 4* a*c)) / (2 * a); 
than 
x1=(-b+Math. sqrt (b*b-4*a*c))/(2*a) ; 


Simply put spaces around all operators + - * / % =. However, don’t put a space after a unary 
minus: a — used to negate a single quantity, such as -b. That way, it can be easily distinguished 
froma binary minus, as ina - b. 

It is customary not to put a space after a method name. That is, write Math. sqrt(x) and not 
Math.sqrt (x). 


Combining Assignment and Arithmetic 


In Java, you can combine arithmetic and assignment. For example, the instruction 
total += cans; 
is a shortcut for 
total = total + cans; 
Similarly, 
total *= 2; 
is another way of writing 
total = total * 2; 


Many programmers find this a convenient shortcut. If you like it, go ahead and use it in your 
own code. For simplicity, we won’t use it in this book, though. 


A punch recipe calls for a given amount of orange soda. In this 
Video Example, you will see how to compute the required number 
of 12-ounce cans, using integer division. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


48 Chapter 2 Fundamental Data Types 


In 1994, Intel Corporation released what 

was then its most powerful processor, the 
Pentium. Unlike previous generations of its processors, it 
had a very fast floating-point unit. Intel’s goal was to com- 
pete aggressively with the makers of higher-end processors 
for engineering workstations. The Pentium was a huge suc- 
cess immediately. 

In the summer of 1994, Dr. Thomas Nicely of Lynchburg 
College in Virginia ran an extensive set of computations 
to analyze the sums of reciprocals of certain sequences of 
prime numbers. The results were not always what his the- 
ory predicted, even after he took into account the inevitable 
roundoff errors. Then Dr. Nicely noted that the same pro- 
gram did produce the correct results when running on the 
slower 486 processor that preceded the Pentium in Intel’s 
lineup. This should not have happened. The optimal round- 
off behavior of floating-point calculations has been stan- 
dardized by the Institute for Electrical and Electronic Engi- 
neers (IEEE) and Intel claimed to adhere to the IEEE standard 
in both the 486 and the Pentium processors. Upon further 
checking, Dr. Nicely discovered that indeed there was a very 
small set of numbers for which the product of two num- 
bers was computed differently on the two processors. For 
example, 


4,195,835 — ((4,195,835/3,145,727) x 3,145,727) 


is mathematically equal to 0, and it did compute as 0 ona 
486 processor. On his Pentium processor the result was 
256. 

As it turned out, Intel had independently discovered 
the bug in its testing and had started to produce chips that 
fixed it. The bug was caused by an error in a table that was 
used to speed up the floating-point multiplication algorithm 
of the processor. Intel determined that the problem was 
exceedingly rare. They claimed that under normal use, a 
typical consumer would only notice the problem once every 
27,000 years. Unfortunately for Intel, Dr. Nicely had not 
been a normal user. 


2.3 In n 


Random Fact 2.1 The Pentium Floating-Point Bug 


Now Intel had a real problem on its hands. It figured that 
the cost of replacing all Pentium processors that it had sold 
so far would cost a great deal of money. Intel already had 
more orders for the chip than it could produce, and it would 
be particularly galling to have to give out the scarce chips 
as free replacements instead of selling them. Intel’s man- 
agement decided to punt on the issue and initially offered 
to replace the processors only for those customers who 
could prove that their work required absolute precision in 
mathematical calculations. Naturally, that did not go over 
well with the hundreds of thousands of customers who had 
paid retail prices of $700 and more for a Pentium chip and 
did not want to live with the nagging feeling that perhaps, 
one day, their income tax program would produce a faulty 
return. 

Ultimately, Intel caved in to public demand and replaced 
all defective chips, at a cost of about 475 million dollars. 


Pentium FDIV error 






















1.333840000— 
1.333820000. 
1.333800000 
1.333780000 4 


> 
SZ 1.3337600004 





1.333740000 4 


1.333720000-| 


1.333700000 





°% 3145727+ 


1.10 


This graph shows a set of numbers for which the original 
Pentium processor obtained the wrong quotient. 


In the following sections, you will see how to read user input and how to control the 
appearance of the output that your programs produce. 


2.3.1 Reading Input 


You can make your programs more flexible if you ask the program user for inputs 
rather than using fixed values. Consider, for example, a program that processes prices 


2.3 Inputand Output 49 


and quantities of soda containers. Prices and quantities are likely to fluctuate. The 
program user should provide them as inputs. 

When a program asks for user input, it should first print a message that tells the 
user which input is expected. Such a message is called a prompt. 


System.out.print("Please enter the number of bottles: "); // Display prompt 


Use the print method, not printin, to display the prompt. You want the input to 
appear after the colon, not on the following line. Also remember to leave a space after 
the colon. 

Because output is sent to System.out, you might think that you use System. in for 
input. Unfortunately, it isn’t quite that simple. When Java was first designed, not 
much attention was given to reading keyboard input. It was assumed that all pro- 

grammers would produce graphical user interfaces with text fields and menus. 
scanner reads bar 
todes: The fava System.in was given a minimal set of features and must be combined with other classes 
Scanner reads to be useful. 
numbers and text. To read keyboard input, you use a class called Scanner. You obtain a Scanner object 
by using the following statement: 





A supermarket 


Scanner in = new Scanner(System. in); 


You will learn more about objects and classes in Chapter 8. For now, simply include 
this statement whenever you want to read keyboard input. 


eee When using the Scanner class, you need to carry out another step: import the class 


grouped into from its package. A package is a collection of classes with a related purpose. All 
packages. Use the classes in the Java library are contained in packages. The System class belongs to the 
Rare package java. lang. The Scanner class belongs to the package java.util. 

from packages. Only the classes in the java. lang package are automatically available in your pro- 


grams. To use the Scanner class from the java.util package, place the following decla- 
ration at the top of your program file: 


import java.util.Scanner; 
Once you have a scanner, you use its nextInt method to read an integer value: 


System.out.print("Please enter the number of bottles: "); 
int bottles = in.nextInt(); 


Syntax 2.5 Input Statement 


Include this line so you can 


use the Scanner class. 
NER jmport java.util.Scanner; 


Create a Scanner object 


to read keyboard input. Scanner in = new Scanner(System. in); Don't use print n here 


Display a prompt in the console window. SES System.out.print("Please enter the number of bottles: "); 


int bottles = in.nextInt(); 
Detine a variable to hold the input value. ——__ 


Ss, The program waits for user input, 
then places the input into the variable. 





50 Chapter 2 Fundamental Data Types 


Use the Scanner class 
to read keyboard 
inputina 

console window. 


Use the printf 
method to specify 
how values should 
be formatted. 


When the nextInt method is called, the program waits until the user types a number 
and presses the Enter key. After the user supplies the input, the number is placed into 
the bottles variable, and the program continues. 

To read a floating-point number, use the nextDouble method instead: 


System.out.print("Enter price: "); 
double price = in.nextDouble(); 


2.3.2 Formatted Output 


When you print the result of a computation, you often want to control its appear- 
ance. For example, when you print an amount in dollars and cents, you usually want 
it to be rounded to two significant digits. That is, you want the output to look like 


Price per liter: 1.22 
instead of 
Price per liter: 1.215962441314554 
The following command displays the price with two digits after the decimal point: 
System.out.printf("%.2f", price); 
You can also specify a field width: 
System.out.printf("%10.2f", price); 


The price is printed using ten characters: six spaces followed by the four characters 
1.22. 


d}o|2)2 


The construct %10.2f is called a format specifier: it describes how a value should be for- 
matted. The letter f at the end of the format specifier indicates that we are displaying a 
floating-point number. Use d for an integer and s for a string; see Table 8 for examples. 


Table 8 Format Specifier Examples 


Format String Sample Output Comments 

"ye" 24 Use d with an integer. 

"%5d" 24 Spaces are added so that the field width is 5. 
"Quantity:%5d" Quantity: 24 Characters inside a format string but outside a 


format specifier appear in the output. 


"%6f" 1.21997 Use f with a floating-point number. 
Ter 1.22 Prints two digits after the decimal point. 
BoC Tpez tia 22 Spaces are added so that the field width is 7. 
"96s" Hello Use s with a string. 


"9d %.2F" 24 1.22 You can format multiple values at once. 


2.3. Inputand Output 51 


You use the printf method to line — ! Zoe mee oe | rom | Eapires 
up your output in neat columns. 


tad 3 ‘blige | 


Z 
pee —__pe, |< Ler [ Zn 


> ae | Lio aa ee lov rte 








A format string contains format specifiers and literal characters. Any characters that 
are not format specifiers are printed verbatim. For example, the command 


System.out.printf("Price per liter:%10.2f", price); 
prints 
Price per liter: 1.22 


You can print multiple values with a single call to the printf method. Here is a typical 
example: 
System.out.printf("Quantity: %d Total: %10.2f", quantity, total); 


The printf method does not 





width 10 start a new line here. 
A 
a ~ 
QyWUlalymypesTlely|s 204 Tl/OPelayi|s Lie ja] 2]2 
No field width was specified, Two digits after 
$o no padding added the decimal point 


The printf method, like the print method, does not start a new line after the output. 
If you want the next output to be ona separate line, you can call System. out.printIn(). 
Alternatively, Section 2.5.4 shows you how to add a newline character to the format 
string. 

Our next example program will prompt for the price of a six-pack and the volume 
of each can, then print out the price per ounce. The program puts to work what you 
just learned about reading input and formatting output. 


section_3/Volume2.java 


import java.util.Scanner; 


[** 

This program prints the price per ounce for a six-pack of cans. 
public class Volume2 
{ 

public static void main(String[] args) 


t 


ORANAUAWN= 


52 Chapter 2 Fundamental Data Types 


10 // Read price per pack 

11 

12 Scanner in = new Scanner(System. in) ; 

13 

14 System.out.print("Please enter the price for a six-pack: "); 
15 double packPrice = in.nextDouble(); 

16 

17 // Read can volume 

18 

19 System.out.print("Please enter the volume for each can (in ounces): "); 
20 double canVolume = in.nextDouble(); 

21 

22 // Compute pack volume 

23 

24 final double CANS _PER_PACK = 6; 

25 double packVolume = canVolume * CANS _PER_PACK; 

26 

27 // Compute and print price per ounce 

28 

29 double pricePerOunce = packPrice / packVolume; 

30 

31 System.out.printfC"Price per ounce: %8.2f", pricePerOunce) ; 
32 System.out.printInQ; 

33 } 

34 } 


Program Run 


Please enter the price for a six-pack: 2.95 
Please enter the volume for each can (in ounces): 12 
Price per ounce: 0.04 





15. Write statements to prompt for and read the user’s age using a Scanner variable 


SELF CHECK 
r. named in. 


f 





16. What is wrong with the following statement sequence? 


System.out.print("Please enter the unit price: "); 
double unitPrice = in.nextDouble(); 
int quantity = in.nextIntQ); 


17. What is problematic about the following statement sequence? 


System.out.print("Please enter the unit price: "); 
double unitPrice = in.nextInt(); 


18. What is problematic about the following statement sequence? 


System.out.print("Please enter the number of cans"); 
int cans = in.nextIntQ; 


19. What is the output of the following statement sequence? 


int volume = 10; 
System.out.printf("The volume is %5d", volume); 

20. Using the printf method, print the values of the integer variables bottles and cans 
so that the output looks like this: 


Bottles: 8 
Cans: 24 


The numbers to the right should line up. (You may assume that the numbers 
have at most 8 digits.) 


2.3. Inputand Output 53 


Practice It Now youcantry these exercises at the end of the chapter: R2.10, P2.6, P2.7. 


Programming Tip 2.4 Use the API Documentation 


The classes and methods of the Java library are listed in the API doc- the apy (Application 
umentation. The API is the “application programming interface”. _ programming Inter- 
A programmer who uses the Java classes to put together acomputer _ face) documentation 
program (or application) is an application programmer. That’s you. __ lists the classes and 
In contrast, the programmers who designed and implemented the ieee 
library classes (such as Scanner) are system programmers. us 

You can find the API documentation at http: //download.oracle.com/javase/7/docs/api. The 
API documentation describes all classes in the Java library —there are thousands of them. For- 
tunately, only a few are of interest to the beginning programmer. To learn more about a class, 
click on its name in the left hand column. You can then find out the package to which the class 
belongs, and which methods it supports (see Figure 4). Click on the link of a method to get a 
detailed description. 

Appendix D contains an abbreviated version of the API documentation. 





Fichier Edition Affichage Historique Marque-pages Outils Aide 






















































































<€ Ss Io} http://download.oracle.com/javase/7/docs/api/ vl ev 
javax.net A ava™ Platfo A] 
javax.netssl Overvie Package E ee Deprecated d =I 8) 
javax.print 
javaxprintatiribute Prev Class Next Class Frames No Frames 
javax.print.attribute.st— 
javax.printevent = ||| Summary: Nested | Field | Constr | Method Detail: Field | Constr | Method 
javax.rmi - - — - oe 
javax.rmi.CORBA java.util 
javax.rmi.ss! 
javax.script Class Scanner 
javay security auth 
ee java.lang.Object 
RunTimeOperations |* java.util.Scanner 
RuntimeOperationsE : 
RuntimePermission All Implemented Interfaces: 
SAAIMalaractory Closeable, AutoCloseable, Iterator<String> 
SAAJResult 
SafeVarargs 
SampleModel = i 
cag public final class Scanner 
SasiClient extends Object 
Sas!ClientFactory implements Iterator<String>, Closeable 
SaslException 
Sas/Server A simple text scanner which can parse primitive types and strings using regular expressions. 
Sas/ServerFactory —_ _ ; aig ; 
Savepoint A Scanner breaks its input into tokens using a delimiter pattern, which by default matches 
SAXException whitespace. The resulting tokens may then be converted into values of different types using 
SAXNotRecognizedE the various next methods. 
SAXNotS rtedEx: 
s AXParseexcept | For example, this code allows a user to read a number from System. in: 
<r ctory Scanner sc = new Scanner(System. in); 
SAXResult int i = sc.nextInt(); 
SAXSource 
SAXTransformerFacts 


As another example, this code allows Long types to be assigned from entries in a file 


ScatteringByteChann— myNumbers: 
SchediladEvecttorcS 
Tm > 






























































Figure 4 The API Documentation of the Standard Java Library 


54 Chapter 2 Fundamental Data Types 


HOW TO 2.1 





Step 1 


Step 2 


Step 3 


Carrying out Computations 


Many programming problems require arithmetic computations. This How To shows you 
how to turna problem statement into pseudocode and, ultimately, a Java program. 

For example, suppose you are asked to write a program that simulates a vending machine. 
A customer selects an item for purchase and inserts a bill into the vending machine. The vend- 
ing machine dispenses the purchased item and gives change. We will assume that all item prices 
are multiples of 25 cents, and the machine gives all change in dollar coins and quarters. 

Your task is to compute how many coins of each type to return. 


Understand the problem: What are the inputs? What are the desired outputs? 


In this problem, there are two inputs: 

e The denomination of the bill that the customer inserts 
e The price of the purchased item 

There are two desired outputs: 

e The number of dollar coins that the machine returns 

e The number of quarters that the machine returns 


Work out examples by hand. 


This is a very important step. If you can’t compute a couple of solutions by hand, it’s unlikely 
that you'll be able to write a program that automates the computation. 

Let’s assume that a customer purchased an item that cost $2.25 and inserted a $5 bill. The 
customer is due $2.75, or two dollar coins and three quarters, in change. 

That is easy for you to see, but how can a Java program come to the same conclusion? The 
key is to work in pennies, not dollars. The change due the customer is 275 pennies. Dividing 
by 100 yields 2, the number of dollars. Dividing the remainder (75) by 25 yields 3, the number 
of quarters. 


Write pseudocode for computing the answers. 


In the previous step, you worked out a specific instance of the problem. You now need to 
come up with a method that works in general. 

Given an arbitrary item price and payment, how can you compute the coins due? First, 
compute the change due in pennies: 


change due = 100 x bill value - item price in pennies 
To get the dollars, divide by 100 and discard the remainder: 
dollar coins = change due / 100 (without remainder) 


The remaining change due can be computed in two ways. If you are familiar with the modulus 
operator, you can simply compute 


change due = change due Z 100 

Alternatively, subtract the penny value of the dollar coins from the change due: 
change due = change due - 100 x dollar coins 

To get the quarters due, divide by 25: 
quarters = change due / 29 


Step 4 


Step 5 


Step 6 


Step 7 


2.3 Inputand Output 55 


Declare the variables and constants that you need, and specify their types. 


Here, we have five variables: 

e billValue 

© itemPrice 

e changeDue 

e dollarCoins 

e quarters 

Should we introduce constants to explain 100 and 25 as PENNIES_PER_DOLLAR and PENNIES_PER_ 
QUARTER? Doing so will make it easier to convert the program to international markets, so we 
will take this step. 


It is very important that changeDue and PENNIES_PER_DOLLAR are of type int because the com- 
putation of dollarCoins uses integer division. Similarly, the other variables are integers. 


Turn the pseudocode into Java statements. 


If you did a thorough job with the pseudocode, this step should be easy. Of course, you have 
to know how to express mathematical operations (such as powers or integer division) in Java. 


changeDue = PENNIES PER_DOLLAR * billValue - itemPrice; 
dollarCoins = changeDue / PENNIES PER_DOLLAR; 

changeDue = changeDue % PENNIES PER_DOLLAR; 

quarters = changeDue / PENNIES PER_QUARTER; 


Provide input and output. 


Before starting the computation, we prompt the user for the bill value and item price: 


System.out.printC"Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): "); 
billValue = in.nextIntQ; 

System.out.print("Enter item price in pennies: "); 

jtemPrice = in.nextIntQ); 


When the computation is finished, we display the result. For extra credit, we use the printf 
method to make sure that the output lines up neatly. 


System.out.printf("Dollar coins: %6d", dollarCoins); 
System.out.printf("Quarters: %6d", quarters); 


Provide a class with a main method. 


Your computation needs to be placed into a class. Find an appropriate name for the class that 
describes the purpose of the computation. In our example, we will choose the name Vending- 
Machine. 

Inside the class, supply a main method. 


A vending machine takes bills 
and gives change in coins. 





56 Chapter 2 Fundamental Data Types 


In the main method, you need to declare constants and variables (Step 4), carry out compu- 
tations (Step 5), and provide input and output (Step 6). Clearly, you will want to first get the 
input, then do the computations, and finally show the output. Declare the constants at the 
beginning of the method, and declare each variable just before it is needed. 

Here is the complete program, how_to_1/VendingMachine. java: 


import java.util.Scanner; 


[** 
This program simulates a vending machine that gives change. 
*/ 
public class VendingMachine 
{ 
public static void main(String[] args) 


{ 


Scanner in = new Scanner(System.in); 


final int PENNIES PER_DOLLAR = 100; 
final int PENNIES _PER_QUARTER = 25; 


System.out.printC("Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): "); 
int billValue = in.nextIntQ; 

System.out.print("Enter item price in pennies: "); 

int itemPrice = in.nextIntQ; 


// Compute change due 


int changeDue = PENNIES PER_DOLLAR * billValue - itemPrice; 
int dollarCoins = changeDue / PENNIES PER_DOLLAR; 

changeDue = changeDue % PENNIES_PER_DOLLAR; 

int quarters = changeDue / PENNIES PER_QUARTER; 


// Print change due 


System.out.printf("Dollar coins: %6d", dollarCoins); 
System.out.printInQ; 

System.out.printf("Quarters: %6d", quarters); 
System.out.printInQ; 


Program Run 


Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): 5 
Enter item price in pennies: 225 

Dollar coins: 2 

Quarters: 3 





WORKED EXAMPLE 2.1 Computing the Cost of Stamps 


+ This Worked Example uses arithmetic functions to simulate a stamp vending machine. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


2.4 Problem Solving: First Do ItBy Hand 57 


54. Problem Solvinoueirer Dalley Hand 


A very important step for developing an algorithm is to first carry out the computa- 
tions by hand. If you can’t compute a solution yourself, it’s unlikely that you'll be 
able to write a program that automates the computation. 

To illustrate the use of hand calculations, consider the following problem. 

A row of black and white tiles needs to be placed along a wall. For aesthetic rea- 
sons, the architect has specified that the first and last tile shall be black. 

Your task is to compute the number of tiles needed and the gap at each end, given 
the space available and the width of each tile. 


<———— otal width ————————_ 








Ate anetalinee To make the problem more concrete, let’s assume the following dimensions: 


for a typical situation . : : : 
ARE pe Total width: 100 inches 


calculation. e Tile width: 5 inches 


The obvious solution would be to fill the space with 20 tiles, but that would not 
work —the last tile would be white. 

Instead, look at the problem this way: The first tile must always be black, and then 
we add some number of white/black pairs: 


The first tile takes up 5 inches, leaving 95 inches to be covered by pairs. Each pair is 
10 inches wide. Therefore the number of pairs is 95 / 10 = 9.5. However, we need to 
discard the fractional part since we can’t have fractions of tile pairs. 

Therefore, we will use 9 tile pairs or 18 tiles, plus the initial black tile. Altogether, 
we require 19 tiles. 

The tiles span 19 x 5 = 95 inches, leaving a total gap of 100-19 x 5=5 inches. 

The gap should be evenly distributed at both ends. At each end, the gap is 
(100-19 x 5)/2=2.5 inches. 

This computation gives us enough information to devise an algorithm with arbi- 














@ Aprogram that trary values for the total width and tile width. 
implements this 
algorithm. number of pairs = integer part of (total width - tile width) / (Z x tile width) 


number of tiles = 1 + Z x number of pairs 
gap at each end = (total width - number of tiles x tile width) / 2 


As you can see, doing a hand calculation gives enough insight into the problem that it 
becomes easy to develop an algorithm. 


58 Chapter 2 Fundamental Data Types 


21. Translate the pseudocode for computing the number of tiles and the gap width 
into Java. 


22. Suppose the architect specifies a pattern with black, gray, and white tiles, like 


this: 


Again, the first and last tile should be black. How do you need to modify the 
algorithm? 











23. A robot needs to tile a floor with alternating black and white tiles. Develop 
an algorithm that yields the color (0 for black, 1 for white), given the row and 
column number. Start with specific values for the row and column, and then 





generalize. 
1 
1 
3 
4 
% 
| h 24. Fora particular car, repair and maintenance costs in year 1 are estimated at $100; 
F in year 10, at $1,500. Assuming that the repair cost increases by the same amount 
| hs every year, develop pseudocode to compute the repair cost in year 3 and then 


generalize to year nn. 


25. The shape of a bottle is approximated by two cylinders of radius r; and 7 and 
heights 4; and 5, joined by a cone section of height /3. 


hy Using the formulas for the volume of a cylinder, V = 27h, and a cone section, 





re + 1% +72 \h 
1 1'2 2 
V=an 


et 3 
develop pseudocode to compute the volume of the bottle. Using an actual bottle 
with known volume as a sample, make a hand calculation of your pseudocode. 








Practice It Now youcantry these exercises at the end of the chapter: R2.15, R2.17, R2.18. 


WORKED EXAMPLE 2.2 Computing Travel Time 
+ In this Worked Example, we develop a hand calculation to compute 
the time that a robot requires to retrieve an item from rocky terrain. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 





Strings are sequences 
of characters. 


The length method 
yields the number 
of characters in 

a string. 


Use the + operator to 
concatenate strings; 
that is, to put them 
together to yield a 
longer string. 


2.5 Strings 59 


Many programs process text, not numbers. Text 
consists of characters: letters, numbers, punc- 
tuation, spaces, and so on. A string is a sequence 
of characters. For example, the string "Harry" is a 
sequence of five characters. 





2.5.1 The String Type 


You can declare variables that hold strings. 
String name = "Harry"; 


We distinguish between string variables (such as the variable name declared above) and 
string literals (character sequences enclosed in quotes, such as "Harry"). A string vari- 
able is simply a variable that can hold a string, just as an integer variable can hold an 
integer. A string literal denotes a particular string, just as a number literal (such as 2) 
denotes a particular number. 

The number of characters in a string is called the length of the string. For exam- 
ple, the length of "Harry" is 5. You can compute the length of a string with the length 
method. 


int n = name. length(Q); 


A string of length 0 is called the empty string. It contains no characters and is written 
moe 
ae”, 


2.5.2 Concatenation 


Given two strings, such as "Harry" and "Morgan", you can concatenate them to one 
long string. The result consists of all characters in the first string, followed by all 
characters in the second string. In Java, you use the + operator to concatenate two 
strings. 

For example, 

String fName = "Harry"; 


String 1Name = "Morgan"; 
String name = fName + 1Name; 


results in the string 
"HarryMorgan"™ 
What if you’d like the first and last name separated by a space? No problem: 


String name = fName + + IName; 


This statement concatenates three strings: fName, the string literal" ", and 1Name. The 
result is 


"Harry Morgan" 


When the expression to the left or the right of a + operator is a string, the other one 
is automatically forced to become a string as well, and both strings are concatenated. 


60 Chapter 2 Fundamental Data Types 


Whenever one of 

the arguments of the 
+ operator is a string, 
the other argument is 
converted to 

a string. 


Use the next method 
of the Scanner class 
to read a string 
containing a 

single word. 


For example, consider this code: 


String jobTitle = "Agent"; 

int employeeld = 7; 

String bond = jobTitle + employeeld; 
Because jobTitle is a string, employeeld is converted from the integer 7 to the string "7". 
Then the two strings "Agent" and "7" are concatenated to form the string "Agent7". 

This concatenation is very useful for reducing the number of System.out.print 
instructions. For example, you can combine 


System.out.print("The total is "); 
System.out.printIn(total); 


to the single call 


System.out.printIn("The total is " + total); 


The concatenation "The total is " + total computes a single string that consists of the 
string "The total is ", followed by the string equivalent of the number total. 


2.5.3 String Input 


You can read a string from the console: 


System.out.print("Please enter your name: "); 
String name = in.next(); 


When a string is read with the next method, only one word is read. For example, sup- 
pose the user types 


Harry Morgan 


as the response to the prompt. This input consists of two words. The call in.nextQ 
yields the string "Harry". You can use another call to in.next() to read the second word. 


2.5.4 Escape Sequences 


To include a quotation mark ina literal string, precede it with a backslash (\), like this: 
"He said \"Hello\"" 


The backslash is not included in the string. It indicates that the quotation mark that 
follows should bea part of the string and not mark the end of the string. The sequence 
\" is called an escape sequence. 

To include a backslash in a string, use the escape sequence \\, like this: 


"C:\\Temp\\Secret. txt" 


Another common escape sequence is \n, which denotes a newline character. Print- 
ing a newline character causes the start of a new line on the display. For example, the 
statement 


System.out.print("*\n**\n***\n") ; 


prints the characters 


* 





on three separate lines. 


String positions are 
counted starting 
with 0. 


Use the substring 
method to extract a 
part of a string. 


2.5 Strings 61 


You often want to add a newline character to the end of the format string when 
you use System. out.printf: 


System.out.printf("Price: %10.2f\n", price); 


2.5.5 Strings and Characters 


Strings are sequences of Unicode characters (see Random 
Fact 2.2). In Java, a character is a value of the type char. 
Characters have numeric values. You can find the values 
of the characters that are used in Western European lan- 4 string is a sequence of 
guages in Appendix A. For example, if you look up the characters. 
value for the character 'H', you can see that is actually 
encoded as the number 72. 
Character literals are delimited by single quotes, and you should not confuse them 


with strings. 





e 'H' is acharacter, a value of type char. 
e "H" is a string containing a single character, a value of type String. 


The charAt method returns a char value from a string. The first string position is 
labeled 0, the second one 1, and so on. 


il | Gb | fe | fe 
12 3 4 


The position number of the last character (4 for the string "Harry") is always one less 
than the length of the string. 
For example, the statement 


String name = "Harry"; 
char start = name.charAt(0); 
char last = name.charAt(4); 


sets start to the value 'H' and last to the value 'y'. 


2.5.6 Substrings 


Once you have a string, you can extract substrings by using the substring method. 


The method call 
str.substring(start, pastEnd) 


returns a string that is made up of the characters in the string str, starting at posi- 
tion start, and containing all characters up to, but not including, the position pastEnd. 
Here is an example: 


String greeting = "Hello, World!"; 
String sub = greeting.substring(0, 5); // sub is "Hello" 


The substring operation makes a string that consists of the first five characters taken 
from the string greeting. 


HEGGB. wor ia) 
0 


123 4 5 6 7 8 9 10 11 12 


62 Chapter 2 Fundamental Data Types 


Let’s figure out how to extract the substring "World". Count characters starting at 0, 
not 1. You find that w has position number 7. The first character that you don’t want, 
!, is the character at position 12. Therefore, the appropriate substring command is 


String sub2 = greeting.substring(7, 12); 


5 
SS 


Hello, RRB: 


0.123 4 5 647 8 9 10 11/12 


It is curious that you must specify the position of the first character that you do want 
and then the first character that you don’t want. There is one advantage to this setup. 
You can easily compute the length of the substring: It is pastEnd - start. For example, 
the string "World" has length 12-7 =5. 

If you omit the end position when calling the substring method, then all characters 
from the starting position to the end of the string are copied. For example, 


String tail = greeting.substring(7); // Copies all characters from position 7 on 


sets tail to the string "World!". 

Following is a simple program that puts these concepts to work. The program asks 
for your name and that of your significant other. It then prints out your initials. 

The operation first.substring(0, 1) makes a 
string consisting of one character, taken from the 
start of first. The program does the same for the 
second. Then it concatenates the resulting one- 
character strings with the string literal "&" to get 
a string of length 3, the initials string. (See 





Figure 5.) 
first =- BRM DMAE 
0 12 3 4 5 6 
second = S el | i | i jy 
0 12 3 4 
initials = [R)/@)/S) 
0 1 2 
Initials are formed from the first 
Figure 5 Building the initials String letter of each name. 


section_5/Initials.java 


1 import java.util.Scanner; 

2 

3 [** 

4 This program prints a pair of initials. 

5 */ 

6 public class Initials 

yt 

8 public static void main(String[] args) 
9 { 

10 Scanner in = new Scanner(System. in); 
11 


2.5 Strings 63 


12 // Get the names of the couple 

13 

14 System.out.print("Enter your first name: "); 
15 String first = in.nextQ); 

16 System.out.print("Enter your significant other's first name: "); 
17 String second = in.next(); 

18 

19 // Compute and display the inscription 

20 

21 String initials = first.substring(0, 1) 

22 + "&' + second.substring(0O, 1); 

23 System.out.printIn(initials); 

24 } 

pas, i 


Program Run 


Enter your first name: Rodolfo 
Enter your significant other's first name: Sally 


R&S 


Statement 


Siti gin le Sita cl= 
str = str + "va"; 


System.out.printIn("Please" 


+ " enter your name: "); 


team = 49 + "ers" 


String first = in.nextQ; 
String last = in.nextQ); 
(User input: Harry Morgan) 


String greeting = "H & S"; 
int n = greeting. lengthQ); 


Simin ciesit pa—seSalliliy ie 
char ch = str.charAt(1); 


Sitringies ic ee—seeSalliliviuee 


String str2 = str.substring(1, 


Siemingiesit ha—seSalluliye 


String str2 = str.substring(1); 


SiuminGyesicie—saSallliVees 


String str2 = str.substring(1, 2); 


String last = str.substring( 
str.lengthQ - 1); 


Table 9 String Operations 


Result 


str is set to "Java" 


Prints 


Please enter your name: 


team is set to "49ers" 


first contains "Harry" 
last contains "Morgan" 


nis set to 5 
chis set to 'a' 
str2 is set to "all" 


str2 is set to "ally" 


str2 is set to "a 


last is set to the string 
containing the last 
character in str 


Comment 


When applied to strings, 


+ denotes concatenation. 


Use concatenation to break up strings 
that don’t fit into one line. 


Because "ers" is a string, 49 is converted 
to a string. 


The next method places the next word 
into the string variable. 


Each space counts as one character. 


This is a char value, not a String. Note 
that the initial position is 0. 


Extracts the substring starting at 
position 1 and ending before position 4. 


If you omit the end position, all 
characters from the position until the 
end of the string are included. 


Extracts a String of length 
1; contrast with str.charAt(1). 


The last character has position 
str.length(Q) - 1. 


64 Chapter 2 Fundamental Data Types 





Practice It 


Special Topic 2.4 





26. Whatis the length of the string "Java Program"? 

27. Consider this string variable. 
String str = "Java Program"; 
Give a call to the substring method that returns the substring "gram". 

28. Use string concatenation to turn the string variable str from Self Check 27 into 
"Java Programming”. 

29. What does the following statement sequence print? 


String str = "Harry"; 

int n = str.lengthQ; 

String mystery = str.substring(O, 1) + str.substring(n - 1, n); 
System.out.printIn(mystery) ; 


30. Give an input statement to read a name of the form “John Q. Public”. 


Now you can try these exercises at the end of the chapter: R2.7, R2.11, P2.15, P2.23. 


Instance Methods and Static Methods 


In this chapter, you have learned how to read, process, and print numbers and strings. Many of 
these tasks involve various method calls. You may have noticed syntactical differences in these 
method calls. For example, to compute the square root of anumber num, you call Math. sqrt (num), 
but to compute the length of a string str, you call str. length(). This section explains the rea- 
sons behind these differences. 

The Java language distinguishes between values of primitive types and objects. Numbers 
and characters, as well as the values false and true that you will see in Chapter 3, are primitive. 
All other values are objects. Examples of objects are 
e astring such as "Hello". 

e aScanner object obtained by calling in = new Scanner (System. in). 


© System.in and System. out. 


In Java, each object belongs to a class. For example, 
e Allstrings are objects of the String class. 
e Ascanner object belongs to the Scanner class. 


© System. out is an object of the PrintStream class. (It is useful to know this so that you can 

look up the valid methods in the API documentation; see Programming Tip 2.4 on page 53.) 
A class declares the methods that you can use with its objects. Here are examples of methods 
that are invoked on objects: 


"Hello".substring(O, 1) 
in.nextDouble() 
System.out.printInC"Hello") 


A method is invoked with the dot notation: the object is followed by the name of the method, 
and the method is followed by parameters enclosed in parentheses. 


The method is This is the These parameters are 
invoked on this object. name of the method. inputs to the method. 
% \ a 


System.out.printIn("Hello") 


You cannot invoke methods on numbers. For example, the call 2.sqrt() would be an error. 


Special Topic 2.5 








ONLINE EXAMPLE 


© Acomplete program 
that uses option 
panes for input 
and output. 


VIDEO EXAMPLE 2.2 Computing Distances on Earth 


PLUS 


2.5 Strings 65 


In Java, classes can declare methods that are not invoked on objects. Such methods are called 
static methods. (The term “static” is a historical holdover from the C and C++ programming 
languages. It has nothing to do with the usual meaning of the word.) For example, the Math 
class declares a static method sqrt. You call it by giving the name of the class and method, then 
the name of the numeric input: Math. sqrt (2). 


The name of the class, ihe name of the static method 
Math. sqrt(2) 
In contrast, a method that is invoked on an object is called an instance method. As a rule of 
thumb, you use static methods when you manipulate numbers. You use instance methods 


when you process strings or perform input/output. You will learn more about the distinction 
between static and instance methods in Chapter 8. 


Using Dialog Boxes for Input and Output 


Most program users find the console window rather old-fashioned. The easiest alternative is 
to create a separate pop-up window for each input. 


lo Input a 
Enter price: 
= | 


Cancel 





An Input Dialog Box 


Call the static showInputDialog method of the JOptionPane class, and supply the string that 
prompts the input from the user. For example, 


String input = JOptionPane.showInputDialog("Enter price:"); 


That method returns a String object. Of course, often you need the input as a number. Use the 
Integer.parseInt and Double.parseDouble methods to convert the string to a number: 


double price = Double.parseDouble(Cinput) ; 
You can also display output in a dialog box: 


JOptionPane.showMessageDialog(null, "Price: " + price); 


In this Video Example, you will see how to write a program that 
computes the distance between any two points on Earth. 





©@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


66 Chapter 2 Fundamental Data Types 


The English alpha- 
bet is pretty simple: 
upper- and lowercase a to z. Other 
European languages have accent marks 
and special characters. For example, 
German has three so-called umlaut 
characters, a, 6, U, and a double-s char- 
acter &. These are not optional frills; 
you couldn’t write a page of German 
text without using these characters 
a few times. German keyboards have 
keys for these characters. 








The German Keyboard Layout 


Many countries don’t use the Roman 
script at all. Russian, Greek, Hebrew, 


Arabic, and Thai letters, to name just a 
few, have completely different shapes. 
To complicate matters, Hebrew and 
Arabic are typed from right to left. Each 
of these alphabets has about as many 
characters as the English alphabet. 





Hebrew, Arabic, and English 


The Chinese languages as well as 
Japanese and Korean use Chinese char- 
acters. Each character represents an 
idea or thing. Words are made up of 
one or more of these ideographic char- 
acters. Over 70,000 ideographs are 
known. 

Starting in 1988, a consortium of 
hardware and software manufacturers 
developed a uniform encoding scheme 


Declare variables with appropriate names and types. 


e A variable is a storage location with a name. 


¢ When declaring a variable, you usually specify an 


initial value. 





¢ When declaring a variable, you also specify the type 
of its values. 


¢ Use the double type for floating-point numbers. 
¢ By convention, variable names should start with a lowercase letter. 


e Anassignment statement stores a new value ina variable, replacing 
the previously stored value. 


Random Fact 2.2 \nternational Alphabets and Unicode 


called Unicode that is capable of 
encoding text in essentially all written 
languages of the world. An early ver- 
sion of Unicode used 16 bits for each 
character. The Java char type corre- 
sponds to that encoding. 

Today Unicode has grown to a 
21-bit code, with definitions for over 
100,000 characters. There are even 
plans to add codes for extinct lan- 
guages, such as Egyptian hieroglyph- 
ics. Unfortunately, that means that a 
Java char value does not always cor- 
respond to a Unicode character. Some 
characters in languages such as Chi- 
nese or ancient Egyptian occupy two 
char values. 


BABA 


Domestic Arrivals 


e: . Vie. iB. ‘BD 


wi 
nt Hk, Macao, Tawan Arrivals ‘Be 


Departures ae 





The Chinese Script 





¢ Use the int type for numbers that cannot have a fractional part. 





¢ The assignment operator = does not denote mathematical equality. 


Chapter Summary 67 


¢ You cannot change the value of a variable that is defined as final. 


¢ Use comments to add explanations for humans who read your 
code. The compiler ignores comments. 





Write arithmetic expressions in Java. 


¢ Mixing integers and floating-point values in an arithmetic expression yields a 
floating-point value. 


¢ The ++ operator adds 1 to a variable; the -- operator subtracts 1. 
¢ Ifboth arguments of / are integers, the remainder is discarded. 





¢ The % operator computes the remainder of an integer division. 


¢ The Java library declares many mathematical functions, such as Math. sqrt (square 
root) and Math. pow (raising to a power). 


e You use a cast (typeName) to convert a value to a different type. 


Write programs that read user input and print formatted output. 


¢ Java classes are grouped into packages. Use the import statement to use classes 
from packages. 


© Use the Scanner class to read keyboard input in a console window. 


¢ Use the printf method to specify how values should be 
formatted. 

¢ The API (Application Programming Interface) 
documentation lists the classes and methods of the 
Java library. 





Carry out hand calculations when developing an algorithm. 


¢ Pick concrete values for a typical situation to use ina hand calculation. 


¢ Use the + operator to concatenate strings; that is, to put them together to yield a 
longer string. 


Write programs that process strings. 


e Strings are sequences of characters. 





¢ The length method yields the number of characters in 
a string. 





¢ Whenever one of the arguments of the + operator is a string, the other argument is 
converted to a string. 


¢ Use the next method of the Scanner class to read a string containing 
a single word. 


¢ String positions are counted starting with 0. 
¢ Use the substring method to extract a part of a string. 





68 Chapter 2 Fundamental Data Types 


java.io.PrintStream max java.math.BigDecimal 
printf min add 

java. lang.Double pow multiply 
parseDouble round subtract 

java. lang. Integer sin java.math. BigInteger 
MAX_VALUE sqrt add 
MIN_VALUE tan multiply 
parseInt toDegrees subtract 

java. lang.Math toRadians java.util.Scanner 
PI java.lang.String next 
abs charAt nextDouble 
cos length nextInt 
exp substring javax.swing.JOptionPane 
log java. lang.System showInputDialog 
log10 in showMessageDialog 


# R2.1 What is the value of mystery after this sequence of statements? 


jnt mystery = 1; 
mystery = 1 - 2 * mystery; 
mystery = mystery + 1; 


# R2.2 What is wrong with the following sequence of statements? 


jnt mystery = 1; 
mystery = mystery + 1; 
int mystery = 1 - 2 * mystery; 


n= R2.3° Write the following mathematical expressions in Java. 


- L 
5 = Sy + Uk + gt 


3 
a4 
p (m,+ my) 
YRS 
FV = PV. io 
100 





C= (2 +b? — 2abcosy 


n= R2.4 Write the following Java expressions in mathematical notation. 
a. dm = m * (Math.sqrt(1 + v / c) / Math.sqrt(1 - v / c) - 1); 
b. volume = Math.PI * r * r * h; 
c. volume = 4 * Math.PI * Math.pow(r, 3) / 3; 
d.z = Math.sqrt(x * x + y * y); 


##R2.5 What are the values of the following expressions? In each line, assume that 


double x = 2.5; 
double y = -1.5; 


Review Exercises 69 


int m = 18; 
int n= 4; 


a.x¢tn*y- (xn) *y 
bm/n+m%n 
a5*x-n/5 
d.1-(Q-@-@-(Q-n)))) 
e. Math. sqrt(Math.sqrt(n)) 


# R2.6 What are the values of the following expressions, assuming that nis 17 and mis 18? 
a.n/10+n% 10 
b.n%2+m%2 
c. (m+n) / 2 
d. (m+n) / 2.0 
e. Cint) (0.5 * (m+ n)) 
f. (int) Math.round(0.5 * (m + n)) 


##R2.7 What are the values of the following expressions? In each line, assume that 


String s = "Hello"; 

String t = "World"; 

a. s.length() + t.lengthQ) 

b. s.substring(1, 2) 

c. s.substring(s.length() / 2, s.lengthQ)) 
d.si+t 

et+s 


# R2.8 Find at least five compile-time errors in the following program. 


public class HasErrors 


{ 
public static void main(); 
{ 
System.out.print(Please enter two numbers:) 
xX = in.readDouble; 
y = in.readDouble; 
System.out.printline("The sum is "+x + y); 
} 
} 


«= R2.9 Find three run-time errors in the following program. 


public class HasErrors 


{ 
public static void main(String[] args) 
{ 
int x = 0; 
int y = 0; 


Scanner in = new Scanner("System.in"); 
System.out.print("Please enter an integer:"); 

XxX = in.readIntQ); 

System.out.print("Please enter another integer: "); 
X = in.readIntQ); 
System.out.printIn("The sum is 


+X + yY)3 


70 Chapter 2 Fundamental Data Types 


« R2.10 Consider the following code segment. 


double purchase = 19.93; 

double payment = 20.00; 

double change = payment - purchase; 
System.out.printIn(change) ; 


The code segment prints the change as 0.07000000000000028. Explain why. Give a 
recommendation to improve the code so that users will not be confused. 


# R2.11 Explain the differences between 2, 2.0, '2', "2", and "2.0". 


# R2.12 Explain what each of the following program segments computes. 


ae X = 23 
y=X+X; 

b.s = "2"; 
t=s+s3 


u= R2.13 Write pseudocode for a program that reads a word and then prints the first character, 
the last character, and the characters in the middle. For example, if the input is Harry, 
the program prints H y arr. 


n= R2.14 Write pseudocode for a program that reads a name (such as Harold James Morgan) and 
then prints a monogram consisting of the initial letters of the first, middle, and last 
name (such as HJM). 


n#2R2.15 Write pseudocode for a program that computes the first and last digit of a num- 
ber. For example, if the input is 23456, the program should print 2 and 6. Hint: %, 
Math. 1og10. 


# R2.16 Modify the pseudocode for the program in How To 2.1 so that the program gives 
change in quarters, dimes, and nickels. You can assume that the price is a multiple of 
5 cents. To develop your pseudocode, first work with a couple of specific values. 


##R2.17 A cocktail shaker is composed of three cone sections. 


Using realistic values for the radii and heights, compute the total 
volume, using the formula given in Self Check 25 for a cone section. 
Then develop an algorithm that works for arbitrary dimensions. 


na R2.18 You are cutting off a piece of pie like this, where cis the length of the 
straight part (called the chord length) and 4 is the height of the piece. 








3 


There is an approximate formula for the area: A = Sch +. 
c 


aa R2.19 


aaa R2.20 


ae R2.21 


aaa R2.22 


= R2.23 


Programming Exercises 71 


However, / is not so easy to measure, whereas the diameter d of a pie is usually 
well-known. Calculate the area where the diameter of the pie is 12 inches and the 
chord length of the segment is 10 inches. Generalize to an algorithm that yields the 
area for any diameter and chord length. 


The following pseudocode describes how to obtain the name of a day, given the day 
number (0 = Sunday, 1 = Monday, and so on.) 


Declare a string called names containing "SunMonTueWedThuFriSat". 
Compute the starting position as 3 x the day number. 
Extract the substring of names at the starting position with length 3. 


Check this pseudocode, using the day number 4. Draw a diagram of the string that is 
being computed, similar to Figure 5. 


The following pseudocode describes how to swap two letters in a word. 


We are given a string str and two positions i and j. (i comes before j) 

Set first to the substring from the start of the string to the last position before i. 

Set middle to the substring from positions i+ 1 toj- 1. 

Set last to the substring from position j + 1 to the end of the string. 

Concatenate the following five strings: first, the string containing just the character at position j, 
middle, the string containing just the character at position i, and last. 


Check this pseudocode, using the string "Gateway" and positions 2 and 4. Draw a 
diagram of the string that is being computed, similar to Figure 5. 


How do you get the first character of a string? The last character? How do you 
remove the first character? The last character? 
Write a program that prints the values 


3 * 1000 * 1000 * 1000 
3.0 * 1000 * 1000 * 1000 


Explain the results. 
This chapter contains a number of recommendations regarding variables and con- 


stants that make programs easier to read and maintain. Briefly summarize these 
recommendations. 


« P2.1 


a P2.2 


= P2,3 


un P2.4 


Write a program that displays the dimensions of a letter-size (8.5 x 11 inches) sheet 
of paper in millimeters. There are 25.4 millimeters per inch. Use constants and com- 
ments in your program. 


Write a program that computes and displays the perimeter of a letter-size (8.5 x 11 
inches) sheet of paper and the length of its diagonal. 


Write a program that reads a number and displays the square, cube, and fourth 
power. Use the Math. pow method only for the fourth power. 
Write a program that prompts the user for two integers and then prints 

e Thesum 


e The difference 


72 Chapter 2 Fundamental Data Types 


e The product 

e The average 

e The distance (absolute value of the difference) 
e The maximum (the larger of the two) 

e The minimum (the smaller of the two) 


Hint: The max and min functions are declared in the Math class. 


## P2.5 Enhance the output of Exercise P2.4 so that the numbers are properly aligned: 


Sum: 45 
Difference: -5 
Product: 500 
Average: 22.50 
Distance: 5 
Maximum: 25 
Minimum: 20 


n= P2.6 Write a program that prompts the user for a measurement in meters and then con- 
verts it to miles, feet, and inches. 
» P2.7 Write a program that prompts the user for a radius and then prints 
e The area and circumference of a circle with that radius 
e The volume and surface area of a sphere with that radius 
«= P2.8 Write a program that asks the user for the lengths of the sides of a rectangle. Then 
print 
e The area and perimeter of the rectangle 
¢ The length of the diagonal (use the Pythagorean theorem) 


» P2.9 Improve the program discussed in How To 2.1 to allow input of quarters in addition 


to bills. 


se# P2.10 Write a program that helps a person decide whether to buy a hybrid car. Your 
program’s inputs should be: 


e The cost of a new car 


Unleaded Super 
Plus Unleaded 


e The estimated miles driven per year 

e The estimated gas price 

¢ The efficiency in miles per gallon 

e The estimated resale value after 5 years 


Compute the total cost of owning the car for 
five years. (For simplicity, we will not take the 
cost of financing into account.) Obtain 
realistic prices for a new and used hybrid 

and a comparable car from the Web. Run your program twice, using today’s gas 
price and 15,000 miles per year. Include pseudocode and the program runs with your 
assignment. 





n= P2.11 Write a program that asks the user to input 
e The number of gallons of gas in the tank 
e The fuel efficiency in miles per gallon 


e The price of gas per gallon 


= P2.12 


see P2,13 


oe P2.14 


= P2.15 


on P2.16 


ae P2,17 


Programming Exercises 73 


Then print the cost per 100 miles and how far the car can go with the gas in the tank. 


File names and extensions. Write a program that prompts the user for the drive letter 
(0), the path (\Windows\System), the file name (Readme), and the extension (txt). Then 
print the complete file name C:\Windows\System\Readme. txt. (If you use UNIX ora 
Macintosh, skip the drive name and use / instead of \ to separate directories.) 


Write a program that reads a number between 1,000 and 999,999 from the user, 
where the user enters a comma in the input. Then print the number without a 
comma. Here is a sample dialog; the user input is in color: 

Please enter an integer between 1,000 and 999,999: 23,456 

23456 
Hint: Read the input as a string. Measure the length of the string. Suppose it contains 
n characters. Then extract substrings consisting of the first 7 — 4 characters and the 
last three characters. 


Write a program that reads a number between 1,000 and 999,999 from the user and 
prints it with a comma separating the thousands. Here is a sample dialog; the user 
input is in color: 


Please enter an integer between 1000 and 999999: 23456 
23,456 


Printing a grid. Write a program that prints the following grid to play tic-tac-toe. 


+— +—+— + 
1 1 1 1 


+--+ 
| | 
+--+ 
| | 
+--+ 
| | 
+--+ 


1 | 1 1 
t+—+—4+—+4 


Of course, you could simply write seven statements of the form 
System.out.print]n("+--+--+--+"); 
You should do it the smart way, though. Declare string variables to hold two kinds 


of patterns: a comb-shaped pattern and the bottom line. Print the comb three times 
and the bottom line once. 


Write a program that reads in an integer and breaks it into a sequence of individual 
digits. For example, the input 16384 is displayed as 


16384 


You may assume that the input has no more than five digits and is not negative. 


Write a program that reads two times in military format (0900, 1730) and prints the 
number of hours and minutes between the two times. Here is a sample run. User 
input is in color. 

Please enter the first time: 0900 


Please enter the second time: 1730 
8 hours 30 minutes 


Extra credit if you can deal with the case where the first time is later than the second: 


Please enter the first time: 1730 
Please enter the second time: 0900 
15 hours 30 minutes 


74 Chapter 2 Fundamental Data Types 


ane P2.18 


aa P2.19 


aa P2.20 


ue P2,.21 


Writing large letters. A large letter H can be produced like this: 


It can be declared as a string literal like this: 
final string LETTERLH = "* = *\n* — *\n*****\n*  *\n*  *\n"5 
(The \n escape sequence denotes a “newline” character that causes subsequent 


characters to be printed on a new line.) Do the same for the letters E, L, and 0. Then 
write the message 


in large letters. 


Write a program that transforms numbers 1, 2, 3, ..., 12 
into the corresponding month names January, February, 
March, ..., December. Hint: Make a very long string "January 
February March ...", in which you add spaces such that each 
month name has the same length. Then use substring to 
extract the month you want. 


Write a program that prints a Christmas tree: 





Remember to use escape sequences. 


Easter Sunday is the first Sunday after the first full moon of spring. To compute 
the date, you can use this algorithm, invented by the mathematician Carl Friedrich 
Gauss in 1800: 


1. Lety be the year (such as 1800 or 2001). 

Divide y by 19 and call the remainder a. Ignore the quotient. 

Divide y by 100 to get a quotient b and a remainder c. 

Divide b by 4 to get a quotient d and a remainder e. 

Divide 8 * b + 13 by 25 to get a quotient g. Ignore the remainder. 

Divide 19 * a + b - d - g + 15 by 30to get a remainder h. Ignore the quotient. 
Divide c by 4 to get a quotient j and a remainder k. 


Divide a + 11 * h by 319 to get a quotient m. Ignore the remainder. 


ee 


Divide 2 *e+2*4j-k-h+m+ 32by7to getaremainder r. Ignore the 
quotient. 


ua Business P2.22 


== Business P2.23 


a= Business P2.24 


== Business P2.25 


= Business P2.26 


Programming Exercises 75 


10. Divide h - m+ r + 90 by 25 to get a quotient n. Ignore the remainder. 
11. Divide h - m+ r +n +19 by 32 to get a remainder p. Ignore the quotient. 


Then Easter falls on day p of month n. For example, if y is 2001: 


a=6 h = 18 n=4 
b= 20, c=1 720, kel p=15 
d=5,e=0 m= 0 
g = 6 r= 6 


Therefore, in 2001, Easter Sunday fell on April 15. Write a program that prompts the 
user for a year and prints out the month and day of Easter Sunday. 


The following pseudocode describes how a bookstore computes the price of an 
order from the total price and the number of the books that were ordered. 


Read the total book price and the number of books. 

Compute the tax (7.9 percent of the total book price). 

Compute the shipping charge (¢Z per book). 

The price of the order is the sum of the total book price, the tax, and the shipping charge. 
Print the price of the order. 


Translate this pseudocode into a Java program. 


The following pseudocode describes how to turn a string containing a ten-digit 

SP g g g 
phone number (such as "4155551212") into a more readable string with parentheses 
and dashes, like this: "(415) 555-1212". 


Take the substring consisting of the first three characters and surround it with “(" and “) ". This is the 
area code. 

Concatenate the area code, the substring consisting of the next three characters, a hyphen, and the 
substring consisting of the last four characters. This is the formatted number. 


Translate this pseudocode into a Java program that reads a telephone number into a 
string variable, computes the formatted number, and prints it. 


The following pseudocode describes how to extract the dollars and cents froma 
price given as a floating-point value. For example, a price 2.95 yields values 2 and 95 
for the dollars and cents. 


Assign the price to an integer variable dollars. 
Multiply the difference price - dollars by 100 and add 0.9. 
Assign the result to an integer variable cents. 


Translate this pseudocode into a Java program. Read a price and print the dollars and 
cents. Test your program with inputs 2.95 and 4.35. 


Giving change. Implement a program that directs a cashier 
how to give change. The program has two inputs: the 
amount due and the amount received from the customer. 
Display the dollars, quarters, dimes, nickels, and pennies 
that the customer should receive in return. In order to avoid 
roundoff errors, the program user should supply both 
amounts in pennies, for example 274 instead of 2.74. 





An online bank wants you to create a program that shows prospective customers 
how their deposits will grow. Your program should read the initial balance and the 


76 Chapter 2 Fundamental Data Types 


= Business P2.27 


= Science P2.28 


ua Science P2.29 


aaa Science P2.30 


annual interest rate. Interest is compounded monthly. Print out the balances after the 
first three months. Here is a sample run: 


Initial balance: 1000 
Annual interest rate in percent: 6.0 


After first month: 1005.00 
After second month: 1010.03 
After third month: 1015.08 


A video club wants to reward its best members with a discount based on the mem- 
ber’s number of movie rentals and the number of new members referred by the 
member. The discount is in percent and is equal to the sum of the rentals and the 
referrals, but it cannot exceed 75 percent. (Hint: Math.min.) Write a program Discount- 
Calculator to calculate the value of the discount. 


Here is a sample run: 


Enter the number of movie rentals: 56 
Enter the number of members referred to the video club: 3 
The discount is equal to: 59.00 percent. 


Consider the following circuit. 





Ry 


























Ry R3 





























Write a program that reads the resistances of the three resistors and computes the 
total resistance, using Ohm’s law. 


The dew point temperature 7, can be calculated (approximately) from the relative 
humidity RH and the actual temperature T by 





— b- f(T,RH) 
‘= 7~J(TRH) 
f(T,RH) = a + In(RH) 


where a = 17.27 and b = 237.7°C. 


Write a program that reads the relative humidity (between 0 and 1) and the tem- 
perature (in degrees C) and prints the dew point value. Use the Java function log to 
compute the natural logarithm. 


The pipe clip temperature sensors shown here are robust sensors that can be clipped 
directly onto copper pipes to measure the temperature of the liquids in the pipes. 


uae Science P2.31 


Programming Exercises 77 





Each sensor contains a device called a thermistor. Thermistors are semiconductor 
devices that exhibit a temperature-dependent resistance described by: 


1 1 
(ri 
R=R,e © 


where R is the resistance (in Q) at the temperature J (in °K), and Ro is the resistance 
(in Q) at the temperature 7) (in °K). B is a constant that depends on the material used 
to make the thermistor. Thermistors are specified by providing values for Ro, To, 


and p. 


The thermistors used to make the pipe clip temperature sensors have Rg = 1075 Q at 
Ty = 85 °C, and B = 3969 °K. (Notice that 6 has units of °K. Recall that the tempera- 
ture in °K is obtained by adding 273 to the temperature in °C.) The liquid tempera- 

ture, in °C, is determined from the resistance R, in Q, using 


BT 


R 
T, In| — 
0 Rs +B 


T= — 273 


Write a Java program that prompts the user for the thermistor resistance R and prints 
a message giving the liquid temperature in °C. 


The circuit shown below illustrates some impor- 
tant aspects of the connection between a power 
company and one of its customers. The customer is 
represented by three parameters, V,, P, and pf. V;is 
the voltage accessed by plugging into a wall outlet. 
Customers depend on having a dependable value 
of V, in order for their appliances to work prop- 
erly. Accordingly, the power company regulates 
the value of V, carefully. P describes the amount of 
power used by the customer and is the primary factor in determining the customer’s 
electric bill. The power factor, pf, is less familiar. (The power factor is calculated as 
the cosine of an angle so that its value will always be between zero and one.) In this 
problem you will be asked to write a Java program to investigate the significance of 
the power factor. 














R=10Q + 
Vv, V, = 120 Vrms 


R=10Q ee 


P=260 W 
pf=0.6 


Power Power Customer 
Company Lines 


78 Chapter 2 Fundamental Data Types 


uae Science P2.32 


« Science P2.33 


In the figure, the power lines are represented, somewhat simplistically, as resistances 
in Ohms. The power company is represented as an AC voltage source. The source 
voltage, V,, required to provide the customer with power P at voltage V, can be 
determined using the formula 


2 
2RP 2RP ; 
Vo =,/| V. + +| —— | (1- pf 
I Ms ) GF a | | 
(V, has units of Vrms.) This formula indicates that the value of V, depends on the 
value of pf. Write a Java program that prompts the user for a power factor value and 


then prints a message giving the corresponding value of V,, using the values for P, R, 
and V, shown in the figure above. 





Consider the following tuning circuit connected to an antenna, where C is a variable 


capacitor whose capacitance ranges from C),;, to C. 


min max’ 


Antenna 





, 2c 
I 


The tuning circuit selects the frequency f = aay To design this circuit for a given 
frequency, take C = JC, ;.C,.,., and calculate the required inductance L from f and 


or : 20 
C. Now the circuit can be tuned to any frequency in the range fixing = ——— 
20 LC nax 


Write a Java program to design a tuning circuit for a given frequency, using a variable 
capacitor with given values for C,,;, and Cyax. (A typical input is f= 16.7 MHz, 
Cymin = 14 pF, and C,,,, = 365 pF.) The program should read in f (in Hz), C. 


m 











to 


‘and 
Cymax (in F), and print the required inductance value and the range of frequencies to 
which the circuit can be tuned by varying the capacitance. 


According to the Coulomb force law, the electric force between two charged 
particles of charge Q; and Q, Coulombs, that are a distance r meters apart, is 


F= Rese Newtons, where € = 8.854 x 107!” Farads/meter. Write a program 
4mer 


that calculates the force ona pair of charged particles, based on the user input of Q, 
Coulombs, Q, Coulombs, and r meters, and then computes and displays the electric 
force. 


ANSWERS TO SELF-CHECK QUESTIONS 


1. 


10. 
11. 
12, 


13. 
14. 


15. 


16. 


One possible answer is 
int bottlesPerCase = 8; 


You may choose a different variable name or a 
different initialization value, but your variable 
should have type int. 


. There are three errors: 


= You cannot have spaces in variable names. 


« The variable type should be double because 
it holds a fractional value. 


= There is a semicolon missing at the end of 
the statement. 


double unitPrice = 1.95; 
jnt quantity = 2; 


System.out.print("Total price: "); 
System.out.printIn(unitPrice * quantity) ; 


Change the declaration of cansPerPack to 
int cansPerPack = 4; 


You need to use a */ delimiter to close a com- 
ment that begins with a /*: 


double canVolume = 0.355; 
/* Liters in a12-ounce can */ 


21. 


The program would compile, and it would 
display the same result. However, a person 
reading the program might find it confusing 
that fractional cans are being considered. 


Its value is modified by the assignment 
statement. 


. Assignment would occur when one car is 


replaced by another in the parking space. 
double interest = balance * percent / 100; 
double sideLength = Math. sqrt(area) ; 

4 * PI * Math.pow(radius, 3) / 3 

or (4.0 / 3) * PI * Math. pow(radius, 3), 
but not (4 / 3) * PI * Math. pow(radius, 3) 
172 and 9 


It is the second-to-last digit of n. For example, 
if nis 1729, thenn / 101s 172, and (n / 10) % 10 
is 2. 

System.out.print("How old are you? "); 

int age = in.nextIntQ; 

There is no prompt that alerts the program 
user to enter the quantity. 


17. 


18. 


20. 


22. 


23. 


Answers to Self-Check Questions 79 


The second statement calls nextInt, not next- 
Double. If the user were to enter a price such as 
1.95, the program would be terminated with an 
“jnput mismatch exception”. 


There is no colon and space at the end of the 
prompt. A dialog would look like this: 


Please enter the number of cans6 


. The total volume is 10 


There are four spaces between is and 10. One 
space originates from the format string (the 


space between s and %), and three spaces are 
added before 10 to achieve a field width of 5. 


Here is a simple solution: 


System.out.printf("Bottles: %8d\n", bottles); 
System.out.printf("Cans: %8d\n", cans); 
Note the spaces after Cans:. Alternatively, 
you can use format specifiers for the strings. 
You can even combine all output into a single 
statement: 


System. out. printf ("%-9s%8d\n%-9s%8d\n", 
"Bottles: ", bottles, "Cans:", cans); 
int pairs = (totalWidth - tileWidth) 

/ (2 * tileWidth); 
int tiles = 1+ 2 * pairs; 
double gap = (totalWidth - 

tiles * tileWidth) / 2.0; 
Be sure that pairs is declared as an int. 


Now there are groups of four tiles (gray/ 
white/gray/black) following the initial black 


tile. Therefore, the algorithm is now 


number of groups = integer part of (total width - tile width) / 
(4 x tile width) 

number of tiles = 1 + 4 x number of groups 

The formula for the gap is not changed. 

Clearly, the answer depends only on whether 

the row and column numbers are even or odd, 

so let’s first take the remainder after divid- 

ing by 2. Then we can enumerate all expected 

answers: 


Row%Z Column%Z Color 
0 0 0 


0 1 1 
1 0 1 
1 1 0 


80 Chapter 2 Fundamental Data Types 


24. 


25. 


In the first three entries of the table, the color 
is simply the sum of the remainders. In the 
fourth entry, the sum would be 2, but we want 
a zero. We can achieve that by taking another 
remainder operation: 

color = ((row % Z) * (column % 2) % Z 

In nine years, the repair costs increased by 
$1,400. Therefore, the increase per year is 
$1,400 /9 ~ $156. The repair cost in year 3 
would be $100 + 2 x $156 = $412. The repair 
cost in year nis $100 + nx $156. To avoid 
accumulation of roundoff errors, it is actually 


a good idea to use the original expression that 
yielded $156, that is, 


Repair cost in year n= 100 +nx 140079 

The pseudocode follows easily from the 
equations: 

bottom volume = zt x ry? x hy 

top volume = a x rg? x hg 

middle volume = zr x (r,? try xX ryt 17) x hg / 3 
total volume = bottom volume * top volume * middle volume 


26. 


27. 
28. 
29. 
30. 


Measuring a typical wine bottle yields 
N= 3.6, N= 1.2, hy = 15, 44= 7; h; =6 
(all in centimeters). Therefore, 
bottom volume = 610.73 

top volume = 31.67 

middle volume = 135.72 

total volume = 778.12 


The actual volume is 750 ml, which is close 
enough to our computation to give confidence 
that it is correct. 


The length is 12. The space counts as a 
character. 


str.substring(8, 12) or str.substring(8) 
str = str + "ming"; 
Hy 


String first = in.nextQ); 
String middle = in.nextQ; 
String last = in.nextQ); 


TTS 3 
DECISIONS 


CHAPTER GOALS 


To implement decisions using if 
statements 





To compare integers, floating-point numbers, and strings 
To write statements using the Boolean data type 
To develop strategies for testing your programs 


To validate user input 


CHAPTER CONTENTS 


3.1 THEIFSTATEMENT 82 3.4 NESTED BRANCHES 100 
Syntax 3.1: if Statement 84 Programming Tip 3.5: Hand-Tracing 103 
Programming Tip 3.1: Brace Layout 86 Common Error 3.4: The Dangling else Problem 104 
Programming Tip 3.2: Always Use Braces 86 Special Topic 3.4: Enumeration Types 105 
Common Error 3.1: A Semicolon After the Video Example 3.1: Computing the Plural of an 

if Condition 86 English Word @ 


Programming Tip 3.3: Tabs 87 


‘ f st 3.5 PROBLEM SOLVING: FLOWCHARTS 105 
Special Topic 3.1: The Conditional Operator 87 


Programming Tip 3.4: Avoid 3.6 PROBLEM SOLVING: TEST CASES 108 
Duplication in Branches 88 Programming Tip 3.6: Make a Schedule and Make 
3.2 COMPARING NUMBERS Time for Unexpected Problems 109 
AND STRINGS 88 Special Topic 3.5: Logging 110 
Syntax 3.2: Comparisons 89 3.7 BOOLEAN VARIABLES 
Common Error 3.2: Exact Comparison of AND OPERATORS 111 
Floating-Point Numbers 91 Common Error 3.5: Combining Multiple 
Common Error 3.3: Using ==to Compare Strings 92 Relational Operators 113 
Special Topic 3.2: Lexicographic Ordering Common Error 3.6: Confusing && and || 
of Strings 92 Conditions 114 
How To 3.1: Implementing an if Statement 93 Special Topic 3.6: Short-Circuit Evaluation of 
Worked Example 3.1: Extracting the Middle @ Boolean Operators 114 
Random Fact 3.1: The Denver Airport Luggage Special Topic 3.7: De Morgan’s Law 115 
Handling >yotein 2° 3.8 APPLICATION: INPUT VALIDATION 116 
3.3 MULTIPLE ALTERNATIVES 96 Video Example 3.2: The Genetic Code @ 
Special Topic 3.3: The switch Statement 99 Random Fact 3.2: Artificial Intelligence 119 


One of the essential features of computer programs is 
their ability to make decisions. Like a train that changes 
tracks depending on how the switches are set, a program 
can take different actions depending on inputs and other 
circumstances. 


In this chapter, you will learn how to program simple and 
complex decisions. You will apply what you learn to the 
task of checking user input. 





3.1 The if Statement 


San ees Oh The if statement is used to implement a decision (see Syntax 3.1). When a condition is 
allows a program to fulfilled, one set of statements is executed. Otherwise, another set of statements is 
carry out different executed. 
Fe ace ae Here is an example using the if statement: In 
to be processed. many countries, the number 13 is considered 
unlucky. Rather than offending superstitious ten- 
ants, building owners sometimes skip the thir- 
teenth floor; floor 12 is immediately followed by 
floor 14. Of course, floor 13 is not usually left 
empty or, as some conspiracy theorists believe, 
filled with secret offices and research labs. It is 
simply called floor 14. The computer that controls 
the building elevators needs to compensate for 
this foible and adjust all floor numbers above 13. 
Let’s simulate this process in Java. We will ask 
the user to type in the desired floor number and 
then compute the actual floor. When the input is 
above 13, then we need to decrement the input to 
obtain the actual floor. For example, if the user — This elevator panel “skips” the 
: : : thirteenth floor. The floor is not 
provides an input of 20, the program determines 7, li missing the communes 
the actual floor as 19. Otherwise, we simply use 


: that controls the elevator adjusts 
the supplied floor number. the floor numbers above 13. 





jnt actualFloor; 


if (floor > 13) 


{ 
actualFloor = floor - 1; 
} 
else 
{ 
actualFloor = floor; 
} 


The flowchart in Figure 1 shows the branching behavior. 
In our example, each branch of the if statement contains a single statement. You 
can include as many statements in each branch as you like. Sometimes, it happens that 


82 


3.1 TheifStatement 83 


Condition 
No else branch 
Ty Fal. True False 
“4. > floor > 13? 
actualFloor = actualFloor = detualElOOr== 
floor - 1 floor 
Figure 1 Figure 2 
Flowchart for if Statement Flowchart for if Statement with No else Branch 


there is nothing to do in the else branch of the statement. In that case, you can omit it 
entirely, such as in this example: 


jnt actualFloor = floor; 
if (floor > 13) 


{ 
actualFloor--; 
+ // No else needed 


See Figure 2 for the flowchart. 


An if statement is like a fork in 
the road. Depending upona 
decision, different parts of the 
program are executed. 





84 Chapter3 Decisions 


Syntax 3.1 if Statement 


if (condition) 


statements 


} 


Braces are not required 

if the branch contains a 
single statement, but it's 
good to always use them. 


_& See page 86. 


Omit the else branch 
if there is nothing to do. 


ss 


F 
{ 
} 
e 


{ 
} 


if (condition) { statements, } 
else { statements, } 


A condition that is true or false. 


Often uses relational operators: 
. == |= < <= > >= (See page 89.) 


f (floor > 13) Don't put a semicolon here! 


as See page $6. 
actualFloor = floor - HK 


Ise If the condition is true, the statement(s) 
_ in this branch are executed in sequence; 


if the condition is false, they are skipped. 





actualFloor = floor; Pe 


If the condition is false, the statement(s) 
in this branch are executed in sequence; 


Lining up braces if the condition is true, they are skipped. 





is a good idea. 
See page 36. 


The following program puts the if statement to work. This program asks for the 
desired floor and then prints out the actual floor. 


section_1/ElevatorSimulation.java 


1 


jmport java.util.Scanner; 


[* * 


This program simulates an elevator panel that skips the 13th floor. 


public class ElevatorSimulation 


{ 


public static void main(String[] args) 


{ 


Scanner in = new Scanner(System. in) ; 
System.out.print('Floor: "); 
int floor = in.nextIntQ; 


// Adjust floor if necessary 


int actualFloor; 
if (floor > 13) 
{ 
actualFloor = floor - 1; 
} 
else 


{ 


3.1 Theif Statement 8&5 


23 actualFloor = floor; 
24 } 


" 


26 System.out.printIn("The elevator will travel to the actual floor 
ih + actualFloor); 


Program Run 


Floor: 20 
The elevator will travel to the actual floor 19 


1. Insome Asian countries, the number 14 is considered unlucky. Some building 
owners play it safe and skip both the thirteenth and the fourteenth floor. How 
would you modify the sample program to handle such a building? 





2. Consider the following if statement to compute a discounted price: 
if (originalPrice > 100) 


{ 

discountedPrice = originalPrice - 20; 
} 
else 
{ 

discountedPrice = originalPrice - 10; 
} 


What is the discounted price if the original price is 95? 100? 105? 
3. Compare this if statement with the one in Self Check 2: 
if (originalPrice < 100) 


{ 

discountedPrice = originalPrice - 10; 
} 
else 
{ 

discountedPrice = originalPrice - 20; 
} 


Do the two statements always compute the same value? If not, when do the 
values differ? 


4. Consider the following statements to compute a discounted price: 


discountedPrice = originalPrice; 
if (originalPrice > 100) 
{ 


discountedPrice = originalPrice - 10; 
} 
What is the discounted price if the original price is 95? 100? 105? 

5. The variables fuelAmount and fuelCapacity hold the actual amount of fuel and the 
size of the fuel tank of a vehicle. If less than 10 percent is remaining in the tank, a 
status light should show a red color; otherwise it shows a green color. Simulate 
this process by printing out either "red" or "green". 


Practice It Now youcantry these exercises at the end of the chapter: R3.5, R3.6, P3.31. 


86 Chapter3 Decisions 


Programming Tip 3.1 Brace Layout 


The compiler doesn’t care where you place 
braces. In this book, we follow the simple rule 
of making { and } line up. 


if (floor > 13) 
{ 


floor--; 
} 
This style makes it easy to spot matching 
braces. Some programmers put the opening 
brace on the same line as the if: 





if (floor > 13) { Properly lining up your code makes your pro- 
floor--; grams easier to read. 


} 


This style makes it harder to match the braces, but it saves a line of code, allowing you to view 
more code on the screen without scrolling. There are passionate advocates of both styles. 

It is important that you pick a layout style and stick with it consistently within a given 
programming project. Which style you choose may depend on your personal preference or a 
coding style guide that you need to follow. 


Jecieuuiciiec ) Always Use Braces 


When the body of an if statement consists of a single statement, you need not use braces. For 
example, the following is legal: 
if (floor > 13) 
floor--; 
However, it is a good idea to always include the braces: 


if (floor > 13) 
{ 


floor--; 
} 
The braces make your code easier to read. They also make it easier for you to maintain the 
code because you won’t have to worry about adding braces when you add statements inside 
an if statement. 


A Semicolon After the if Condition 


Common Error 3.1 
The following code fragment has an unfortunate error: 


if (floor > 13) ; // ERROR 
{ 


floor--; 
} 
There should be no semicolon after the if condition. The compiler interprets this statement as 
follows: If floor is greater than 13, execute the statement that is denoted by a single semicolon, 
that is, the do-nothing statement. The statement enclosed in braces is no longer a part of the if 





ecole leclaalaaliale mil oor) 








Special Topic 3.1 
he 


3.1 TheifStatement 87 


statement. It is always executed. In other words, even if the value of floor is not above 13, it is 
decremented. 


Tabs 


Block-structured code has the property that nested statements are indented by one or more 
levels: 


public class ElevatorSimulation 













{ 
public static void main(String[] args) 
{ 
int floor; 
if (floor > 13) 
{ 
| floor--; You use 
} the Tab key 
to move the 
} cursor to the next 
| | indentation level. 
0 1 2 3. Indentation level 


How do you move the cursor from the leftmost column to the appropriate indentation level? 
A perfectly reasonable strategy is to hit the space bar a sufficient number of times. With most 
editors, you can use the Tab key instead. A tab moves the cursor to the next indentation level. 
Some editors even have an option to fill in the tabs automatically. 

While the Tab key is nice, some editors use tab characters for alignment, which is not so 
nice. Tab characters can lead to problems when you send your file to another person or a 
printer. There is no universal agreement on the width of a tab character, and some software 
willignore tab characters altogether. It is therefore best to save your files with spaces instead of 
tabs. Most editors have a setting to automatically convert all tabs to spaces. Look at the docu- 
mentation of your development environment to find out how to activate this useful setting. 


The Conditional Operator 


Java has a conditional operator of the form 
condition ? value, : value 


The value of that expression is either value, if the test passes or value if it fails. For example, 
we can compute the actual floor number as 
actualFloor = floor > 13 ? floor - 1: floor; 
which is equivalent to 
if (floor > 13) { actualFloor = floor - 1; } else { actualFloor = floor; } 
You can use the conditional operator anywhere that a value is expected, for example: 
System.out.printIn("Actual floor: " + (floor > 13 ? floor - 1: floor)); 


We don’t use the conditional operator in this book, but it is a convenient construct that you 
will find in many Java programs. 


88 Chapter3 Decisions 


Programming Tip 3.4 Avoid Duplication in Branches 


Look to see whether you duplicate code in each branch. If so, move it out of the if statement. 
Here is an example of such duplication: 


if (floor > 13) 


{ 

actualFloor = floor - 1; 

System.out.printIn("Actual floor: " + actualFloor); 
} 
else 
{ 

actualFloor = floor; 

System.out.printIn("Actual floor: " + actualFloor); 
} 


The output statement is exactly the same in both branches. This is not an error—the program 
will run correctly. However, you can simplify the program by moving the duplicated state- 
ment, like this: 


if (floor > 13) 


{ 
actualFloor = floor - 1; 
} 
else 
{ 
actualFloor = floor; 
} 


System.out.printIn("Actual floor: " + actualFloor); 


Removing duplication is particularly important when programs are maintained for a long 
time. When there are two sets of statements with the same effect, it can easily happen that a 
programmer modifies one set but not the other. 


2 mparing Numbers an rin 


Teena Every if statement contains a condi- he 

operators tion. In many cases, the condition 

(< <= > >= == !=) involves comparing two values. For 

tocomparenumbers. — ¢xample, in the previous examples we 
tested floor > 13. The comparison > is 
called a relational operator. Java has 
six relational operators (see Table 1). 

As you can see, only two Java rela- 
tional operators (> and <) look as you 
would expect from the mathematical 
notation. Computer keyboards do not 
have keys for =, s, or #, but the >=, <s, 
and != operators are easy to remember 
because they look similar. The == opera- 





eee : In Java, you use a relational operator to check 
tor is initially confusing to most new- whether one value is greater than another. 


comers to Java. 


3.2 Comparing Numbers and Strings 89 


Table 1 Relational Operators 


Java Math Notation Description 
> > Greater than 
>= = Greater than or equal 
< < Less than 
<= < Less than or equal 
= = Equal 
le # Not equal 


In Java, = already has a meaning, namely assignment. The == operator denotes equality 
testing: 


floor = 13; // Assign 13 to floor 
if (floor == 13) // Test whether floor equals 13 


You must remember to use == inside tests and to use = outside tests. 


Syntax 3.2 Comparisons 


These quantities are compared. 


floor > 13 


Check that you have the right direction: 0 ee tSea'page #9. 
Mme OT; == != < <= > >= a . 


> (greater) or < (less) 


Check the boundary condition: 
> (greater) or >= (greater or equal)? floor == 13 


* Checks for equality. 


String input; 
if Cinput.equals("Y")) 


\ Use equals to compare strings. (See page 92.) 


double x; double y; final double EPSILON = 1E-14; 
if (Math.abs(x - y) < EPSILON) 


we 


Checks that these floating-point numbers are very close. 


AG See page 91. 





90 Chapter3 Decisions 


ONLINE EXAMPLE 


A program that 
demonstrates 


comparisons of 


The relational operators in Table 1 have a lower precedence than the arithmetic opera- 


tors. That means, you can write arithmetic expressions on either side of the relational 


numbers and strings. floor - 1 < 13 


Do not use the == 
operator to compare 


strings. Use the 
equals method 
instead. 


operator without using parentheses. For example, in the expression 


both sides (floor - 1 and 13) of the < operator are evaluated, and the results are com- 
pared. Appendix B shows a table of the Java operators and their precedence. 
To test whether two strings are equal to each other, you must use the method called 


equals: 


if (stringl.equals(string2)) . 


Do not use the == operator to compare strings. The comparison 


if (stringl == string2) // Not useful 


has an unrelated meaning. It tests whether the two strings are stored in the same loca- 

tion. You can have strings with identical contents stored in different locations, so this 

test never makes sense in actual programming; see Common Error 3.3 on page 92. 
Table 2 summarizes how to compare values in Java. 


Table 2 Relational Operator Examples 


Expression 


3=6/2 


1.0 / 3.0 == 0.333333333 


"10" 5 5 


"Tomato".substring(0, 3).equals("Tom") 


"Tomato".substring(0, 3) == ("Tom") 


Value 
true 


Error 


false 


false 


true 


true 
true 
Error 


false 


Error 


true 


false 


Comment 
3 is less than 4; <= tests for “less than or equal”. 


The “less than or equal” operator is <=, not =<. 
The “less than” symbol comes first. 


> is the opposite of <-. 


The left-hand side must be strictly smaller than 
the right-hand side. 


Both sides are equal; <+ tests for “less than or 
equal”. 


== tests for equality. 
|= tests for inequality. It is true that 3 is not 5-1. 
Use == to test for equality. 


Although the values are very close to one 
another, they are not exactly equal. See Common 
Error 3.2 on page 91. 


You cannot compare a string to a number. 


Always use the equals method to check whether 
two strings have the same contents. 


Never use == to compare strings; it only checks 
whether the strings are stored in the same 
location. See Common Error 3.3 on page 92. 





SELF CHECK 
¢ 





Practice It 


(@loyaalankelamaane) mci 








3.2 Comparing Numbers and Strings 91 


6. Which of the following conditions are true, provided a is 3 and b is 4? 
aatl<«b 
b.a+1>=b 


c a+1!=b 


7. Give the opposite of the condition 
floor > 13 


8. What is the error in this statement? 


if (scoreA = scoreB) 


{ 


System.out.printIn("Tie"); 


} 


9. Supply a condition in this if statement to test whether the user entered a Y: 


System.out.printIn("Enter Y to quit."); 
String input = in.next(); 


At Ga a: 2) 
{ 

System.out.printIn("Goodbye."); 
} 


10. How do you test that a string str is the empty string? 


Now you can try these exercises at the end of the chapter: R3.4, R3.7, P3.18. 


Exact Comparison of Floating-Point Numbers 


Floating-point numbers have only a limited precision, and cal- 
culations can introduce roundoff errors. You must take these 
inevitable roundoffs into account when comparing floating- 
point numbers. For example, the following code multiplies the 
square root of 2 by itself. Ideally, we expect to get the answer 2: 


double r = Math.sqrt(2.0); 
if (r * r == 2.0) 





{ 

System.out.printIn("Math.sqrt(2.0) squared is 2.0"); Take limited precision into 
} account when comparing 
else floating-point numbers. 
{ 

System.out.printIn("Math.sqrt(2.0) squared is not 2.0 but " 

saan dca oD 
} 
This program displays 


Math.sqrt(2.0) squared is not 2.0 but 2.00000000000000044 


It does not make sense in most circumstances to compare floating-point numbers exactly. 
Instead, we should test whether they are close enough. That is, the magnitude of their differ- 
ence should be less than some threshold. Mathematically, we would write that x and y are close 
enough if 


|x-yl<e 


92 Chapter3 Decisions 


(@foyaalankelam ane) mci) 


Special Topic 3.2 





for a very small number, «. ¢ is the Greek letter epsilon, a letter used to denote a very small 
quantity. It is common to set ¢ to 107! when comparing double numbers: 


final double EPSILON = 1E-14; 
double r = Math.sqrt(2.0); 
if (Math.abs(r * r - 2.0) < EPSILON) 


{ 
System.out.printIn("Math.sqrt(2.0) squared is approximately 2.0"); 


} 


Using == to Compare Strings 
If you write 
if (nickname == "Rob") 


then the test succeeds only if the variable nickname refers to the exact same location as the string 
literal "Rob". The test will pass if a string variable was initialized with the same string literal: 


String nickname = "Rob"; 


if (nickname == "Rob") // Test is true 


However, if the string with the letters R 0 b has been assembled in some other way, then the test 


will fail: 


String name = "Robert"; 
String nickname = name.substring(0, 3); 


if (nickname == "Rob") // Test is false 


In this case, the substring method produces a string in a different memory location. Even 
though both strings have the same contents, the comparison fails. 

You must remember never to use == to compare strings. Always use equals to check whether 
two strings have the same contents. 


Lexicographic Ordering of Strings 


If two strings are not identical to each other, you still 
may want to know the relationship between them. The 
compareTo method compares strings in “lexicographic” 
order. This ordering is very similar to the way in which 
words are sorted ina dictionary. If 


stringl.compareTo(string2) < 0 


then the string string1 comes before the string string2 
in the dictionary. For example, this is the case if stringl 
is "Harry", and string2 is "Hello". If 





To see which of two terms comes 


a ot first in the dictionary, consider the 
then string1 comes after string2 in dictionary order. first letter in which they differ. 


Finally, if 


stringl.compareTo(string2) > 0 


stringl.compareTo(string2) == 


then string1 and string2 are equal. 


3.2 Comparing Numbers and Strings 93 


There are a few technical differences between the ordering in a 


a : : Pane The compareTo 
dictionary and the lexicographic ordering in Java. In Java: f 


method compares 
e Alluppercase letters come before the lowercase letters. For strings in 
example, "2" comes before "a". lexicographic order. 


e The space character comes before all printable characters. 
e¢ Numbers come before letters. 
e For the ordering of punctuation marks, see Appendix A. 


When comparing two strings, you compare the first letters of each 

word, then the second letters, and so on, until one of the strings ends 

or you find the first letter pair that doesn’t match. Clalrle 
If one of the strings ends, the longer string is considered the 

“larger” one. For example, compare "car" with "cart". The first 

three letters match, and we reach the end of the first string. There- 

fore "car" comes before "cart" in lexicographic ordering. Sy Ne 
When you reach a mismatch, the string containing the “larger” : paps 

character is considered “larger”. For example, let’s compare "cat" ™7_ Deore E 

with "cart". The first two letters match. Because t comes after r, the — Lexicographic 

string "cat" comes after "cart" in the lexicographic ordering. Ordering 


ea Kae ac 


LO)’ Os ea | Implementing an if Statement 






This How To walks you through the process of implementing an if statement. We will illus- 
trate the steps with the following example problem: 

The university bookstore has a Kilobyte Day sale every October 24, giving an 8 percent 
discount on all computer accessory purchases if the price is less than $128, and a 16 percent 
discount if the price is at least $128. Write a program that asks the cashier for the original price 
and then prints the discounted price. 


Step 1 Decide upon the branching condition. 


In our sample problem, the obvious choice for the 
condition is: 


original price < 1237 


That is just fine, and we will use that condition in 
our solution. 

But you could equally well come up with a 
correct solution if you choose the opposite condi- 
tion: Is the original price at least $128? You might 
choose this condition if you put yourself into the Sales discounts are often higher for 
position of a shopper who wants to know when expensive products. Use the if statement 
the bigger discount applies. to implement such a decision. 





Step 2 Give pseudocode for the work that needs to be 
done when the condition is true. 


In this step, you list the action or actions that are taken in the “positive” branch. The details 
depend on your problem. You may want to print a message, compute values, or even exit the 
program. 


94 Chapter3 Decisions 


Step 3 


Step 4 


Step 5 


Step 6 


Step 7 


In our example, we need to apply an 8 percent discount: 
discounted price = 0.92 x original price 
Give pseudocode for the work (if any) that needs to be done when the condition is vot true. 


What do you want to do in the case that the condition of Step 1 is not satisfied? Sometimes, 
you want to do nothing at all. In that case, use an if statement without an else branch. 

In our example, the condition tested whether the price was less than $128. If that condition 
is not true, the price is at least $128, so the higher discount of 16 percent applies to the sale: 


discounted price = 0.84 x original price 
Double-check relational operators. 


First, be sure that the test goes in the right direction. It is a common error to confuse > and <. 
Next, consider whether you should use the < operator or its close cousin, the <= operator. 

What should happen if the original price is exactly $128? Reading the problem carefully, we 
find that the lower discount applies if the original price is less than $128, and the higher dis- 
count applies when it is at least $128. A price of $128 should therefore vot fulfill our condition, 
and we must use <, not <=. 


Remove duplication. 


Check which actions are common to both branches, and move them outside. (See Program- 
ming Tip 3.4 on page 88.) 

In our example, we have two statements of the form 

discounted price = __ x original price 
They only differ in the discount rate. It is best to just set the rate in the branches, and to do the 
computation afterwards: 

If original price < 128 

discount rate = 0.92 
Else 


discount rate = 0.84 
discounted price = discount rate x original price 


Test both branches. 


Formulate two test cases, one that fulfills the condition of the if statement, and one that does 
not. Ask yourself what should happen in each case. Then follow the pseudocode and act each 
of them out. 

In our example, let us consider two scenarios for the original price: $100 and $200. We 
expect that the first price is discounted by $8, the second by $32. 

When the original price is 100, then the condition 100 < 128 is true, and we get 


discount rate = 0.92 
discounted price = 0.92 x 100 = 92 


When the original price is 200, then the condition 200 < 128 is false, and 


discount rate = 0.84 
discounted price = 0.84 x 200 = 168 


In both cases, we get the expected answer. 
Assemble the if statement in Java. 


Type the skeleton 


if © 
{ 


@ The complete 


} 
else 
{ 
} 


3.2 Comparing Numbers and Strings 


95 


and fill it in, as shown in Syntax 3.1 on page 84. Omit the else branch if it is not needed. 
In our example, the completed statement is 


if (originalPrice < 128) 


program for } 
calculating a 
discounted price. 








Making decisions is 
an essential part of 
any computer program. Nowhere is 
this more obvious than in a computer 
system that helps sort luggage at an 
airport. After scanning the luggage 
identification codes, the system sorts 
the items and routes them to differ- 
ent conveyor belts. Human operators 
then place the items onto trucks. When 
the city of Denver built a huge airport 
to replace an outdated and congested 
facility, the luggage system contractor 
went a step further. The new system 
was designed to replace the human 
Operators with robotic carts. Unfortu- 
nately, the system plainly did not 
work. It was plagued by mechanical 
problems, such as luggage falling onto 
the tracks and jamming carts. Equally 
frustrating were the software glitches. 
Carts would uselessly accumulate at 
some locations when they were needed 
elsewhere. 





discountedPrice 


{ 
discountRate = 0.92; 
} 
else 
{ 
discountRate = 0.84; 


discountRate * originalPrice; 


WORKED EXAMPLE 3.1 Extracting the Middle 


+ This Worked Example shows how to extract the middle character from a 
string, or the two middle characters if the length of the string is even. 


The airport had been scheduled 
to open in 1993, but without a func- 
tioning luggage system, the opening 
was delayed for over a year while the 
contractor tried to fix the problems. 
The contractor never succeeded, 
and ultimately a manual system was 
installed. The delay cost the city and 
airlines close to a billion dollars, and 
the contractor, once the leading lug- 
gage systems vendor in the United 
States, went bankrupt. 

Clearly, it is very risky to build a 
large system based on a technology 
that has never been tried on a smaller 
scale. As robots and the software that 
controls them get better over time, 
they will take on a larger share of lug- 
gage handling in the future. But it is 
likely that this will happen in an incre- 
mental fashion. 


rit 
3 


(E 
@ i 2 


Random Fact 3.1 The Denver Airport Luggage Handling System 





The Denver airport originally had a 
fully automatic system for moving lug- 
gage, replacing human operators with 
robotic carts. Unfortunately, the sys- 
tem never worked and was dismantled 
before the airport was opened. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


96 Chapter3 Decisions 


3.3 Multiple Al | 


Multiple if 
statements can be 
combined to evaluate 
complex decisions. 


The 1989 Loma Prieta 
earthquake that 
damaged the Bay 
Bridge in San Francisco 
and destroyed many 
buildings measured 7.1 
on the Richter scale. 





rT 
ANIMATION 
Multiple Alternatives 


it 


In Section 3.1, you saw how to program a two-way branch with an if statement. In 
many situations, there are more than two cases. In this section, you will see how to 
implement a decision with multiple alternatives. 

For example, consider a program that displays the effect of an earthquake, as mea- 
sured by the Richter scale (see Table 3). 


Table 3 Richter Scale 
Value Effect 
8 Most structures fall 
7 Many buildings destroyed 


6 Many buildings considerably 
damaged, some collapse 


4.5 Damage to poorly constructed 
buildings 





The Richter scale is a measurement of the strength of an earthquake. Every step in 
the scale, for example from 6.0 to 7.0, signifies a tenfold increase in the strength of the 
quake. 

In this case, there are five branches: one each for the four descriptions of damage, 
and one for no destruction. Figure 3 shows the flowchart for this multiple-branch 
statement. 

You use multiple if statements to implement multiple alternatives, like this: 

if Crichter >= 8.0) 

{ 


System.out.printIn("Most structures fall"); 


} 
else if (richter >= 7.0) 


oa 


System.out.printIn("Many buildings destroyed") ; 


} 
else if C(richter >= 6.0) 


{ 


System.out.printIn("Many buildings considerably damaged, some collapse"); 


} 


else if (richter >= 4.5) 


{ 


System.out.printIn("Damage to poorly constructed buildings"); 


} 


else 


f 


System.out.printIn("No destruction of buildings"); 


} 


As soon as one of the four tests succeeds, the effect is displayed, and no further tests 
are attempted. If none of the four cases applies, the final else clause applies, and a 
default message is printed. 


3.3 Multiple Alternatives 97 


False 
True 
False 


Here you must sort the conditions and test against the largest cutoff first. 
Suppose we reverse the order of tests: 


Figure 3 
Multiple Alternatives 













if (richter >= 4.5) // Tests in wrong order 
{ 


System.out.printIn("Damage to poorly constructed buildings"); 


else if (richter >= 6.0) 
{ 


} 
else if (richter >= 7.0) 
{ 


System.out.printIn("Many buildings considerably damaged, some collapse"); 


System.out.printIn("Many buildings destroyed"); 


98 Chapter3 Decisions 


else if C(richter >= 8.0) 


{ 
System.out.printIn("Most structures fall"); 
} 
This does not work. Suppose the value of richter is 7.1. That value is at least 4.5, 
When using multiple ‘ : 
if statements, test matching the first case. The other tests will never be attempted. 
general conditions The remedy is to test the more specific conditions first. Here, the condition 


after more specific 


oe richter >= 8.0 is more specific than the condition richter >= 7.0, and the condition 
conditions. 


richter >= 4.5 is more general (that is, fulfilled by more values) than either of the first 
two. 

In this example, it is also important that we use an if/else if/else sequence, not 
just multiple independent if statements. Consider this sequence of independent tests. 


if (richter >= 8.0) // Didn’t use else 
{ 


System.out.printIn("Most structures fall"); 


if Crichter >= 7.0) 


{ 
System.out.printIn("Many buildings destroyed") ; 
} 
if Crichter >= 6.0) 
{ 


System.out.printIn("Many buildings considerably damaged, some collapse"); 


if Crichter >= 4.5) 
{ 


The complete System.out.printIn("Damage to poorly constructed buildings"); 


program for printing } 
earthquake N he al ; ] lusi If rich is 7.1, th he | h 
descriptions. ow the alternatives are no onger exclusive. richter 1s 7.1, then the last trree tests 


all match, and three messages are printed. 





11. Ina game program, the scores of players A and B are stored in variables scoreA 
and scoreB. Assuming that the player with the larger score wins, write an if/ 


else if/else sequence that prints out "A won", "B won", or "Game tied". 


SELF CHECK 


f 





12. Write a conditional statement with three branches that sets s to 1 if x is positive, 
to -1 if x is negative, and to O if x is zero. 


13. How could you achieve the task of Self Check 12 with only two branches? 
14. Beginners sometimes write statements such as the following: 


if (price > 100) 
{ 


discountedPrice = price - 20; 


} 
else if (price <= 100) 
{ 


} 


Explain how this code can be improved. 


discountedPrice = price - 10; 


15. Suppose the user enters -1 into the earthquake program. What is printed? 


Practice It 


Special Topic 3.3 








3.3 Multiple Alternatives 99 


16. Suppose we want to have the earthquake program check whether the user en- 
tered a negative number. What branch would you add to the if statement, and 
where? 


Now you can try these exercises at the end of the chapter: R3.22, P3.9, P3.34. 


The switch Statement 


An if/else if/else sequence that compares a value against several alternatives can be imple- 
mented as a switch statement. For example, 





int digit=.. .; 
switch (digit) 
{ 
case 1: digitName = "one"; break; 
case 2: digitName = "two"; break; 
case 3: digitName = "three"; break; 
case 4: digitName = "four"; break; 
case 5: digitName = "five"; break; 
case 6: digitName = "six"; break; 
case 7: digitName = "seven"; break; 
case 8: digitName = "eight"; break; 
case 9: digitName = "nine"; break; 
default: digitName = ""; break; The switch statement lets you choose 
} from a fixed set of alternatives. 


This is a shortcut for 


int digit=...; 

if (digit == 1) { digitName = "one"; } 

else if (digit == 2) { digitName = "two"; } 
else if (digit == 3) { digitName = "three"; } 
else if (digit == 4) { digitName = "four"; } 
else if (digit == 5) { digitName = "five"; } 
else if (digit == 6) { digitName = "six"; } 
else if (digit == 7) { digitName = "seven"; } 
else if (digit == 8) { digitName = "eight"; } 
else if (digit == 9) { digitName = "nine"; } 
else { digitName = ""; } 


It isn’t much of a shortcut, but it has one advantage—it is obvious that all branches test the 
same value, namely digit. 

The switch statement can be applied only in narrow circumstances. The values in the case 
clauses must be constants. They can be integers or characters. As of Java 7, strings are permit- 
ted as well. You cannot use a switch statement to branch on floating-point values. 

Every branch of the switch should be terminated by a break instruction. If the break is miss- 
ing, execution falls through to the next branch, and so on, until a break or the end of the switch 
is reached. In practice, this fall-through behavior is rarely useful, but it is a common cause 
of errors. If you accidentally forget a break statement, your program compiles but executes 
unwanted code. Many programmers consider the switch statement somewhat dangerous and 
prefer the if statement. 

We leave it to you to use the switch statement for your own code or not. At any rate, you 
need to have a reading knowledge of switch in case you find it in other programmers’ code. 


100 Chapter 3 Decisions 


___3.4 Nested Branches 


a It is often necessary to include an if statement inside another. Such an arrangement is 
When a decision 


statement is called a nested set of statements. 

contained inside the Here is a typical example: In the United States, different tax rates are used depend- 
eee Enea ing on the taxpayer’s marital status. There are different tax schedules for single and 
TRAST for married taxpayers. Married taxpayers add their income together and pay taxes on 
are nested. the total. Table 4 gives the tax rate computations, using a simplification of the sched- 


ules in effect for the 2008 tax year. A different tax rate applies to each “bracket”. In 
this schedule, the income in the first bracket is taxed at 10 percent, and the income in 
the second bracket is taxed at 25 percent. The income limits for each bracket depend 
on the marital status. 


Table 4 Federal Tax Rate Schedule 


If your status is Single and 


if the taxable income is the tax is of the amount over 
at most $32,000 10% $0 
over $32,000 $3,200 + 25% $32,000 
If your status is Married and 
if the taxable income is the tax is of the amount over 
at most $64,000 10% $0 
over $64,000 $6,400 + 25% $64,000 


ee eees Now compute the taxes due, given a marital status and an income figure. The key 
are required for point is that there are two /evels of decision making. First, you must branch on the 
problems that marital status. Then, for each marital status, you must have another branch on income 
have two levels of level. 

decision making. oe a : F : 

The two-level decision process is reflected in two levels of if statements in the pro- 
gram at the end of this section. (See Figure 4 for a flowchart.) In theory, nesting can go 
deeper than two levels. A three-level decision process (first by state, then by marital 
status, then by income level) requires three nesting levels. 





hm 
ANIMATION 
Nested Branches 


['\ 


Computing income taxes requires 
multiple levels of decisions. 





3.4 Nested Branches 101 


True True 
False False 






eo 
a 





Figure 4 Income Tax Computation 


section_4/TaxCalculator.java 


1 import java.util.Scanner; 


2 

3 [** 

4 This program computes income taxes, using a simplified tax schedule. 
5 4/) 

6 public class TaxCalculator 

ue 

8 public static void main(String[] args) 

9 { 

10 final double RATE1 = 0.10; 

11 final double RATE2 = 0.25; 

12 final double RATE1_SINGLE_LIMIT = 32000; 

13 final double RATE1_MARRIED_LIMIT = 64000; 

14 

15 double taxl = 0; 

16 double tax2 = 0; 

17 

18 // Read income and marital status 

19 

20 Scanner in = new Scanner(System. in); 

21 System.out.print("Please enter your income: "); 
22 double income = in.nextDouble(); 
23 
24 System.out.print("Please enter s for single, m for married: "); 
25 String maritalStatus = in.nextQ); 
26 
27 // Compute taxes due 


102 Chapter 3 Decisions 


29 if (maritalStatus.equals(''s")) 

30 { 

31 if Cincome <= RATE1_SINGLE_LIMIT) 

32 { 

33 taxl = RATE1 * income; 

34 } 

35 else 

36 { 

37 taxl = RATE1 * RATE1_SINGLE_LIMIT; 

38 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT) ; 
39 } 

40 } 

41 else 

42 { 

43 if Cincome <= RATE1_MARRIED_LIMIT) 

44, { 

45 taxl = RATE1 * income; 

46 } 

47 else 

48 { 

49 taxl = RATE1 * RATE1_MARRIED_LIMIT; 

50 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); 
51 } 

52 } 

53 

54 double totalTax = taxl + tax2; 

55 

56 System.out.printIn('The tax is $" + totalTax); 
57 } 

58 } 


Program Run 


Please enter your income: 80000 
Please enter s for single, m for married: m 
The tax is $10400 


17. What is the amount of tax that a single taxpayer pays on an income of $32,000? 
18. Would that amount change if the first nested if statement changed from 

if Cincome <= RATE1_SINGLE_LIMIT) 

to 

if Cincome < RATE1_SINGLE_LIMIT) 


19. Suppose Harry and Sally each make $40,000 per year. Would they save taxes if 
they married? 





20. How would you modify the TaxCalculator. java program in order to check that 
the user entered a correct value for the marital status (i.e., s or m)? 

21. Some people object to higher tax rates for higher incomes, claiming that you 
might end up with less money after taxes when you get a raise for working hard. 
What is the flaw in this argument? 


Practice It Now youcantry these exercises at the end of the chapter: R3.9, R3.21, P3.18, P3.21. 





3.4 Nested Branches 103 


Hand-Tracing 


A very useful technique for understanding whether a pro- 
gram works correctly is called hand-tracing. You simulate 
the program’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 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 the current statement. In your mind, 
execute statements one at a time. Every time the value of a 
variable changes, cross out the old value and write the new 
value below the old one. 

For example, let’s trace the tax program with the data 


tax2 are initialized to 0. 


8 public static void main(String[] args) 
9 


10 final double RATE1 = 0.10; 

11 final double RATE2 = 0.25; 

12 final double RATE1_SINGLE_LIMIT = 32000; 
13 final double RATE1 MARRIED _LIMIT = 64000; 
14 

15 double tax1 = 0; 

16 double tax2 = 0; 
17 


In lines 22 and 25, income and maritalStatus are 
initialized by input statements. 


20 Scanner in = new Scanner(System.in); 


21 System.out.print("Please enter your income: "); 

22 double income = in.nextDouble(); 

23 

24 System.out.print("Please enter s for single, m for married: "); 


25 String maritalStatus = in.next(); 





Hand-tracing helps you 
understand whether a 
fromthe programrunonpage102.Inlines15and16,taxland — program works correctly. 


taxZ 


income 





0 
































Because maritalStatus is not "s", we move to the else branch of the outer if statement 


(line 41). 

29 if (maritalStatus.equals("s")) 

30 

31 if (income <= RATE1_SINGLE_LIMIT) 

32 { 

33 taxl = RATE1 * income; 

34 } 

35 else 

36 { 

37 taxl = RATE1 * RATE1_SINGLE_LIMIT; 
38 tax2 = RATE2 * (income - RATE1_SINGLE LIMIT); 
39 } 

40 } 

41 else 

42 


Because income is not <= 64000, we move to the else branch of the inner if statement (line 47). 


43 if (income <= RATE1_MARRIED_LIMIT) 

44 { 

45 taxl = RATE1 * income; 

46 } 

47 else 

48 { 

49 taxl = RATE1 * RATE1_MARRIED_LIMIT; 


50 tax2 
51 } 


RATE2 * (income - RATE1_MARRIED_LIMIT) ; 


104 Chapter 3 Decisions 


(@foyaalaakeal =a ne) mse. 





The values of tax1 and tax2 are updated. 


income 
80000 


48 { 

49 tax1 = RATE1 * RATE1 MARRIED_LIMIT; 

50 tax2 = RATE2 * (income - RATE1 MARRIED LIMIT) ; 
51 } 

52 } 

53 























Their sum totalTax is computed and printed. 
Then the program ends. 


54 double totalTax = taxl + tax2; R marital total 
55 tncome status tax 
56 System.out.printIn("The tax is $" + totalTax); 

57 } 80000 mM 








10400 

















Because the program trace shows the expected 
output ($10,400), it successfully demonstrated 
that this test case works correctly. 





The Dangling else Problem 


When an if statement is nested inside another if statement, the following error may occur. 


double shippingCharge = 5.00; // $5 inside continental U.S. 
if (country.equals("USA")) 
if (state.equals("HI")) 
shippingCharge = 10.00; // Hawaii is more expensive 
else // Pitfall! 
shippingCharge = 20.00; // As are foreign shipments 


The indentation level seems to suggest that the else is grouped with the test country. 
equals("USA"). Unfortunately, that is not the case. The compiler ignores all indentation and 
matches the else with the preceding if. That is, the code is actually 


double shippingCharge = 5.00; // $5 inside continental U.S. 
if (country.equals("USA")) 
if (state.equals("HI")) 
shippingCharge = 10.00; // Hawaii is more expensive 
else // Pitfall! 
shippingCharge = 20.00; // As are foreign shipments 


That isn’t what you want. You want to group the else with the first if. 
The ambiguous else is called a dangling else. You can avoid this pitfall if you always use 
braces, as recommended in Programming Tip 3.2 on page 86: 


double shippingCharge = 5.00; // $5 inside continental U.S. 
if (country.equals("USA")) 


{ 
if (state.equals("HI")) 
{ 
shippingCharge = 10.00; // Hawaii is more expensive 
} 
} 
else 
{ 


shippingCharge = 20.00; // As are foreign shipments 
} 


3.5 Problem Solving: Flowcharts 105 


Enumeration Types 


Special Topic 3.4 





In many programs, you use variables that can hold one of a finite number of values. For exam- 
ple, in the tax return class, the maritalStatus variable holds one of the values "s" or "m". If, due 
to some programming error, the maritalStatus variable is set to another value (such as "d" or 
"w"), then the programming logic may produce invalid results. 

Ina simple program, this is not really a problem. But as programs grow over time, and more 
cases are added (such as the “married filing separately” status), errors can slip in. Java version 
5.0 introduces a remedy: enumeration types. An enumeration type has a finite set of values, 
for example 





public enum FilingStatus { SINGLE, MARRIED, MARRIED_FILING_SEPARATELY } 


You can have any number of values, but you must include them all in the enum declaration. 
You can declare variables of the enumeration type: 


FilingStatus status = FilingStatus.SINGLE; 


If you try to assign a value that isn’t a FilingStatus, such as 2 or "S", then the compiler reports 
an error. 
Use the == operator to compare enumeration values, for example: 


if (status == FilingStatus.SINGLE) ... 
Place the enum declaration inside the class that implements your program, such as 


public class TaxReturn 


{ 
public enum FilingStatus { SINGLE, MARRIED, MARRIED_FILING_SEPARATELY } 


public static void main(String[] args) 
{ 


} 


VIDEO EXAMPLE 3.1 Computing the Plural of an English Word 


(ix The plural of apple is apples, but the plural of cherry is cherries. In 
PLUS 


this Video Example, we develop an algorithm for computing the 
plural of an English word. 





.5 Problem Solving: Flowchar 


You have seen examples of flowcharts earlier in this chapter. A flowchart shows the 
Flow charts are made ae . 
up of elements for structure of decisions and tasks that are required to solve a problem. When you have 
tasks, input/output, to solve a complex problem, it is a good idea to draw a flowchart to visualize the flow 
and decisions. of control 


The basic flowchart elements are shown in Figure 5. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


106 Chapter 3 Decisions 


Figure 5 
Flowchart Elements 


Each branch of a 
decision can contain 
tasks and further 
decisions. 


Never point an 
arrow inside 
another branch. 


Ti 
Simple task Input/output Condition — 


False 


The basic idea is simple enough. Link tasks and input/output boxes in the sequence in 
which they should be executed. Whenever you need to make a decision, draw a dia- 
mond with two outcomes (see Figure 6). 

Each branch can contain a sequence of tasks and even additional decisions. If there 
are multiple choices for a value, lay them out as in Figure 7. 

There is one issue that you need to be aware of when drawing flowcharts. Uncon- 
strained branching and merging can lead to “spaghetti code”, a messy network of 
possible pathways through a program. 

There is a simple rule for avoiding spaghetti code: Never point an arrow inside 
another branch. 

To understand the rule, consider this example: Shipping costs are $5 inside the 
United States, except that to Hawaii and Alaska they are $10. International shipping 
costs are also $10. 











Ti 
Choice 1 ws 
False 
Ti 
Choice 2 oo 
False 
T . True 
Condition = Choice 3 
False False 








Figure 6 Flowchart with Two Outcomes Figure 7 Flowchart with Multiple Choices 


3.5 Problem Solving: Flowcharts 107 


You might start out with a flowchart like the following: 





False 


Now you may be tempted to reuse the “shipping cost = $10” task: 


True 
False 
i> 


False 





Don’t do that! The red arrow points inside a different branch. Instead, add another 
task that sets the shipping cost to $10, like this: 


True 
False 


True 
False 





108 Chapter 3 Decisions 


Not only do you avoid spaghetti code, but it is also a 


A program to better design. In the future it may well happen that the 
co Ere web cost for international shipments is different from that 
to Alaska and Hawaii. 

Flowcharts can be very useful for getting an intui- 
tive understanding of the flow of an algorithm. How- 
ever, they get large rather quickly when you add more 
details. At that point, it makes sense to switch from 


costs. 





Spaghetti code has so many 
flowcharts to pseudocode. pathways that it becomes 


impossible to understand. 


22. Draw a flowchart for a program that reads a value temp and prints “Frozen” if it 
is less than zero. 


23. What is wrong with the flowchart at right? 
24. How do you fix the flowchart of 





True 
Self Check 23? Tapco? 
25. Draw a flowchart for a program that reads a 
value x. If it is less than zero, print “Error”. False 
Otherwise, print its square root. 
26. Draw a flowchart for a program that reads a eh, 
ae ‘ npu' ? 
value temp. If it is less than zero, print “Ice”. 
If it is greater than 100, print “Steam”. Oth- 
erwise, print “Liquid”. Pale 
Status = “OK” Status = “Error” 


Practice It Now youcantry these exercises at the end of the 
chapter: R3.12, R3.13, R3.14. 


.6 Problem Solving: Ti 


Consider how to test the tax computation program from Section 3.4. Of course, 
you cannot try out all possible inputs of marital status and income level. Even if you 
could, there would be no point in trying them all. If the program correctly computes 
one or two tax amounts ina given bracket, then we have a good reason to believe that 
all amounts will be correct. 


You want to aim for complete coverage of all decision points. Here is a plan for 
Each branch of your 


program should obtaining a comprehensive set of test cases: 
be covered bya shied. ; 
test case. e There are two possibilities for the marital status and two tax brackets for each 


status, yielding four test cases. 


e Testa handful of boundary conditions, such as an income that is at the boundary 
between two brackets, and a zero income. 


° Ifyou are responsible for error checking (which is discussed in Section 3.8), also 
test an invalid input, such as a negative income. 


It is a good idea to 
design test cases 
before implementing 
a program. 






SELF CHECK 
& ; 


Practice It 


ra colele-laalaaliace mil oo iie) 





3.6 Problem Solving: Test Cases 109 


Make a list of the test cases and the expected outputs: 


Test Case Expected Output Comment 


30,000 s 3,000 102% bracket 
72,000 s 13,200 3,200 * 25% of 40,000 
50,000 m 5,000 102% bracket 
104,000 m 16,400 6,400 + 25Z of 40,000 
32,000 s 3,200 boundary case 
0 0 boundary case 


When you develop a set of test cases, it is helpful to have a flowchart of your program 
(see Section 3.5). Check off each branch that has a test case. Include test cases for the 
boundary cases of each decision. For example, if a decision checks whether an input is 
less than 100, test with an input of 100. 

It is always a good idea to design test cases before starting to code. Working 
through the test cases gives you a better understanding of the algorithm that you are 
about to implement. 


27. Using Figure 1 on page 83 asa guide, follow the process described in Section 3.6 to 
design a set of test cases for the ElevatorSimulation. java program in Section 3.1. 


28. What is a boundary test case for the algorithm in How To 3.1 on page 93? What is 
the expected output? 


29. Using Figure 3 on page 97 as a guide, follow the process described in Section 3.6 to 
design a set of test cases for the EarthquakeStrength. java program in Section 3.3. 


30. Suppose you are designing a part of a program for a medical ro- 
bot that has a sensor returning an x- and y-location (measured in 
cm). You need to check whether the sensor location is inside the 
circle, outside the circle, or on the boundary (specifically, hav- 
ing a distance of less than 1 mm from the boundary). Assume the 
circle has center (0, 0) and a radius of 2 cm. Give a set of test cases. 


Now you can try these exercises at the end of the chapter: R3.15, R3.16. 


Make a Schedule and Make Time for Unexpected Problems 


Commercial software is notorious for being delivered later than promised. For example, 
Microsoft originally promised that its Windows Vista operating system would be available late 
in 2003, then in 2005, then in March 2006; it finally was released in January 2007. Some of the 
early promises might not have been realistic. It was in Microsoft’s interest to let prospective 
customers expect the imminent availability of the product. Had customers known the actual 
delivery date, they might have switched to a different product in the meantime. Undeniably, 
though, Microsoft had not anticipated the full complexity of the tasks it had set itself to solve. 

Microsoft can delay the delivery of its product, but it is likely that you cannot. Asa student 
or a programmer, you are expected to manage your time wisely and to finish your assignments 
on time. You can probably do simple programming exercises the night before the due date, 
but an assignment that looks twice as hard may well take four times as long, because more 
things can go wrong. You should therefore make a schedule whenever you start a program- 
ming project. 


110 Chapter 3 Decisions 


SJ of<\el [1 Ko) 0) | os is) 


First, estimate realistically how much time it 
will take you to: 


e Design the program logic. 
e Develop test cases. 
e Type the program in and fix syntax errors. 


Test and debug the program. 





For example, for the income tax program I might ‘ 
estimate an hour for the design; 30 minutes for — ern F 

developing test cases; an hour for data entry and | = VG! 

fixing syntax errors; and an hour for testing and . 

debugging. That is a total of 3.5 hours. If work Make a schedule for your programming 
two hours a day on this project, it will take me — work and build in time for problems. 
almost two days. 

Then think of things that can go wrong. Your computer might break down. You might be 
stumped by a problem with the computer system. (That is a particularly important concern 
for beginners. It is very common to lose a day over a trivial problem just because it takes time 
to track down a person who knows the magic command to overcome it.) As a rule of thumb, 
double the time of your estimate. That is, you should start four days, not two days, before the 
due date. If nothing went wrong, great; you have the program done two days early. When the 
inevitable problem occurs, you have a cushion of time that protects you from embarrassment 
and failure. 


Logging 


Sometimes you run a program and you are not sure where it spends its time. To get a printout 
of the program flow, you can insert trace messages into the program, such as this one: 


if (status == SINGLE) 


{ 
System.out.printIn("status is SINGLE"); 


} 


However, there is a problem with using System. out.printin for trace messages. When you are 
done testing the program, you need to remove all print statements that produce trace mes- 
sages. If you find another error, however, you need to stick the print statements back in. 

To overcome this problem, you should use the Logger class, which allows you to turn off the 
trace messages without removing them from the program. 

Instead of printing directly to System.out, use the global logger object that is returned 
by the call Logger.getGlobal(Q). (Prior to Java 7, you obtained the global logger as 
Logger. getLogger("global").) Then call the info method: 


Logger.getGlobal().info("status is SINGLE"); ; 
Logging messages can be 


By default, the message is printed. But if you call deactivated when testing 


Logger.getGlobal() .setLevel (Level .OFF) ; Petula 


at the beginning of the main method of your program, all log message printing is suppressed. 
Set the level to Level. INFO to turn logging of info messages on again. Thus, you can turn off 
the log messages when your program works fine, and you can turn them back on if you find 
another error. In other words, using Logger. getGlobal().info is just like System.out.print1n, 
except that you can easily activate and deactivate the logging. 

The Logger class has many other options for industrial-strength logging. Check out the API 
documentation if you want to have more control over logging. 


3.7 Boolean Variables and Operators 111 


____3.7 Boolean Variables and Operators 0 


The Boolean type 
boolean has two 
values, false 
and true. 





A Boolean variable 
is also called a flag 
because it can be 
either up (true) or 
down (false). 


Java has two Boolean 
operators that 
combine conditions: 
&& (and) and || (or). 


Sometimes, you need to evaluate a logical condition in one part of a program and use 
it elsewhere. To store a condition that can be true or false, you use a Boolean variable. 
Boolean variables are named after the mathematician George Boole (1815-1864), a 
pioneer in the study of logic. 

In Java, the boolean data type has exactly two values, denoted false and true. These 
values are not strings or integers; they are special values, just for Boolean variables. 
Here is a declaration of a Boolean variable: 


boolean failed = true; 
You can use the value later in your program to make a decision: 


if (failed) // Only executed if failed has been set to true 
{ 


} 


When you make complex decisions, you often need to combine Boolean values. An 
operator that combines Boolean conditions is called a Boolean operator. In Java, the 
&& operator (called and) yields true only when both conditions are true. The | | opera- 
tor (called or) yields the result true if at least one of the conditions is true. 

Suppose you write a program that processes temperature values, and you want 
to test whether a given temperature corresponds to liquid water. (At sea level, water 
freezes at 0 degrees Celsius and boils at 100 degrees.) Water is liquid if the tempera- 
ture is greater than zero and less than 100: 


if (temp > 0 && temp < 100) { System.out.printInC"Liquid"); } 


The condition of the test has two parts, joined by the & operator. Each part is a Bool- 
ean value that can be true or false. The combined expression is true if both individual 
expressions are true. If either one of the expressions is false, then the result is also false 
(see Figure 8). 

The Boolean operators && and | | have a lower precedence than the relational opera- 
tors. For that reason, you can write relational expressions on either side of the Bool- 
ean operators without using parentheses. For example, in the expression 


temp > 0 && temp < 100 


the expressions temp > 0 and temp < 100 are evaluated first. Then the && operator com- 
bines the results. Appendix B shows a table of the Java operators and their 
precedence. 


A B A &&B A B A||B A 1A 
true true true true true true true false 
true false false true false true false true 
false true false false true true 
false false false false false false 


Figure 8 Boolean Truth Tables 


112 Chapter 3 Decisions 


At this geyser in Iceland, 
you can see ice, liquid 
water, and steam. 





Conversely, let’s test whether water is ot liquid at a given temperature. That is the 


A program case when the temperature is at most 0 or at least 100. Use the | | (or) operator to com- 
comparing wombat bine the expressions: 

using Boolean 

expressions. if (temp <= 0 || temp >= 100) { System.out.print]n("Not liquid"); } 


Figure 9 shows flowcharts for these examples. 
e Sometimes you need to invert a condition with the not Boolean operator. The 
To invert a condition, , ie ; she, 
use the ! (not) ! operator takes a single condition and evaluates to true if that condition is false and to 
operator. false if the condition is true. In this example, output occurs if the value of the Boolean 
variable frozen is false: 


if (!frozen) { System.out.printInC"Not frozen"); } 


Table 5 illustrates additional examples of evaluating Boolean operators. 





and or 
False False False 
Temperature Temperature Temperature 
> 0? <0? = 100? 
Both conditions > , _ True True True 

Temperature False 

< 100? De 

_ True 
Water is Water is 
liquid not liquid 


Figure 9 Flowcharts for and and or Combinations 


Expression 


0 < 200 && 200 < 100 


S) 
A 


0 < 200 || 100 < 200 


200 || 200 < 100 


3.7 Boolean Variables and Operators 113 


Table 5 Boolean Operator Examples 


Value 
false 
true 


true 


0 <x &x < 100 || x == -1 (<x &-x < 100) 


Q 0<x < 10 


S x & y > 0 


!€0 < 200) 


frozen == 


frozen == 








Y 
SELF CHECK 


f 






Practice It 


(@foyaalanke)al=laae) mci) 








0 


true 


false 


31. 


32. 
33. 


|| x == -1 


Error 


Error 


false 


frozen 


!frozen 


34. Whatis the value of !! frozen? 


Comment 
Only the first condition is true. 
The first condition is true. 


The || is not a test for “either-or”. If both 
conditions are true, the result is true. 


The & operator has a higher precedence than the 
|| operator (see Appendix B). 


Error: This expression does not test whether x is 
between 0 and 100. The expression 0 < x isa 
Boolean value. You cannot compare a Boolean 
value with the integer 100. 


Error: This expression does not test whether x and 
y are positive. The left-hand side of && is an integer, 
x, and the right-hand side, y > 0, isa Boolean value. 
You cannot use && with an integer argument. 


0 < 200is true, therefore its negation is false. 


There is no need to compare a Boolean variable 
with true. 


It is clearer to use ! than to compare with false. 


Suppose x and y are two integers. How do you test whether both of them are 
Zero? 


How do you test whether at least one of them is zero? 


How do you test whether exactly one of them is zero? 


35. What is the advantage of using the type boolean rather than strings "false"/"true" 
or integers 0/1? 


Now you can try these exercises at the end of the chapter: R3.29, P3.25, P3.27. 


Combining Multiple Relational Operators 


Consider the expression 


if (0 <= temp <= 100) // Error 


This looks just like the mathematical test 0 < temp < 100. But in Java, it is a compile-time error. 
Let us dissect the condition. The first half, 0 <= temp, is a test with an outcome true or false. 
The outcome of that test (true or false) is then compared against 100. This seems to make no 


114 Chapter 3 Decisions 


(@oyaalankelaM =a ne) ms iie) 


Special Topic 3.6 





sense. Is true larger than 100 or not? Can one compare truth values and numbers? In Java, you 
cannot. The Java compiler rejects this statement. 
Instead, use && to combine two separate tests: 


if (0 <= temp && temp <= 100) . 
Another common error, along the same lines, is to write 
if Cinput == 1 || 2)... // Error 


to test whether input is 1 or 2. Again, the Java compiler flags this construct as an error. You 
cannot apply the || operator to numbers. You need to write two Boolean expressions and join 
them with the | | operator: 


if Cinput == 1 || input == 2). 


Confusing && and | | Conditions 


It is a surprisingly common error to confuse and and or conditions. A value lies between 0 and 
100 if it is at least 0 and at most 100. It lies outside that range if it is less than 0 or greater than 
100. There is no golden rule; you just have to think carefully. 

Often the and or or is clearly stated, and then it isn’t too hard to implement it. But some- 
times the wording isn’t as explicit. It is quite common that the individual conditions are nicely 
set apart ina bulleted list, but with little indication of how they should be combined. Consider 
these instructions for filing a tax return. You can claim single filing status if any one of the fol- 
lowing is true: 


e You were never married. 
e You were legally separated or divorced on the last day of the tax year. 
e You were widowed, and did not remarry. 


Since the test passes if any one of the conditions is true, you must combine the conditions with 
or. Elsewhere, the same instructions state that you may use the more advantageous status of 
married filing jointly if all five of the following conditions are true: 


e Your spouse died less than two years ago and you did not remarry. 
e You havea child whom you can claim as dependent. 

e That child lived in your home for all of the tax year. 

e You paid over half the cost of keeping up your home for this child. 
e You filed a joint return with your spouse the year he or she died. 


Because all of the conditions must be true for the test to pass, you must combine them with an 
and. 


Short-Circuit Evaluation of Boolean Operators 


The && and | | operators are computed using short-circuit evaluation. Saar ane 

In other words, logical expressions are evaluated from left to right, Lhe a 
and evaluation stops as soon as the truth value is determined. When —_ computed using 
an && is evaluated and the first condition is false, the second condition _ short-circuit 


is not evaluated, because it does not matter what the outcome of the plies ae 
second test is. as the trut value Is 
FE | ‘fet . determined, no 
or example, consider the expression Freee eet 


quantity > 0 && price / quantity < 10 are evaluated. 


NY el-Kel f-1 im Ko) 0) (ens V4 








3.7 Boolean Variables and Operators 115 


Suppose the value of quantity is zero. Then the test quantity > 0 fails, and the second test is not 
attempted. That is just as well, because it is illegal to divide by zero. 

Similarly, when the first condition of an || expression is true, then the remainder is not 
evaluated because the result must be true. 

This process is called short-circuit evaluation. 


Ina short circuit, electricity travels along the path of least 
resistance. Similarly, short-circuit evaluation takes the fast- 
est path for computing the result of a Boolean expression. 





De Morgan’s Law 


Humans generally have a hard time comprehending logical conditions with not operators 
applied to and/or expressions. De Morgan’s Law, named after the logician Augustus De Mor- 
gan (1806-1871), can be used to simplify these Boolean expressions. 

Suppose we want to charge a higher shipping rate if we don’t ship within the continental 
United States. 


if (!(country.equals("USA") && !state.equals("AK") && !state.equals("HI"))) 
{ 
shippingCharge = 20.00; 

} 
This test is a little bit complicated, and you have to think carefully through the logic. When it 
is not true that the country is USA amd the state is not Alaska and the state is not Hawaii, then 
charge $20.00. Huh? It is not true that some people won’t be confused by this code. 

The computer doesn’t care, but it takes human programmers to write and maintain the 
code. Therefore, it is useful to know how to simplify such a condition. 

De Morgan’s Law has two forms: one for the negation of an 
and expression and one for the negation of an or expression: De Morgan's law tells 


1(A && B) is the same as 1A || !B as Nene oe 
1(A || BD is the same as 1A && !B 


Pay particular attention to the fact that the and and or operators are reversed by moving the 
not inward. For example, the negation of “the state is Alaska or it is Hawaii”, 


!(state.equals("AK") || state.equals("HI")) 

is “the state is not Alaska and it is not Hawaii”: 
'state.equals("AK") && !state.equals("HI") 

Now apply the law to our shipping charge computation: 


! Ccountry.equals ("USA") 
&& !state.equals("AK") 
&& !state.equals("HI")) 


is equivalent to 


!country.equals("USA") 
|| !!state.equals("AK") 
|| !!state.equalsC"HI")) 


116 Chapter 3 Decisions 


Because two ! cancel each other out, the result is the simpler test 


!country.equals("USA") 
|| state.equals("AK") 
|| state.equals("HI") 
In other words, higher shipping charges apply when the destination is outside the United 
States or to Alaska or Hawaii. 
To simplify conditions with negations of and or or expressions, it is usually a good idea to 
apply De Morgan’s Law to move the negations to the innermost level. 


An important application for the if statement is input validation. Whenever 
your program accepts user input, you need to make sure that the user-supplied 
values are valid before you use them in your computations. 

Consider our elevator simulation program. Assume that the elevator panel 
has buttons labeled 1 through 20 (but not 13). The following are illegal inputs: 


e The number 13 


e Zero ora negative number 





e Anumber larger than 20 


Like a quality control worker, . ° a 
you want to make sure that e Aninput that is not a sequence of digits, such as five 
user input is correct before 
processing it. 


In each of these cases, we will want to give an error message and exit the 
program. 
It is simple to guard against an input of 13: 


if (floor == 13) 
{ 
} 
Here is how you ensure that the user doesn’t enter a number outside the valid range: 
if (floor <= 0 || floor > 20) 
{ 
} 


However, dealing with an input that is not a valid integer is a more serious problem. 
When the statement 


System.out.printInC"Error: There is no thirteenth floor."); 


System.out.printInC"Error: The floor must be between 1 and 20."); 


floor = in.nextIntQ; 


is executed, and the user types in an input that is not an integer (such as five), then 
Call the hasNextInt or 
hyacl\oredntentnike thei integer variable floor is not set. Instead, a run-time exception occurs and the pro- 
method to ensure — gram is terminated. To avoid this problem, you should first call the hasNextInt method 
noemerswen inputs which checks whether the next input is an integer. If that method returns true, you 
can safely call nextInt. Otherwise, print an error message and exit the program. 


if Cin. hasNextInt(Q)) 

{ 
int floor = in.nextIntQ; 
Process the input value 

} 


3.8 Application: Input Validation 117 
else 
{ 
} 


Here is the complete elevator simulation program with input validation: 


System.out.printIn("Error: Not an integer."); 


section_8/ElevatorSimulation2.java 
1 import java.util.Scanner; 
[** 


This program simulates an elevator panel that skips the 13th floor, checking for 
input errors. 


2 

3 

4 

5 
Gu) 
7 public class ElevatorSimulation2 
8 
9 


{ 
public static void main(String[] args) 

10 { 
11 Scanner in = new Scanner(System. in) ; 
12 System.out.print('Floor: "); 
13 if Cin. hasNextInt(Q)) 
14 { 
15 // Now we know that the user entered an integer 
16 
17 int floor = in.nextIntQ; 
18 
19 if (floor == 13) 
20 { 
21 System.out.printInC"Error: There is no thirteenth floor."); 
Papa } 
23 else if (floor <= 0 || floor > 20) 
24 { 
25 System.out.printInC"Error: The floor must be between 1 and 20."); 
26 } 
27 else 
28 { 
29 // Now we know that the input is valid 
30 
31 int actualFloor = floor; 
32 if (floor > 13) 
33 { 
34 actualFloor = floor - 1; 
35 } 
36 
37 System.out.printIn("The elevator will travel to the actual floor " 
38 + actualFloor); 
39 } 
40 } 
41 else 
42 { 
43 System.out.printInC"Error: Not an integer."); 
44 } 
45 } 
46 } 


Program Run 


Floor: 13 
Error: There is no thirteenth floor. 


118 Chapter 3 Decisions 


36. Inthe ElevatorSimulation2 program, what is the output when the input is 
a. 100? 
b. -1? 
c. 20? 
d. thirteen? 





37. Your task is to rewrite lines 19-26 of the ElevatorSimulation2 program so that 
there is a single if statement with a complex condition. What is the condition? 


If G..<.<) 
{ 


} 


38. Inthe Sherlock Holmes story “The Adventure of the Sussex Vampire”, the 
inimitable detective uttered these words: “Matilda Briggs was not the name of 
a young woman, Watson, ... It was a ship which is associated with the giant rat 
of Sumatra, a story for which the world is not yet prepared.” Over a hundred 
years later, researchers found giant rats in Western New Guinea, another part of 
Indonesia. 


System.out.printInC"Error: Invalid floor number"); 


Suppose you are charged with writing a program that processes rat weights. It 
contains the statements 

System.out.print("Enter weight in kg: "); 

double weight = in.nextDouble(); 


What input checks should you supply? 


When processing inputs, you want to reject values that are too large. But how large is too large? 
These giant rats, found in Western New Guinea, are about five times the size of a city rat. 





39. Run the following test program and supply inputs 2 and three at the prompts. 
What happens? Why? 


import java.util.Scanner 


public class Test 
{ 
public static void main(String[] args) 
{ 
Scanner in = new Scanner (System. in); 
System.out.printC"Enter an integer: "); 
int m = in.nextIntQ; 
System.out.print("Enter another integer: "); 
int n = in.nextIntQ; 
System.out.printin(m + 


+n); 
} 
} 


Practice It Now youcantry these exercises at the end of the chapter: R3.3, R3.32, P3.11. 


VIDEO EXAMPLE 3.2 The Genetic Code 


Toe Watch this Video Example to see how to build a “decoder ring” for 
PLUS 


the genetic code. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


When one uses a 
sophisticated com- 
puter program such as a tax prepara- 
tion package, one is bound to attribute 
some intelligence to the computer. 
The computer asks sensible questions 
and makes computations that we find 
a mental challenge. After all, if doing 
one’s taxes were easy, we wouldn't 
need a computer to do it for us. 

As programmers, however, we 
know that all this apparent intelligence 
is an illusion. Human programmers 
have carefully “coached” the software 
in all possible scenarios, and it simply 
replays the actions and decisions that 
were programmed into it. 

Would it be possible to write com- 
puter programs that are genuinely 
intelligent in some sense? From the 
earliest days of computing, there was 
a sense that the human brain might 
be nothing but an immense computer, 
and that it might well be feasible to 
program computers to imitate some 
processes of human thought. Serious 
research into artificial intelligence 
began in the mid-1950s, and the first 
twenty years brought some impres- 
sive successes. Programs that play 
chess—surely an activity that appears 
to require remarkable intellectual pow- 
ers—have become so good that they 
now routinely beat all but the best 
human players. As far back as 1975, 
an expert-system program called 
Mycin gained fame for being better in 
diagnosing meningitis in patients than 
the average physician. 

However, there were serious set- 
backs as well. From 1982 to 1992, 
the Japanese government embarked 
on a massive research project, funded 
at over 40 billion Japanese yen. It was 
known as the Fifth-Generation Project. 
Its goal was to develop new hardware 
and software to greatly improve the 
performance of expert system soft- 
ware. At its outset, the project created 
fear in other countries that the Japa- 
nese computer industry was about to 
become the undisputed leader in the 
field. However, the end results were 
disappointing and did little to bring 





3.8 Application: Input Validation 


Random Fact 3.2 Artificial Intelligence 


artificial intelligence applications to 
market. 

From the very outset, one of the 
stated goals of the Al community was 
to produce software that could trans- 
late text from one language to another, 
for example from English to Russian. 
That undertaking proved to be enor- 
mously complicated. Human language 
appears to be much more subtle and 
interwoven with the human experi- 
ence than had originally been thought. 
Even the grammar-checking tools that 
come with word-processing programs 
today are more of a gimmick than a 
useful tool, and analyzing grammar 
is just the first step in translating 
sentences. 

The CYC (from encyclopedia) proj- 
ect, started by Douglas Lenat in 1984, 
tries to codify the implicit assump- 
tions that underlie human speech and 
writing. The team members started 
out analyzing news articles and asked 
themselves what unmentioned facts 
are necessary to actually understand 
the sentences. For example, consider 
the sentence, “Last fall she enrolled in 
Michigan State”. The reader automati- 
cally realizes that “fall” is not related 
to falling down in this context, but 
refers to the season. While there is 
a state of Michigan, here Michigan 
State denotes the university. A priori, 
a computer program has none of this 





119 


knowledge. The goal of the CYC proj- 
ect is to extract and store the requi- 
site facts—that is, (1) people enroll in 
universities; (2) Michigan is a state; (3) 
many states have universities named 
X State University, often abbreviated 
as X State; (4) most people enroll in 
a university in the fall. By 1995, the 
project had codified about 100,000 
common-sense concepts and about 
a million facts of knowledge relating 
them. Even this massive amount of 
data has not proven sufficient for use- 
ful applications. 

In recent years, artificial intelli- 
gence technology has seen substantial 
advances. One of the most astounding 
examples is the outcome of a series 
of “grand challenges” for autono- 
mous vehicles posed by the Defense 
Advanced Research Projects Agency 
(DARPA). Competitors were invited to 
submit a computer-controlled vehi- 
cle that had to complete an obstacle 
course without a human driver or 
remote control. The first event, in 
2004, was a disappointment, with 
none of the entrants finishing the 
route. In 2005, five vehicles com- 
pleted a grueling 212 km course in the 
Mojave desert. Stanford’s Stanley came 
in first, with an average speed of 30 
km/h. In 2007, DARPA moved the com- 
petition to an “urban” environment, an 
abandoned air force base. Vehicles 
had to be able to 
interact with each 
other, following Cali- 
fornia traffic laws. As 
Stanford’s Sebastian 
Thrun explained: “In 
the last Grand Chal- 
lenge, it didn’t really 
matter whether an 
obstacle was a rock 
or a bush, because 
either way you’d just 
drive around it. The 
current challenge is to 
move from just sens- 
ing the environment 
to understanding it.” 


Winner of the 2007 DARPA Urban Challenge 


120 Chapter 3 Decisions 


Use the if statement to implement a decision. 


e The if statement allows a program to carry out 
different actions depending on the nature of the 
data to be processed. 





Implement comparisons of numbers and objects. 


r ¢ Use relational operators (< <= > >= == !=) to compare numbers. 
¢ Do not use the == operator to compare strings. Use the equals method instead. 
¢ The compareTo method compares strings in lexicographic order. = 


Implement complex decisions that require multiple if statements. 





¢ Multiple if statements can be combined to evaluate complex decisions. 


¢ When using multiple if statements, test general conditions after more specific 
conditions. 





Implement decisions whose branches require further decisions. 


e When a decision statement is contained inside the branch of another decision 
statement, the statements are vested. 


¢ Nested decisions are required for problems that have two levels of decision 


=; = king. 
= ma 


Draw flowcharts for visualizing the control flow of a program. 





¢ Flow charts are made up of elements for tasks, 


input/output, and decisions. i, Ts 
e Each branch of a decision can contain tasks and further 
decisions. rile 


¢ Never point an arrow inside another branch. 


Design test cases for your programs. 


¢ Each branch of your program should be covered by a test case. 
¢ Itisa good idea to design test cases before implementing a program. 


¢ Logging messages can be deactivated when testing is complete. 


Review Exercises 121 


Use the Boolean data type to store and combine conditions that can be true or false. 


¢ The Boolean type boolean has two values, false and true. 

¢ Java has two Boolean operators that combine conditions: & (and) and || (07). 
¢ To invert a condition, use the ! (ot) operator. 

¢ The &and || operators are computed using short-circuit evaluation: As soon as 


the truth value is determined, no further conditions are evaluated. 


¢ De Morgan’s law tells you how to negate && and || conditions. 





Apply if statements to detect whether user input is valid. 


© Call the hasNextInt or hasNextDouble method to ensure that the 
next input is a number. 








java.lang.String java.util. logging.Level 
equals INFO 
comparelo OFF 
java.util.Scanner java.util. logging.Logger 
hasNextDouble getGlobal 
hasNextInt info 
setLevel 


= R3.1 What is the value of each variable after the if statement? 


a. int n= 1; int k = 2; int r=n; 
if (k <n) { r=k; } 

b. int n = 1; int k = 2; int r; 
if (n<k) { r=k; } 
else {r=k +n; } 

c. int n= 1; int k = 2; intr=k; 
if (r<k) {ne=r; } 
else { k =n; } 

d. int n = 1; int k = 2; int r = 3; 


if(r<n+k) {r=2%* n; } 
else {k=2 * r; } 


m# R3.2 Explain the difference between 


s=0; 
if («> 0) { s++; } 
if (y > 0) { s++; } 


and 


s=0; 
if (x > 0) { s++; } 
else if (y > 0) { st+; } 


122 Chapter 3 Decisions 


ae R3.3 


o R3.4 


oe R3.5 


ue R3.6 


aa R3.7 


« R3.8 


Find the errors in the following if statements. 


a. if x > 0 then System.out.print(x); 
b. if (1 + x > Math.pow(x, Math.sqrt(2)) { y =y +x; } 
c. if (x = 1) { y+; } 


d. x = in.nextIntQ); 
if Cin. hasNextInt()) 


{ 
sum = sum + X; 
} 
else 
{ 
System.out.printIn("Bad input for x"); 
} 


e. String letterGrade = "F"; 


if (grade >= 90) { letterGrade = "A"; } 
if (grade >= 80) { letterGrade = "B"; } 
if (grade >= 70) { letterGrade = "C"; } 
if (grade >= 60) { letterGrade = "D"; } 


What do these code fragments print? 
a. int n = 1; 
int m = -1; 


if (mn < -m) { System.out.print(n); } 
else { System.out.print(m); } 

b. int n = 1; 
int m = -1; 
if (-n >= m) { System.out.print(n); } 
else { System.out.print(m); } 

c. double x = 0; 
double y = 1; 
if (Math.abs(x - y) < 1) { System.out.print(x); } 
else { System.out.print(y); } 

d. double x = Math.sqrt(2); 
double y = 2; 
if (x * x == y) { System.out.print(x); } 
else { System.out.print(y); } 


Suppose x and y are variables of type double. Write a code fragment that sets y to x if x 
is positive and to 0 otherwise. 


Suppose x and y are variables of type double. Write a code fragment that sets y to the 
absolute value of x without calling the Math. abs function. Use an if statement. 


Explain why it is more difficult to compare floating-point numbers than integers. 
Write Java code to test whether an integer n equals 10 and whether a floating-point 
number x is approximately equal to 10. 


It is easy to confuse the = and == operators. Write a test program containing the 
statement 
if (floor = 13) 


What error message do you get? Write another test program containing the 
statement 


count == 0; 


What does your compiler do when you compile the program? 


Review Exercises 123 


«= R3.9 Each square ona chess board can be described by a letter and number, such as g5 in 
this example: 


a bedefgh 


8 8 
7 7 
6 6 
5 [-—5 
4 4 
3 3 
: 2 
1 1 


a becdefgh 


The following pseudocode describes an algorithm that determines whether a square 
with a given letter and number is dark (black) or light (white). 


If the letter is ana, ¢, e, or g 
If the number is odd 
color = "black" 
Else 
color = "white" 
Else 
If the number is even 
color = "black" 
Else 
color = "white" 


Using the procedure in Programming Tip 3.5, trace this pseudocode with input g5. 


«= R3.10 Give a set of four test cases for the algorithm of Exercise R3.9 that covers all 
branches. 


«= R3.11 Inascheduling program, we want to check whether two appointments overlap. For 
simplicity, appointments start at a full hour, and we use military time (with hours 
0-24). The following pseudocode describes an algorithm that determines whether 
the appointment with start time start] and end time end! overlaps with the appoint- 
ment with start time startZ and end time endZ. 


If start1 > startZ 
$= startl 
Else 
$= startZ 
If endl < endZ 
e = endl 
Else 
e= endZ 
Ifs<e 
The appointments overlap. 
Else 
The appointments don't overlap. 


Trace this algorithm with an appointment from 10-12 and one from 11-13, then with 
an appointment from 10-11 and one from 12-13. 


124 Chapter 3 Decisions 


= R3.12 
= R3.13 
= R3.14 
we R3.15 
ue R3.16 
ua R317 


ot R3.18 


at R3.19 


ae R3.20 


= R3.21 


ae R3.22 


# R3.23 


ue R3.24 


Draw a flow chart for the algorithm in Exercise R3.11. 
Draw a flow chart for the algorithm in Exercise P3.17. 
Draw a flow chart for the algorithm in Exercise P3.18. 
Develop a set of test cases for the algorithm in Exercise R3.11. 
Develop a set of test cases for the algorithm in Exercise P3.18. 


Write pseudocode for a program that prompts the user for a month and day and 
prints out whether it is one of the following four holidays: 


e New Year’s Day (January 1) 


Independence Day (July 4) 
Veterans Day (November 11) 
Christmas Day (December 25) 


Write pseudocode for a program that assigns letter grades for a quiz, according to the 
following table: 


Score Grade 


90-100 A 
80-89 B 
70-79 C 
60-69 D 

< 60 F 


Explain how the lexicographic ordering of strings in Java differs from the order- 
ing of words ina dictionary or telephone book. Hint: Consider strings such as 18M, 
wiley.com, Century 21, and While-U-Wwait. 


Of the following pairs of strings, which comes first in lexicographic order? 


a. "Tom", "Jerry" 

b. "Tom", "Tomato" 

c. "church", "Churchill" 

d. "car manufacturer", "carburetor" 
e. "Harry", "hairy" 

f. "Java", " Car" 

g. "Tom", "Tom" 

h. "Car", "Cari" 

i. "car", "bar" 


Explain the difference between an if/else if/else sequence and nested if statements. 
Give an example of each. 


Give an example of an if/else if/else sequence where the order of the tests does not 
matter. Give an example where the order of the tests matters. 


Rewrite the condition in Section 3.3 to use < operators instead of >= operators. What 
is the impact on the order of the comparisons? 


Give a set of test cases for the tax program in Exercise P3.22. Manually compute the 
expected results. 


Review Exercises 125 


» R3.25 Make up a Java code example that shows the dangling else problem using the follow- 
ing statement: A student with a GPA of at least 1.5, but less than 2, is on probation. 
With less than 1.5, the student is failing. 


ua R3.26 Complete the following truth table by finding the truth values of the Boolean 
expressions for all combinations of the Boolean inputs p, q, and r. 


p q r (p && q) || Ir !(p && (q || !r)) 
false false false 
false false true 
false true false 


5 more combinations 


na=R3.27 True or false? A && B is the same as B && A for any Boolean conditions A and B. 


# R3.28 The ‘ 


‘advanced search” feature of many search engines allows you to use Boolean 


operators for complex queries, such as “(cats OR dogs) AND NOT pets”. Contrast 
these search operators with the Boolean operators in Java. 


== R3.29 Suppose the value of b is false and the value of x is 0. What is the value of each of the 
following expressions? 


a. b && x == 0 
b.b || x == 0 
c. !b && x == 0 
d.!b || x == 0 
e. b & x != 0 
f.b |= 0 
g. !b && x I= 0 
h. !b || x !=0 


«= R3.30 Simplify the following expressions. Here, bis a variable of type boolean. 


a. 


b. 
Cc. 
d. 


b == true 
b == false 
b != true 
b != false 


»#=# R3.31 Simplify the following statements. Here, b is a variable of type boolean and nis a vari- 
able of type int. 


a. 


b. 
c. 
d. 


if (n == 0) { b = true; } else { b = false; } 
(Hint: What is the value of n == 0?) 

if (n == 0) { b = false; } else { b = true; } 

b = false; if (n> 1) { if (n < 2) { b = true; } } 
if (n <1) { b = true; } else { b=n> 2; } 


126 Chapter 3 Decisions 


# R3.32 


What is wrong with the following program? 


System.out.print("Enter the number of quarters: "); 
jnt quarters = in.nextIntQ); 
if Cin. hasNextInt()) 


{ 
total = total + quarters * 0.25; 
System.out.printIn("Total: " + total); 
} 
else 
{ 
System.out.printInC"Input error."); 
} 


= P3.1 


ue P3.2 


ue P3,3 


un P3.4 


oe P3.5 


un P3.6 


un P3.7 


ue P3.8 


Write a program that reads an integer and prints whether it is negative, zero, or 
positive. 


Write a program that reads a floating-point number and prints “zero” if the number 
is zero. Otherwise, print “positive” or “negative”. Add “small” if the absolute value 
of the number is less than 1, or “large” if it exceeds 1,000,000. 


Write a program that reads an integer and prints how many digits the number has, by 
checking whether the number is = 10, = 100, and so on. (Assume that all integers are 
less than ten billion.) If the number is negative, first multiply it with -1. 


Write a program that reads three numbers and prints “all the same” if they are all the 
same, “all different” if they are all different, and “neither” otherwise. 


Write a program that reads three numbers and prints “increasing” if they are in 
: = “ : = Tied 7 . oe ‘4 »” 
increasing order, “decreasing” if they are in decreasing order, and “neither” other- 

: ho ba »” “ : 4 = »” 4 bd 
wise. Here, “increasing” means “strictly increasing”, with each value larger than its 
predecessor. The sequence 3 4 4 would not be considered increasing. 


Repeat Exercise P3.5, but before reading the numbers, ask the user whether increas- 
ing/decreasing should be “strict” or “lenient”. In lenient mode, the sequence 3 4 4 is 
increasing and the sequence 4 4 4 is both increasing and decreasing. 


Write a program that reads in three integers and prints “in order” if they are sorted in 
ascending or descending order, or “not in order” otherwise. For example, 


125 in order 
152 not in order 
5 21 in order 
122. in order 


Write a program that reads four integers and prints “two pairs” if the input consists 
of two matching pairs (in some order) and “not two pairs” otherwise. For example, 
1221. two pairs 
1223. not two pairs 
2222 _ two pairs 


Programming Exercises 127 


» P3.9 Write a program that reads a temperature value and the letter C for Celsius or F for 
Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature 
at sea level. 


» P3.10 The boiling point of water drops by about one degree centigrade for every 300 
meters (or 1,000 feet) of altitude. Improve the program of Exercise P3.9 to allow the 
user to supply the altitude in meters or feet. 


» P3.11 Add error handling to Exercise P3.10. If the user does not enter a number when 
expected, or provides an invalid unit for the altitude, print an error message and end 
the program. 


«= P3.12 Write a program that translates a letter grade into a number grade. Letter grades are 
A, B, C, D, and F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 
0. There is no F+ or F—. A + increases the numeric value by 0.3, a— decreases it by 0.3. 
However, an A+ has value 4.0. 


Enter a letter grade: B- 
The numeric value is 2.7. 


n= P3.13 Write a program that translates a number between 0 and 4 into the closest letter 
grade. For example, the number 2.8 (which might have been the average of several 
grades) would be converted to B-. Break ties in favor of the better grade; for example 
2.85 should bea B. 


a= P3.14 Write a program that takes user input describing a playing card in the following 
shorthand notation: 


Ace 
. 10 Card values 
Jack 


Queen 


> 


King 
Diamonds 
Hearts 
Spades 
Clubs 


Your program should print the full description of the card. For example, 


nn FZ OK H 4 N 


Enter the card notation: QS 
Queen of Spades 


«= P3.15 Write a program that reads in three floating-point numbers and prints the largest of 
the three inputs. For example: 


Please enter three numbers: 4 9 2.5 
The largest number is 9. 


n= P3.16 Write a program that reads in three strings and sorts them lexicographically. 


Enter three strings: Charlie Able Baker 
Able 

Baker 

Charlie 


128 Chapter 3 Decisions 


«= P3.17 When two points in time are compared, each given as hours (in military time, rang- 
ing from 0 and 23) and minutes, the following pseudocode determines which comes 
first. 


If hour < hourZ 
time! comes first. 
Else if hour 1 and hourZ are the same 
If minute! < minuteZ 
time! comes first. 
Else if minute! and minuteZ are the same 
time! and timeZ are the same. 
Else 
timeZ comes first. 
Else 
timeZ comes first. 


Write a program that prompts the user for two points in time and prints the time that 
comes first, then the other time. 


e# P3.18 The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a 
given month and day. 


If month is 1, Z, or 3, season = "Winter" 
Else if month is 4, 9, or 6, season = “Spring” 
Else if month is 7, 8, or 9, season = “Summer” 
Else if month is 10, 11, or 12, season = “Fall” 
If month is divisible by 3 and day >= 21 
If season is "Winter", season = “Spring” 
Else if season is "Spring", season = "Summer" 
Else if season is “Summer”, season = “Fall” 
Else season = "Winter" 


Write a program that prompts the user for a month 
and day and then prints the season, as determined 
by this algorithm. 





«= P3.19 Write a program that reads in two floating-point numbers and tests whether they are 
the same up to two decimal places. Here are two sample runs. 
Enter two floating-point numbers: 2.0 1.99998 
They are the same up to two decimal places. 


Enter two floating-point numbers: 2.0 1.98999 
They are different. 


a= P3.20 Write a program that prompts for the day and month of the user’s birthday and then 
prints a horoscope. Make up fortunes for programmers, like this: 

Please enter your birthday (month and day): 6 16 

Gemini are experts at figuring out the behavior of complicated programs. 


You feel where bugs are coming from and then stay one step ahead. Tonight, 
your style wins approval from a tough critic. 


Each fortune should contain the name of the astrological sign. (You will find the 
names and date ranges of the signs at a distressingly large number of sites on the 
Internet.) 





ae P3.21 


aue P3.22 


Programming Exercises 129 


The original U.S. income tax of 1913 was quite simple. The tax was 
e 1 percent on the first $50,000. 
e 2 percent on the amount over $50,000 up to $75,000. 
¢ 3 percent on the amount over $75,000 up to $100,000. 
¢ 4 percent on the amount over $100,000 up to $250,000. 
e 5 percent on the amount over $250,000 up to $500,000. 
© 6 percent on the amount over $500,000. 
There was no separate schedule for single or married taxpayers. Write a program that 


computes the income tax according to this schedule. 


Write a program that computes taxes for the following schedule. 


If your status is Single and 


if the taxable income is over but not over the tax is of the amount over 
$0 $8,000 10% $0 
$8,000 $32,000 $800 + 15% $8,000 
$32,000 $4,400 + 25% $32,000 
If your status is Married and 
if the taxable income is over but not over the tax is of the amount over 
$0 $16,000 10% $0 
$16,000 $64,000 $1,600 + 15% $16,000 
$64,000 $8,800 + 25% $64,000 


aee P3.23 


ane P3.24 


=» P3.25 


The TaxCalculator. java program uses a simplified version of the 2008 U.S. income tax 
schedule. Look up the tax brackets and rates for the current year, for both single and 
married filers, and implement a program that computes the actual income tax. 


Unit conversion. Write a unit conversion program that asks the users from which 
unit they want to convert (fl. 02, gal, oz, lb, in, ft, mi) and to which unit they want to 
convert (ml, |, g, kg, mm, cm, m, km). Reject incompatible conversions (such as gal 
— km). Ask for the value to be converted, then display the result: 

Convert from? gal 

Convert to? ml 


Value? 2.5 
2.5 gal = 9462.5 ml 


Write a program that prompts the user to provide a single character from the alpha- 
bet. Print Vowel or Consonant, depending on the user input. If the user input is 
nota letter (between a and z or A and Z), or is a string of length > 1, print an error 
message. 


130 Chapter 3 Decisions 


nun P3.26 Roman numbers. Write a program that converts a positive integer into the Roman 


ua P3,27 


ane P3.28 


number system. The Roman number system has digits 


1 

5 

10 
50 
100 
500 
1,000 


zoorsxM<c 


Numbers are formed according to the following rules: 
a. Only numbers up to 3,999 are represented. 


b. As in the decimal system, the thousands, hundreds, tens, and ones are 
expressed separately. 


c. The numbers 1 to 9 are expressed as 


I 1 
II 2 
Ill 3 
IV 4 
Vv 2 
VI 6 
VII 7 
VI 8 
IX 


As you can see, an I preceding a V or X is subtracted from the value, and you 
can never have more than three I’s ina row. 





‘oO 


d. Tens and hundreds are done the same way, except that the letters X, L, C and C, 
D, Mare used instead of I, V, X, respectively. 


Your program should take an input, such as 1978, and convert it to Roman numerals, 


MCMLXXVIII. 


Write a program that asks the user to enter a month (1 for January, 2 for February, 
and so on) and then prints the number of days in the month. For February, print “28 
or 29 days”. 


Enter a month: 5 
30 days 


Do not use a separate if/else branch for each month. Use Boolean operators. 


A year with 366 days is called a leap year. Leap years are necessary to keep the cal- 
endar synchronized with the sun because the earth revolves around the sun once 
every 365.25 days. Actually, that figure is not entirely precise, and for all dates after 
1582 the Gregorian correction applies. Usually years that are divisible by 4 are leap 
years, for example 1996. However, years that are divisible by 100 (for example, 1900) 
are not leap years, but years that are divisible by 400 are leap years (for example, 


uae P3.29 


sae Business P3.30 


== Business P3.31 


== Business P3.32 


| 
| 






» Business P3.33 


Programming Exercises 131 


2000). Write a program that asks the user for a year and computes whether that year 
is a leap year. Use a single if statement and Boolean operators. 


French country names are feminine when they end with the letter e, masculine other- 
wise, except for the following which are masculine even though they end with e: 

e le Belize 

e le Cambodge 


e le Mexique 


le Mozambique 


le Zaire 
le Zimbabwe 


Write a program that reads the French name of a country and adds the article: le for 
masculine or la for feminine, such as le Canada or la Belgique. 


However, if the country name starts with a vowel, use |’; for example, l’ Afghanistan. 
For the following plural country names, use les: 

e les Etats-Unis 

e les Pays-Bas 


Write a program to simulate a bank transaction. There are two bank accounts: check- 
ing and savings. First, ask for the initial balances of the bank accounts; reject nega- 
tive balances. Then ask for the transactions; options are deposit, withdrawal, and 
transfer. Then ask for the account; options are checking and savings. Then ask for the 
amount; reject transactions that overdraw an account. At the end, print the balances 
of both accounts. 


Write a program that reads in the name and salary of an employee. Here the salary 
will denote an hourly wage, such as $9.25. Then ask how many hours the employee 
worked in the past week. Be sure to accept fractional hours. Compute the pay. Any 
overtime work (over 40 hours per week) is paid at 150 percent of the regular wage. 
Print a paycheck for the employee. 


When you use an automated teller machine (ATM) with your bank card, you need 
to use a personal identification number (PIN) to access your account. If a user fails 
more than three times when entering the PIN, the machine will block the card. 
Assume that the user’s PIN is “1234” and write a program that asks the user for the 
PIN no more than three times, and does the following: 


e Ifthe user enters the right number, print a message saying, “Your PIN is 
correct”, and end the program. 


e Ifthe user enters a wrong number, print a message saying, “Your PIN is 
incorrect” and, if you have asked for the PIN less than three times, ask for it 
again. 

e Ifthe user enters a wrong number three times, print a message saying “Your 
bank card is blocked” and end the program. 


Calculating the tip when you go to a restaurant is not difficult, but your restaurant 
wants to suggest a tip according to the service diners receive. Write a program that 
calculates a tip according to the diner’s satisfaction as follows: 


e Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 
2 = Satisfied, 3 = Dissatisfied. 


132 Chapter 3 Decisions 


e Ifthe diner is totally satisfied, calculate a 20 percent tip. 
e Ifthe diner is satisfied, calculate a 15 percent tip. 
e Ifthe diner is dissatisfied, calculate a 10 percent tip. 


¢ Report the satisfaction level and tip in dollars and cents. 


=» Business P3.34 A supermarket awards coupons depending on how much a customer spends on 
groceries. For example, if you spend $50, you will get a coupon worth eight percent 
of that amount. The following table shows the percent used to calculate the coupon 
awarded for different amounts spent. Write a program that calculates and prints the 
value of the coupon a person can receive based on groceries purchased. 
Here is a sample run: 


Please enter the cost of your groceries: 14 
You win a discount coupon of $ 1.12. (8% of your purchase) 


Money Spent Coupon Percentage 
Less than $10 No coupon 
From $10 to $60 8% 
More than $60 to $150 10% 
More than $150 to $210 12% 
More than $210 14% 


= Science P3.35 Write a program that prompts the user for a wavelength value and prints a descrip- 


tion of the corresponding part of the electromagnetic spectrum, as given in the fol- 
lowing table. 


Electromagnetic Spectrum 





Type Wavelength (m) Frequency (Hz) 
Radio Waves Silo <3x10? 
Microwaves ier to len 3x 10? to3x10!! 
Infrared 7x 10-’ to 10% 3x10! to 4x 10" 


Visible light Ax 10) to7 ~10y ||) 4x 10171675 10)" 


Ultraviolet 1or to 4 1077 Fi M0 to 310.” 
X-rays NO = to tr® 3x 10! tot 10 
Gamma rays 0m Sox 10, 


= Science P3.36 Repeat Exercise P3.35, modifying the program so that it prompts for the frequency 
instead. 


Programming Exercises 133 


= Science P3.37 Repeat Exercise P3.35, modifying the program so that it first asks the user whether 


«== Science P3.38 A minivan has two sliding doors. Each door can be 


the input will be a wavelength or a frequency. 


opened by either a dashboard switch, its inside handle, 
or its outside handle. However, the inside handles do not 
work if a child lock switch is activated. In order for the 
sliding doors to open, the gear shift must be in park, and 
the master unlock switch must be activated. (This book’s 
author is the long-suffering owner of just such a vehicle.) 





Your task is to simulate a portion of the control software for the vehicle. The input is 
a sequence of values for the switches and the gear shift, in the following order: 


¢ Dashboard switches for left and right sliding door, child lock, and master 
unlock (0 for off or 1 for activated) 


e Inside and outside handles on the left and right sliding doors (0 or 1) 
e The gear shift setting (one of PND123R). 


A typical input would be 00010100P. 


Print “left door opens” and/or “right door opens” as appropriate. If neither door 
opens, print “both doors stay closed”. 


= Science P3.39 Sound level L in units of decibel (dB) is determined by 


en 





L = 20 logio(p/po) 


where p is the sound pressure of the sound (in Pascals, abbreviated Pa), and pp is a 
reference sound pressure equal to 20 x 10-° Pa (where L is 0 dB). The following table 
gives descriptions for certain sound levels. 


Threshold of pain 130 dB 
Possible hearing damage 120 dB 
Jack hammer at 1 m 100 dB 
Traffic ona busy roadway atl0m 90dB 
Normal conversation 60dB 
Calm library 30dB 
Light leaf rustling OdB 


Write a program that reads a value and a unit, either dB or Pa, and then prints the 
closest description from the list above. 


= Science P3.40 The electric circuit shown below is designed to measure the temperature of the gas in 


a chamber. 














11.43 V 
© Voltmeter @ 





134 Chapter 3 Decisions 


uae Science P3.41 





The resistor R represents a temperature sensor enclosed in the chamber. The resis- 
tance R, in Q, is related to the temperature T, in °C, by the equation 


In this device, assume Rp = 100 Q and k = 0.5. The voltmeter displays the value of the 
voltage, V,,,, across the sensor. This voltage V,,, indicates the temperature, T, of the 
gas according to the equation 


7-R_%_R& Vn 
k 


k kV,-V, k 


Suppose the voltmeter voltage is constrained to the range V,,;, = 12 volts < V,, s 
Vinax = 18 volts. Write a program that accepts a value of V,,, and checks that it’s 
between 12 and 18. The program should return the gas temperature in degrees 


Celsius when V,,, is between 12 and 18 and an error message when it isn’t. 


Crop damage due to frost is one of the many risks confronting farmers. The figure 
below shows a simple alarm circuit designed to warn of frost. The alarm circuit uses 
a device called a thermistor to sound a buzzer when the temperature drops below 
freezing. Thermistors are semiconductor devices that exhibit a temperature depen- 
dent resistance described by the equation 


1 1 
(4 
R=R e U 


where R is the resistance, in Q, at the temperature T, in °K, and Rg is the resistance, 
in Q, at the temperature To, in°K. 6 is a constant that depends on the material used to 
make the thermistor. 


Thermistor 





The circuit is designed so that the alarm will sound when 
Ry Ry 
R+R, Rz+R,y 





The thermistor used in the alarm circuit has Rg = 33,192 Q at Ty = 40 °C, and 

B= 3,310 °K. (Notice that 6 has units of °K. The temperature in °K is obtained by 
adding 273° to the temperature in °C.) The resistors Ry, R3, and Ry have a resistance 
of 156.3 kQ = 156,300 Q. 


Write a Java program that prompts the user for a temperature in °F and prints a 
message indicating whether or not the alarm will sound at that temperature. 


Answers to Self-Check Questions 135 


= Science P3.42 A mass m = 2 kilograms is attached to the end of a rope of length r = 3 meters. The 
mass is whirled around at high speed. The rope can withstand a maximum tension 
ot T= 60 Newtons. Write a program that accepts a rotation speed v and determines 
whether such a speed will cause the rope to break. Hint: T = mv?/r. 


= Science P3.43 A mass m is attached to the end of a rope of length ry = 3 meters. The rope can only 
be whirled around at speeds of 1, 10, 20, or 40 meters per second. The rope can 
withstand a maximum tension of T = 60 Newtons. Write a program where the user 
enters the value of the mass m, and the program determines the greatest speed at 
which it can be whirled without breaking the rope. Hint: T = mv*/r. 


ua Science P3.44 The average person can jump off the ground 
with a velocity of 7 mph without fear of leaving 
the planet. However, if an astronaut jumps with 
this velocity while standing on Halley’s Comet, 
will the astronaut ever come back down? Create 
a program that allows the user to input a launch 
velocity (in mph) from the surface of Halley’s 
Comet and determine whether a jumper will 
return to the surface. If not, the program should 
calculate how much more massive the comet 
must be in order to return the jumper to the surface. 


Hint: Escape velocity is Dacape'= pa ,where G = 6.67 x 10°" N m?/kg? is 


the gravitational constant, M = 1.3 x 107?kg is the mass of Halley’s comet, and 





R = 1.153 x 10°m is its radius. 


ANSWERS TO SELF-CHECK QUESTIONS 


1. Change the if statement to 7. floor <= 13 
if (floor > 14) 8. The values should be compared with ==, not =. 
{ ; aan 
actualFloor = floor - 2; 9. input.equals("Y") 
} 10. str.equals("") or str.lengthQ == 0 
2. 85.90. 85. 11. if (scoreA > scoreB) 
3. The only difference is if originalPrice is 100. { ; 
; System.out.printIn("A won"); 
The statement in Self Check 2 sets discounted- } ‘ . : 
Price to 90; this one sets it to 80. else if (scoreA < scoreB) 
4. 95,100.95. t ee ee 
System.out.printIn("B won"); 
5. if (fuelAmount < 0.10 * fuelCapacity) } 
{ else 
System.out.printInC"red"); { 
} System.out.printIn("Game tied"); 
else } 
{ . ; 
System.out.printIn(C"green") ; 12. if &>0) fs = ae = sdie 3 


} else if (x < 0 


) 
else { s = 0; } 
6. (a) and (b) are both true, (c) is false. 


136 Chapter 3 Decisions 


13. 


14. 


15. 
16. 


17. 
18. 


19. 


20. 


21. 


22. 


23. 


You could first set s to one of the three values: 
s=0; 

if «>0) {s=1; } 
else if (x < 0) { s = -1; } 

The if (price <= 100) can be omitted (leaving 
just else), making it clear that the else branch 
is the sole alternative. 


No destruction of buildings. 
Add a branch before the final else: 


else if (richter < 0) 


{ 


} 
3200. 


No. Then the computation is 0.10 x 32000 + 
0.25 x (32000 — 32000). 


No. Their individual tax is $5,200 each, and if 
they married, they would pay $10,400. Actu- 
ally, taxpayers in higher tax brackets (which 
our program does not model) may pay higher 
taxes when they marry, a phenomenon known 
as the marriage penalty. 


System.out.printIn("Error: Negative input"); 


Change else in line 41 to 


else if (maritalStatus.equals("m")) 
and add another branch after line 52: 


else 


{ 
System.out.printin( 
"Error: marital status should be s or m."); 


} 


The higher tax rate is only applied on the 
income in the higher bracket. Suppose you are 
single and make $31,900. Should you try to 
get a $200 raise? Absolutely: you get to keep 
90 percent of the first $100 and 75 percent of 
the next $100. 


Read temp 
True : 
temp <0? Print “Frozen” 


False 


The “True” arrow from the first decision 
points into the “True” branch of the second 
decision, creating spaghetti code. 


24 


. Here is one solution. In Section 3.7, you will 
see how you can combine the conditions fora 
more elegant solution. 


Input < 0? 


False 


Input > 100? 


False 


Status = “OK” 


Read x 


x<0? 


False 


Print vx 


Read temp 


temp <0? 


False 


temp > 100? 


False 


Print “Liquid” 


True 
Status = “Error” 


True 
Status = “Error” 


True 


Print “Error” 


True 


Print “Ice” 


True 
Print “Steam” 


27. 


29. 


30. 


31. 


32. 
33. 
34. 
35. 
36. 











Test Expected 
Case _ Output Comment 
12 12 Below 13th floor 
14 13 Above 13th floor 
13 2 The specification is not clear— See 


Section 3.8 for a version of this 
program with error handling 





A boundary test case is a price of $128. A 16 
percent discount should apply because the 
problem statement states that the larger dis- 
count applies if the price is at least $128. Thus, 
the expected output is $107.52. 


Test Expected 
Case Output 

9 Most structures fall 
7.5 Many buildings destroyed 


Comment 























65 Many buildings ... 
5 Damage to poorly... 
3 No destruction... 

3.0 Most structures fall Boundary case. In this 
program, boundary cases 
are not as significant 
because the behavior of 
an earthquake changes 
gradually. 

-] The specification is not 


clear—see Self Check 
16 for a version of this 
program with error 


handling. 


Test Case Expected Output Comment 
(0.5, 0.9) inside 
(4, 2) outside 
(0, 2) on the boundary Exactly on the boundary 


(1.414, 1.414) onthe boundary Close to the boundary 





(0, 1.9) inside Not less than 1 mm 
from the boundary 

(0, 2.1) outside Not less than 1 mm 
from the boundary 





x == 0 && y == 0 

x==0 || y==0 

(x == 0 && y != 0) || (y == 0 && x != 0) 
The same as the value of frozen. 


You are guaranteed that there are no other 
values. With strings or integers, you would 
need to check that no values such as "maybe" or 
~1 enter your calculations. 


37. 


38. 
. Check for in.hasNextDouble(), to make sure a 


40. 


Answers to Self-Check Questions 137 


(a) Error: The floor must be between 1 and 20. 
(b) Error: The floor must be between 1 and 20. 
(c) 19 (d) Error: Not an integer. 


floor == 13 || floor <= 0 || floor > 20 


researcher didn’t supply an input such as oh 

my. Check for weight <= 0, because any rat must 
surely have a positive weight. We don’t know 
how giant a rat could be, but the New Guinea 
rats weighed no more than 2 kg. A regular 
house rat (rattus rattus) weighs up to 0.2 kg, so 
we'll say that any weight > 10 kg was surely an 
input error, perhaps confusing grams and kilo- 
grams. Thus, the checks are 


if Cin.hasNextDouble()) 
{ 


double weight = in.nextDouble(); 
if (weight < 0) 
{ 
System.out.printIn( 
"Error: Weight cannot be negative."); 


else if (weight > 10) 
{ 
System.out.printIn( 
"Error: Weight > 10 kg."); 
} 


else 


Process valid weight. 
} 
} 


else 


} 


System.out.printC"Error: Not a number"); 


The second input fails, and the program termi- 
nates without printing anything. 


CHAPTER GOALS 








To implement while, for, and do loops 
To hand-trace the execution of a program 


To become familiar with common 
loop algorithms 


To understand nested loops 


To implement programs that read and process data sets 


To use a computer for simulations 


CHAPTER CONTENTS 


4.1 THEWHILELOOP 140 

Syntax 4.1: while Statement 141 

Common Error 4.1: Don’t Think “Are We 
There Yet?” 144 

Common Error 4.2: |Infinite Loops 145 

Common Error 4.3: Off-by-One Errors 145 

Random Fact 4.1: The First Bug 146 


4.2 PROBLEM SOLVING: 
HAND-TRACING 147 


4.3 THEFORLOOP 150 

Syntax 4.2: for Statement 152 

Programming Tip 4.1: Use for Loops for Their 
Intended Purpose Only 155 

Programming Tip 4.2: Choose Loop Bounds That 
Match Your Task 155 

Programming Tip 4.3: Count Iterations 156 


4.4 THEDOLOOP 156 
Programming Tip 4.4: Flowcharts for Loops 157 


4.5 APPLICATION: PROCESSING 
SENTINEL VALUES 158 

Special Topic 4.1: The Loop-and-a-Half Problem 
and the break Statement 160 


Special Topic 4.2: Redirection of Input 
and Output 161 

Video Example 4.1: Evaluating a Cell 
Phone Plan @ 


4.6 PROBLEM SOLVING: 
STORYBOARDS 162 


4.7 COMMON LOOP ALGORITHMS 165 
How To 4.1: Writing a Loop 169 
Worked Example 4.1: Credit Card Processing @ 


4.8 NESTEDLOOPS 172 


Worked Example 4.2: Manipulating the Pixels 
inanlmage @ 


4.9 APPLICATION: RANDOM NUMBERS 
AND SIMULATIONS 176 

Special Topic 4.3: Drawing Graphical Shapes 179 

Video Example 4.2: Drawing a Spiral © 

Random Fact 4.2: Software Piracy 182 





activities in the real world. 





4.1 The while Loop 


In this section, you will learn about loop statements that 
repeatedly execute instructions until a goal has been 
reached. 

Recall the investment problem from Chapter 1. You 
put $10,000 into a bank account that earns 5 percent inter- 
est per year. How many years does it take for the account 
balance to be double the original investment? 

In Chapter 1 we developed the following algorithm for 
this problem: 


In a loop, a part of a program is repeated over and over, 
until a specific goal is reached. Loops are important for 
calculations that require repeated steps and for processing 
input consisting of many data items. In this chapter, you will 
learn about loop statements in Java, as well as techniques 
for writing programs that process input and simulate 


—e 


Because the interest 
earned also earns interest, 
a bank balance grows 
exponentially. 


Start with a year valve of 0, a column for the interest, and a balance of 10,000. 


interest balance 
$10,000 

















Repeat the following steps while the balance is less than #Z0,000. 
Add 1 to the year value. 
Compute the interest as balance x 0.09 (i.e. 9 percent interest). 
Add the interest to the balance. 

Report the final year value as the answer. 


You now know how to declare and update the variables in Java. What you don’t yet 
know is how to carry out “Repeat steps while the balance is less than $20,000”. 


In a particle accelerator, subatomic particles 
traverse a loop-shaped tunnel multiple times, 
gaining the speed required for physical experiments. 
Similarly, in computer science, statements in a 

loop are executed while a condition is true. 


140 





4.1. Thewhile Loop 141 


Figure 1 Flowchart of awhile Loop 


balance < False 
TARGET ? 
incon In Java, the while statement implements such a True 
instructions repetition (see Syntax 4.1). It has the form 
repeatedly while a ; as 
condition is true. while (condition) Increment 
{ year 
statements 
} 
As long as the condition remains true, the statements ae 
. . F t 
inside the while statement are executed. These state- aegis 
. interest 
ments are called the body of the while statement. 
In our case, we want to increment the year coun- 
ter and add interest while the balance is less than the 
target balance of $20,000: Add interest 
while (balance < TARGET) be leuies 
{ 
year++; 
double interest = balance * RATE / 100; 
balance = balance + interest; 
} 


A while statement is an example of a loop. If you draw a flowchart, the flow of execu- 
tion loops again to the point where the condition is tested (see Figure 1). 


Syntax 4.1 while Statement 


Syntax while (condition) 
{ 


statements 


} 


This variable is declared outside the loop 
and updated in the loop. 


Beware of “off-by-one” 
errors in the loop condition. 


double balance = 0; AR See page 149. 


If the condition 
never becomes false, 
an infinite loop occurs. 


. See page $6. 
AR See page 149. while (balance < TARGET) bicuee 


{ = These statements 
double interest = balance * RATE / 100; i ci wele 
This variable is created —— balance = 


; bide = balance + interest; a the condition is true. 
in each loop iteration. } 


Don't put a semicolon here! 





ce ease eae 
is a good idea. a sing ment, but it's g always mM. 


See page 36. ake page 86. 





142 Chapter4 Loops 


When you declare a variable inside the loop body, the variable is created for each 
iteration of the loop and removed after the end of each iteration. For example, con- 
sider the interest variable in this loop: 


while (balance < TARGET) 

{ 
year++; 
double interest = balance * RATE / 100; 
balance = balance + interest; 

} // interest no longer declared here 





In contrast, the balance and years variables were declared outside the loop body. That 
way, the same variable is used for all iterations of the loop. 


@ Check the loop condition _ The condition is true 
while (balance < TARGET) 
; i 
oe year++; 
double interest = balance * RATE / 100; 
year= 0 | balance = balance + interest; 
i 


2] Execute the statements in the loop 
while (balance < TARGET) 


; { 
] 10500 year++: 
double interest = balance * RATE / 100; 
= balance = balance + interest; 
} 
500 


3 Check the loop condition again 





while (balance < TARGET) 


: { 
lan 10500 year++; 
double interest = balance * RATE / 100; 
balance = balance + interest; 
} 


4) After 15 iterations 





while (balance < TARGET) 


5 it 
ice 20789.28 year++; 
double interest = balance * RATE / 100; 
balance = balance + interest; 
$ 


5 } Execute the statement following the loop 
while (balance < TARGET) 


alance = 20789.28 { 
year++; 
Figure 2 double interest = balance * RATE / 100; 
Execution of the balance = balance + interest; 


t 


DoubleInvestment System.out.printIn(year) ; 


Loop 


4.1. Thewhile Loop 143 


Here is the program that solves the investment problem. Figure 2 illustrates the pro- 
gram’s execution. 


section_1/Doublelnvestment.java 
[** 


2 __ This program computes the time required to double an investment. 
i Lee class DoubleInvestment 

Z ' public static void main(String[] args) 

3 

9 


{ 

final double RATE = 5; 

final double INITIAL_BALANCE = 10000; 
10 final double TARGET = 2 * INITIAL_BALANCE; 
11 
12 double balance = INITIAL_BALANCE; 
13 int year = 0; 
14 
15 // Count the years required for the investment to double 
16 
17 while (balance < TARGET) 
18 { 
19 year++; 
20 double interest = balance * RATE / 100; 
21 balance = balance + interest; 
22 } 
23 
24 System.out.printin("The investment doubled after " 
25 + year +" years.")3 
26 } 
Care 


Program Run 


The investment doubled after 15 years. 


1. How many years does it take for the investment to triple? Modify the program 
and run it. 


2. Ifthe interest rate is 10 percent per year, how many years does it take for the 
investment to double? Modify the program and run it. 





3. Modify the program so that the balance after each year is printed. How did you 
do that? 


4. Suppose we change the program so that the condition of the while loop is 
while (balance <= TARGET) 
What is the effect on the program? Why? 

5. What does the following loop print? 


intn=1; 
while (n < 100) 
{ 

aa iH 


System.out.print(n +" "); 


} 


Practice It Now youcantry these exercises at the end of the chapter: R4.1, R4.5, P4.14. 


144 Chapter 4 Loops 


Table 1 while Loop Examples 


Loop Output Explanation 

i = 0; sum = 0; il When sum is 10, the loop condition is 

while (sum < 10) 2s false, and the loop ends. 

{ 3 
i++; sum = sum + 7; 4 10 
Print i and sum; 

} 

i = 0; sum = 0; il = Because sum never reaches 10, this is an 

while (sum < 10) 2 =3 “infinite loop” (see Common Error 4.2 

{ 3 -6 on page 145). 
i++; sum = sum - 7; 4 -10 
Print i and sum; 

} 

i = 0; sum = 0; (No output) The statement sum < 0 is false when the 

while (sum < 0) condition is first checked, and the loop 

{ is never executed. 
i++; sum = sum - 7; 

Print i and sum; 

} 

i = 0; sum = 0; (No output) The programmer probably thought, 

while (sum >= 10) “Stop when the sum is at least 10.” 

{ However, the loop condition controls 
i++; sum = sum + 7; when the loop is executed, not when it 
Print i and sum; ends (see Common Error 4.1 on 

} page 144). 

i = 0; sum = 0; (No output, program Note the semicolon before the {. 

while (sum < 10) ; does not terminate) This loop has an empty body. It runs 

{ forever, checking whether sum < 0 and 
i++; sum = sum + i; doing nothing in the body. 

Print i and sum; 

} 


Common Error 4.1 Don’t Think “Are We There Yet?” 


When doing something repetitive, most of us want to know when 
we are done. For example, you may think, “I want to get at least 
$20,000,” and set the loop condition to 


balance >= TARGET 





But the while loop thinks the opposite: How long am I allowed to 
keep going? The correct loop condition is 


while (balance < TARGET) 


In other words: “Keep at it while the balance is less than the target.” 


When writing a loop condition, don’t ask, “Are we there yet?” 
The condition determines how long the loop will keep going. 








(@foyaalankelamala ae) meas) 








4.1 ThewhileLoop 145 


Infinite Loops 


A very annoying loop error is an infinite loop: a loop that 
runs forever and can be stopped only by killing the program 
or restarting the computer. If there are output statements 
in the program, then reams and reams of output flash by on 
the screen. Otherwise, the program just sits there and hangs, 
seeming to do nothing. On some systems, you can kill a hang- 
ing program by hitting Ctrl + C. On others, you can close the 
window in which the program runs. 

A common reason for infinite loops is forgetting to update 
the variable that controls the loop: 





int year = 1; 


while (year <= 20) Like this hamster who can’t 
{ stop running in the treadmill, 
double interest = balance * RATE / 100; an infinite loop never ends. 


balance = balance + interest; 


} 


Here the programmer forgot to add a year++ command in the loop. As a result, the year always 
stays at 1, and the loop never comes to an end. 

Another common reason for an infinite loop is accidentally incrementing a counter that 
should be decremented (or vice versa). Consider this example: 


int year = 20; 
while (year > 0) 


{ 
double interest = balance * RATE / 100; 
balance = balance + interest; 
year++; 

} 


The year variable really should have been decremented, not incremented. This is a common 
error because incrementing counters is so much more common than decrementing that your 
fingers may type the ++ on autopilot. As a consequence, year is always larger than 0, and the 
loop never ends. (Actually, year may eventually exceed the largest representable positive inte- 
ger and wrap around to a negative number. Then the loop ends—of course, with a completely 
wrong result.) 


Off-by-One Errors 


Consider our computation of the number of years that are required to double an investment: 


int year = 0; 

while (balance < TARGET) 

{ 
yeart++; 
balance = balance * (1 + RATE / 100); 

} 

System.out.printIn("The investment doubled after 
+ year +" years."); 


Should year start at 0 or at 1? Should you test for balance < TARGET or for balance <= TARGET? It is 
easy to be off by one in these expressions. 


146 Chapter 4 Loops 


Some people try to solve off-by-one errors by randomly inserting +1 or -1 until the pro- 
gram seems to work—a terrible strategy. It can take a long time to compile and test all the vari- 
ous possibilities. Expending a small amount of mental effort is a real time saver. 

Fortunately, off-by-one errors are easy to avoid, simply by 
thinking through a couple of test cases and using the information 
from the test cases to come up with a rationale for your decisions. 

Should year start at 0 or at 1? Look at a scenario with simple val- 
ues: an initial balance of $100 and an interest rate of 50 percent. After 
year 1, the balance is $150, and after year 2 it is $225, or over $200. So 
the investment doubled after 2 years. The loop executed two times, 
incrementing year each time. Hence year must start at 0, not at 1. 


An off-by-one error is 
a common error 
when programming 
loops. Think through 
simple test cases 

to avoid this type 

of error. 


year balance 
0 #100 





1 #150 
Z 9225 





In other words, the balance variable denotes the balance after the end of the year. At the outset, 
the balance variable contains the balance after year 0 and not after year 1. 

Next, should you use a < or <= comparison in the test? This is harder to figure out, because 
it is rare for the balance to be exactly twice the initial balance. There is one case when this 
happens, namely when the interest is 100 percent. The loop executes once. Now year is 1, and 
balance is exactly equal to 2 * INITIAL_BALANCE. Has the investment doubled after one year? It 
has. Therefore, the loop should not execute again. If the test condition is balance < TARGET, the 
loop stops, as it should. If the test condition had been balance <= TARGET, the loop would have 
executed once more. 

In other words, you keep adding interest while the balance has not yet doubled. 


Random Fact 4.1 The First Bug 


According to legend, 
the first bug was 
found in the Mark II, a huge electrome- 
chanical computer at Harvard Univer- 
sity. It really was caused by a bug—a 
moth was trapped ina relay switch. 

Actually, from the note that the 
operator left in the log book next to 
the moth (see the photo), it appears as 
if the term “bug” had already been in 
active use at the time. 





The First Bug 


The pioneering computer scientist 
Maurice Wilkes wrote, “Somehow, at 
the Moore School and afterwards, one 
had always assumed there would be 
no particular difficulty in getting pro- 


ee ek 


1/ae 


sine 





grams right. | can remember the exact 
instant in time at which it dawned on 
me that a great part of my future life 
would be spent finding mistakes in my 
own programs.” 


Come py 


Top< (Sine chest) 


Ad clas Bales (2 Pane| F 
(mc Th) vn relay: 


29 bug being found. 


Hand-tracing isa 
simulation of code 
execution in which 
you step through 
instructions and 
track the values of 
the variables. 


4.2 Problem Solving: Hand-Tracing 147 


In Programming Tip 3.5, you learned about the method of hand-tracing. When you 
hand-trace code or pseudocode, you write the names of the variables on a sheet of 
paper, mentally execute each step of the code and update the variables. 

It is best to have the code written or printed on a sheet of paper. Use a marker, 
such as a paper clip, to mark the current line. Whenever a variable changes, cross out 
the old value and write the new value below. When a program produces output, also 
write down the output in another column. 

Consider this example. What value is displayed? 

int n = 1729; 

int sum = 0; 

while (n > 0) 


{ 
int digit =n % 10; 
sum = sum + digit; 
n=n/ 10; 

} 


System.out.printIn(sum) ; 


There are three variables: n, sum, and digit. 











The first two variables are initialized with 1729 and 0 before the loop is entered. 


int n = 1729; 
 _ int sum = 0; 
while (n > 0) 














{ 
int digit =n % 10; 
sum = sum + digit; 
n=n/ 10; 

} 





System.out.printIn(sum) ; 











ae 





Because nis greater than zero, enter the loop. The variable digit is set to 9 (the remain- 
der of dividing 1729 by 10). The variable sumis set to0+9=9. 


int n = 1729; 
int sum = 0; 
while (n > 0) 
{ 








int digit =n % 10; 
(comms) sum = sum + digit; 
n=n/ 10; 








} 


System.out.printIn(sum) ; 




















148 Chapter 4 Loops 


Finally, n becomes 172. (Recall that the remainder in the division 1729 / 10 is dis- 
carded because both arguments are integers.) 
Cross out the old values and write the new ones under the old ones. 











int n = 1729; a 
int sum = 0; n sum digit 
while (n > 0) 174g 104 

{ 


int digit = n % 10; 7Z | 9 a 


sum = sum + digit; 
(cama) n=n/ 10; 
} 

















System.out.printIn(sum) ; 














Now check the loop condition again. 
int n = 1729; 


int sum = 0; 
C& while (n > 0) 
{ 


int digit =n % 10; 
sum = sum + digit; 
n=n/ 10; 

} 


System.out.print]n(sum) ; 


Because nis still greater than zero, repeat 



















































































the loop. Now digit becomes 2, sum is set 
to9+2=11, and nis set to 17. 
ome 
Repeat the loop once again, setting digit os 
£6 7; sumto 1 + 7=18; and nto 1, Pe ese eh 
1729 | 
VL x x 
YW Uv 0S 
1 18 7 
Es 
Enter the loop for one last time. Now fek 
digit is set to 1, sum to 19, and n becomes ws via is 
zero. 1729 
pegs x 
Ww Ww z 
xX wv Te 
0 19 1 
ee 








hm 
ANIMATION 
Tracing a Loop 


it 


Hand-tracing can 
help you understand 
how an unfamiliar 
algorithm works. 


Hand-tracing can 
show errors in code 
or pseudocode. 








4.2 Problem Solving: Hand-Tracing 149 


int n = 1729; 
int sum = 0; 


Cc) whil 
t MeN Because n equals zero, 


int digit =n % 10: this condition is not true. 
sum = sum + digit; 
n=n/ 10; 

} 


System.out.printIn(sum) ; 


The condition n > 0 is now false. Continue with the statement after the loop. 


int n = 1729; 
int sum = 0; 
while (n > 0) 

















{ 
int digit =n % 10; 
sum = sum + digit; 
n=n/ 10; 

} 





Ce System.out.printin(sum) ; 




















This statement is an output statement. The value that is output is the value of sum, 
which is 19. 

Of course, you can get the same answer by just running the code. However, hand- 
tracing can give you an insight that you would not get if you simply ran the code. 
Consider again what happens in each iteration: 


e We extract the last digit of n. 
e We add that digit to sum. 
¢ We strip the digit off n. 


In other words, the loop forms the sum of the digits in n. You now know what the 
loop does for any value of n, not just the one in the example. (Why would anyone 
want to form the sum of the digits? Operations of this kind are useful for checking 
the validity of credit card numbers and other forms of ID numbers—see Exercise 
P4.32.) 

Hand-tracing does not just help you understand code that works correctly. It is 
a powertul technique for finding errors in your code. When a program behaves in a 
way that you don’t expect, get out a sheet of paper and track the values of the vari- 
ables as you mentally step through the code. 

You don’t need a working program to do hand-tracing. You can hand-trace 
pseudocode. In fact, it is an excellent idea to hand-trace your pseudocode before you 
go to the trouble of translating it into actual code, to confirm that it works correctly. 


6. Hand-trace the following code, showing the value of n and the output. 


int n= 5; 

while (n >= 0) 

{ 
n--; 
System.out.print(n); 


} 


150 Chapter 4 Loops 


Practice It 


Ta 


10. 


Hand-trace the following code, showing the value of n and the output. What 
potential error do you notice? 
int n = 1; 
while (n <= 3) 
{ 
System.out.print(n + ", "); 
n++; 
t 


Hand-trace the following code, assuming that ais 2 and nis 4. Then explain what 
the code does for arbitrary values of aand n. 


int r=1; 
int 7 = 1; 
while (i <= n) 
{ 
rene as 
itt; 
t 
Trace the following code. What error do you observe? 
intn=1; 
while (n != 50) 
{ 
System.out.printIn(n) ; 
n=n +4 10; 
} 


The following pseudocode is intended to count the number of digits in the 
number u: 


count = 1 

temp =n 

while (temp > 10) 
Increment count. 
Divide temp by 10.0. 


Trace the pseudocode for n= 123 and n= 100. What error do you find? 


Now you can try these exercises at the end of the chapter: R4.3, R4.6. 


4.3 The for Loop 


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 
example: 


The for loop is 
used whena 

value runs froma 
starting point to an 
ending point witha 
constant increment 
or decrement. 


int counter = 1; // Initialize the counter 
while (counter <= 10) // Check the counter 
{ 

System.out.printIn(counter) ; 

counter++; // Update the counter 


} 


Because this loop type is so common, there is a special form for it, called the for loop 
(see Syntax 4.2). 


4.3 TheforLoop 151 


for (int counter = 1; counter <= 10; 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 executes 
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 definite number of times; ten times in our example. 
In contrast, you do not know how many iterations 
it takes to accumulate a target balance. Such a loop is 
called indefinite. 

The for loop neatly groups the initialization, con- 
dition, and update expressions together. However, it You can visualize the for loop as 
is important to realize that these expressions are not an orderly sequence of steps. 
executed together (see Figure 3). 


System.out.printIn(counter) ; 





TmA 
ANIMATION 
The for Loop 


¢ The initialization is executed once, before the loop is entered. @ 
/ | \ ¢ The condition is checked before each iteration. @@ 


¢ The update is executed after each iteration. @ 


1) Initialize counter 


for (int counter = 1; counter <= 10; counter++) 


{ 


System.out.printIn(Ccounter) ; 


} 





for (int counter = 1; counter <= 10; counter++) 
‘t 
System.out.printIn(counter) ; 


} 





for (int counter = 1; counter <= 10; counter++) 


{ 


System.out.printIn(counter) ; 





t 


for (int counter = 1; counter <= 10; counter++) 
{ 


System.out.printIn(Ccounter) ; 





} 


for (int counter = 1; counter <= 10; counter++) 


i 
Figure 3 


Execution of a 
for Loop 


System.out.printIn(counter) ; 





t 


152 Chapter 4 Loops 


Syntax 4.2 for Statement 


Syntax for (initialization; condition; update) 


statements 


} 
These three 


expressions should be related. 


ti See page 199. 


This initialization The condition is This update is 

happens once checked before executed after 

before the loop starts. each iteration. each iteration. 
for (int 1 = 5; 7 <= 10; i++) 
{ 

The variable 7 is sum = sum + 7; This loop executes 6 times. 
defined only in this for loop. } iS page 196. 
See page 193. 





A for loop can count down instead of up: 
for (int counter = 10; counter >= 0; counter--) ... 
The increment or decrement need not be in steps of 1: 
for (int counter = 0; counter <= 10; counter = counter +2)... 


See Table 2 for additional variations. 
So far, we have always declared the counter variable in the loop initialization: 


for (int counter = 1; counter <= 10; counter++) 


{ 
} 


// counter no longer declared here 


Table 2 for Loop Examples 


Loop Values of 7 Comment 
for Gi = 0; 7 <= 5; i++) 012345 Note that the loop is executed 6 times. (See 
Programming Tip 4.3 on page 156.) 
for (i = 5; i >= 0; i--) 543210 Use i-- for decreasing values. 
ou Gh = eae al ) 02468 Use i = i + 2forastep size of 2. 
for (i = 0; i != 9; i = 7+ 2) 02468101214... You can use < or <= instead of != to avoid 
(infinite loop) this problem. 
for Gi = 1; i < 20; i =i * 2) 124816 You can specify any rule for modifying i, 


such as doubling it in every step. 


for (i = 0; i < str.lengthQ; i++) 012... untilthelastvalid Inthe loop body, use the expression 
index of the string str str.charAt(i) to get the ith character. 


4.3 TheforLoop 153 


Such a variable is declared for all iterations of the loop, but you cannot use it after the 
loop. If you declare the counter variable before the loop, you can continue to use it 
after the loop: 

int counter; 

for (counter = 1; counter <= 10; counter++) 


{ 
} 


// counter still declared here 


Here is a typical use of the for loop. We want to print the balance of our savings 
account over a period of years, as shown in this table: 


Year Balance 

1 10500.00 
year = 1 

2 11025.00 

3) 11576.25 

4 12155.06 

5 12762.82 


False 
year < nyears? 


The for loop pattern applies because the variable 
year starts at 1 and then moves in constant incre- 


oe True 
ments until it reaches the target: 
for (int year = 1; year <= nyears; year++) Update balance; 
Print year and 
Update balance. ia 
Print year and balance. 
} 
Following is the complete program. Figure 4 
shows the corresponding flowchart. 
yeart++ 


Figure 4 Flowchart of a for Loop 


section_3/InvestmentTable.java 


1 import java.util.Scanner; 


2 
3 [** 
4 This program prints a table showing the growth of an investment. 
sy yf 
6 public class InvestmentTable 
oe 
8 public static void main(String[] args) 
9 { 
10 final double RATE = 5; 
11 final double INITIAL_BALANCE = 10000; 


154 Chapter 4 Loops 


12 double balance = INITIAL_BALANCE; 

13 

14 System.out.print("Enter number of years: "); 
15 Scanner in = new Scanner(System. in); 

16 int nyears = in.nextIntQ); 

17 

18 // Print the table of balances for each year 

19 

20 for (int year = 1; year <= nyears; year++) 
21 { 

22 double interest = balance * RATE / 100; 
23 balance = balance + interest; 

24 System.out.printf("'%4d %10.2f\n", year, balance); 
25 } 

26 } 

Vy an 


Program Run 


Enter number of years: 10 
1 10500.00 
11025.00 
11576.25 
12155.06 
12762. 82 
13400.96 
14071.00 
14774.55 
I 13} 6 263 
16288.95 


OOONDUNHRWN 


eA 


Another common use of the for loop is to traverse all characters of a string: 


for Cint i = 0; i < str.lengthQ); i++) 
{ 
char ch = str.charAt(i); 
Process ch 
} 
Note that the counter variable i starts at 0, and the loop is terminated when i reaches 
the length of the string. For example, if str has length 5, i takes on the values 0, 1, 2, 3, 
and 4. These are the valid positions in the string. 


11. Write the for loop of the InvestmentTable. java program as a while loop. 
12. How many numbers does this loop print? 

for (int n = 10; n >= 0; n--) 

{ 

} 


13. Write a for loop that prints all even numbers between 10 and 20 (inclusive). 





System.out.printIn(n) ; 


14. Write a for loop that computes the sum of the integers from 1 to n. 


15. How would you modify the for loop of the InvestmentTable. java program to 
print all balances until the investment has doubled? 


Practice It Now youcantry these exercises at the end of the chapter: R4.4, R4.10, P4.8, P4.13. 


Programming Tip 4.1 





aceyela-laalaaliale mm Nl ok-ay4 





4.3 TheforLoop 155 


Use for Loops for Their Intended Purpose Only 


A for loop is an idiom for a loop of a particular form. A value runs from the start to the end, 
with a constant increment or decrement. 

The compiler won’t check whether the initialization, condition, and update expressions are 
related. For example, the following loop is legal: 


// Confusing—unrelated expressions 
for (System.out.print("Inputs: "); in.hasNextDouble(); sum = sum + x) 
{ 


x = in.nextDoubleQ; 


} 


However, programmers reading such a for loop will be confused because it does not match 
their expectations. Use a while loop for iterations that do not follow the for idiom. 

You should also be careful not to update the loop counter in the body of a for loop. Con- 
sider the following example: 


for (int counter = 1; counter <= 100; counter++) 


{ 
if (counter % 10 == 0) // Skip values that are divisible by 10 


{ 
} 


System.out.printIn(counter) ; 


counter++; // Bad style—you should not update the counter in a for loop 


} 


Updating the counter inside a for loop is confusing because the counter is updated again at the 
end of the loop iteration. In some loop iterations, counter is incremented once, in others twice. 
This goes against the intuition of a programmer who sees a for loop. 

If you find yourself in this situation, you can either change from a for loop to awhile loop, 
or implement the “skipping” behavior in another way. For example: 


for (int counter = 1; counter <= 100; counter++) 


{ 
if (counter % 10 != 0) // Skip values that are divisible by 10 
{ 
System.out.printIn(counter) ; 
} 
} 


Choose Loop Bounds That Match Your Task 


Suppose you want to print line numbers that go from 1 to 10. Of course, you will use a loop: 
for (int i = 1; i <= 10; i++) 


The values for i are bounded by the relation 1 < is 10. Because there are < on both bounds, the 
bounds are called symmetric. 
When traversing the characters in a string, it is more natural to use the bounds 


for (int i = 0; i < str.lengthQ); i++) 


In this loop, i traverses all valid positions in the string. You can access the ith character as str. 
charAt(i). The values for i are bounded by 0 <i <str. length), witha sto the left and a<to the 
right. That is appropriate, because str.length() is not a valid position. Such bounds are called 
asymmetric. 

In this case, it is not a good idea to use symmetric bounds: 


for (int i = 0; i <= str.lengthQ - 1; i++) // Use < instead 


The asymmetric form is easier to understand. 


156 Chapter 4 Loops 


Programming Tip 4.3 


Count Iterations 


Finding the correct lower and upper bounds for an iteration can be confusing. Should you 
start at 0 or at 1? Should you use <= b or < basa termination condition? 

Counting the number of iterations is a very useful device for better understanding a loop. 
Counting is easier for loops with asymmetric bounds. The loop 


for (int i = a; i < b; i++) 
is executed b - a times. For example, the loop traversing the characters in a string, 
for Cint i = 0; i < str.lengthQ); i++) 


runs str. length() times. That makes perfect sense, because there are str. length() characters in 
a string. 
The loop with symmetric bounds, 


for (int i = a; 7 <= b; i++) 


is executed b - a + 1times. That “+1” is the source of many programming errors. 
For example, 


for (int i = 0; i <= 10; i++) 


runs 11 times. Maybe that is what you want; if not, start at 1 or use < 10. 

One way to visualize this “+1” error is 
by looking at a fence. Each section has one 
fence post to the left, and there is a final post 
on the right of the last section. Forgetting to 
count the last value is often called a “fence 
post error”. 


How many posts do you need for a fence 
with four sections? It is easy to be “off by one” 
with problems such as this one. 





4.4 The do loop 


The do loop is 
appropriate when 
the loop body 
must be executed 
at least once. 


ONLINE EXAMPLE 


A program to 
illustrate the use of 
the do loop for input 
validation. 


Sometimes you want to execute the body of a loop at least once and perform the loop 
test after the body is executed. The do loop serves that purpose: 


do 
{ 


statements 


while (condition); 


The body of the do loop is executed first, then the condition is tested. 

Some people call such a loop a post-test loop because the condition is tested after 
completing the loop body. In contrast, while and for loops are pre-test loops. In those 
loop types, the condition is tested before entering the loop body. 

A typical example for a do loop is input validation. Suppose you ask a user to enter 
a value < 100. If the user doesn’t pay attention and enters a larger value, you ask 
again, until the value is correct. Of course, you cannot test the value until the user has 
entered it. This is a perfect fit for the do loop (see Figure 5): 





Practice It 


Programming Tip 4.4 





16. 


17. 


18. 


19. 


20. 


4.4 ThedoLoop 157 


Figure 5 Flowchart of a do Loop 


int value; 
do Prompt user 
1 to enter 
System.out.print("Enter an integer < 100: "); a value < 100 
value = in.nextIntQ); 
} 
while (value >= 100); 
Copy the input 
to value 


Suppose that we want to check for inputs that are 
at least 0 and at most 100. Modify the do loop for 
this check. 


Rewrite the input check do loop using a while loop. 

What is the disadvantage of your solution? ive 
Suppose Java didn’t have a do loop. Could you 

rewrite any do loop as a while loop? 

Write a do loop that reads integers and computes False 


their sum. Stop when reading the value 0. 

Write a do loop that reads integers and computes their sum. Stop when reading a 
zero or the same value twice in a row. For example, if the input is 1 2 3 4 4, then 
the sum is 14 and the loop stops. 


Now you can try these exercises at the end of the chapter: R4.9, R4.16, R4.17. 


Flowcharts for Loops 


In Section 3.5, you learned how to use flowcharts to visualize the flow of control ina program. 
There are two types of loops that you can include in a flowchart; they correspond to a while 
loop and a do loop in Java. They differ in the placement of the condition—either before or after 
the loop body. 


False 


Condition? Loop body 
True 

Sr aa! a Condition? 

False 


As described in Section 3.5, you want to avoid “spaghetti code” in your flowcharts. For loops, 
that means that you never want to have an arrow that points inside a loop body. 


158 Chapter 4 Loops 


A sentinel value 
denotes the end of a 
data set, but it is not 
part of the data. 


In this section, you will learn how to write loops that read and process a sequence of 
input values. 

Whenever you read a sequence of inputs, you 
need to have some method of indicating the end 
of the sequence. Sometimes you are lucky and no 
input value can be zero. Then you can prompt the 
user to keep entering numbers, or 0 to finish the 
sequence. If zero is allowed but negative numbers 
are not, you can use —1 to indicate termination. 

Such a value, which is not an actual input, 
but serves as a signal for termination, is called a 
sentinel. 

Let’s put this technique to work in a program 
that computes the average of a set of salary values. 
In our sample program, we will use -1 asa sentinel. 
Anemployee would surely not work for a negative 
salary, but there may be volunteers who work for 
free. 

Inside the loop, we read an input. If the input is 
not—1, we process it. In order to compute the aver- In the military, a sentinel guards 


age, we need the total sum of all salaries, and the 49 border or passage. In computer 
number of inputs. science, a sentinel value denotes 
the end of an input sequence or the 

salary = in.nextDouble(); border between input sequences. 
if (salary != -1) 
{ 

sum = sum + Salary; 

count++; 


} 


We stay in the loop while the sentinel value is not detected. 





while (salary != -1) 
{ 
} 


There is just one problem: When the loop is entered for the first time, no data value 
has been read. We must make sure to initialize salary with some value other than the 
sentinel: 


double salary = 
// Any value mie than -1 will do 


After the loop has finished, we compute and print the average. Here is the complete 
program: 


section_5/SentinelDemo.java 


jmport java.util.Scanner; 


/* * 


This program prints the average of salary values that are terminated with a sentinel. 


VUbWN 


You can usea 
Boolean variable to 
control a loop. Set 
the variable before 
entering the loop, 
then set it to the 
opposite to leave 
the loop. 


4.5 Application: Processing Sentinel Values 


6 public class SentinelDemo 


et 
8 
9 

10 

11 

12 


public static void main(String[] args) 


{ 


double sum = 0; 
int count = 0; 
double salary = 0; 


159 


System.out.print("Enter salaries, -1 to finish: "); 


Scanner in = new Scanner(System. in); 


// Process data until the sentinel is entered 


while (salary != -1) 
{ 
salary = in.nextDouble(); 
if (salary != -1) 
{ 
sum = sum + Salary; 
count++; 
} 
} 


// Compute and print the average 


if Ccount > 0) 
{ 
double average = sum / count; 
System.out.printIn("Average salary: 
} 
else 


{ 


System.out.printIn('No data"); 


Program Run 


Enter salaries, -1 to finish: 10 10 40 -1 
Average salary: 20 


+ average); 


Some programmers don’t like the “trick” of initializing the input variable with a value 
other than the sentinel. Another approach is to use a Boolean variable: 


System.out.print("Enter salaries, -1 to finish: "); 
boolean done = false; 
while (!done) 


{ 
value = in.nextDouble(); 
if (value == -1) 
{ 
done = true; 
} 
else 
Process value. 
} 
} 


Special Topic 4.1 on page 160 shows an alternative mechanism for leaving such a loop. 


160 Chapter 4 Loops 


Now consider the case in which any number (positive, negative, or zero) can be 
an acceptable input. In such a situation, you must use a sentinel that is not a number 
(such as the letter Q). As you have seen in Section 3.8, the condition 


in. hasNextDouble() 


is false if the next input is not a floating-point number. Therefore, you can read and 
process a set of inputs with the following loop: 
System.out.print("Enter values, Q to quit: "); 


while Cin.hasNextDouble()) 
{ 


value = in.nextDouble(Q); 
Process value. 


21. What does the Sentine1Demo. java program print when the user immediately types 
—1 when prompted for a value? 





22. Why does the Sentine1Demo. java program have two checks of the form 
salary != -1 


23. What would happen if the declaration of the salary variable in Sentine1Demo. java 
was changed to 


double salary = -1; 


24. Inthe last example of this section, we prompt the user “Enter values, Q to quit.” 
What happens when the user enters a different letter? 


25. What is wrong with the following loop for reading a sequence of values? 


System.out.print("Enter values, Q to quit: "); 
do 


double value = in.nextDouble(); 
sum = sum + value; 
count++; 


} 
while (in.hasNextDouble()); 


Practice It Now youcantry these exercises at the end of the chapter: R4.13, P4.27, P4.28. 


Special Topic 4.1 The Loop-and-a-Half Problem and the break Statement 


Consider again this loop for processing inputs until a sentinel value has been reached: 


boolean done = false; 
while (!done) 


; { 
"| double value = in.nextDoubleQ); 
if (value == -1) 
{ 
done = true; 
} 
else 
{ 
Process value. 
} 
} 


SY of <\el f= m Ke) 0) ens 4 








VIDEO EXAMPLE 4.1 Evaluating a Cell Phone Plan 


PLUS 


4.5 Application: Processing Sentinel Values 161 


The actual test for loop termination is in the middle of the loop, not at the top. This is called a 
loop and a half because one must go halfway into the loop before knowing whether one needs 
to terminate. 

As an alternative, you can use the break reserved word. 


while (true) 


{ 
double value = in.nextDouble(Q); 
if (value == -1) { break; } 
Process value. 

} 


The break statement breaks out of the enclosing loop, independent of the loop condition. 
When the break statement is encountered, the loop is terminated, and the statement following 
the loop is executed. 

In the loop-and-a-half case, break statements can be beneficial. But itis difficult to lay down 
clear rules as to when they are safe and when they should be avoided. We do not use the break 
statement in this book. 


Redirection of Input and Output 


Consider the Sentine1Demo program that computes the average 

value of an input sequence. If you use such a program, then itis 7334 input froma fle, 
quite likely that you already have the values ina file, anditseems Use output redirection to 
a shame that you have to type them all in again. The command capture program output 
line interface of your operating system provides a way to linka __ ina file. 

file to the input of a program, as if all the characters in the file had 

actually been typed by a user. If you type 


Use input redirection to 


java SentinelDemo < numbers.txt 


the program is executed, but it no longer expects input from the keyboard. All input com- 
mands get their input from the file numbers. txt. This process is called input redirection. 

Input redirection is an excellent tool for testing programs. When you develop a program 
and fix its bugs, it is boring to keep entering the same input every time you run the program. 
Spend a few minutes putting the inputs into a file, and use redirection. 

You can also redirect output. In this program, that is not terribly useful. If you run 


java SentinelDemo < numbers.txt > output.txt 
the file output.txt contains the input prompts and the output, such as 


Enter salaries, -1 to finish: Enter salaries, -1 to finish: 
Enter salaries, -1 to finish: Enter salaries, -1 to finish: 
Average salary: 15 


However, redirecting output is obviously useful for programs that produce lots of output. 
You can format or print the file containing the output. 


In this Video Example, you will learn how to designa 5 
program that computes the cost of a cell phone plan ss 
from actual usage data. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


162 Chapter 4 Loops 


A storyboard consists 
of annotated 
sketches for each 
step in an action 
sequence. 


Developing a 
storyboard helps you 
understand the 
inputs and outputs 
that are required for 
a program. 


Figure 6 
Storyboard for the 
Design of a Web 
Application 


___ 4.6 Problem Solving: Storyboards 


When you design a program that interacts with a user, you need to make a plan for 
that interaction. What information does the user provide, and in which order? What 
information will your program display, and in which format? What should happen 
when there is an error? When does the program quit? 

This planning is similar to the development of a movie or a computer game, where 
storyboards are used to plan action sequences. A storyboard is made up of panels that 
show a sketch of each step. Annotations explain what is happening and note any spe- 
cial situations. Storyboards are also used to develop software—see Figure 6. 

Making a storyboard is very helpful when you begin designing a program. You 
need to ask yourself which information you need in order to compute the answers 
that the program user wants. You need to decide how to present those answers. These 
are important considerations that you want to settle before you design an algorithm 
for computing the answers. 

Let’s look at a simple example. We want to write a program that helps users with 
questions such as “How many tablespoons are in a pint?” or “How many inches are 
30 centimeters?” 

What information does the user provide? 


e The quantity and unit to convert from 
e The unit to convert to 


What if there is more than one quantity? A user may have a whole table of centimeter 
values that should be converted into inches. 

What if the user enters units that our program doesn’t know how to handle, such 
as angstrom? 

What if the user asks for impossible conversions, such as inches to gallons? 








Observstioret sees 


Pema hestarnmesmened Wh 
em aucehorag 8 mas aS rd 
Magne denver ah atta 


Sp a era hae out gna Pah, 
ceevierty 








4.6 Problem Solving: Storyboards 163 


Let’s get started with a storyboard panel. It is a good idea to write the user inputs in 
a different color. (Underline them if you don’t have a color pen handy.) 


Converting a Sequence of Values 





What unit do you want to convert from? cm 
What unit do you want to convert to? in 
Enter values, terminated by zero ————— Allows conversion of multiple values 


30 

30 cm = 11.81 in 

100 — Format makes clear what got converted 
100 cm = 39.37 in 

0 


What unit do you want to convert from? 


The storyboard shows how we deal with a potential confusion. A user who wants to 
know how many inches are 30 centimeters may not read the first prompt carefully 
and specify inches. But then the output is “30 in = 76.2 cm”, alerting the user to the 
problem. 

The storyboard also raises an issue. How is the user supposed to know that “cm” 
and “in” are valid units? Would “centimeter” and “inches” also work? What happens 
when the user enters a wrong unit? Let’s make another storyboard to demonstrate 
error handling. 


Handling Unknown Units (needs improvement) 





What unit do you want to convert from? cm 
What unit do you want to convert to? inches 
Sorry, unknown vnit. 

What unit do you want to convert to? inch 
Sorry, unknown unit. 

What unit do you want to convert to? grrr 


To eliminate frustration, it is better to list the units that the user can supply. 


From unit (in, ft, mi, mm, cm, m, km, 02, Ib, g, kg, tsp, thsp, pint, gal): cm 
To unit: in 
~~ No need to list the units again 


We switched to a shorter prompt to make room for all the unit names. Exercise R4.21 
explores a different alternative. 

There is another issue that we haven’t addressed yet. How does the user quit the 
program? The first storyboard suggests that the program will go on forever. 

We can ask the user after seeing the sentinel that terminates an input sequence. 


164 Chapter 4 Loops 


Exiting the Program 

From unit (in, ft, mi, mm, cm, m, km, 02, Ib, g, kg, tsp, thsp, pint, gal): cm 
To unit: in 

Enter values, terminated by zero 

30 

30 cm= 11.81 in 

0 


__—— Sentinel triggers the prompt to exit 
More conversions ly, n)? 


(Program exits) 


As you can see from this case study, a storyboard is essential for developing a work- 
ing program. You need to know the flow of the user interaction in order to structure 
your program. 


y 


26. Provide a storyboard panel for a program that reads a number of test scores and 
prints the average score. The program only needs to process one set of scores. 
Don’t worry about error handling. 





27. Google has a simple interface for converting units. You just type the question, 
and you get the answer. 








Google |How many inches in 30 cm Search | Asvances searcn 





Web @B snow options... ; Results 1 - 10 of about 4,180,000 for How many Inches In 30 cm. (0.24 seconds) 


& 30 centimeters = 11.8110236 inches 


More about calculator. 


Make storyboards for an equivalent interface in a Java program. Show a scenario 
in which all goes well, and show the handling of two kinds of errors. 


28. Consider a modification of the program in Self Check 26. Suppose we want to 
drop the lowest score before computing the average. Provide a storyboard for 
the situation in which a user only provides one score. 


29. What is the problem with implementing the following storyboard in Java? 


Computing Multiple Averages 


Enter scores: 90 80 90 100 80 
The average is $8 
Enter scores: 100 70 70 100 80 


The average is $8 
-1 is used as a sentinel to exit the program 
Enter scores: -1 = an 


(Program exits) 


30. Produce a storyboard for a program that compares the growth of a $10,000 
investment for a given number of years under two interest rates. 


Practice It Now youcantry these exercises at the end of the chapter: R4.21, R4.22, R4.23. 


4.7 Common Loop Algorithms 165 


In the following sections, we discuss some of the most common algorithms that are 
implemented as loops. You can use them as starting points for your loop designs. 


4.7.1 Sum and Average Value 


- Computing the sum of a number of inputs is a very common task. Keep a running 
o compute an 


avenge Keep total, a variable to which you add each input value. Of course, the total should be 
total and a count initialized with 0. 
of all values. 


double total = 0; 
while Cin.hasNextDouble()) 


double input = in.nextDouble(); 
total = total + input; 


} 


Note that the total variable is declared outside the loop. We want the loop to update 
a single variable. The input variable is declared inside the loop. A separate variable is 
created for each input and removed at the end of each loop iteration. 

To compute an average, count how many values you have, and divide by the count. 
Be sure to check that the count is not zero. 

double total = 0; 

int count = 0; 

while Cin.hasNextDouble()) 


{ 
double input = in.nextDouble(); 
total = total + input; 
count++3 

} 


double average = 0; 
if (count > 0) 
{ 


} 


average = total / count; 


4.7.2 Counting Matches 


You often want to know how many values fulfill a particular condition. For example, 
To count values that 


fulfill a condition, you may want to count how many spaces are ina string. Keep a counter, a variable 
check all values and that is initialized with 0 and incremented whenever there is a match. 
increment a counter : 
for each match. int spaces = 0; 
for (int i = 0; i < str.lengthQ); i++) 
{ 
char ch = str.charAt(i); 
if (ch == '' ') 
{ 
spaces++; 
} 


} 


For example, if str is "My Fair Lady", spaces is incremented twice (when i is 2 and 7). 


166 


If your goal is to find 
a match, 


Chapter 4 Loops 


Note that the spaces variable is declared outside the loop. We want the loop to 
update a single variable. The ch variable is declared inside the loop. A separate variable 
is created for each iteration and removed at the end of each loop iteration. 

This loop can also be used for scanning inputs. The following loop reads text, a 
word at a time, and counts the number of words with at most three letters: 


int shortWords = 0; 
while Cin. hasNext(Q)) 


{ 
String input = in.next(); 
if Cinput.length() <= 3) 
{ 
shortWords++; 
} 
} 


In a loop that counts matches, 
a counter is incremented 
whenever a match is found. 





4.7.3 Finding the First Match 


When you count the values that fulfill a condition, you need to look at all values. 
exit theloop | However, if your task is to find a match, then you can stop as soon as the condition is 


when the match fulfilled. 


is found. 


Here is a loop that finds the first space in a string. Because we do not visit all ele- 
ments in the string, a while loop is a better choice than a for loop: 

boolean found = false; 

char ch = '?'; 

int position = 0; 

while (!found && position < str.length(Q)) 

{ 


ch = str.charAt(position) ; 
if (ch == ' ') { found = true; } 
else { position++; } 

} 

If a match was found, then found is true, ch is 
the first matching character, and position is 
the index of the first match. If the loop did 
not find a match, then found remains false 
after the end of the loop. 

Note that the variable ch is declared out- 
side the while loop because you may want to 
use the input after the loop has finished. If it 
had been declared inside the loop body, you when searching, you look at items until a 
would not be able to use it outside the loop. match is found. 





4.7 Common Loop Algorithms 167 


4.7.4 Prompting Until a Match is Found 


In the preceding example, we searched a string for a character that matches a condi- 
tion. You can apply the same process to user input. Suppose you are asking a user to 
enter a positive value < 100. Keep asking until the user provides a correct input: 


boolean valid = false; 
double input = 0; 
while (!valid) 
{ 
System.out.print("Please enter a positive value < 100: "); 
input = in.nextDouble(); 
if (0 < input && input < 100) { valid = true; } 
else { System.out.printIn("Invalid input."); } 


} 


Note that the variable input is declared outside the while loop because you will want to 
use the input after the loop has finished. 


4.7.5 Maximum and Minimum 


earthen To compute the largest value in a sequence, keep a variable that stores the largest ele- 


value, update the ment that you have encountered, and update it when you find a larger one. 


largest value seen so ‘ . 
frnnenever yous double largest = in.nextDoubleQ; 


a larger one. while (in. hasNextDouble()) 

{ 
double input = in.nextDouble(); 
if Cinput > largest) 
{ 

largest = input; 

} 

} 


This algorithm requires that there is at least one input. 
To compute the smallest value, simply reverse the comparison: 


double smallest = in.nextDouble(); 
while (in.hasNextDouble()) 


double input = in.nextDouble(); 
if Cinput < smallest) 
{ 

smallest = input; 


} 


To find the height of the tallest bus rider, 
remember the largest value so far, and 
update it whenever you see a taller one. 





168 Chapter 4 Loops 


To compare adjacent 
inputs, store the 
preceding input in 

a variable. 


ONLINE EXAMPLE 


@ A program using 
common loop 
algorithms. 





4.7.6 Comparing Adjacent Values 


When processing a sequence of values in a loop, you sometimes need to compare a 
value with the value that just preceded it. For example, suppose you want to check 
whether a sequence of inputs contains adjacent duplicates such as 17 29 94 9. 


Now you face a challenge. Consider the typical loop for reading a value: 


double input; 
while Cin.hasNextDouble()) 
{ 


input = in.nextDouble(); 


with the preceding one? At any time, input 


} 
How can you compare the current input iN | . é 4 S4 
de 


contains the current input, overwriting the 
previous one. 


The answer is to store the previous input, 


like this: j —a 
double input = 0; When comparing adjacent values, store 
while Cin.hasNextDouble()) the previous value ina variable. 

{ 


double previous = input; 
input = in.nextDoubleQ); 
if (input == previous) 


{ 


} 
} 


System.out.printIn("Duplicate input"); 


One problem remains. When the loop is entered for the first time, input has not yet 
been read. You can solve this problem with an initial input operation outside the loop: 


31. 


32. 
33. 


34. 


double input = in.nextDouble(); 
while (in.hasNextDouble()) 
{ 
double previous = input; 
input = in.nextDoubleQ); 
if (input == previous) 


{ 
} 


System.out.printIn("Duplicate input"); 


What total is computed when no user input is provided in the algorithm in 
Section 4.7.1? 


How do you compute the total of all positive inputs? 

What are the values of position and ch when no match is found in the algorithm 
in Section 4.7.3? 

What is wrong with the following loop for finding the position of the first space 
ina string? 

boolean found = false; 


for (int position = 0; !found && position < str.length(); position++) 


{ 


Practice It 


HOW TO 4.1 






Step 1 


4.7 Common Loop Algorithms 169 


char ch = str.charAt(position) ; 
if (ch == ' ') { found = true; } 
t 


35. How do you find the position of the /ast space in a string? 


36. What happens with the algorithm in Section 4.7.5 when no input is provided at 
all? How can you overcome that problem? 


Now you can try these exercises at the end of the chapter: P4.5, P4.9, P4.10. 


Writing a Loop 


This How To walks you through the process of implementing a 
loop statement. We will illustrate the steps with the following 
example problem: 

Read twelve temperature values (one for each month), and dis- 
play the number of the month with the highest temperature. For 
example, according to http://worldclimate.com, the average maxi- 
mum temperatures for Death Valley are (in order by month, in 
degrees Celsius): 


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 temperature (45.7 degrees 
Celsius) is July, and the program should display 7. 





Decide what work must be done imside the loop. 


Every loop needs to do some kind of repetitive work, such as 
e Reading another item. 

e Updating a value (such as a bank balance or total). 

e Incrementing a counter. 


If you can’t figure out what needs to go inside the loop, start by writing down the steps that 
you would take if you solved the problem by hand. For example, with the temperature reading 
problem, you might write 


Read first value. 

Read second valve. 

If second value is higher than the first, set highest temperature to that value, highest month to Z. 

Read next value. 

If value is higher than the first and second, set highest temperature to that value, highest month to 3. 

Read next value. 

If value is higher than the highest temperature seen so far, set highest temperature to that value, 
highest month to 4. 


Now look at these steps and reduce them to a set of uniform actions that can be placed into the 
loop body. The first action is easy: 


Read next value. 


The next action is trickier. In our description, we used tests “higher than the first”, “higher 
than the first and second”, “higher than the highest temperature seen so far”. We need to settle 
on one test that works for all iterations. The last formulation is the most general. 


170 Chapter 4 Loops 


Step 2 


Step 3 


Step 4 


Similarly, we must find a general way of setting the highest month. We need a variable that 
stores the current month, running from 1 to 12. Then we can formulate the second loop action: 


If value is higher than the highest temperature, set highest temperature to that value, 
highest month to current month. 


Altogether our loop is 


Repeat 
Read next value. 
If value is higher than the highest temperature, 
set highest temperature to that value, 
set highest month to current month. 
Increment current month. 


Specify the loop condition. 


What goal do you want to reach in your loop? Typical examples are 
e Has acounter reached its final value? 

e Have you read the last input value? 

e Hasa value reached a given threshold? 


In our example, we simply want the current month to reach 12. 
Determine the loop type. 


We distinguish between two major loop types. A count-controlled loop is executed a defi- 
nite number of times. In an event-controlled loop, the number of iterations is not known in 
advance—the loop is executed until some event happens. 

Count-controlled loops can be implemented as for statements. For other loops, consider 
the loop condition. Do you need to complete one iteration of the loop body before you can 
tell when to terminate the loop? In that case, choose a do loop. Otherwise, use a while loop. 

Sometimes, the condition for terminating a loop changes in the middle of the loop body. In 
that case, you can use a Boolean variable that specifies when you are ready to leave the loop. 
Follow this pattern: 


boolean done = false; 
while (!done) 
{ 
Do some work. 
If all work has been completed 


{ 
done = true; 
} 
else 
{ 
Do more work. 
} 


} 
Such a variable is called a flag. 


In summary, 
e Ifyou know in advance how many times a loop is repeated, use a for loop. 
e Ifthe loop body must be executed at least once, use a do loop. 
e Otherwise, use awhile loop. 


In our example, we read 12 temperature values. Therefore, we choose a for loop. 
Set up variables for entering the loop for the first time. 


List all variables that are used and updated in the loop, and determine how to initialize them. 
Commonly, counters are initialized with 0 or 1, totals with 0. 


Step 5 


Step 6 


Step 7 


4.7 Common Loop Algorithms 171 


In our example, the variables are 


current month 
highest value 
highest month 


We need to be careful how we set up the highest temperature value. We can’t simply set it to 
0. After all, our program needs to work with temperature values from Antarctica, all of which 
may be negative. 
A good option is to set the highest temperature value to the first input value. Of course, 
then we need to remember to read in only 11 more values, with the current month starting at 2. 
We also need to initialize the highest month with 1. After all, in an Australian city, we may 
never find a month that is warmer than January. 


Process the result after the loop has finished. 


In many cases, the desired result is simply a variable that was updated in the loop body. For 
example, in our temperature program, the result is the highest month. Sometimes, the loop 
computes values that contribute to the final result. For example, suppose you are asked to 
average the temperatures. Then the loop should compute the sum, not the average. After the 
loop has completed, you are ready to compute the average: divide the sum by the number of 
inputs. 

Here is our complete loop. 


Read first value; store as highest value. 
highest month = 1 
For current month from Z to 1Z 
Read next value. 
If value is higher than the highest value 
Set highest value to that value. 
Set highest month to current month. 


Trace the loop with typical examples. 


Hand trace your loop code, as described in Section 4.2. Choose example values that are not too 
complex— executing the loop 3-5 times is enough to check for the most common errors. Pay 
special attention when entering the loop for the first and last time. 

Sometimes, you want to make a slight modification to make tracing feasible. For example, 
when hand-tracing the investment doubling problem, use an interest rate of 20 percent rather 
than 5 percent. When hand-tracing the temperature loop, use 4 data values, not 12. 

Let’s say the data are 22.6 36.6 44.5 24.2. Here is the walkthrough: 


current month 


current value 


highest month 


highest value 








366 


X 
a 


1£6 
266 





4AG 


3 


44.5 




















The trace demonstrates that highest month and highest value are properly set. 


Implement the loop in Java. 


Here’s the loop for our example. Exercise P4.4 asks you to complete the program. 


double highestValue; 


highestValue = in.nextDouble(); 


int highestMonth = 1; 


172 Chapter 4 Loops 


WORKED EXAMPLE 4.1 Credit Card Processing 


+ This Worked Example uses a loop to remove spaces from a 





4.8 N 


When the body of a 
loop contains 
another loop, the 
loops are nested. A 
typical use of nested 
loops is printing a 
table with rows 

and columns. 


for Cint currentMonth = 2; currentMonth <= 12; currentMonth++) 
{ 

double nextValue = in.nextDoubleQ); 

if (nextValue > highestValue) 

{ 


highestValue = nextValue; 
highestMonth = currentMonth; 


} 
} 
System. out.printInChighestMonth) ; 





credit card number. 





L 


In Section 3.4, you saw how to nest two if statements. Similarly, complex iterations 
sometimes require a nested loop: a loop inside another loop statement. When pro- 
cessing tables, nested loops occur naturally. An outer loop iterates over all rows of the 
table. An inner loop deals with the columns in the current row. 

In this section you will see how to printa table. For simplicity, we will simply print 
the powers of x, x”, as in the table at right. 

Here is the pseudocode for printing the table: 


Dee | feo | [aoe xe 
Print table header. 
For x from 1 to 10 1 1 1 1 
Print table row. 7 4 8 16 
Print new line. 
How do you print a table row? You need to print a 2 z 2 ef 
value for each exponent. This requires a second loop. 
Ren elt 10 100 1000 10000 


Print x". 


This loop must be placed inside the preceding loop. We say that the inner loop is 
nested inside the outer loop. 


The hour and minute displays in a digital clock are an 
example of nested loops. The hours loop 12 times, and 
for each hour, the minutes loop 60 times. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


4.8 NestedLoops 173 





Figure 7 
Flowchart of a Nested Loop 





There are 10 rows in the outer loop. For each x, the program prints four columns 
in the inner loop (see Figure 7). Thus, a total of 10 x 4 = 40 values are printed. 

Following is the complete program. Note that we also use loops to print the table 
header. However, those loops are not nested. 


section_8/PowerTable.java 
[** 


2 ; This program prints a table of powers of x. 
: Hake class PowerTable 

3 : public static void main(String[] args) 
3 

9 


{ 

final int NMAX = 4; 

final double XMAX = 10; 
10 
11 // Print table header 
12 
13 for (int n = 1; n <= NMAX; n++) 
14 { 
15 System.out.printf("%10d", n); 
16 } 


17 System.out.printInQ; 


174 Chapter 4 Loops 


for Cint n = 1; n <= NMAX; n++) 
{ 
System.out.printf("%10s", "x "); 
} 
System.out.printInQ; 
// Print table body 
for (double x = 1; x <= XMAX; x++) 
{ 
// Print table row 
for (int n = 1; n <= NMAX; n++) 
{ 
System.out.printf('%10.0f", Math.pow(x, n)); 
} 
System.out.printInQ; 
} 
} 
} 


Program Run 


37. 


38. 
39. 
40. 





41. 


1 2 3 4 
Xx Xx Xx X 
1 al il i 
2 4 8 16 
3 9 27 81 
4 16 64 256 
5 25 125 625 
6 36 216 1296 
7 49 343 2401 
8 64 512 4096 
g 81 729 6561 
10 100 1000 10000 


Why is there a statement System. out.printIn(); in the outer loop but not in the 
inner loop? 

How would you change the program to display all powers from x° to x°? 
If you make the change in Self Check 38, how many values are displayed? 
What do the following nested loops display? 


for (int i = 0; i < 3; i++) 


{ 

for (int j = 0; j < 4; j+4) 

{ 

System.out.print(i + j); 

} 

System.out.printIn(); 
} 
Write nested loops that make the following pattern of brackets: 
CCCI 0) 
CCI CI 0) 


CCCI 0) 


4.8 NestedLoops 175 
Practice It Now youcantry these exercises at the end of the chapter: R4.27, P4.19, P4.21. 


Table 3 Nested Loop Examples 


Nested Loops Output Explanation 
for Gi = 1; i <= 3; i++) wie Prints 3 rows of 4 
{ wake asterisks each. 


for (Gj = 1; j <= 4; j+4) { Primt "*" 3 **** 
System.out.printInQ; 


} 
for (i = 1; i <= 4; i+) rk Prints 4 rows of 3 
{ eH asterisks each. 
for (Gj = 1; j <= 3; j+) { Print "*" 3 #** 
System.out.printInQ; wR 
} 
for (i = 1; i <= 4; i+) * Prints 4 rows of 
{ we lengths 1, 2, 3, and 4. 
for G =1; j «= i; J+) { Print "*" } tH 
System.out.printInQ; RR 
} 
for (i = 1; i <= 3; i+4) See Prints asterisks in 
d HoH even columns, 
Oe G = ig gy 55 ihey) -¥o¥- dashes in odd 
{ columns. 


if (7 % 2 == 0) { Print "*" } 
else { Print "-" } 

} 

System.out.printInQ; 


} 
for Gi = 1; i <= 3; i+) ae Prints a 
{ ae checkerboard 
for (j = 1; j <= 5; j++) oad pattern. 
{ 
HF Gi % 2 == 7% 2) 4 Matar" F 
else { Print" " } 
} 
System.out.printInQ; 
} 


WORKED EXAMPLE 4.2 Manipulating the Pixels in an Image 


+ This Worked Example shows how to use nested loops for 
manipulating the pixels in an image. The outer loop tra- 
verses the rows of the image, and the inner loop accesses 
each pixel of a row. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


176 Chapter 4 Loops 


4.9 Application: Random Numbers 
| Simulati 


nec A simulation program uses the computer to simulate an activity in the real world (or 

use the computer to an imaginary one). Simulations are commonly used for predicting climate change, 

simulate an activity. analyzing traffic, picking stocks, and many other applications in science and busi- 
ness. In many simulations, one or more loops are used to modify the state of a system 
and observe the changes. You will see examples in the following sections. 


4.9.1 Generating Random Numbers 


Many events in the real world are difficult to predict with absolute precision, yet we 
can sometimes know the average behavior quite well. For example, a store may know 
from experience that a customer arrives every five minutes. Of course, that is an aver- 
age —customers don’t arrive in five minute intervals. To accurately model customer 
traffic, you want to take that random fluctuation into account. Now, how can you 
run such a simulation in the computer? 
ee one The Java library has a random number generator, which produces numbers that 
randomness by appear to be completely random. Calling Math. random() yields a random floating-point 
calling the random number that is = 0 and < 1. Call Math. random() again, and you get a different number. 
RUMpSE generator The following program calls Math. random() ten times. 


section_9_1/RandomDemo.java 
[** 


: ; This program prints ten random numbers between 0 and 1. 
i aoe class RandomDemo 

2 public static void main(String[] args) 

3 

9 


{ 
for Cint 7 = 1; 71 <= 10; i++) 
{ 
10 double r = Math.random(); 
11 System.out.printIn(r); 
12 } 
13 } 


Program Run 


0.6513550469421886 

- 920193662882893 
-6904776061289993 
-8862828776788884 
.7730177555323139 

. 3020238718668635 
-0028504531690907164 
- 9099983981705169 
-1151636530517488 
 1592258808929058 


Sa ooo oe S 


4.9 Application: Random Numbers and Simulations 177 


Actually, the numbers are not completely random. They are drawn from sequences 
of numbers that don’t repeat for a long time. These sequences are actually computed 
from fairly simple formulas; they just behave like random numbers (see Exercise 
P4.25). For that reason, they are often called pseudorandom numbers. 


4.9.2 Simulating Die Tosses 

In actual applications, you need to transform the output from 
the random number generator into different ranges. For exam- 
ple, to simulate the throw of a die, you need random integers 
between 1 and 6. 

Here is the general recipe for computing random integers 
between two bounds a and b. As you know from Program- 
ming Tip 4.3 on page 156, there areb - a+ 1values betweenaand 
b, including the bounds themselves. First compute 


(int) (Math.random() * (b - a + 1)) 





to obtain a random integer between 0 and b - a, then add a, yielding a random value 
between a and b: 


int r = (int) (Math.random() * (b - a+ 1)) +; 


Here is a program that simulates the throw of a pair of dice: 


section_9_2/Dice.java 
[** 


1 

2 This program simulates tosses of a pair of dice. 
3 */ 

4 public class Dice 

5 { 

6 public static void main(String[] args) 

7 

8 

9 


{ 

for (int i = 1; 71 <= 10; i++) 

{ 
10 // Generate two random numbers between 1 and 6 
11 
12 int dl = (int) (Math.randomQ) * 6) + 1; 
13 int d2 = (int) (Math.random() * 6) + 1; 
14 System.out.printIn(d1 + " " + d2); 
15 } 
16 System.out.printInQ; 
17 } 
18 } 


Program Run 


a 


W~AAAMAAMRFPUNERENU 
NWRPPRBNRPNE 


178 Chapter 4 Loops 


4.9.3 The Monte Carlo Method 


The Monte Carlo method is 
an ingenious method for find- 
ing approximate solutions to 
problems that cannot be pre- 
cisely solved. (The method is 
named after the famous casino in 
Monte Carlo.) Here is a typical 
example. It is difficult to com- 
pute the number a, but you can 
approximate it quite well with 
the following simulation. 

Simulate shooting a dart into a square surrounding a circle of radius 1. That is easy: 
generate random x and y coordinates between —-1 and 1. 

If the generated point lies inside the circle, we count 7 
it as a hit. That is the case when x” + y* < 1. Because our 
shots are entirely random, we expect that the ratio of hits 
/ tries is approximately equal to the ratio of the areas of 
the circle and the square, that is, a / 4. Therefore, our 
estimate for a is 4 x hits / tries. This method yields an 
estimate for a, using nothing but simple arithmetic. 

To generate a random floating-point value between -1 
and 1, you compute: 


double r = Math.random(); // Osr<1l 
double x = -1+2* r; //-1l<x< 1 








As r ranges from 0 (inclusive) to 1 (exclusive), x ranges from —1 + 2 x 0 =~1 (inclusive) 
to-1+2x 1=1 (exclusive). In our application, it does not matter that x never reaches 
1. The points that fulfill the equation x = 1 lie ona line with area 0. 

Here is the program that carries out the simulation: 


section_9_3/MonteCarlo.java 
[** 


2 __ This program computes an estimate of pi by simulating dart throws onto a square. 
z i ic class MonteCarlo 

public static void main(String[] args) 

3 

9 


{ 

final int TRIES = 10000; 
10 int hits = 0; 
11 for (int i = 1; 1 <= TRIES; i++) 
12 { 
13 // Generate two random numbers between -1 and 1 
14 
15 double r = Math. random(); 
16 double x = -1 + 2 * r; // Between -1 and 1 
17 r = Math.random(); 
18 double y = -1+2* Fr; 









SELF CHECK 


Practice It 





Special Topic 4.3 





4.9 Application: Random Numbers and Simulations 179 


// Check whether the point lies in the unit circle 


if &«*x+y * y <1) { hits++; } 
} 


/* 
The ratio hits / tries is approximately the same as the ratio 
circle area / square area = pi/ 4 


*/ 


double piEstimate = 4.0 * hits / TRIES; 


System.out.printIn("Estimate for pi: " + piEstimate); 


Program Run 


Estimate for pi: 3.1504 


42. How do you simulate a coin toss with the Math. random() method? 


43. How do you simulate the picking of a random playing card? 


44. Why does the loop body in Dice. java call Math. random() twice? 


45. In many games, you throw a pair of dice to get a value between 2 and 12. What is 
wrong with this simulated throw of a pair of dice? 


int sum = (int) (Math.random() * 11) + 2; 


46. How do you generate a random floating-point number = 0 and < 100? 


Now you can try these exercises at the end of the chapter: R4.28, P4.7, P4.24. 


Drawing Graphical Shapes 


In Java, it is easy to produce simple drawings such as the 
one in Figure 8. By writing programs that draw such pat- 


terns, you can practice programming loops. For now, we 
give you a program outline into which you place your 
drawing code. The program outline also contains the 
necessary code for displaying a window containing your 
drawing. You need not look at that code now. It will be 
discussed in detail in Chapter 10. 

Your drawing instructions go inside the draw method: 


public class TwoRowsOfSquares 


{ 


public static void draw(Graphics g) 


{ 
Drawing instructions Figure 8 Two Rows of Squares 


} 


} 








When the window is shown, the draw method is called, and your drawing instructions will be 


executed. 


180 Chapter 4 Loops 


The draw method receives an object of type Graphics. The Graphics object has methods for 
drawing shapes. It also remembers the color that is used for drawing operations. You can think 
of the Graphics object as the equivalent of System.out for drawing shapes instead of printing 
values. 

Table 4 shows useful methods of the Graphics class. 


Table 4 Graphics Methods 


Method Result Notes 


g.drawRect(x, y, width, height) Ce y) is the top left corner. 


(x, y) is the top left corner 
of the box that bounds the 
ellipse. To draw a circle, use 
the same value for width 


and height. 


g.drawOval(x, y, width, height) 





g.fillRect(x, y, width, height) The rectangle is filled in. 


g.fill0val(x, y, width, height) The oval is filled in. 


(x1, y1) and (x2, y2) are 
the endpoints. 


g.drawLine(x1, yl, x2, y2) 


g.drawString("Message", x, y) (x, y) is the basepoint. 


‘\on 


Basepoint Baseline 
g.setColor(color) From now on, Use Color.RED, Color.GREEN, 
draw or fill methods Color.BLUE, and so on. (See 
will use this color. Table 10.1 for a complete 


list of predefined colors.) 


The program below draws the squares shown in Figure 8. When you want to produce your 
own drawings, make a copy of this program and modify it. Replace the drawing tasks in the 
draw method. Rename the class (for example, Spiral instead of TwoRowsOfSquares). 


special_topic_3/TwoRowsOfSquares.java 


import java.awt.Color; 

import java.awt.Graphics; 
import javax.swing.JFrame; 
import javax.swing.JComponent; 


[** 


This program draws two rows of squares. 


a 


public class TwoRowsOfSquares 


{ 


CUONAVUABAWN= 


— 


4.9 Application: Random Numbers and Simulations 181 


11 public static void draw(Graphics g) 

12 { 

13 final int width = 20; 

14 g.setColor(Color.BLUE) ; 

15 

16 // Top row. Note that the top left corner of the drawing has coordinates (0, 0) 
17 int x = 0; 

18 int. y="03 

19 for Cint i = 0; i < 10; i++) 

20 { 

21 g.fillRect(x, y, width, width); 

22 xX =X + 2 * width; 

23 } 

24 // Second row, offset from the first one 

25 x = width; 

26 y = width; 

27 for (int i = 0; 71 < 10; i++) 

28 { 

29 g.fillRect(x, y, width, width); 

30 xX =X + 2 * width; 

31 } 

32 } 

33 

34 public static void main(String[] args) 

35 { 

36 // Do not look at the code in the main method 
37 // Your code will go into the draw method above 
38 

39 JFrame frame = new JFrame(); 

40 

41 final int FRAME_WIDTH = 400; 

42 final int FRAME_HEIGHT = 400; 

43 

44 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT) ; 
45 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; 
46 

47 JComponent component = new JComponent() 

48 { 

49 public void paintComponent(Graphics graph) 
50 { 

51 draw(graph) ; 

52 } 

53 33 

54 

55 frame.add(component) ; 

56 frame.setVisible(true); 

57 } 

58 } 


VIDEO EXAMPLE 4.2 Drawing a Spiral 


Toe In this Video Example, you will see how to develop a program 


that draws a spiral. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


182 Chapter 4 Loops 


As you read this, you 
will have written a few 
computer programs and experienced 
firsthand how much effort it takes to 
write even the humblest of programs. 
Writing a real software product, such 
as a financial application or a computer 
game, takes a lot of time and money. 
Few people, and fewer companies, are 
going to spend that kind of time and 
money if they don’t have a reasonable 
chance to make more money from their 
effort. (Actually, some companies give 
away their software in the hope that 
users will upgrade to more elaborate 
paid versions. Other companies give 
away the software that enables users to 
read and use files but sell the software 
needed to create those files. Finally, 
there are individuals who donate their 
time, out of enthusiasm, and produce 
programs that you can copy freely.) 
When selling software, a company 
must rely on the honesty of its cus- 
tomers. It is an easy matter for an 
unscrupulous person to make copies 
of computer programs without paying 
for them. In most countries that is ille- 
gal. Most governments provide legal 
protection, such as copyright laws and 
patents, to encourage the develop- 
ment of new products. Countries that 
tolerate widespread piracy have found 





Random Fact 4.2 Software Piracy 


that they have an ample cheap supply 
of foreign software, but no local man- 
ufacturers willing to design good soft- 
ware for their own citizens, such as 
word processors in the local script or 
financial programs adapted to the local 
tax laws. 

When a mass market for software 
first appeared, vendors were enraged 
by the money they lost through piracy. 
They tried to fight back by various 
schemes to ensure that only the legiti- 
mate owner could use the software, 
such as dongles—devices that must 
be attached to a printer port before 
the software will run. Legitimate users 
hated these measures. They paid for 
the software, but they had to suffer 
through inconveniences, such as hav- 
ing multiple dongles stick out from 
their computer. In the United States, 
market pressures forced most vendors 
to give up on these copy protection 
schemes, but they are still common- 
place in other parts of the world. 

Because it is so easy and inexpen- 
sive to pirate software, and the chance 
of being found out is minimal, you 
have to make a moral choice for your- 
self. If a package that you would really 
like to have is too expensive for your 
budget, do you steal it, or do you stay 


Explain the flow of execution in a loop. 


e A loop executes instructions repeatedly while a 


condition is true. 


e An off-by-one error is acommon error when 


programming loops. Think through simple test 


cases to avoid this type of error. 


honest and get by with a more afford- 
able product? 

Of course, piracy 
is not limited to 
software. The same 
issues arise for other 
digital products as 
well. You may have 
had the opportunity 
to obtain copies of 
songs or movies 
without payment. Or you may have 
been frustrated by a copy protec- 
tion device on your music player that 
made it difficult for you to listen to 
songs that you paid for. Admittedly, 
it can be difficult to have a lot of sym- 
pathy for a musical ensemble whose 
publisher charges a lot of money for 
what seems to have been very little 
effort on their part, at least when 
compared to the effort that goes into 
designing and implementing a soft- 
ware package. Nevertheless, it seems 
only fair that artists and authors 
receive some compensation for their 
efforts. How to pay artists, authors, 
and programmers fairly, without 
burdening honest customers, is an 
unsolved problem at the time of this 
writing, and many computer scientists 
are engaged in research in this area. 








Use the technique of hand-tracing to analyze the behavior of a program. 


e Hand-tracing is a simulation of code execution in which you step 
through instructions and track the values of the variables. 


e Hand-tracing can help you understand how an unfamiliar algo- 


rithm works. 


e Hand-tracing can show errors in code or pseudocode. 





Chapter Summary 183 


Use for loops for implementing count-controlled loops. 


¢ The for loop is used when a value runs from a starting point to an ending point 
with a constant increment or decrement. 





Choose between the while loop and the do loop. 
¢ The do loop is appropriate when the loop body must be executed at least once. 
Implement loops that read sequences of input data. 
e A sentinel value denotes the end of a data set, but it is not part of 


the data. 


¢ You can use a Boolean variable to control a loop. Set the variable 
to true before entering the loop, then set it to false to leave the 
loop. 

¢ Use input redirection to read input from a file. Use output 
redirection to capture program output ina file. 





Use the technique of storyboarding for planning user interactions. 


¢ A storyboard consists of annotated sketches for each step in an action sequence. 
¢ Developing a storyboard helps you understand the inputs and outputs that are 
required for a program. 


Know the most common loop algorithms. 


¢ To compute an average, keep a total and a count of all values. 


e To count values that fulfill a condition, check all values and increment a counter 
for each match. 


¢ If your goal is to find a match, exit the loop when the match is found. 


¢ To find the largest value, update the largest value seen so far whenever you see a 
larger one. 


¢ To compare adjacent inputs, store the preceding input in a variable. 
Use nested loops to implement multiple levels of iteration. 


¢ When the body of a loop contains another loop, the loops are nested. A typical 
use of nested loops is printing a table with rows and columns. 





Apply loops to the implementation of simulations. 


¢ Inasimulation, you use the computer to simulate an activity. 


e You can introduce randomness by calling the random number 
generator. 





184 Chapter 4 Loops 


java.awt.Color java.lang.Math 
java.awt.Graphics random 
drawLine 
drawOval 
drawRect 
drawString 
setColor 


# R4.1 Write a while loop that prints 
a. All squares less than n. For example, if nis 100, print 0 149 16 25 36 49 64 81. 


b. All positive numbers that are divisible by 10 and less than n. For example, if nis 
100, print 10 20 30 40 50 60 70 80 90 


c. All powers of two less than n. For example, if nis 100, print 1 2 4 8 16 32 64. 


##R4.2 Write a loop that computes 
a. The sum of all even numbers between 2 and 100 (inclusive). 
b. The sum of all squares between 1 and 100 (inclusive). 
c. The sum of all odd numbers between a and b (inclusive). 


d. The sum of all odd digits of n. (For example, if n is 32677, the sum would 
be3-+ 747247) 


» R4.3 Provide trace tables for these loops. 
a. int i = 0; int j = 10; int n= 0; 
while (i < j) { i++; j--; nt+; } 
b. int i = 0; int j = 0; int n= 0; 
while (i < 10) { i++; n=n+ i+ 5; jtt; } 
c. int i = 10; int j = 0; int n = 0; 
while (i > 0) { i--; j++} n=n+i- j; } 
d. int i = 0; int j = 10; int n = 0; 
while Gi != j) {7 = i+ 2; j = j - 2; n++; } 


«= R4.4 What do these loops print? 


a. for (int 
. for (int 


j = 1; 1 < 10; i++) { System.out.print(i +" "); } 
b j = 1; 1 < 10; i += 2) { System.out.print(@i +" "); } 

c. for (int i = 10; i > 1; i--) { System.out.print(Gi +" "); } 

d. for (int i = 0; i < 10; i++) { System.out.print(i +" "); } 

e. for (int i = 1; 1 < 10; i = 7 * 2) { System.out.print(i +" "); } 

f. for (int i = 1; i < 10; i++) { if Gi % 2 == 0) { System.out.print(i +" "); } } 


# R4.5 What is an infinite loop? On your computer, how can you terminate a program that 
executes an infinite loop? 


» R4.6 Write a program trace for the pseudocode in Exercise P4.6, assuming the input val- 
ues are 4 7-2-5 0. 


an R4,7 


o R48 


«R49 


= R4.10 


on R4,11 


a R4,12 


=o R4.13 


oa R4.14 


Review Exercises 185 


What is an “off-by-one” error? Give an example from your own programming 
experience. 


What is a sentinel value? Give a simple rule when it is appropriate to use a numeric 
sentinel value. 


Which loop statements does Java support? Give simple rules for when to use each 
loop type. 


How many iterations do the following loops carry out? Assume that i is not 
changed in the loop body. 

a. for (int i = 1; 1 <= 10; i++)... 

b. for (int i = 0; i < 10; i++)... 

c. for (int i = 10; i > 0; i--)... 

d. for (int i = -10; i <= 10; i++)... 

e. for (int i = 10; i >= 0; i++)... 

f. for (int i = -10; i <= 10; i =i+2)... 

g. for (int i = -10; i <= 10; i=i7+3)... 


Write pseudocode for a program that prints a calendar such as the following: 
Su M T WTh F Sa 


12 3 4 

5 6 7 8 910 11 

12 13 14 15 16 17 18 

19 20 21 22 23 24 25 
26 27 28 29 30 31 


Write pseudocode for a program that prints a Celsius/Fahrenheit conversion table 
such as the following: 


Celsius | Fahrenheit 


eee Pentedei asses 
0 | 32 

10 | 50 

20 | 68 

100 | 212 


Write pseudocode for a program that reads a student record, consisting of the stu- 
dent’s first and last name, followed by a sequence of test scores and a sentinel of -1. 
The program should print the student’s average score. Then provide a trace table for 
this sample input: 


Harry Morgan 94 71 86 95 -1 


Write pseudocode for a program that reads a sequence of student records and prints 
the total score for each student. Each record has the student’s first and last name, 
followed by a sequence of test scores and a sentinel of —1. The sequence is terminated 
by the word END. Here is a sample sequence: 

Harry Morgan 94 71 86 95 -1 


Sally Lin 99 98 100 95 90 -1 
END 


Provide a trace table for this sample input. 


186 Chapter 4 Loops 


» R4.15 Rewrite the following for loop into a while loop. 


int s = 0; 
for (int i = 1; 1 <= 10; i++) 
{ . 
Ss=s+i; 
} 


« R4.16 Rewrite the following do loop into a while loop. 


int n = in.nextIntQ; 
double x = 0; 
double s; 
do 
{ 
s=1.0/ (+n *n); 
n++3 
X=X+S5S!3 


} 
while (s > 0.01); 


= R4.17 Provide trace tables of the following loops. 


a. int s =1; 
int n=1; 
while (s < 10) {s=s +n; } 
n++; 
b. int s = 1; 
for (int n= 1; n < 5; n++) fs =s +n; } 
c. int s = 1; 
int n=1; 
do 
{ 
s=sS+4+n; 
n++; 


} 
while (s < 10 * n); 
» R4.18 What do the following loops print? Work out the answer by tracing the code, not by 
using the computer. 


a. ints =1; 
for (int n = 1; n <= 55 n++) 


{ 
s=S+n; 
System.out.print(s + " "); 
} 
b. int s = 1; 
for (int n = 1; s <= 10; System.out.print(s + " ")) 
{ 
n=n¢4 2; 
s=sS+n; 
} 
c. int s = 1; 
int n; 
for (n = 1; n <= 5; n++) 
{ 
s=s+n; 
n++3 
} 


System.out.print(s + +n); 


« R4.19 


aa R4.20 


=o R4.21 


a R4,22 


= R4.23 


a R4.24 


oe R4.25 


« R4.26 


Review Exercises 187 


What do the following program segments print? Find the answers by tracing the 
code, not by using the computer. 
a. intn=1; 
for (int i = 2; i < 5; i++) fn =n+i; } 
System.out.print(n); 
b. int i; 
double n= 1 / 2; 
for Gi = 2; 1 <= 5; i++) fn =n4+1.0/ 1; } 
System.out.print(i); 
c. double x = 1; 


double y = 1; 
int i = 0; 
do 
{ 
yey/2; 
X=X+Y3 
itt; 
} 


while (x < 1.8); 
System.out.print(i); 
d. double x = 1; 
double y = 1; 
int i = 0; 
while (y >= 1.5) 
{ 
x=xX/ 2; 
y=HX + yy 
j++; 
} 


System.out.print(i); 


Give an example of a for loop where symmetric bounds are more natural. Give an 
example of a for loop where asymmetric bounds are more natural. 


Add a storyboard panel for the conversion program in Section 4.6 on page 162 that 
shows a scenario where a user enters incompatible units. 


In Section 4.6, we decided to show users a list of all valid units in the prompt. If the 
program supports many more units, this approach is unworkable. Give a storyboard 
panel that illustrates an alternate approach: If the user enters an unknown unit, a list 
of all known units is shown. 


Change the storyboards in Section 4.6 to support a menu that asks users whether 
they want to convert units, see program help, or quit the program. The menu should 
be displayed at the beginning of the program, when a sequence of values has been 
converted, and when an error is displayed. 


Draw a flow chart for a program that carries out unit conversions as described in 
Section 4.6. 


In Section 4.7.5, the code for finding the largest and smallest input initializes the 
largest and smallest variables with an input value. Why can’t you initialize them 
with zero? 


What are nested loops? Give an example where a nested loop is typically used. 


188 Chapter 4 Loops 


«= R4.27 The nested loops 


for (int i = 1; i <= height; i++) 


for (int j = 1; j <= width; j++) { System.out.print("*"); } 
System.out.printInQ ; 


display a rectangle of a given width and height, such as 


KRRK 





Write a single for loop that displays the same rectangle. 


»= R4.28 Suppose you design an educational game to teach children how to read a clock. How 
do you generate random values for the hours and minutes? 


na R4.29 Inatravel simulation, Harry will visit one of his friends that are located in three 
states. He has ten friends in California, three in Nevada, and two in Utah. How do 
you produce a random number between 1 and 3, denoting the destination state, with 
a probability that is proportional to the number of friends in each state? 


» P4.1 Write programs with loops that compute 
a. The sum of all even numbers between 2 and 100 (inclusive). 
b. The sum of all squares between 1 and 100 (inclusive). 
c. All powers of 2 from 2° up to 27°. 
d. The sum of all odd numbers between a and b (inclusive), where a and b are 
inputs. 
e. The sum of all odd digits of an input. (For example, if the input is 32677, the 
sum would be 3 + 7+ 7= 17.) 
ue P4.2 Write programs that read a sequence of integer inputs and print 
a. The smallest and largest of the inputs. 
b. The number of even and odd inputs. 


c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 
181019. 


d. All adjacent duplicates. For example, if the input is 13 3455 6 662, the 
program should print 3 5 6. 
n= P4.3 Write programs that read a line of input as a string and print 
a. Only the uppercase letters in the string. 
b. Every second letter of the string. 
c. The string, with all vowels replaced by an underscore. 
d. The number of vowels in the string. 
e. The positions of all vowels in the string. 


«= P4.4 Complete the program in How To 4.1 on page 169. Your program should read twelve 
temperature values and print the month with the highest temperature. 


oe P4,5 


= P4.6 


aun P4,7 





=o P4.8 


un P49 


« P4.10 


Programming Exercises 189 


Write a program that reads a set of floating-point values. Ask the user to enter the 
values, then print 


e the average of the values. 

e the smallest of the values. 

e the largest of the values. 

e the range, that is the difference between the smallest and largest. 
Of course, you may only prompt for the values once. 
Translate the following pseudocode for finding the minimum value from a set of 
inputs into a Java program. 


Set a Boolean variable “first” to true. 
While another value has been read successfully 
If first is true 
Set the minimum to the value. 
Set first to false. 
Else if the value is less than the minimum 
Set the minimum to the value. 
Print the minimum. 


Translate the following pseudocode for randomly permuting the characters in a 
string into a Java program. 


Read a word. 

Repeat word.length() times 
Pick a random position i in the word, but not the last position. 
Pick a random position j > i in the word. 
Swap the letters at positions j and i. 

Print the word. 


To swap the letters, construct substrings as follows: 
first 7 middle = last 
Then replace the string with 
first + word.charAt(j) + middle + word.charAt(i) + last 
Write a program that reads a word and prints each character of the word ona sepa- 
rate line. For example, if the user provides the input "Harry", the program prints 
H 


a 
(f 
le 
y 
Write a program that reads a word and prints the word in reverse. For example, if the 


user provides the input "Harry", the program prints 
yrraH 
Write a program that reads a word and prints the number of vowels in the word. For 


this exercise, assume that a e i o u y are vowels. For example, if the user provides the 
input "Harry", the program prints 2 vowels. 


190 Chapter 4 Loops 


aoe P4,11 


ane P4.12 


s P4.13 


ua P4,14 


oe P4,.15 


Write a program that reads a word and prints the number of syllables in the word. 
For this exercise, assume that syllables are determined as follows: Each sequence of 
adjacent vowels a e i ou y, except for the last e in a word, is a syllable. However, if 
that algorithm yields a count of 0, change it to 1. For example, 


Word Syllables 
Harry 2 
hairy 2 
hare 1 
the 1 


Write a program that reads a word and prints all substrings, sorted by length. For 
example, if the user provides the input "rum", the program prints 


lg 


m 

ru 

um 

rum 
Write a program that prints all powers of 2 from 2° up to 2”°. 
Write a program that reads a number and prints all of its binary digits: Print the 
remainder number % 2, then replace the number with number / 2. Keep going until the 
number is 0. For example, if the user provides the input 13, the output should be 


1 


0 
1 
a 


Mean and standard deviation. Write a program that reads a set of floating-point data 
values. Choose an appropriate mechanism for prompting for the end of the data set. 
When all values have been read, print out the count of the values, the average, and 
the standard deviation. The average of a data set {x1,...,X,} is X = Lx; /n, where 
Xx; =x, +...+x, isthe sum of the input values. The standard deviation is 





However, this formula is not suitable for the task. By the time the program has 
computed Xx, the individual x; are long gone. Until you know how to save these 
values, use the numerically less stable formula 


= 2 “dx) 


n-1 








5 


You can compute this quantity by keeping track of the count, the sum, and the sum 
of squares as you process the input values. 


on P4.16 


aoe P4.17 


ane P4.18 


« P4.19 


aa P4,20 


Programming Exercises 191 


The Fibonacci numbers are defined by the sequence 


f,=1 
fy =1 
Ii = Jur ip 


Reformulate that as 


foldl = 1; 

fold2 = 1; 

fnew = foldl + fold2; 
After that, discard fold2, which is no longer needed, and set fold2 to fold1 and fold1 to 
fnew. Repeat an appropriate number of times. 





Fibonacci numbers describe the 
growth of a rabbit population. 


Implement a program that prompts the user for an integer 7 and prints the mth 
Fibonacci number, using the above algorithm. 


Factoring of integers. Write a program that asks the user for an integer and then 
prints out all its factors. For example, when the user enters 150, the program should 
print 

2 


3 
5 
5 


Prime numbers. Write a program that prompts the user for an integer and then prints 
out all prime numbers up to that integer. For example, when the user enters 20, the 
program should print 


2 
3 
5 
7 
11 
13 
17 
19 


Recall that a number is a prime number if it is not divisible by any number except 1 
and itself. 


Write a program that prints a multiplication table, like this: 


1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 


10 20 30 40 50 60 70 80 90 100 


Write a program that reads an integer and displays, using asterisks, a filled and hol- 
low square, placed next to each other. For example if the side length is 5, the program 
should display 


RRERRE Hk 


192 Chapter4 Loops 


ue P4,21 


aoe P4,22 


an P4,23 


ue P4,24 


Write a program that reads an integer and displays, using asterisks, a filled diamond 
of the given side length. For example, if the side length is 4, the program should dis- 


play 





The game of Nim. This is a well-known game with a number of variants. The fol- 
lowing variant has an interesting winning strategy. Two players alternately take 
marbles from a pile. In each move, a player chooses how many marbles to take. The 
player must take at least one but at most half of the marbles. Then the other player 
takes a turn. The player who takes the last marble loses. 


Write a program in which the computer plays against a human opponent. Generate a 
random integer between 10 and 100 to denote the initial size of the pile. Generate a 
random integer between 0 and 1 to decide whether the computer or the human takes 
the first turn. Generate a random integer between 0 and 1 to decide whether the 
computer plays smart or stupid. In stupid mode the computer simply takes a random 
legal value (between 1 and 7/2) from the pile whenever it has a turn. In smart mode 
the computer takes off enough marbles to make the size of the pile a power of two 
minus 1—that is, 3, 7, 15, 31, or 63. That is always a legal move, except when the size 
of the pile is currently one less than a power of two. In that case, the computer makes 
a random legal move. 


You will note that the computer cannot be beaten in smart mode when it has the first 
move, unless the pile size happens to be 15, 31, or 63. Of course, a human player who 
has the first turn and knows the winning strategy can win against the computer. 


The Drunkard’s Walk. A drunkard in a grid of streets randomly picks one of four 
directions and stumbles to the next intersection, then again randomly picks one of 
four directions, and so on. You might think that on average the drunkard doesn’t 
move very far because the choices cancel each other out, but that is actually not the 
case. 


Represent locations as integer pairs (x, y). Implement the drunkard’s walk over 100 
intersections, starting at (0, 0), and print the ending location. 


The Monty Hall Paradox. Marilyn vos Savant described the following problem 
(loosely based on a game show hosted by Monty Hall) ina popular magazine: “Sup- 
pose you’re ona game show, and you're given the choice of three doors: Behind one 
door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who 
knows what’s behind the doors, opens another door, say No. 3, which has a goat. 
He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to 
switch your choice?” 


Ms. vos Savant proved that it is to your advantage, but many of her readers, includ- 
ing some mathematics professors, disagreed, arguing that the probability would not 
change because another door was opened. 

Your task is to simulate this game show. In each iteration, randomly pick a door 
number between 1 and 3 for placing the car. Randomly have the player pick a door. 
Randomly have the game show host pick a door having a goat (but not the door that 


= P4.25 


aa P4.26 


Programming Exercises 193 


the player picked). Increment a counter for strategy 1 if the player wins by switching 
to the host’s choice, and increment a counter for strategy 2 if the player wins by 
sticking with the original choice. Run 1,000 iterations and print both counters. 


A simple random generator is obtained by the formula 


FS (a ‘ae b)%m 


new 


and then setting rgjq to Tnew- If m is chosen as 2°, then you can compute 


Trew — 4° "old t b 
because the truncation of an overflowing result to the int type is equivalent to 
computing the remainder. 


Write a program that asks the user to enter a seed value for rgjg. (Such a value is often 
called a seed). Then print the first 100 random integers generated by this formula, 
using a = 32310901 and b = 1729. 


The Buffon Needle Experiment. The following experiment was devised by Comte 
Georges-Louis Leclerc de Buffon (1707-1788), a French naturalist. A needle of 
length 1 inch is dropped onto paper that is ruled with lines 2 inches apart. If the 
needle drops onto a line, we count it as a hit. (See Figure 9.) Buffon discovered that 
the quotient tries/hits approximates 2. 











Figure 9 
The Buffon Needle Experiment 





For the Buffon needle experiment, you must generate two random numbers: one to 
describe the starting position and one to describe the angle of the needle with the 
x-axis. Then you need to test whether the needle touches a grid line. 


Generate the lower point of the needle. Its x-coordinate is irrelevant, and you may 
assume its y-coordinate yoy, to be any random number between 0 and 2. The angle a 
between the needle and the x-axis can be any value between 0 degrees and 180 
degrees (a radians). The upper end of the needle has y-coordinate 


Vhigh ~ Jlow + sino 


The needle is a hit if ypigh 1s at least 2, as shown in Figure 10. Stop after 10,000 tries 
and print the quotient tries/hits. (This program is not suitable for computing the 
value of a. You need x in the computation of the angle.) 





Figure 10 
A Hit in the Buffon Needle Experiment 0 





194 Chapter 4 Loops 


»= Business P4.27 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. 


«= Business P4.28 Write a program that first asks the user igs SINGAPORE 
to type in today’s price of one dollar 4 HONG KONG 
in Japanese yen, then reads U.S. dollar = 
values and converts each to Japanese 
yen. Use 0 as the sentinel value to denote the end of dollar inputs. Then the program 
reads a sequence of yen amounts and converts them to dollars. The second sequence 
is terminated by another zero value. 





u= Business P4.29 Your company has shares of stock it would like to sell when their value exceeds a 
certain target price. Write a program that reads the target price and then reads the 
current stock price until it is at least the target price. Your program should use a 
Scanner to read a sequence of double values from standard input. Once the minimum 
is reached, the program should report that the stock price exceeds the target price. 


«= Business P4.30 Write an application to pre-sell a limited number of cinema tickets. Each buyer can 
buy as many as 4 tickets. No more than 100 tickets can be sold. Implement a pro- 
gram called TicketSeller that prompts the user for the desired number of tickets and 
then displays the number of remaining tickets. Repeat until all tickets have been 
sold, and then display the total number of buyers. 


«= Business P4.31 Youneed to control the number of people who can be in an oyster bar at the same 
time. Groups of people can always leave the bar, but a group cannot enter the bar 
if they would make the number of people in the bar exceed the maximum of 100 
occupants. Write a program that reads the sizes of the groups that arrive or depart. 
Use negative numbers for departures. After each input, display the current number 
of occupants. As soon as the bar holds the maximum number of people, report that 
the bar is full and exit the program. 


uns Business P4.32 Credit Card Number Check. The last digit of a credit card number is the check 
digit, which protects against transcription errors such as an error ina single digit or 
switching two digits. The following method is used to verify actual credit card num- 
bers but, for simplicity, we will describe it for numbers with 8 digits instead of 16: 


e Starting from the rightmost digit, form the sum of every other digit. For 
example, if the credit card number is 4358 9795, then you form the sum 
5+7+84+3=23. 


¢ Double each of the digits that were not included in the preceding step. Add all 
digits of the resulting numbers. For example, with the number given above, 
doubling the digits, starting with the next-to-last one, yields 18 18 10 8. Adding 
all digits in these values yields 1+8+1+8+1+0+8=27. 
e Add the sums of the two preceding steps. If the last digit of the result is 0, the 
number is valid. In our case, 23 + 27 = 50, so the number is valid. 
Write a program that implements this algorithm. The user should supply an 8-digit 
number, and you should print out whether the number is valid or not. If it is not 
valid, you should print the value of the check digit that would make it valid. 


a= Science P4.33 


aa Science P4.34 


Programming Exercises 195 


Ina predator-prey simulation, you compute the populations of predators and prey, 
using the following equations: 


PVEV na = PTCV, X (1 +A-Bx pred, ) 
pred, ,, = pred, x (1 -C+Dx prey,,) 


Here, A is the rate at which prey birth exceeds natural 
death, B is the rate of predation, C is the rate at which 
predator deaths exceed births without food, and D repre- 
sents predator increase in the presence of food. 


Write a program that prompts users for these rates, the 
initial population sizes, and the number of periods. Then 
print the populations for the given number of periods. As 
inputs, try A =0.1, B= C=0.01, and D = 0.00002 with 
initial prey and predator populations of 1,000 and 20. 





Projectile flight. Suppose a cannonball is propelled straight into the air with a starting 
velocity Yo Any calculus book will state that the position of the ball after t seconds is 
s(t) = —4 ge + Upt, where g = 9.81 m s? is the gravitational force of the earth. No 
calculus textbook ever mentions why someone would want to carry out such an 
obviously dangerous experiment, so we will do it in the safety of the computer. 


In fact, we will confirm the theorem 
from calculus by a simulation. In our 
simulation, we will consider how the 
ball moves in very short time intervals 
At. Ina short time interval the velocity v 
is nearly constant, and we can compute 
the distance the ball moves as As = vAt. 
In our program, we will simply set 


const double DELTA_T = 0.01; 





and update the position by 
s=s +v * DELTAT; 

The velocity changes constantly —in fact, it is reduced by the gravitational force of 

the earth. Ina short time interval, Av =—gAt, we must keep the velocity updated as 


v=v-g * DELTAT; 
In the next iteration the new velocity is used to update the distance. 


Now run the simulation until the cannonball falls back to the earth. Get the initial 
velocity as an input (100 m/s is a good value). Update the position and velocity 100 
times per second, but print out the position only every full second. Also printout the 
values from the exact formula s(t) = —t gi? + Upt for comparison. 


Note: You may wonder whether there is a benefit to this simulation when an exact 
formula is available. Well, the formula from the calculus book is not exact. Actually, 
the gravitational force diminishes the farther the cannonball is away from the surface 
of the earth. This complicates the algebra sufficiently that it is not possible to give an 
exact formula for the actual motion, but the computer simulation can simply be 
extended to apply a variable gravitational force. For cannonballs, the calculus-book 
formula is actually good enough, but computers are necessary to compute accurate 
trajectories for higher-flying objects such as ballistic missiles. 


196 Chapter4 Loops 


aaa Science P4.35 


= Science P4.36 


uae Science P4.37 





A simple model for the hull of a ship is given by 


B 2x) z/ 
eae ra ag 
where B is the beam, L is the length, and T is the draft. (Note: There are two values of 
y for each x and z because the hull is symmetric from starboard to port.) 





The cross-sectional area at a point x is called the “section” in nauti- 
cal parlance. To compute it, let z go from 0 to-T in z increments, 
each of size T/n. For each value of z, compute the value for y. 
Then sum the areas of trapezoidal strips. At right are the strips 
where n = 4. 


Write a program that reads in values for B, L, T, x, and n and then 
prints out the cross-sectional area at x. 





Radioactive decay of radioactive materials can be mod- 
eled by the equation A = Age*(!°87/”), where A is the 
amount of the material at time t, Ag is the amount at 
time 0, and 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 / Ay ina patient 
body every hour for 24 hours after receiving a dose. 





The photo at left shows an electric device called a “transformer”. Transformers are 
often constructed by wrapping coils of wire around a ferrite core. The figure below 
illustrates a situation that occurs in various audio devices such as cell phones and 
music players. In this circuit, a transformer is used to connect a speaker to the output 
of an audio amplifier. 


Ry =209 





Amplifier Transformer Speaker 


= Graphics P4.38 


= Graphics P4.39 


uae Graphics P4.40 


a Graphics P4.41 


uae Graphics P4.42 


Programming Exercises 197 


The symbol used to represent the transformer is intended to suggest two coils of 
wire. The parameter 7 of the transformer is called the “turns ratio” of the trans- 
former. (The number of times that a wire is wrapped around the core to form a coil is 
called the number of turns in the coil. The turns ratio is literally the ratio of the 
number of turns in the two coils of wire.) 


When designing the circuit, we are concerned primarily with the value of the power 
delivered to the speakers—that power causes the speakers to produce the sounds we 
want to hear. Suppose we were to connect the speakers directly to the amplifier 
without using the transformer. Some fraction of the power available from the 
amplifier would get to the speakers. The rest of the available power would be lost in 
the amplifier itself. The transformer is added to the circuit to increase the fraction of 
the amplifier power that is delivered to the speakers. 


The power, P,, delivered to the speakers is calculated using the formula 


2 
nv, 
P=RI|s 
n°R, + R, 
Write a program that models the circuit shown and varies the turns ratio from 0.01 to 


2 in 0.01 increments, then determines the value of the turns ratio that maximizes the 
power delivered to the speakers. 


Write a program to plot the following face. 


Write a graphical application that displays a checkerboard with 64 squares, alternat- 
ing white and black. 


Write a graphical application that draws a spiral, such as the following: 


It is easy and fun to draw graphs of curves with the Java graphics library. Simply 
draw 100 line segments joining the points (x, f(x)) and (x + d, f(x + d)), where x 
ranges from Xin tO Xpax and d = (xX... — Xmin 

Draw the curve f(x) = 0.00005x? — 0,03x? + 4x + 200, where x ranges from 0 to 
400 in this fashion. 


Draw a picture of the “four-leaved rose” whose equation in polar coordinates is 
r = cos(20) . Let @ go from 0 to 27 in 100 steps. Each time, compute r and then 
compute the (x, y) coordinates from the polar coordinates by using the formula 


x =r-cos(@), y = r- sin(@) 


198 Chapter 4 Loops 


ANSWERS TO SELF-CHECK QUESTIONS 


10. 


. 23 years. 
. 7 years. 


Adda statement 
System.out.printIn(balance) ; 
as the last statement in the while loop. 


The program prints the same output. This is 
because the balance after 14 years is slightly 
below $20,000, and after 15 years, it is slightly 
above $20,000. 

2 4 8 16 32 64 128 

Note that the value 128 is printed even though 
it is larger than 100. 


output 


n 
5 
4 
3 
2 
t 
8 
-1 


FPORNWA 


n output 
zt oi, 
2 1, 2, 

oly ar33y 

4 
There is acomma after the last value. Usually, 
commas are between values only. 


a n 
2 4 


De ANH I 
ubw wy H oa 


1 
The code computes a". 


output 
1 

11 

21 

31 

41 

51 

61 


PREAH ys 


This is an infinite loop. nis never equal to 50. 


count temp 
1 123 
Z 12.3 
3 1.23 


11. 


12. 
13. 


14. 


15. 


16. 


17. 


This yields the correct answer. The number 
123 has 3 digits. 


count temp 
1 100 
Z 10.0 


This yields the wrong answer. The number 100 
also has 3 digits. The loop condition should 
have been 


while (temp >= 10) 


jnt year = 1; 
while (year <= nyears) 


double interest = balance * RATE / 100; 
balance = balance + interest; 
System.out.printf("%4d %10.2f\n", 

year, balance); 
yeart++; 


} 
11 numbers: 109876543210 
for (int i = 10; 7 <= 20; i = 7+ 2) 


{ 
System.out.printIn(i); 
} 
int sum = 0; 
for (int i = 1; 1 <= nj i++) 
{ . 
sum = sum + 7; 
} 


for (int year = 1; 
balance <= 2 * INITIAL_BALANCE; year++) 


However, it is best not to use a for loop in this 
case because the loop condition does not relate 
to the year variable. A while loop would bea 
better choice. 


do 
{ 
System.out.print( 
"Enter a value between 0 and 100: "); 
value = in.nextInt(); 
} 


while (value < 0 || value > 100); 


int value = 100; 

while (value >= 100) 

{ 
System.out.print("Enter a value < 100: "); 
value = in.nextIntQ); 


} 


18. 


19. 


20. 


21. 
22. 


23. 


24. 


25. 


26. 


Here, the variable value had to be initialized 
with an artificial value to ensure that the loop 
is entered at least once. 


Yes. The do loop 
do { body } while (condition) ; 
is equivalent to this while loop: 


boolean first = true; 
while (first || condition) 


body; 


first = false; 


} 

int x; 

int sum = 0; 

do 

{ 
xX = in.nextIntQ; 
sum = sum + Xx; 

} 

while (x != 0); 

int x = 0; 

jnt previous; 

do 

{ . 
previous = x; 
xX = in.nextIntQ; 
sum = sum + Xx; 

} 


while (x != 0 && previous != x); 
No data 


The first check ends the loop after the sentinel 
has been read. The second check ensures that 
the sentinel is not processed as an input value. 


The while loop would never be entered. The 
user would never be prompted for input. 
Because count stays 0, the program would then 
print "No data". 


The nextDouble method also returns false. 

A more accurate prompt would have been: 
“Enter values, a key other than a digit to quit.” 
But that might be more confusing to the pro- 
gram user who would need now ponder which 
key to choose. 


If the user doesn’t provide any numeric input, 
the first call to in.nextDoubleQ will fail. 


Computing the average 


Enter scores, Q to quit: 90 80 90 100 30Q 
The average is 88 
(Program exits) 


27. 


28. 


29. 


30. 


31. 
32. 


33. 


Answers to Self-Check Questions 199 


Simple conversion 


Only one value can be converted 


Your conversion question: How many in are 30 cm 


30 cm = 11.81 in ; ; 
(Program exits) — = Run program again for another question 


Unknown unit 


Your conversion question: How many inches are 30 cm? 

Unknown unit: inches 

Known units are in, ft, mi, mm, cm, m, km, 0z, Ib, g, ka, tsp, thsp, pint, gal 
(Program exits) 


Program doesn't understand question syntax 


Your conversion question: What is an angstrom? 
Please formulate your question as “How many (unit) are (value) (unit)?” 
(Program exits) 


One score is not enough 


Enter scores, Q to quit: 90 Q 
Error: At least two scores are required. 
(Program exits) 


It would not be possible to implement this 
interface using the Java features we have cov- 
ered up to this point. There is no way for the 
program to know when the first set of inputs 
ends. (When you read numbers with value = 
in.nextDouble(), itis your choice whether to put 
them ona single line or multiple lines.) 


Comparing two interest rates 


First interest rate in percent: 5 
Second interest rate in percent: 10 





Years: 9 

Year 52 102 

0 1000.00 10000.00-——~ Higgdt racine is bial 
1 1050000 1000.00 

2 11025.00 12100.00 

3 1157625 1910.00 

4 12155.06 14641.00 

5 1276282 16105.10 


The total is zero. 


double total = 0; 
while Cin. hasNextDouble()) 


double input = in.nextDouble(); 

if Cinput > 0) { total = total + input; } 
} 
position is str. length() and ch is unchanged 
from its initial value, '?'. Note that ch must 


200 Chapter 4 Loops 


34. 


35. 


36. 


37. 


38. 


be initialized with some value—otherwise the 
compiler will complain about a possibly unini- 
tialized variable. 

The loop will stop when a match is found, but 
you cannot access the match because neither 
position nor chare defined outside the loop. 
Start the loop at the end of string: 


boolean found = false; 
int i = str.lengthQ - 1; 
while (!found && i >= 0) 


{ 
char ch = str.charAt(i); 
if (ch == ' ') { found = true; } 
else { i--; } 

} 


The initial call to in.nextDouble() fails, termi- 
nating the program. One solution is to do all 
input in the loop and introduce a Boolean vari- 
able that checks whether the loop is entered for 
the first time. 
double input = 0; 
boolean first = true; 
while Cin. hasNextDouble()) 
: double previous = input; 

jnput = in.nextDouble(); 

if (first) { first = false; } 

else if Cinput == previous) 

{ 


System.out.printIn("Duplicate input"); 
} 
} 


All values in the inner loop should be dis- 
played on the same line. 


Change lines 13, 18, and 30 to for (int n = 0; 
n <= NMAX; n++). Change NMAX to 5. 


39. 


40. 


41. 


42. 


43. 


44. 


45. 


46. 


60: The outer loop is executed 10 times, and 
the inner loop 6 times. 


0123 
1234 
2345 
for (int i = 1; 7 <= 3; i++) 
{ 
for (int j = 1; j <= 4; j++) 
{ 
System.out.print("[]"); 
} 
System.out.printInQ; 
} 


Compute (int) (Math.random() * 2), and use 0 
for heads, 1 for tails, or the other way around. 


Compute (int) (Math.random() * 4) and asso- 
ciate the numbers 0... 3 with the four suits. 
Then compute (int) (Math.random() * 13) and 
associate the numbers 0... 12 with Jack, Ace, 2 
... 10, Queen, and King. 


We need to call it once for each die. If we 
printed the same value twice, the die tosses 
would not be independent. 


The call will produce a value between 2 and 
12, but all values have the same probability. 
When throwing a pair of dice, the number 7 is 
six times as likely as the number 2. The correct 
formula is 

int sum = (int) (Math.random() * 6) + Cint) 
(Math.random() * 6) + 2; 


Math.random() * 100.0 


TTT) S 
METHODS 


CHAPTER GOALS 


To be able to implement methods 


To become familiar with the concept of 
parameter passing 





To develop strategies for decomposing 
complex tasks into simpler ones 


To be able to determine the scope of a variable 


To learn how to think recursively (optional) 


CHAPTER CONTENTS 


5.1 METHODS AS BLACK BOXES 202 5.7 PROBLEM SOLVING: STEPWISE 


5.2 IMPLEMENTING METHODS 204 a mate ae wieeaaeu 593 
Syntax 5.1: Static Method Declaration 205 rOgranining Tip-3:3; Keep Metiods sien 


Programming Tip 5.1: Method Comments 207 POG TAENING vp pea) Macing Momods.22° 
Programming Tip 5.5: Stubs 224 


5.3 PARAMETER PASSING 207 Worked Example 5.2: Calculating a 
Programming Tip 5.2: Do Not Modify Parameter Course Grade © 


“ see a rere 5.8 VARIABLE SCOPE 225 
OT EO nae o cone Video Example 5.1: Debugging @ 


Arguments 209 
5.4 RETURNVALUES 210 5.9 RECURSIVE METHODS 
. a (OPTIONAL) 228 
Common Error 5.2: Missing Return Value 212 How To 5.2: Thinking Recursively 231 


How I9./2 Implemennnge Mehod: 212 Random Fact 5.1: The Explosive Growth of 
Worked Example 5.1: Generating Random Personal Computers 232 

Passwords @ Video Example 5.2: Fully Justified Text @ 
5.5 METHODS WITHOUT 

RETURN VALUES 214 


5.6 PROBLEM SOLVING: REUSABLE 
METHODS 215 





_|_ Meth 


A method isa 
named sequence 
of instructions. 


202 





Black Box 


A method is a sequence of instructions with a name. You have already encountered 
several methods. For example, the Math. pow method, which was introduced in Chapter 
2, contains instructions to compute a power x”. Moreover, every Java program has a 
method called main. 

You call a method in order to execute its instructions. For example, consider the 
following program fragment: 


public static void main(String[] args) 


{ 
double result = Math.pow(2, 3); 


} 


By using the expression Math.pow(2, 3), main calls the Math.pow method, asking it to 
compute 2°. The instructions of the Math.pow method execute and compute the result. 
The Math. pow method returns its result back to main, and the main method resumes exe- 
cution (see Figure 1). 


main 
Pass 2 and 3 to Math . pow 
Math. pow 
Compute 2? 
Pass result 
to caller 
Use result 


Figure 1 Execution Flow During a Method Call 


Arguments are 
supplied whena 
method is called. 


The return value is 
the result that the 


method computes. 


5.1 Methods as Black Boxes 203 


Figure 2 
The Math.pow Method 
as a Black Box 


Arguments 
2,3 


Return value 


When another method calls the Math. pow method, it provides “inputs”, such as the 
values 2 and 3 in the call Math.pow(2, 3). These values are called the arguments of the 
method call. Note that they are not necessarily inputs provided by a human user. 
They are simply the values for which we want the method to compute a result. The 
“output” that the Math. pow method computes is called the return value. 

Methods can receive multiple arguments, but they return only one value. It is also 
possible to have methods with no arguments. An example is the Math. random method 
that requires no argument to produce a random number. 

The return value of a method is returned to the calling method, where it is pro- 
cessed according to the statement containing the method call. For example, suppose 
your program contains a statement 


double result = Math.pow(2, 3); 


When the Math.pow method returns its result, the return value is stored in the 
variable result. 

Do not confuse returning a value with producing program output. If you want 
the return value to be printed, you need to add a statement such as System.out. 
print(result). 

At this point, you may wonder how the Math. pow method performs its job. For 
example, how does Math.pow compute that 2? is 8? By multiplying 2 x 2 x 2? With 
logarithms? Fortunately, as a user of the method, you don’t need to know how the 
method is implemented. You just need to know the specification of the method: If you 
provide arguments x and y, the method returns x”. Engineers use the term black box 
for a device with a given specification but unknown implementation. You can think 
of Math. pow as a black box, as shown in Figure 2. 

When you design your own methods, you will want to make them appear as black 
boxes to other programmers. Those programmers want to use your methods without 
knowing what goes on inside. Even if you are the only person working ona program, 
making each method into a black box pays off: there are fewer details that you need to 
keep in mind. 


Although a thermostat is usually white, you 
can think of it as a “black box”. The input is the 
desired temperature, and the output is a signal 
to the heater or air conditioner. 





204 Chapter5 Methods 


1. Consider the method call Math.pow(3, 2). What are the arguments and return 
values? 

2. What is the return value of the method call Math. pow(Math.pow(2, 2), 2)? 

3. The Math.ceil method in the Java standard library is described as follows: The 
method receives a single argument a of type double and returns the smallest double 
value = a that is an integer. What is the return value of Math.ceil(2.3)? 





4. It is possible to determine the answer to Self Check 3 without knowing how the 
Math.ceil method is implemented. Use an engineering term to describe this 
aspect of the Math.cei] method. 


Practice It Now you cantry these exercises at the end of the chapter: R5.3, R5.6. 


.2 Implementing Meth 


In this section, you will learn how to implement a 
method from a given specification. We will use a very 
simple example: a method to compute the volume of a 
cube with a given side length. 


The cubeVolume method uses a given side 
length to compute the volume of a cube. 





niteercence When writing this method, you need to 


method, you provide 
a name for the ; 
method, a variable ¢ Declare a variable for each argument (double sideLength). These variables are called 


foreaclvatgaments the parameter variables. 
and a type for 


the result. e Specify the type of the return value (double). 


e Picka name for the method (cubeVolume). 


e Add the public static modifiers. We will discuss the meanings of these modifiers 
in Chapter 8. For now, you should simply add them to your methods. 


Put all this information together to form the first line of the method’s declaration: 
public static double cubeVolume(double sideLength) 


This line is called the header of the method. Next, specify the body of the method. 
The body contains the variable declarations and statements that are executed when 
the method is called. 

The volume of a cube of side length s is s x s x s. However, for greater clarity, our 
parameter variable has been called sideLength, not s, so we need to compute sideLength 
* sideLength * sideLength. 

We will store this value in a variable called volume: 


double volume = sideLength * sideLength * sideLength; 
In order to return the result of the method, use the return statement: 


return volume; 


5.2 Implementing Methods 205 


The return statement gives the 
method's result to the caller. 





The body of a method is enclosed in braces. Here is the complete method: 


public static double cubeVolume(double sideLength) 

{ 
double volume = sideLength * sideLength * sideLength; 
return volume; 


} 


Let’s put this method to use. We’ll supply a main method that calls the cubeVolume 
method twice. 


public static void main(String[] args) 


{ 
double resultl = cubeVolume(2); 
double result2 = cubeVolume(10) ; 
System.out.printIn("A cube with side length 2 has volume " + result1); 
System.out.printIn("A cube with side length 10 has volume " + result2); 
} 


When the method is called with different arguments, the method returns different 
results. Consider the call cubeVolume(2). The argument 2 corresponds to the sideLength 
parameter variable. Therefore, in this call, sideLength is 2. The method computes 


Syntax 5.1 Static Method Declaration 


Syntax public static returnType methodName(parameterType parameterName, .. . 


method body 
} 


Type of return value Type of parameter variable 
Name of method Pi of parameter variable 


public static double cubeVolume(double sideLength) 


{ 
Method body, double volume = sideLength * sideLength * sideLength; 
executed when return volume; 


method is called. } 


return statement 
exits method and 
returns result. 





206 Chapter5 Methods 


sideLength * sideLength * sideLength, or 2 * 2 * 2. When the method is called with a dif- 
ferent argument, say 10, then the method computes 10 * 10 * 10. 

Now we combine both methods into a test program. Note that both methods are 
contained in the same class. Also note the comment that describes the behavior of the 
cubeVolume method. (Programming Tip 5.1 describes the format of the comment.) 


section_2/Cubes.java 
[** 


2 ; This program computes the volumes of two cubes. 
; oe class Cubes 

: public static void main(String[] args) 

; double resultl = cubeVolume(2); 

9 double result2 = cubeVolume(10); 


10 System.out.printInC"A cube with side length 2 has volume " + result1); 
11 System.out.printInC"A cube with side length 10 has volume " + result2); 
12 } 

13 

14 /** 

15 Computes the volume of a cube. 

16 @param sideLength the side length of the cube 

17 @return the volume 

18 */ 

19 public static double cubeVolume(double sideLength) 

20 { 

21 double volume = sideLength * sideLength * sideLength; 

22 return volume; 

23 } 

24 } 


Program Run 


A cube with side length 2 has volume 8 
A cube with side length 10 has volume 1000 


5. What is the value of cubeVolume (3) ? 
6. What is the value of cubeVolume (cubeVolume(2)) ? 


7. Provide an alternate implementation of the body of the cubeVolume method by 
calling the Math.pow method. 





8. Declare a method squareArea that computes the area of a square of a given side 
length. 

9. Consider this method: 
public static int mystery(int x, int y) 


{ 
double result = (x + y) / (y - x); 
return result; 


} 
What is the result of the call mystery(2, 3)? 


Practice It Now youcantry these exercises at the end of the chapter: R5.1, R5.2, P5.5, P5.22. 


Programming Tip 5.1 





5.3 Parameter Passing 207 


Method Comments 


Whenever you write a method, you should comment its behavior. Comments are for human 
readers, not compilers. The Java language provides a standard layout for method comments, 
called the javadoc convention, as shown here: 


/** 
Computes the volume of a cube. Serre Soe 
@param sideLength the side length of the cube BE haere 
7 @return the volume meaninatente 
. parameter variables 
public static double cubeVolume(double sideLength) and return value, as 
{ well as any special 
double volume = sideLength * sideLength * sideLength; requirements. 
return volume; 
} 


Comments are enclosed in /** and */ delimiters. The first line of the comment describes the 
purpose of the method. Each @param clause describes a parameter variable and the @return 
clause describes the return value. 

Note that the method comment does not document the implementation (how the method 
carries out its work) but rather the design (what the method does). The comment allows other 
programmers to use the method as a “black box”. 


.3 Param rP in 





Parameter variables 
hold the arguments 
supplied in the 
method call. 


A recipe for a fruit pie may say to use any kind of fruit. 
Here, “fruit” is an example of a parameter variable. 
Apples and cherries are examples of arguments. 


In this section, we examine the mechanism of parameter passing more closely. When 

a method is called, variables are created for receiving the method’s arguments. These 

variables are called parameter variables. (Another commonly used term is formal 

parameters.) The values that are supplied to the method when it is called are the 

arguments of the call. (These values are also commonly called the actual param- 

eters.) Each parameter variable is initialized with the corresponding argument. 
Consider the method call illustrated in Figure 3: 


double result1 = cubeVolume(2) ; 









pie(fruit) piel fruit) 





208 Chapter5 Methods 





hm 
ANIMATION 
Parameter Passing 


[i 





SELF CHECK 


1) Method call 


double resultl = cubeVolume(2); 


(2) Initializing method parameter variable 


double resultl = cubeVolume(2); 


a) About to return to the caller 


double volume = sideLength * sideLength * sideLength; 
return volume; 


4) After method call 


double resultl = cubeVolume(2); 





Figure 3 Parameter Passing 


e The parameter variable sideLength of the cubeVolume method is created when the 


method is called. @ 


e The parameter variable is initialized with the value of the argument that was 
passed in the call. In our case, sideLength is set to2. @ 


The method computes the expression sideLength * sideLength * sideLength, which 
has the value 8. That value is stored in the variable volume. @ 


The method returns. All of its variables are removed. The return value is trans- 
ferred to the caller, that is, the method calling the cubeVolume method. The caller 
puts the return value in the result1 variable. @ 


Now consider what happens in a subsequent call, cubeVolume(10). A new parameter 
variable is created. (Recall that the previous parameter variable was removed when 
the first call to cubeVolume returned.) It is initialized with 10, and the process repeats. 
After the second method call is complete, its variables are again removed. 


10. What does this program print? Use a diagram like Figure 3 to find the answer. 


public static double mystery(int x, int y) 
{ 
double z = x + y; 
z=Z/ 2.0; 
return Z; 
} 
public static void main(String[] args) 


{ 


int a= 5; 
int b = 7; 


Practice It 


5.3 Parameter Passing 209 


System.out.printIn(mystery(a, b)); 
} 


11. What does this program print? Use a diagram like Figure 3 to find the answer. 


public static int mystery(int x) 


{ 
int y=x * x; 
return y; 
3 
public static void main(String[] args) 
{ 
int a = 4; 


System.out.printIn(mystery(a + 1)); 
3 


12. What does this program print? Use a diagram like Figure 3 to find the answer. 


public static int mystery(int n) 
{ 
n++3 
n++3 
return n; 
} 
public static void main(String[] args) 
{ 
int a= 5; 
System.out.printIn(mystery(a)); 


} 


Now you can try these exercises at the end of the chapter: R5.5, R5.14, P5.8. 


Programming Tip 5.2 Do Not Modify Parameter Variables 


se 





In Java, a parameter variable is just like any other variable. You can modify the values of the 
parameter variables in the body of a method. For example, 


public static int totalCents(int dollars, int cents) 

{ 
cents = dollars * 100 + cents; // Modifies parameter variable 
return cents; 


} 


However, many programmers find this practice confusing (see Common Error 5.1). To avoid 
the confusion, simply introduce a separate variable: 


public static int totalCents(int dollars, int cents) 
{ 

int result = dollars * 100 + cents; 

return result; 


Gommonerrorsa Trying to Modify Arguments 


The following method contains a common error: trying to modify an argument. 


public static int addTax(double price, double rate) 
{ 
double tax = price * rate / 100; 
price = price + tax; // Has no effect outside the method 


210 Chapter5 Methods 


return tax; 


} 
Now consider this call: 


double total = 10; 
addTax(total, 7.5); // Does not modify total 


When the addTax method is called, price is set to 10. Then price is changed to 10.75. When the 
method returns, all of its parameter variables are removed. Any values that have been assigned 
to them are simply forgotten. Note that total is mot changed. In Java, a method can never 
change the contents of a variable that was passed as an argument. 


5.4 Return Values 


The return statement 
terminates a method 
call and yields the 
method result. 


You use the return statement to specify the result of a method. In the preceding exam- 
ples, each return statement returned a variable. However, the return statement can 
return the value of any expression. Instead of saving the return value ina variable and 
returning the variable, it is often possible to eliminate the variable and return a more 
complex expression: 


public static double cubeVolume(double sideLength) 
{ 


} 


When the return statement is processed, the method exits immediately. Some 

. . P . : . . a4 
programmers find this behavior convenient for handling exceptional cases at the 
beginning of the method: 


return sideLength * sideLength * sideLength; 


public static double cubeVolume(double sideLength) 


{ 
if (sideLength < 0) { return 0; } 
// Handle the regular case 


} 


If the method is called with a negative value for sideLength, then the method returns 0 
and the remainder of the method is not executed. (See Figure 4.) 


True 
F 13A F sideLength <0? return 0 
| Newark Airport - 
Elizabeth Seaport 
False 
volume = 


sideLength x 
sideLength x 
sideLength 


return volume 





Figure4_ A return Statement Exits a Method Immediately 


ONLINE EXAMPLE 


A program showing a 
method with multiple 
return statements. 





Practice It 


5.4 ReturnValues 211 


Every branch of a method needs to return a value. Consider the following incor- 
rect method: 


public static double cubeVolume(double sideLength) 
{ 
if (sideLength >= 0) 
{ 
return sideLength * sideLength * sideLength; 
} // Error—no return value if sideLength < 0 


The compiler reports this as an error. A correct implementation is: 


public static double cubeVolume(double sideLength) 


{ 
if (sideLength >= 0) 
{ 
return sideLength * sideLength * sideLength; 
i; 
else 
{ 
return 0; 
t 
} 


Many programmers dislike the use of multiple return statements in a method. You 
can avoid multiple returns by storing the method result in a variable that you return 
in the last statement of the method. For example: 


public static double cubeVolume(double sideLength) 


{ 
double volume; 
if (sideLength >= 0) 
{ 
volume = sideLength * sideLength * sideLength; 
} 
else 
{ 
volume = 0; 
} 
return volume; 
} 


13. Suppose we change the body of the cubeVolume method to 
if (sideLength <= 0) { return 0; } 
return sideLength * sideLength * sideLength; 
How does this method differ from the one described in this section? 


14. What does this method do? 


public static boolean mystery (int n) 
{ 
if (n % 2 == 0) { return true }; 
else { return false; } 


} 
15. Implement the mystery method of Self Check 14 witha single return statement. 


Now you can try these exercises at the end of the chapter: R5.13, P5.20. 


212 Chapter5 Methods 


(@foynalaakelaM=laae) moe. 





HOW TO 5.1 





Step 1 


Step 2 


Missing Return Value 


It is a compile-time error if some branches of a method return a value and others do not. Con- 
sider this example: 


public static int sign(double number) 
{ 
if (number < 0) { return -1; } 
if (number > 0) { return 1; } 
// Error: missing return value if number equals 0 


} 


This method computes the sign of a number: -1 for negative numbers and +1 for positive num- 
bers. If the argument is zero, however, no value is returned. The remedy is to add a statement 
return 0; to the end of the method. 


Implementing a Method 


A method is a computation that can be used multiple 
times with different arguments, either in the same pro- 
gram or in different programs. Whenever a computa- 
tion is needed more than once, turn it into a method. 

To illustrate this process, suppose that you are help- 
ing archaeologists who research Egyptian pyramids. 
You have taken on the task of writing a method that 
determines the volume of a pyramid, given its height 
and base length. 





Describe what the method should do. 


Provide a simple English description, such as “Compute the volume of a pyramid whose base 
is a square.” 


SEK 


Determine the method’s “inputs”. 


Make a list of all the parameters that can vary. Itiscommonforbegin- 4, eoimpitatlons 
ners to implement methods that are overly specific. Forexample, you that can be reused 
may know that the great pyramid of Giza, the largest of the Egyptian _into methods. 
pyramids, has a height of 146 meters and a base length of 230 meters. 
You should oz use these numbers in your calculation, even if the original problem only asked 
about the great pyramid. It is just as easy—and far more useful—to write a method that com- 
putes the volume of any pyramid. 

In our case, the parameters are the pyramid’s height and base length. At this point, we have 
enough information to document the method: 


/** 
Computes the volume of a pyramid whose base is a square. 
@param height the height of the pyramid 
@param baseLength the length of one side of the pyramid’s base 
@return the volume of the pyramid 


*/ 


Step 3 


Step 4 


Step 5 


Step 6 


ONLINE EXAMPLE 


@ The program for 
calculating a 
pyramid’s volume. 


5.4 ReturnValues 213 


Determine the types of the parameter variables and the return value. 


The height and base length can both be floating-point numbers. Therefore, we will choose the 
type double for both parameter variables. The computed volume is also a floating-point num- 
ber, yielding a return type of double. Therefore, the method will be declared as 


public static double pyramidVolume(double height, double baseLength) 
Write pseudocode for obtaining the desired result. 


In most cases, a method needs to carry out several steps to find the desired answer. You may 
need to use mathematical formulas, branches, or loops. Express your method in pseudocode. 
An Internet search yields the fact that the volume of a pyramid is computed as 


volume = 1/3 x height x base area 
Because the base is a square, we have 
base area = hase length x base length 


Using these two equations, we can compute the volume from the arguments. 
Implement the method body. 


In our example, the method body is quite simple. Note the use of the return statement to 
return the result. 


public static double pyramidVolume(double height, double baseLength) 


{ 
double baseArea = baseLength * baseLength; 
return height * baseArea / 3; 
} 
Test your method. 


After implementing a method, you should test it in isolation. Such a test is called a unit test. 
Work out test cases by hand, and make sure that the method produces the correct results. 

For example, for a pyramid with height 9 and base length 10, we expect the area to be 1/3 x 9 x 
100 = 300. If the height is 0, we expect an area of 0. 


public static void main(String[] args) 


{ 
System.out.printIn("Volume: " + pyramidVolume(9, 10)); 
System.out.printIn("Expected: 300"); 
System.out.printIn("Volume: " + pyramidVolume(0, 10)); 
System.out.printIn("Expected: 0"); 

} 

The output confirms that the method worked as expected: 

Volume: 300 

Expected: 300 

Volume: 0 

Expected: 0 





WORKED EXAMPLE 5.1 Generating Random Passwords 


o 








Enter your current password: 








This Worked Example creates a method that generates 
passwords of a given length with at least one digit and 
one special character. 


Enter your new password: 














Retype your new password: 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


214 Chapter5 Methods 


____5.5 Methods Without Return Values 0 


Use a return type of 
void to indicate that a 
method does not 
return a value. 


ONLINE EXAMPLE 


© Acomplete program 
demonstrating the 
boxString method. 


Sometimes, you need to carry out a 
sequence of instructions that does 
not yield a value. If that instruction 
sequence occurs multiple times, you 
will want to package it into a method. 
In Java, you use the return type void to 
indicate the absence of a return value. 

Here is a typical example: Your task 
is to print a string in a box, like this: 





Avoid method returns no value, but it can 
produce output. 


However, different strings can be substituted for Hello. A method for this task can be 
declared as follows: 


public static void boxString(String contents) 


Now you develop the body of the method in the usual way, by formulating a general 
method for solving the task. 


Print a line that contains the - character n+ Z times, where n is the length of the string. 
Print a line containing the contents, surrounded with a ! to the left and right. 
Print another line containing the - character n + Z times. 


Here is the method implementation: 


[** 
Prints a string in a box. 
@param contents the string to enclose in a box 


¥/ 

public static void boxString(String contents) 

{ 
int n = contents. length(); 
for (int i = 0; i < n+ 2; i++) { System.out.print("-"); } 
System.out.printInQ; 
System.out.printIn("!" + contents + "!"); 
for (int i = 0; i < n+ 2; i++) { System.out.print("-"); } 
System.out.printInQ; 

} 


Note that this method doesn’t compute any value. It performs some actions and then 
returns to the caller. 

Because there is no return value, you cannot use boxString in an expression. You 
can call 


boxString("Hello"); 
but not 
result = boxString("Hello"); // Error: boxString doesn’t return a result. 


If you want to return from a void method before reaching the end, you use a return 
statement without a value. For example, 


public static void boxString(String contents) 


{ 





Practice It 


ae 


Eliminate replicated 
code or pseudocode 
by defining a method. 


5.6 Problem Solving: Reusable Methods 215 


int n = contents. length); 


if (n == 0) 
i! 
return; // Return immediately 


} 


16. How do you generate the following printout, using the boxString method? 


17. What is wrong with the following statement? 
System.out.print(boxString("Hello")); 


18. Implement a method shout that prints a line consisting of a string followed by 
three exclamation marks. For example, shout("He11o") should print Hello! !!. The 
method should not return a value. 


19. How would you modify the boxString method to leave a space around the string 


that is being boxed, like this: 


20. The boxString method contains the code for printing a line of - characters twice. 
Place that code into a separate method printLine, and use that method to simplify 
boxString. What is the code of both methods? 


Now you can try these exercises at the end of the chapter: R5.4, P5.25. 


ving: R le Meth 


You have used many methods from the standard Java library. These methods have 
been provided as a part of the Java platform so that programmers need not recre- 
ate them. Of course, the Java library doesn’t cover every conceivable need. You will 
often be able to save yourself time by designing your own methods that can be used 
for multiple problems. 

When you write nearly identical code or pseudocode multiple times, either in the 
same program or in separate programs, consider introducing a method. Here is a typ- 
ical example of code replication: 

int hours; 

do 

{ 

System.out.print("Enter a value between 0 and 23: "); 
hours = in.nextIntQ; 

} 


while (hours < 0 || hours > 23); 


216 Chapter5 Methods 


int minutes; 

do 

{ 
System.out.print("Enter a value between 0 and 59: "); 
minutes = in.nextIntQ); 


} 


while (minutes < 0 || minutes > 59); 


This program segment reads two variables, making sure that each of them is within a 
certain range. It is easy to extract the common behavior into a method: 


[** 
Prompts a user to enter a value up to a given maximum until the user 
provides a valid input. 
@param high the largest allowable input 
@return the value provided by the user (between 0 and high, inclusive) 


+] 
public static int readIntUpToCint high) 
{ 
int input; 
Scanner in = new Scanner(System. in) ; 
do 
{ 
System.out.print("Enter a value between 0 and " + high +": "); 
jnput = in.nextIntQ); 
} 


while Cinput < 0 || input > high); 
return input; 


} 
Then use this method twice: 


int hours = readIntUpTo(23); 
jnt minutes = readIntUpTo(59) ; 


We have now removed the replication of the loop—it only occurs once, inside the 
method. 

Note that the method can be reused in other programs that need to read integer 
values. However, we should consider the possibility that the smallest value need not 
always be zero. 


Here is a better alternative: 
Design your methods 


to be reusable. /** 
Shelby ee eter Prompts a user to enter a value within a given range until the user 
Marie Beate provides a valid input. 
WNcRne TeRea @param low the smallest allowable input 
@param high the largest allowable input 


is reused. : ‘ : : 
@return the value provided by the user (between low and high, inclusive) 
*/ 
public static int readIntBetween(int low, int high) 
{ 
int input; 
Scanner in = new Scanner(System. in) ; 
do 
{ 


System.out.print("Enter a value between " + low + " and "+ high + ": "); 


jnput = in.nextIntQ); 


while Cinput < low || input > high); 
return input; 


5.6 Problem Solving: Reusable Methods 217 


When carrying out the same task 
multiple times, use a method. 





In our program, we call 


A complete program int hours = readIntBetween(0, 23); 
demonstrating the 


readIntBetween Another program can call 
method. 
int month = readIntBetween(1, 12); 
In general, you will want to provide parameter variables for the values that vary when 


a method is reused. 





21. Consider the following statements: 


int totalPennies = (int) Math.round(100 * total) % 100; 
int taxPennies = (int) Math.round(100 * (total * taxRate)) % 100; 


SELF CHECK 


f 





Introduce a method to reduce code duplication. 
22. Consider this method that prints a page number on the left or right side of a 

page: 

if (page % 2 == 0) { System.out.printIn(page); } 

else { System.out.printIn(" 


+ page); } 
Introduce a method with return type boolean to make the condition in the if 
statement easier to understand. 

23. Consider the following method that computes compound interest for an 
account with an initial balance of $10,000 and an interest rate of 5 percent: 
public static double balance(int years) { return 10000 * Math.pow(1.05, years); } 
How can you make this method more reusable? 

24. The comment explains what the following loop does. Use a method instead. 


// Counts the number of spaces 
int spaces = 0; 
for (int i = 0; i < input. lengthQ; i++) 
{ 
if Cinput.charAt(i) == ' ') { spaces++; } 
} 
25. InSelf Check 24, you were asked to implement a method that counts spaces. 
How can you generalize it so that it can count any character? Why would you 
want to do this? 


Practice It Now youcantry these exercises at the end of the chapter: R5.7, P5.21. 


218 Chapter5 Methods 


Use the process of 
stepwise refinement 
to decompose 
complex tasks into 
simpler ones. 


Figure 5 
Flowchart of 
Coffee-Making 
Solution 





One of the most powerful strategies for 
problem solving is the process of stepwise 
refinement. To solve a difficult task, break 
it down into simpler tasks. Then keep break- 
ing down the simpler tasks into even simpler 
ones, until you are left with tasks that you 
know how to solve. 

Now apply this process to a problem of 
everyday life. You get up in the morning and 
simply must get coffee. How do you get cof- 
fee? You see whether you can get someone 
else, such as your mother or mate, to bring 
you some. If that fails, you must make coffee. 


Can you 
ask someone 
> 


Do you 
have a micro- 
wave? 


Fill kettle 
with water 


Fill cup 
with water 








A production process is broken down 
into sequences of assembly steps. 


Do you 
have instant 
coffee? 


Add water 
to coffee 
maker 


Add filter 
to coffee 
maker 


Add coffee 
beans to 
grinder 





Add coffee 
beans to 
filter 


Turn coffee 
maker on 


When you discover 
that you needa 
method, write a 
description of the 
parameter variables 
and return values. 


A method may 
require simpler 
methods to carry 
out its work. 


5.7. Problem Solving: Stepwise Refinement 219 


How do you make coffee? If there is instant coffee available, you can make instant coffee. 
How do you make instant coffee? Simply boil water and mix the boiling water with the 
instant coffee. How do you boil water? If there is a microwave, then you fill a cup 
with water, place it in the microwave and heat it for three minutes. Otherwise, you fill 
a kettle with water and heat it on the stove until the water comes to a boil. On the 
other hand, if you don’t have instant coffee, you must brew coffee. How do you brew 
coffee? You add water to the coffee maker, put in a filter, grind coffee, put the coffee in 
the filter, and turn the coffee maker on. How do you grind coffee? You add coffee 
beans to the coffee grinder and push the button for 60 seconds. 

Figure 5 shows a flowchart view of the coffee-making solution. Refinements are 
shown as expanding boxes. In Java, you implement a refinement as a method. For 
example, a method brewCoffee would call grindCoffee, and brewCoffee would be called 
from a method makeCoffee. 

Let us apply the process of stepwise refine- 
ment to a programming problem. When print- 
ing a check, it is customary to write the check 
amount both as a number (“$274.15”) and as a 
text string (“two hundred seventy four dollars 
and 15 cents”). Doing so reduces the recipient’s 
temptation to add a few digits in front of the 
amount. 

For a human, this isn’t particularly difficult, 
but how can a computer do this? There is no 
built-in method that turns 274 into "two hundred seventy four". We need to program 
this method. Here is the description of the method we want to write: 


[** 

Turns a number into its English name. 

@param number a positive integer < i ,000 

@return the name of number (e.g., “two hundred seventy four”) 
“/ 


public static String intName(int number) 





How can this method do its job? Consider a simple case first. If the number is between 
1 and 9, we need to compute "one" ... "nine". In fact, we need the same computation 
again for the hundreds (two hundred). Any time you need something more than once, it 
is a good idea to turn that into a method. Rather than writing the entire method, write 
only the comment: 
[** 
Turns a digit into its English name. 
@param digit an integer between 1 and 9 
@return the name of digit (“one”... “nine”) 
* 
Le ic static String digitName(int digit) 


Numbers between 10 and 19 are special cases. Let’s have a separate method teenName 
that converts them into strings "eleven", "twelve", "thirteen", and so on: 


[** 
Turns a number between 10 and 19 into its English name. 
@param number an integer between 10 and 19 
@return the name of the number (“ten” .. . “nineteen”) 
*/ 


public static String teenName(int number) 


220 Chapter5 Methods 






7 
ANIMATION 
Tracing a Method 


in 


Next, suppose that the number is between 20 and 99. The name of such a number has 
two parts, such as "seventy four". We need a way of producing the first part, "twenty", 
"thirty", and so on. Again, we will put that computation into a separate method: 


[** 
Gives the name of the tens part of a number between 20 and 99. 
@param number an integer between 20 and 99 
@return the name of the tens part of the number (“twenty” ... “ninety”) 


public static String tensName(int number) 


Now let us write the pseudocode for the intName method. If the number is between 
100 and 999, then we show a digit and the word "hundred" (such as "two hundred"). 
We then remove the hundreds, for example reducing 274 to 74. Next, suppose the 
remaining part is at least 20 and at most 99. If the number is evenly divisible by 10, 
we use tensName, and we are done. Otherwise, we print the tens with tensName (such as 
"seventy") and remove the tens, reducing 74 to 4. In a separate branch, we deal with 
numbers that are at between 10 and 19. Finally, we print any remaining single digit 
(such as "four"). 


part = number (The part that still needs to be converted) 


name = “" (The name of the number) 


If part >= 100 
name = name of hundreds in part * “ hundred" 
Remove hundreds from part. 


If part >= 20 
Append tensName(part) to name. 
Remove tens from part. 

Else if part >= 10 
Append teenNamel(part) to name. 
part = 0 


If (part > 0) 
Append digitName(part) to name. 


Translating the pseudocode into Java is straightforward. The result is shown in the 
source listing at the end of this section. 
Note how we rely on helper methods to do much of the detail work. Using the 
process of stepwise refinement, we now need to consider these helper methods. 
Let’s start with the digitName method. This method is so simple to implement that 
pseudocode is not really required. Simply use an if statement with nine branches: 
public static String digitName(int digit) 
{ 
if (digit == 1) { return "one" }; 
if (digit == 2) { return "two" }; 


} 


The teenName and tensName methods are similar. 


5.7. Problem Solving: Stepwise Refinement 221 


This concludes the process of stepwise refinement. Here is the complete program: 


section_7/IntegerName.java 


1 
2 
3 
4 
5 
6 
7 
8 


9 
10 
11 
12 


import java.util.Scanner; 


[** 


This program turns an integer into its English name. 


ay 


public class IntegerName 


{ 


public static void main(String[] args) 


{ 


} 


[** 


*/ 


Scanner in = new Scanner(System. in); 

System.out.print("Please enter a positive integer < 1000: "); 
jnt input = in.nextIntQ; 

System.out.printIn(intName(Cinput)) ; 


Turns a number into its English name. 
@param number a positive integer < 1,000 
@return the name of the number (e.g. “two hundred seventy four”) 


public static String intName(int number) 


{ 


" 


int part = number; // The part that still needs to be converted 
String name = ""; // The name of the number 


if (part >= 100) 
{ 
name 
part 


digitName(part / 100) + " hundred"; 
part % 100; 


oll 


if (part >= 20) 
{ 
name 
part 


= name + + tensName(part) ; 
= part % 10; 
else if (part >= 10) 
{ 
name 
part 
} 


name + + teenName(part) ; 
0; 


if (part > 0) 


name = name + + digitName(part) ; 


} 


return name; 


Turns a digit into its English name. 
@param digit an integer between 1 and 9 
@return the name of digit (“one”... “nine” 


222 Chapter5 Methods 


56 
57 
58 
59 
60 
61 
62 
63 
64 
65 


106 
107 } 


public static String digitName(int digit) 
{ 


if (digit == 1) { return "one"; } 
if (digit == 2) { return "two"; } 
if (digit == 3) { return "three"; } 
if (digit == 4) { return "four"; } 
if (digit == 5) { return "five"; } 
if (digit == 6) { return "six"; } 
if (digit == 7) { return "seven"; } 
if (digit == 8) { return "eight"; } 
if (digit == 9) { return "nine"; } 
return ""; 

} 

[** 


Turns a number between 10 and 19 into its English name. 
@param number an integer between 10 and 19 
@return the name of the given number (“ten” .. . “nineteen”) 
uy 
public static String teenName(int number) 


{ 


if (number == 10) { return "ten"; } 
if (number == 11) { return "eleven"; } 
if (number == 12) { return "twelve"; } 
if (number == 13) { return "thirteen"; } 
if (number == 14) { return "fourteen"; } 
if (number == 15) { return "fifteen"; } 
if (number == 16) { return "sixteen"; } 
if (number == 17) { return "seventeen"; } 
if (number == 18) { return "eighteen"; } 
if (number == 19) { return "nineteen"; } 
return ""; 

} 

[** 


Gives the name of the tens part of a number between 20 and 99. 
@param number an integer between 20 and 99 
@return the name of the tens part of the number (“twenty” .. . “ninety”) 

* 

/ 

public static String tensName(int number) 

{ 
if (number >= 90) 
if (number >= 80) 
if (number >= 70) 
if (number >= 60) 
if (number >= 50) 
if (number >= 40) 
if (number >= 30) 
if (number >= 20) 


we 


return ""s 


return "ninety"; } 
return "eighty"; } 
return "seventy"; } 
return "sixty"; } 
return "fifty"; } 
return "forty"; } 
return "thirty"; } 
return "twenty"; } 


AAA AAAS 


} 


Program Run 


Please enter a positive integer < 1000: 729 
seven hundred twenty nine 








SELF CHECK 





& 
f 
\ 


90 


Practice It 


cole le-laalaaliale mil oo yes) 






cole} e-Uaalaaiiale MA oma 


se 





5.7. Problem Solving: Stepwise Refinement 223 


26. Explain how you can improve the intName method so that it can handle argu- 
ments up to 9999. 


27. Why does line 40 set part = 0? 


28. What happens when you call intName(0)? How can you change the intName 
method to handle this case correctly? 


29. Trace the method call intName(72), as described in Programming Tip 5.4. 


30. Use the process of stepwise refinement to break down the task of printing the 
following table into simpler tasks. 


to-nn- S atatatateiatetatatatal + 
| Gf aiti*a| 
Slatted S alatetaleietetatatatal + 
| 1| 1 | 
| 2 | 8 | 
| 20 | 8000 | 
S oraiiaiee S atatatateiatetatatatal + 


Now you can try these exercises at the end of the chapter: R5.12, P5.11, P5.24. 


Keep Methods Short 


There is a certain cost for writing a method. You need to design, code, and test the method. 
The method needs to be documented. You need to spend some effort to make the method 
reusable rather than tied to a specific context. To avoid this cost, it is always tempting just to 
stuff more and more code in one place rather than going through the trouble of breaking up 
the code into separate methods. It is quite common to see inexperienced programmers pro- 
duce methods that are several hundred lines long. 

As arule of thumb, a method that is so long that its code will not fit on a single screen in 
your development environment should probably be broken up. 


Tracing Methods 


When you design a complex method, it is a good idea to carry out a manual walkthrough 
before entrusting your program to the computer. 

Take an index card, or some other piece of paper, and write down the method call that you 
want to study. Write the name of the method and the names and values of the parameter vari- 


ables, like this: 


intName(number = 416) 











Then write the names and initial values of the method variables. Write them ina table, because 
you will update them as you walk through the code. 


intName(number = 416) 
part name 








416 7 














224 Chapter5 Methods 


cele} e-laalaaliale ml il Ouse) 


We enter the test part >= 100. part / 100 is 4 and part % 100 is 16. digitName(4) is easily seen to 
be "four". (Had digitName been complicated, you would have started another sheet of paper to 
figure out that method call. It is quite common to accumulate several sheets in this way.) 

Now name has changed to name + " "+ digitName(part / 100) + " hundred", that is "four hun- 
dred", and part has changed to part % 100, or 16. 


intName(number = 416) 
part name 
~416— cue 











16 “four hundred" 











Now you enter the branch part >= 10. teenName(16) is sixteen, so the variables now have the 
values 


intName(number = 416) 
name 


~w_ 














“four hundred sixteen" 








Now it becomes clear why you need to set part to 0 in line 40. Otherwise, you would enter the 
next branch and the result would be "four hundred sixteen six". Tracing the code is an effective 
way to understand the subtle aspects of a method. 


Stubs 


When writing a larger program, it is not always 
feasible to implement and test all methods at once. 
You often need to test a method that calls another, 
but the other method hasn’t yet been imple- 
mented. Then you can temporarily replace the 
missing method with a stub. A stub is a method 
that returns a simple value that is sufficient for 
testing another method. Here are examples of 
stub methods: 





[** 
Turns a digit into its English name. 
@param digit an integer between 1 and 9 Stubs are incomplete methods that can 
Greturn the name of digit (“one”... nine” be used for testing. 
5 
public static String digitName(int digit) 
{ 
return "mumble"; 
} 
/** 


Gives the name of the tens part of a number between 20 and 99. 
@param number an integer between 20 and 99 
@return the tens name of the number (“twenty” ... “ninety”) 


WORKED EXAMPLE 5.2 Calculating a Course Grade Ss en 


: wi 
+ This Worked Example uses stepwise refinement to solve the gue is 





The scope of a 
variable is the part of 
the program in which 
it is visible. 


5.8 Variable Scope 225 


*/ 
public static String tensName(int number) 


{ 


return "mumblety"; 
} 
If you combine these stubs with the intName method and test it with an argument of 274, you 
will get a result of "mumble hundred mumblety mumble", which indicates that the basic logic of the 
intName method is working correctly. 


. . a>” ~ 
problem of converting a set of letter grades into an average poe =, 
grade for a course. +? 


As your programs get larger and contain more variables, you may encounter prob- 
lems where you cannot access a variable that is defined in a different part of your pro- 
gram, or where two variable definitions conflict with each other. In order to resolve 
these problems, you need to be familiar with the concept of variable scope. 

The scope of a variable is the part of the program in which you can access it. For 
example, the scope of a method’s parameter variable is the entire method. In the fol- 
lowing code segment, the scope of the parameter variable sideLength is the entire 
cubeVolume method but not the main method. 


public static void main(String[] args) 


{ 
System.out.println(cubeVolume(10)) ; 
} 
public static double cubeVolume(double sideLength) 
{ 
return sideLength * sideLength * sideLength; 
} 


A variable that is defined within a method is called a local variable. When a local 
variable is declared in a block, its scope ranges from its declaration until the end of 
the block. For example, in the code segment below, the scope of the square variable is 


highlighted. 


public static void main(String[] args) 


{ 
int sum = 0; 
for (int i = 1; 7 <= 10; i++) 
{ 
int square = 7i * i; 
sum = sum + Square; 
} 
System.out.print]n(sum) ; 
} 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


226 Chapter5 Methods 


The scope of a variable that is declared in a for statement extends to the end of the 
statement: 


public static void main(String[] args) 
{ 

int sum = 0; 

or Gime a = ile a <= ws We) 


{ 
} 


System.out.printIn(sum) ; 


} 


sum = sum +7 * 75 


Here is an example of a scope problem. The following code will not compile: 


public static void main(String[] args) 


{ 
double sideLength = 10; 
int result = cubeVolume(); 
System.out.printIn(result) ; 
} 
public static double cubeVolume() 
{ 
return sideLength * sideLength * sideLength; // ERROR 
} 


Note the scope of the variable sideLength. The cubeVolume method attempts to read 
the variable, but it cannot—the scope of sideLength does not extend outside the main 
method. The remedy is to pass it as an argument, as we did in Section 5.2. 

It is possible to use the same variable name more than once in a program. Consider 
the result variables in the following example: 


public static void main(String[] args) 


{ 
int result = square(3) + square(4); 
System.out.printIn(result) ; 
} 
public static int square(int n) 
{ 
int result =n * n; 
return result; 
} 





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. 


5.8 Variable Scope 227 


Sens ee Each result variable is declared in a separate method, and their scopes do not overlap. 
parameter variables You can even have two variables with the same name in the same method, provided 


can have the same that their scopes do not overlap: 
name, provided that 
their scopes do 
not overlap. public static void main(String[] args) 
{ 
int sum = 0; 
for (int i = 1; i <= 10; i++) 


{ 
sum = sum + 7; 
} 
for (int i = 1; i <= 10; i++) 
{ 
sum = sum +7 * 75 
} 


System.out.print]n(sum) ; 


It is not legal to declare two variables with the same name in the same method in such 
a way that their scopes overlap. For example, the following is not legal: 


public static int sumOfSquares(int n) 


{ 
int sum = 0; 
for (int 1 = 1; 7 <= n; i++) 
{ 
int n=i1%* i; // ERROR 
sum = sum + n; 
} 
return sum; 
} 


The scope of the local variable n is contained within the scope of the parameter vari- 
able n. In this case, you need to rename one of the variables. 


Consider this sample program: 





1 public class Sample 
2 
3 public static void main(String[] args) 
4 { 
5 int x = 4; 
6 x = mystery(x + 1); 
7 System.out.printIn(s) ; 
8 } 
9 
10 public static int mystery(int x) 
11 { 
12 ints =0; 
13 for (int i = 0; i < x; Xx++) 
14 { 
15 intx=i+4+1; 


16 S=S +X} 


228 Chapter5 Methods 


17 
18 
19 
20 


31. 
32. 
33. 


34. 
35. 


} 


return s; 
i 
t 


Which lines are in the scope of the variable i declared in line 13? 
Which lines are in the scope of the parameter variable x declared in line 10? 


The program declares two local variables with the same name whose scopes 
don’t overlap. What are they? 


There is a scope error in the mystery method. How do you fix it? 
There is a scope error in the main method. What is it, and how do you fix it? 


Practice It Now youcantry these exercises at the end of the chapter: R5.9, R5.10. 


VIDEO EXAMPLE 5.1 Debugging =e wees Serre 


Toe In this Video Example, you will learn how to use a debugger to find + spc 
L U S errors In a program. cae cam 
Ph a: 
worapmats! 


A recursive method is a method that calls itself. This is not as unusual as it sounds at 
first. Suppose you face the arduous task of cleaning up an entire house. You may well 
say to yourself, “I'll pick a room and clean it, and then Ill clean the other rooms.” In 
other words, the cleanup task calls itself, but with a simpler input. Eventually, all the 
rooms will be cleaned. 


Cleaning up a house can be solved recursively: 
Clean one room, then clean up the rest. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


A recursive 
computation solves 
a problem by using 
the solution of the 
same problem with 
simpler inputs. 


For a recursion to 
terminate, there must 
be special cases for 
the simplest inputs. 


5.9 Recursive Methods (Optional) 229 


In Java, a recursive method uses the same principle. Here is a typical example. We 
want to print triangle patterns like this: 

[] 

QC] 


CCC] 
CCCI 0) 


Specifically, our task is to provide a method 
public static void printTriangle(int sideLength) 


The triangle given above is printed by calling printTriangle(4). To see how recursion 
helps, consider how a triangle with side length 4 can be obtained from a triangle with 
side length 3. 

[] 

[IC] 

[ICC] 

[ICICICI 

Print the triangle with side length 3. 

Print a line with four [). 


More generally, here are the Java instructions for an arbitrary side length: 


public static void printTriangle(int sideLength) 


{ 
printTriangle(sideLength - 1); 
for (int i = 0; i < sideLength; i++) 
{ 
System.out.print("[]"); 
} 
System.out.printInQ; 
} 


There is just one problem with this idea. When the side length is 1, we don’t want to 
call printTriangle(0), printTriangle(-1), and so on. The solution is simply to treat this 
as a special case, and not to print anything when sideLength is less than 1. 


public static void printTriangle(int sideLength) 


{ 
if (sideLength < 1) { return; } 
printTriangle(sideLength - 1); 
for (int i = 0; i < sideLength; i++) 
{ 
System.out.print("[]"); 
} 
System.out.printInQ; 
} 


Look at the printTriangle method one more time and notice how utterly reasonable it 
is. If the side length is 0, nothing needs to be printed. The next part is just as reason- 
able. Print the smaller triangle and don’t think about why that works. Then print a 
row of []. Clearly, the result is a triangle of the desired size. 

There are two key requirements to make sure that the recursion is successful: 


e Every recursive call must simplify the task in some way. 
e There must be special cases to handle the simplest tasks directly. 


The printTriangle method calls itself again with smaller and smaller side lengths. 
Eventually the side length must reach 0, and the method stops calling itself. 


230 Chapter5 Methods 


This set of Russian dolls looks similar to the 
call pattern of a recursive method. 





Here is what happens when we print a triangle with side length 4: 


e The call printTriangle(4) calls printTriangle(3). 
e The call printTriangle(3) calls printTriangle(2). 
e The call printTriangle(2) calls printTriangle(1). 
e The call printTriangle(1) calls printTriangle(0). 
¢ The call printTriangle(0) returns, doing nothing. 
e The call printTriangle(1) prints []. 
e The call printTriangle(2) prints [][]. 
¢ The call printTriangle(3) prints [][1[). 
¢ The call printTriangle(4) prints [](] (1 (0. 





ry 

ANIMATION 

Tracing a Recursion 

\ The call pattern of a recursive method looks complicated, and the key to the success- 
ful design of a recursive method is not to think about it. 

Recursion is not really necessary to print triangle shapes. You can use nested loops, 


like this: 
public static void printTriangle(int sideLength) 
{ 
for (int i = 0; i < sideLength; i++) 
{ 
for (int j = 0; j < i; j++) 
{ 
System.out.print("[]"); 
} 
System.out.printInQ; 
3 
+) The complete 3 
TrianglePrinter 


However, this pair of loops is a bit tricky. Many people find the recursive solution 
simpler to understand. 


program. 


36. Consider this slight modification of the printTriangle method: 
public static void printTriangle(int sideLength) 


{ 
if (sideLength < 1) { return; } 
for (int i = 0; i < sideLength; i++) 


{ 





System.out.print("[]"); 


5.9 Recursive Methods (Optional) 231 


} 

System.out.printInQ; 

printTriangle(sideLength - 1); 
} 


What is the result of printTriangle(4) ? 
37. Consider this recursive method: 
public static int mystery(int n) 


; if (n <= 0) { return 0; } 
return n + mystery(n - 1); 
} 
What is mystery(4)? 
38. Consider this recursive method: 
public static int mystery(int n) 


{ 
if (n <= 0) { return 0; } 
return mystery(n / 2) + 1; 


} 
What is mystery (20)? 
39. Write a recursive method for printing n box shapes [] ina row. 


40. The intName method in Section 5.7 accepted arguments < 1,000. Using a recursive 
call, extend its range to 999,999. For example an input of 12,345 should return 
"twelve thousand three hundred forty five". 


Practice It Now youcantry these exercises at the end of the chapter: R5.16, P5.16, P5.18. 






HOW TO 5.2 Thinking Recursively 


To solve a problem recursively requires a different mindset than to solve it by programming 
loops. In fact, it helps if you are, or pretend to be, a bit lazy and let others do most of the work 
for you. If you need to solve a complex problem, pretend that “someone else” will do most 
of the heavy lifting and solve the problem for all simpler inputs. Then you only need to figure 
out how you can turn the solutions with simpler inputs into a solution for the whole problem. 

To illustrate the recursive thinking process, consider the problem of Section 4.2, computing 
the sum of the digits of a number. We want to design a method digitSum that computes the sum 
of the digits of an integer n. 

For example, digitSum(1729) =1+7+2+9=19 


Step 1 Break the input into parts that can themselves be inputs to the problem. 


In your mind, focus ona particular input or set of inputs for the task aan 
that you want to solve, and think how you can simplify the inputs. he key to fining’ 
‘ . . recursive solution is 

Look for simplifications that can be solved by the same task, and seducing the input to 
whose solutions are related to the original task. a simpler input for 

In the digit sum problem, consider how we can simplify an the same problem. 
input such as n = 1729. Would it help to subtract 1? After all, 
digitSum(1729) = digitSum(1728) + 1. But consider n = 1000. There seems to be no obvious rela- 
tionship between digitSum(1000) and digitSum(999). 

A much more promising idea is to remove the last digit, that is, to compute n / 10 = 172. The 
digit sum of 172 is directly related to the digit sum of 1729. 


232 Chapter5 Methods 


Step 2 Combine solutions with simpler inputs into a solution of the original problem. 
In your mind, consider the solutions for the simpler inputs that you have discovered in Step 1. 
Don’t worry how those solutions are obtained. Simply have faith that the solutions are readily 
available. Just say to yourself: These are simpler inputs, so someone else will solve the problem 
for me. 

In the case of the digit sum task, ask yourself how you can obtain wre, designing a 
digitSum(1729) if you know digitSum(172). You simply add the last recursive solution, 
digit (9) and you are done. How do you get the last digit? As the — do not worry about 
remainder n % 10. The value digitSum(n) can therefore be obtained as multiple nested calls. 

ca Simply focus on 
digitSum(n / 10) +n % 10 reducing a problem 
Don’t worry how digitSum(n / 10) is computed. The input is smaller, '°? stanly 
3 simpler one. 
and therefore it works. 
Step 3 Find solutions to the simplest inputs. 


A recursive computation keeps simplifying its inputs. To make sure that the recursion comes 
to a stop, you must deal with the simplest inputs separately. Come up with special solutions 
for them. That is usually very easy. 


Look at the simplest inputs for the digitSum problem: 


e Anumber witha single digit 


e 0 


In 1971, Marcian E. 
“Ted” Hoff, an engineer 
at Intel Corporation, 
was working on a chip for a manufac- 
turer of electronic calculators. He real- 
ized that it would be a better idea to 
develop a general-purpose chip that 
could be programmed to interface with 
the keys and display of a calculator, 
rather than to do yet another custom 
design. Thus, the microprocessor was 
born. At the time, its primary applica- 
tion was as acontroller for calculators, 
washing machines, and the like. It took 
years for the computer industry to 
notice that a genuine central process- 
ing unit was now available as a single 
chip. 

Hobbyists were the first to catch 
on. In 1974 the first computer kit, the 
Altair 8800, was available from MITS 
Electronics for about $350. The kit 
consisted of the microprocessor, a Cir- 
cuit board, a very small amount of 
memory, toggle switches, and a row of 
display lights. Purchasers had to sol- 
der and assemble it, then program it in 
machine language through the toggle 
switches. It was nota big hit. 





The first big hit was the Apple II. It 
was a real computer with a keyboard, 
a monitor, and a floppy disk drive. 
When it was first released, users had a 
$3,000 machine that could play Space 
Invaders, run a primitive bookkeep- 
ing program, or let users program it 
in BASIC. The original Apple II did not 
even support lowercase letters, mak- 
ing it worthless for word processing. 
The breakthrough came in 1979 with 
a new spreadsheet program, VisiCalc. 
In a spreadsheet, you enter financial 
data and their relationships into a grid 
of rows and columns (see the figure at 
right). Then you modify some of the 
data and watch in real time how the 
others change. For example, you can 
see how changing the mix of widgets 
in a manufacturing plant might affect 
estimated costs and profits. Middle 
managers in companies, who under- 
stood computers and were fed up with 
having to wait for hours or days to get 
their data runs back from the comput- 
ing center, snapped up VisiCalc and the 
computer that was needed to run it. 
For them, the computer was a spread- 
sheet machine. 


Random Fact 5.1 The Explosive Growth of Personal Computers 


The next big hit was the IBM Per- 
sonal Computer, ever after known as 
the PC. It was the first widely available 
personal computer that used Intel’s 
16-bit processor, the 8086, whose 
successors are still being used in per- 
sonal computers today. The success 
of the PC was based not on any engi- 
neering breakthroughs but on the fact 
that it was easy to clone. IBM published 
the computer's specifications in order 
to encourage third parties to develop 
plug-in cards. Perhaps IBM did not 
foresee that functionally equivalent 
versions of their computer could be 
recreated by others, but a variety of 
PC clone vendors emerged, and ulti- 
mately IBM stopped selling personal 
computers. 

IBM never produced an operating 
system for its PCs—that is, the soft- 
ware that organizes the interaction 
between the user and the computer, 
starts application programs, and man- 
ages disk storage and other resources. 
Instead, IBM offered customers the 
option of three separate operating 
systems. Most customers couldn't 
care less about the operating system. 


ONLINE EXAMPLE t 


5.9 Recursive Methods (Optional) 


233 


A number with a single digit is its own digit sum, so you can stop the recursion when n < 10, 
and return nin that case. Or, you can be even lazier. If n has a single digit, then digitSum(n / 10) 
+n % 10 equals digitSum(0) + n. You can simply terminate the recursion when nis zero. 


Step 4 


Implement the solution by combining the simple cases and the reduction step. 


Now you are ready to implement the solution. Make separate cases for the simple inputs that 
you considered in Step 3. If the input isn’t one of the simplest cases, then implement the logic 
you discovered in Step 2. 

Here is the complete digitSum method: 


public static int digitSum(int n) 


if (n == 
A program 

illustrating the } 
digitSum method. 





They chose the system that was able 
to launch most of the few applications 
that existed at the time. It happened 
to be DOS (Disk Operating System) by 






A VISICALC™ screen: 


Entry Type V tor 
fos laa. foe re 





Epics Foemat nacaton 


Entry Contents Line 


Prompt Line 


Eon un 
means 


Row and Column label's 


Dotlars and Cones Format 


Labet Entry 


Tao andoas wren the 
screens spa 


VIDEO EXAMPLE 5.2 Fully Justified Text 


In printed books (such as this one), all but the last line of a | 
paragraph have the same length. In this Video Example, | 
you will see how to achieve this effect. 


Microsoft. Microsoft licensed the same 
Operating system to other hardware 
vendors and encouraged software 
companies to write DOS applications. 


dew 


Left Jusntes Format 
vr 


Genera Format (FG) 


Repeanng Laber «> 


Megs suandnn Format 


integer Format (#1 Vaive Entry 


The Visicalc Spreadsheet Running on an Apple II 


0) { return 0; } // Special case for terminating the recursion 
return digitSum(n / 10) + n % 10; // General case 


A huge number of useful application 
programs for PC-compatible machines 
was the result. 

PC applications were certainly use- 
ful, but they were not easy to learn. 
Every vendor developed a different 
user interface: the collection of key- 
strokes, menu options, and settings 
that a user needed to master to use 
a software package effectively. Data 
exchange between applications was 
difficult, because each program used a 
different data format. The Apple Mac- 
intosh changed all that in 1984. The 
designers of the Macintosh had the 
vision to supply an intuitive user inter- 
face with the computer and to force 
software developers to adhere to it. 
It took Microsoft and PC-compatible 
manufacturers years to catch up. 

Most personal computers are used 
for accessing information from online 
sources, entertainment, word process- 
ing, and home finance. Some analysts 
predict that the personal computer will 
merge with the television set and cable 
network into an entertainment and 
information appliance. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


234 Chapter5 Methods 


Understand the concepts of methods, arguments, and return values. 


e A method is a named sequence of instructions. 
e Arguments are supplied when a method is called. 
¢ The return value is the result that the method computes. 





Be able to implement methods. 
¢ When declaring a method, you provide a name for the method, a variable for each 
argument, and a type for the result. 


% ¢ Method comments explain the purpose of the method, the meaning of the param- 
eter variables and return value, as well as any special requirements. 





Describe the process of parameter passing. 
e Parameter variables hold the arguments 
supplied in the method call. @D 
pielfruit) pie(fruit) 


@ © 


¢ The return statement terminates a method call and yields the 
method result. 


Describe the process of returning a value from a method. 





¢ Turn computations that can be reused into methods. 


Design and implement methods without return values. 


ee 


Develop methods that can be reused for multiple problems. 


e Use a return type of void to indicate that a method does not return a value. 


e Eliminate replicated code or pseudocode by defining a method. 


¢ Design your methods to be reusable. Supply parameter variables for the values 
that can vary when the method is reused. 


Apply the design principle of stepwise refinement. 


¢ Use the process of stepwise refinement to decompose complex tasks into 
simpler ones. 


¢ When you discover that you need a method, write a description of the parameter 
variables and return values. 





e¢ A method may require simpler methods to carry out its work. 


Review Exercises 235 


Determine the scope of variables in a program. 


¢ The scope of a variable is the part of the program in which it is 
visible. 

¢ Two local or parameter variables can have the same name, 
provided that their scopes do not overlap. 





Understand recursive method calls and implement simple recursive methods. 


e A recursive computation solves a problem by using the solution of the same 
problem with simpler inputs. 


¢ Fora recursion to terminate, there must be special cases for the simplest inputs. 


¢ The key to finding a recursive solution is reducing the input to a simpler input for 
the same problem. 





¢ When designing a recursive solution, do not worry about multiple nested calls. 
Simply focus on reducing a problem to a slightly simpler one. 


# R5.1 In which sequence are the lines of the Cubes. java program in Section 5.2 executed, 
starting with the first line of main? 
# R5.2 Write method headers for methods with the following descriptions. 
a. Computing the larger of two integers 
b. Computing the smallest of three floating-point numbers 


c. Checking whether an integer is a prime number, returning true if it is and 
false otherwise 


d. Checking whether a string is contained inside another string 


e. Computing the balance of an account with a given initial balance, an annual 
interest rate, and a number of years of earning interest 


f. Printing the balance of an account with a given initial balance and an annual 
interest rate over a given number of years 


g. Printing the calendar for a given month and year 


h. Computing the weekday for a given day, month, and year (as a string such 
as "Monday") 


i. Generating a random integer between 1 and 


» R5.3 Give examples of the following methods from the Java library. 
a. A method with a double argument and a double return value 
b. A method with two double arguments and a double return value 
c. A method with a String argument and a double return value 


d. A method with no arguments and a double return value 


# R5.4 True or false? 
a. A method has exactly one return statement. 


b. A method has at least one return statement. 


236 Chapter5 Methods 


c. A method has at most one return value. 

d. A method with return value void never has a return statement. 

e. When executing a return statement, the method exits immediately. 

f. A method with return value void must print a result. 

g. A method without parameter variables always returns the same value. 


##R5.5 Consider these methods: 
public static double f(double x) { return g(x) + Math.sqrt(h(x)); } 
public static double g(double x) { return 4 * h(x); } 
public static double h(double x) { return x * x + k(x) - 1; } 
public static double k(double x) { return 2 * (x +1); } 
Without actually compiling and running a program, determine the results of the 
following method calls. 
F(2)5 
g(h(2)); 
k(g@2) + h(2)); 
F(0) + (1) + F(2); 
F(-1) + g(-1) + hC-1) + k(-1); 


a. double x1 
b. double x2 
c. double x3 
d. double x4 
e. double x5 


# R5.6 What is the difference between an argument and a return value? How many argu- 
ments can a method call have? How many return values? 


##R5.7 Designa method that prints a floating-point number as a currency value (witha $ 
sign and two decimal digits). 


a. Indicate how the programs ch02/section_3/Volume2. java and ch04/section_3/ 
InvestmentTable. java should change to use your method. 


b. What change is required if the programs should show a different currency, such 
as euro? 


«= Business R5.8 Write pseudocode for a method that translates a telephone number with letters in it 
(such as 1-800-FLOWERS) into the actual phone number. Use the standard letters 


ona phone pad. 








##R5.9 Describe the scope error in the following program and explain how to fix it. 


public class Conversation 


{ 


public static void main(String[] args) 


{ 


Scanner in = new Scanner(System. in); 


Review Exercises 237 


System.out.printC"What is your first name? "); 
String input = in.nextQ); 
System.out.printIn("Hello, " + input); 
System.out.print("How old are you? "); 

jnt input = in.nextIntQ; 

jnput++; 

System.out.printIn("Next year, you will be 


} 


+ input); 


} 


##R5.10 For each of the variables in the following program, indicate the scope. Then deter- 
mine what the program prints, without actually running the program. 


1 public class Sample 
2f{ 
3 public static void main(String[] args) 
4 { 
5 int i = 10; 
6 int b = g(i); 
7 System.out.printIn(b + i); 
8 } 
9 
10 public static int f(int 7) 
11 { 
12 int n=0; 
13 while (n * n <= 71) { n++; } 
14 return n - 1; 
15 } 
16 
17 public static int g(int a) 
18 { 
19 int b = 0; 
20 for (int n = 0; n < a; n++) 
21 { 
22 int i = f(n); 
23 b=b+ i; 
24 } 
25 return b; 
26 } 
27 +} 


##R5.11 Use the process of stepwise refinement to describe the process of making scrambled 
eggs. Discuss what you do if you do not find eggs in the refrigerator. 


# R5.12 Performa walkthrough of the intName method with the following arguments: 
a.5 
b. 12 
c. 21 
d. 301 
e. 324 
f. 0 


g. -2 
##R5.13 Consider the following method: 


public static int f(int a) 


if (a < 0) { return -1; } 
int n=a; 


238 Chapter5 Methods 


while (n > 0) 


{ 
if (n % 2 == 0) // n is even 
{ 
n=n/2; 
} 
else if (n == 1) { return 1; } 
else {n=3* n+4+1; } 
} 
return 0; 


} 
Perform traces of the computations f(-1), f(0), f(1), f(2), £(10), and f(100). 


###R5.14 Consider the following method that is intended to swap the values of two integers: 


public static void falseSwap(int a, int b) 
{ 

int temp = a; 

a=b; 

b = temp; 
} 


public static void main(String[] args) 
{ 
int x = 3; 
int y = 4; 
falseSwap(x, y); 
System.out.printIn(x + 


+ y)3 
} 


Why doesn’t the falseSwap method swap the contents of x and y? 


na2R5.15 Give pseudocode fora recursive method for printing all substrings of a given string. 
For example, the substrings of the string "rum" are "rum" itself, "ru", "um", "r", "u" 


"m", and the empty string. You may assume that all letters of the string are different. 


na R5.16 Give pseudocode fora recursive method that sorts all letters in a string. For example, 
the string "goodbye" would be sorted into "bdegooy". 


» P5.1 Write the following methods and provide a program to test them. 


a. double smallest(double x, double y, double z), returning the smallest of the 
arguments 


b. double average(double x, double y, double z), returning the average of the 
arguments 
n# P5.2 Write the following methods and provide a program to test them. 


a. boolean al1TheSame(double x, double y, double z), returning true if the arguments 
are all the same 


b. boolean allDifferent(double x, double y, double z), returning true if the argu- 
ments are all different 


c. boolean sorted(double x, double y, double z), returning true if the arguments are 
sorted, with the smallest one coming first 


aa P5,3 


= P5.4 


=o P5.5 


ua P5.6 


an P5.7 


ua P58 


=o P5.9 


Programming Exercises 239 


Write the following methods. 

a. int firstDigit(int n), returning the first digit of the argument 

b. int lastDigit(int n), returning the last digit of the argument 

c. int digits(int n), returning the number of digits of the argument 
For example, firstDigit(1729) is 1, lastDigit (1729) is 9, and digits (1729) is 4. Provide a 
program that tests your methods. 
Write a method 

public static String middle(String str) 
that returns a string containing the middle character in str if the length of str is odd, 
or the two middle characters if the length is even. For example, middle("middle") 
returns "dd". 
Write a method 

public static String repeat(String str, int n) 
that returns the string str repeated n times. For example, repeat ("ho", 3) returns 
"hohoho". 
Write a method 

public static int countVowels(String str) 
that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and 
u, and their uppercase variants. 
Write a method 

public static int countWords(String str) 
that returns a count of all words in the string str. Words are separated by spaces. For 
example, countWords("Mary had a little lamb") should return 5. 


It is a well-known phenomenon that most people are easily able to read a text whose 
words have two characters flipped, provided the first and last letter of each word are 
not changed. For example, 


I dn’ot gvie a dman for a man taht can olny sepll a wrod one way. (Mrak Taiwn) 


Write a method String scramble(String word) that constructs a scrambled version of a 
given word, randomly flipping two characters other than the first and last one. Then 
write a program that reads words and prints the scrambled words. 
Write methods 

public static double sphereVolume(double r) 

public static double sphereSurface(double r) 

public static double cylinderVolume(double r, double h) 

public static double cylinderSurface(double r, double h) 

public static double coneVolume(double r, double h) 

public static double coneSurface(double r, double h) 
that compute the volume and surface area of a sphere with radius r, a cylinder witha 
circular base with radius r and height h, and a cone with a circular base with radius r 


and height h. Then write a program that prompts the user for the values of r and h, 
calls the six methods, and prints the results. 


240 Chapter5 Methods 


ua P5,.10 


ue P5,11 
oa P5,12 


ane P5.13 


ooe P5.14 


oe P5.15 


ue P5.16 


ue P5,17 


o P5.18 


o P5.19 





Write a method 
public static double readDouble(String prompt) 


that displays the prompt string, followed by a space, reads a floating-point number 
in, and returns it. Here is a typical usage: 


salary = readDouble("Please enter your salary:"); 
percentageRaise = readDouble("What percentage raise would you like?"); 


Enhance the intName method so that it works correctly for values < 1,000,000,000. 


Enhance the intName method so that it works correctly for negative values and zero. 
Caution: Make sure the improved method doesn’t print 20 as "twenty zero". 


For some values (for example, 20), the intName method returns a string with a lead- 
ing space (" twenty"). Repair that blemish and ensure that spaces are inserted only 
when necessary. Hint: There are two ways of accomplishing this. Either ensure that 
leading spaces are never inserted, or remove leading spaces from the result before 
returning it. 


Write a method String getTimeName(int hours, int minutes) that returns the English 
name for a point in time, such as "ten minutes past two", "half past three", "a quarter to 
four", or "five o'clock". Assume that hours is between 1 and 12. 
Write a recursive method 

public static String reverse(String str) 


that computes the reverse of a string. For example, reverse("flow") should return 
"wolf". Hint: Reverse the substring starting at the second character, then add the first 
character at the end. For example, to reverse "flow", first reverse "low" to "wol", then 


add the "f" at the end. 
Write a recursive method 
public static boolean isPalindrome(String str) 


that returns true if str is a palindrome, that is, a word that is the same when reversed. 
Examples of palindrome are “deed”, “rotor”, or “aibohphobia”. Hint: A word is a 
palindrome if the first and last letters match and the remainder is also a palindrome. 


Use recursion to implement a method public static boolean find(String str, String 
match) that tests whether match is contained in str: 

boolean b = find("Mississippi", "sip"); // Sets b to true 
Hint: If str starts with match, then you are done. If not, consider the string that you 
obtain by removing the first character. 


Use recursion to determine the number of digits in an integer n. Hint: If nis < 10, it 
has one digit. Otherwise, it has one more digit than n / 10. 


Use recursion to compute a”, where nis a positive integer. Flint: If 7 is 1, then 
a” =a. If nis even, then a” =(a" /2)2 Otherwise, a” =a x a” 
Leap years. Write a method 

public static boolean isLeapYear(int year) 


that tests whether a year is a leap year: that is, a year with 366 days. Exercise P3.28 
describes how to test whether a year is a leap year. In this exercise, use multiple if 
statements and return statements to return the result as soon as you know it. 


oe P5,21 


a= Business P5.22 


== Business P5.23 


== Business P5.24 


== Business P5.25 


Programming Exercises 241 


In Exercise P3.26 you were asked to write a program to 
convert a number to its representation in Roman numerals. 
At the time, you did not know how to eliminate duplicate 
code, and as a consequence the resulting program was rather 
long. Rewrite that program by implementing and using the 
following method: 





public static String romanDigit(int n, String one, String five, String ten) 


That method translates one digit, using the strings specified for the one, five, and ten 
values. You would call the method as follows: 
romanOnes = romanDigit(n % 10, “I”, “V”, “X”); 


n=n/ 10; 
romanTens = romanDigit(n % 10, “X”, “L”, “C”); 


Write a method that computes the balance of a bank account with a given initial 
balance and interest rate, after a given number of years. Assume interest is com- 
pounded yearly. 


Write a program that prints instructions to get coffee, asking the user for input 
whenever a decision needs to be made. Decompose each task into a method, for 
example: 


public static void brewCoffee() 


{ 
System.out.printIn(“Add water to the coffee maker.”); 
System.out.printIn(“Put a filter in the coffee maker.”); 
grindCoffee() ; 
System.out.printIn(“Put the coffee in the filter.”); 

} 


Write a program that prints a paycheck. Ask the program user for the name of the 
employee, the hourly rate, and the number of hours worked. If the number of hours 
exceeds 40, the employee is paid “time and a half”, that is, 150 percent of the hourly 
rate on the hours exceeding 40. Your check should look similar to that in the fig- 

ure below. Use fictitious names for the payer and the bank. Be sure to use stepwise 
refinement and break your solution into several methods. Use the intName method to 
print the dollar amount of the check. 











W See Cee Publishers’ Bank Minnesota CHECK 74-39 
111 River Street HES 
| LEY Hoboken, NJ 07030-5774 2000 Prince Blvd NUMBER 06333 311 567390 
Jonesville, MN 55400 
Date Amount 


4659484 04/29/13 | $xxx****274.15 


TWO HUNDRED SEVENTY FOUR AND 15 / 100 ¥X®XX# HA KKK IK AK ARK KIKI RK IK IK IIR IKK KIA AIK 
TO THE ORDER OF: 

JOHN DOE 

1009 Franklin Blvd 

Sunnyvale, CA 95014 


WO?HdOH CLOW fFOOB20975r 140k 











Postal bar codes. For faster sorting of letters, the United States Postal Service encour- 
ages companies that send large volumes of mail to use a bar code denoting the zip 
code (see Figure 6). 


242 Chapter5 Methods 


KKKKKKKKKKKKKKK ECRLOT ** CO57 


CODE C671RTS2 

JOHN DOE CO57 
1009 FRANKLIN BLVD 

SUNNYVALE CA 95014 — 5143 


WaVassUabaDDocorsaldaDradalalosollaboctrtdelastl 

Figure6 A Postal Bar Code 
The encoding scheme for a five-digit zip code is shown in Figure 7. There are 
full-height frame bars on each side. The five encoded digits are followed by a check 
digit, which is computed as follows: Add up all digits, and choose the check digit to 


make the sum a multiple of 10. For example, the zip code 95014 has a sum of 19, so 
the check digit is 1 to make the sum equal to 20. 


Frame bars 


Digit 1 Digit2 Digit3 Digit 4 Digit5 Check 
Digit 





Figure 7 Encoding for Five-Digit Bar Codes 


Each digit of the zip code, and the check digit, is encoded according to the table 
below, where 1 denotes a full bar and 0 a half bar: 


Digit Bar ] Bar 2 Bar 3 Bar 4 Bar 5 
(weight 7) (weight 4) (weight 2) (weight1) (weight 0) 

1 0 0 0 il 1 
2 0 0 1 0 1 
3 0 0 1 il 0 
4 0 1 0 0 1 
5 0 1 0 1 0 
6 0 1 1 0 0 
7 1 0 0 0 1 

1 0 0 1 0 
9 1 0 1 0 0 
0 1 1 0 0 0 


The digit can be easily computed from the bar code using the column weights 7, 4, 2, 
1, 0. For example, 01100 isOx7+1x4+1x2+0x1+0x0=6. The only exception 
is 0, which would yield 11 according to the weight formula. 


aaa Business P5.26 


== Business P5.27 


== Business P5.28 


aaa Business P5.29 


Programming Exercises 243 


Write a program that asks the user for a zip code and prints the bar code. Use : for 
half bars, | for full bars. For example, 95014 becomes 


Wisse ee [eres | Peel ere || 
Provide these methods: 


public static void printDigit(Cint d) 
public static void printBarCode(int zipCode) 


Write a program that reads in a bar code (with : denoting half bars and | denoting 
full bars) and prints out the zip code it represents. Print an error message if the bar 
code is not correct. 


Write a program that converts a Roman number such as MCMLX XVIII to its deci- 
mal number representation. Hint: First write a method that yields the numeric value 
of each of the letters. Then use the following algorithm: 


total = 0 
While the roman number string is not empty 
If value(first character) is at least value(second character), or the string has length 1 
Add value(first character) to total. 
Remove the character. 
Else 
Add the difference value(second character) - value(first character) to total. 
Remove both characters. 


A non-governmental organization needs a program to calculate the amount of finan- 
cial assistance for needy families. The formula is as follows: 


e Ifthe annual household income is between $30,000 and $40,000 and the 
household has at least three children, the amount is $1,000 per child. 


e Ifthe annual household income is between $20,000 and $30,000 and the 
household has at least two children, the amount is $1,500 per child. 


e Ifthe annual household income is less than $20,000, the amount is $2,000 per 
child. 


Implement a method for this computation. Write a program that asks for the house- 
hold income and number of children for each applicant, printing the amount 
returned by your method. Use -1 as a sentinel value for the input. 


Ina social networking service, a user has friends, the 
friends have other friends, and so on. We are interested 
in knowing how many people can be reached from a 
person by following a given number of friendship rela- 
tions. This number is called the “degree of separation”: 
one for friends, two for friends of friends, and so on. 
Because we do not have the data from an actual social 
network, we will simply use an average of the number of friends per user. 





Write a recursive method 
public static double reachablePeople(int degree, double averageFriendsPerUser) 


Use that method in a program that prompts the user for the desired degree and 
average, and then prints the number of reachable people. This number should 
include the original user. 


244 Chapter5 Methods 


«= Business P5.30 Having a secure password is a very important practice, when much of our informa- 


aan Science P5.31 


aa Science P5.32 


tion is stored online. Write a program that validates a new password, following these 
rules: 


¢ The password must be at least 8 characters long. 
e The password must have at least one uppercase and one lowercase letter 
e The password must have at least one digit. 


Write a program that asks for a password, then asks again to confirm it. If the 
passwords don’t match or the rules are not fulfilled, prompt again. Your program 
should include a method that checks whether a password is valid. 


You are designing an element for a control panel that displays a temperature value 
between 0 and 100. The element’s color should vary continuously from blue (when 
the temperature is 0) to red (when the temperature is 100). Write a method public 
static int colorForValue(double temperature) that returns a color value for the given 
temperature. Colors are encoded as red/green/blue values, each between 0 and 255. 
The three colors are combined into a single integer, using the formula 


color = 65536 x red + 256 x green + blue 


Each of the intermediate colors should be fully saturated; that is, it should be on the 
outside of the color cube, along the path that goes from blue through cyan, green, 
and yellow to red. 





You need to know how to mterpolate between values. In general, if an output y 
should vary from cto d as an input x varies from a to J, then y is computed as follows: 


z=(x-a)/(b-a) 
y=dz+c(1-z) 


If the temperature is between 0 and 25 degrees, interpolate between blue and cyan, 
whose (red, green, blue) components are (0, 0, 255) and (0, 255, 255). For temperature 
values between 25 and 50, interpolate Beereon (0, 255,255) and (0, 255, 0), which rep- 
resents the color green. Do the same for the remaining two path segments. 

You need to interpolate each color component separately and then combine the 
interpolated colors to a single integer. 

Be sure to use appropriate helper methods to solve your task. 


In a movie theater, the angle 6 at which a viewer sees the picture on the screen 
depends on the distance x of the viewer from the screen. For a movie theater with the 
dimensions shown in the picture below, write a method that computes the angle for a 
given distance. 


n= Science P5.33 The effective focal length fof a lens of thickness d 


Programming Exercises 245 








Next, provide a more general method that works for theaters with arbitrary 
dimensions. 


that has surfaces with radii of curvature R, and Ry 


is given by 
1, 1 1 (n-1)d 
oe iz R, RR, | 





where 7 is the refractive index of the lens medium. 
Write a method that computes fin terms of the other 
parameters. 








= Science P5.34 A laboratory container is shaped like the frustum of a cone: 











Write methods to compute the volume and surface area, using these equations: 


V = 1h(R? + RF + R,R,) 


S =n(R,+R,)\(R,-R,) +h? + aR? 


= Science P5.35 Electric wire, like that in the photo, is a cylindrical conductor covered by an insulat- 





ing material. The resistance of a piece of wire is given by the formula 
pee aca! 
A nd? 


where p is the resistivity of the conductor, and L, A, and d are the length, cross- 
sectional area, and diameter of the wire. The resistivity of copper is 1.678 x 107° Q m. 


246 Chapter5 Methods 


aa Science P5.36 


The wire diameter, d, is commonly specified by the American wire gauge (AWG), 
which is an integer, 7. The diameter of an AWG 71 wire is given by the formula 
36—-n 
d =0.127 x92 39 mm 





Write a method 
public static double diameter(int wireGauge) 


that accepts the wire gauge and returns the corresponding wire diameter. Write 
another method 


public static double copperWireResistance(double length, int wireGauge) 


that accepts the length and gauge of a piece of copper wire and returns the resistance 
of that wire. The resistivity of aluminum is 2.82 x 107° Q m. Write a third method 


public static double aluminumWireResistance(double length, int wireGauge) 


that accepts the length and gauge of a piece of aluminum wire and returns the 
resistance of that wire. 


Write a program to test these methods. 


The drag force ona car is given by 


where pis the density of air (1.23 kg/m?), v is the velocity in units of m/s, A is the 
projected area of the car (2.5 m*), and Cp is the drag coefficient (0.2). 


The amount of power in watts required to overcome such drag force is P = Fpv, and 
the equivalent horsepower required is Hp = P/ 746. Write a program that accepts a 
car’s velocity and computes the power in watts and in horsepower needed to over- 
come the resulting drag force. Note: 1 mph = 0.447 m/s. 


ANS WiERSmOn Sie EGE Gl l@lUi Saal @iNis 


1. 


- 


ee P 


The arguments are 3 and 2. The return value 9. (2+3)/@G-2)=5 

1s 9. 10. When the mystery method is called, x is set to 

The inner call to Math. pow returns 27 = 4. There- 5, y 1s set to 7, and z becomes 12.0. Then z is 

fore, the outer call returns 4? = 16. changed to 6.0, and that value is returned and 

3.0 printed. 

Users of the method can treat itasa black box. "1: When the method is called, ss is set to 5. Then 

7 y is set to 25, and that value is returned and 
printed. 

8x8x8=512 


double volume = Math.pow(sideLength, 3); 


return volume; 


public static double squareArea( 13 
double sideLength) 


{ 


12. When the method is called, nis set to 5. Then n 
is incremented twice, setting it to 7. That value 
is returned and printed. 

. Itacts the same way: If sideLength is 0, it returns 
0 directly instead of computing 0 x 0 x 0. 


double area = sideLength * sideLength; 14. Itreturns true if nis even; false if nis odd. 


return area; 


} 


15. 


16. 


17. 


18. 


19. 


20. 


PA 


public static boolean mystery(Cint n) 


{ 


} 


boxString("Hello"); 
boxString("World") ; 


return n % 2 == 0; 


The boxString method does not return a value. 
Therefore, you cannot use it in a call to the 
print method. 


public static void shout(String message) 


{ 
} 


public static void boxString(String contents) 


{ 


System.out.printIn(message ++ "!!!"); 


jnt n = contents. lengthQ; 
for (int i = 0; 1 <n + 4; i++) 
{ 

System.out.print("-"); 
} 
System.out.printInQ; 
System.out.printIn("! " + contents +" !"); 
for (int i = 0; 1 <n + 4; i++) 
{ 

System.out.print("-"); 
} 
System.out.printIn() 


} 


public static void printLine(int count) 
{ 
for (int i = 0; 7 < count; i++) 
{ 
System.out.print("-"); 
} 
System.out.printIn(Q; 
} 
public static void boxString(String contents) 
{ 
jnt n = contents. lengthQ; 
printLine(n + 2); 
System.out.printin( 
printLine(n + 2); 


+ contents + "!"); 


} 


jnt totalPennies = getPennies(total); 
jnt taxPennies = getPennies(total * taxRate); 


where the method is defined as 


@param amount an amount in dollars and cents 
@return the number of pennies in the amount 
we 
public static int getPennies(double amount) 


{ 
} 


return (int) Math.round(100 * amount) % 100; 


22. 


23. 


24. 


25. 


Answers to Self-Check Questions 247 


if CisEven(page)) .. . 
where the method is defined as follows: 
public static boolean isEven(int n) 


{ 
} 


Add parameter variables so you can pass the 
initial balance and interest rate to the method: 


return n % 2 == 0; 


public static double balance( 
double initialBalance, double rate, 
int years) 


{ 


* 


return initialBalance * pow( 
1+ rate / 100, years); 
} 


int spaces = countSpaces (input) ; 


where the method is defined as follows: 


@param str any string 

@return the number of spaces in str 
*/ 
public static int countSpaces(String str) 
{ 

int count = 0; 

for (int i = 0; i < str.lengthQ); i++) 


{ 


if (str.charAt(i) == ' ') 
{ 

count++; 
} 


} 


return count; 


} 


It is very easy to replace the space with any 
character. 


@param str any string 
@param ch a character whose occurrences 
should be counted 
@return the number of times that ch occurs 
instr 
a7 
public static int count(String str, char ch) 
{ 
int count = 0; 
for (int i = 0; i < str.lengthQ); i++) 


{ 
} 


return count; 


if (str.charAt(i) == ch) { count++; } 


} 


This is useful if you want to count other char- 
acters. For example, count (input, ",") counts 


the commas in the input. 


248 Chapter5 Methods 


26. 


27. 


28. 


29. 


30. 


Change line 28 to 

name = name + digitName(part / 100) 
+ " hundred"; 

In line 25, add the statement 


if (part >= 1000) 
{ 
name 
part 


digitName(part / 1000) + "thousand "; 
part % 1000; 


} 


In line 18, change 1000 to 10000 in the 
comment. 


In the case of “teens”, we already have the last 
digit as part of the name. 


Nothing is printed. One way of dealing with 
this case is to add the following statement 
before line 23. 


if (number == 0) { return "zero"; } 


Here is the approximate trace: 


intName(number = 72) 
name 
5 ry" 








" seventy two" 














Note that the string starts with a blank space. 
Exercise P5.13 asks you to eliminate it. 


Here is one possible solution. Break up the 
task print table into print header and 

print body. The print header task calls print separator, 
prints the header cells, and calls print separator 
again. The print body task repeatedly calls print row 
and then calls print separator. 


31. 
32. 
33. 
34. 


35. 


36. 


37. 
38. 


39. 


40. 


Lines 14-17. 
Lines 11-19. 
The variables x defined in lines 5 and 15. 


Rename the local variable x that is declared in 
line 15, or rename the parameter variable x that 
is declared in line 10. 


The main method accesses the local variable s 
of the mystery method. Assuming that the main 
method intended to print the last value of s 
before the method returned, it should simply 
print the return value that is stored in its local 
variable x. 


CCCI 0 
CIC] 
CC] 

] 


44+34+2+1+0=10 

mystery(10) + 1 = mystery(5) + 2 = mystery(2) + 3 
= mystery(1) + 4 = mystery(0) +5 =5 

The idea is to print one [], then print n - 1of 

them. 


public static void printBoxes(int n) 


if (n == 0) { return; } 
System.out.print("[]"); 
printBoxes(n - 1); 


} 


Simply add the following to the beginning of 
the method: 


if (part >= 1000) 
{ 


return intName(part / 1000) + " thousand " 


+ intName(part % 1000); 


SST TTS G 
ARRAYS AND 
ARRAY LISTS 


CHAPTER GOALS 


To collect elements using arrays 
and array lists 





To use the enhanced for loop for traversing arrays and array lists 
To learn common algorithms for processing arrays and array lists 


To work with two-dimensional arrays 


CHAPTER CONTENTS 


6.1 ARRAYS 250 How To 6.1: Working with Arrays 275 
Syntax 6.1: Arrays 251 Worked Example 6.1: Rolling the Dice © 


Common Error 6.1: Bounds Errors 255 6.6 PROBLEM SOLVING: DISCOVERING 


Common Error 6.2: Uninitialized Arrays 255 ALGORITHMS BY MANIPULATING 
Programming Tip 6.1: Use Arrays for Sequences PHYSICAL OBJECTS 279 

OF Related Items 298 Video Example 6.1: Removing Duplicates from 
Random Fact 6.1: An Early Internet Worm 256 an Array @ 


6.2 THE ENHANCED FOR LOOP 257 
Syntax 6.2: The Enhanced for Loop 258 


6.7 TWO-DIMENSIONAL ARRAYS 282 
Syntax 6.3: Two-Dimensional Array 


6.3 COMMON ARRAY ALGORITHMS 258 Declaration 283 
Common Error 6.3: Underestimating the Size Worked Example 6.2: A World Population Table & 
of a Data Set 267 Special Topic 6.4: Two-Dimensional Arrays with 


Variable Row Lengths 288 
Special Topic 6.5: Multidimensional Arrays 289 


Special Topic 6.1: Sorting withthe JavaLibrary 267 
Special Topic 6.2: Binary Search 267 


6.4 USING ARRAYS WITH METHODS 268 6.8 ARRAYLISTS 289 
Special Topic 6.3: Methods with a Variable Syntax 6.4: Array Lists 290 
Number of Parameters 272 Common Error 6.4: Length and Size 299 
Special Topic 6.6: The Diamond Syntax 
6.5 PROBLEM SOLVING: ADAPTING in Java 7 299 


ALGORITHMS 272 
Programming Tip 6.2: Reading Exception 
Reports 274 


Video Example 6.2: Game of Life @ 








6.1 Arrays 


An array collects a 
sequence of values of 
the same type. 


250 


We start this chapter by introducing the array data type. Arrays are the fundamental 
mechanism in Java for collecting multiple values. In the following sections, you will 
learn how to declare arrays and how to access array elements. 


6.1.1 Declaring and Using Arrays 


Suppose you write a program that reads a sequence of values and prints out the 
sequence, marking the largest value, like this: 

32 

54 

67.5 

29 

35 

80 

115 <= largest value 

44.5 

100 

65 


You do not know which value to mark as the largest one until you have seen them all. 
After all, the last value might be the largest one. Therefore, the program must first 
store all values before it can print them. 

Could you simply store each value in a separate variable? If you know that there 
are ten values, then you could store the values in ten variables value1, value2, value3, ..., 
valuel0. However, such a sequence of variables is not very practical to use. You would 
have to write quite a bit of code ten times, once for each of the variables. In Java, an 
array is a much better choice for storing a sequence of values of the same type. 

Here we create an array that can hold ten values of type double: 


new double[10] 


The number of elements (here, 10) is called the length of the array. 

The new operator constructs the array. You will want to store the array in a variable 
so that you can access it later. 

The type of an array variable is the type of the element to be stored, followed by (1. 
In this example, the type is double[], because the element type is double. 

Here is the declaration of an array variable of type double[] (see Figure 1): 


double[] values; (1) 


When you declare an array variable, it is not yet initialized. You need to initialize the 
variable with the array: 


double[] values = new double[10]; 2) 


6.1 Arrays 251 





Declare the array variable Initialize it with an array Access an array element 


Figure 1 An Array of Size 10 


Now values is initialized with an array of 10 numbers. By default, each number in the 
array 1s 0. 
When you declare an array, you can specify the initial values. For example, 


double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 }; 


When you supply initial values, you don’t use the new operator. The compiler deter- 
mines the length of the array by counting the initial values. 
annuainonene To access a value in an array, you specify which “slot” you want to use. That is 
inan array are done with the 0 operator: 
accessed by an values (47 2 95: 6 


integer index i, using 
ag! Now the number 4 slot of values is filled with 35 (see Figure 1). This “slot number” is 
Als . . 5 
! called an index. Each slot in an array contains an element. 
i Because values is an array of double values, each element values[i] can be used like 
n array element : : Sq e 
Ger ra weal (Pe any variable of type double. For example, you can display the element with index 4 
any variable. with the following command: 


System.out.printIn(values[4]); 


Syntax 6.1 Arrays 


Syntax To construct an array: new typeName [length] 


To access an element: array Reference [index] 


Element 
Name of array variable type Length 


Type of array variable “double[] values = new double[10]; 


double[] moreValues = { 32, 54, 67.5, 29, 35 }; 
—$—$—$—<—S 
Use brackets to access an element. ~~ Wistte. 


values[i] = 0; 


\ The index must be = 0 and < the length of the array. 


AK See page 259. 





252 Chapter6 Arrays and Array Lists 


An array index must 
be at least zero and 

less than the size of 
the array. 


A bounds error, 
which occurs if you 
supply an invalid 
array index, can 
cause your program 
to terminate. 


Before continuing, we must take care of an 
important detail of Java arrays. If you look 
carefully at Figure 1, you will find that the 
fifth element was filled when we changed 
values[4]. In Java, the elements of arrays | jke @ mailbox that is identified by a box 
are numbered starting at 0. That is, the number, an array element is identified by 
legal elements for the values array are an index. 





values[0], the first element 


values[1], the second element 
, the third element 
, the fourth element 


, the fifth element 


values[2] 


values [3] 


values[4] 





values[9], the tenth element 


In other words, the declaration 
double[] values = new double[10]; 


creates an array with ten elements. In this array, an index can be any integer ranging 
from 0 to 9. 

You have to be careful that the index stays within the valid range. Trying to access 
an element that does not exist in the array is a serious error. For example, if values has 
ten elements, you are not allowed to access values[20]. Attempting to access an ele- 
ment whose index is not within the valid index range is called a bounds error. The 
compiler does not catch this type of error. When a bounds error occurs at run time, it 
causes a run-time exception. 

Here is a very common bounds error: 


double[] values = new double[10]; 
values[10] = value; 


There is no values[10] in an array with ten elements—the index can range from 0 to 9. 

To avoid bounds errors, you will want to know how many elements are in an array. 
The expression values. length yields the length of the values array. Note that there are 
no parentheses following length. 


Table 1 Declaring Arrays 


int[] numbers = new int[10]; Anarray of ten integers. All elements are 
initialized with zero. 

final int LENGTH = 10; It is a good idea to use a named constant 

int[] numbers = new int[LENGTH]; instead of a “magic number”. 

int length = in.nextIntQ; The length need not be a constant. 


double[] data = new double[length]; 
int[] squares = { 0, 1, 4, 9, 16 }; Anarray of five integers, with initial values. 


Stringl] friends = { "Emily", "Bob", “Cindy” }; An array of three strings. 


OQ double[] data = new int[10]; Error: You cannot initialize a double[] 


variable with an array of type int[]. 


Use the expression 
array. length to find 
the number of 
elements in an array. 


An array reference 
specifies the location 
of an array. Copying 
the reference yields a 
second reference to 
the same array. 


6.1 Arrays 253 


The following code ensures that you only access the array when the index variable 
i is within the legal bounds: 


if (0 <= i && i < values.length) { values[i] = value; } 


Arrays suffer from a significant limitation: their length is fixed. If you start out with 
an array of 10 elements and later decide that you need to add additional elements, 
then you need to make a new array and copy all elements of the existing array into the 
new array. We will discuss this process in detail in Section 6.3.9. 

To visit all elements of an array, use a variable for the index. Suppose values has ten 
elements and the integer variable i is set to 0, 1, 2, and so on, up to 9. Then the expres- 
sion values[i] yields each element in turn. For example, this loop displays all elements 
in the values array. 

for (int i = 0; i < 10; i++) 


{ 


System.out.printIn(values[i]); 


} 


Note that in the loop condition the index is Jess than 10 because there is no element 
corresponding to values[10]. 


6.1.2 Array References 


If you look closely at Figure 1, you will note that the variable values does not store 
any numbers. Instead, the array is stored elsewhere and the values variable holds a 
reference to the array. (The reference denotes the location of the array in memory.) 
When you access the elements in an array, you need not be concerned about the fact 
that Java uses array references. This only becomes important when copying array 
references. 

When you copy an array variable into another, both variables refer to the same 
array (see Figure 2). 


int[] scores = { 10, 9, 7, 4, 5 }; 
int[] values = scores; // Copying array reference 


You can modify the array through either of the variables: 
scores[3] = 10; 


System.out.printIn(values[3]); // Prints 10 


Section 6.3.9 shows how you can make a copy of the contents of the array. 





Figure 2 
Two Array Variables Referencing the Same Array 


254 Chapter6 Arrays and Array Lists 


6.1.3 Partially Filled Arrays 


With a partially filled 
array, you need to 


remember how many 
elements are filled. 


With a partially filled 
array, keepa 

companion variable 
for the current size. 


ONLINE EXAMPLE 


@ Aprogram 
demonstrating array 
operations. 





An array cannot change size at run time. This is a problem when you don’t know in 
advance how many elements you need. In that situation, you must come up with a 
good guess on the maximum number of elements that you need to store. For exam- 
ple, we may decide that we sometimes want to store more than ten elements, but 
never more than 100: 


final int LENGTH = 100; 
double[] values = new double[LENGTH]; 


Ina typical program run, only a part of the array will be occupied by actual elements. 
We call such an array a partially filled array. You must keep a companion variable 
that counts how many elements are actually used. In Figure 3 we call the companion 
variable currentSize. 

The following loop collects inputs and fills up the values array: 


int currentSize = 0; 
Scanner in = new Scanner(System. in); 
while (in. hasNextDouble()) 


{ 
if (currentSize < values. length) 
{ 
values[currentSize] = in.nextDouble(); 
currentSize++; 
} 
} 


At the end of this loop, currentSize contains the actual number of elements in the 
array. Note that you have to stop accepting inputs if the currentSize companion vari- 
able reaches the array length. 

To process the gathered array elements, you again use the companion variable, not 
the array length. This loop prints the partially filled array: 


for (int i = 0; i < currentSize; i++) 


System.out.printIn(values[i]); 





currentSize 


>values. length 


Not currently used 








Figure 3 A Partially Filled Array 









(y) 
SELF CHECK 
eer 


Practice It 


(@oyaalankelamaage) mom 


(Gloyaalankelamaane) mon 









6.1 Arrays 255 


1. Declare an array of integers containing the first five prime numbers. 


2. Assume the array primes has been initialized as described in Self Check 1. What 
does it contain after executing the following loop? 


for (int i = 0; 7 < 2; i++) 
{ 


primes[4 - i] = primes[i]; 
} 


3. Assume the array primes has been initialized as described in Self Check 1. What 
does it contain after executing the following loop? 


for (int i = 0; 71 < 53 i++) 


{ 
} 


4. Given the declaration 


primes [i]++; 


int[] values = new int[10]; 


write statements to put the integer 10 into the elements of the array values with 
the lowest and the highest valid index. 


5. Declare an array called words that can hold ten elements of type String. 
6. Declare an array containing two strings, "Yes", and "No". 


7. Can you produce the output on page 250 without storing the inputs in an array, 
by using an algorithm similar to the algorithm for finding the maximum in 
Section 4.7.5? 


Now you can try these exercises at the end of the chapter: R6.1, R6.2, R6.6, P6.1. 


Bounds Errors 


Perhaps the most common error in using arrays is accessing a nonexistent element. 


double[] values = new double[10]; 
values[10] = 5.4; 
// Error—values has 10 elements, and the index can range from 0 to 9 


If your program accesses an array through an out-of-bounds index, there is no compiler error 
message. Instead, the program will generate an exception at run time. 


Uninitialized Arrays 


A common error is to allocate an array variable, but not an actual array. 


double[] values; 
values[0] = 29.95; // Error—values not initialized 


The Java compiler will catch this error. The remedy is to initialize the variable with an array: 
double[] values = new double[10]; 


256 Chapter6 Arrays and Array Lists 


Use Arrays for Sequences of Related Items 


acoyele-laalenliale mi ohoral| 


Arrays are intended for storing sequences of values with the same meaning. For example, an 
array of test scores makes perfect sense: 


int[] scores 


But an array 


int[] personalData = 


= new int[NUMBER_OF_SCORES]; 


new int[3]; 


that holds a person’s age, bank balance, and shoe size in positions 0, 1, and 2 is bad design. 
It would be tedious for the programmer to remember which of these data values is stored in 
which array location. In this situation, it is far better to use three separate variables. 


In November 1988, 
Robert Morris, a stu- 
dent at Cornell University, launched a 
so-called virus program that infected 
about 6,000 computers connected to 
the Internet across the United States. 
Tens of thousands of computer users 
were unable to read their e-mail or oth- 
erwise use their computers. All major 
universities and many high-tech com- 
panies were affected. (The Internet was 
much smaller then than it is now.) 

The particular kind of virus used in 
this attack is called a worm. The worm 
program crawled from one computer 
on the Internet to the next. The worm 
would attempt to connect to finger, 
a program in the UNIX operating sys- 
tem for finding information on a user 
who has an account on a particular 
computer on the network. Like many 
programs in UNIX, finger was written 
in the C language. In order to store 
the user name, the finger program 
allocated an array of 512 characters, 
under the assumption that nobody 
would ever provide such a long input. 
Unfortunately, C does not check that 
an array index is less than the length 
of the array. If you write into an array 
using an index that is too large, you 
simply overwrite memory locations 
that belong to some other objects. In 
some versions of the finger program, 
the programmer had been lazy and had 
not checked whether the array holding 
the input characters was large enough 





Random Fact 6.1 An Early Internet Worm 


to hold the input. So the worm pro- 
gram purposefully filled the 512-char- 
acter array with 536 bytes. The excess 
24 bytes would overwrite a return 
address, which the attacker knew was 
stored just after the array. When that 
method was finished, it didn’t return 
to its caller but to code supplied by the 
worm (see the figure, A “Buffer Over- 
run” Attack). That code ran under the 
same super-user privileges as finger, 
allowing the worm to gain entry into 
the remote system. Had the program- 
mer who wrote finger been more 
conscientious, this particular attack 
would not be possible. 

In Java, as in C, all programmers 
must be very careful not to overrun 
array boundaries. However, in Java, 
this error causes a run-time exception, 
and it never corrupts memory outside 
the array. This is one of the safety fea- 
tures of Java. 

One may well speculate what would 
possess the virus author to spend 
many weeks to plan the antisocial act 
of breaking into thousands of comput- 
ers and disabling them. It appears that 
the break-in was fully intended by the 
author, but the disabling of the com- 
puters was a bug, caused by continu- 
ous reinfection. Morris was sentenced 
to 3 years probation, 400 hours of com- 
munity service, and a $10,000 fine. 

In recent years, computer attacks 
have intensified and the motives 
have become more sinister. Instead 


of disabling computers, viruses often 
steal financial data or use the attacked 
computers for sending spam e-mail. 
Sadly, many of these attacks continue 
to be possible because of poorly writ- 
ten programs that are susceptible to 
buffer overrun errors. 


1) Before the attack 


Buffer for input 
(512 bytes) 


Return address = 


(2) After the attack 


Overrun buffer 
(536 bytes) 


Return address 





A “Buffer Overrun” Attack 


6.2 TheEnhancedforLoop 257 


6.2 The Enhanced forLoop 


Often, you need to visit all elements of an array. The enhanced for loop makes this 
You can use the 


enhanced for loop process particularly easy to program. 
ie visit all elements Here is how you use the enhanced for loop to total up all elements in an array 
of an array. 


named values: 


double[] values=.. .3 
double total = 0; 
for (double element : values) 


{ 


} 


The loop body is executed for each element in the array values. At the beginning of 
each loop iteration, the next element is assigned to the variable element. Then the loop 
body is executed. You should read this loop as “for each element in values”. 

This loop is equivalent to the following for loop and an explicit index variable: 


total = total + element; 


for (int i = 0; i < values.length; i++) 


double element = values[i]; 
total = total + element; 


} 


Note an important difference between the enhanced for loop and the basic for loop. 
In the enhanced for loop, the element variable is assigned values [0], values[1], and so 
on. In the basic for loop, the index variable i is assigned 0, 1, and so on. 
Hear eam Keep in mind that the enhanced for loop has a very specific purpose: getting the 
for loop if you do elements of a collection, from the beginning to the end. It is not suitable for all array 
not need the index algorithms. In particular, the enhanced for loop does not allow you to modify the 
Ca contents of an array. The following loop does not fill an array with zeroes: 


loop body. 
for (double element : values) 
{ 
element = 0; // ERROR: this assignment does not modify array elements 
} 


When the loop is executed, the variable element is set to values [0]. Then element is set to 
0, then to values [1], then to 0, and so on. The values array is not modified. The remedy 
is simple: Use a basic for loop: 


ONLINE EXAMPLE 


An program that 
demonstrates the 
enhanced for loop. 


for (int i = 0; 7 < values. length; i++) \\\ W/ 
—_~ 


values[i] = 0; // OK 


as = 


The enhanced for loop is a convenient mechanism for 
traversing all elements in a collection. 





258 Chapter6 Arrays and Array Lists 


Syntax 6.2 The Enhanced for Loop 


Syntax for (typeName variable : collection) 
{ 


statements 


} 


This variable is set in each loop iteration. 
It is only defined inside the loop. An array 


for (double element : values) 


{ 
These statements { sum = sum + element; The variable 


} contains an element, 


are executed for each not an index. 


element. 





8. What does this enhanced for loop do? 


int counter = 0; 
for (double element : values) 





if (element == 0) { counter++; } 


- 
9. Write an enhanced for loop that prints all elements in the array values. 


10. Write an enhanced for loop that multiplies all elements in a double[] array named 
factors, accumulating the result in a variable named product. 


11. Why is the enhanced for loop not an appropriate shortcut for the following basic 
for loop? 


for (int i = 0; i < values.length; i++) { values[i] = 7 * i; } 


Practice It Now youcantry these exercises at the end of the chapter: R6.7, R6.8, R6.9. 


In the following sections, we discuss some of the most common algorithms for work- 


ing with arrays. If you use a partially filled array, remember to replace values. length 
with the companion variable that represents the current size of the array. 


6.3.1 Filling 
This loop fills an array with squares (0, 1, 4, 9, 16, ...). Note that the element with 
index 0 contains 07, the element with index 1 contains 12, and so on. 


for (int i = 0; i < values.length; i++) 


{ 
} 


values[i] = 71 * 7; 





When separating 
elements, don’t place 
a separator before 
the first element. 


To print five 
elements, you need 
four separators. 


6.3. CommonArray Algorithms 259 


6.3.2 Sum and Average Value 


You have already encountered this algorithm in Section 4.7.1. When the values are 
located in an array, the code looks much simpler: 

double total = 0; 

for (double element : values) 


{ 
} 


double average = 0; 
if (values.length > 0) { average = total / values.length; } 


total = total + element; 


6.3.3 Maximum and Minimum 


Use the algorithm from Section 4.7.5 that keeps a variable for the largest element 
already encountered. Here is the implementation of that algorithm for an array: 


double largest = values[0]; 
for (int i = 1; i < values.length; i++) 


if (values[i] > largest) 


largest = values[i]; 
} 
} 


Note that the loop starts at 1 because we initialize largest with values [0]. 
To compute the smallest element, reverse the comparison. 
These algorithms require that the array contain at least one element. 


6.3.4 Element Separators 


When you display the elements of an array, you usually want to separate them, often 
with commas or vertical lines, like this: 


32 | 54 | 67.5 | 29 | 35 


Note that there is one fewer separator than there are numbers. Print the separator 
before each element in the sequence except the initial one (with index 0) like this: 


for (int i = 0; i < values.length; i++) 


{ 
if G > 0) 
{ 
System.out.print(" | "); 
r 
System.out.print(values[i]); 
} 


If you want comma separators, you can use the Arrays.toString method. The 
expression 


Arrays.toString(values) 
returns a string describing the contents of the array values in the form 
[32, 54, 67.5, 29, 35] 


260 Chapter6 Arrays and Array Lists 





To search fora 
specific element, 
visit the elements 
and stop when you 
encounter the match. 


A linear search 
inspects elements in 
sequence untila 
match is found. 


currentSize < 





Figure 4 


Removing an Element in an Unordered Array 


The elements are surrounded by a pair of brackets and separated by commas. This 
method can be convenient for debugging: 


System.out.printIn("values=" + Arrays.toString(values)) ; 


6.3.5 Linear Search 


You often need to search for the position of a specific element in an array so that you 
can replace or remove it. Visit all elements until you have found a match or you have 
come to the end of the array. Here we search for the position of the first element in an 
array that is equal to 100: 


int searchedValue = 100; 

int pos = 0; 

boolean found = false; 

while (pos < values.length && ! found) 
{ 


if (values[pos] == searchedValue) 


{ 
} 
else 


{ 
} 


found = true; 


pos++; 


} 
if (found) { System.out.print]n("Found at position: 
else { System.out.printIn("Not found"); } 


" 


+ pos); } 


This algorithm is called linear search or sequential search because you inspect the 
elements in sequence. If the array is sorted, you can use the more efficient binary 
search algorithm— see Special Topic 6.2 on page 267. 


6.3.6 Removing an Element 


Suppose you want to remove the element with index pos from the array values. As 
explained in Section 6.1.3, you need a companion variable for tracking the number of 
elements in the array. In this example, we use a companion variable called currentSize. 

If the elements in the array are not in any particular order, simply overwrite the 
element to be removed with the Jast element of the array, then decrement the current- 
Size variable. (See Figure 4.) 





32 [0] [0] 

Mr [1] [1] 
67.5 [2] [2] 

29 : : 
34.5 [pos] 1) : [pos] 

80 e 

115 Decrement after i Decrement after 
445 moving element 8: moving elements 
100 S rf 

65 {currentSize - 1] [currentSize - 1] 


Figure 5 
Removing an Element in an Ordered Array 





hm 
ANIMATION 
Removing from 
an Array 


[yA 





hm 
ANIMATION 
Inserting into 
an Array 


yA 


Before inserting an 
element, move 
elements to the end 
of the array starting 
with the last one. 


currentSize < 





Figure 6 








6.3. CommonArray Algorithms 261 


values[pos] = values[currentSize - 1]; 
currentSize--; 


The situation is more complex if the order of the elements matters. Then you must 
move all elements following the element to be removed to a lower index, and then 
decrement the variable holding the size of the array. (See Figure 5.) 


for (int i = pos + 1; 7 < currentSize; i++) 


{ 

values[i - 1] = values[il; 
} 
currentSize--; 


6.3.7 Inserting an Element 


In this section, you will see how to insert an element into an array. Note that you 
need a companion variable for tracking the array size, as explained in Section 6.1.3. 

If the order of the elements does not matter, you can simply insert new elements at 
the end, incrementing the variable tracking the size. 


if (currentSize < values. length) 


{ 
currentSize++; 
values[currentSize - 1] = newElement; 


} 


It is more work to insert an element at a particular position in the middle of an array. 
First, move all elements after the insertion location to a higher index. Then insert the 
new element (see Figure 7). 

Note the order of the movement: When you remove an element, you first move 
the next element to a lower index, then the one after that, until you finally get to the 
end of the array. When you insert an element, you start at the end of the array, move 
that element to a higher index, then move the one before that, and so on until you 
finally get to the insertion location. 


if (currentSize < values. length) 


{ 
currentSize++; 
for (int i = currentSize - 1; i > pos; i--) 
{ 
values[i] = values[i - 1]; 
values[pos] = newElement; 
} 
32 [0] [0] 
54 [1] | 
2 
— [2] : 3 Insert new element here 
34.5 e: [pos] 
80 Inser t new element here ra) % 
115 39 * Incremented before 
445 Incremented before moving elements 
100 inserting element g 





[currentSize - 1] [currentSize - 1] 


Figure 7 


Inserting an Element in an Unordered Array Inserting an Element in an Ordered Array 


262 Chapter6 Arrays and Array Lists 


Use a temporary 
variable when 
swapping two 
elements. 


You often need to swap elements of an array. For example, 
you can sort an array by repeatedly swapping elements 
that are not in order. 

Consider the task of swapping the elements at posi- 
tions i and j of an array values. We’d like to set values[i] 
to values[j]. But that overwrites the value that is currently 
stored in values[i], so we want to save that first: 


double temp = values[i]; 
values[i] = values[j]; 


Now we can set values[j] to the saved value. 


values[j] = temp; 


Figure 8 shows the process. 





Figure 8 Swapping Array Elements 





To swap two elements, you 
need a temporary variable. 


Values to be swapped 


5 


Use the Arrays. 
copyOf method to 
copy the elements of 
an array intoa 

new array. 


6.3. CommonArray Algorithms 263 





Array variables do not themselves hold array elements. They hold a reference to the 
actual array. If you copy the reference, you get another reference to the same array 
(see Figure 9): 


double[] values = new double[6]; 
// Fillarray 
double[] prices = values; 1) 


If you want to make a true copy of an array, call the Arrays. copyOf method (as shown 
in Figure 9). 
double[] prices = Arrays.copyOf(values, values. length) ; @® 


The call Arrays. copyOf(values, n) allocates an array of length n, copies the first n elements 
of values (or the entire values array ifn > values. length) into it, and returns the new array. 


@ After the assignment prices = values (2 } After calling Arrays . copyOf 


= 
prices = 










—_ CC UC‘ 





Figure 9 Copying an Array Reference versus Copying an Array 


In order to use the Arrays class, you need to add the following statement to the top of 
your program: 


import java.util.Arrays; 


Another use for Arrays. copyOf is to grow an array that has run out of space. The fol- 
lowing statements have the effect of doubling the length of an array (see Figure 10): 


double[] newalues = Arrays.copyOf(values, 2 * values. length); @ 
values = newValues; (2 } 


The copy0f method was added in Java 6. If you use Java 5, replace 
double[] newalues = Arrays.copyOf(values, n) 


with 


264 Chapter6 Arrays and Array Lists 


1) Move elements to a larger array (2) Store the reference to the larger array in values 





Figure 10 Growing an Array 


double[] new/alues = new double[n]; 
for Cint i = 0; i < n && i < values. length; i++) 
{ 

newValues[i] = values[i]; 


} 


3.10 R ing In 


If you know how many inputs the user will supply, it is simple to place them into an 
array: 
double[] inputs = new double[NUMBER_OF_INPUTS]; 
for Gi = 0; i < inputs.length; i++) 
{ 
inputs[i] = in.nextDouble(); 


However, this technique does not work if you need to read a sequence of arbitrary 
length. In that case, add the inputs to an array until the end of the input has been 
reached. 


int currentSize = 0; 
while Cin.hasNextDouble() && currentSize < inputs. length) 
{ 

inputs[currentSize] = in.nextDoubleQ; 

currentSizet++; 


} 


6.3. CommonArray Algorithms 265 


Now inputs is a partially filled array, and the companion variable currentSize is set to 
the number of inputs. 

However, this loop silently throws away inputs that don’t fit into the array. A bet- 
ter approach is to grow the array to hold all inputs. 

double[] inputs = new double[INITIAL_SIZE]; 

int currentSize = 0; 

while Cin.hasNextDouble()) 

{ 


// Grow the array if it has been completely filled 
if (currentSize >= inputs. length) 


{ 
} 


inputs = Arrays.copyOf(inputs, 2 * inputs.length); // Grow the inputs array 


inputs[currentSize] = in.nextDoubleQ); 
currentSize++; 


} 
When you are done, you can discard any excess (unfilled) elements: 

inputs = Arrays.copyOf(inputs, currentSize) ; 
The following program puts these algorithms to work, solving the task that we set our- 
selves at the beginning of this chapter: to mark the largest value in an input sequence. 
section_3/LargestinArray.java 


1 import java.util.Scanner; 


2 

3 [** 

4 This program reads a sequence of values and prints them, marking the largest value. 
5 */ 

6 public class LargestInArray 

yn! 

8 public static void main(String[] args) 

9 { 

10 final int LENGTH = 100; 

11 double[] values = new double[LENGTH]; 

12 jnt currentSize = 0; 

13 

14 // Read inputs 

15 

16 System.out.printIn("Please enter values, Q to quit:"); 
17 Scanner in = new Scanner(System. in) ; 

18 while Cin.hasNextDouble() && currentSize < values. length) 
19 { 

20 values[currentSize] = in.nextDouble(); 
21 currentSize++; 

22 } 

23 

24 // Find the largest value 

25 

26 double largest = values[0]; 

27 for (int i = 1; i < currentSize; i++) 

28 { 

29 if (values[i] > largest) 

30 { 

31 largest = values[i]; 

32 } 


33 } 


266 Chapter6 Arrays and Array Lists 





SELF CHECK 


f 








34 
35 
36 
37 
38 
39 
40 
41 


// Print all values, marking the largest 
for (int i = 0; i < currentSize; i++) 
: System.out.print(values[i]); 
if (values[i] == largest) 
: System.out.print(" <== largest value"); 
, Sasa: 


Program Run 


12. 


13. 
14. 


15. 


16. 


17. 


Please enter values, Q to quit: 
34.5 80 115 44.5 Q 

34.5 

80 

115 <== largest value 

44.5 


Given these inputs, what is the output of the LargestInArray program? 

20 10 20Q 

Write a loop that counts how many elements in an array are equal to zero. 
Consider the algorithm to find the largest element in an array. Why don’t we 
initialize largest and i with zero, like this? 

double largest = 0; 

for (int i = 0; i < values.length; i++) 


if (values[i] > largest) 


largest = values[i]; 
} 
} 
When printing separators, we skipped the separator before the initial element. 
Rewrite the loop so that the separator is printed after each element, except for 
the last element. 


What is wrong with these statements for printing an array with separators? 


System.out.print(values[0]); 
for (int i = 1; i < values.length; i++) 


{ 


} 


When finding the position of a match, we used a while loop, not a for loop. What 
is wrong with using this loop instead? 


System.out.print(", " + values[i]); 


for (pos = 0; pos < values.length && !found; pos++) 
if (values[pos] > 100) 
{ 


found = true; 


} 


6.3. CommonArray Algorithms 267 


} 


18. When inserting an element into an array, we moved the elements with larger 
index values, starting at the end of the array. Why is it wrong to start at the inser- 
tion location, like this? 


for (int i = pos; i < currentSize - 1; i++) 


values[i + 1] = values[i]; 


Practice It Now youcantry these exercises at the end of the chapter: R6.17, R6.20, P6.15. 


Common crore Underestimating the Size of a Data Set 





SSE Programmers commonly underestimate the amount of input data that a user will pour into an 
unsuspecting program. Suppose you write a program to search for text ina file. You store each 
line in a string, and keep an array of strings. How big do you make the array? Surely nobody 
is going to challenge your program with an input that is more than 100 lines. Really? It is very 
easy to feed in the entire text of Alice in Wonderland or War and Peace (which are available on 
the Internet). All of a sudden, your program has to deal with tens or hundreds of thousands of 
lines. You either need to allow for large inputs or politely reject the excess input. 


Sorting with the Java Library 





Special Topic 6.1 
Sorting an array efficiently is not an easy task. You will 
learn in Chapter 14 how to implement efficient sorting 
algorithms. Fortunately, the Java library provides an effi- 
cient sort method. 

To sort an array values, call 


Arrays.sort(values) ; 


If the array is partially filled, call 





Arrays.sort(values, 0, currentSize) ; 


Binary Search 


When an array is sorted, there is a much faster search algorithm than the linear search of Sec- 
tion 6.3.5. 
Consider the following sorted array values. 


[0] [1] [2] [3] [4] [5] [6] [7] 
(105 8 9 1217 2032 


We would like to see whether the number 15 is in the array. Let’s narrow our search by finding 
whether the number is in the first or second half of the array. The last point in the first half of 
the values array, values [3], is 9, which is smaller than the number we are looking for. Hence, 
we should look in the second half of the array for a match, that is, in the sequence: 





C0] [1] [2] [3] (4] [5] [6] (7) 


153° BRB 


268 Chapter6 Arrays and Array Lists 


Now the last element of the first half of this sequence is 17; hence, the number must be located 


in the sequence: 
[4] [5] 


The last element of the first half of this very short sequence is 12, which is smaller than the 
number that we are searching, so we must look in the second half: 


[5] 
12 Bj 2 


We still don’t have a match because 15 17, and we cannot divide the subsequence further. If 
we wanted to insert 15 into the sequence, we would need to insert it just before values [5]. 

This search process is called a binary search, because we cut the size of the search in half in 
each step. That cutting in half works only because we know that the array is sorted. Here is an 
implementation in Java: 


boolean found = false; 

int low = 0; 

int high = values.length - 1; 

int pos = 0; 

while Clow <= high && ! found) 

{ 
pos = (low + high) / 2; // Midpoint of the subsequence 
if (values[pos] == searchedNumber) { found = true; } 
else if (values[pos] < searchedNumber) { low = pos + 1; } // Look in second half 
else { high = pos - 1; } // Look in first half 

} 

if (found) { System.out.printIn("Found at position " + pos); } 

else { System.out.printIn("Not found. Insert before position " 


" 


+ pos); } 


4 ing Arr with Meth 


Arrays can occur as 
method arguments 
and return values. 


In this section, we will explore how to write methods that process arrays. 

When you define a method with an array argument, you provide a parameter vari- 
able for the array. For example, the following method computes the sum of an array 
of floating-point numbers: 


public static double sum(double[] values) 


{ 
double total = 0; 
for (double element : values) 
{ 
total = total + element; 
} 
return total; 
} 


This method visits the array elements, but it does not modify them. It is also possible 
to modify the elements of an array. The following method multiplies all elements of 
an array by a given factor: 


public static void multiply(double[] values, double factor) 


{ 
for (int i = 0; i < values.length; i++) 


{ 


Figure 11 
Trace of Call to 
the multiply Method 


6.4 Using Arrays with Methods 269 


values[i] = values[i] * factor; 
} 
} 


Figure 11 traces the method call 


multiply(scores, 10); 


Note these steps: 


The parameter variables values and factor are created. @ 


The parameter variables are initialized with the arguments that are passed in the 
call. In our case, values is set to scores and factor is set to 10. Note that values and 
scores are references to the same array. @ 


The method multiplies all array elements by 10.@ 


The method returns. Its parameter variables are removed. However, scores still 
refers to the array with the modified elements. @ 


Method call 





Initializing method parameter variables 


sd scores = —_~_ 







About to return to the caller 


sd scores = ——_._ 


After method call 


270 Chapter6 Arrays and Array Lists 


A method can return an array. Simply build up the result in the method and return it. 
In this example, the squares method returns an array of squares from 0? up to (m— 1): 


public static int[] squares(Cint n) 


{ 
int{] result = new int[n]; 
for (int i = 0; i <n; i++) 
result[i] = 71 * 7; 
} 
return result; 
} 


The following example program reads values from standard input, multiplies them 
by 10, and prints the result in reverse order. The program uses three methods: 


e The readInputs method returns an array, using the algorithm of Section 6.3.10. 
e The multiply method has an array argument. It modifies the array elements. 


¢ The printReversed method also has an array argument, but it does not modify the 
array elements. 


section_4/Reverse.java 


1 import java.util.Scanner; 


2 
3 [** 
4 This program reads, scales, and reverses a sequence of numbers. 
Sis, 
6 public class Reverse 
ey 4 
8 public static void main(String[] args) 
9 { 
10 double[] numbers = readInputs(5); 
11 multiply(numbers, 10); 
12 printReversed(numbers) ; 
13 } 
14 
15 [** 
16 Reads a sequence of floating-point numbers. 
17 @param numberOfInputs the number of inputs to read 
18 @return an array containing the input values 
19 */ 
20 public static double[] readInputsCint numberOfInputs) 
21 { 
22 System.out.printIn(C'Enter " + numberOfInputs + " numbers: "); 
23 Scanner in = new Scanner(System. in) ; 
24 double[] inputs = new double[numberOfInputs] ; 
25 for Cint i = 0; i < inputs.length; i++) 
26 { 
27 jnputs[i] = in.nextDoubleQ); 
28 
29 return inputs; 
30 } 
31 
32 /e* 
33 Multiplies all elements of an array by a factor. 
34 @param values an array 
35 @param factor the value with which element is multiplied 





6.4 Using Arrays with Methods 271 


public static void multiply(double[] values, double factor) 


{ 


for Cint i = 0; i < values.length; i++) 


values[i] = values[i] * factor; 
} 
} 


[** 
Prints an array in reverse order. 
@param values an array of numbers 
@return an array that contains the elements of values in reverse order 


ae static void printReversed(double[] values) 

// Traverse the array in reverse order, starting with the last element 
for Cint i = values.length - 1; 7 >= 0; i--) 
: System.out.print(values[i] + " "); 

: A sea susie: 


Program Run 


19. 


20. 


21. 


22. 


Enter 5 numbers: 
ee Se OOO 
100.0 0.0 200.0 250.0 120.0 


How do you call the squares method to compute the first five squares and store 
the result in an array numbers? 


Write a method fi11 that fills all elements of an array of integers with a given 
value. For example, the call fi11(scores, 10) should fill all elements of the array 
scores with the value 10. 

Describe the purpose of the following method: 

public static int[] mysteryCint length, int n) 


{ 
int[] result = new int[length]; 
for (int i = 0; i < result.length; i++) 
{ 
result[i] = (int) (n * Math.random()); 
} 
return result; 
} 


Consider the following method that reverses an array: 


public static int[] reverse(int[] values) 


{ 


int[] result = new int[values. length]; 
for (int i = 0; i < values.length; i++) 


{ 
} 


return result; 


result[i] = values[values.length - 1 - i]; 


} 


272 Chapter6 Arrays and Array Lists 


Practice It 


SY ol-Kel f-1 io) 0] (em os} 


Pr 


By combining 
fundamental 
algorithms, you can 
solve complex 
programming tasks. 


Suppose the reverse method is called with an array scores that contains the 
numbers 1, 4, and 9. What is the contents of scores after the method call? 


23. Provide a trace diagram of the reverse method when called with an array that 
contains the values 1, 4, and 9. 


Now you can try these exercises at the end of the chapter: R6.25, P6.6, P6.7. 


Methods with a Variable Number of Parameters 


Starting with Java version 5.0, it is possible to declare methods that receive a variable number 
of parameters. For example, we can write a sum method that can compute the sum of any num- 
ber of arguments: 


sum(1, 3); // Sets ato 4 
sum(1, 7, 2, 9); // Sets bto19 


The modified sum method must be declared as 


int a 
int b 


public static void sum(int... values) 


The ... symbol indicates that the method can receive any number of int arguments. The values 
parameter variable is actually an int[] array that contains all arguments that were passed to the 
method. The method implementation traverses the values array and processes the elements: 


public void sum(int... values) 


{ 
int total = 0; 
for (int i = 0; i < values.length; i++) // values is an int[] 
{ 
total = total + values[i]; 
} 
return total; 
} 


ving: A ing Algorithm 


In Section 6.3, you were introduced to a number of fundamental array algorithms. 
These algorithms form the building blocks for many programs that process arrays. 
In general, it is a good problem-solving strategy to have a repertoire of fundamental 
algorithms that you can combine and adapt. 

Consider this example problem: You are given the quiz scores of a student. You are 
to compute the final quiz score, which is the sum of all scores after dropping the low- 
est one. For example, if the scores are 


8 7 8.5 9.5 7 4 10 


then the final score is 50. 
We do not have a ready-made algorithm for this situation. Instead, consider which 
algorithms may be related. These include: 
¢ Calculating the sum (Section 6.3.2) 
e Finding the minimum value (Section 6.3.3) 


¢ Removing an element (Section 6.3.6) 


You should be 
familiar with the 
implementation of 
fundamental 
algorithms so that 
you can adapt them. 


6.5 Problem Solving: Adapting Algorithms 273 


We can formulate a plan of attack that combines these algorithms: 


Find the minimum. 
Remove it from the array. 
Calculate the sum. 


Let’s try it out with our example. The minimum of 


[0] [1] [2] [3] [4] [5] [6] 
Si] 7 oI. 5) 7/ | 4! | alo) 


is 4. How do we remove it? 

Now we have a problem. The removal algorithm in Section 6.3.6 locates the ele- 
ment to be removed by using the position of the element, not the value. 

But we have another algorithm for that: 


e Linear search (Section 6.3.5) 
We need to fix our plan of attack: 


Find the minimum valve. 

Find its position. 

Remove that position from the array. 
Calculate the sum. 


Will it work? Let’s continue with our example. 
We found a minimum value of 4. Linear search tells us that the value 4 occurs at 


position 5. 
[0] [1] [2] [3] [4] [5] [6] 


8) 7 18.519.5 7 Mw 


We remove it: 


[0] [1] [2] [3] [4] [5] 
Gh] 7 [eiosfSos 7 | alo) 


Finally, we compute the sum: 8 + 7 + 8.5+9.5+7+10=50. 

This walkthrough demonstrates that our strategy works. 

Can we do better? It seems a bit inefficient to find the minimum and then make 
another pass through the array to obtain its position. 

We can adapt the algorithm for finding the minimum to yield the position of the 
minimum. Here is the original algorithm: 


double smallest = values[0]; 
for (int i = 1; i < values. length; i++) 


{ 
if (values[i] < smallest) 
{ 
smallest = values[i]; 
} 
} 


When we find the smallest value, we also want to update the position: 
if (values[i] < smallest) 
smallest = values[i]; 


smallestPosition = 7; 


} 


274 Chapter6 Arrays and Array Lists 


ONLINE EXAMPLE 


@ Aprogram that 
computes the final 
score using the 
adapted algorithm 
for finding the 
minimum. 





Practice It 


aceyele-laalanliale mil ohepy4 


In fact, then there is no reason to keep track of the smallest value any longer. It is sim- 
ply values[smallestPosition]. With this insight, we can adapt the algorithm as follows: 


int smallestPosition = 0; 
for (int i = 1; i < values.length; i++) 
{ 


if (walues[i] < values[smallestPosition]) 


smallestPosition = 7; 


} 
With this adaptation, our problem is solved with the following strategy: 
Find the position of the minimum. 


Remove it from the array. 
Calculate the sum. 


The next section shows you a technique for discovering a new algorithm when none 
of the fundamental algorithms can be adapted to a task. 


24. Section 6.3.6 has two algorithms for removing an element. Which of the two 
should be used to solve the task described in this section? 


25. Itisn’t actually necessary to remove the minimum in order to compute the total 
score. Describe an alternative. 


26. How can you print the number of positive and negative values in a given array, 
using one or more of the algorithms in Section 4.7? 


27. How can you print all positive values in an array, separated by commas? 
28. Consider the following algorithm for collecting all matches in an array: 


int matchesSize = 0; 
for (int i = 0; i < values.length; i++) 


{ 
if (values[i] fulfills the condition) 
{ 
matches[matchesSize] = values[i]; 
matchesSize++; 
} 
} 


How can this algorithm help you with Self Check 27? 


Now you can try these exercises at the end of the chapter: R6.26, R6.27. 


Reading Exception Reports 


You will sometimes have programs that terminate, reporting an “exception”, such as 


Exception in thread “main” java. lang.ArrayIndexOutOfBoundsException: 10 
at Homework1.processValues (Homework1. java:14) 
at Homework1.main(Homework1. java: 36) 


Quite a few students give up at that point, saying “it didn’t work”, or “my program died”, 
without reading the error message. Admittedly, the format of the exception report is not very 
friendly. But, with some practice, it is easy to decipher it. 


HOW TO 6.1 






Step 1 


6.5 Problem Solving: Adapting Algorithms 275 


There are two pieces of useful information: 


1. The name of the exception, such as ArrayIndexOutOfBoundsException 


2. The stack trace, that is, the method calls that led to the exception, such as 
Homework1. java:14 and Homework1. java: 36 in our example. 


The name of the exception is always in the first line of the report, and it ends in Exception. 
If you get an ArrayIndexOutOfBoundsException, then there was a problem with an invalid array 
index. That is useful information. 

To determine the line number of the offending code, look at the file names and line num- 
bers. The first line of the stack trace is the method that actually generated the exception. The 
last line of the stack trace is a line in main. In our example, the exception was caused by line 14 
of Homework1. java. Open up the file, go to that line, and look at it! Also look at the name of the 
exception. In most cases, these two pieces of information will make it completely obvious 
what went wrong, and you can easily fix your error. 

Sometimes, the exception was thrown by a method that is in the standard library. Here is a 
typical example: 


Exception in thread "main" java. lang.StringIndexOutOfBoundsException: String index 
out of range: -4 
at java. lang.String.substring(String.java:1444) 
at Homework2.main(Homework2.java:29) 


The exception happened in the substring method of the String class, but the real culprit is the 
first method in a file that you wrote. In this example, that is Homework2.main, and you should 
look at line 29 of Homework2. java. 


Working with Arrays 


In many data processing situations, you 
need to process a sequence of values. This 
How To walks you through the steps for 
storing input values in an array and carrying 
out computations with the array elements. 

Consider again the problem from Sec- 
tion 6.5: A final quiz score is computed by 
adding all the scores, except for the lowest 
one. For example, if the scores are 


of Sao 8.5 77 Ss oto 
then the final score is 50. 





Decompose your task into steps. 


You will usually want to break down your task into multiple steps, such as 
e Reading the data into an array. 

e Processing the data in one or more steps. 

e Displaying the results. 


When deciding how to process the data, you should be familiar with the array algorithms in 
Section 6.3. Most processing tasks can be solved by using one or more of these algorithms. 


276 Chapter6 Arrays and Array Lists 


Step 2 


Step 3 


Step 4 


In our sample problem, we will want to read the data. Then we will remove the minimum 
and compute the total. For example, if the input is 8 7 8.5 9.5 7 5 10, we will remove the mini- 
mum of 5, yielding 8 7 8.5 9.5 7 10. The sum of those values is the final score of 50. 

Thus, we have identified three steps: 


Read inputs. 
Remove the minimum. 
Calculate the sum. 


Determine which algorithm(s) you need. 


Sometimes, a step corresponds to exactly one of the basic array algorithms in Section 6.3. That 
is the case with calculating the sum (Section 6.3.2) and reading the inputs (Section 6.3.10). At 
other times, you need to combine several algorithms. To remove the minimum value, you can 
find the minimum value (Section 6.3.3), find its position (Section 6.3.5), and remove the ele- 
ment at that position (Section 6.3.6). 

We have now refined our plan as follows: 


Read inputs. 

Find the minimum. 
Find its position. 
Remove the minimum. 
Calculate the sum. 


This plan will work—see Section 6.5. But here is an alternate approach. It is easy to compute 
the sum and subtract the minimum. Then we don’t have to find its position. The revised plan is 


Read inputs. 

Find the minimum. 
Caleulate the sum. 
Subtract the minimum. 


Use methods to structure the program. 


Even though it may be possible to put all steps into the main method, this is rarely a good idea. 
It is better to make each processing step into a separate method. In our example, we will imple- 
ment three methods: 


@ readInputs 

© sum 

© minimum 

The main method simply calls these methods: 
double[] scores = readInputs(); 


double total = sum(scores) - minimum(scores); 
System.out.printIn("Final score: " + total); 


Assemble and test the program. 


Place your methods into a class. Review your code and check that you handle both normal 
and exceptional situations. What happens with an empty array? One that contains a single ele- 
ment? When no match is found? When there are multiple matches? Consider these boundary 
conditions and make sure that your program works correctly. 

In our example, it is impossible to compute the minimum if the array is empty. In that case, 
we should terminate the program with an error message before attempting to call the minimum 
method. 


6.5 Problem Solving: Adapting Algorithms 277 


What if the minimum value occurs more than once? That means that a student had more 
than one test with the same low score. We subtract only one of the occurrences of that low 
score, and that is the desired behavior. 

The following table shows test cases and their expected output: 


Test Case Expected Output Comment 
8 7 a5 Bos 7 3 10) 50 See Step 1. 
8779 24 Only one instance of the low score should be removed. 
8 0 After removing the low score, no score remains. 
(no inputs) Error That is nota legal input. 


Here’s the complete program (how_to_1/Scores. java): 


import java.util.Arrays; 
import java.util.Scanner; 


/[** 
This program computes a final score for a series of quiz scores: the sum after dropping 
the lowest score. The program uses arrays. 


¥/ 
public class Scores 
{ 
public static void main(String[] args) 
{ 
double[] scores = readInputs(); 
if (scores.length == 0) 
{ 
System.out.printInC"At least one score is required."); 
} 
else 
{ 
double total = sum(scores) - minimum(scores); 
System.out.printIn("Final score: " + total); 
} 
} 
/* * 
Reads a sequence of floating-point numbers. 
@return an array containing the numbers 
*/ 
public static double[] readInputs() 
{ 


// Read the input values into an array 


final int INITIAL_SIZE = 10; 
double[] inputs = new double[INITIAL_SIZE] ; 
System.out.printIn("Please enter values, Q to quit:"); 
Scanner in = new Scanner(System.in); 
int currentSize = 0; 
while (Cin.hasNextDouble()) 
{ 
// Grow the array if it has been completely filled 


278 Chapter6 Arrays and Array Lists 


if (currentSize >= inputs. length) 


{ 
inputs = Arrays.copyOf(inputs, 2 * inputs. length) ; 
} 
jnputs[currentSize] = in.nextDoubleQ; 
currentSize++; 
} 
return Arrays.copyOf(inputs, currentSize) ; 
} 
/** 


Computes the sum of the values in an array. 
@param values an array 
@return the sum of the values in values 
*/ 
public static double sum(double[] values) 
{ 
double total = 0; 
for (double element : values) 


{ 
total = total + element; 
} 
return total; 
} 
/** 


Gets the minimum value from an array. 
@param values an array of size >= 1 
@return the smallest element of values 
*/ 
public static double minimum(double[] values) 
{ 
double smallest = values[0]; 
for (int i = 1; 7 < values. length; i++) 


{ 
if (values[i] < smallest) 
{ 
smallest = values[i]; 
} 
} 
return smallest; 





WORKED EXAMPLE 6.1 Rolling the Dice 





Sia er 
+ This Worked Example shows how to analyze a set of die =  — 
tosses to see whether the die is “fair”. > - « 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 279 


6.6 Problem Solving: Discovering Algorithms by 
Manipulating Physical Obj 


ff, = In Section 6.5, you saw how to solve a problem by combining and adapting 
ae / known algorithms. But what do you do when none of the standard algorithms 
is sufficient for your task? In this section, you will learn a technique for dis- 
covering algorithms by manipulating physical objects. 
Consider the following task: You are given an array whose size is an even 
number, and you are to switch the first and the second half. For example, if the 
array contains the eight numbers 





Manipulating physical objects 


can give you ideas for Ea TES WZ) el IS 


discovering algorithms. 


then you should change it to 


171398 


Many students find it quite challenging to come up with an algorithm. They may 
know that a loop is required, and they may realize that elements should be inserted 
(Section 6.3.7) or swapped (Section 6.3.8), but they do not have sufficient intuition to 
draw diagrams, describe an algorithm, or write down pseudocode. 
(ee aeenucnuner One useful technique for discovering an algorithm is to manipulate physical 
coins, playing cards, objects. Start by lining up some objects to denote an array. Coins, playing cards, or 
or toys to visualize small toys are good choices. 
aliattaveclvalues: Here we arrange eight coins: 


©2026 e@ 
Ss As 


Now let’s step back and see what we can do to change the order of the coins. 
We can remove a coin (Section 6.3.6): 





Visualizing the 


removal of an 
array element S; 







We can insert a coin (Section 6.3.7): 


Visualizing the 


insertion of an rN j a) 
array element ve - Ni 2 





280 Chapter6 Arrays and Array Lists 


Or we can swap two coins (Section 6.3.8). 


Visualizing the 
swapping of 
two coins 





Go ahead—line up some coins and try out these three operations right now so that 
you get a feel for them. 

Now how does that help us with our problem, switching the first and the second 
half of the array? 

Let’s put the first coin into place, by swapping it with the fifth coin. However, as 
Java programmers, we will say that we swap the coins in positions 0 and 4: 





‘eece ee 


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





6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 281 


ONLINE EXAMPLE 


@ A program that 
implements the 
algorithm that 
switches the first 
and second halves 
of an array. 


You can use paper 
clips as position 
markers or counters. 





Now an algorithm is becoming apparent: 


i=0 
j=... (we'll think about that in a minute) 
While (don't know yet) 
Swap elements at positions i and j 
it* 


jet 


Where does the variable j start? When we have eight coins, the coin at position zero is 
moved to position 4. In general, it is moved to the middle of the array, or to position 
size / 2. 
And how many iterations do we make? We need to swap all coins in the first half. 
That is, we need to swap size / Z coins. The pseudocode is 
i-0 
jrsize/Z 
While (i < size / Z) 
Swap elements at positions i and j 
i*t* 


jet 


It is a good idea to make a walkthrough of the pseudocode (see Section 4.2). You can 
use paper clips to denote the positions of the variables i and j. If the walkthrough is 
successful, then we know that there was no “off-by-one” error in the pseudocode. 
Self Check 29 asks you to carry out the walkthrough, and Exercise P6.8 asks you to 
translate the pseudocode to Java. Exercise R6.28 suggests a different algorithm for 
switching the two halves of an array, by repeatedly removing and inserting coins. 

Many people find that the manipulation of physical objects is less intimidating 
than drawing diagrams or mentally envisioning algorithms. Give it a try when you 
need to design a new algorithm! 


29. Walk through the algorithm that we developed in this section, using two paper 
clips to indicate the positions for i and j. Explain why there are no bounds errors 
in the pseudocode. 


30. Take out some coins and simulate the following pseudocode, using two paper 
clips to indicate the positions for iand j. 


i=0 
j=size- 1 
While (i < j) 


Swap elements at positions i and j 
it* 
j-- 

What does the algorithm do? 

31. Consider the task of rearranging all elements in an array so that the even num- 
bers come first. Otherwise, the order doesn’t matter. For example, the array 
14142135 6 23 
could be rearranged to 
42146153231 


282 Chapter6 Arrays and Array Lists 


Using coins and paperclips, discover an algorithm that solves this task by 
swapping elements, then describe it in pseudocode. 


32. Discover an algorithm for the task of Self Check 31 that uses removal and 
insertion of elements instead of swapping. 


33. Consider the algorithm in Section 4.7.4 that finds the 
largest element in a sequence of inputs —zot the largest 
element in an array. Why is this algorithm better visual- 
ized by picking playing cards from a deck rather than 
arranging toy soldiers in a sequence? 





Practice It Now you cantry these exercises at the end of the chapter: R6.28, R6.29, P6.8. 


VIDEO EXAMPLE 6.1 Removing Duplicates from an Array 


AT In this Video Example, we will discover an algorithm for removing duplicates from an array. 


./ Two-Dimensional Arr 


It often happens that you want to store 
collections of values that have a two- 
dimensional layout. Such data sets com- 
monly occur in financial and scientific 
applications. An arrangement consisting 
of rows and columns of values is called a 
two-dimensional array, or a matrix. 

Let’s explore how to store the example 
data shown in Figure 12: the medal counts 
of the figure skating competitions at the 
2010 Winter Olympics. 








Gold Silver Bronze 
Canada 1 0 1 
China 1 1 0 
Germany 0 0 1 
Korea 1 0 0 
Japan 0 1 1 
Russia 0 1 1 
United States 1 1 0 





= Figure 12 Figure Skating Medal Counts 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


6.7 Two-Dimensional Arrays 283 


6.7.1 Declaring Two-Dimensional Arrays 


In Java, you obtain a two-dimensional array by supplying the number of rows and 
Use a two- - : : 
dimensional array to columns. For example, new int[7][3] is an array with seven rows and three columns. 
store tabular data. You store a reference to such an array ina variable of type int[][]. Here is a complete 
declaration of a two-dimensional array, suitable for holding our medal count data: 
final int COUNTRIES = 7; 


final int MEDALS = 3; 
int{][] counts = new int [COUNTRIES] [MEDALS]; 


Alternatively, you can declare and initialize the array by grouping each row: 


int[{][] counts = 


{ 


AAA AAS 
POOrRPORPF 
PRROOrR SA 
ORPRFPOROR 
an ana anon o 


hs 
As with one-dimensional arrays, you cannot change the size of a two-dimensional 
array once it has been declared. 


Syntax 6.3 Two-Dimensional Array Declaration 
Number of rows 
Name Element type vA Numberof columns 
\ a 


double[][] tableEntries = new double[7] [3]; 
All values are initialized with 0. 


Name 


Set des List of initial values 


10, 11, 8 }, 


, 6 
roe 





6.7.2 Accessing Elements 


ae To access a particular element in the two-dimensional array, you need to specify two 
Individual elements : : ; j 
i) a iwo-ehinacasiainel index values in separate brackets to select the row and column, respectively (see Fig- 


array are accessed by ure 13): 
using two index . 
values, arrayli][j]. int medalCount = counts[3][1]; 


284 Chapter6 Arrays and Array Lists 


To access all elements in a two-dimensional array, you use two nested loops. For 
example, the following loop prints all elements of counts: 


for (int i = 0; i < COUNTRIES; i++) 








{ 
// Process the ith row 
for (int j = 0; j < MEDALS; j++) 
{ 
// Process the jth column in the ith row 
System.out.printf("%8d", counts[i][j]); 
} 
System.out.printInQ; // Start a new line at the end of the row 
} 
Column index 
(O](1IL2] 
( [0] 
[1] 
3 [2] counts [3] [1] 
lao} Li 
4. 31 
Be B 
Figure 13 ma [4] 
Accessing an Element ina [5] 
Two-Dimensional Array _ [6] 


6.7.3 Locating Neighboring Elements 


Some programs that work with two-dimensional arrays need to locate the elements 
that are adjacent to an element. This task is particularly common in games. Figure 14 
shows how to compute the index values of the neighbors of an element. 

For example, the neighbors of counts[3][1] to the left and right are counts[3][0] and 
counts [3] [2]. The neighbors to the top and bottom are counts[2][1] and counts[4][1]. 

You need to be careful about computing neighbors at the boundary of the array. 
For example, counts[0][1] has no neighbor to the top. Consider the task of computing 
the sum of the neighbors to the top and bottom of the element count[i][j]. You need 
to check whether the element is located at the top or bottom of the array: 

int total = 0; 

if Gi > 0) { total = total + counts[i - 1][j]; } 

if Gi < ROWS - 1) { total = total + counts[i + 1][j]; } 


Ci = 20llis) = eh = SIC) = LIN te) a by 


vile = fi(3] fifj + 1 


Figure 14 tie i) = yi a) ey ay 
Neighboring Locations ina 
Two-Dimensional Array 


6.7 Two-Dimensional Arrays 285 


6.7.4 Computing Row and Column Totals 


A common task is to compute row or column totals. In our example, the row totals 
give us the total number of medals won by a particular country. 

Finding the right index values is a bit tricky, and it is a good idea to make a quick 
sketch. To compute the total of row i, we need to visit the following elements: 


0 MEDALS - 1 


row i— [i][0] [J[1] [i] [2] 


As you can see, we need to compute the sum of counts[i][j], where j ranges from 0 to 
MEDALS - 1. The following loop computes the total: 


int total = 0; 
for (int j = 0; j < MEDALS; j++) 
{ 


} 


Computing column totals is similar. Form the sum of counts[i][j], where i ranges 
from 0 to COUNTRIES - 1. 


total = total + counts[i][jl]; 





hin int total = 0; 
ANIMATION for (int i = 0; i < COUNTRIES; i++) 
Tracing a Nested { 
Loop in a 2D Array total = total + counts[i][j]; 


[yA 


column j 


[01 [3] ——0 
[1] [3] 
[2] [3] 
[3](3] 
[4] [3] 
[5] [3] 


[6] [3] -— COUNTRIES - 1 








286 Chapter6 Arrays and Array Lists 


6.7.5 Two-Dimensional Array Parameters 


When you pass a two-dimensional array to a method, you will want to recover the 
dimensions of the array. If values is a two-dimensional array, then 


© values. length is the number of rows. 


© values[0].length is the number of columns. (See Special Topic 6.4 for an explana- 
tion of this expression.) 


For example, the following method computes the sum of all elements in a two- 
dimensional array: 


public static int sum(int[][] values) 


{ 
int total = 0; 
for (int i = 0; i < values.length; i++) 
{ 
for Cint j = 0; j < values[0].length; j++) 
total = total + values[i][j]; 
} 
} 
return total; 
} 


Working with two-dimensional arrays is illustrated in the following program. The 
program prints out the medal counts and the row totals. 


section_7/Medals.java 
[** 


This program prints a table of medal winner counts with row totals. 


1 

2 

3 * 

4 public class Medals 

> a 

6 public static void main(String[] args) 
7 

8 

9 


{ 

final int COUNTRIES = 

final int MEDALS = 
10 
11 String[] countries = 
12 
13 "Canada", 
14 "China", 
15 "Germany", 
16 "Korea", 
17 "Japan", 
18 "Russia", 
19 "United States" 
20 3 
21 
22 int({][] counts = 
23 { 
24 4 0%, 
25 { 1, 1, 0 }, 
26 4.0;. 0; Tbs 
27 { 1,0, 0}; 
28 <0; 4; a, 
29 405. 2, de 
30 { 4, 2,0 4 





6.7 Two-Dimensional Arrays 287 


Fi 
System.out.printin¢" Country Gold Silver Bronze Total"); 


// Print countries, counts, and row totals 

for (int i = 0; i < COUNTRIES; i++) 

{ 
// Process the ith row 
System.out.printf('%15s", countries[i]); 


int total = 0; 


// Print each row element and update the row total 
for Cint j = 0; j < MEDALS; j++) 
{ 

System.out.printf('%8d", counts[i][j]); 

total = total + counts[i][j]; 


} 


// Display the row total and print a new line 
System.out.printf("%8d\n", total); 


Program Run 


34. 
35. 


36. 


37. 


38. 


Country Gold Silver Bronze Total 


Canada i 0 als 2 

China 1 ils 0 2 
Germany 0 0 1 dl 

Korea il 0 0 il 

Japan 0 a dl 2 

Russia 0 1 1 2 

United States il al 0 2 


What results do you get if you total the columns in our sample data? 
Consider an 8 x 8 array for a board game: 
int({][] board = new int[8][8]; 


Using two nested loops, initialize the board so that zeroes and ones alternate, as 
ona checkerboard: 


Oro 
ROR 
Oro 
FOR 
OrRO 
FOR 
OHO 
ROR 


10101010 
Hint: Check whether i + j is even. 
Declare a two-dimensional array for representing a tic-tac-toe board. The board 


has three rows and columns and contains strings "x", "o", and" ". 

Write an assignment statement to place an "x" in the upper-right corner of the 
tic-tac-toe board in Self Check 36. 

Which elements are on the diagonal joining the upper-left and the lower-right 
corners of the tic-tac-toe board in Self Check 36? 


288 Chapter6 Arrays and Array Lists 


Practice It 


Now you can try these exercises at the end of the chapter: R6.30, P6.18, P6.19. 


WORKED EXAMPLE 6.2 A World Population Table 


a” 





This Worked Example shows how to print world population data in a table with row and col- 
umn headers, and with totals for each of the data columns. 


Special Topic 6.4 Two-Dimensional Arrays with Variable Row Lengths 


4 


When you declare a two-dimensional array with the command 
int[][] a = new int[3][3]; 
then you get a3 x 3 matrix that can store 9 elements: 
a[0][0] a[0][1] a[0][2] 
a[1][0] al1][1] afi] [2] 
a[2][0] al2][1] a{2][2] 
In this matrix, all rows have the same length. 
In Java it is possible to declare arrays in which the row length varies. For example, you can 
store an array that has a triangular shape, such as: 
b[0] [0] 
b[1][0] b[1] [1] 
b[2][0] b{2][1] b{2][2] 
To allocate such an array, you must work harder. First, you allocate space to hold three rows. 
Indicate that you will manually set each row by leaving the second array index empty: 
double[][] b = new double[3][]; 
Then allocate each row separately (see Figure 15): 


for (int i = 0; 7 < b.length; i++) 
{ 

b[i] = new double[i + 1]; 
} 


You can access each array element as b[i][j]. The expression b[i] selects the ith row, and the 
[j] operator selects the jth element in that row. 


(b= —~, (Geter) 








Figure 15 A Triangular Array 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


Sy eX-\elf-1 im Ke) 0) oll ois) 








An array list stores 
a sequence of 
values whose 

size can change. 


6.8 Array Lists 289 


Note that the number of rows is b. length, and the length of the ith row is b[i]. length. For 
example, the following pair of loops prints a ragged array: 


for Cint i = 0; 7 < b.length; i++) 

; for (int j = 0; j < bli].length; j++) 
: System.out.print(b[i][j]); 
ee «printing; 

} 


Alternatively, you can use two enhanced for loops: 
for (double[] row : b) 


{ 
for (double element : row) 
{ 
System.out.print(element) ; 
} 
System.out.printInQ; 
} 


Naturally, such “ragged” arrays are not very common. 

Java implements plain two-dimensional arrays in exactly the same way as ragged arrays: 
as arrays of one-dimensional arrays. The expression new int[3][3] automatically allocates an 
array of three rows, and three arrays for the rows’ contents. 


Multidimensional Arrays 
You can declare arrays with more than two dimensions. For example, here is a three-dimen- 
sional array: 
int{][][] rubiksCube = new int[3][3][3]; 
Each array element is specified by three index values: 
rubiksCube [i] [j] Lk] 


When you write a program that collects inputs, you 
don’t always know how many inputs you will have. 
In such a situation, an array list offers two significant 
advantages: 


e Array lists can grow and shrink as needed. 
e The ArrayList class supplies methods for common 
tasks, such as inserting and removing elements. 


In the following sections, you will learn how to work 
with array lists. 





An array list expands to hold as many elements as needed. 


290 Chapter6 Arrays and Array Lists 


Syntax 6.4 Array Lists 





Syntax To construct an array list: new ArrayList<typeName>() 


To access an element: arraylistReference .get (index) 


arraylistReference.set(index, value) 


Variable name An array list object of size 0 


Variable type 
\ 


ArrayList<String> friends = new ArrayList<String>Q; 


The add method 
appends an element to the array list, 
increasing its size. 


friends.add ("Cindy") ; 
String name = friends.get(i); 


Use the friends.set(i, "Harry"); 


get and set methods 
to access an element. 
The index must be = 0 and < friends.size(). 


6.8.1 Declaring and Using Array Lists 





The ArrayList class 
is a generic class: 
ArrayList<Type> 
collects elements of 
the specified type. 


1) Before add 


ee eee 
oe er 


The following statement declares an array list of strings: 
ArrayList<String> names = new ArrayList<String>(); 


The ArrayList class is contained in the java.util package. In order to use array lists in 
your program, you need to use the statement import java.util ArrayList. 

The type ArrayList<String> denotes an array list of String elements. The angle 
brackets around the String type tell you that String is a type parameter. You can 
replace String with any other class and get a different array list type. For that reason, 
ArrayList is called a generic class. However, you cannot use primitive types as type 
parameters —there is no ArrayList<int> or ArrayList<double>. Section 6.8.5 shows how 
you can collect numbers in an array list. 

It is a common error to forget the initialization: 


ArrayList<String> names; 
names.add("Harry"); // Error—names not initialized 


Here is the proper initialization: 
ArrayList<String> names = new ArrayList<String>(); 


Note the () after new ArrayList<String> on the right-hand side of the initialization. It 
indicates that the constructor of the ArrayList<String> class is being called. We will 
discuss constructors in Chapter 8. 








Size increased 


3 
| New element 
J 


added at end 








Figure 16 Adding an Element with add 


Use the size method 
to obtain the current 
size of an array list. 


Use the get and set 
methods to access an 
array list element ata 
given index. 





An array list has 
methods for adding 
and removing ele- 
ments in the middle. 


Figure 17 
Adding and 
Removing 
Elements in the 
Middle of an 
Array List 


6.8 Array Lists 291 


When the ArrayList<String> is first constructed, it has size 0. You use the add method 
to add an element to the end of the array list. 
names.add("Emily"); // Now names has size 1 and element "Emily" 


names.add("Bob"); // Now names has size 2 and elements "Emily", "Bob" 
names.add("Cindy"); // names has size 3 and elements "Emily", "Bob", and "Cindy" 


The size increases after each call to add (see Figure 16). The size method yields the 
current size of the array list. 

To obtain an array list element, use the get method, not the [] operator. As with 
arrays, index values start at 0. For example, names. get (2) retrieves the name with index 
2, the third element in the array list: 


String name = names.get(2); 


As with arrays, it is an error to access a nonexistent element. A very common bounds 
error is to use the following: 

int i = names.sizeQ; 

name = names.get(i); // Error 
The last valid index is names.sizeQ) - 1. 

To set an array list element to a new value, use the set method. 


names.set(2, "Carolyn"); 


This call sets position 2 of the names array list to "Carolyn", overwriting whatever value 
was there before. 

The set method overwrites existing values. It is different from the add method, 
which adds a new element to the array list. 

You can insert an element in the middle of an array list. For example, the call names. 
add(1, "Ann") adds a new element at position 1 and moves all elements with index 1 or 
larger by one position. After each call to the add method, the size of the array list 
increases by 1 (see Figure 17). 





® After names.add(1, "Ann") 
New element 
names = = ——“_ added at index 1 


Moved from index 1 to 2 





Moved from index 2 to 3 


(3) After names. remove(1) 


names = 7 Moved from index 2 to 1 


Moved from index 3 to 2 


292 Chapter6 Arrays and Array Lists 


Conversely, the remove method removes the element at a given position, moves all 


Use the add and oe ‘ 
PN aire reltG elements after the removed element down by one position, and reduces the size of the 
add and remove array list by 1. Part 3 of Figure 17 illustrates the result of names. remove(1). 


SUSY Uist clerne ne: With an array list, it is very easy to get a quick printout. Simply pass the array list 
to the printIn method: 


System.out.printIn(names); // Prints [Emily, Bob, Carolyn] 


6.8.2 Using the Enhanced for Loop with Array Lists 


You can use the enhanced for loop to visit all elements of an array list. For example, 
the following loop prints all names: 


ArrayList<String> names =... ; 
for (String name : names) 


{ 
} 


This loop is equivalent to the following basic for loop: 


System.out.printIn(name) ; 


for (int i = 0; i < names.sizeQ); i++) 


{ 
String name = names.get(i); 
System.out.printIn(name) ; 
} 
Table 2 Working with Array Lists 
ArrayList<String> names = new ArrayList<String>Q; Constructs an empty array list that can 
hold strings. 
names.add("Ann") ; Adds elements to the end. 
names.add("Cindy") ; 
System.out.printIn(names) ; Prints [Ann, Cindy]. 
names.add(1, "Bob"); Inserts an element at index 1. 


names is now [Ann, Bob, Cindy]. 


names. remove(0); Removes the element at index 0. 
names is now [Bob, Cindy]. 


names.set(0, "Bi11"); Replaces an element with a different value. 
names is now [Bill, Cindy]. 


String name = names.get(i); Gets an element. 


String last = names.get(names.size() - 1); Gets the last element. 


ArrayList<Integer> squares = new ArrayList<Integer>(); | Constructs an array list holding the first 
for Cint 1 = 0; i < 10; i++) ten squares. 
{ 


squares.add(i * i); 


6.8 Array Lists 293 


6.8.3 Copying Array Lists 














As with arrays, you need to remember that array list variables hold references. Copy- 
ing the reference yields two references to the same array list (see Figure 18). 
ArrayList<String> friends = names; 
friends.add("Harry") ; 


Now both names and friends reference the same array list to which the string "Harry" 
was added. 

If you want to make a copy of an array list, construct the copy and pass the original 
list into the constructor: 


ArrayList<String> newNames = new ArrayList<String>(names) ; 





Figure 18 Copying an Array List Reference 


6.8.4 Array Lists and Methods 


Like arrays, array lists can be method arguments and return values. Here is an exam- 
ple: a method that receives a list of strings and returns the reversed list. 


public static ArrayList<String> reverse(ArrayList<String> names) 


{ 
// Allocate a list to hold the method result 
ArrayList<String> result = new ArrayList<String>(); 
// Traverse the names list in reverse order, starting with the last element 
for (int i = names.sizeQ) - 1; 7 >= 0; i--) 
// Add each name to the result 
result.add(names.get(i)); 
} 
return result; 
} 


If this method is called with an array list containing the names Emily, Bob, Cindy, it 
returns a new array list with the names Cindy, Bob, Emily. 


6.8.5 Wrappers and Auto-boxing 





In Java, you cannot directly insert primitive type values—numbers, characters, or 
To collect numbers in : : : 
array lists, you must boolean values—into array lists. For example, you cannot form an ArrayList<double>. 
use wrapper classes. Instead, you must use one of the wrapper classes shown in the following table. 


294 Chapter6 Arrays and Array Lists 


Primitive Type Wrapper Class 


byte Byte 
boolean Boolean 
char Character 
double Double 
Float Float 
int Integer 
long Long 
short Short 


For example, to collect double values in an array list, you use an ArrayList<Double>. 
Note that the wrapper class names start with uppercase letters, and that two of them 
differ from the names of the corresponding primitive type: Integer and Character. 

Conversion between primitive types and the corresponding wrapper classes is 
automatic. This process is called auto-boxing (even though auto-wrapping would 
have been more consistent). 

For example, if you assign a double value to a Double variable, the number is auto- 
matically “put into a box” (see Figure 19). 


Double wrapper = 29.95; 
Conversely, wrapper values are automatically “unboxed” to primitive types. 
double x = wrapper; 


Because boxing and unboxing is automatic, you don’t need to think about it. Simply 
remember to use the wrapper type when you declare array lists of numbers. From 
then on, use the primitive type and rely on auto-boxing. 

ArrayList<Double> values = new ArrayList<Double>(); 


values.add(29.95); 
double x = values.get(0); 





Figure 19 A Wrapper Class Variable 


Like truffles that must be in a wrapper to be sold, 
a number must be placed in a wrapper to be stored in an array list. 





6.8 Array Lists 295 


6.8.6 Using Array Algorithms with Array Lists 


The array algorithms in Section 6.3 can be converted to array lists simply by using the 
array list methods instead of the array syntax (see Table 3 on page 297). For example, this 
code snippet finds the largest element in an array: 


double largest = values[0]; 
for (int i = 1; i < values.length; i++) 


if (values[i] > largest) 
{ 


largest = values[i]; 
} 
} 


Here is the same algorithm, now using an array list: 


double largest = values.get(0); 
for (int i = 1; 7 < values.size(); i++) 


if (values.get(i) > largest) 
{ 


largest = values.get(i); 
} 
} 


6.8.7 Storing Input Values in an Array List 


When you collect an unknown number of inputs, array lists are much easier to use 
than arrays. Simply read inputs and add them to an array list: 


ArrayList<Double> inputs = new ArrayList<Double>(); 
while (in.hasNextDouble()) 


jinputs.add(in.nextDoubleQ); 


} 


6.8.8 Removing Matches 


It is easy to remove elements from an array list, by calling the remove method. A com- 

mon processing task is to remove all elements that match a particular condition. Sup- 

pose, for example, that we want to remove all strings of length < 4 from an array list. 
Of course, you traverse the array list and look for matching elements: 


ArrayList<String> words = ...; 
for (int i = 0; i < words.size(Q); i++) 
{ 

String word = words.get(i); 

if (word.lengthQ) < 4) 


Remove the element at index i. 
} 
t 
But there is a subtle problem. After you remove the element, the for loop increments 
i, skipping past the ext element. 


296 Chapter6 Arrays and Array Lists 


ONLINE EXAMPLE 
+) A version of the 


Scores program 
using an array list. 


Consider this concrete example, where words sale the strings "Welcome", "to", 
"the", "island!". When i is 1, we remove the word "to" at index 1. Then i is incre- 
mented to 2, and the word "the", which is now at ne 1, is never examined. 

















We should not increment the index when removing a word. The appropriate pseudo- 
code is 


If the element at index i matches the condition 
Remove the element. 

Else 
Increment i. 


Because we don’t always increment the index, a for loop is not appropriate for this 
algorithm. Instead, use a while loop: 
int i = 0; 
while (i < words.size(Q)) 
{ 
String word = words.get(i); 
if (word.lengthQ < 4) 
{ 


} 
else 


{ 
} 


words.remove(i); 


j++; 


6.8.9 Choosing Between Array Lists and Arrays 


For most programming tasks, array lists are easier to use than arrays. Array lists can 
grow and shrink. On the other hand, arrays have a nicer syntax for element access and 
initialization. 

Which of the two should you choose? Here are some recommendations. 


e Ifthe size of a collection never changes, use an array. 


e Ifyou collect a long sequence of primitive type values and you are concerned 
about efficiency, use an array. 


e Otherwise, use an array list. 
The following program shows how to mark the largest value in a sequence of values. 


This program uses an array list. Note how the program is an improvement over the 
array versionon page 265. This programcan process input sequences ofarbitrary length. 


6.8 Array Lists 297 


Table 3 Comparing Array and Array List Operations 


Operation Arrays 


Get an element. xX = values[4]; 


Replace an element. values[4] = 35; 


Number of elements. values. length 


currentSize 
(companion variable, see 
Section 6.1.3) 


Number of filled elements. 


Remove an element. See Section 6.3.6 


Add an element, growing See Section 6.3.7 


the collection. 


Initializing a collection. int[] values = { 1, 4, 9 }; 


section_8/LargestinArrayList.java 


1 import java.util.ArrayList; 
2 import java.util.Scanner; 


/* * 


Array Lists 
x = values.get(4) 
values.set(4, 35); 
values.size() 


values.size() 
values.remove(4); 
values.add(35); 


No initializer list syntax; 
call add three times. 


This program reads a sequence of values and prints them, marking the largest value. 


3 
4 
5 
6 
7 public class LargestInArrayList 
8 
9 
10 


{ 

public static void main(String[] args) 

{ 
11 ArrayList<Double> values = new ArrayList<Double>() ; 
12 
13 // Read inputs 
14 
15 System.out.printIn("Please enter values, Q to quit:"); 
16 Scanner in = new Scanner(System. in) ; 
17 while Cin.hasNextDouble()) 
18 { 
19 values.add(in.nextDouble()); 
20 } 
21 
22 // Find the largest value 
23 
24 double largest = values.get(0); 
25 for (int i = 1; 7 < values.sizeQ); i++) 
26 { 
27 if (values.get(i) > largest) 
28 { 
29 largest = values.get(i); 
30 } 
31 } 
32 
33 // Print all values, marking the largest 


298 Chapter6 Arrays and Array Lists 


for (double element : values) 


System.out.print(element) ; 
if (element == largest) 


{ 
} 


System.out.printInQ; 


System.out.print(" <== largest value"); 


Program Run 


39. 


40. 





41. 


42. 


43. 


44. 


Please enter values, Q to quit: 
35 80 115 44.5 Q 

35 

80 

115 <== largest value 

44.5 


Declare an array list primes of integers that contains the first five prime numbers 
(2, 3, 5, 7, and 11). 

Given the array list primes declared in Self Check 39, write a loop to print its ele- 
ments in reverse order, starting with the last element. 


What does the array list names contain after the following statements? 


ArrayList<String> names = new ArrayList<String>; 
names.add("Bob"); 

names.add(0, "Ann"); 

names.remove(1); 

names.add("Cal"); 


What is wrong with this code snippet? 


ArrayList<String> names; 
names .add(Bob) ; 
Consider this method that appends the elements of one array list to another. 


public static void append(ArrayList<String> target, ArrayList<String> source) 


{ 
for (int i = 0; i < source.size(); i++) 


{ 
} 


target.add(source.get(i)); 


} 
What are the contents of names1 and names2 after these statements? 


ArrayList<String> namesl = new ArrayList<String>(Q ; 
names1.add("Emi ly"); 

names1.add("Bob"); 

namesl.add("Cindy") ; 

ArrayList<String> names2 = new ArrayList<String>() ; 
names2.add("Dave"); 

append(names1, names2); 


Suppose you want to store the names of the weekdays. Should you use an array 
list or an array of seven strings? 


6.8 Array Lists 299 


45. The section_8 directory of your source code contains an alternate implementa- 
tion of the problem solution in How To 6.1 on page 275. Compare the array and 
array list implementations. What is the primary advantage of the latter? 


Practice It Now youcantry these exercises at the end of the chapter: R6.10, R6.34, P6.21, 
P6.23. 


Common Error 6.4 Length and Size 


Unfortunately, the Java syntax for determining the number of elements in an array, an array 
list, and a string is not at all consistent. 


DataType Number of Elements 


Array a. length 
Array list a.size() 
String a. lengthQ 


It is a common error to confuse these. You just have to remember the correct syntax for every 
data type. 


The Diamond Syntax in Java 7 


SY of-\elf- Ke) 0] el oF) 





Java 7 introduces a convenient syntax enhancement for declaring array lists and other generic 
classes. In a statement that declares and constructs an array list, you need not repeat the type 
parameter in the constructor. That is, you can write 


ArrayList<String> names = new ArrayList<>(); 
instead of 


ArrayList<String> names = new ArrayList<String>Q; 





This shortcut is called the “diamond syntax” because the empty brackets < look like a dia- 
mond shape. 


VIDEO EXAMPLE 6.2 Game of Life 


(Tow Conway’s Game of Life simulates the growth of a population, 
PLUS 


using only two simple rules. This Video Example shows you how 
to implement this famous “game”. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


300 Chapter6 Arrays and Array Lists 


Use arrays for collecting values. 


rere) a e Anarray collects a sequence of values of the same type. 
\ ie ¢ Individual elements in an array are accessed by an integer index i, using the 
notation array([il. 
e Anarray element can be used like any variable. 


e Anarray index must be at least zero and less than the size of the array. 

¢ A bounds error, which occurs if you supply an invalid array index, can cause your 
program to terminate. 

¢ Use the expression array.length to find the number of elements in an 
array. 

e Anarray reference specifies the location of an array. Copying the 
reference yields a second reference to the same array. 


¢ With a partially filled array, keep a companion variable for the 
current size. 


Eur 


Know when to use the enhanced for loop. 


¢ You can use the enhanced for loop to visit all elements of an array. 
© Use the enhanced for loop if you do not need the index values in the loop body. 


Know and use common array algorithms. 


¢ When separating elements, don’t place a separator before the first element. 
e A linear search inspects elements in sequence until a match is found. 


¢ Before inserting an element, move elements to the end of the array starting with 
the last one. 





¢ Use a temporary variable when swapping two elements. 
¢ Use the Arrays.copyOf method to copy the elements of an array into a new array. 


Implement methods that process arrays. 
e Arrays can occur as method arguments and return values. 
Combine and adapt algorithms for solving a programming problem. 


¢ By combining fundamental algorithms, you can solve complex programming 
tasks. 


¢ You should be familiar with the implementation of fundamental algorithms so 
that you can adapt them. 


Discover algorithms by manipulating physical objects. 


—— vi 77 ‘iA ¢ Use a sequence of coins, playing cards, or toys to visualize an array of values. 


thittiict& ¢ You can use paper clips as position markers or counters. 


Review Exercises 301 


Use two-dimensional arrays for data that is arranged in rows and columns. 


¢ Use atwo-dimensional array to store tabular data. 


¢ Individual elements in a two-dimensional array are 
accessed by using two index values, array[i] [i]. 





Use array lists for managing collections whose size can change. 


e Anarray list stores a sequence of values whose size can change. 


¢ The ArrayList class is a generic class: ArrayList<Type> collects elements of the 
specified type. 


¢ Use the size method to obtain the current size of an array list. 


© Use the get and set methods to access an array list element 
at a given index. 

¢ Use the add and remove methods to add and remove array 
list elements. 


¢ To collect numbers in array lists, you must use wrapper 
classes. 








java. lang.Boolean java.util.ArrayList<E> 
java. lang.Double add 
java. lang. Integer get 
java.util.Arrays remove 

copyOf set 

toString size 


n# R6.1 Write code that fills an array values with each set of numbers below. 
a. 1 2 3 4 5 6 7 8 9 10 


b. 0 2 4 6 8 10 12 14 16 18 20 
c. | 4 9 16 25 36 49 64 81 100 
d.0 0 0 0 0 0 0 0 0 0 

e. 1 4 9 16 9 z 4 9 11 

f. 0 1 0 1 0 1 0 1 0 1 

g.0 1 2 3 4 0 1 2 3 4 


302 Chapter6 Arrays and Array Lists 


##R6.2 Consider the following array: 
int[] a= { I, 2, 35 4, 55 4, 3% 2, 1, 0 ie 
What is the value of total after the following loops complete? 


a. int total = 0; 
for (int i = 0; i < 10; i++) { total = total + a[i]; } 


b. int total = 0 


for (int i = i < 10; i =i1+ 2) { total = total + ali]; } 
c. int total = 0; 

for (int i = 1; i < 10; i = i + 2) { total = total + afi]; } 
d. int total = 0; 

for (int i = 2; i <= 10; i++) { total = total + ali]; } 
e. int total = 0; 

for (int i = 1; i < 10; i = 2 * i) { total = total + afi]; } 
f. int total = 0; 

for (int i = 9; i >= 0; i--) { total = total + a[i]; } 
g. int total = 0; 

for (int i = 9; i >= 0; 1 =i - 2) { total = total + afi]; } 
h. int total = 0; 

for (int i = 0; i < 10; i++) { total = a[i] - total; } 


«= R6.3 Consider the following array: 
int{] a={1, 2, 3, 4, 5, 4, 3, 2, 1, 0 }; 
What are the contents of the array a after the following loops complete? 
a. for (int 7 = 1; i < 10; i++) { afi] = ali - 1]; } 
b. for Cint i = 9; i > 0; i--) { a[i] = ali - 1]; } 
c. for (int 1 = 0; i < 9; i++) { a[i] = ali+ 1]; } 
d. for (int i = 8; i >= 0; i--) { a[i] = ali +1]; } 
e. for (int i = 1; i < 10; i++) { ali] = ali] + afi - 1]; } 
f. for CGint i =1; i < 10; i = i+ 2) { a[i] =0; } 
g- for (int 1 = 0; i < 5; i++) { ali + 5] = ali]; } 
h. for Gint i = 1; 1 < 5; i++) { a[i] = a[9 - i]; } 
na2R6.4 Write a loop that fills an array values with ten random numbers between 1 and 100. 


Write code for two nested loops that fill values with ten different random numbers 
between 1 and 100. 


##R6.5 Write Java code for a loop that simultaneously computes both the maximum and 
minimum of an array. 


» R6.6 What is wrong with each of the following code segments? 


a. int[] values = new int[10]; 
for (int i = 1; i <= 10; i++) 


{ 
} 


b. int[] values; 
for (int i = 0; i < values.length; i++) 


{ 
} 


values[i] VF 18 


values[i] 1 


Review Exercises 303 


«= R6.7 Write enhanced for loops for the following tasks. 


ua R6.8 


ue R69 


= R6.10 


= R6.11 


= R612 


= R6.13 


=o R6.14 


= R615 


a. Printing all elements of an array ina single row, separated by spaces. 
b. Computing the product of all elements in an array. 


c. Counting how many elements in an array are negative. 


Rewrite the following loops without using the enhanced for loop construct. Here, 
values is an array of floating-point numbers. 
a. for (double x : values) { total = total + x; } 
b. for (double x : values) { if (x == target) { return true; } } 
c. int i = 0; 
for (double x : values) { values[i] = 2 * x; i++; } 


Rewrite the following loops, using the enhanced for loop construct. Here, values is 
an array of floating-point numbers. 

a. for (int i = 0; 7 < values.length; i++) { total = total + values[i]; } 

b. for (int i = 1; i < values.length; i++) { total = total + values[i]; } 

c. for (int i = 0; i < values.length; i++) 


if (values[i] == target) { return i; } 


} 


What is wrong with each of the following code segments? 


a. ArrayList<int> values = new ArrayList<int>(); 
b. ArrayList<Integer> values = new ArrayListQ); 
c. ArrayList<Integer> values = new ArrayList<Integer>; 
d. ArrayList<Integer> values = new ArrayList<Integer>(); 
for (int 1 = 1; i <= 10; i++) 
: values.set(i - 1, i * i); 


} 

e. ArrayList<Integer> values; 
for (int i = 1; i <= 10; i++) 
{ 


values.add(i * i); 


} 


What is an index of an array? What are the legal index values? What is a bounds 
error? 


Write a program that contains a bounds error. Run the program. What happens on 
your computer? 


Write a loop that reads ten numbers and a second loop that displays them in the 
opposite order from which they were entered. 


Trace the flow of the linear search loop in Section 6.3.5, where values contains the 
elements 80 90 100 120 110. Show two columns, for pos and found. Repeat the trace 
when values contains 80 90 100 70. 


Trace both mechanisms for removing an element described in Section 6.3.6. Use an 
array values with elements 110 90 100 120 80, and remove the element at index 2. 


304 Chapter6 Arrays and Array Lists 


oe R6.16 


= R6.17 


= R6.18 


= R6.19 


ua R6.20 


ua R6.21 


ue R6.22 


ue R6.23 


une R6.24 


For the operations on partially filled arrays below, provide the header of a method. 
Do not implement the methods. 


a. Sort the elements in decreasing order. 

b. Print all elements, separated by a given string. 

c. Count how many elements are less than a given value. 
d. Remove all elements that are less than a given value. 


e. Place all elements that are less than a given value in another array. 


Trace the flow of the loop in Section 6.3.4 with the given example. Show two col- 
umns, one with the value of i and one with the output. 


Consider the following loop for collecting all elements that match a condition; in 
this case, that the element is larger than 100. 


ArrayList<Double> matches = new ArrayList<Double>(); 
for (double element : values) 


{ 
if (element > 100) 
{ 
matches.add(element) ; 
} 
} 


Trace the flow of the loop, where values contains the elements 110 90 100 120 80. 
Show two columns, for element and matches. 


Trace the flow of the loop in Section 6.3.5, where values contains the elements 80 
90 100 120 110. Show two columns, for pos and found. Repeat the trace when values 
contains the elements 80 90 120 70. 


Trace the algorithm for removing an element described in Section 6.3.6. Use an array 
values with elements 110 90 100 120 80, and remove the element at index 2. 


Give pseudocode for an algorithm that rotates the elements of an array by one posi- 
tion, moving the initial element to the end of the array, like this: 
13 |S) jalalyats 


LLL LL 


3) 5 |v falabyaleyy) 2 


Give pseudocode for an algorithm that removes all negative values from an array, 
preserving the order of the remaining elements. 


Suppose values is a sorted array of integers. Give pseudocode that describes how 
a new value can be inserted in its proper position so that the resulting array stays 
sorted. 


A run is a sequence of adjacent repeated values. Give pseudocode for computing the 
length of the longest run in an array. For example, the longest run in the array with 
elements 


12553124322223655631 
has length 4. 


Review Exercises 305 


s##R6.25 What is wrong with the following method that aims to fill an array with random 
numbers? 


public static void fillWithRandomNumbers(double[] values) 
{ 

double[] numbers = new double[values. length]; 

for (int i = 0; i < numbers. length; i++) 


numbers[i] = Math.random(); 


} 


values = numbers; 


} 


»=R6.26 You are given two arrays denoting x- and y-coordinates of a set of om 
points in the plane. For plotting the point set, we need to know the 
x- and y-coordinates of the smallest rectangle containing the | 
points. : x 














How can you obtain these values from the fundamental algorithms 
in Section 6.3? ' 





« R6.27 Solve the problem described in Section 6.5 by sorting the array first. How do you 
need to modify the algorithm for computing the total? 


n= RG6.28 Solve the task described in Section 6.6 using an algorithm that removes and inserts 
elements instead of switching them. Write the pseudocode for the algorithm, assum- 
ing that methods for removal and insertion exist. Act out the algorithm with a 
sequence of coins and explain why it is less efficient than the swapping algorithm 
developed in Section 6.6. 


= R6.29 Develop an algorithm for finding the most frequently occurring value in an array of 
numbers. Use a sequence of coins. Place paper clips below each coin that count how 
many other coins of the same value are in the sequence. Give the pseudocode for an 
algorithm that yields the correct answer, and describe how using the coins and paper 


clips helped you find the algorithm. 


«= R6.30 Write Java statements for performing the following tasks with an array declared as 
int[][] values = new int[ROWS] [COLUMNS] ; 
e Fillall entries with 0. 


Fill elements alternately with Os and 1s in a checkerboard pattern. 


Fill only the elements at the top and bottom row with zeroes. 


Compute the sum of all elements. 


Print the array in tabular form. 


#= R6.31 Write pseudocode for an algorithm that fills the first and last column as well as the 
first and last row of a two-dimensional array of integers with -1. 


» R6.32 Section 6.8.8 shows that you must be careful about updating the index value when 
you remove elements from an array list. Show how you can avoid this problem by 
traversing the array list backwards. 


306 Chapter6 Arrays and Array Lists 


«= R6.33 True or false? 
a. All elements of an array are of the same type. 
b. Arrays cannot contain strings as elements. 
c. Two-dimensional arrays always have the same number of rows and columns. 


d. Elements of different columns in a two-dimensional array can have 
different types. 


e. A method cannot return a two-dimensional array. 
f. A method cannot change the length of an array argument. 


g. A method cannot change the number of columns of an argument that is a 
two-dimensional array. 


== R6.34 How do you perform the following tasks with array lists in Java? 
a. Test that two array lists contain the same elements in the same order. 
b. Copy one array list to another. 
c. Fill an array list with zeroes, overwriting all elements in it. 
d. Remove all elements from an array list. 


« R6.35 True or false? 
a. All elements of an array list are of the same type. 
b. Array list index values must be integers. 
c. Array lists cannot contain strings as elements. 
d. Array lists can change their size, getting larger or smaller. 
e. A method cannot return an array list. 


f. A method cannot change the size of an array list argument. 


a= P6.1 Write a program that initializes an array with ten random integers and then prints 
four lines of output, containing 


e Every element at an even index. 
e Every even element. 
e All elements in reverse order. 


¢ Only the first and last element. 


a= P6.2 Write array methods that carry out the following tasks for an array of integers. For 
each method, provide a test program. 


a. Swap the first and last elements in the array. 


b. Shift all elements by one to the right and move the last element into the first 
position. For example, 1 4 9 16 25 would be transformed into 25 14 9 16. 


c. Replace all even elements with 0. 
d. Replace each element except the first and last by the larger of its two neighbors. 


= P6.3 


un P6.4 


= P6.5 


uu P6.6 


= P6.7 


= P6.8 


uu P6.9 


ua P6.10 


Programming Exercises 307 


e. Remove the middle element if the array length is odd, or the middle two 
elements if the length is even. 


f. Move all even elements to the front, otherwise preserving the order of the 
elements. 


g. Return the second-largest element in the array. 

h. Return true if the array is currently sorted in increasing order. 

i. Return true if the array contains two adjacent duplicate elements. 

j. Return true if the array contains duplicate elements (which need not be 
adjacent). 


Modify the LargestInArray. java program in Section 6.3 to mark both the smallest and 
the largest elements. 


Write a method sumwithoutSmallest that computes the sum of an array of values, 
except for the smallest one, in a single loop. In the loop, update the sum and the 
smallest value. After the loop, return the difference. 


Write a method public static void removeMin that removes the minimum value from a 
partially filled array without calling other methods. 


Compute the alternating sum of all elements in an array. For example, if your pro- 
gram reads the input 


149 14 9 7 4 9 Ii! 
then it computes 
(= 4991609274 9294 412 


Write a method that reverses the sequence of elements in an array. For example, if 
you call the method with the array 


149 146 9 7 4 9 11 


then the array is changed to 
11947 9 169 4 +1 


Write a method that implements the algorithm developed in Section 6.6. 


Write a method 
public static boolean equals(int[] a, int[] b) 


that checks whether two arrays have the same elements in the same order. 


Write a method 
public static boolean sameSet(int[] a, int[] b) 


that checks whether two arrays have the same elements in some order, ignoring 
duplicates. For example, the two arrays 


149 169 7 4 9 11 
and 
11 117 9 16 4 1 


would be considered identical. You will probably need one or more helper methods. 


308 Chapter6 Arrays and Array Lists 


aun P6.11 


ua P6,12 


ua P6.13 


uu P6.14 


ou P6.15 


Write a method 
public static boolean sameElements(int[] a, int[] b) 


that checks whether two arrays have the same elements in some order, with the same 
multiplicities. For example, 


149 169 7 4 9 1 
and 
11 1 4 9 169 7 4 ~°9 


would be considered identical, but 


149 169 7 4 9 11 
and 
11 11 7 9 16 4 1 4 9 


would not. You will probably need one or more helper methods. 


A run is a sequence of adjacent repeated values. Write a program that generates a 
sequence of 20 random die tosses in an array and that prints the die values, marking 
the runs by including them in parentheses, like this: 


12 (55) 31243 (2222)36(55)631 
Use the following pseudocode: 


Set a boolean variable inKun to false. 
For each valid index i in the array 
If inRun 
If values[i] is different from the preceding value 
Print ). 
inKun = false. 
If not inRun 
If values[i] is the same as the following value 
Print (. 
inRun = true. 
Print values(i). 
If inRun, print ). 


Write a program that generates a sequence of 20 random die tosses in an array and 
that prints the die values, marking only the longest run, like this: 


125531243 2222)3655631 


If there is more than one run of maximum length, mark the first one. 


Write a program that generates a sequence of 20 random values between 0 and 99 in 
an array, prints the sequence, sorts it, and prints the sorted sequence. Use the sort 
method from the standard Java library. 


Write a program that produces ten random permutations of the numbers 1 to 10. To 
generate a random permutation, you need to fill an array with the numbers 1 to 10 
so that no two entries of the array have the same contents. You could do it by brute 
force, by generating random values until you have a value that is not yet in the array. 
But that is inefficient. Instead, follow this algorithm. 


Programming Exercises 309 


Make a second array and fill it with the numbers 1 to 10. 
Repeat 10 times 

Pick a random element from the second array. 

Remove it and append it to the permutation array. 


n= P6.16 Itisa well-researched fact that men ina restroom generally prefer to maximize 


une P6.17 


une P6.18 


their distance from already occupied stalls, by occupying the middle of the longest 
sequence of unoccupied places. 


For example, consider the situation where ten stalls are empty. 





The first visitor will occupy a middle position: 
X 





The next visitor will be in the middle of the empty area at the left. 
X X 





Write a program that reads the number of stalls and then prints out diagrams in the 
format given above when the stalls become filled, one at a time. Hint: Use an array of 
boolean values to indicate whether a stall is occupied. 


In this assignment, you will model the game of Bulgarian Solitaire. The game starts 
with 45 cards. (They need not be playing cards. Unmarked index cards work just as 
well.) Randomly divide them into some number of piles of random size. For exam- 
ple, you might start with piles of size 20, 5, 1, 9, and 10. In each round, you take one 
card from each pile, forming a new pile with these cards. For example, the sample 
starting configuration would be transformed into piles of size 19, 4, 8, 9, and 5. The 
solitaire is over when the piles have size 1, 2, 3, 4, 5, 6, 7, 8, and 9, in some order. (It 
can be shown that you always end up with such a configuration.) 


In your program, produce a random starting configuration and print it. Then keep 


applying the solitaire step and print the result. Stop when the solitaire final configu- 
ration is reached. 


Magic squares. Ann x n matrix that is filled with the numbers 1, 2, 3,..., n isa 


magic square if the sum of the elements in each row, in each column, and in the two 
diagonals is the same value. 


AG) 63 2 HS, 
By JAW) PabL] 
|| 7 jil2 
41514 1 


Write a program that reads in 16 values from the keyboard and tests whether they 
form a magic square when put into a 4 x 4 array. You need to test two features: 


1. Does each of the numbers 1, 2, ..., 16 occur in the user input? 


2. When the numbers are put into a square, are the sums of the rows, columns, 
and diagonals equal to each other? 


310 Chapter6 Arrays and Array Lists 


au P6.19 


ua P6.20 


ua P6,21 


ane P6.22 


ua P6.23 


Implement the following algorithm to construct magic 7 x m squares; it works only if 


nis odd. 


Set row = n- 1, column =n / Z. 
Fork=lun*n 
Place k at [row][column]. 
Increment row and column. 
If the row or column is n, replace it with 0. 
If the element at [row][column] has already been filled 
Set row and column to their previous values. 
Decrement row. 


Here is the 5 x 5 square that you get if you follow this method: 


MALU 25) 2 | ©) 
all) p24 ES) 21S 
4 6 13 20 22 
23 5 7 14 16 
1724 1 8 15 


Write a program whose input is the number 7 and whose output is the magic square 
of order 7 if 7 is odd. 


Write a method that computes the average of the neighbors of a two-dimensional 
array element in the eight directions shown in Figure 14. 


public static double neighborAverage(int[][] values, int row, int column) 
However, if the element is located at the boundary of the array, only include the 


neighbors that are in the array. For example, if row and column are both 0, there are 
only three neighbors. 


Write a program that reads a sequence of input values and displays a bar chart of the 
values, using asterisks, like this: 


* 








You may assume that all values are positive. First figure out the maximum value. 
That value’s bar should be drawn with 40 asterisks. Shorter bars should use propor- 
tionally fewer asterisks. 


Improve the program of Exercise P6.21 to work correctly when the data set contains 
negative values. 


Improve the program of Exercise P6.21 by adding captions for each bar. Prompt the 
user for the captions and data values. The output should look like this: 





Egypt * 
France * 
Japan 
Uruguay * 
Switzerland *** 


RHEREEERE RE 





uu P6.24 


uae P6.25 


= P6.26 


ua P6.27 


Programming Exercises 311 


A theater seating chart is implemented as a two-dimensional array of ticket prices, 


like this: 


10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 10 
10 10 10 10 10 10 10 10 10 10 
10 10 20 20 20 20 20 20 10 10 
10 10 20 20 20 20 20 20 10 10 
10 10 20 20 20 20 20 20 10 10 
20 20 30 30 40 40 30 30 20 20 
20 30 30 40 50 50 40 30 30 20 
30 40 50 50 50 50 50 50 40 30 


Write a program that prompts users to 
pick either a seat or a price. Mark sold 
seats by changing the price to 0. When 
a user specifies a seat, make sure it is 
available. When a user specifies a price, 
find any seat with that price. 





Write a program that plays tic-tac-toe. The tic-tac-toe 
game is played on a3 x 3 grid as in the photo at right. The 
game is played by two players, who take turns. The first 
player marks moves with a circle, the second with a cross. 
The player who has formed a horizontal, vertical, or diag- 
onal sequence of three marks wins. Your program should 
draw the game board, ask the user for the coordinates of 
the next mark, change the players after every successful 
move, and pronounce the winner. 





Write a method 
public static ArrayList<Integer> append(ArrayList<Integer> a, ArrayList<Integer> b) 
that appends one array list after another. For example, if ais 


1 4 9 16 


and b is 
9 7 4 9 I1 


then append returns the array list 
149 1464 9 7 4 9 Ii 


Write a method 
public static ArrayList<Integer> merge(ArrayList<Integer> a, ArrayList<Integer> b) 
that merges two array lists, alternating elements from both array lists. If one array 
list is shorter than the other, then alternate as long as you can and then append the 
remaining elements from the longer array list. For example, if ais 
1 4 9 16 


and b is 
9 7 4 9 I1 


then merge returns the array list 
1947 9 4 16 9 11 


312 Chapter6 Arrays and Array Lists 


ua P6.28 


a= Business P6.29 


«= Business P6.30 


aus Business P6.31 


Write a method 


public static ArrayList<Integer> mergeSorted(ArrayList<Integer> a, 
ArrayList<Integer> b) 
that merges two sorted array lists, producing a new sorted array list. Keep an index 
into each array list, indicating how much of it has been processed already. Each time, 
append the smallest unprocessed element from either array list, then advance the 
index. For example, if a is 
1 4 9 16 


and b is 
479 9 1 


then mergeSorted returns the array list 


14479 9 9 11 16 


A pet shop wants to give a discount to its 
clients if they buy one or more pets and 

at least five other items. The discount is 
equal to 20 percent of the cost of the other 
items, but not the pets. 





Implement a method 
public static void discount(double[] prices, boolean[] isPet, int nItems) 

The method receives information about a particular sale. For the ith item, prices[i] is 

the price before any discount, and isPet[i] is true if the item is a pet. 


Write a program that prompts a cashier to enter each price and then a Y for a pet or N 
for another item. Use a price of -1 as a sentinel. Save the inputs in an array. Call the 
method that you implemented, and display the discount. 


A supermarket wants to reward its best customer of each day, showing the custom- 
er’s name ona screen in the supermarket. For that purpose, the customer’s purchase 
amount is stored in an ArrayList<Double> and the customer’s name is stored ina cor- 
responding ArrayList<String>. 


Implement a method 


public static String nameOfBestCustomer(ArrayList<Double> sales, 
ArrayList<String> customers) 


that returns the name of the customer with the largest sale. 


Write a program that prompts the cashier to enter all prices and names, adds them to 
two array lists, calls the method that you implemented, and displays the result. Use a 
price of 0 as a sentinel. 


Improve the program of Exercise P6.30 so that it displays the top customers, that 
is, the topN customers with the largest sales, where topN is a value that the user of the 
program supplies. 


Implement a method 


public static ArrayList<String> nameOfBestCustomers(ArrayList<Double> sales, 
ArrayList<String> customers, int topN) 


If there were fewer than topN customers, include all of them. 


aa Science P6.32 


uae Science P6.33 


ua Science P6.34 


a= Science P6.35 


uae Science P6.36 


Programming Exercises 313 


java reads a sound file (in WAV format), calls a 
method process for processing the sample values, and 
saves the sound file. Your task is to implement the 
process method by introducing an echo. For each 
sound value, add the value from 0.2 seconds ago. 
Scale the result so that no value is larger than 32767. 


Sounds can be represented by an array of “sample a a9 
values” that describe the intensity of the sound at a a 

| 

2 

Gy 


point in time. The program ch06/sound/SoundEffect. 
G awe e we : 





So 


You are given a two-dimensional array of values that give the height of a terrain at 
different points in a square. Write a method 


public static void floodMap(double[][] heights, double waterLevel) 


that prints out a flood map, showing which of the points in the terrain would be 
flooded if the water level was the given value. In the flood map, print a * for each 
flooded point and a space for each point that is not flooded. 


Here is a sample map: 


* kok 


i a a a a 
i a 
* + + + + 





Then write a program that reads one hundred terrain height values and shows how 
the terrain gets flooded when the water level increases in ten steps from the lowest 
point in the terrain to the highest. 


Sample values from an experiment often need to be smoothed out. One simple 
approach is to replace each value in an array with the average of the value and its 
two neighboring values (or one neighboring value if it is at either end of the array). 
Implement a method 


public static void smooth(double[] values, int size) 


that carries out this operation. You should not create another array in your solution. 


Modify the ch06/animation/BlockAnimation. java program to show an animated sine 
wave. In the zth frame, shift the sine wave by / degrees. 


Write a program that models the movement of an object 
with mass m that is attached to an oscillating spring. linsuechad = 
When a spring is displaced from its equilibrium posi- spring 
tion by an amount x, Hooke’s law states that the restor- 

ing force is 





F=-kx 


where k is a constant that depends on the spring. (Use 
10 N/m for this simulation.) 


Start with a given displacement x (say, 0.5 meter). Set 
the initial velocity v to 0. Compute the acceleration a 


314 Chapter6 Arrays and Array Lists 


from Newton’s law (F = ma) and Hooke’s law, using a mass of 1 kg. Use a small time 
interval At = 0.01 second. Update the velocity—it changes by aAt. Update the 
displacement—it changes by vAt. 


Every ten iterations, plot the spring displacement as a bar, where 1 pixel represents 
1 cm. Use the technique in Special Topic 4.3 for creating an image. 


«= Graphics P6.37 Using the technique of Special Topic 4.3, generate the image of a checkerboard. 


« Graphics P6.38 Using the technique of Special Topic 4.3, generate the image of a sine wave. Draw a 
line of pixels for every five degrees. 





V 


NINES Wi Resa Ole Sie) a Gil Gir @lU ie Saal L@ INES 


1. int[] primes = { 2, 3, 5, 7, 11}; you don’t know where to add the <= until you 
2 2.3, 5, 3,2 have seen all values. 
3. 9, 4. 6,8: 22 8. It counts how many elements of values are 
4. values[0] = 10; pee 
values[9] = 10; 9. for (double x : values) 
{ 
or better: values[values. length - 1] = 10; System.out.printIn(o; 
5. String[] words = new String[10]; } 
6. String[] words = { "Yes", "No" }; 10. double product = 1; 
> Ff double f : fact 
7. No. Because you don’t store the values, you i eubis ae 


need to print them when you read them. But product = product * f; 


11. 


12. 


13. 


14. 


15. 


16. 


17. 


18. 


19. 


20. 


21. 


22. 


23. 


} 


The loop writes a value into values[i]. The 
enhanced for loop does not have the index 
variable i. 

20 <== largest value 


10 
20 <== largest value 


int count = 0; 


for (double x : values) 


if (x == 0) { count++; } 
} 
If all elements of values are negative, then the 
result is incorrectly computed as 0. 
for (int i = 0; 7 < values. length; i++) 
: System.out.print(values[i]); 


if G < values.length - 1) 
{ 


} 
} 


Now you know why we set up the loop the 
other way. 


System.out.print(" | "); 


If the array has no elements, then the program 
terminates with an exception. 


If there is a match, then pos is incremented 
before the loop exits. 


This loop sets all elements to values [pos]. 
int[] numbers = squares(5); 


public static void fill(int[] values, int value) 


{ 


for (int i = 0; i < values.length; i++) 


values[i] = value; } 

} 
The method returns an array whose length is 
given in the first argument. The array is filled 
with random integers between 0 and n- 1. 
The contents of scores is unchanged. The 
reverse method returns a new array with the 
reversed numbers. 


values 
(1, 4, 9] 


























24. 


25. 


26. 


27. 


28. 


29. 


30. 
31. 


Answers to Self-Check Questions 315 


Use the first algorithm. The order of elements 
does not matter when computing the sum. 


Find the minimum value. 
Calculate the sum. 
Subtract the minimum value. 


Use the algorithm for counting matches 
(Section 4.7.2) twice, once for counting the 
positive values and once for counting the 
negative values. 


You need to modify the algorithm in 
Section 6.3.4. 

boolean first = true; 

for (int i = 0; i < values.length; i++) 


{ 
if (walues[i] > 0)) 


if (first) { first = false; } 
else { System.out.print(", "); } 


} 


System.out.print(values[i]); 


} 


Note that you can no longer use i > 0as the 
criterion for printing a separator. 


Use the algorithm to collect all positive ele- 
ments in an array, then use the algorithm in 
Section 6.3.4 to print the array of matches. 


The paperclip for iassumes positions 0, 1, 2, 

3. When iis incremented to 4, the condition 

i < size / Z becomes false, and the loop ends. 
Similarly, the paperclip for j assumes positions 
4,5, 6, 7, which are the valid positions for the 
second half of the array. 


eece OOS 
U 


! 


It reverses the elements in the array. 


Here is one solution. The basic idea is to move 
all odd elements to the end. Put one paper clip 
at the beginning of the array and one at the 
end. If the element at the first paper clip is odd, 
swap it with the one at the other paper clip and 
move that paper clip to the left. Otherwise, 
move the first paper clip to the right. Stop 
when the two paper clips meet. Here is the 
pseudocode: 

i=0 

j= size-1 


316 Chapter6 Arrays and Array Lists 


32. 


33. 


34. 


35. 


While (i < j) 
If (ali) is odd) 
Swap elements at positions i and j. 
jr- 
Else 
it* 
Here is one solution. The idea is to remove 
all odd elements and move them to the end. 
The trick is to know when to stop. Nothing is 
gained by moving odd elements into the area 
that already contains moved elements, so we 


want to mark that area with another paper clip. 


i=0 
moved = size 
While (i < moved) 
If (ali) is odd) 
Remove the element at position i and add it 
at the end. 
moved-- 


When you read inputs, you get to see values 
one at a time, and you can’t peek ahead. Pick- 
ing cards one at a time from a deck of cards 
simulates this process better than looking at a 
sequence of items, all of which are revealed. 


You get the total number of gold, silver, and 
bronze medals in the competition. In our 
example, there are four of each. 


for (int i = 0; 7 < 8; i++) 


{ 
for Cint j = 0; j < 8; j++) 
{ 
board[i][j] = (i + j) % 2; 
} 


} 


36. 
37. 
38. 
39. 


40. 


41. 
42. 
43. 


44. 


45. 


String[][] board = new String[3] [3]; 
board[0] [2] = "x"; 
board[0] [0], board[1] [1], board[2] [2] 


ArrayList<Integer> primes = 
new ArrayList<Integer>(); 
primes.add(2); 
primes.add(3); 
primes.add(5); 
primes.add(7); 
primes.add(11); 


for (int i = primes.sizeQ) - 1; i >= 0; i--) 


{ 


} 
"Ann", "Cal" 
The names variable has not been initialized. 


System.out.printIn(primes.get(i)); 


names1 contains “Emily”, “Bob”, “Cindy”, 
“Dave”; names2 contains “Dave” 

Because the number of weekdays doesn’t 
change, there is no disadvantage to using an 
array, and it is easier to initialize: 


String[] weekdayNames = { "Monday", "Tuesday", 
"Wednesday", "Thursday", “Friday”, 
"Saturday", "Sunday" }; 


Reading inputs into an array list is much easier. 


CHAPTER 7 


NW Ou ea: 
AND EXCEPTION g§ 


HANDLING 


CHAPTER GOALS 


To read and write text files 
To process command line arguments 


To throw and catch exceptions 








To implement programs that propagate checked exceptions 


CHAPTER CONTENTS 


7.1 READING AND WRITING TEXT 
FILES 318 

Common Error 7.1: Backslashes in 
File Names 321 

Common Error 7.2: Constructing a Scanner 
with a String 321 

Special Topic 7.1: Reading Web Pages 321 

Special Topic 7.2: File Dialog Boxes 321 

Special Topic 7.3: Reading and Writing 
Binary Data 322 


7.2 TEXTINPUT AND OUTPUT 323 
Special Topic 7.4: Regular Expressions 330 


Video Example 7.1: Computing a Document’s 


Readability @ 


7.3 COMMAND LINE ARGUMENTS 330 


How To 7.1: Processing Text Files 333 


Random Fact 7.1: Encryption Algorithms 336 
Worked Example 7.1: Analyzing Baby Names @ 


7.4 EXCEPTION HANDLING 337 
Syntax 7.1: Throwing an Exception 338 
Syntax 7.2: Catching Exceptions 341 
Syntax 7.3: The throws Clause 343 
Syntax 7.4: The finally Clause 344 
Programming Tip 7.1: Throw Early, 
Catch Late 345 
Programming Tip 7.2: Do Not Squelch 
Exceptions 345 
Programming Tip 7.3: Do Not Use catch and 
finally in the Same try Statement 346 
Special Topic 7.5: Automatic Resource 
Management in Java 7 346 
Random Fact 7.2: The Ariane Rocket Incident 347 


7.5 APPLICATION: HANDLING 
INPUT ERRORS 347 


Video Example 7.2: Detecting 
Accounting Fraud @ 


317 





In this chapter, you will learn how to read and write 
files—a very useful skill for processing real world data. As 
an application, you will learn how to encrypt data. (The 
Enigma machine shown at left is an encryption device used 
by Germany in World War Il. Pioneering British computer 
scientists broke the code and were able to intercept 
encoded messages, which was a significant help in winning 
the war.) The remainder of this chapter tells you how your 
programs can report and recover from problems, such as 
missing files or malformed content, using the exception- 
handling mechanism of the Java language. 








7.| Reading and Writing Text Files 


We begin this chapter by discussing the common task of reading and writing files that 

contain text. Examples of text files include not only files that are created witha simple 

text editor, such as Windows Notepad, but also Java source code and HTML files. 
Te ar eee mare In Java, the most convenient mechanism for reading text is to use the Scanner class. 
for reading text files. You already know how to use a Scanner for reading console input. To read input from 

a disk file, the Scanner class relies on another class, File, which describes disk files and 

directories. (The File class has many methods that we do not discuss in this book; for 

example, methods that delete or rename a file.) 

To begin, construct a File object with the name of the input file: 


File inputFile = new FileC("input.txt"); 
Then use the File object to construct a Scanner object: 
Scanner in = new Scanner(inputFi le); 


This Scanner object reads text from the file input.txt. You can use the Scanner methods 
(such as next Int, nextDouble, and next) to read data from the input file. 
For example, you can use the following loop to process numbers in the input file: 


while (in.hasNextDouble()) 


{ 
double value = in.nextDouble(); 
Process value. 
} 
Wheto oe To write output to a file, you construct a Printwriter object with the desired file name, 
files, use the for example 
PrintWriter class . : . . 7 1 
and the print/ PrintWriter out = new PrintWriter("output. txt"); 
printIn/printf 


If the output file already exists, it is emptied before the new data are written into it. If 
the file doesn’t exist, an empty file is created. 

The Printwriter class is an enhancement of the PrintStream class that you already 
know — System. out is a PrintStream object. You can use the familiar print, printin, and 
printf methods with any PrintWwriter object: 


methods. 


out.printInC"Hello, World!"); 
out.printfC("Total: %8.2f\n", total); 


318 


Close all files when 
you are done 
processing them. 


7.1 Reading and Writing Text Files 319 


When you are done processing a file, be sure to close the Scanner or PrintWriter: 


in.close(); 
out.close(); 


If your program exits without closing the Printwriter, some of the output may not be 
written to the disk file. 

The following program puts these concepts to work. It reads a file containing 
numbers, and writes the numbers to another file, lined up in a column and followed 
by their total. 

For example, if the input file has the contents 


32 54 67.5 29 35 80 
115 44.5 100 65 


then the output file is 


32.00 
54.00 
67.50 
29.00 
35.00 
80.00 
115.00 
44.50 
100.00 
65.00 
Total: 622.00 


There is one additional issue that we need to tackle. If the input or output file for a 
Scanner doesn’t exist, a FileNotFoundException occurs when the Scanner object is con- 
structed. The compiler insists that we specify what the program should do when that 
happens. Similarly, the Printwriter constructor generates this exception if it cannot 
open the file for writing. (This can happen if the name is illegal or the user does not 
have the authority to create a file in the given location.) In our sample program, we 
want to terminate the main method if the exception occurs. To achieve this, we label 
the main method with a throws declaration: 


public static void main(String[] args) throws FileNotFoundException 


You will see in Section 7.4 how to deal with exceptions in a more professional way. 
The File, PrintWriter, and FileNotFoundException classes are contained in the java.io 
package. 


section_1/Total.java 


1 import java.io.File; 
2 import java.io.FileNotFoundException; 
3 import java.io.PrintWriter; 
4 import java.util.Scanner; 
5 
6 
7 This program reads a file with numbers, and writes the numbers to another 
8 file, are up in a column and followed by their total. 
9 */ 
10 eee class Total 
11 { 
12 public static void main(String[] args) throws FileNotFoundException 


13 { 


320 Chapter 7 Input/Output and Exception Handling 


14 // Prompt for the input and output file names 
15 

16 Scanner console = new Scanner(System.in); 
17 System.out.print("Input file: "); 

18 String inputFileName = console.next(); 
19 System.out.printCOutput file: "); 

20 String outputFileName = console.next(); 
21 

22 // Construct the Scanner and PrintWriter objects for reading and writing 
23 

24 File inputFile = new FileCinputFileName) ; 
25 Scanner in = new Scanner(inputFi le); 

26 PrintWriter out = new PrintWriter(outputFileName) ; 
27 

28 // Read the input and write the output 

29 

30 double total = 0; 

31 

32 while Cin. hasNextDouble()) 

33 

34 double value = in.nextDouble() ; 

35 out.printf('%15.2f\n", value); 

36 total = total + value; 

37 } 

38 

39 out.printfC("Total: %8.2f\n", total); 

40 

41 in.closeQ); 

42 out.close(Q); 

43 } 

44 } 


1. What happens when you supply the same name for the input and output files to 
the Total program? Try it out if you are not sure. 

2. What happens when you supply the name of a nonexistent input file to the Total 
program? Try it out if you are not sure. 





3. Suppose you wanted to add the total to an existing file instead of writing a new 
file. Self Check 1 indicates that you cannot simply do this by specifying the same 
file for input and output. How can you achieve this task? Provide the pseudo- 
code for the solution. 


4. How do you modify the program so that it shows the average, not the total, of 
the inputs? 

5. How can you modify the Total program so that it writes the values in two 
columns, like this: 


32.00 54.00 
67.50 29.00 
35.00 80.00 
115.00 44.50 
100.00 65.00 
Total: 622.00 


Practice It Now youcantry these exercises at the end of the chapter: R7.1, R7.2, P7.1. 


(@loyaalankelamalage)ayan 


(@loyaalankelamalane) mys 


Special Topic 7.1 


Special Topic 7.2 











7.1 Reading and Writing Text Files 321 


Backslashes in File Names 


When you specify a file name as a string literal, and the name contains backslash characters (as 
ina Windows file name), you must supply each backslash twice: 


File inputFile = new File("c:\\homework\\input.dat") ; 


A single backslash inside a quoted string is an escape character that is combined with the 
following character to form a special meaning, such as \n for a newline character. The \\ com- 
bination denotes a single backslash. 

When a user supplies a file name to a program, however, the user should not type the back- 
slash twice. 


Constructing a Scanner with a String 


When you construct a PrintWriter with a string, it writes to a file: 
PrintWriter out = new PrintWriterC"output.txt") ; 

However, this does not work for a Scanner. The statement 
Scanner in = new Scanner("input.txt"); // Error? 


does not open a file. Instead, it simply reads through the string: in.next© returns the string 
"input.txt". (This is occasionally useful—see Section 7.2.4.) 
You must simply remember to use File objects in the Scanner constructor: 


Scanner in = new Scanner(new File("input.txt")); // OK 


Reading Web Pages 


You can read the contents of a web page with this sequence of commands: 


String address = "http://horstmann.com/index.htm1"; 
URL pageLocation = new URL(address); 
Scanner in = new Scanner(pageLocation.openStream()) ; 


Now simply read the contents of the web page with the Scanner 
in the usual way. The URL constructor and the openStream method @ Aprogram that reads 
can throw an IOException, so you need to tag the main method with data from a web page. 
throws IOException. (See Section 7.4.3 for more information on the 
throws clause.) 

The uRL class is contained in the java.net package. 


File Dialog Boxes 


Ina 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 
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 
most basic form it is quite simple: Construct a file chooser object; then call the show0penDialog 
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. 


322 Chapter 7 Input/Output and Exception Handling 


@ A program that 
demonstrates how to 
use a file chooser. 


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 nu11. 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.show0penDialog(null) == JFileChooser.APPROVE_OPTION) 
{ 
File selectedFile = chooser.getSelectedFile(); 
in = new Scanner(selectedFile); 























} 
[| Open x 
Call with = = 
showOpenDialog Look In: = api 7 ‘| [a = (pa]s- 
method Ze 
i 5 index-files By allclasses-noframe.html Q overview-summe 
Cijava Bi constant-values.html Q overview-tree.hul 
(J javax deprecated-listhtml Qy package-list 
Cjorg [) help-dochtmt (\ serialized-form.h 
Cd resources C) index.html [\ stylesheetcss 
[\ allclasses-frame.html —[") overview-frame.html 
4] i [oI 
File Name: ; ; 


SY of <\ol F-1  Ke) 0) om as} 


( 





Files of Type: all Files 





Button is “Save” when _ | 
showSaveDialog method ' 
Aorealled | Open al Cancel “ | 




















EE ———————————————————————————— a 





A JFileChooser Dialog Box 


Reading and Writing Binary Data 


You use the Scanner and PrintWriter classes to read and write text files. Text files contain 
sequences of characters. Other files, such as images, are not made up of characters but of bytes. 
A byte is a fundamental storage unit in a computer—a number consisting of eight binary dig- 
its. (A byte can represent unsigned integers between 0 and 255 or signed integers between -128 
and 127.) The Java library has a different set of classes, called streams, for working with binary 
files. While modifying binary files is quite challenging and beyond the scope of this book, we 
give you a simple example of copying binary data from a web site to a file. 
You use an InputStream to read binary data. For example, 


URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif") ; 
InputStream in = imageLocation.openStream() ; 


To write binary data to a file, use a Fi leOutputStream: 


FileQutputStream out = new FileQutputStream("duke. gif"); 


7.2 Tex 


The next method 
reads a string that 
is delimited by 
white space. 


7.2 TextInputand Output 323 


The read method of an input stream reads a single byte and returns —1 when no further input is 
available. The write method of an output stream writes a single byte. 
The following loop copies all bytes from an input stream to an output stream: 


boolean done = false; 
while (!done) 


{ 
int input = in.readQ); // -1 ora byte between 0 and 255 
if Cinput == -1) { done = true; } 
else { out.write(input); } 

} 


In n 


In the following sections, you will learn how to process text with complex contents, 
and you will learn how to cope with challenges that often occur with real data. 


7.2.1 Reading Words 


The next method of the Scanner class reads the next string. Consider the loop 


while Cin. hasNext()) 
{ 


String input = in.next(); 
System.out.printIn(Cinput) ; 


} 
If the user provides the input: 
Mary had a little lamb 


this loop prints each word ona separate line: 


Mary 
had 

a 
little 
lamb 


However, the words can contain punctuation marks and other symbols. The next 
method returns any sequence of characters that is not white space. White space 
includes spaces, tab characters, and the newline characters that separate lines. For 
example, the following strings are considered “words” by the next method: 

snow. 

1729 

C++ 
(Note the period after snow—it is considered a part of the word because it is not white 
space.) 

Here is precisely what happens when the next method is executed. Input characters 
that are white space are consumed —that is, removed from the input. However, they 
do not become part of the word. The first character that is not white space becomes 
the first character of the word. More characters are added until either another white 
space character occurs, or the end of the input file has been reached. However, if the 
end of the input file is reached before any character was added to the word, a “no such 
element exception” occurs. 


324 Chapter 7 


The Character class 
has methods for 
classifying 
characters. 


Input/Output and Exception Handling 


Sometimes, you want to read just the words and discard anything that isn’t a letter. 
You achieve this task by calling the useDelimiter method on your Scanner object: 

Scanner in = new Scanner(. . .); 

in.useDelimiter(" [AA-Za-z]+"); 
Here, we set the character pattern that separates words to “any sequence of charac- 
ters other than letters”. (See Special Topic 7.4.) With this setting, punctuation and 
numbers are not included in the words returned by the next method. 


7.2.2 Reading Characters 


Sometimes, you want to read a file one character at a time. You will see an example in 
Section 7.3 where we encrypt the characters of a file. You achieve this task by calling 
the useDelimiter method on your Scanner object with an empty string: 


Scanner in = new Scanner(. . .); 
in.useDelimiter(""); 


Now each call to next returns a string consisting of a single character. Here is how you 
can process the characters: 


while (in. hasNext()) 


{ 
char ch = in.next().charAt(0); 
Process ch. 


7.2.3 Classifying Characters 


When you read a character, or when you analyze the characters in a word or line, 
you often want to know what kind of character it is. The Character class declares sev- 
eral useful methods for this purpose. Each of them has an argument of type char and 
returns a boolean value (see Table 1 ). 

For example, the call 


Character.isDigit(ch) 


returns true if chis a digit ('0'...'9' ora digit in another writing system—see Random 
Fact 2.2), false otherwise. 


Table 1 Character Testing Methods 


Bee teh Peto aana tre 

isDigit Ona 

isLetter JA 18h, G, @, lo © 
jsUpperCase JX, 18h, (C 
jsLowerCase a, b, G 


isWhiteSpace space, newline, tab 


7.2 TextInputand Output 325 


7.2.4 Reading Lines 


When each line of a file is a data record, it is often best to read entire lines with the 
The nextLine method ; 
reads an entire line. nextLine method: 


String line = in.nextLine(); 


The next input line (without the newline character) is placed into the string line. You 
can then take the line apart for further processing. 

The hasNextLine method returns true if there is at least one more line in the input, 
false when all lines have been read. To ensure that there is another line to process, call 
the hasNextLine method before calling nextLine. 

Here is a typical example of processing lines in a file. A file with population data 
from the CIA Fact Book site (https: //ww.cia.gov/library/publications/the-world- 
factbook/index.htm1) contains lines such as the following: 

China 1330044605 


India 1147995898 
United States 303824646 


Because some country names have more than one word, it would be tedious to read 

this file using the next method. For example, after reading United, how would your pro- 

gram know that it needs to read another word before reading the population count? 
Instead, read each input line into a string: 


while (in. hasNextLine()) 

{ 
String line = nextLine(); 
Process line. 

} 


Use the isDigit and iswhiteSpace methods introduced to find out where the name ends 
and the number starts. 
Locate the first digit: 


int i = 0; 
while (!Character.isDigit(line.charAt(i))) { i++; } 


Then extract the country name and population: 


String countryName = line.substring(0, 1); 
String population = line.substring(i); 


However, the country name contains one or more spaces at the end. Use the trim 
method to remove them: 


countryName = countryName.trim(Q) ; 


Use trim to 
7 starts here remove this space. i ends here 





U8 ae eis ae ee [rel Sita rau ita peaks) Ba ON om Ron 2a 4 RON 4a BG 
O 12 3 4 5 6 7 & 9 10 11 12 13 14 15 16 17 18 19 20 21 22 
‘ ws J 
ce YY 
countryName population 


The trim method returns the string with all white space at the beginning and end 
removed. 


326 Chapter 7 Input/Output and Exception Handling 


If a string contains 
the digits of a 
number, you use the 
Integer.parseInt or 
Double.parseDouble 
method to obtain the 
number value. 


There is one additional problem. The population is stored in a string, not a num- 
ber. In Section 7.2.6, you will see how to convert the string to a number. 


7.2.5 Scanning a String 


In the preceding section, you saw how to break a string into parts by looking at 
individual characters. Another approach is occasionally easier. You can use a Scanner 
object to read the characters from a string: 


Scanner lineScanner = new Scanner(line); 


Then you can use lineScanner like any other Scanner object, reading words and 
numbers: 


String countryName = lineScanner.next(); // Read first word 
// Add more words to countryName until number encountered 
while (!]ineScanner.hasNextInt(Q)) 


{ 
} 


int populationValue = lineScanner.nextInt(); 


countryName = countryName + + lineScanner.next(); 


7.2.6 Converting Strings to Numbers 


Sometimes you have a string that contains a number, such as the population string 
in Section 7.2.4. For example, suppose that the string is the character sequence 
"303824646". To get the integer value 303824646, you use the Integer. parseInt method: 
int populationValue = Integer.parseInt (population) ; 
// populationValue is the integer 303824646 
To convert a string containing floating-point digits to its floating-point value, use the 
Double. parseDouble method. For example, suppose input is the string "3.95". 
double price = Double.parseDouble(input) ; 
// price is the floating-point number 3.95 
You need to be careful when calling the Integer. parseInt and Double. parseDouble meth- 
ods. The argument must be a string containing the digits of an integer, without any 
additional characters. Not even spaces are allowed! In our situation, we happen to 
know that there won’t be any spaces at the beginning of the string, but there might be 
some at the end. Therefore, we use the trim method: 


int populationValue = Integer.parseInt(population.trim()); 


How To 7.1 on page 333 continues this example. 


7.2.7 Avoiding Errors When Reading Numbers 


You have used the nextInt and nextDouble methods of the Scanner class many times, but 
here we will have a look at what happens in “abnormal” situations. Suppose you call 


int value = in.nextIntQ; 


The nextInt method recognizes numbers such as 3 or -21. However, if the input is not 
a properly formatted number, an “input mismatch exception” occurs. For example, 
consider an input containing the characters 


7.2 TextInputand Output 327 


2\al | s |e ECl@lm)e lu] tr |y 


White space is consumed and the word 21st is read. However, this word is not a prop- 
erly formatted number, causing an input mismatch exception in the nextInt method. 

If there is no input at all when you call nextInt or nextDouble, a “no such element 
exception” occurs. To avoid exceptions, use the hasNextInt method to screen the input 
when reading an integer. For example, 


if Cin. hasNextIntQ) 
{ 


int value = in.nextIntQ; 


} 
Similarly, you should call the hasNextDouble method before calling nextDouble. 


7.2.8 Mixing Number, Word, and Line Input 


The nextInt, nextDouble, and next methods do not consume the white space that follows 
the number or word. This can be a problem if you alternate between calling nextInt/ 
nextDouble/next and nextLine. Suppose a file contains country names and population 
values in this format: 

China 

1330044605 

India 

1147995898 


United States 
303824646 


Now suppose you read the file with these instructions: 


while (in. hasNextLine()) 

{ 
String countryName = in.nextLine(); 
int population = in.nextIntQ; 
Process the country name and population. 

} 


Initially, the input contains 
ny ae a ay Na ES SS On Oe a 2a Ge CO ed Na Es i fe a es Na 
After the first call to the nextLine method, the input contains 
UPS SIO(O4 416/015 all yale yi jaw 
After the call to nextInt, the input contains 
Wali yi pel} a |e pa 


Note that the nextInt call did mot consume the newline character. Therefore, the sec- 
ond call to nextLine reads an empty string! 

The remedy is to add a call to nextLine after reading the population value: 

String countryName = in.nextLine(); 


int population = in.nextIntQ; 
in.nextLine(); // Consume the newline 


The call to nextLine consumes any remaining white space and the newline character. 


328 Chapter 7 Input/Output and Exception Handling 


7.2.9 Formatting Output 


When you write numbers or strings, you often want to control how they appear. For 
example, dollar amounts are usually formatted with two significant digits, such as 


Cookies: 3.20 
You know from Section 2.3.2 how to achieve this output with the printf method. In 


this section, we discuss additional options of the printf method. 
Suppose you need to print a table of items and prices, each stored in an array, such 


as this one: 
Cookies: 3.20 
Linguine: 2-95: 
Clams: 17.29 


Note that the item strings line up to the left, whereas the numbers line up to the right. 
By default, the printf method lines up values to the right. To specify left alignment, 
you add a hyphen (-) before the field width: 

System.out.printf("%-10s%10.2f", items[i] + ":", prices[i]); 


Here, we have two format specifiers. 


© %-10s formats a left-justified string. The string items[i] + ":"is padded with spaces 
so it becomes ten characters wide. The - indicates that the string is placed on the 
left, followed by sufficient spaces to reach a width of 10. 


© %10.2f formats a floating-point number, also in a field that is ten characters wide. 
However, the spaces appear to the left and the value to the right. 





A. left-justified sh 4 a 
a widt widt 
si A A 
f a a = 
Ga) Rae jimi ise iLj7|.|2]9 
Two digits after 


the decimal point 


A construct such as %-10s or %10.2f is called a format specifier: it describes how a value 
should be formatted. 


Table 2 Format Flags 


Flag Meaning Example 
- Left alignment 1.23 followed by spaces 
0 Show leading zeroes 001.23 
+ Show a plus sign for positive numbers $1.23 
( Enclose negative numbers in parentheses (1.23) 
: Show decimal separators 12,300 


A Convert letters to uppercase 1.23E+1 


7.2 TextInputand Output 329 


Table 3 Format Types 


Code Type Example 
d Decimal integer 123 
fi Fixed floating-point 12.30 
e Exponential floating-point 1.23e+1 
g General floating-point 12.3 


(exponential notation is used for 
very large or very small values) 


s String Tax: 


A format specifier has the following structure: 


ONLINE EXAMPLE 


© Aprogram that 
processes a file e 
containing a mixture 
of text and numbers. 





10. 


The first character is a% 


Next, there are optional “flags” that modify the format, such as - to indicate left 
alignment. See Table 2 for the most common format flags. 


Next is the field width, the total number of characters in the field (including the 
spaces used for padding), followed by an optional precision for floating-point 
numbers. 


The format specifier ends with the format type, such as f for floating-point values 
or s for strings. There are quite a few format types— Table 3 shows the most 
important ones. 


Suppose the input contains the characters Hello, World!. What are the values of 
word and input after this code fragment? 

String word = in.nextQ); 

String input = in.nextLine(); 

Suppose the input contains the characters 995.0 Fred. What are the values of 
number and input after this code fragment? 

int number = 0; 

if Cin.hasNextInt(Q)) { number = in.nextInt(); } 

String input = in.next(); 

Suppose the input contains the characters 6E6 6,995.00. What are the values of x1 
and x2 after this code fragment? 

double x1 = in.nextDoubleQ); 

double x2 = in.nextDoubleQ); 

Your input file contains a sequence of numbers, but sometimes a value is not 
available and is marked as N/A. How can you read the numbers and skip over the 
markers? 


How can you remove spaces from the country name in Section 7.2.4 without 
using the trim method? 


Practice It Now you cantry these exercises at the end of the chapter: P7.2, P7.4, P7.5. 


330 Chapter 7 Input/Output and Exception Handling 


Special Topic 7.4 





VIDEO EXAMPLE 7.1 Computing a Document’s Readability 


PLUS 


Regular Expressions 


Regular expressions describe character patterns. For example, numbers have a simple form. 
They contain one or more digits. The regular expression describing numbers is [0-9]+. The set 
[0-9] denotes any digit between 0 and 9, and the + means “one or more”. 

The search commands of professional programming editors understand regular expres- 
sions. Moreover, several utility programs use regular expressions to locate matching text. A 
commonly used program that uses regular expressions is grep (which stands for “global regu- 
lar expression print”). You can run grep from a command line or from inside some compila- 
tion environments. Grep is part of the UNIX operating system, and versions are available for 
Windows. It needs a regular expression and one or more files to search. When grep runs, it 
displays a set of lines that match the regular expression. 

Suppose you want to find all magic numbers (see Programming Tip 2.2) ina file. 


grep [0-9]+ Homework. java 


lists all lines in the file Homework. java that contain sequences of digits. That isn’t terribly useful; 
lines with variable names x1 will be listed. OK, you want sequences of digits that do not imme- 
diately follow letters: 


grep [AA-Za-z][0-9]+ Homework. java 


The set [AA-Za-z] denotes any characters that are not in the ranges A to Zand a to z. This works 
much better, and it shows only lines that contain actual numbers. 

The useDelimiter method of the Scanner class accepts a regular expression to describe delim- 
iters—the blocks of text that separate words. As already mentioned, if you set the delimiter 
pattern to [AA-Za-z]+, a delimiter is a sequence of one or more characters that are not letters. 

For more information on regular expressions, consult one of the many tutorials on the 
Internet by pointing your search engine to “regular expression tutorial”. 


In this Video Example, we develop a program that computes the Flesch 
Readability Index for a document. 





Depending on the operating system and Java development environment used, there 
are different methods of starting a program—for example, by selecting “Run” in 
the compilation environment, by clicking on an icon, or by typing the name of the 
program at the prompt in a command shell window. The latter method is called 
“invoking the program from the command line”. When you use this method, you 
must of course type the name of the program, but you can also type in additional 
information that the program can use. These additional strings are called command 
line arguments. For example, if you start a program with the command line 


java ProgramClass -v input.dat 


then the program receives two command line arguments: the strings "-v" and "input. 
dat". It is entirely up to the program what to do with these strings. It is customary to 
interpret strings starting with a hyphen (-) as program options. 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


Programs that start 
from the command 
line receive the 
command line 
arguments in the 
main method. 


7.3. Command LineArguments 331 


Should you support command line arguments for your programs, or should you 
prompt users, perhaps with a graphical user interface? For a casual and infrequent 
user, an interactive user interface is much better. The user interface guides the user 
along and makes it possible to navigate the application without much knowledge. But 
for a frequent user, a command line interface has a major advantage: it is easy to auto- 
mate. If you need to process hundreds of files every day, you could spend all your 
time typing file names into file chooser dialog boxes. However, by using batch files or 
shell scripts (a feature of your computer’s operating system), you can automatically 
call a program many times with different command line arguments. 

Your program receives its command line arguments in the args parameter of the 
main method: 


public static void main(String[] args) 


In our example, args is an array of length 2, containing the strings 

args[0]: "-v" 

args[1]: "input.dat" 
Let us write a program that encrypts a file—that is, 
scrambles it so that it is unreadable except to those who 
know the decryption method. Ignoring 2,000 years of 
progress in the field of encryption, we will use a method 
familiar to Julius Caesar, replacing A with a D, B with 
an E, and so on (see Figure 1). 

The program takes the following command line 
arguments: 


e An optional -d flag to indicate decryption instead of 
encryption 





e The input file name 





beer iad oe 


e The output file name We FO / 
For example The emperor Julius Caesar 
° used a simple scheme to 
java CaesarCipher input.txt encrypt.txt encrypt messages. 


encrypts the file input.txt and places the result into 
encrypt. txt. 


java CaesarCipher -d encrypt.txt output.txt 


decrypts the file encrypt.txt and places the result into output.txt. 


Plaintext M eet me al | ic ea ahs ee 
tyyr Fe Fo Fey 
Encrypted text P h h w @) | In d w w k h 


Figure 1 Caesar Cipher 


section_3/CaesarCipher.java 


import java.io.File; 

import java.io.FileNotFoundException; 
import java.io.PrintWriter; 

import java.util.Scanner; 


RWN = 


332 Chapter 7 Input/Output and Exception Handling 


[** 


This program encrypts a file using the Caesar cipher. 


*/ 


public class CaesarCipher 


{ 


public static void main(String[] args) throws FileNotFoundException 


{ 


/ 
pub 
{ 


final int DEFAULT_KEY = 3; 
int key = DEFAULT_KEY; 
String inFile = ""; 


String outFile = ""; 
int files = 0; // Number of command line arguments that are files 


for Cint i = 0; i < args.length; i++) 
{ 

String arg = args[i]; 

if (arg.charAt(0) == '-') 

{ 


// tis acommand line option 


char option = arg.charAt(1); 
if (option == 'd') { key = -key; } 
else { usage(); return; } 

} 

else 

{ 


// \tis a file name 


files++; 

if (files == 1) { inFile = arg; } 

else if (files == 2) { outFile = arg; } 
} 


t 
if (files != 2) { usageQ); return; } 


Scanner in = new Scanner(new File(inFile)); 
in.useDelimiter(""); // Process individual characters 
PrintWriter out = new PrintWriter(outFile); 


while Cin. hasNext(Q)) 

{ 
char from = in.next(Q).charAt(0); 
char to = encrypt(from, key); 
out.print(to) ; 

} 

in.close(); 

out.close(); 


Encrypts upper- and lowercase characters by shifting them 
according to a key. 

@param ch the letter to be encrypted 

@param key the encryption key 

@return the encrypted letter 


lic static char encrypt(char ch, int key) 


int base = 0; 






7.3. Command LineArguments 333 


65 if C'A' <= ch && ch <= 'Z') { base = 'A'; } 

66 else if ('a' <= ch && ch <= 'z') { base = 'a'; } 

67 else { return ch; } // Nota letter 

68 int offset = ch - base + key; 

69 final int LETTERS = 26; // Number of letters in the Roman alphabet 
70 if (offset > LETTERS) { offset = offset - LETTERS; } 

71 else if (offset < 0) { offset = offset + LETTERS; } 

72 return (char) (base + offset); 

73 } 

74 

75 /** 

76 Prints a message describing proper usage. 

77 */ 

78 public static void usage() 

79 { 

80 System.out.printIn("Usage: java CaesarCipher [-d] infile outfile"); 
81 } 

82 } 


11. Ifthe program is invoked with java CaesarCipher -d filel.txt, what are the 
elements of args? 


12. Trace the program when it is invoked as in Self Check 11. 





13. Will the program run correctly if the program is invoked with java CaesarCipher 
filel.txt file2.txt -d? If so, why? If not, why not? 


14. Encrypt CAESAR using the Caesar cipher. 


15. How can you modify the program so that the user can specify an encryption key 
other than 3 with a -k option, for example 


java CaesarCipher -k15 input.txt output.txt 


Practice It Now youcantry these exercises at the end of the chapter: R7.4, P7.8, P7.9. 


HOW TO 7.1 Processing Text Files 


Processing text files that contain real data can be 
surprisingly challenging. This How To gives you step- 
by-step guidance. 

As an example, we will consider this task: Read 
two country data files, worldpop.txt and worldarea.txt 
(supplied with the book’s companion code). Both files 
contain the same countries in the same order. Write a 
file world_pop_density.txt that contains country names 
and population densities (people per square km), with 
the country names aligned left and the numbers aligned 





right: 
Afghanistan 50.56 
pea ra 127.64 Singapore is one of the most densely 
Aliana 125.91 populated countries in the world. 
Algeria 14.18 


American Samoa 288.92 


334 Chapter 7 Input/Output and Exception Handling 


Step 1 


Step 2 


Step 3 


Step 4 


Step 5 


Understand the processing task. 


As always, you need to have a clear understanding of the task before designing a solution. Can 
you carry out the task by hand (perhaps with smaller input files)? If not, get more information 
about the problem. 

One important aspect that you need to consider is whether you can process the data as it 
becomes available, or whether you need to store it first. For example, if you are asked to write 
out sorted data, you first need to collect all i input, perhaps by placing it in an array list. How- 
ever, it is often possible to process the data “on the go”, without storing it. 

In our example, we can read each file a line ata time and compute the density for each line 
because our input files store the population and area data in the same order. 

The following pseudocode describes our processing task. 


While there are more lines to be read 
Read a line from each file. 
Extract the country name. 
population = number following the country name in the line from the first file 
area = number following the country name in the line from the second file 
If area != 0 
density = population / area 
Print country name and density. 


Determine which files you need to read and write. 


This should be clear from the problem. In our example, there are two input files, the popula- 
tion data and the area data, and one output file. 


Choose a mechanism for obtaining the file names. 


There are three options: 
e Hard-coding the file names (such as "worldpop. txt"). 
e Asking the user: 


Scanner in = new Scanner(System. in); 
System.out.print("Enter filename: "); 
String inFile = in.nextLineQ; 

e Using command-line arguments for the file names. 


In our example, we use hard-coded file names for simplicity. 
Choose between line, word, and character-based input. 


Asarule of thumb, read lines if the input data is grouped by lines. That is the case with tabular 
data, such as in our example, or when you need to report line numbers. 

When gathering data that can be distributed over several lines, then it makes more sense to 
read words. Keep in mind that you lose all white space when you read words. 

Reading characters is mostly useful for tasks that require access to individual characters. 
Examples include analyzing character frequencies, changing tabs to spaces, or encryption. 


With line-oriented input, extract the required data. 


It is simple to read a line of input with the nextLine method. Then you need to get the data out 
of that line. You can extract substrings, as described in Section 7.2.4. 

Typically, you will use methods such as Character.iswhitespace and Character.isDigit to 
find the boundaries of substrings. 

If you need any of the substrings as numbers, you must convert them, using Integer.parseInt 
or Double. parseDouble. 


Step 6 


7.3. Command LineArguments 335 


Use methods to factor out common tasks. 


Processing input files usually has repetitive tasks, such as skipping over white space or extract- 
ing numbers from strings. It really pays off to develop a set of methods to handle these tedious 
operations. 

In our example, we have two common tasks that call for helper methods: extracting the 
country name and the value that follows. We will implement methods 


public static String extractCountry(String line) 
public static double extractValue(String line) 


These methods are implemented as described in Section 7.2.4. 
Here is the complete source code (how_to_1/PopulationDensity. java). 


import java.io.File; 

import java.io.FileNotFoundException; 
import java.io.PrintWriter; 

import java.util.Scanner; 


/** 
This program reads data files of country populations and areas and prints the 
population density for each country. 
*] 
public class PopulationDensity 
{ 
public static void main(String[] args) throws FileNotFoundException 
{ 


// Construct Scanner objects for input files 


Scanner inl = new Scanner(new FileC"worldpop.txt")); 
Scanner in2 = new Scanner(new File("worldarea.txt")); 


// Construct PrintWriter for the output file 
PrintWriter out = new PrintWriter("world_pop_density.txt"); 
// Read lines from each file 


while Cinl.hasNextLineQ) && in2.hasNextLine(Q)) 
{ 

String linel = inl.nextLineQ; 

String line2 = in2.nextLineQ; 


// Extract country and associated value 
String country = extractCountry(linel) ; 
double population = extractValue(line1) ; 
double area = extractValue(line2); 


// Compute and print the population density 
double density = 0; 
if (area != 0) // Protect against division by zero 


{ 
density = population / area; 
} 
out.printf("%-40s%15.2f\n", country, density); 


} 


inl.closeQ); 
in2.close(Q); 
out.close(); 


336 Chapter 7 Input/Output and Exception Handling 


/** 
Extracts the country from an input line. 
@param line a line containing a country name, followed by a number 


@return the country name 


*/ 


public static String extractCountry(String line) 


{ 


int i = 0; // Locate the start of the first digit 


while (!Character.isDigit(line.charAt(i))) { i++; } 
return line.substring(O, i).trimQ; // Extract the country name 


} 
/* * 


Extracts the value from an input line. 
@param line a line containing a country name, followed by a value 
@return the value associated with the country 


*/ 


public static double extractValue(String line) 


{ 


int i = 0; // Locate the start of the first digit 
while (!Character.isDigit(line.charAt(i))) { i++; } 
// Extract and convert the value 
return Double.parseDouble(line.substring(i).trimQ); 





The exercises at the 
end of this chapter 
give a few algorithms for encrypting 
text. Don’t actually use any of those 
methods to send secret messages 
to your lover. Any skilled cryptogra- 
pher can break these schemes in a 
very short time—that is, reconstruct 
the original text without knowing the 
secret keyword. 

In 1978, Ron Rivest, Adi Shamir, 
and Leonard Adleman introduced an 
encryption method that is much more 
powerful. The method is called RSA 
encryption, after the last names of its 
inventors. The exact scheme is too 
complicated to present here, but it is 
not actually difficult to follow. You can 
find the details in http://theory.1cs. 
mit.edu/~rivest/rsapaper.pdf. 

RSA is a remarkable encryption 
method. There are two keys: a pub- 
lic key and a private key. (See the fig- 
ure.) You can print the public key on 
your business card (or in your e-mail 
signature block) and give it to any- 





Random Fact 7.1 Encryption Algorithms 


one. Then anyone can send you mes- 
sages that only you can decrypt. Even 
though everyone else knows the public 
key, and even if they intercept all the 
messages coming to you, they cannot 
break the scheme and actually read 
the messages. In 1994, hundreds of 
researchers, collaborating over the 
Internet, cracked an RSA message 
encrypted with a 129-digit key. Mes- 
sages encrypted with a key of 230 dig- 
its or more are expected to be secure. 
The inventors of the algorithm 
obtained a patent for it. A patent is a 
deal that society makes with an inven- 
tor. For a period of 20 years, the inven- 
tor has an exclusive right for its com- 
mercialization, may collect royalties 
from others wishing to manufacture 
the invention, and may even stop com- 
petitors from using it altogether. In 
return, the inventor must publish the 
invention, so that others may learn 
from it, and must relinquish all claim 
to it after the monopoly period ends. 
The presumption is that in the absence 


of patent law, inventors would be 
reluctant to go through the trouble of 
inventing, or they would try to cloak 
their techniques to prevent others 
from copying their devices. 

There has been some controversy 
about the RSA patent. Had there not 
been patent protection, would the 
inventors have published the method 
anyway, thereby giving the benefit to 
society without the cost of the 20-year 
monopoly? In this case, the answer is 
probably yes. The inventors were aca- 
demic researchers, who live on sala- 
ries rather than sales receipts and are 
usually rewarded for their discover- 
ies by a boost in their reputation and 
careers. Would their followers have 
been as active in discovering (and pat- 
enting) improvements? There is no 
way of knowing, of course. Is an algo- 
rithm even patentable, or is it a math- 
ematical fact that belongs to nobody? 
The patent office did take the latter 
attitude for a long time. The RSA inven- 
tors and many others described their 


WORKED EXAMPLE 7.1 Analyzing Baby Names 


o 





7.4 Ex 


In this Worked Example, you will use data from the 
Social Security Administration to analyze the most 
popular baby names. 


ion Han 


7.4 ExceptionHandling 337 





lin 


There are two aspects to dealing with program errors: detection and handling. For 
example, the Scanner constructor can detect an attempt to read from a non-existent 
file. However, it cannot handle that error. A satisfactory way of handling the error 
might be to terminate the program, or to ask the user for another file name. The Scan- 
ner class cannot choose between these alternatives. It needs to report the error to 
another part of the program. 

In Java, exception handling provides a flexible mechanism for passing control from 
the point of error detection to a handler that can deal with the error. In the following 
sections, we will look into the details of this mechanism. 


inventions in terms of imaginary elec- 
tronic devices, rather than algorithms, 
to circumvent that restriction. Nowa- 
days, the patent office will award soft- 
ware patents. 

There is another interesting aspect 
to the RSA story. A programmer, Phil 
Zimmermann, developed a program 
called PGP (for Pretty Good Privacy) 
that is based on RSA. Anyone can use 
the program to encrypt messages, and 
decryption is not feasible even with 
the most powerful computers. You can 
get a copy of a free PGP implementa- 
tion from the GNU project (http://www. 
gnupg.org). The existence of strong 
encryption methods bothers’ the 
United States government to no end. 
Criminals and foreign agents can send 
communications that the police and 
intelligence agencies cannot decipher. 
The government considered charging 
Zimmermann with breaching a law 
that forbids the unauthorized export of 
munitions, arguing that he should have 
known that his program would appear 


on the Internet. There have been seri- 
ous proposals to make it illegal for pri- 
vate citizens to use these encryption 


methods, or to keep the keys secret 
from law enforcement. 











Alice The message Bob 
is encrypted with 
Bob’s public ki 
ie pee Decrypted 
text 
SEB 
Xwya 
Txu% 
> *(Wt 
&93ya 
Encrypted The message is 
text 


decypted with Bob’s 
matching private key 





Public-Key Encryption 


@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


338 Chapter 7 Input/Output and Exception Handling 


To signal an 
exceptional 
condition, use the 
throw statement 
to throw an 
exception object. 


When you throw 
an exception, 
processing 
continues in an 


exception handler. 


Syntax 7.1 





7.4.1 Throwing Exceptions 


When you detect an error condition, your job is really easy. You just throw an appro- 
priate exception object, and you are done. For example, suppose someone tries to 
withdraw too much money from a bank account. 


if (amount > balance) 


// Now what? 
} 


First look for an appropriate exception class. The Java library provides many classes 
to signal all sorts of exceptional conditions. Figure 2 shows the most useful ones. 
(The classes are arranged as a tree-shaped hierarchy, with more specialized classes at 
the bottom of the tree. We will discuss such hierarchies in more detail in Chapter 9.) 

Look around for an exception type that might describe your situation. How about 
the ArithmeticException? Is it an arithmetic error to have a negative balance? No—Java 
can deal with negative numbers. Is the amount to be withdrawn illegal? Indeed it is. It 
is just too large. Therefore, let’s throw an I11egalArgumentException. 


if (amount > balance) 
{ 
} 


When you throw an exception, execution does not 
continue with the next statement but with an excep- 
tion handler. That is the topic of the next section. 


throw new IllegalArgumentException("Amount exceeds balance"); 


When you throw an exception, the normal control flow 
is terminated. This is similar to a circuit breaker that 
cuts off the flow of electricity in a dangerous situation. 





Throwing an Exception 


Syntax — throw exceptionObject; 


Most exception objects 
can he constructed with 


if (amount > balance) an error message. 


{ iy 


_ throw new I]legalArgumentException("Amount exceeds balance"); 


A new 
exception object 
is constructed, 
then thrown. 


balance = balance - amount; 
This line is not executed when 
the exception is thrown. 


7.4 Exception Handling 339 





Figure 2 A Part of the Hierarchy of Exception Classes 


7,42 hing Ex ion 





Se ta eee Every exception should be handled somewhere in your program. If an exception has 


ALD eaG CALIOET no handler, an error message is printed, and your program terminates. Of course, 
exception inside a such an unhandled exception is confusing to program users. 

ea ae You handle exceptions with the try/catch statement. Place the statement into a 
Gavan GEWEO. location of your program that knows how to handle a particular exception. The try 


block contains one or more statements that may cause an exception of the kind that 


340 Chapter 7 Input/Output and Exception Handling 





7 
ANIMATION 
Exception Handling 


fi 


you are willing to handle. Each catch clause contains the handler for an exception 
type. Here is an example: 


try 
{ 
String filename =.. .; 
Scanner in = new Scanner(new File(filename)) ; 
String input = in.next(); 
int value = Integer.parseInt (input) ; 


a (IOException exception) 

: exception.printStackTrace() ; 

ie (NumberFormatException exception) 

' System.out.printIn(exception.getMessage()); 
} 


Three exceptions may be thrown in this try block: 


The Scanner constructor can throw a FileNotFoundException. 
Scanner.next can throw a NoSuchElementException. 


Integer.parseInt can throw a NumberFormatException. 


If any of these exceptions is actually thrown, then the rest of the instructions in the 
try block are skipped. Here is what happens for the various exception types: 


If a FileNotFoundException is thrown, then the catch clause for the I0Exception is 
executed. (If you look at Figure 2, you will note that FileNotFoundException is a 
descendant of 10Exception.) If you want to show the user a different message for a 
FileNotFoundException, you must place the catch clause before the clause for an 
IOException. 


If a NumberFormatException occurs, then the second catch clause is executed. 


A NoSuchElementException is not caught by any of the catch clauses. The exception 
remains thrown until it is caught by another try block. 


Each catch clause contains a handler. When the catch (IOException exception) block is 
executed, then some method in the try block has failed with an IOException (or one of 
its descendants). 

In this handler, we produce a printout of the chain of method calls that led to the 
exception, by calling 


You should only catch those exceptions 
that you can handle. 


exception. printStackTrace() 





7.4 ExceptionHandling 341 


Syntax 7.2 Catching Exceptions 


Syntax try 
{ 


statement 
statement 


} 
catch (ExceptionClass exceptionObject) 


statement 
statement 


This constructor can throw a 


Fi leNotFoundException. 
try 


{ 
Scanner in = new Scanner(new File("input.txt")); 
String input = in.next(); 


rocess(input) ; fej ‘ 
When an IOException is thrown, ; p p ue This is the exception that was thrown. 


execution resumes here. i a (IOException exception) 
{ 


System.out.printIn("Could not open input file"); 


} 
Additional catch clauses ——=-—eatch (Excepti on except) A Fil eNotFoundExcepti on 
can appear here. Place { is a special case of an IOException. 


more specific exceptions System.out.printIn(except.getMessage) ; 
before more general ones. } 





In the second exception handler, we call exception. getMessage() to retrieve the message 
associated with the exception. When the parseInt method throws a NumberFormatExcep- 
tion, the message contains the string that it was unable to format. When you throw an 
exception, you can provide your own message string. For example, when you call 


throw new IllegalArgumentException("Amount exceeds balance"); 


the message of the exception is the string provided in the constructor. 

In these sample catch clauses, we merely inform the user of the source of the prob- 
lem. Often, it is better to give the user another chance to provide a correct input—see 
Section 7.5 for a solution. 


7.4.3 Checked Exceptions 


In Java, the exceptions that you can throw and catch fall into three categories. 


e Internal errors are reported by descendants of the type Error. One example is the 
OutOfMemoryError, which is thrown when all available computer memory has been 
used up. These are fatal errors that happen rarely, and we will not consider them 


in this book. 

e Descendants of RuntimeException, such as as IndexOutOfBoundsException or I1legal- 
ArgumentException indicate errors in your code. They are called unchecked 
exceptions. 


342 Chapter 7 Input/Output and Exception Handling 


Checked exceptions 
are due to external 
circumstances that 
the programmer 
cannot prevent. 
The compiler 
checks that your 
program handles 
these exceptions. 


Add a throws clause 
to a method that can 
throw a checked 
exception. 





e All other exceptions are checked exceptions. These exceptions indicate that 
something has gone wrong for some external reason beyond your control. In 
Figure 2, the checked exceptions are shaded in a darker color. 


Why have two kinds of exceptions? A checked exception describes a problem that 
can occur, no matter how careful you are. For example, an I0Exception can be caused 
by forces beyond your control, such as a disk error or a broken network connection. 
The compiler takes checked exceptions very seriously and ensures that they are han- 
dled. Your program will not compile if you don’t indicate how to deal with a checked 
exception. 

The unchecked exceptions, on the other hand, are your fault. The compiler does 
not check whether you handle an unchecked exception, such as an IndexOutOfBounds- 
Exception. After all, you should check your index values rather than install a handler 
for that exception. 

If you have a handler for a checked exception in the same method that may throw 
it, then the compiler is satisfied. For example, 

try 

{ 


File inFile = new File(filename) ; 
Scanner in = new Scanner(inFile); // Throws FileNotFoundException 


catch (FileNotFoundException exception) // Exception caught here 


{ 
} 


However, it commonly happens that the current method cannot handle the excep- 
tion. In that case, you need to tell the compiler that you are aware of this exception 
and that you want your method to be terminated when it occurs. You supply a 
method with a throws clause. 


public static String readData(String filename) throws FileNotFoundException 


{ 


File inFile = new File(filename) ; 
Scanner in = new Scanner(inFile); 


The throws clause signals the caller of your method that it may encounter a 
FileNotFoundException. Then the caller needs to make the same decision—han- 
dle the exception, or declare that the exception may be thrown. 

It sounds somehow irresponsible not to handle an exception when you 
know that it happened. Actually, the opposite is true. Java provides an 
exception handling facility so that an exception can be sent to the appropri- 
ate handler. Some methods detect errors, some methods handle them, and 
some methods just pass them along. The throws clause simply ensures that no 
exceptions get lost along the way. 


Just as trucks with large or hazardous loads carry warning signs, 
the throws clause warns the caller that an exception may occur. 


7.4 ExceptionHandling 343 


Syntax 7.3 The throws Clause 


Syntax modifiers returnType methodName(parameterType pavameterName, . . . 
throws ExceptionClass, ExceptionClass, . . . 


public static String readData(String filename) 
throws FileNotFoundException, NumberFormatException 


You must specify all checked exceptions You may also list unchecked exceptions. 
that this method may throw. 





7.4.4 The finally Clause 


Scene Occasionally, you need to take some action whether or not an exception is thrown. 


is entered, the The finally construct is used to handle this situation. Here is a typical situation. 
statements in a It is important to close a PrintWriter to ensure that all output is written to the file. 
Pimellyagauseite In the following code segment, we open a stream, call one or more methods, and then 
guaranteed to be 

executed, whether close the stream: 

or not an exception : ‘ _ : i . . 

SCC PrintWriter out = new PrintWriter(filename) ; 


writeData(out) ; 
out.closeQ); // May never get here 


Now suppose that one of the methods before the last line throws an exception. Then 
the call to close is never executed! You solve this problem by placing the call to close 
inside a finally clause: 

PrintWriter out = new PrintWriter(filename) ; 

try 

{ 


writeData(out) ; 


} 
finally 


out.close(); 


} 


In anormal case, there will be no problem. When the 
try block is completed, the finally clause is executed, 
and the writer is closed. However, if an exception 
occurs, the finally clause is also executed before the 


exception is passed to its handler. 


© A program that Use the finally clause whenever you need to do 
demonstrates some clean up, such as closing a file, to ensure that 
TO Ina ale: the clean up happens no matter how the method 
catching exceptions. : 
exits. 


All visitors to a foreign country have to go through 
passport control, no matter what happened on their 
trip. Similarly, the code in a finally clause is always 

executed, even when an exception has occurred. 





344 Chapter 7 Input/Output and Exception Handling 


Syntax 7.4 The finally Clause 


Syntax try 
{ 


statement 
statement 


} 
finally 


{ 
statement 
statement 


This variable must be declared outside the try block 
so that the finally clause can access it. 


PrintWriter out = new PrintWriter(filename) ; 
This code may try 
throw exceptions. rf 
Se writeData(out) ; 


} 


. . finally 
This code is { 


always executed, elitactose(): 
even if an exception occurs. — | } 












Ss 
& ; 


16. Suppose balance is 100 and amount is 200. What is the value of balance after these 
statements? 


if (amount > balance) 


{ 
} 


balance = balance - amount; 


throw new IllegalArgumentException("Amount exceeds balance"); 


17. When depositing an amount into a bank account, we don’t have to worry about 
overdrafts —except when the amount is negative. Write a statement that throws 
an appropriate exception in that case. 


18. Consider the method 


public static void main(String[] args) 
{ 
try 
{ 
Scanner in = new Scanner(new FileC"input.txt")); 
int value = in.nextIntQ; 
System.out.printIn(value) ; 
} 
catch (IOException exception) 


{ 
} 


System.out.printIn("Error opening file."); 


} 


Practice It 


Programming Tip 7.1 


os 


cole leclaalaaliale mal oar 


ee 








7.4 ExceptionHandling 345 


Suppose the file with the given file name exists and has no contents. Trace the 
flow of execution. 
19. Why is an ArrayIndexOutOfBoundsException not a checked exception? 
20. Is there a difference between catching checked and unchecked exceptions? 
21. What is wrong with the following code, and how can you fix it? 
public static void writeAll(String[] lines, String filename) 


{ 
PrintWriter out = new PrintWriter(filename) ; 
for (String line : lines) 


{ 

out.printIn(line.toUpperCase()); 
} 
out.close(); 


} 


Now you can try these exercises at the end of the chapter: R7.7, R7.8, R7.9. 


Throw Early, Catch Late 


When a method detects a problem that it cannot solve, it is better 
to throw an exception rather than try to come up with an imperfect Ue atone 
fix. For example, suppose a method expects to read a number froma _ problem is detected. 
file, and the file doesn’t contain a number. Simply using a zero value —_ Catch it only 
would be a poor choice because it hides the actual problem and per- — when the problem 
haps causes a different problem elsewhere. can be handled: 
Conversely, a method should only catch an exception if it can 
really remedy the situation. Otherwise, the best remedy is simply to have the exception propa- 
gate to its caller, allowing it to be caught by a competent handler. 
These principles can be summarized with the slogan “throw early, catch late”. 


Do Not Squelch Exceptions 


When you call a method that throws a checked exception and you haven’t specified a handler, 
the compiler complains. In your eagerness to continue your work, it is an understandable 
impulse to shut the compiler up by squelching the exception: 


try 
{ 
Scanner in = new Scanner(new File(filename)); 
// Compiler complained about FileNotFoundException 


} 
catch (FileNotFoundException e) {} // So there! 


The do-nothing exception handler fools the compiler into thinking that the exception has 
been handled. In the long run, this is clearly a bad idea. Exceptions were designed to transmit 
problem reports to a competent handler. Installing an incompetent handler simply hides an 
error condition that could be serious. 


346 Chapter 7 Input/Output and Exception Handling 


core leclaalaaliale mil oats) 


Sy of <\ol f-1  Ko) 0) | om as) 





Do Not Use catch and finally in the Same try Statement 


It is possible to have a finally clause following one or more catch clauses. Then the code in the 
finally clause is executed whenever the try block is exited in any of three ways: 


1. After completing the last statement of the try block 


2. After completing the last statement of a catch clause, if this try block caught an 
exception 


3. When an exception was thrown in the try block and not caught 


It is tempting to combine catch and finally clauses, but the resulting code can be hard to 
understand, and it is often incorrect. Instead, use two statements: 


e atry/finally statement to close resources 
© aseparate try/catch statement to handle errors 
For example, 


try 
{ 
PrintWriter out = new PrintWriter(filename) ; 
try 
{ 
Write output. 


t 
finally 


{ 


out.close(); 
} 
} 


catch (IOException exception) 


Handle exception. 
} 


Note that the nested statements work correctly if the Printwriter constructor throws an excep- 
tion, too. 


Automatic Resource Management in Java 7 


In Java 7, you can use a new form of the try block that automatically closes a PrintWriter or 
Scanner object. Here is the syntax: 


try (PrintWriter out = new PrintWriter(filename)) 


{ 
Write output to out. 


} 


The close method is automatically invoked on the out object when the try block ends, whether 
or not an exception has occurred. A finally statement is not required. 


7.5 Application: Handling Input Errors 


347 


TE Random Fact 7.2 The Ariane Rocket Incident 





The European Space 
: Agency (ESA), Europe’s 
counterpart to NASA, had developed a 
rocket model called Ariane that it had 
successfully used several times to 
launch satellites and scientific experi- 
ments into space. However, when anew 
version, the Ariane 5, was launched on 
June 4, 1996, from ESA's launch site 
in Kourou, French Guiana, the rocket 
veered off course about 40 seconds 
after liftoff. Flying at an angle of more 
than 20 degrees, rather than straight 
up, exerted such an aerodynamic force 
that the boosters separated, which trig- 
gered the automatic self-destruction 
mechanism. The rocket blew itself up. 
The ultimate cause of this accident 
was an unhandled exception! The 
rocket contained two identical devices 
(called inertial reference systems) that 
processed flight data from measuring 
devices and turned the data into infor- 
mation about the rocket position. 





The Explosion of the Ariane Rocket 


lication: Han 


The onboard computer used the posi- 
tion information for controlling the 
boosters. The same inertial reference 
systems and computer software had 
worked fine on the Ariane 4. 

However, due to design changes 
to the rocket, one of the sensors mea- 
sured a larger acceleration force than 
had been encountered in the Ariane 4. 
That value, expressed as a floating- 
point value, was stored in a 16-bit 
integer (like a short variable in Java). 
Unlike Java, the Ada language, used 
for the device software, generates an 
exception if a floating-point number is 
too large to be converted to an integer. 
Unfortunately, the programmers of the 
device had decided that this situation 
would never happen and didn’t provide 
an exception handler. 

When the overflow did happen, the 
exception was triggered and, because 
there was no handler, the device shut 
itself off. The onboard computer sensed 


the failure and switched over to the 
backup device. However, that device 
had shut itself off for exactly the same 
reason, something that the designers 
of the rocket had not expected. They 
figured that the devices might fail for 
mechanical reasons, and the chance of 
two devices having the same mechani- 
cal failure was considered remote. At 
that point, the rocket was without reli- 
able position information and went off 
course. 

Perhaps it would have been better if 
the software hadn’t been so thorough? 
If it had ignored the overflow, the 
device wouldn’t have been shut off. It 
would have computed bad data. But 
then the device would have reported 
wrong position data, which could have 
been just as fatal. Instead, a correct 
implementation should have caught 
overflow exceptions and come up with 
some strategy to recompute the flight 
data. Clearly, giving up was not a 
reasonable option in this context. 

The advantage of 
the exception-handling 
mechanism is that it 
makes these issues 
explicit to program- 
mers—something to 
think about when you 
curse the Java compiler 
for complaining about 
uncaught exceptions. 


ling In Error 


This section walks through an example program that includes exception handling. 
The program, DataAnalyzer. java, asks the user for the name of a file. The file is expected 
to contain data values. The first line of the file should contain the total number of val- 
ues, and the remaining lines contain the data. A typical input file looks like this: 


3 

1.45 
= 2d. 
0.05 


348 Chapter 7 Input/Output and Exception Handling 


When designing a 
program, ask your- 
self what kinds of 


exceptions can occur. 


For each exception, 
you need to decide 
which part of 

your program 

can competently 
handle it. 


What can go wrong? There are two principal risks. 


e The file might not exist. 
e The file might have data in the wrong format. 


Who can detect these faults? The Scanner constructor will throw an exception when 
the file does not exist. The methods that process the input values need to throw an 
exception when they find an error in the data format. 

What exceptions can be thrown? The Scanner constructor throws a FileNot- 
FoundException when the file does not exist, which is appropriate in our situation. 
When there are fewer data items than expected, or when the file doesn’t start with the 
count of values, the program will throw an NoSuchElementException. Finally, when there 
are more inputs than expected, an 10Exception should be thrown. 

Who can remedy the faults that the exceptions report? Only the main method of 
the DataAnalyzer program interacts with the user, so it catches the exceptions, prints 
appropriate error messages, and gives the user another chance to enter a correct file: 

// Keep trying until there are no more exceptions 

boolean done = false; 

while (!done) 

{ 

try 
{ 
Prompt user for file name. 


double[] data = readFile(filename) ; 
Process data. 
done = true; 


catch (FileNotFoundException exception) 


{ 


System.out.printIn("File not found."); 


} 


catch (NoSuchElementException exception) 


{ 
System.out.printIn("File contents invalid."); 


} 


catch (IOException exception) 


{ 


exception.printStackTraceQ) ; 
} 
} 


The first two catch clauses in the main method give a human-readable error report if 
bad data was encountered or the file was not found. However, if another IOException 
occurs, then it prints a stack trace so that a programmer can diagnose the problem. 

The following readFile method constructs the Scanner object and calls the readData 
method. It does not handle any exceptions. If there is a problem with the input file, it 
simply passes the exception to its caller. 


public static double[] readFile(String filename) throws IOException 
{ 

File inFile = new File(filename) ; 

Scanner in = new Scanner(inFile); 

try 

{ 


7.5 Application: Handling Input Errors 349 


return readData(in); 


} 
finally 


in.close(); 


} 


Note how the finally clause ensures that the file is closed even when an exception 
occurs. 

Also note that the throws clause of the readFile method need not include the File- 
NotFoundException class because it is a special case of an I0Exception. 

The readData method reads the number of values, constructs an array, and fills it 
with the data values. 


public static double[] readData(Scanner in) throws IOException 

{ 
int numberOfValues = in.nextIntQ); // May throw NoSuchElementException 
double[] data = new double[numberOfValues] ; 


i] 


for (int i = 0; i < numberOfValues; i++) 


data[i] = in.nextDouble(); // May throw NoSuchElementException 
} 


if Cin. hasNext(Q)) 
{ 


} 


return data; 


throw new IOException("End of file expected"); 


} 


As discussed in Section 7.2.7, the calls to the nextInt and nextDouble methods can throw 
a NoSuchElementException when there is no input at all or an InputMismatchException if the 
input is not a number. As you can see from Figure 2 on page 340, an InputMismatch- 
Exception is a special case of a NoSuchElementException. 

You need not declare the NoSuchElementException in the throws clause because it is not 
a checked exception, but you can include it for greater clarity. 

There are three potential errors: 


e The file might not start with an integer. 
e There might not bea sufficient number of data values. 
e There might be additional input after reading all data values. 
In the first two cases, the Scanner throws a NoSuchElementException. Note again that this 
is not a checked exception—we could have avoided it by calling hasNextInt/hasNext- 
Double first. However, this method does not know what to do in this case, so it allows 
the exception to be sent to a handler elsewhere. 

When we find that there is additional unexpected input, we throw an IOException. 
To see the exception handling at work, look at a specific error scenario. 

1. main calls readFile. 

2. readFile calls readData. 

3. readData calls Scanner .nextInt. 

4. 


There is no integer in the input, and Scanner.nextInt throws a NoSuchElement- 
Exception. 


350 Chapter 7 Input/Output and Exception Handling 


5. readData has no catch clause. It terminates immediately. 


. readFile has no catch clause. It terminates immediately after executing the 


finally clause and closing the file. 


. The first catch clause in main is for a FileNotFoundException. The exception that is 


currently being thrown is a NoSuchElementException, and this handler doesn’t 
apply. 


. The next catch clause is for a NoSuchElementException, and execution resumes 


here. That handler prints a message to the user. Afterward, the user is given 
another chance to enter a file name. Note that the statements for processing the 
data have been skipped. 


This example shows the separation between error detection (in the readData method) 
and error handling (in the main method). In between the two is the readFile method, 
which simply passes the exceptions along. 


section_5/DataAnalyzer.java 


import java.io.File; 

jmport java.io.FileNotFoundException; 
import java.io. IOException; 

import java.util.Scanner; 

import java.util .NoSuchElementException; 


[** 

This program processes a file containing a count followed by data values. 

If the file doesn’t exist or the format is incorrect, you can specify another file. 
*/ 
public class DataAnalyzer 


{ 


public static void main(String[] args) 


{ 


Scanner in = new Scanner(System. in) ; 
// Keep trying until there are no more exceptions 


boolean done = false; 
while (!done) 
{ 
try 
{ 
System.out.print("Please enter the file name: "); 
String filename = in.next(); 


double[] data = readFile(filename) ; 
// Asan example for processing the data, we compute the sum 


double sum = 0; 
for (double d : data) { sum = sum + d; } 


System.out.printIn('The sum is “ + sum); 
done = true; 

} 

catch (FileNotFoundException exception) 

{ 


System.out.printInC"File not found."); 


7.5 Application: Handling Input Errors 351 


40 } 

41 catch (NoSuchElementException exception) 

42 { 

43 System.out.printInC"File contents invalid."); 
44 

45 catch (IOException exception) 

46 { 

47 exception.printStackTrace() ; 

48 } 

49 } 

50 } 

51 

52 /** 

53 Opens a file and reads a data set. 

54 @param filename the name of the file holding the data 
55 @return the data in the file 

56 */ 

57 public static double[] readFile(String filename) throws IOException 
58 { 

59 File inFile = new File(filename); 

60 Scanner in = new Scanner(inFile); 

61 try 

62 { 

63 return readData(in) ; 

64 } 

65 finally 

66 { 

67 in.closeQ); 

68 } 

69 } 

70 

71 /** 

72 Reads a data set. 

73 @param in the scanner that scans the data 

74 @return the data set 

75 a 

76 public static double[] readData(Scanner in) throws IOException 
77 { 

78 int numberOfValues = in.nextIntQ; // May throw NoSuchElementException 
79 double[] data = new double[numberOfValues] ; 

80 

81 for (int i = 0; i < numberOfValues; i++) 

82 { 

83 data[i] = in.nextDouble(); // May throw NoSuchElementException 
84 } 

85 

86 if Cin. hasNext()) 

87 { 

88 throw new IOException("End of file expected"); 
89 } 

90 return data; 

91 } 

92 } 


22. Why doesn’t the readFile method catch any exceptions? 


23. Consider the try/finally statement in the readFile method. Why was the in vari- 
able declared outside the try block? 





352 Chapter 7 Input/Output and Exception Handling 


24. Suppose the user specifies a file that exists and is empty. Trace the flow of execu- 
tion in the DataAnalyzer program. 


25. Why didn’t the readData method call hasNextInt/hasNextDouble to ensure that the 
NoSuchElementException is not thrown? 


Practice It Now youcantry these exercises at the end of the chapter: R7.15, R7.16, P7.13. 


VIDEO EXAMPLE 7.2 Detecting Accounting Fraud 


(Gia In this Video Example, you will see how to detect accounting fraud 
PLUS 


by analyzing digit distributions. You will learn how to read data 
from the Internet and handle exceptional situations. 





Develop programs that read and write files. 


¢ Use the Scanner class for reading text files. 


¢ When writing text files, use the PrintWriter class and the print/print1n/printf 
methods. 


¢ Close all files when you are done processing them. 
Be able to process text in files. 


¢ The next method reads a string that is delimited by white space. 
e The Character class has methods for classifying characters. 
e The nextLine method reads an entire line. 


e Ifa string contains the digits of a number, you use the Integer.parseInt or 
Double. parseDouble method to obtain the number value. 


Process the command line arguments of a program. 


¢ Programs that start from the command line receive the com- 
mand line arguments in the main method. 





Use exception handling to transfer control from an error location to an error handler. 


¢ To signal an exceptional condition, use the throw statement to throw an exception 
object. 


¢ When you throw an exception, processing continues in an exception handler. 


e Place the statements that can cause an exception inside a try 
block, and the handler inside a catch clause. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


Review Exercises 353 


¢ Checked exceptions are due to external circumstances that the programmer 
cannot prevent. The compiler checks that your program handles these exceptions. 
e Adda throws clause to a method that can throw a checked exception. 


¢ Onceatry block is entered, the statements in a finally clause are 
guaranteed to be executed, whether or not an exception is 
thrown. 





¢ Throw an exception as soon as a problem is detected. Catch it 
only when the problem can be handled. 





Use exception handling in a program that processes input. 


e¢ When designing a program, ask yourself what kinds of exceptions can occur. 


¢ For each exception, you need to decide which part of your program can compe- 


tently handle it. 
java.io.File java. lang.NumberFormatException 
java.io.FileNotFoundException java. lang.RuntimeException 
java.io. IOException java. lang. Throwable 
java.io.PrintWriter getMessage 
close printStackTrace 
java. lang.Character java.net.URL 
isDigit openStream 
jisLetter java.util .InputMismatchException 
isLowerCase java.util .NoSuchElementException 
isUpperCase java.util.Scanner 
iswhiteSpace close 
java. lang.Double hasNextLine 
parseDouble nextLine 
java. lang.Error useDelimiter 
java. lang. Integer javax.swing.JFileChooser 
parseInt getSelectedFile 
java. lang.I1legalArgumentException showOpenDialog 
java. lang.Nul]PointerException showSaveDialog 


##R7.1 What happens if you try to opena file for reading that doesn’t exist? What happens if 
you try to opena file for writing that doesn’t exist? 


##R7.2 What happens if you try to opena file for writing, but the file or device is write- 
protected (sometimes called read-only)? Try it out with a short test program. 


» R7.3, How do you opena file whose name contains a backslash, like c:temp\output . dat? 
»R7.4 Ifa program Woozle is started with the command 
java Woozle -Dname=piglet -I\eeyore -v heff.txt a.txt lump.txt 


what are the values of args[0], args[1], and so on? 


#R7.5 What is the difference between throwing an exception and catching an exception? 


354 Chapter 7 Input/Output and Exception Handling 


# R7.6 What is a checked exception? What is an unchecked exception? Give an example for 
each. Which exceptions do you need to declare with the throws reserved word? 


#=R7.7 Why don’t you need to declare that your method might throw an IndexOutOfBounds- 
Exception? 


«2 R7.8 When your program executes a throw statement, which statement is executed next? 
##R7.9 What happens if an exception does not have a matching catch clause? 
##R7.10 What can your program do with the exception object that a catch clause receives? 


«= R7.11 Is the type of the exception object always the same as the type declared in the catch 
clause that catches it? If not, why not? 


» R7.12 What is the purpose of the finally clause? Give an example of how it can be used. 


»#R7.13 | What happens when an exception is thrown, the code of a finally clause executes, 
and that code throws an exception of a different kind than the original one? Which 
one is caught by a surrounding catch clause? Write a sample program to try it out. 


##R7.14 Which exceptions can the next and nextInt methods of the Scanner class throw? Are 
they checked exceptions or unchecked exceptions? 


«= R7.15 Suppose the program in Section 7.5 reads a file containing the following values: 


1 

2 

3 

4 
What is the outcome? How could the program be improved to give a more accurate 
error report? 


== R7.16 Can the readFile method in Section 7.5 throw a Nul1PointerException? If so, how? 


« P7.1 Write a program that carries out the following tasks: 


Open a file with the name hello.txt. 

Store the message “Hello, World!” in the file. 

Close the file. 

Open the same file again. 

Read the message into a string variable and print it. 


=» P7.2 Write a program that reads a file containing text. Read each line and send it to the 
output file, preceded by line numbers. If the input file is 


Mary had a little lamb 

Whose fleece was white as snow. 
And everywhere that Mary went, 
The lamb was sure to go! 


then the program produces the output file 


/* 1 */ Mary had a little lamb 

/* 2 */ Whose fleece was white as snow. 
/* 3 */ And everywhere that Mary went, 
/* 4 */ The lamb was sure to go! 





= P7,3 


=o P7.4 


aa P7,5 


an P7.6 


an P7.7 


aa P7.8 


an P7.9 


Programming Exercises 355 


The line numbers are enclosed in /* */ delimiters so that the program can be used for 
numbering Java source files. 
Prompt the user for the input and output file names. 


Repeat Exercise P7.2, but allow the user to specify the file name on the command- 
line. If the user doesn’t specify any file name, then prompt the user for the name. 


Write a program that reads a file containing two columns of floating-point numbers. 
Prompt the user for the file name. Print the average of each column. 


Write a program that asks the user for a file name and prints the number of charac- 
ters, words, and lines in that file. 


Write a program Find that searches all files specified on the command line and prints 
out all lines containing a specified word. For example, if you call 


java Find ring report.txt address.txt Homework. java 
then the program might print 


report.txt: has broken up an international ring of DVD bootleggers that 
address.txt: Kris Kringle, North Pole 

address.txt: Homer Simpson, Springfield 

Homework. java: String filename; 


The specified word is always the first command line argument. 


Write a program that checks the spelling of all words ina file. It should read each 
word of a file and check whether it is contained in a word list. A word list is avail- 
able on most Linux systems in the file /usr/share/dict/words. (If you don’t have access 
to a Linux system, your instructor should be able to get you a copy.) The program 
should print out all words that it cannot find in the word list. 


Write a program that replaces each line of a file with its reverse. For example, if you 
run 

java Reverse HelloPrinter. java 
then the contents of He11oPrinter. java are changed to 


retnirPolleH ssalc cilbup 


{ 


)sgra J[gnirtS(niam diov citats cilbup 


{ 


wodniw elosnoc eht ni gniteerg a yalpsiD // 


;)"!dlroW ,olleH"(nitnirp.tuo.metsyS 
} 
} 


Of course, if you run Reverse twice on the same file, you get back the original file. 
Write a program that reads each line ina file, reverses its lines, and writes them to 
another file. For example, if the file input.txt contains the lines 


Mary had a little lamb 

Its fleece was white as snow 
And everywhere that Mary went 
The lamb was sure to go. 


and you run 
reverse input.txt output.txt 


then output.txt contains 


356 Chapter 7 Input/Output and Exception Handling 


a P7.10 


ua P7,11 


aue P7.12 


aa P7,13 


ua P7.14 


oe P7,15 


== Business P7.16 


=a Business P7.17 


== Business P7.18 


The lamb was sure to go. 

And everywhere that Mary went 
Its fleece was white as snow 
Mary had a little lamb 


Get the data for names in prior decades from the Social Security Administration. 
Paste the table data in files named babynames80s.txt, etc. Modify the worked_examp1e_1/ 
BabyNames . java program so that it prompts the user for a file name. The numbers in 
the files have comma separators, so modify the program to handle them. Can you 
spot a trend in the frequencies? 


Write a program that reads in worked_example_1/babynames.txt and produces two files, 
boynames.txt and girlnames.txt, separating the data for the boys and girls. 


Write a program that reads a file in the same format as worked_example_1/babynames. txt 
and prints all names that are both boy and girl names (such as Alexis or Morgan). 


Write a program that asks the user to input a set of floating-point values. When the 
user enters a value that is not a number, give the user a second chance to enter the 
value. After two chances, quit reading input. Add all correctly specified values and 
print the sum when the user is done entering data. Use exception handling to detect 
improper inputs. 


Using the mechanism described in Special Topic 7.1, write a program that reads all 
data from a web page and writes them to a file. Prompt the user for the web page 


URL and the file. 


Using the mechanism described in Special Topic 7.1, write a program that reads all 
data from a web page and prints all hyperlinks of the form 


<a href="link">link text</a> 


Extra credit if your program can follow the links that it finds and find links in those 
web pages as well. (This is the method that search engines such as Google use to find 
web sites.) 


A hotel salesperson enters sales in a text file. Each line contains the following, 
separated by semicolons: The name of the client, the service sold (such as Dinner, 
Conference, Lodging, and so on), the amount of the sale, and the date of that event. 
Write a program that reads such a file and displays the total amount for each service 
category. Display an error if the file does not exist or the format is incorrect. 


Write a program that reads a text file as described in Exercise P7.16, and that writes a 
separate file for each service category, containing the entries for that category. Name 
the output files Dinner. txt, Conference. txt, and so on. 


A store owner keeps a record of daily cash transactions ina text file. Each line 
contains three items: The invoice number, the cash amount, and the letter P if the 
amount was paid or R if it was received. Items are separated by spaces. Write a pro- 
gram that prompts the store owner for the amount of cash at the beginning and end 
of the day, and the name of the file. Your program should check whether the actual 
amount of cash at the end of the day equals the expected value. 


uae Science P7.19 


uae Science P7.20 


Programming Exercises 357 


After the switch in the figure below closes, the voltage (in volts) across the capacitor 
is represented by the equation 


v(t) = B(1 - el(RC)) 


Suppose the parameters of the electric circuit are B = 12 volts, R = 500 Q, and 
C=0.25 uF. Consequently 


v(t) = 12(1 - €7 0-008") 


where t has units of us. Read a file params. txt containing the values for B, R, C, and 
the starting and ending values for t. Write a file rc. txt of values for the time ¢ and the 
corresponding capacitor voltage v(t), where t goes from the given starting value to 
the given ending value in 100 steps. In our example, if t goes from 0 to 1,000 us, the 
twelfth entry in the output file would be: 


110 7.02261 


The figure below shows a plot of the capacitor voltage from the circuit shown in 
Exercise P7.19. The capacitor voltage increases from 0 volts to B volts. The “rise 
time” is defined as the time required for the capacitor voltage to change from 

v1, =0.05 x Btov,=0.95 x B. 





0 t (ps) 


The file rc. txt contains a list of values of time t and the corresponding capacitor 
voltage v(t). A time in us and the corresponding voltage in volts are printed on the 
same line. For example, the line 


110 7.02261 


indicates that the capacitor voltage is 7.02261 volts when the time is 110 us. The time 
is increasing in the data file. 


Write a program that reads the file rc.txt and uses the data to calculate the rise time. 
Approximate B by the voltage in the last line of the file, and find the data points that 
are closest to 0.05 x B and 0.95 x B. 


358 Chapter 7 Input/Output and Exception Handling 


«= Science P7.21 Suppose a file contains bond energies and bond lengths for covalent bonds in the 
following format: 





Single, double, Bond energy Bond length 

or triple bond (kJ/mol) (nm) 
C|c 370 0.154 
C||C 680 0.13 
C|||C 890 0.12 
C|H 435 0.11 
C|N 305 0.15 
ClO 360 0.14 
C\|F 450 0.14 
C|Cl 340 0.18 
O|H 500 0.10 
O|O 220 0.15 
O|si 375 0.16 
N|H 430 0.10 
N|O 250 0.12 
FF 160 0.14 
H|H 435 0.074 


Write a program that accepts data from one column and returns the corresponding 
data from the other columns in the stored file. If input data matches different rows, 
then return all matching row data. For example, a bond length input of 0.12 should 
return triple bond C|||C and bond energy 890 kJ/mol and single bond N|O and bond 
energy 250 kJ/mol. 


ANSWERS TO SELF-CHECK QUESTIONS 


. When the Printwriter object is created, the out- 
put file is emptied. Sadly, that is the same file as 
the input file. The input file is now empty and 
the while loop exits immediately. 


. The program throws a FileNotFoundException 
and terminates. 


« Open a scanner for the file. 
For each number in the scanner 

Add the number to an array. 
Close the scanner. 
Set total to 0. 
Open a print writer for the file. 
For each number in the array 

Write the number to the print writer. 

Add the number to total. 
Write total to the print writer. 
Close the print writer. 
. Adda variable count that is incremented when- 
ever a number is read. In the end, print the 
average, not the total, as 
%8.2~\n", 
Because the string "Average" is three characters 
longer than "Total", change the other output to 
out.printf("%18.2f\n", value). 
. Adda variable count that is incremented when- 
ever a number is read. Only write a new line 
when it is even. 


out.printf("Average: total / count); 


count++; 

out.printf("%8.2f", value); 

if (count % 2 == 0) { out.printin(Q); } 

At the end of the loop, write a new line if count 
is odd, then write the total: 

1) { out.printingd); } 
%10.2f\n", total); 


and input is "World!" 


if (count % 2 == 
out.printf("Total: 


. wordis "Hello," 


. Because 995.0 is not an integer, the call 
in.hasNextInt() returns false, and the call 
in.nextInt() is skipped. The value of number 
stays 0, and input is set to the string "995.0". 


. x11s set to 6000000. Because a comma is not 
considered a part of a floating-point number 
in Java, the second call to nextDouble causes an 
input mismatch exception and x2 is not set. 


9. 


10. 


11. 
12. 


14. 
15. 


Answers to Self-Check Questions 359 


Read them as strings, and convert those strings 
to numbers that are not equal to N/A: 


String input = in.nextQ); 

if C!input.equals("N/A")) 

{ 
double value = Double.parseDouble(input) ; 
Process value. 

} 


Locate the last character of the country name: 
int j=i-1; 
while (!Character.iswhiteSpace(line.charAt(j))) 
{ 

as 
} 


Then extract the country name: 


String countryName = line.substring(0, j + 1); 

















args[0] is "-d" and args[1] is "file1.txt" 
key | infile ovtFile | i | arg 
4 | __ pil vil | o | -a 
-3 | filel txt | | filet txt 

a 





Then the program prints a message 


Usage: java CaesarCipher [-d] infile outfile 


. The program will run correctly. The loop that 


parses the options does not depend on the 
positions in which the options appear. 


FDHVDU 


Add the lines 
else if (option == 'k') 


key = Integer.parseInt( 
args[i].substring(2)); 


after line 27 and update the usage information. 


. Itis still 100. The last statement was not 


executed because the exception was thrown. 


. if (amount < 0) 


{ 
throw new I1legalArgumentException( 
"Negative amount"); 


360 Chapter 7 Input/Output and Exception Handling 


18. 


19. 


20. 


21. 


The Scanner constructor succeeds because 

the file exists. The nextInt method throws 

a NoSuchElementException. This is zot an 
10Exception. Therefore, the error is not caught. 
Because there is no other handler, an error 
message is printed and the program terminates. 


Because programmers should simply check 
that their array index values are valid instead 
of trying to handle an ArrayIndexOutOfBounds- 
Exception. 


No. You can catch both exception types in the 
same way, as you can see in the code example 
on page 339. 


There are two mistakes. The Printwriter con- 
structor can throw a FileNotFoundException. You 
should supply a throws clause. And if one of the 
array elements is nu11, a Nul1PointerException is 
thrown. In that case, the out.close() statement 
is never executed. You should use a try/finally 
statement. 


22 


23. 


25. 


The exceptions are better handled in the main 
method. 


If it had been declared inside the try block, its 
scope would only have extended until the end 
of the try block, and it would not have been 
accessible in the finally clause. 


. main calls readFile, which calls readData. The call 


in.nextIntQ throws a NoSuchE1 ementException. 
The readFile method doesn’t catch it, so it 
propagates back to main, where it is caught. 
An error message is printed, and the user can 
specify another file. 


We want to throw that exception, so that 
someone else can handle the problem of a bad 


data file. 


TTT S 
OBJECTS AND 
CLASSES 


CHAPTER GOALS 


To understand the concepts of classes, 
objects, and encapsulation 





To implement instance variables, methods, and constructors 
To be able to design, implement, and test your own classes 


To understand the behavior of object references, static variables, and static methods 


CHAPTER CONTENTS 


8.1 OBJECT-ORIENTED Special Topic 8.2: Overloading 380 


PROGRAMMIN 2 
oe oer 8.7 TESTINGACLASS 380 


8.2 IMPLEMENTING A SIMPLE CLASS 364 How To 8.1: Implementing a Class 382 
Syntax 8.1: Instance Variable Declaration 365 Worked Example 8.1: |mplementing a Bank 
Account Class @ 


8.3 SPECIFYING THE PUBLIC INTERFACE Video Example 8.1: Paying Off aLoan © 


OFACLASS 367 
Special Topic 8.1: The javadoc Utility 370 8.8 PROBLEM SOLVING: 


TRACING OBJECTS 386 
8.4 DESIGNING THE DATA 


REPRESENTATION 371 8.9 PROBLEM SOLVING: PATTERNS 
FOR OBJECT DATA 388 

Video Example 8.2: Modeling a Robot Escaping 
from aMaze @ 

Random Fact 8.1: Electronic Voting Machines 394 


8.5 IMPLEMENTING INSTANCE 
METHODS 372 


Syntax 8.2: Instance Methods 373 
Programming Tip 8.1: All Instance Variables 


Should Be Private; Most Methods Should 8.10 OBJECT REFERENCES 395 

Be Public 374 Special Topic 8.3: Calling One Constructor 
8.6 CONSTRUCTORS 375 ihemAnonmer 29° 
Syntax 8.3: Constructors 376 8.11 STATIC VARIABLES AND 
Common Error 8.1: Forgetting to Initialize Object METHODS 400 

References ina Constructor 378 Random Fact 8.2: Open Source and 
Common Error 8.2: Trying to Call Free Software 402 


a Constructor 379 


Common Error 8.3: Declaring a Constructor 
as void 379 








This chapter introduces you to object-oriented program- 
ming, an important technique for writing complex pro- 
grams. In an object-oriented program, you don’t simply 
manipulate numbers and strings, but you work with objects 
that are meaningful for your application. Objects with 
the same behavior (such as the windmills to the left) are 
grouped into classes. A programmer provides the desired 
behavior by specifying and implementing methods for 
these classes. In this chapter, you will learn how to discover, 
specify, and implement your own classes, and how to use 
them in your programs. 


8.1 Object-Oriented Programming 


A class describes a 
set of objects with 
the same behavior. 


ACar class describes passenger vehicles that can 
carry 4-5 people and a small amount of luggage. 


362 


You have learned how to structure your programs by decomposing tasks into meth- 
ods. This is an excellent practice, but experience shows that it does not go far enough. 
It is difficult to understand and update a program that consists of a large collection of 
methods. 

To overcome this problem, computer scientists invented object-oriented pro- 
gramming, a programming style in which tasks are solved by collaborating objects. 
Each object has its own set of data, together with a set of methods that act upon the 
data. 

You have already experienced this programming style when you used strings, the 
System.out object, or a Scanner object. Each of these objects has a set of methods. For 
example, you can use the length and substring methods to work with String objects. 

When you develop an object-oriented program, you create your own objects that 
describe what is important in your application. For example, in a student database 
you might work with Student and Course objects. Of course, then you must supply 
methods for these objects. 

In Java, a programmer doesn’t implement a single object. Instead, the program- 
mer provides a class. A class describes a set of objects with the same behavior. For 
example, the String class describes the behavior of all strings. The class specifies how 





Every class has a 
public interface: a 
collection of methods 
through which the 
objects of the class 
can be manipulated. 


Encapsulation is 

the act of providing 

a public interface and 
hiding the implemen- 
tation details. 


Encapsulation 
enables changes in 
the implementation 
without affecting 
users of aclass. 


You can drive a car by operating the 
steering wheel and pedals, without 
knowing how the engine works. 
Similarly, you use an object through its 
methods. The implementation is hidden. 


8.1 Object-Oriented Programming 363 


a string stores its characters, which methods can be used with strings, and how the 
methods are implemented. 

In contrast, the PrintStream class describes the behavior of objects that can be used 
to produce output. One such object is System. out, and you have seen in Chapter 7 how 
to create PrintStream objects that send output to a file. 

Each class defines a specific set of methods that you can use with its objects. For 
example, when you have a String object, you can invoke the length method: 


"Hello, World". 1Tength() 


We say that the length method is a method of the String class. The PrintStream class has 
a different set of methods. For example, the call 


System.out. lengthQ) 


would be illegal—the PrintStream class has no length method. However, PrintStream 
has a print1n method, and the call 


out.printInC"Hello, World!") 


is legal. 

The set of all methods provided by a class, together with a description of their 
behavior, is called the public interface of the class. 

When you work with an object of a class, you do not know how the object stores 
its data, or how the methods are implemented. You need not know how a String orga- 
nizes a character sequence, or how a PrintWriter object sends data to a file. All you 
need to know is the public interface—which methods you can apply, and what these 
methods do. The process of providing a public interface, while hiding the implemen- 
tation details, is called encapsulation. 

When you design your own classes, you will use encapsulation. That is, you will 
specify a set of public methods and hide the implementation details. Other program- 
mers on your team can then use your classes without having to know their imple- 
mentations, just as you are able to make use of the String and PrintStream classes. 

If you work ona program that is being developed over a long period of time, it is 
common for implementation details to change, usually to make objects more efficient 
or more capable. When the implementation is hidden, the improvements do not affect 
the programmers that use the objects. 





364 Chapter 8 Objects and Classes 


A driver of an electric car doesn't 
have to learn new controls even 
though the car engine is very 
different. Neither does the program- 
mer who uses an object with an 
improved implementation—as long 
as the same methods are used. 





1. Is the method call "He11o0, World". printin© legal? Why or why not? 


2. When using a String object, you do not know how it stores its characters. How 
can you access them? 





3. Describe a way in which a String object might store its characters. 


4. Suppose the providers of your Java compiler decide to change the way that a 
String object stores its characters, and they update the String method implemen- 
tations accordingly. Which parts of your code do you need to change when you 
get the new compiler? 


Practice It Now youcantry these exercises at the end of the chapter: R8.1, R8.4. 


8.2 Impl , simple Cl 


In this section, we look at the implementation of 
avery simple class. You will see how objects store 
their data, and how methods access the data of an 
object. Knowing how a very simple class operates 
will help you design and implement more com- 
plex classes later in this chapter. 

Our first example is a class that models a tally 
counter, a mechanical device that is used to count 
people—for example, to find out how many peo- 
ple attend a concert or board a bus (see Figure 1). 

Whenever the operator pushes a button, the 
counter value advances by one. We model this 
operation with a count method. A physical coun- 
ter has a display to show the current value. In our Figure1 A Tally Counter 
simulation, we use a getValue method instead. 





An object’s instance 
variables store 

the data required 
for executing 

its methods. 


Syntax 8.1 


8.2 Implementing aSimple Class 365 


Here is an example of using the Counter class. First, we construct an object of the 
class: 


Counter tally = new Counter(); 


In Java, you use the new operator to construct objects. We will discuss object con- 
struction in more detail in Section 8.6. 

Next, we invoke methods on our object. First, we invoke the count method twice, 
simulating two button pushes. Then we invoke the getValue method to check how 
many times the button was pushed. 

tally.countQ; 

tally.countQ; 

int result = tally.getValueQ; // Sets result to 2 


We can invoke the methods again, and the result will be different. 


tally.countQ); 
tally.countQ); 


result = tally.getValue(); // Sets result to 4 


As you can see, the tally object remembers the effect of prior method calls. 

When implementing the Counter class, we need to specify how each counter object 
stores its data. In this simple example, that is very straightforward. Each counter 
needs a variable that keeps track of how many times the counter has been advanced. 

An object stores its data in instance variables. An instance of a class is an object of 
the class. Thus, an instance variable is a storage location that is present in each object 
of the class. 

You specify instance variables in the class declaration: 


public class Counter 


{ 


private int value; 
} 
An instance variable declaration consists of the following parts: 


e Anmodifier (private) 
e The type of the instance variable (such as int) 
e The name of the instance variable (such as value) 


Instance Variable Declaration 


Syntax public class ClassName 
{ 


private typeName variableName; 


public class Counter Each object of this class 
{ has a separate copy of 


Instance variables should Brians nt value; tay Instance variant: 


always be private. 
Type of the variable 





366 Chapter 8 Objects and Classes 


Each object of a class 
has its own set of 
instance variables. 


An instance method 
can access the 
instance variables 
of the object on 
which it acts. 


A private instance 
variable can only 
be accessed by the 
methods of its 
own class. 


ONLINE EXAMPLE 


The complete 
Counter class anda 
CounterTester 
program. 


Each object of a class has its own set of instance variables. For example, if concert- 
Counter and boardingCounter are two objects of the Counter class, then each object has its 
own value variable (see Figure 2). 

As you will see in Section 8.6, the instance variable value is set to 0 when a Counter 
object is constructed. 

Next, let us have a quick look at the implementation of the methods of the Counter 
class. The count method advances the counter value by 1. 


public void count() 


{ 


} 


We will cover the syntax of the method header in Section 8.3. For now, focus on the 
body of the method inside the braces. 

Note how the count method increments the instance variable value. Which instance 
variable? The one belonging to the object on which the method is invoked. For exam- 
ple, consider the call 


value = value + 1; 


concertCounter.count(); 


This call advances the value variable of the concertCounter object. 

The methods that you invoke on an object are called instance methods to distin- 
guish them from the static methods of Chapter 5. 

Finally, look at the other instance method of the Counter class. The getvalue method 
returns the current value: 


public int getValue() 
{ 


} 


This method is required so that users of the Counter class can find out how often a 
particular counter has been clicked. A user cannot simply access the value instance 
variable. That variable has been declared with the access specifier private. 

The private specifier restricts access to the methods of the same class. For example, 
the value variable can be accessed by the count and getValue methods of the Counter 
class but not a method of another class. Those other methods need to use the getValue 
method if they want to find out the counter’s value, or the count method if they want 


to change it. 


return value; 






Instance 
variables 


Figure 2_ Instance Variables 


8.3 Specifying the Public Interface ofaClass 367 





These clocks have common behavior, but each of them has a different state. Similarly, objects of 
a class can have their instance variables set to different values. 


Private instance variables are an essential part of encapsulation. They allow a pro- 
grammer to hide the implementation of a class from a class user. 


5. Supply the body of a method public void reset() that resets the counter back to 
zero. 


6. Consider a change to the implementation of the counter. Instead of using an 
integer counter, we use a string of | characters to keep track of the clicks, just like 
a human might do. 





public class Counter 
{ 


private String strokes = ""; 
public void count() 


{ 
strokes = strokes + 


} 


} 
How do you implement the getValue method with this data representation? 


7. Suppose another programmer has used the original Counter class. What changes 
does that programmer have to make in order to use the modified class? 


8. Suppose you use a class Clock with private instance variables hours and minutes. 
How can you access these variables in your program? 


Practice It Now youcantry these exercises at the end of the chapter: P8.1, P8.2. 


When designing a class, you start by specifying its public interface. The public inter- 
face of a class consists of all methods that a user of the class may want to apply to its 
objects. 

Let’s consider a simple example. We want to use objects that simulate cash registers. 
A cashier who rings up a sale presses a key to start the sale, then rings up each item. A 
display shows the amount owed as well as the total number of items purchased. 


368 Chapter 8 Objects and Classes 


In our simulation, we want to call the following methods on a cash register object: 


e Add the price of an item. 


© Get the total amount owed, and the count of 
items purchased. 


e Clear the cash register to start a new sale. 


Here is an outline of the CashRegister class. We sup- 
You can use method 


Readers and nether ply comments for all of the methods to document 
comments to specify their purpose. 

the public interface 

of aclass. pee 


A simulated cash register that tracks the item 
count and the total amount due. 

*/ 

public class CashRegister 


{ 





private data—see Section 8.4 


[** 
Adds an item to this cash register. 
@param price the price of this item 
xf 
public void addItem(double price) 
{ 


} 
[ee 


Gets the price of all items in the current sale. 
@return the total price 

*/ 

public double getTotal() 

{ 


} 
[** 


Gets the number of items in the current sale. 
@return the item count 

*/ 

public int getCount() 

{ 


} 
[** 


Clears the item count and the total. 
*/ 
public void clear() 


{ 
} 


implementation —see Section 8.5 


implementation —see Section 8.5 


implementation —see Section 8.5 


implementation —see Section 8.5 


ONLINE EXAMPLE 


€} The documentation The method declarations and comments make up the public interface of the class. The 
of the public data and the method bodies make up the private implementation of the class. 
interface of the Note that the methods of the CashRegister class are instance methods. They are not 
pe Sregts Esher: declared as static. You invoke them on objects (or instances) of the CashRegister class. 


A mutator method 
changes the object 
on which it operates. 


An accessor method 
does not change 
the object on which 
it operates. 





Practice It 


8.3 Specifying the Public Interface ofaClass 369 





gure -registerl =  —— 
An Object Reference Se 


and an Object 








To see an instance method in action, we first need to construct an object: 


CashRegister registerl = new CashRegister(); 
// Constructs a CashRegister object 


This statement initializes the register1 variable with a reference to a new CashRegister 
object—see Figure 3. (We discuss the process of object construction in Section 8.6 
and object references in Section 8.10.) 

Once the object has been constructed, we are ready to invoke a method: 


registerl.addItem(1.95); // Invokes a method 


When you look at the public interface of a class, it is useful to classify its methods as 
mutators and accessors. A mutator method modifies the object on which it operates. 
The CashRegister class has two mutators: addItem and clear. After you call either of 
these methods, the object has changed. You can observe that change by calling the 
getTotal or getCount method. 

An accessor method queries the object for some information without changing 
it. The CashRegister class has two accessors: getTotal and getCount. Applying either of 
these methods to a CashRegister object simply returns a value and does not modify the 
object. For example, the following statement prints the current total and count: 


System.out.printIn(registerl.getTotal()) + + registerl.getCount()); 


Now we know what a CashRegister object can do, but not ow it does it. Of course, to 
use CashRegister objects in our programs, we don’t need to know. 
In the next sections, you will see how the CashRegister class is implemented. 


9. What does the following code segment print? 


CashRegister reg = new CashRegister(); 
reg.clear(); 

reg.addItem(0.95); 
reg.addItem(0.95); 
System.out.printIn(reg.getCount() + 


+ reg.getTotal()); 
10. What is wrong with the following code segment? 


CashRegister reg = new CashRegister(); 
reg.clear(); 

reg.addItem(0.95); 
System.out.printIn(reg.getAmountDue()) ; 


11. Declare a method getDollars of the CashRegister class that yields the amount of 
the total sale as a dollar value without the cents. 


12. Name two accessor methods of the String class. 
13. Is the nextInt method of the Scanner class an accessor or a mutator? 


14. Provide documentation comments for the Counter class of Section 8.2. 


Now you can try these exercises at the end of the chapter: R8.2, R8.8. 


370 Chapter 8 Objects and Classes 


Special Topic 8.1 





The javadoc Utility 


The javadoc utility formats documentation comments into a neat set of documents that you 
can view in a web browser. It makes good use of the seemingly repetitive phrases. The first 
sentence of each method comment is used for a summary table of all methods of your class 
(see Figure 4). The @param and @return comments are neatly formatted in the detail description 
of each method (see Figure 5). If you omit any of the comments, then javadoc generates docu- 
ments that look strangely empty. 

This documentation format may look familiar. It is the same format that is used in the offi- 
cial Java documentation. The programmers who implement the Java library use javadoc them- 
selves. They too document every class, every method, every parameter, and every return value, 
and then use javadoc to extract the documentation. 

Many integrated programming environments can execute javadoc for you. Alternatively, 
you can invoke the javadoc utility from a shell window, by issuing the command 


javadoc MyClass.java 












CashRegister - Mozilla Firefox 
File Edit View History Bookmarks Tools Help 


& i file:///home/cay/books/bjol/code/ch08/section_8_3/index.html v 

















All Classes 
CashRegister 


Method Summary 


getCount() 
Gets the number of items in the current sale. 


double | getTotal ( ) 
Gets the price of all items in the current sale. 








Figure 4 A Method Summary Generated by javadoc 


») CashRegister - Mozilla Firefox 
File Edit View History Bookmarks Tools Help 








a & yj file:///home/cay/books/bjol/code/ch08/section_8_3/index.html 








All Classes 


CashRegister addItem 


public void addItem(double price) 
Adds an item to this cash register. 


Parameters: 
price - the price of this item 





getTotal 








Figure 5 Method Detail Generated by javadoc 


For each accessor 
method, an object 
must either store or 
compute the result. 


Commonly, there is 
more than one way of 
representing the data 
of an object, and you 
must make a choice. 


8.4 Designing the Data Representation 371 


The javadoc utility produces files such as MyClass. html in HTML format, which you can inspect 
ina browser. You can use hyperlinks to navigate to other classes and methods. 

You can run javadoc before implementing any methods. Just leave all the method bodies 
empty. Don’t run the compiler—it would complain about missing return values. Simply run 
javadoc on your file to generate the documentation for the public interface that you are about 
to implement. 

The javadoc tool is wonderful because it does one thing right: It allows you to put the docu- 
mentation together with your code. That way, when you update your programs, you can see 
right away which documentation needs to be updated. Hopefully, you will update it right then 
and there. Afterward, run javadoc again and get updated information that is timely and nicely 
formatted. 


An object stores its data in instance variables. These are variables that are declared 
inside the class (see Syntax 8.1). 

When implementing a class, you have to determine which data each object needs to 
store. The object needs to have all the information necessary to carry out any method 
call. 

Go through all methods and consider their data requirements. It is a good idea to 
start with the accessor methods. For example, a CashRegister object must be able to 
return the correct value for the getTotal method. That means, it must either store all 
entered prices and compute the total in the method call, or it must store the total. 

Now apply the same reasoning to the getCount method. If the cash register stores all 
entered prices, it can count them in the getCount method. Otherwise, you need to have 
a variable for the count. 

The addItem method receives a price as an 
argument, and it must record the price. If the 
CashRegister object stores an array of entered 
prices, then the addItem method appends the 
price. On the other hand, if we decide to store 
just the item total and count, then the addItem 
method updates these two variables. 

Finally, the clear method must prepare the 
cash register for the next sale, either by emp- 
tying the array of prices or by setting the total 
and count to zero. 

We have now discovered two different 
ways of representing the data that the object 
needs. Either of them will work, and we have 
to make a choice. We will choose the simpler 
one: variables for the total price and the item 
count. (Other options are explored in Exer- 





cises P8.16 and P8.17.) Like a wilderness explorer who needs to 
carry all items that may be needed, an 
int itemCount; object needs to store the data required 


double totalPrice; for any method calls. 


372 Chapter 8 Objects and Classes 


The instance variables are declared in the class, but outside any methods, with the 
private modifier: 


public class CashRegister 


{ 
private int itemCount; 
private double totalPrice; 
} 
ene non Note that method calls can come in any order. For example, consider the CashRegister 
data representation class. After calling 


supports method 


cells hac Atlee registerl.getTotal() 


a program can make another call to 


Reg usbehs add venta) 
@ The CashRegister You should not assume that you can clear the sum ina call to getTotal. Your data rep- 
class wlth instarice resentation should allow for method calls that come in arbitrary order, in the same 
way that occupants of a car can push the various buttons and levers in any order they 
choose. 


variables. 


15. What is wrong with this code segment? 


CashRegister register2 = new CashRegister(); 
register2.clearQ; 

register2.addItem(0.95); 
System.out.printIn(register2.totalPrice) ; 





16. Consider a class Time that represents a point in time, such as 9 A.M. or 3:30 P.M. 
Give two sets of instance variables that can be used for implementing the Time 
class. (Hint for the second set: Military time.) 


17. Suppose the implementor of the Time class changes from one implementation 
strategy to another, keeping the public interface unchanged. What do the pro- 
grammers who use the Time class need to do? 


18. Consider a class Grade that represents a letter grade, such as A+ or B. Give two dif- 
ferent sets of instance variables that can be used for implementing the Grade class. 


Practice It Now youcantry these exercises at the end of the chapter: R8.6, R8.16. 


When implementing a class, you need to provide the bodies for all methods. Imple- 
menting an instance method is very similar to implementing a static method, with one 
essential difference: You can access the instance variables of the class in the method 
body. 

For example, here is the implementation of the addItem method of the CashRegister 
class. (You can find the remaining methods at the end of the next section.) 


public void addItem(double price) 
{ 

jtemCount++; 

totalPrice = totalPrice + price; 


8.5 Implementing Instance Methods 373 


Syntax 8.2 Instance Methods 


Syntax — modifiers returnType methodName(parameterType parameterName, . . . 


method body 
} 


public class CashRegister 


{ 


public void addItem(double price) 
{ 
jtemCount++; 
totalPrice = totalPrice + price; 





; ; Whenever you use an instance variable, such as itemCount or totalPrice, ina method, it 
The object on which 


a method is applied denotes that instance variable of the object on which the method was invoked. For 
is the implicit example, consider the call 
parameter. 


registerl.addItem(1.95); 
The first statement in the addItem method is 
jtemCount++; 


Which itemCount is incremented? In this call, it is the itemCount of the register1 object. 
(See Figure 6.) 


(1) Before the method call. 


Figure 6 
Implicit and Explicit 
Parameters 





374 Chapter 8 


HB The CashRegister 
class with method 
implementations. 


Explicit parameters 
of a method are listed 
in the method 
declaration. 





SELF CHECK 
‘g 





Practice It 


cole le-laalaayiale nm al oxsral 








Objects and Classes 


When an item is added, it affects the 
instance variables of the cash register 
object on which the method is invoked. 





The object on which a method is invoked is called the implicit parameter of the 
method. In Java, you do not actually write the implicit parameter in the method dec- 
laration. For that reason, the parameter is called “implicit”. 

In contrast, parameters that are explicitly mentioned in the method declaration, 
such as the totalPrice parameter variable, are called explicit parameters. Every 
method has exactly one implicit parameter and zero or more explicit parameters. 


19. What are the values of register1.itemCount, register1.totalPrice, register2. 
jtemCount, and register2.totalPrice after these statements? 
CashRegister registerl = new CashRegister(); 
registerl.addItem(0.90); 
registerl.addItem(0.95); 
CashRegister register2 = new CashRegister(); 
register2.addItem(1.90) ; 
20. Implement a method getDollars of the CashRegister class that yields the amount of 
the total sale as a dollar value without the cents. 


21. Consider the substring method of the String class that is described in Section 
2.5.6. How many parameters does it have, and what are their types? 


22. Consider the length method of the String class. How many parameters does it 
have, and what are their types? 


Now you can try these exercises at the end of the chapter: R8.10, P8.16, P8.17, P8.18. 


All Instance Variables Should Be Private; Most Methods 
Should Be Public 


It is possible to declare instance variables as public, but you should not do that in your own 
code. Always use encapsulation, with private instance variables that are manipulated with 
methods. 

Typically, methods are public. However, sometimes you have a method that is used only 
as a helper method by other methods. In that case, you can make the helper method private. 
Simply use the private reserved word when declaring the method. 


A constructor 
initializes the 
instance variables 
of an object. 


A constructor is 
invoked when an 
object is created with 
the new operator. 


The name ofa 
constructor is 
the same as the 
class name. 


A class can have 
multiple 
constructors. 


The compiler picks 
the constructor 
that matches the 
construction 
arguments. 


8.6 Constructors 375 


8.6 Constructors 


A constructor initializes the instance variables of an object. The constructor is 
automatically called whenever an object is created with the new operator. 

You have seen the new operator in Chapter 2. It is used whenever a new object is 
required. For example, the expression new Scanner (System. in) in the statement 


Scanner in = new Scanner(System.in); 


constructs a new object of the Scanner class. Specifically, a constructor of the Scan- 
ner class is called with the argument System. in. That constructor initializes the Scanner 
object. 

The name of a constructor is identical to the name of its class. For example: 


public class CashRegister 


{ 
/** 
Constructs a cash register with cleared item count and total. 
*/ 
public CashRegister() // A constructor 
{ 
jitemCount = 0; 
totalPrice = 0; 
} 
t 


Constructors never return values, but you do not use the void reserved word when 
declaring them. 

Many classes have more than one constructor. This allows you to declare objects 
in different ways. Consider for example a BankAccount class that has two constructors: 


public class BankAccount 


{ 


[** 

Constructs a bank account with a zero balance. 
*/ 
public BankAccount() {.. . } 


[** 
Constructs a bank account with a given balance. 
@param initialBalance the initial balance 

*/ 

public BankAccount(double initialBalance) { ... } 


} 


Both constructors have the same name as the class, BankAccount. The first constructor 
has no parameter variables, whereas the second constructor has a parameter variable 
of type double. 

When you construct an object, the compiler chooses the constructor that matches 
the arguments that you supply. For example, 


BankAccount joesAccount = new BankAccount(); 
// Uses BankAccount() constructor 

BankAccount 1lisasAccount = new BankAccount(499.95) ; 
// Uses BankAccount (double) constructor 


376 Chapter 8 Objects and Classes 


Syntax 8.3 Constructors 


By default, numbers 
are initialized as 0, 
Booleans as false, 
and object references 
as null. 


If you do not provide 
a constructor, a 
constructor with 

no arguments 

is generated. 





public class BankAccount 


{ A constructor has the 
A constructor private double balance; same name as the class. 
has no return type, 


vot even void. public BankAccount() 
{ 


balance = 0; 


} 


These constructors 


initialize the balance public BankAccount(double initialBalance) 
instance variable. ‘ 


balance = initialBalance; ‘i A 
This constructor is 


picked for the expression 
new BankAccount (499.95). 


} 


If you do not initialize an instance variable in a constructor, it is automatically set to a 
default value: 


e Numbers are set to zero. 
e Boolean variables are initialized as false. 


¢ Object and array references are set to the special value nu11 that indicates that no 
object is associated with the variable (see Section 8.10). This is usually not desir- 
able, and you should initialize object references in your constructors (see Com- 
mon Error 8.1 on page 378). 


In this regard, instance variables differ from local variables declared inside methods. 
The computer reports an error if you use a local variable that has not been explicitly 
initialized. 

If you do not supply any constructor for a class, the compiler automatically gener- 
ates a constructor. That constructor has no arguments, and it initializes all instance 
variables with their default values. Therefore, every class has at least one constructor. 

You have now encountered all concepts that are necessary to implement the 
CashRegister class. 


A constructor is like a set of 
assembly instructions for an object. 





8.6 Constructors 377 


The complete code for the class is given here. In the next section, you will see how 
to test the class. 


section_6/CashRegister.java 


1 [** 
2 A simulated cash register that tracks the item count and 
3 the total amount due. 
4 +*/ 
5 public class CashRegister 
6 { 
7 private int itemCount; 
8 private double totalPrice; 
9 
10 /e* 
11 Constructs a cash register with cleared item count and total. 
12 */ 
13 public CashRegister() 
14 { 
15 jtemCount = 0; 
16 totalPrice = 0; 
17 } 
18 
19 /** 
20 Adds an item to this cash register. 
21 @param price the price of this item 
22 */ 
23 public void addItem(double price) 
24 { 
25 jtemCount++; 
26 totalPrice = totalPrice + price; 
27 } 
28 
29 [** 
30 Gets the price of all items in the current sale. 
31 @return the total amount 
32 */ 
33 public double getTotal() 
34 { 
35 return totalPrice; 
36 } 
37 
38 [** 
39 Gets the number of items in the current sale. 
40 @return the item count 
41 */ 
42 public int getCount() 
43 { 
44, return itemCount; 
45 } 
46 
47 [** 
48 Clears the item count and the total. 
49 */ 
50 public void clear() 
51 { 
52 jtemCount = 0; 
53 totalPrice = 0; 
54 } 


378 Chapter 8 Objects and Classes 





Practice It 


(@loyaalaakelamalage) arse 





23. 


24. 


25. 
26. 


27. 


Consider this class: 


public class Person 


{ 


private String name; 


public Person(String firstName, String lastName) 
{ 


name = lastName +", " + firstName; 
} 


} 

If an object is constructed as 

Person harry = new Person("Harry", "Morgan"); 

what is its name instance variable? 

Provide an implementation for a Person constructor so that after the call 
Person p = new Person(); 

the name instance variable of pis "unknown". 

What happens if you supply no constructor for the CashRegister class? 
Consider the following class: 


public class Item 


{ 
private String description; 
private double price; 


public Item) {... } 
// Additional methods omitted 
} 


Provide an implementation for the constructor. Be sure that no instance variable 
is set to null. 


Which constructors should be supplied in the Item class so that each of the fol- 
lowing declarations compiles? 


a. Item item2 = new Item("Corn flakes"); 


b. Item item3 = new Item(3.95); 

c. Item item4 = new Item("Corn flakes", 3.95); 
d. Item item1 = new ItemQ); 

e. Item item5; 


Now you can try these exercises at the end of the chapter: R8.12, P8.4, P8.5. 


Forgetting to Initialize Object References in a Constructor 


Just as it is a common error to forget to initialize a local variable, it is easy to forget about 
instance variables. Every constructor needs to ensure that all instance variables are set to 
appropriate values. 


If you do not initialize an instance variable, the Java compiler will initialize it for you. 


Numbers are initialized with 0, but object references—such as string variables—are set to the 
null reference. 


AR 





(@loyaayankelamaiane) arse) 


AM 


8.6 Constructors 379 


Of course, 0 is often a convenient default for numbers. However, nu11 is hardly ever a con- 
venient default for objects. Consider this “lazy” constructor for a modified version of the 
BankAccount class: 


public class BankAccount 


{ 
private double balance; 
private String owner; 


public BankAccount(double initialBalance) 


{ 


balance = initialBalance; 
} 
} 


In this case, balance is initialized, but the owner variable is set to a nul] reference. This can be a 
problem — it is illegal to call methods on the nu11 reference. 
To avoid this problem, it is a good idea to initialize every instance variable: 


public BankAccount(double initialBalance) 


{ 
balance = initialBalance; 
owner = "None"; 


Trying to Call a Constructor 
A constructor is not a method. You must use it in combination with the new reserved word: 
CashRegister registerl = new CashRegister(); 
After an object has been constructed, you cannot invoke the constructor on that object again. 
For example, you cannot call the constructor to clear an object: 
regi stard.CashRegistent; // Error 


It is true that the constructor can set a mew CashRegister object to the cleared state, but you 
cannot invoke a constructor on an existing object. However, you can replace the object with a 
new one: 


registerl = new CashRegister(); // OK 


Declaring a Constructor as void 
Do not use the void reserved word when you declare a constructor: 
public void BankAccount() // Error—don’t use void! 


This would declare a method with return type void and not a constructor. Unfortunately, the 
Java compiler does not consider this a syntax error. 


380 Chapter 8 Objects and Classes 


Special Topic 8.2 





A unit test verifies 
that a class works 
correctly in isolation, 
outside a complete 
program. 


To test a class, use 
an environment for 
interactive testing, 
or write a tester 
class to execute 
test instructions. 


Overloading 


When the same method name is used for more than one method, then the name is overloaded. 
In Java you can overload method names provided that the parameter types are different. For 
example, you can declare two methods, both called print: 


public void print(CashRegister register) 
public void print(BankAccount account) 


When the print method is called, 
print (x); 


the compiler looks at the type of x. If x is a CashRegister object, the first method is called. If x is an 
BankAccount object, the second method is called. If x is neither, the compiler generates an error. 

We have not used the overloading feature in this book. Instead, we gave each method a 
unique name, such as printRegister or printAccount. However, we have no choice with con- 
structors. Java demands that the name of a constructor equal the name of the class. If a class has 
more than one constructor, then that name must be overloaded. 


8.7 Testing a Class 


In the preceding section, we completed the implementation of the CashRegister class. 
What can you do with it? Of course, you can compile the file CashRegister. java. How- 
ever, you can’t execute the CashRegister class. It doesn’t contain a main method. That is 
normal—most classes don’t contain a main method. They are meant to be combined 
with a class that has a main method. 

In the long run, your class may become a part 
of a larger program that interacts with users, stores 
data in files, and so on. However, before integrat- 
ing a class into a program, it is always a good idea 
to test it in isolation. Testing in isolation, outside a 
complete program, is called unit testing. 

To test your class, you have two choices. Some 
interactive development environments, such as 
Blue] (http://bluej.org) and Dr. Java (http: //drjava. 
org), have commands for constructing objects and 
invoking methods. Then you can test a class sim- 
ply by constructing an object, calling methods, and 
verifying that you get the expected return values. 
Figure 7 shows the result of calling the getTotal 
method ona CashRegister object in Blue]. 

Alternatively, you can write a tester class. A 
tester class is a class with a main method that contains statements to run methods of 
another class. A tester class typically carries out the following steps: 





An engineer tests a part in isolation. 
This is an example of unit testing. 


1. Construct one or more objects of the class that is being tested. 
2. Invoke one or more methods. 
3. Print out one or more results. 


4. Print the expected results. 


8.7 TestingaClass 381 





a [Bluej: register [-[5Ix 
Projet Edit Tools View Help 





New Class. 


double getTotald 


cashRegiL.getTotald Inspect 
returned: irom paste | 














Figure 7 The Return Value of the getTotal Method in Blue) 


Here is a class to run methods of the CashRegister class. The main method constructs 
an object of type CashRegister, invokes the addItem method three times, and then dis- 
plays the result of the getCount and getTotal methods. 


section_7/CashRegisterTester.java 
[** 


2 ‘ This program tests the CashRegister class. 
; ieee class CashRegisterTester 

5 ; public static void main(String[] args) 
g 

9 


{ 
CashRegister registerl = new CashRegister(); 
registerl.addItem(1.95); 
10 registerl.addItem(0.95); 
11 registerl.addItem(2.50); 
12 System.out.printIn(register1l.getCount()); 
13 System.out.printInC'Expected: 3"); 
14 System.out.printf("%.2f\n", registerl.getTotal()); 
15 System.out.printInC"Expected: 5.40"); 
16 } 


Program Run 


3 

Expected: 3 
5.40 

Expected: 5.40 


In our sample program, we add three items totaling $5.40. When displaying the 
method results, we also display messages that describe the values we expect to see. 


382 Chapter 8 Objects and Classes 


Pa This is a very important step. You want to spend some time thinking about what 
Determining the 


expected result the expected result is before you run a test program. This thought process will help 
in advance is an you understand how your program should behave, and it can help you track down 
important part 
of testing. 


errors at an early stage. 

To produce a program, you need to combine the CashRegister and CashRegisterTester 
classes. The details for building the program depend on your compiler and develop- 
ment environment. In most environments, you need to carry out these steps: 

1. Make a new subfolder for your program. 

2. Make two files, one for each class. 

3. Compile both files. 

4. Run the test program. 

Many students are surprised that such a simple program contains two classes. How- 
ever, this is normal. The two classes have entirely different purposes. The CashRegister 


class describes objects that model cash registers. The CashRegisterTester class runs a 
test that puts a CashRegister object through its paces. 


28. How would you enhance the tester class to test the clear method? 


29. When you run the CashRegisterTester program, how many objects of class 
CashRegister are constructed? How many objects of type CashRegisterTester? 





30. Why is the CashRegisterTester class unnecessary in development environments 
that allow interactive testing, such as Blue]? 


Practice It Now youcantry these exercises at the end of the chapter: P8.10, P8.11, P8.21. 





HOW TO 8.1 Implementing a Class 


A very common task is to implement a class whose objects can carry out a set of specified 
actions. This How To walks you through the necessary steps. 
As an example, consider a class Menu. An object of this 

class can display a menu such as 


1) Open new account 

2) Log into existing account 

3) Help 

4) Quit 
Then the menu waits for the user to supply a value. If the 
user does not supply a valid value, the menu is redisplayed, 
and the user can try again. 





Step 1 Get an informal list of the responsibilities of your objects. 


Be careful that you restrict yourself to features that are actually required in the problem. With 
real-world items, such as cash registers or bank accounts, there are potentially dozens of fea- 
tures that might be worth implementing. But your job is not to faithfully model the real world. 
You need to determine only those responsibilities that you need for solving your specific 
problem. 

In the case of the menu, you need to 


Display the menu. 
Get user input. 


8.7 TestingaClass 383 


Now look for hidden responsibilities that aren’t part of the problem description. How do 
objects get created? Which mundane activities need to happen, such as clearing the cash regis- 
ter at the beginning of each sale? 

In the menu example, consider how a menu is produced. The programmer creates an empty 
menu object and then adds options “Open new account”, “Help”, and so on. That is another 
responsibility: 


Add an option. 
Step 2 Specify the public interface. 


Turn the list in Step 1 into a set of methods, with specific types for the parameter variables and 
the return values. Many programmers find this step simpler if they write out method calls that 
are applied to a sample object, like this: 


Menu mainMenu = new Menu(); 
mainMenu.addOption(“Open new account”); 
// Add more options 
int input = mainMenu.getInputQ ; 

Now we have a specific list of methods. 

e void addOption(String option) 

e int getInputQ 


What about displaying the menu? There is no sense in displaying the menu without also ask- 
ing the user for input. However, getInput may need to display the menu more than once if the 
user provides a bad input. Thus, display is a good candidate for a private method. 

To complete the public interface, you need to specify the constructors. Ask yourself what 
information you need in order to construct an object of your class. Sometimes you will want 
two constructors: one that sets all instance variables to a default and one that sets them to user- 
supplied values. 

In the case of the menu example, we can get by with a single constructor that creates an 
empty menu. 

Here is the public interface: 


public class Menu 


{ 
public Menu() {... } 
public void addOption(String option) {.. . } 
public int getInput() {... } 

} 


Step 3. Document the public interface. 


Supply a documentation comment for the class, then comment each method. 
/** 


A menu that is displayed on a console. 
BA 
public class Menu 
{ 

/* * 

Constructs a menu with no options. 
*/ 
public Menu() {... } 


/* * 
Adds an option to the end of this menu. 
@param option the option to add 

*/ 

public void addOption(String option) {.. . } 


384 Chapter 8 


Step 4 


Step 5 


Objects and Classes 


/* * 
Displays the menu, with options numbered starting with 1, 
and prompts the user for input. Repeats until a valid input 


is supplied. 

@return the number that the user supplied 
*/ 
public int getInput() {... } 


} 
Determine instance variables. 


Ask yourself what information an object needs to store to do its job. The object needs to be 
able to process every method using just its instance variables and the method arguments. 

Go through each method, perhaps starting with a simple one or an interesting one, and ask 
yourself what the object needs to carry out the method’s task. Which data items are required in 
addition to the method arguments? Make instance variables for those data items. 

In our example, let’s start with the addOption method. We clearly need to store the added 
menu option so that the menu can be displayed later. How should we store the options? As an 
array list of strings? As one long string? Both approaches can be made to work. We will use an 
array list here. Exercise P8.3 asks you to implement the other approach. 


public class Menu 


{ 


private ArrayList<String> options; 


} 


Now consider the getInput method. It shows the stored options and reads an integer. When 
checking that the input is valid, we need to know the number of menu items. Because we store 
them in an array list, the number of menu items is simply obtained as the size of the array list. 
If you stored the menu items in one long string, you might want to keep another instance vari- 
able that stores the item count. 

We will also need a scanner to read the user input, which we will add as another instance 
variable: 


private Scanner in; 
Implement constructors and methods. 


Implement the constructors and methods in your class, one at a time, starting with the easiest 
ones. For example, here is the implementation of the addOption method: 


public void addOption(String option) 


{ 
options.add (option) ; 


} 


Here is the getInput method. This method is a bit more sophisticated. It loops until a valid 
input has been obtained, displaying the menu options before reading the input. 


public int getInput() 


{ 
int input; 
do 
{ 
for (int i = 0; 7 < options.size(Q); i++) 
{ 
int choice = i+ 1; 
System.out.printIn(choice + ") " + options.get(i)); 
} 
input = in.nextIntQ; 
} 


while (input < 1 || input > options.size(Q)); 


8.7 TestingaClass 385 


return input; 


} 
Finally, we need to supply a constructor to initialize the instance variables: 


public Menu() 

{ 
options = new ArrayList<String>(); 
in = new Scanner(System. in); 


} 


If you find that you have trouble with the implementation of some of your methods, you may 
need to rethink your choice of instance variables. It is common for a beginner to start out with 
a set of instance variables that cannot accurately describe the state of an object. Don’t hesitate 
to go back and rethink your implementation strategy. 

Once you have completed the implementation, compile your class and fix any compiler 
errors. 


Step 6 Test your class. 


Write a short tester program and execute it. The tester program should carry out the method 
calls that you found in Step 2. 


public class MenuTester 
{ 
public static void main(String[] args) 
{ 
Menu mainMenu = new Menu(); 
mainMenu.addOption("Open new account"); 
mainMenu.addOption("Log into existing account"); 
mainMenu.addOption("Help") ; 
mainMenu.addOption("Quit"); 
int input = mainMenu.getInputQ ; 
System.out.printin("Input: " + input) ; 


} 


Program Run 


1) Open new account 

2) Log into existing account 
3) Help 

4) Quit 


1) Open new account 
2) Log into existing account 


3) Help 


@ The complete Menu 4) Quit 
and MenuTester 3 
classes. Input: 3 





WORKED EXAMPLE 8.1 Implementing a Bank Account Class 


+ This Worked Example shows how to develop a class that simulates a bank account. 





@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


386 Chapter 8 Objects and Classes 


VIDEO EXAMPLE 8.1 Paying Off a Loan 


When you take out a loan, the bank tells you how much you need 

f sur to pay and for how long. Where do these numbers come from? 
This Video Example uses a Loan object to demonstrate how a loan 
is paid off. 





.8 Problem Solving: Tracin 


You have seen how the technique of hand-tracing is useful for understanding how a 
program works. When your program contains objects, it is useful to adapt the tech- 
nique so that you gain a better understanding about object data and encapsulation. 


Use an index card or a sticky note for each object. On the front, write the methods 
Write the methods 


Gains HOGA that the object can execute. On the back, make a table for the values of the instance 
card, and the variables. 
instance variables 


so ePe nee Here is a card for a CashRegister object: 





CashRegister reg] itemCount totalPrice 


clear 
addltem(price) 
getTotal 
getCount 




















front back 


In a small way, this gives you a feel for encapsulation. An object is manipulated 
through its public interface (on the front of the card), and the instance variables are 


hidden in the back. 


When an object is constructed, fill in the initial values of the instance variables: 





itemCount totalPrice 














Whenever a mutator method is executed, cross out the old values and write the new 
Update the values of : 
the instance ones below. Here is what happens after a call to the addItem method: 


variables whena 
mutator method 


is called. itemCount totalPrice 

















@ Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


ONLINE EXAMPLE 


@ An enhanced 
CashRegister class 
that computes the 
sales tax. 





8.8 Problem Solving: Tracing Objects 387 


If you have more than one object in your program, you will have multiple cards, one 
for each object: 





itemCount totalPrice itemCount totalPrice 














These diagrams are also useful when you design a class. Suppose you are asked to 
enhance the CashRegister class to compute the sales tax. Add a method getSalesTax to 
the front of the card. Now turn the card over, look over the instance variables, and 
ask yourself whether the object has sufficient information to compute the answer. 
Remember that each object is an autonomous unit. Any data value that can be used in 
a computation must be 


e Aninstance variable. 
e A method argument. 


e A static variable (uncommon; see Section 8.11). 


To compute the sales tax, we need to know the tax rate and the total of the taxable 
items. (Food items are usually not subject to sales tax.) We don’t have that informa- 
tion available. Let us introduce additional instance variables for the tax rate and the 
taxable total. The tax rate can be set in the constructor (assuming it stays fixed for the 
lifetime of the object). When adding an item, we need to be told whether the item is 
taxable. If so, we add its price to the taxable total. 

For example, consider the following statements. 

CashRegister reg2(7.5); // 7.5 percent sales tax 


reg2.addItem(3.95, false); // Not taxable 
reg2.addItem(19.95, true); // Taxable 


When you record the effect ona card, it looks like this: 


itemCount totalPrice taxableTotal taxRate 














With this information, it becomes easy to compute the tax. It is taxableTotal x taxRate / 100. 
Tracing the object helped us understand the need for additional instance variables. 


- Consider a Car class that simulates fuel consumption in a car. We will assume a 
fixed efficiency (in miles per gallon) that is supplied in the constructor. There are 
methods for adding gas, driving a given distance, and checking the amount of gas 


388 Chapter 8 Objects and Classes 


left in the tank. Make a card for a Car object, choosing suitable instance variables 
and showing their values after the object was constructed. 


32. Trace the following method calls: 


Car myCar(25); 

myCar.addGas (20) ; 
myCar.drive(100) ; 
myCar.drive(200) ; 
myCar.addGas(5) ; 

33. Suppose you are asked to simulate the odometer of 
the car, by adding a method getMilesDriven. Add an 
instance variable to the object’s card that is suitable 
for computing this method. 


34. Trace the methods of Self Check 32, updating the 
instance variable that you added in Self Check 33. 





Practice It Now youcantry these exercises at the end of the chapter: R8.13, R8.14, R8.15. 


8.9 Problem Solving: Patterns for Object Data 


When you design a class, you first consider the needs of the programmers who use 
the class. You provide the methods that the users of your class will call when they 
manipulate objects. When you implement the class, you need to come up with the 
instance variables for the class. It is not always obvious how to do this. Fortunately, 
there is a small set of recurring patterns that you can adapt when you design your 
own classes. We introduce these patterns in the following sections. 


8.9.1 Keeping a Total 


Reon Many classes need to keep track of a quantity that can go up or downas certain meth- 


ronthenatalic ods are called. Examples: 

updated in methods os ‘ 

areTU TARO Cte e A bank account has a balance that is increased by a deposit, decreased by a 
decrease the total withdrawal. 

amount. 


e Acash register has a total that is increased when an item is added to the sale, 
cleared after the end of the sale. 


e Acar has gas in the tank, which is increased when fuel is added and decreased 
when the car drives. 

In all of these cases, the implementation strategy is similar. Keep an instance variable 

that represents the current total. For example, for the cash register: 


private double totalPrice; 


Locate the methods that affect the total. There is usually a method to increase it by a 
given amount. 


public void addItem(double price) 
{ 


} 


totalPrice = totalPrice + price; 


A counter that 
counts events is 
incremented in 
methods that 
correspond to 
the events. 


8.9 Problem Solving: Patterns for Object Data 389 


Depending on the nature of the class, there may be a method that reduces or clears the 
total. In the case of the cash register, there is a clear method: 


public void clear() 


{ 


} 
There is usually a method that yields the current total. It is easy to implement: 


total = 0; 


public double getTotal() 
{ 


} 


All classes that manage a total follow the same basic pattern. Find the methods that 
affect the total and provide the appropriate code for increasing or decreasing it. Find 
the methods that report or use the total, and have those methods read the current total. 


return totalPrice; 


8.9.2 Counting Events 


You often need to count how often certain events occur in the life of an object. For 
example: 


e Inacash register, you want to know how many items have been added ina sale. 
e A bank account charges a fee for each transaction; you need to count them. 


Keep a counter, such as 
private int itemCount; 


Increment the counter in those methods that correspond to the events that you want 
to count. 


public void addItem(double price) 
{ 


totalPrice = totalPrice + price; 
jtemCount++; 


} 


You may need to clear the counter, for example at the end of a sale or a statement 
period. 


public void clear() 


{ 
total = 0; 
itemCount = 0; 
} 
There may or may not bea method that reports the count to the class user. The count 
may only be used to compute a fee or an average. Find out which methods in your 
class make use of the count, and read the current value in those methods. 


8.9.3 Collecting Values 


Some objects collect numbers, strings, or other objects. For example, each multiple- 
choice question has a number of choices. A cash register may need to store all prices 
of the current sale. 


390 Chapter 8 Objects and Classes 


An object can collect 
other objects in an 
array or array list. 


An object property 
can be accessed 
with a getter method 
and changed with 

a setter method. 


Use an array list or an array to store the values. 
(An array list is usually simpler because you won’t 
need to track the number of values.) For example, 


public class Question 


{ 


private ArrayList<String> choices; 


} 


In the constructor, initialize the instance variable to 
an empty collection: 





public Question() 
{ A shopping cart object needs to 
choices = new ArrayList<String>( ; manage a collection of items. 


} 


You need to supply some mechanism for adding values. It is common to provide a 
method for appending a value to the collection: 


public void add(String question) 
{ 


} 


The user of a Question object can call this method multiple times to add the various 
choices. 


choices.add(question) ; 


8.9.4 Managing Properties of an Object 


A property is a value of an object that an object user can set and retrieve. For example, 
a Student object may have a name and an ID. 

Provide an instance variable to store the property’s value and methods to get and 
set it. 


public class Student 


{ 


private String name; 


public String getName() { return name; } 
public void setName(String newName) { name = newName; } 
} 


It is common to add error checking to the setter method. For example, we may want 
to reject a blank name: 


public void setName(String newName) 
{ 
} 


Some properties should not change after they have been set in the constructor. For 
example, a student’s ID may be fixed (unlike the student’s name, which may change). 
In that case, don’t supply a setter method. 


if (newName.length() > 0) { name = newName; } 


public class Student 


{ 


If your object can 
have one of several 
states that affect the 
behavior, supply an 
instance variable 
for the current state. 


8.9 Problem Solving: Patterns for Object Data 391 


private int id; 


public Student(int anId) { id = anId; } 
public String getIdQ) { return id; } 
// No setId method 


8.9.5 Modeling Objects with Distinct States 


Some objects have behavior that varies depending on what has happened in the past. 
For example, a Fish object may look for food when it is hungry and ignore food after 
it has eaten. Such an object would need to remember whether it has recently eaten. 

Supply an instance variable that models the state, together with some constants for 
the state values: 


public class Fish 


{ 


private int hungry; 


public static final int NOT_HUNGRY = 0; 
public static final int SOMEWHAT_HUNGRY = 1; 
public static final int VERY_HUNGRY = 2; 


} 


(Alternatively, you can use an enumeration—see Special Topic 3.4.) 
Determine which methods change the state. In this example, a fish that has just 
eaten food, won’t be hungry. But as the fish moves, it will get hungrier. 


public void eat() 


{ 
hungry = NOT_HUNGRY; 


} 


public void move() 


{ 


if (hungry < VERY_HUNGRY) { hungry++; } 
} 


Ifa fishis ina hungry state, 
its behavior changes. 





392 Chapter 8 Objects and Classes 


To model a moving 
object, you need to 
store and update 
its position. 


Finally, determine where the state affects behavior. A fish that is very hungry will 
want to look for food first. 


public void move() 


{ 
if (hungry == VERY_HUNGRY) 


Look for food. 


8.9.6 Describing the Position of an Object 


Some objects move around during their lifetime, and they remember their current 
position. For example, 


e A train drives along a track and keeps track of the distance from the terminus. 


e A simulated bug living ona grid crawls from one grid location to the next, or 
makes 90 degree turns to the left or right. 


e Acannonball is shot into the air, then descends as it is pulled by the gravitational 
force. 


Such objects need to store their position. Depending on the nature of their move- 
ment, they may also need to store their orientation or velocity. 

If the object moves along a line, you can represent the position as a distance from 
a fixed point. 


private double distanceFromTerminus; 
If the object moves ina grid, remember its current location and direction in the grid: 


private int row; 

private int column; 

private int direction; // 0 = North, 1 = East, 2 = South, 3 = West 
When you model a physical object such as a cannonball, you need to track both the 
position and the velocity, possibly in two or three dimensions. Here we model a can- 
nonball that is shot upward into the air: 


private double zPosition; 
private double zVelocity; 


There will be methods that update the position. In the simplest case, you may be told 
by how much the object moves: 


public void move(double distanceMoved) 


{ 
} 


distanceFromlerminus = distanceFromTerminus + distanceMoved; 








@: 





A bug ina grid needs to store its row, 
column, and direction. 
































8.9 Problem Solving: Patterns for Object Data 393 


If the movement happens in a grid, you need to update the row or column, depending 
on the current orientation. 


public void moveOneUnit() 


{ 
if (direction == NORTH) { row--; } 
else if (direction == EAST) { column++; } 


} 


Exercise P8.25 shows you how to update the position of a physical object with known 
velocity. 

Whenever you have a moving object, keep in mind that your program will simu- 
late the actual movement in some way. Find out the rules of that simulation, such as 
movement along a line or in a grid with integer coordinates. Those rules determine 
how to represent the current position. Then locate the methods that move the object, 
and update the positions according to the rules of the simulation. 


35. Suppose we want to count the number of transactions in a bank account ina 
statement period, and we add a counter to the BankAccount class: 


public class BankAccount 


{ 





private int transactionCount; 


} 
In which methods does this counter need to be updated? 

36. Inthe example in Section 8.9.3, why is the add method required? That is, why 
can’t the user of a Question object just call the add method of the ArrayList<String> 
class? 


37. Suppose we want to enhance the CashRegister class in Section 8.6 to track the 
prices of all purchased items for printing a receipt. Which instance variable 
should you provide? Which methods should you modify? 

38. Consider an Employee class with properties for tax ID number and salary. Which 
of these properties should have only a getter method, and which should have 
getter and setter methods? 

39. Look at the direction instance variable in the bug example in Section 8.9.6. This 
is an example of which pattern? 


Practice It Now youcantry these exercises at the end of the chapter: P8.6, P8.7, P8.12. 


VIDEO EXAMPLE 8.2 Modeling a Robot Escaping from a Maze a 
fi, 


Toe In this Video Example, we will program classes that model a robot 
PLUS 


escaping froma maze. 





© Available online in WileyPLUS and at ww.wiley.com/college/horstmann. 


394 Chapter 8 Objects and Classes 


In the 2000 presiden- 
tial elections in the 
United States, votes were tallied by a 
variety of machines. Some machines 
processed cardboard ballots into 
which voters punched holes to indicate 
their choices (see below). When voters 
were not careful, remains of paper— 
the now infamous “chads’—were par- 
tially stuck in the punch cards, caus- 
ing votes to be miscounted. A manual 
recount was necessary, but it was not 
carried out everywhere due to time 
constraints and procedural wrangling. 
The election was very close, and there 
remain doubts in the minds of many 
people whether the election outcome 
would have been different if the voting 
machines had accurately counted the 
intent of the voters. 








Punch Card Ballot 


Subsequently, voting machine man- 
ufacturers have argued that electronic 
voting machines would avoid the prob- 
lems caused by punch cards or opti- 
cally scanned forms. In an electronic 
voting machine, voters indicate their 
preferences by pressing buttons or 
touching icons on a computer screen. 
Typically, each voter is presented with 
a summary screen for review before 
casting the ballot. The process is very 
similar to using a bank's automated 
teller machine. 

It seems plausible that these 
machines make it more likely that a 
vote is counted in the same way that 
the voter intends. However, there 
has been significant controversy 
surrounding some types of electronic 
voting machines. If a machine simply 


records the votes and prints out the 
totals after the election has been com- 
pleted, then how do you know that the 
machine worked correctly? Inside the 
machine is a computer that executes a 
program, and, as you may know from 
your own experience, programs can 
have bugs. 

In fact, some electronic voting 
machines do have bugs. There have 
been isolated cases where machines 
reported tallies that were impossible. 
When a machine reports far more or far 
fewer votes than voters, then it is clear 
that it malfunctioned. Unfortunately, it 
is then impossible to find out the 
actual votes. Over time, one would 
expect these bugs to be fixed in the 


software. More insidiously, if the 
results are plausible, nobody may ever 
investigate. 


Many computer scientists have spo- 
ken out on this issue and confirmed 
that it is impossible, with today’s tech- 
nology, to tell that software is error 
free and has not been tampered with. 
Many of them recommend that elec- 
tronic voting machines should employ 
a voter verifiable audit trail. (A good 
source of information is http://veri- 
fiedvoting.org.) Typically, a voter- 
verifiable machine prints out a ballot. 
Each voter has a chance to review the 
printout, and then deposits it in an 
old-fashioned ballot box. If there is 





Touch Screen Voting Machine 


Random Fact 8.1 Electronic Voting Machines 


a problem with the electronic equip- 
ment, the printouts can be scanned or 
counted by hand. 

As this book is written, this con- 
cept is strongly resisted both by 
manufacturers of electronic voting 
machines and by their customers, 
the cities and counties that run elec- 
tions. Manufacturers are reluctant 
to increase the cost of the machines 
because they may not be able to pass 
the cost increase on to their custom- 
ers, who tend to have tight budgets. 
Election officials fear problems with 
malfunctioning printers, and some of 
them have publicly stated that they 
actually prefer equipment that elimi- 
nates bothersome recounts. 

What do you think? You probably 
use an automated bank teller machine 
to get cash from your bank account. 
Do you review the paper record that 
the machine issues? Do you check your 
bank statement? Even if you don’t, do 
you put your faith in other people who 
double-check their balances, so that 
the bank won’t get away with wide- 
spread cheating? 

Is the integrity of banking equip- 
ment more important or less impor- 
tant than that of voting machines? 
Won’t every voting process have some 
room for error and fraud anyway? Is 
the added cost for equipment, paper, 
and staff time reasonable to combat 
a potentially slight 
risk of malfunction 
and fraud? Computer 


scientists cannot 
answer these ques- 
tions—an_ informed 


society must make 
these tradeoffs. But, 
like all professionals, 
they have an obliga- 
tion to speak out 
and give accurate 
testimony about the 
capabilities and limi- 
tations of computing 
equipment. 


An object reference 
specifies the location 
of an object. 


Multiple object 
variables can contain 
references to the 
same object. 





Primitive type 

variables store 
values. Object 
variables store 
references. 


8.10 Object References 395 





In Java, a variable whose type is a class does not actually hold an object. It merely 
holds the memory location of an object. The object itself is stored elsewhere—see 
Figure 8. 

We use the technical term object reference to denote the memory location of an 
object. When a variable contains the memory location of an object, we say that it 
refers to an object. For example, after the statement 


CashRegister regl = new CashRegister(); 


the variable regi refers to the CashRegister object that the new operator constructed. 
Technically speaking, the new operator returned a reference to the new object, and that 
reference is stored in the regi variable. 


Figure 8 
An Object Variable Containing 
an Object Reference 








You can have two (or more) object variables that store references to the same object, 
for example by assigning one to the other. 
CashRegister reg2 = regl; 


Now you can access the same CashRegister object both as regi and as reg2, as shown in 
Figure 9. 


Figure 9 
Two Object Variables 
Referring to the Same Object 





In this regard, object variables differ from variables for primitive types (numbers, 
characters, and boolean values). When you declare 


int numl = 0; 
then the num1 variable holds the number 0, not a reference to the number (see 
Figure 10). 


Figure 10 A Variable of Type int Stores a Number 


396 Chapter 8 Objects and Classes 





rm\ 
ANIMATION 
Object References 


ik 


When copying an 
object reference, you 
have two references 
to the same object. 


You can see the difference between primitive type variables and object variables when 
you make a copy of a variable. When you copy a number, the original and the copy of 
the number are independent values. But when you copy an object reference, both the 
original and the copy are references to the same object. 

Consider the following code, which copies a 
number and then changes the copy (see Figure 11): 


int und = 0; @ ¥ 


int num2 = num1; 


oe e 


Now the variable num1 contains the value 0, and 
num2 contains 1. 


Now consider the seemingly analogous code num2= 0 > 


with CashRegister objects (see Figure 12): 


CashRegister regl = new CashRegisterO; @ 3) ‘num= 0 
CashRegister reg2 = regl; @Q 


reg2.addItem(2.95); & 


Because regi and reg2 refer to the same cash regis- 
ter after step @, both variables now refer to a cash 
register with item count 1 and total price 2.95. Figure 11 Copying Numbers 





Figure 12 Copying Object References 


The null reference 
refers to no object. 


Ina method, the 
this reference 
refers to the 
implicit parameter. 


8.10 Object References 397 


There is a reason for the difference between numbers and objects. In the computer, 
each number requires a small amount of memory. But objects can be very large. It is 
far more efficient to manipulate only the memory location. 


8.10.2 The null Reference 


An object reference can have the special value nu11 if it refers to no object at all. It is 
common to use the nu11 value to indicate that a value has never been set. For example, 


String middleInitial = null; // No middle initial 


You use the == operator (and not equals) to test whether an object reference is a nu11 
reference: 


if (middleInitial == null) 


{ 
System.out.printIn(firstName + " " + lastName) ; 
} 
else 
{ 
System.out.printIn(firstName + " " + middleInitial + ". " + lastName) ; 
} 


Note that the nu11 reference is not the same as the empty string "". The empty string 
is a valid string of length 0, whereas a nu11 indicates that a String variable refers to no 
string at all. 

It is an error to invoke a method ona nu11 reference. For example, 


CashRegister reg = null; 
System.out.printIn(reg.getTotal()); // Error—cannot invoke a method on nu11 


This code causes a “null pointer exception” at run time. 

The null reference is the default value for an object reference that is contained 
inside another object or an array of objects. In order to avoid run-time errors, you 
need to replace these nu11 references with references to actual objects. 

For example, suppose you construct an array of bank accounts: 


BankAccount[] accounts = new BankAccount[NACCOUNTS] ; 


You now have an array filled with nu11 references. If you want an array of actual bank 
accounts, you need to construct them: 
for (int i = 0; i < accounts.length; i++) 


{ 


accounts[i] = new BankAccount(); 


} 


8.10.3 The this Reference 


Every instance method receives the implicit parameter in a variable called this. 
For example, consider the method call 


regl.addItem(2.95); 


When the method is called, the parameter variable this refers to the same object as 
regl (see Figure 13). 


398 Chapter 8 Objects and Classes 











Figure 13. The Implicit Parameter of a Method Call 


You don’t usually need to use the this reference, but you can. For example, you 
can write the addItem method like this: 


void addItem(double price) 
{ 
this.itemCount++; 
this.totalPrice = this.totalPrice + price; 


} 


Some programmers like to use the this reference to make it clear that itemCount and 
totalPrice are instance variables and not local variables. You may want to try it out 
and see if you like that style. 

There is another situation where the this reference can make your programs eas- 
ier to read. Consider a constructor or instance method that calls another instance 
method on the same object. For example, the CashRegister constructor can call the 
clear method instead of duplicating its code: 


public CashRegister() 
{ 


} 


This call is easier to understand when you use the this reference: 


clearQ); 


public CashRegister() 
{ 


} 


It is now more obvious that the method is invoked on the object that is being 
constructed. 

Finally, some people like to use the this reference in constructors. Here is a typical 
example: 


this.clearQ; 


public class Student 
{ 


private int id; 
private String name; 


public Student(int id, String name) 
{ 

this.id = id; 

this.name = name; 


} 





Practice It 


NY el-Kel f-1 ke) 0) (ents is} 








8.10 Object References 399 


The expression id refers to the parameter variable, and this.id to the instance variable. 
In general, if both a local variable and an instance variable have the same name, you can 
access the local variable by its name, and the instance variable with the this reference. 

You can implement the constructor without using the this reference. Simply 
choose other names for the parameter variables: 


public Student(int anId, String aName) 


{ 
id = anld; 
name = aName; 


40. Suppose we have a variable 
String greeting = "Hello"; 
What is the effect of this statement? 
String greeting2 = greeting; 
41. After calling String greeting3 = greeting2.toUpperCase(), what are the contents of 
greeting and greeting2? 
42. What is the value of s.length@ if s is 
a. the empty string ""? 
b. null? 
43. Whatis the type of this in the call greeting. substring(1, 4)? 


44. Supply a method addItems(int quantity, double price) in the CashRegister class to 
add multiple instances of the same item. Your implementation should repeatedly 
call the addItem method. Use the this reference. 


Now you can try these exercises at the end of the chapter: R8.19, R8.20. 


Calling One Constructor from Another 


Consider the BankAccount class outlined in Section 8.6. It has two constructors: a construc- 
tor without arguments to initialize the balance with zero, and another constructor to supply 
an initial balance. Rather than explicitly setting the balance to zero, one constructor can call 
another constructor of the same class instead. There is a shorthand notation to achieve this 
result: 


public class BankAccount 


{ 
public BankAccount (double initialBalance) 
{ 
balance = initialBalance; 
} 
public BankAccount () 
{ 
this(0); 
} 
} 


The command this(0); means “Call another constructor of this class and supply the value 0”. 
Such a call to another constructor can occur only as the first line in a constructor. 


400 Chapter 8 Objects and Classes 


AT 


A static variable 
belongs to the class, 
not to any object of 
the class. 


A static method is 
not invoked on 
an object. 


This syntax is a minor convenience. We will not use it in this book. Actually, the use of 
the reserved word this is a little confusing. Normally, this denotes a reference to the implicit 
parameter, but if this is followed by parentheses, it denotes a call to another constructor of this 
class. 


ic Variables and Meth 


Sometimes, a value properly belongs to a class, not 
to any object of the class. You use a static variable 
for this purpose. Here is a typical example: We want 
to assign bank account numbers sequentially. That 
is, we want the bank account constructor to con- 
struct the first account with number 1001, the next 
with number 1002, and so on. To solve this prob- 
lem, we need to have a single value of lastAssigned- 7), peserved word static isa 
Number that is a property of the class, not any object — pgidover from the C++ language. 
of the class. Such a variable is called a static variable, Its use in Java has no relationship 
because you declare it using the static reserved to the normal use of the term. 
word. 





public class BankAccount 


{ 
private double balance; 
private int accountNumber; 
private static int lastAssignedNumber = 1000; 


public BankAccount () 

{ 
lastAssignedNumber++ ; 
accountNumber = lastAssignedNumber; 


} 
} 


Every BankAccount object has its own balance and accountNumber instance variables, but 
there is only a single copy of the lastAssignedNumber variable (see Figure 14). That vari- 
able is stored in a separate location, outside any BankAccount objects. 

Like instance variables, static variables should always be declared as private to 
ensure that methods of other classes do not change their values. However, static con- 
stants may be either private or public. For example, the BankAccount class can define a 
public constant value, such as 


public class BankAccount 


{ 
public static final double OVERDRAFT_FEE = 29.95; 


} 


Methods from any class can refer to such a constant as BankAccount . OVERDRAFT_FEE. 
Sometimes a class defines methods that are not invoked on an object. Such a 
method is called a static method. A typical example of a static method is the sqrt 
method in the Math class. Because numbers aren’t objects, you can’t invoke methods 
on them. For example, if x is a number, then the call x.sqrt( is not legal in Java. 


8.11 Static Variables and Methods 401] 





Figure 14 A Static Variable and Instance Variables 


Therefore, the Math class provides a static method that is invoked as Math.sqrt(x). No 
object of the Math class is constructed. The Math qualifier simply tells the compiler 
where to find the sqrt method. 

You can define your own static methods for use in other classes. Here is an example: 


public class Financial 
{ 
/** 
Computes a percentage of an amount. 
@param percentage the percentage to apply 
@param amount the amount to which the percentage is applied 
@return the requested percentage of the amount 
*/ 
public static double percentOf(double percentage, double amount) 
{ 


} 
} 
When calling this method, supply the name of the class containing it: 


double tax = Financial.percentOf(taxRate, total); 


Aprogram with static You had to use static methods in Chapter 5 before you knew how to implement your 
ea and own objects. However, in object-oriented programming, static methods are not very 
varlaples. 

common. 


return (percentage / 100) * amount; 


402 Chapter 8 Objects and Classes 


Nevertheless, the main method is always static. When the program starts, there 
aren’t any objects. Therefore, the first method of a program must be a static method. 


45. 
46. 
47. 





Name two static variables of the System class. 


Name a static constant of the Math class. 


public static double average(double[] values) 


The following method computes the average of an array of numbers: 


Why should it not be defined as an instance method? 


48. 


Harry tells you that he has found a great way to avoid those pesky objects: Put 


all code into a single class and declare all methods and variables static. Then main 
can call the other static methods, and all of them can access the static variables. 
Will Harry’s plan work? Is it a good idea? 


Practice It 


Most companies that 
produce software 
regard the source code as a trade 
secret. After all, if customers or com- 
petitors had access to the source code, 
they could study it and create similar 
programs without paying the original 
vendor. For the same reason, custom- 
ers dislike secret source code. If acom- 
pany goes out of business or decides 
to discontinue support for a computer 
program, its users are left stranded. 
They are unable to fix bugs or adapt 
the program to a new operating sys- 
tem. Nowadays, some software pack- 
ages are distributed with “open source” 
or “free software” licenses. Here, the 
term “free” doesn’t refer to price, but 
to the freedom to inspect and modify 
the source code. Richard Stallman, a 
famous computer scientist and win- 
ner of a MacArthur “genius” grant, pio- 
neered the concept of free software. 
He is the inventor of the Emacs text 
editor and the originator of the GNU 
project that aims to create an entirely 
free version of a UNIX compatible oper- 
ating system. All programs of the GNU 
project are licensed under the General 
Public License or GPL. The GPL allows 
you to make as many copies as you 
wish, make any modifications to the 
source, and redistribute the original 
and modified programs, charging noth- 
ing at all or whatever the market will 
bear. In return, you must agree that 





your modifications also fall under the 
GPL. You must give out the source code 
to any changes that you distribute, 
and anyone else can distribute them 
under the same conditions. The GPL, 
and similar open source licenses, form 
a social contract. Users of the software 
enjoy the freedom to use and modify 
the software, and in return they are 
obligated to share any improvements 
that they make. Many programs, such 
as the Linux operating system and 
the GNU C++ compiler, are distributed 
under the GPL. 

Some commercial software vendors 
have attacked the GPL as “viral” and 
“undermining the commercial software 
sector’. Other companies have a more 
nuanced strategy, producing propri- 
etary software while also contributing 
to open source projects. 

Frankly, open source is not a pana- 
cea and there is plenty of room for 
the commercial software sector. Open 
source software often lacks the polish 
of commercial software because many 
of the programmers are volunteers 
who are interested in solving their 
own problems, not in making a prod- 
uct that is easy to use by others. Some 
product categories are not available at 
all as open source software because 
the development work is unattractive 
when there is little promise of com- 
mercial gain. Open source software has 
been most successful in areas that are 


Now you can try these exercises at the end of the chapter: P8.14, P8.15. 


Random Fact 8.2 Open Source and Free Software 


of interest to programmers, such as 
the Linux operating system, Web serv- 
ers, and programming tools. 

On the positive side, the open soft- 
ware community can be very competi- 
tive and creative. It is quite common 
to see several competing projects that 
take ideas from each other, all rap- 
idly becoming more capable. Having 
many programmers involved, all read- 
ing the source code, often means that 
bugs tend to get squashed quickly. 
Eric Raymond describes open source 
development in his famous article “The 
Cathedral and the Bazaar” (http:// 
catb.org/~esr/writings/cathedral- 
bazaar/cathedral-bazaar/index.htm1). 
He writes “Given enough eyeballs, all 
bugs are shallow”. 





Richard Stallman, a pioneer of the 
free source movement. 


Chapter Summary 403 


Understand the concepts of classes, objects, and encapsulation. 


e Aclass describes a set of objects with the same behavior. 


e Every class has a public interface: a collection of methods 
through which the objects of the class can be manipulated. 

¢ Encapsulation is the act of providing a public interface and 
hiding the implementation details. 





¢ Encapsulation enables changes in the implementation 
without affecting users of a class. 


Understand instance variables and method implementations of a simple class. 


e An object’s instance variables store the data required for 
executing its methods. 


¢ Each object of a class has its own set of instance variables. 





e Aninstance method can access the instance variables of 
the object on which it acts. 


e A private instance variable can only be accessed by the methods of its own class. 
Write method headers that describe the public interface of a class. 


¢ You can use method headers and method comments to specify the public interface 
of a class. 


e A mutator method changes the object on which it operates. 


e Anaccessor method does not change the object on which it operates. 





Choose an appropriate data representation for a class. 


¢ For each accessor method, an object must either store or compute the result. 


¢ Commonly, there is more than one way of representing the data of an object, and 
you must make a choice. 


¢ Be sure that your data representation supports method calls in any order. 





Provide the implementation of instance methods for a class. 


¢ The object on which a method is applied is the implicit parameter. 


e Explicit parameters of a method are listed in the method 
declaration. 





Design and implement constructors. 


e A constructor initializes the instance variables of an object. 
e A constructor is invoked when an object is created with the new operator. 


The name of a constructor is the same as the class name. 





A class can have multiple constructors. 


The compiler picks the constructor that matches the construction arguments. 


404 Chapter 8 Objects and Classes 


¢ By default, numbers are initialized as 0, Booleans as false, and object references 
as null. 


¢ Ifyou do not provide a constructor, a constructor with no arguments is generated. 


Write tests that verify that a class works correctly. 


e A unit test verifies that a class works correctly in isolation, outside a complete 
program. 


¢ To test a class, use an environment for interactive testing, or write a tester class to 
execute test instructions. 





¢ Determining the expected result in advance is an important part of testing. 


Use the technique of object tracing for visualizing object behavior. 


e Write the methods on the front of a card, and the instance variables on the back. 


¢ Update the values of the instance variables when a mutator method is called. 


Use patterns to design the data representation of a class. 


e Aninstance variable for the total is updated in methods that increase or decrease 
the total amount. 


¢ A counter that counts events is incremented in methods that correspond to the 
events. 


e An object can collect other objects in an array or array list. 


e An object property can be accessed with a getter method and changed with a 
setter method. 





¢ If your object can have one of several states that affect the 
behavior, supply an instance variable for the current state. 


¢ To model a moving object, you need to store and update its 
position. 


Describe the behavior of object references. 


e An object reference specifies the location of an object. 

¢ Multiple object variables can contain references to the same object. 

e Primitive type variables store values. Object variables store references. 

¢ When copying an object reference, you have two references to the same object. 
¢ The null reference refers to no object. 





¢ Ina method, the this reference refers to the implicit parameter. 


Understand the behavior of static variables and methods. 


e A static variable belongs to the class, not to any object of the class. 
e A static method is not invoked on an object. 





Review Exercises 405 


= R8.1 
= R8.2 


= R8.3 


= R8.4 


oe R8.5 


une R8.6 


= R8.7 
= R8.8 
= R8.9 
= R8.10 


= R8.11 


= R8.12 


= R8.13 


oa R8.14 


aoe R8.15 


What is encapsulation? Why is it useful? 


What values are returned by the calls reg1. getCount(), regl.getTotal(), reg2.getCount(), 
and reg2.getTotal() after these statements? 

CashRegister regl = new CashRegister(); 

regl.addItem(3.25); 

regl.addItem(1.95); 

CashRegister reg2 = new CashRegister(); 

reg2.addItem(3.25); 

reg2.clear(); 


Consider the Menu class in How To 8.1 on page 382. What is displayed when the fol- 
lowing calls are executed? 

Menu simpleMenu = new Menu(); 

simpleMenu.addOption("0k") ; 


simpleMenu.addOption("Cancel") ; 
int response = simpleMenu.getInputQ) ; 


What is the public interface of a class? How does it differ from the implementation of 
a class? 


Consider the data representation of a cash register that keeps track of sales tax in 
Section 8.8. Instead of tracking the taxable total, track the total sales tax. Redo the 
walkthrough with this change. 


Suppose the CashRegister needs to support a method void undo() that undoes the 
addition of the preceding item. This enables a cashier to quickly undo a mistake. 
What instance variables should you add to the CashRegister class to support this 
modification? 


What is an instance method, and how does it differ from a static method? 
What is a mutator method? What is an accessor method? 
What is an implicit parameter? How does it differ from an explicit parameter? 


How many implicit parameters can an instance method have? How many implicit 
parameters can a static method have? How many explicit parameters can an instance 
method have? 


What is a constructor? 


How many constructors can a class have? Can you have a class with no construc- 
tors? Ifa class has more than one constructor, which of them gets called? 


Using the object tracing technique described in Section 8.8, trace the program at the 
end of Section 8.7. 


Using the object tracing technique described in Section 8.8, trace the program in 
Worked Example 8.1. 


Design a modification of the BankAccount class in Worked Example 8.1 in which the 
first five transactions per month are free and a $1 fee is charged for every additional 
transaction. Provide a method that deducts the fee at the end of a month. What addi- 
tional instance variables do you need? Using the object tracing technique described 


406 Chapter 8 Objects and Classes 


une R8.16 


aoe R8.17 


uae R8.18 


at R8.19 
ae R8.20 


in Section 8.8, trace a scenario that shows how the fees are computed over two 
months. 


Instance variables are “hidden” by declaring them as private, but they aren’t hidden 
very well at all. Anyone can read the class declaration. Explain to what extent the 
private reserved word hides the private implementation of a class. 


You can read the itemCount instance variable of the CashRegister class with the getCount 
accessor method. Should there be a setCount mutator method to change it? Explain 
why or why not. 


Ina static method, it is easy to differentiate between calls to instance methods and 
calls to static methods. How do you tell them apart? Why is it not as easy for meth- 
ods that are called from an instance method? 


What is the this reference? Why would you use it? 


What is the difference between the number zero, the nu11 reference, the value false, 
and the empty string? 


= P8.1 


= P8.2 


une P8.3 


uu P8.4 


=» P8.5 


uu P8.6 


We want to add a button to the tally counter in Section 8.2 that allows an operator to 
undo an accidental button click. Provide a method 


public void undo() 


that simulates such a button. As an added precaution, make sure that the operator 
cannot click the undo button more often than the count button. 


Simulate a tally counter that can be used to admit a limited number of people. First, 
the limit is set with a call 


public void setLimitCint maximum) 


e count button was clicked more often than the limit, simulate an alarm 
If th t butt licked ften than the limit lat larm by 
printing out a message “Limit exceeded”. 


Reimplement the Menu class so that it stores all menu items in one long string. 
Hint: Keep a separate counter for the number of options. When a new option is 
added, append the option count, the option, and a newline character. 


Implement a class Address. An address has a house number, a street, an optional 
apartment number, a city, a state, and a postal code. Supply two constructors: one 
with an apartment number and one without. Supply a print method that prints the 
address with the street on one line and the city, state, and zip code on the next line. 
Supply a method public boolean comesBefore(Address other) that tests whether this 
address comes before another when the addresses are compared by postal code. 


Implement a class SodaCan with methods getSurfaceArea() and get- 
Volume(). In the constructor, supply the height and radius of the can. S 


Implement a class Car with the following properties. A car has a certain 
fuel efficiency (measured in miles/gallon) and a certain amount of fuel 
in the gas tank. The efficiency is specified in the constructor, and the 
initial fuel level is 0. Supply a method drive that simulates driving the 


ua P8,7 


ua P8.8 


une P8.9 


ua P8.10 


ue P8.11 


Programming Exercises 407 


car fora certain distance, reducing the fuel level in the gas tank, and methods getGas- 
Level, to return the current fuel level, and addGas, to tank up. Sample usage: 

Car myHybrid = new Car(50); // 50 miles per gallon 

myHybrid.addGas(20); // Tank 20 gallons 


myHybrid.drive(100); // Drive 100 miles 
System.out.printIn(myHybrid.getGasLevel()); // Print fuel remaining 


Implement a class Student. For the purpose of this exercise, a student has a name 
and a total quiz score. Supply an appropriate constructor and methods getName(), 
addQuiz(int score), getTotalScore(), and getAverageScore(). To compute the latter, you 
also need to store the number of quizzes that the student took. 


Modify the Student class of Exercise P8.7 to compute grade point averages. Methods 
are needed to add a grade and get the current GPA. Specify grades as elements of a 
class Grade. Supply a constructor that constructs a grade from a string, such as "B+". 
You will also need a method that translates grades into their numeric values (for 
example, "B+" becomes 3.3). 


Declare a class ComboLock that works like the combination lock 

in a gym locker, as shown here. The lock is constructed with a 
combination —three numbers between 0 and 39. The reset method 
resets the dial so that it points to 0. The turnLeft and turnRight 
methods turn the dial by a given number of ticks to the left or 
right. The open method attempts to open the lock. The lock opens 
if the user first turned it right to the first number in the combina- 
tion, then left to the second, and then right to the third. 





public class ComboLock 


{ 
public ComboLock(int secretl, int secret2, int secret3) {... } 
public void reset() {... } 
public void turnLeftCint ticks) { ... } 
public void turnRight(int ticks) {... } 
public boolean open() {... } 
} 


Implement a VotingMachine class that can be used for a simple election. Have methods 
to clear the machine state, to vote for a Democrat, to vote for a Republican, and to 
get the tallies for both parties. 


Provide a class for authoring a simple letter. In the constructor, supply the names of 
the sender and the recipient: 
public Letter(String from, String to) 
Supply a method 
public void addLine(String line) 
to add a line of text to the body of the letter. Supply a method 
public String getText() 
that returns the entire text of the letter. The text has the form: 


Dear recipient name: 
blank line 

first line of the body 
second line of the body 


408 Chapter 8 Objects and Classes 


ua P8.12 


ua P8.13 


last line of the body 
blank line 
Sincerely, 
blank line 


sender name 
Also supply amain method that prints this letter. 
Dear John: 


I am sorry we must part. 
I wish you all the best. 


Sincerely, 


Mary 
Construct an object of the Letter class and call addline twice. 
Write a class Bug that models a bug moving along a horizontal line. The bug moves 
either to the right or left. Initially, the bug moves to the right, but it can turn to 


change its direction. In each move, its position changes by one unit in the current 
direction. Provide a constructor 


public Bug(int initialPosition) 
and methods 

© public void turn() 

©@ public void move() 

©@ public int getPosition() 
Sample usage: 


Bug bugsy = new Bug(10); 

bugsy.move(); // Now the position is 11 

bugsy.turn(); 

bugsy.move(); // Now the position is 10 
Your main method should construct a bug, make it move and turn a few times, and 
print the actual and expected positions. 


Implement a class Moth that models a moth flying in a straight line. The moth has a 
position, the distance from a fixed origin. When the moth moves toward a point of 
light, its new position is halfway between its old position and the position of the 
light source. Supply a constructor 

public Moth(double initialPosition) 
and methods 

©@ public void moveToLight(double lightPosition) 

© public void getPosition() 


Your main method should construct a moth, move it toward a couple of light sources, 
and check that the moth’s position is as expected. 


naa P8.14 Write static methods 


® public static double sphereVolume(double r) 
©@ public static double sphereSurface(double r) 
®@ public static double cylinderVolume(double r, double h) 
©@ public static double cylinderSurface(double r, double h) 


oe P8.15 


== Business P8.16 


== Business P8.17 


== Business P8.18 


== Business P8.19 


== Business P8.20 


== Business P8.21 


Programming Exercises 409 


© public static double coneVolume(double r, double h) 

® public static double coneSurface(double r, double h) 
that compute the volume and surface area of a sphere with a radius r, a cylinder with 
a circular base with radius r and height h, and a cone with a circular base with radius r 
and height h. Place them into a class Geometry. Then write a program that prompts the 
user for the values of r and h, calls the six methods, and prints the results. 


Solve Exercise P8.14 by implementing classes Sphere, Cylinder, and Cone. Which 
approach is more object-oriented? 


Reimplement the CashRegister class so that it keeps track of the price of each added 
item in an ArrayList<Double>. Remove the itemCount and totalPrice instance variables. 
Reimplement the clear, addItem, getTotal, and getCount methods. Add a method 
displayA11 that displays the prices of all items in the current sale. 


Reimplement the CashRegister class so that it keeps track of the total price as an 
integer: the total cents of the price. For example, instead of storing 17.29, store the 
integer 1729. Such an implementation is commonly used because it avoids the accu- 
mulation of roundoff errors. Do not change the public interface of the class. 


After closing time, the store manager would like to know how much business was 
transacted during the day. Modify the CashRegister class to enable this functionality. 
Supply methods getSalesTotal and getSalesCount to get the total amount of all sales 
and the number of sales. Supply a method resetSales that resets any counters and 
totals so that the next day’s sales start from zero. 


Implement a class Portfolio. This class has two objects, checking and savings, of the 
type BankAccount that was developed in Worked Example 8.1 (ch08/worked_examp1e_1/ 
BankAccount. java in your code files). Implement four methods: 


® public void deposit(double amount, String account) 
® public void withdraw(double amount, String account) 
©@ public void transfer(double amount, String account) 
©® public double getBalance(String account) 
Here the account string is "S$" or "C". For the deposit or withdrawal, it indicates which 


account is affected. For a transfer, it indicates the account from which the money is 
taken; the money is automatically transferred to the other account. 


Design and implementa class Country that stores the name of the country, its popula- 
tion, and its area. Then write a program that reads in a set of countries and prints 

e The country with the largest area. 

e The country with the largest population. 

e The country with the largest population density (people per square 

kilometer (or mile)). 

Design a class Message that models an e-mail message. A message has a recipient, a 
sender, and a message text. Support the following methods: 

e Aconstructor that takes the sender and recipient 

e A method append that appends a line of text to the message body 


e A method toString that makes the message into one long string like this: "From: 
Harry Morgan\nTo: Rudolf Reindeer\n.. ." 


Write a program that uses this class to make a message and print it. 


410 Chapter 8 Objects and Classes 


aa Business P8.22 


a= Business P8.23 


aun Business P8.24 


sen Science P8.25 


aa Science P8.26 


Design a class Mailbox that stores e-mail messages, using the Message class of Exercise 
P8.21. Implement the following methods: 


® public void addMessage(Message m) 
© public Message getMessage(int i) 


® public void removeMessage(int i) 


Design a Customer class to handle a customer loyalty marketing campaign. After 
accumulating $100 in purchases, the customer receives a $10 discount on the next 
purchase. Provide methods 


® void makePurchase(double amount) 
® boolean discountReached() 


Provide a test program and test a scenario in which a customer has earned a discount 
and then made over $90, but less than $100 in purchases. This should not result ina 
second discount. Then add another purchase that results in the second discount. 


The Downtown Marketing Association wants 
to promote downtown shopping with a loyalty 
program similar to the one in Exercise P8.23. 
Shops are identified by a number between 

1 and 20. Add a new parameter variable to the 
makePurchase method that indicates the shop. 
The discount is awarded if a customer makes 
purchases in at least three different shops, 
spending a total of $100 or more. 





Design a class Cannonball to model a cannonball that is fired into the air. A ball has 

e Anx-anday-position. 

e Anx-anday-velocity. 

Supply the following methods: 

e A constructor with an x-position (the y-position is initially 0) 

e A method move(double sec) that moves the ball to the next position (First 
compute the distance traveled in sec seconds, using the current velocities, then 
update the x- and y-positions; then update the y- velocity by taking into 
account the gravitational acceleration of -9.81 m/s’; the x-velocity is 
unchanged.) 

© Methods getx and gety that get the current location of the cannonball 

e A method shoot whose arguments are the angle a and initial velocity v (Com- 
pute the x-velocity as v cos a and the y-velocity as v sin a; then keep calling 
move with a time interval of 0.1 seconds until the y-position is 0; call getx and 
getY after every move and display the position.) 


Use this class in a program that prompts the user for the starting angle and the initial 
velocity. Then call shoot. 


The colored bands on the top-most resistor shown in the photo below indicate a 
resistance of 6.2 kQ +5 percent. The resistor tolerance of +5 percent indicates the 
acceptable variation in the resistance. A 6.2 kQ +5 percent resistor could have a 
resistance as small as 5.89 kQ or as large as 6.51 kQ. We say that 6.2 kQ is the nominal 
value of the resistance and that the actual value of the resistance can be any value 
between 5.89 kQ and 6.51 kQ. 


ua Science P8.27 


Programming Exercises 411 






Write a program that represents a »* ee 
resistor as a class. Provide a single oe 

“ 
constructor that accepts values for the a 


nominal resistance and tolerance and 
then determines the actual value ran- 
domly. The class should provide public 
methods to get the nominal resistance, 
tolerance, and the actual resistance. t , 

Write a main method for the program that demonstrates that the class works properly 
by displaying actual resistances for ten 330 Q +10 percent resistors. 


In the Resistor class from Exercise P8.26, supply a 
method that returns a description of the “color bands” 


for the resistance and tolerance. A resistor has four color 
bands: First ait J | (ie 
e The first band is the first significant digit of the Second band Multiplier 


resistance value. 
e The second band is the second significant digit of the resistance value. 
e The third band is the decimal multiplier. 
e The fourth band indicates the tolerance. 


Color Digit Multiplier Tolerance 
Black 0 x10° — 
Brown 1 x10! +1% 
Red 2 x10? +2% 
Orange 3) x10? = 
Yellow 4 x104 — 
Green 5 x10° +0.5% 
Blue 6 x10° +0.25% 
Violet 7 x10” +0.1% 
Gray 8 x108 +0.05% 
White 9 x10? _ 
Gold _ < 10m! +5% 
Silver = lor +10% 
None — -- +20% 


For example (using the values from the table as a key), a resistor with red, violet, 
green, and gold bands (left to right) will have 2 as the first digit, 7 as the second digit, 
a multiplier of 10°, and a tolerance of +5 percent, for a resistance of 2,700 kQ, plus or 
minus 5 percent. 


41 


2 Chapter 8 Objects and Classes 


uu= Science P8.28 The figure below shows a frequently used electric circuit called a “voltage divider”. 
The input to the circuit is the voltage v;. The output is the voltage v,. The output of 
a voltage divider is proportional to the input, and the constant of proportionality is 
called the “gain” of the circuit. The voltage divider is represented by the equation 


v R, 


v, R, +R, 


where G is the gain and R, and Ry are the resistances of the two resistors that com- 


prise the voltage divider. 


Manufacturing variations cause the actual resistance values to deviate from the 
nominal values, as described in Exercise P8.26. In turn, variations in the resistance 
values cause variations in the values of the gain of the voltage divider. We calculate 
the nominal value of the gain using the nominal resistance values and the actual 
value of the gain using actual resistance values. 


Write a program that contains two classes, VoltageDivider and Resistor. The Resistor 
class is described in Exercise P8.26. The VoltageDivider class should have two instance 
variables that are objects of the Resistor class. Provide a single constructor that 
accepts two Resistor objects, nominal values for their resistances, and the resistor 
tolerance. The class should provide public methods to get the nominal and actual 
values of the voltage divider’s gain. 


Write a main method for the program that demonstrates that the class works properly 
by displaying nominal and actual gain for ten voltage dividers each consisting of 5% 
resistors having nominal values R; = 250 Q and R, =750 Q. 


ANSWERS eOsSiE ERG EG t@OluiESsmlOIN:sS 


1. No—the object "Hello, World" belongs to the return strokes. length(); 

String class, and the String class has no printIn } 

method. 7. None—the public interface has not changed. 
2. Through the substring and charAt methods. 8. You cannot access the instance variables 
3. Asan ArrayList<Character>. Asa char array. directly. You must use the methods provided 


. None. The methods will have the same effect, 


and your code could not have manipulated 
String objects in any other way. 


10. 


by the Clock class. 
2 1.90 


There is no method named getAmountDue. 


5. public void reset() 11. public int getDollarsQ); 
{ ancien 12. length, substring. In fact, all methods of the 
} String class are accessors. 

< wibtieaneaeraines) 13. A mutator. Getting the next number removes 
{ it from the input, thereby modifying it. Not 


14. 


IS; 


16. 


17. 


18. 


19. 
20. 


convinced? Consider what happens if you call 
the nextInt method twice. You will usually 

get two different numbers. But if you call an 
accessor twice on an object (without a muta- 
tion between the two calls), you are sure to get 
the same result. 


This class models a tally counter. 
ap 
public class Counter 


{ 


private int value; 


yew 


Gets the current value of this counter. 
@return the current value 

*/ 

public int getValue() 

{ 


} 


return value; 


Advances the value of this counter by 1. 
ay 
public void count() 


{ 


value = value + 1; 
} 


The code tries to access a private instance 
variable. 
(1) int hours; // Between 1 and 12 


int minutes; // Between 0 and 59 
boolean pm; // True for P.M., false for A.M. 


(2) int hours; // Military time, between 0 and 23 
int minutes; // Between 0 and 59 


(3) int totalMinutes // Between 0 and 60 * 24 - 1 


They need not change their programs at all 
because the public interface has not changed. 
They need to recompile with the new version 
of the Time class. 


(1) String letterGrade; // "A+", "B" 
(2) double numberGrade; // 4.3, 3.0 
21.85 11.90 


public int getDollars() 
{ 
int dollars = (int) totalPrice; 
// Truncates cents 
return dollars; 


} 


21. 


22. 


23. 
24. 
25. 


26. 


27. 


28. 


29. 
30. 


31. 


Answers to Self-Check Questions 413 


Three parameters: two explicit parameters of 
type int, and one implicit parameter of type 
String. 

One parameter: the implicit parameter of type 
String. The method has no explicit parameters. 


"Morgan, Harry" 
public Person() { name = "unknown"; } 


A constructor is generated that has the same 
effect as the constructor provided in this sec- 
tion. It sets both instance variables to zero. 


public Item() 
{ 

price = 0; 

description = ""; 
} 
The price instance variable need not be initial- 
ized because it is set to zero by default, but it is 
clearer to initialize it explicitly. 


(a) Item(String) (b) Item(double) 
(c) Item(String, double) (d) Item() 
(e) No constructor has been called. 


Add these lines: 


registerl.clear(); 
System.out.printIn(registerl.getCountQ); 
System.out.printInC"Expected: 0"); 
System.out.printf("%.2f\n", 
registerl.getTotal()); 
System.out.printIn("Expected: 0.00"); 


1,0 
These environments allow you to call methods 
on an object without creating a main method. 





Car myCar 


Car(mpq) 
add¢as(amount) 
drive(distance) 
getGasLeft 





front 





gasLeft 


milesPerGallon 














back 


414 


32. 


33. 


34. 


35. 


36. 


37. 


Chapter 8 Objects and Classes 





milesPerGallon 














gasLeft wmilesPerGallon totalMiles 











milesPerGallon totalMiles 





13 








It needs to be incremented in the deposit and 
withdraw methods. There also needs to be some 
method to reset it after the end of a statement 
period. 


The ArrayList<String> instance variable is pri- 
vate, and the class users cannot acccess it. 


Add an ArrayList<Double> prices. In the addItem 
method, add the current price. In the reset 
method, replace the array list with an empty 
one. Also supply a method printReceipt that 
prints the prices. 


38. 


39. 


40. 


41. 


42. 


43. 
44. 


45. 
46. 
47. 


48. 


The tax ID of an employee does not change, 
and no setter method should be supplied. The 
salary of an employee can change, and both 
getter and setter methods should be supplied. 


It is an example of the “state pattern” 
described in Section 8.9.5. The direction is a 
state that changes when the bug turns, and it 
affects how the bug moves. 


Both greeting and greeting2 refer to the same 
string "Hello". 


They both still refer to the string "He110". 
The toUpperCase method computes the string 
"HELLO", but it is not a mutator—the original 
string is unchanged. 


(a) 0 

(b) A null pointer exception is thrown. 

It is a reference of type String. 

public void addItems(int quantity, double price) 


{ 
for (int i = 1; i <= quantity; i++) 
{ 
this.addItem(price) ; 


i 
} 


System. in and System. out 
Math. PI 


The method needs no data of any object. The 
only required input is the values argument. 


Yes, it works. Static methods can call each 
other and access static variables—any method 
can. But it is a terrible idea. A program that 
consists of a single class with many methods is 
hard to understand. 


CHAPTER GOALS 





To learn about inheritance 


To implement subclasses that inherit and override superclass methods 


To understand the concept of polymorphism 


To be familiar with the common superclass Object and its methods 


To work with interface types 


CHAPTER CONTENTS 


9.1 INHERITANCE HIERARCHIES 416 

Programming Tip 9.1: Use a Single Class for 
Variation in Values, Inheritance for Variation 
in Behavior 420 


9.2 IMPLEMENTING SUBCLASSES 420 

Syntax 9.1: Subclass Declaration 422 

Common Error 9.1: Replicating Instance Variables 
from the Superclass 423 

Common Error 9.2: Confusing Super- and 
Subclasses 424 


9.3 OVERRIDING METHODS 424 
Common Error 9.3: Accidental Overloading 428 
Common Error 9.4: Forgetting to Use super 
When Invoking a Superclass Method 429 
Special Topic 9.1: Calling the Superclass 
Constructor 429 
Syntax 9.2: Constructor with 
Superclass Initializer 430 


9.4 POLYMORPHISM 430 

Special Topic 9.2: Dynamic Method Lookup and 
the Implicit Parameter 433 

Special Topic 9.3: Abstract Classes 434 

Special Topic 9.4: Final Methods and Classes 435 


Special Topic 9.5: Protected Access 436 

How To 9.1: Developing an Inheritance 
Hierarchy 436 

Worked Example 9.1: Implementing an Employee 
Hierarchy for Payroll Processing @ 

Video Example 9.1: Building a 
Discussion Board @ 


9.5 OBJECT: THE COSMIC 
SUPERCLASS 441 
Syntax 9.3: The instanceof Operator 445 
Common Error 9.5: Don’t Use Type Tests 446 
Special Topic 9.6: Inheritance and the 
toString Method 446 
Special Topic 9.7: Inheritance and the 
equals Method 447 


9.6 INTERFACE TYPES 448 
Syntax 9.4: Interface Types 449 
Common Error 9.6: Forgetting to Declare 
Implementing Methods as Public 453 
Special Topic 9.8: Constants in Interfaces 453 
Special Topic 9.9: Function Objects 454 
Video Example 9.2: Drawing 
Geometric Shapes @ 





9.1 Inheritance Hierarchies 


A subclass inherits 
data and behavior 
from a superclass. 


You can always use 
a subclass object 
in place of a 
superclass object. 


416 


In object-oriented design, inheritance is a relationship between a more general class 
(called the superclass) and a more specialized class (called the subclass). The subclass 
inherits data and behavior from the superclass. For example, consider the relation- 
ships between different kinds of vehicles depicted in Figure 1. 

Every car is a vehicle. Cars share the common traits of all vehicles, such as the abil- 
ity to transport people from one place to another. We say that the class Car inherits 
from the class Vehicle. In this relationship, the Vehicle class is the superclass and the 
Car class is the subclass. In Figure 2, the superclass and subclass are joined with an 
arrow that points to the superclass. 

Suppose we have an algorithm that manipulates a Vehicle object. Because a car is a 
special kind of vehicle, we can use a Car object in such an algorithm, and it will work 
correctly. The substitution principle states that you can always use a subclass object 
when a superclass object is expected. For example, consider a method that takes an 
argument of type Vehicle: 


void processVehicle(Vehicle v) 


a 


Vehicle 





Sedan SUV 


Figure 1 An Inheritance Hierarchy of Vehicle Classes 


9.1 Inheritance Hierarchies 417 


Figure 2 
An Inheritance Diagram 





Because Car is a subclass of Vehicle, you can call that method with a Car object: 


Car myCar = new Car(. . .); 

processVehicle(myCar) ; 
Why provide a method that processes Vehicle objects instead of Car objects? That 
method is more useful because it can handle any kind of vehicle (including Truck and 
Motorcycle objects). In general, when we group classes into an inheritance hierarchy, 
we can share common code among the classes. 

In this chapter, we will consider a simple hierar- 
chy of classes. Most likely, you have taken computer- ae 
graded quizzes. A quiz consists of questions, and there ES oe a 


: \. aed 
are different kinds of questions: pee re 6 ra 
e Fill-in-the-blank es = 
¢ Choice (single or multiple) NX 
¢ Numeric (where an approximate answer is ok; 

e.g., 1.33 when the actual answer is 4/3) We will develop a simple but 


flexible quiz-taking program 


e Free response to illustrate inheritance. 


Figure 3 shows an inheritance hierarchy for these 
question types. 


Figure 3 
Inheritance Hierarchy 
of Question Types 





418 Chapter9 Inheritance and Interfaces 


At the root of this hierarchy is the Question type. A question can display its text, 
and it can check whether a given response is a correct answer. 


section_1/Question.java 
[** 


1 

2 A question with a text and an answer. 
Se 

4 public class Question 

> { 

6 private String text; 

7 private String answer; 

8 

9 


[** 
10 Constructs a question with empty question and answer. 
11 */ 
12 public Question() 
13 { 
14 text = ""5 
15 answer = ""; 
16 } 
17 
18 [** 
19 Sets the question text. 
20 @param questionText the text of this question 
21 * 
22 public void setText(String questionText) 
23 { 
24 text = questionText; 
25 } 
26 
27 /** 
28 Sets the answer for this question. 
29 @param correctResponse the answer 
30 */ 
31 public void setAnswer(String correctResponse) 
32 { 
33 answer = correctResponse; 
34 } 
35 
36 /** 
37 Checks a given response for correctness. 
38 @param response the response to check 
39 @return true if the response was correct, false otherwise 
40 */ 
41 public boolean checkAnswer(String response) 
42 { 
43 return response. equals (answer) ; 
44 } 
45 
46 {i 
47 Displays this question. 
48 */ 
49 public void display() 
50 { 
51 System.out.printIn(text) ; 
52 } 


9.1 Inheritance Hierarchies 419 


This question class is very basic. It does not handle multiple-choice questions, 
numeric questions, and so on. In the following sections, you will see how to form 
subclasses of the Question class. 

Here is a simple test program for the Question class: 


section_1/QuestionDemol .java 


1 import java.util.ArrayList; 


2 import java.util.Scanner; 

3 

4 [** 

5 This program shows a simple quiz with one question. 
6 */ 

7 public class QuestionDemo1 

8 { 

9 public static void main(String[] args) 

10 { 

11 Scanner in = new Scanner(System.in); 

12 

13 Question q = new Question(); 

14 q.setText("Who was the inventor of Java?"); 
15 q.setAnswer("James Gosling"); 

16 

17 q.displayQ; 

18 System.out.print("Your answer: "); 

19 String response = in.nextLine(); 
20 System.out.printIn(q.checkAnswer(response) ) ; 
21 } 
papa 


Program Run 


Who was the inventor of Java? 
Your answer: James Gosling 
true 


1. Consider classes Manager and Employee. Which should be the superclass and which 
should be the subclass? 


2. What are the inheritance relationships between classes BankAccount, Checking- 
Account, and Savi ngsAccount ? 





3. Figure 7.2 shows an inheritance diagram of exception classes in Java. List all 
superclasses of the class RuntimeException. 


4. Consider the method doSomething(Car c). List all vehicle classes from Figure 1 
whose objects cannot be passed to this method. 


5. Should a class Quiz inherit from the class Question? Why or why not? 


Practice It Now youcantry these exercises at the end of the chapter: R9.1, R9.7, R9.9. 


420 Chapter9 Inheritance and Interfaces 


Programming Tip 9.1 Use a Single Class for Variation in Values, Inheritance for 
: Variation in Behavior 


The purpose of inheritance is to model objects with different behavior. When students first 
learn about inheritance, they have a tendency to overuse it, by creating multiple classes even 
though the variation could be expressed with a simple instance variable. 

Consider a program that tracks the fuel efficiency of a fleet of cars by logging the distance 
traveled and the refueling amounts. Some cars in the fleet are hybrids. Should you create a sub- 
class HybridCar? Not in this application. Hybrids don’t behave any differently than other cars 
when it comes to driving and refueling. They just have a better fuel efficiency. A single Car class 
with an instance variable 


double milesPerGallon; 


is entirely sufficient. 

However, if you write a program that shows how to repair different kinds of vehicles, then 
it makes sense to have a separate class HybridCar. When it comes to repairs, hybrid cars behave 
differently from other cars. 


.2 Implementin 


In this section, you will see how to forma subclass and how a subclass automatically 
inherits functionality from its superclass. 
Suppose you want to write a program that handles questions such as the following: 
In which country was the inventor of Java born? 
1. Australia 
2. Canada 


3. Denmark 
4. United States 


You could write a ChoiceQuestion class from scratch, with methods to set up the ques- 
tion, display it, and check the answer. But you don’t have to. Instead, use inheritance 
and implement ChoiceQuestion as a subclass of the Question class (see Figure 4). 


Recon In Java, you form a subclass by specifying what makes the subclass different from 


methods that it does its superclass. . 
not override. Subclass objects automatically have the instance variables that are declared in the 
superclass. You only declare instance variables that are not part of the superclass 
objects. 
Question 
Figure 4 Choi ce 
Question 


The ChoiceQuestion Class isa 
Subclass of the Question Class 


A subclass can 
override a 
superclass method 
by providing a new 
implementation. 


The extends reserved 
word indicates that a 
class inherits froma 
superclass. 


9.2 Implementing Subclasses 421 


Like the manufacturer of a 
stretch limo, who starts with a 
regular car and modifies it, a 
programmer makes a subclass 
by modifying another class. 





The subclass inherits all public methods from the superclass. You declare any 
methods that are new to the subclass, and change the implementation of inherited 
methods if the inherited behavior is not appropriate. When you supply a new imple- 
mentation for an inherited method, you override the method. 

A Choi ceQuestion object differs from a Question object in three ways: 


¢ Its objects store the various choices for the answer. 
e There is a method for adding answer choices. 


e The display method of the ChoiceQuestion class shows these choices so that the 
respondent can choose one of them. 


When the ChoiceQuestion class inherits from the Question class, it needs to spell out 
these three differences: 


public class ChoiceQuestion extends Question 


{ 
// This instance variable is added to the subclass 
private ArrayList<String> choices; 


// This method is added to the subclass 


public void addChoice(String choice, boolean correct) {.. . } 


// This method overrides a method from the superclass 
public void display) {.. . } 
} 


The reserved word extends denotes inheritance. 

Figure 5 shows the layout of a ChoiceQuestion object. It has the text and answer 
instance variables that are declared in the Question superclass, and it adds an additional 
instance variable, choices. 

The addChoice method is specific to the ChoiceQuestion class. You can only apply it to 
ChoiceQuestion objects, not general Question objects. 

In contrast, the display method is a method that already exists in the superclass. 
The subclass overrides this method, so that the choices can be properly displayed. 


Question portion 





Figure 5 Data Layout of Subclass Object 


422 Chapter 9 Inheritance and Interfaces 


Syntax 9.1 Subclass Declaration 


public class SubclassName extends SuperclassName 


{ 
instance variables 
methods 


} The reserved word extends 


denotes inheritance. 


Declare instance variables Subclass Superelass 
that are added to / 7 
the subclass. public class ChoiceQuestion extends Question 
{ 
dockaremetesthat are private ArrayList<String> choices 
jal iS Tnat al 


added to the subelass. ~~. public void addChoice(String choice, boolean correct) {... 


Declare methods that public void display() {.. . } 
the subclass overrides. a. 





All other methods of the Question class are automatically inherited by the Choice- 
Question class. 
You can call the inherited methods ona subclass object: 


choiceQuestion.setAnswer("2"); 


However, the private instance variables of the superclass are inaccessible. Because 
these variables are private data of the superclass, only the superclass has access to 
them. The subclass has no more access rights than any other class. 

In particular, the ChoiceQuestion methods cannot directly access the instance vari- 
able answer. These methods must use the public interface of the Question class to access 
its private data, just like every other method. 

To illustrate this point, let’s implement the addChoice method. The method has two 
arguments: the choice to be added (which is appended to the list of choices), and a 
Boolean value to indicate whether this choice is correct. For example, 


question.addChoice("Canada", true); 


The first argument is added to the choices variable. If the second argument is true, then 
the answer instance variable becomes the number of the current choice. For example, if 
choices.size() is 2, then answer is set to the string "2". 


public void addChoice(String choice, boolean correct) 
{ 

choices.add(choice); 

if (correct) 


{ 
// Convert choices.size() to string 
String choiceString = "" + choices.size(); 
setAnswer(choiceString) ; 

} 


} 


You can’t just access the answer variable in the superclass. Fortunately, the Ques- 
tion class has a setAnswer method. You can call that method. On which object? The 


ONLINE EXAMPLE 


@ Aprogram that 
shows a simple Car 
class extending a 
Vehicle class. 





SELF CHECK 


Practice It 


(@leyaalankelamaiage) mcm 








9.2 Implementing Subclasses 423 


question that you are currently modifying—that is, the implicit parameter of the 
ChoiceQuestion.addChoice method. As you saw in Chapter 8, if you invoke a method on 
the implicit parameter, you don’t have to specify the implicit parameter and can write 
just the method name: 


setAnswer(choiceString) ; 


If you prefer, you can make it clear that the method is executed on the implicit 
parameter: 


this.setAnswer(choiceString) ; 


6. Suppose qis an object of the class Question and cq an object of the class Choice- 
Question. Which of the following calls are legal? 
a. q.setAnswer (response) 
b. cq.setAnswer (response) 
c. q.addChoice(choice, true) 
d. cq.addChoice(choice, true) 
7. Suppose the class Employee is declared as follows: 


public class Employee 


{ 
private String name; 
private double baseSalary; 
public void setName(String newName) { . . . } 
public void setBaseSalary(double newSalary) { .. . } 
public String getName() {... } 
public double getSalary() {.. . } 
} 


Declare a class Manager that inherits from the class Employee and adds an instance 
variable bonus for storing a salary bonus. Omit constructors and methods. 


8. Which instance variables does the Manager class from Self Check 7 have? 


9. Inthe Manager class, provide the method header (but not the implementation) for 
a method that overrides the getSalary method from the class Employee. 


10. Which methods does the Manager class from Self Check 9 inherit? 


Now you can try these exercises at the end of the chapter: R9.3, P9.6, P9.10. 


Replicating Instance Variables from the Superclass 


A subclass has no access to the private instance variables of the superclass. 


public ChoiceQuestion(String questionText) 


{ 


text = questionText; // Error—tries to access private superclass variable 
} 
When faced with a compiler error, beginners commonly “solve” this issue by adding another 
instance variable with the same name to the subclass: 


public class ChoiceQuestion extends Question 


{ 


424 Chapter9 Inheritance and Interfaces 


private ArrayList<String> choices; 
private String text; // Don’t! 


} 


Sure, now the constructor compiles, but it doesn’t set the correct text! Such a ChoiceQuestion 
object has two instance variables, both named text. The constructor sets one of them, and the 
display method displays the other. 


Question portion 





a eae 





If you compare an object of type ChoiceQuestion with an object of type Question, you find that 


e The reserved word extends suggests that the ChoiceQuestion object is an extended version of 
a Question. 


e The ChoiceQuestion object is larger; it has an added instance variable, choices. 
e The ChoiceQuestion object is more capable; it has an addChoice method. 


It seems a superior object in every way. So why is ChoiceQuestion called the subclass and 
Question the superclass? 

The super/sub terminology comes from set theory. Look at the set of all questions. Not all 
of them are ChoiceQuestion objects; some of them are other kinds of questions. Therefore, the 
set of ChoiceQuestion objects is a subset of the set of all Question objects, and the set of Question 
objects is a superset of the set of ChoiceQuestion objects. The more specialized objects in the 
subset have a richer state and more capabilities. 


verriding Meth 





An overriding 
method can extend 
or replace the 
functionality of the 


superclass method. 


The subclass inherits the methods from the superclass. If you are not satisfied with 
the behavior of an inherited method, you override it by specifying a new implemen- 
tation in the subclass. 

Consider the display method of the ChoiceQuestion class. It overrides the superclass 
display method in order to show the choices for the answer. This method extends the 
functionality of the superclass version. This means that the subclass method carries 
out the action of the superclass method (in our case, displaying the question text), and 
it also does some additional work (in our case, displaying the choices). In other cases, 
a subclass method replaces the functionality ofa superclass method, implementing an 
entirely different behavior. 

Let us turn to the implementation of the display method of the ChoiceQuestion class. 
The method needs to 


© Display the question text. 
© Display the answer choices. 


Use the reserved 
word super to calla 
superclass method. 





hm 
ANIMATION 
Inheritance 


fi 





9.3 Overriding Methods 425 


The second part is easy because the answer choices are an instance variable of the 
subclass. 


public class ChoiceQuestion 


{ 


public void display() 
{ 
// Display the question text 


// Display the answer choices 
for (int i = 0; 71 < choices.size(); i++) 
{ 


int choiceNumber = i + 1; 
System.out.printIn(choiceNumber + 


+ choices.get(i)); 
} 
I 

t 
But how do you get the question text? You can’t access the text variable of the super- 
class directly because it is private. 

Instead, you can call the display method of the superclass, by using the reserved 
word super: 

public void display() 


{ 
// Display the question text 


super.display(); // OK 
// Display the answer choices 


} 
If you omit the reserved word super, then the method will not work as intended. 


public void display() 
{ 
// Display the question text 
displayQ; // Error—invokes this.displayQ 


} 


Because the implicit parameter this is of type ChoiceQuestion, and there is a method 
named display in the ChoiceQuestion class, that method will be called—but that is just 
the method you are currently writing! The method would call itself over and over. 

Here is the complete program that lets you take a quiz consisting of two Choice- 
Question objects. We construct both objects and pass them to a method presentQuestion. 
That method displays the question to the user and checks whether the user response 
is correct. 


section_3/QuestionDemo2.java 


public static void main(String[] args) 


{ 


1 import java.util.Scanner; 

2 

3 [** 

4 This program shows a simple quiz with two choice questions. 
5 af 

6 public class QuestionDemo2 

a 

8 

9 


426 Chapter9 Inheritance and Interfaces 


ChoiceQuestion first = new ChoiceQuestion(); 

first.setText("What was the original name of the Java language?"); 
first.addChoice("*7", false); 

first.addChoice("Duke", false); 

first.addChoice("Oak", true)