An Interdisciplinary Approach
Robert Sedgewick Kevin Wayne
Introduction
to
Programming in Java
Introduction
to
Programming in Java
An Interdisciplinary Approach
Robert Sedgewick
and
KevinWayne
Princeton University
Boston San Francisco New York
London Toronto Sydney Tokyo Singapore Madrid
Mexico City Munich Paris Cape Town Hong Kong Montreal
Publisher
Executive Editor
Associate Editor
Associate ManagingEditor
SeniorDesigner
Digital Assets Manager
Senior MediaProducer
SeniorMarketingManager
MarketingAssistant
Senior Author Support/
Technology Specialist
GregTobin
Michael Hirsch
LindseyTriebel
Jeffrey Holcomb
Joyce Cosentino Wells
Marianne Groth
BethanyTidd
Michelle Brown
SarahMilmore
SeniorManufacturingBuyer
Copyeditor
Composition and Illustrations Robert Sedgewick andKevin Wayne
JoeVetere
CarolMelville
Genevieve d'Entremont
Cover Image: ©RobertSedgewick and Kevin Wayne
Page 353 ©2006 C.Herscovici, Brussels / Artists Rights Society (ARS), New York Banque d' Images, ADAGP / Art
Resource, NY
Many ofthe designations used by manufacturers and sellers todistinguish their products are claimed as trade
marks. Where those designations appear inthis book, and Addison-Wesley was aware ofa trademark claim, the
designations have beenprinted in initial caps or allcaps.
The interior of this book was composedin AdobeInDesign.
LibraryofCongressCataloging-in-Publication Data
Sedgewick, Robert, 1946-
Introduction toprogramming inJava: aninterdisciplinary approach / byRobert Sedgewick andKevin Wayne.
p. cm.
Includes index.
ISBN978-0-321-49805-2 (alk. paper)
1. Java (Computer program language) 2. Computer programming. I.Wayne, Kevin Daniel, 1971- II.Title.
QA76.73.J38S413 2007
005.13'3-dc22
2007020235
Copyright ©2008 Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in anyform or byanymeans, electronic, mechanical, photocopying,
recording, or otherwise, without theprior written permission of thepublisher. Printed in the United States of
America. Forinformationon obtainingpermissionfor useof materialin thiswork,pleasesubmit a written request
to Pearson Education,Inc., Rightsand Contracts Department, 501 BoylstonStreet,Suite 900,Boston,MA02116,
fax (617) 671-3447, or online at http: //www.pearsoned. com/1egal /permi ssi ons. htm.
ISBN-13:978-0-321-49805-2
ISBN-10:0-321-49805-4
123456789 10—CRW—11 10 09 08 07
The basis for education in the last millenniumwas "reading, writing, and arith
metic;" now it is reading, writing, and computing. Learning to program is an
essential part of the education of every student in the sciences and engineering.
Beyond direct applications, it isthe first step in understanding the natureof com
puter science's undeniable impact on the modern world. This book aims to teach
programming to those who need or want to learn it, in a scientific context.
Our primary goal is to empower students by supplying the experience and
basic tools necessary to use computation effectively. Our approach is to teach stu
dents that writing a program is a natural, satisfying, and creative experience (not
an onerous task reserved for experts). We progressively introduce essential con
cepts, embrace classic applications from applied mathematics and the sciences to
illustrate the concepts, andprovide opportunities for students to write programs
to solveengagingproblems.
We usethe Java programming language foralloftheprograms in thisbook—
we refer to Java after programming in thetitle to emphasize the idea that the book
is aboutfundamental concepts inprogramming, not Java per se. This book teaches
basic skills forcomputational problem-solving thatare applicable in many modern
computing environments, and is a self-contained treatment intended for people
withno previous experience in programming.
Thisbook is an interdisciplinary approachto the traditional CS1 curriculum,
where we highlight the role of computing in other disciplines, from materials sci
ence to genomics to astrophysics to network systems. This approach emphasizes
for students the essential idea that mathematics, science, engineering, and com
puting are intertwined in the modern world. While it is a CS1 textbook designed
for anyfirst-year college studentinterested in mathematics, science, or engineer
ing (including computerscience), the book also can be used for self-study or as a
supplement in a coursethat integrates programmingwith another field.
Coverage The bookisorganized around fourstages oflearning to program: ba
sic elements, functions, object-oriented programming, and algorithms (with data
structures). We provide the basic information readers need to buildconfidence in
writing programs at each level before moving to thenext level. An essential feature
of our approach is to use example programs that solve intriguing problems, sup
ported with exercises ranging from self-study drills to challenging problems that
call for creative solutions.
Basic elements include variables, assignment statements, built-in types of
data,flow of control (conditionals and loops), arrays, and input/output, including
graphics and sound.
Functions and modules are the student's first exposure to modular program
ming. We build upon familiarity with mathematical functions to introduce Java
static methods, and then consider the implications of programming with func
tions, including libraries of functions and recursion. We stress the fundamental
idea of dividing a program into components that can beindependently debugged,
maintained, and reused.
Object-orientedprogramming isourintroduction to data abstraction. We em
phasize the concepts ofadata type (aset ofvalues and aset ofoperations onthem)
and an object (an entity that holds a data-type value) and their implementation
using Java's class mechanism. We teach students how to use, create, anddesign data
types. Modularity, encapsulation, and other modern programming paradigms are
the central concepts of this stage.
Algorithms and data structures combine these modern programming para
digms with classic methods of organizing and processing data that remain effec
tive for modern applications. We provide an introduction to classical algorithms
for sorting and searching as well as fundamental data structures (including stacks,
queues, and symbol tables) and their application, emphasizing theuse ofthescien
tificmethod to understand performance characteristics of implementations.
Applications in science and engineering are a key feature of the text. We moti
vate each programming conceptthat we address by examiningits impact on spe
cific applications. We draw examples from applied mathematics, the physical and
biological sciences, andcomputer science itself, andinclude simulation of physical
systems, numerical methods, data visualization, sound synthesis, image process
ing, financial simulation, and information technology. Specific examples include a
treatment in the first chapterof Markov chains for web page ranks and case stud
ies that address the percolation problem, N-body simulation, and the small-world
VI
phenomenon. These applications are an integral partofthetext. They engage stu
dents in the material, illustrate theimportance oftheprogramming concepts, and
provide persuasive evidence of the critical role played by computation in modern
science and engineering.
Our primary goal is to teach the specific mechanismsand skills that are need
edto develop effective solutions to anyprogramming problem. We workwithcom
plete Java programs andencourage readers to use them. We focus on programming
by individuals, not library programming or programming in the large (which we
treat briefly in an appendix).
Use in the Curriculum This book is intended for a first-year college course
aimed at teaching novices to program in the context of scientific applications.
Taught from this book, prospective majors in any area of science and engineering
will learnto programin a familiar context. Students completing a course basedon
this book willbe well-prepared to apply their skills in later courses in science and
engineering and to recognize when further education in computer science might
be beneficial.
Prospective computer science majors, in particular, canbenefit fromlearning
to program in the contextof scientific applications. A computer scientist needsthe
same basic background in the scientific method and the same exposure to the role
of computation in science as does a biologist, an engineer, or a physicist.
Indeed, our interdisciplinary approach enables colleges and universities to
teach prospective computer science majors and prospective majors in other fields
ofscience andengineering in thesame course. We cover thematerial prescribed by
CS1, but our focus on applications brings life to the concepts and motivates stu
dents to learn them. Our interdisciplinary approach exposes students to problems
in manydifferent disciplines, helping themto morewisely choose a major.
Whatever thespecific mechanism, theuse ofthis bookisbestpositioned early
in the curriculum. First, this positioning allows us to leverage familiar material
in high school mathematics and science. Second, students who learn to program
early in theircollege curriculum will thenbeable to use computers moreeffectively
when moving on to courses in their specialty. Like reading and writing, program
ming is certain to be an essential skill for any scientist or engineer. Students who
have grasped the concepts in thisbookwill continually develop that skill through a
lifetime,reaping the benefits of exploitingcomputation to solve or to better under
stand the problems and projects that arise in their chosen field.
VII
Prerequisites This book is meant to be suitable for typical science and engi
neering students in theirfirst year ofcollege. Thatis, we do not expect preparation
beyond what is typically required for other entry-level science and mathematics
courses.
Mathematical maturity is important. While we do not dwell on mathematical ma
terial, we do refer to the mathematics curriculum that students have taken in high
school, including algebra, geometry, and trigonometry. Moststudents in our target
audience (those intending to major in the sciences and engineering) automatically
meet these requirements. Indeed, we take advantage of their familiarity with the
basic curriculum to introduce basic programming concepts.
Scientific curiosity is also an essential ingredient. Science and engineering students
bring with them a sense offascination intheability ofscientific inquiry tohelp ex
plain what goes on in nature. We leverage this predilection with examples ofsimple
programs that speak volumes aboutthe naturalworld. We do not assume anyspe
cific knowledge beyond that provided bytypical highschool courses in mathemat
ics,physics, biology, or chemistry.
Programming experience is not necessary, but also is not harmful. Teaching pro
gramming is our primary goal, so we assume no prior programming experience.
But writing a program to solve a new problem isa challenging intellectual task, so
students who have written numerous programs in high school can benefit from
taking an introductory programming course based on this book (just as students
whohave writtennumerous essays in highschool canbenefit froman introductory
writing course in college). The book can support teaching students with varying
backgrounds because the applications appeal to bothnovices andexperts alike.
Experience using a computer is also not necessary, but also is not at all a problem.
College students use computers regularly, to communicate with friends and rela
tives, listento music, process photos,and manyother activities. The realization that
they can harness the power of their own computer in interesting and important
ways is an excitingand lasting lesson.
In summary,virtuallyallstudentsin science and engineeringare prepared to take a
course based on this book as a part of their first-semester curriculum.
VIII