
本书是斯坦福大学教授、著名的计算机科学教育领导者Eric S.Roberts编写的《C语言艺术与科学》一书的姊妹篇,是计算机科学的经典教材,介绍了计算机科学的基础知识和程序设计的专门知识。本书以介绍Java语言为主线,不仅涵盖Java语言的基本知识,而且介绍了软件工程技术以及如何应用良好的程序设计风格进行开发等内容。本书采用了Java库函数的方法,强调抽象的原则,详细阐述了库和模块化开发。此外,本书还利用大量实例讲述解决问题的全过程,对开发过程中常见的错误也给出了解决和避免的方法。
本书是关于数据结构、程序设计和软件工程的绝佳入门书籍,既可作为高等院校计算机科学导论课程及Java语言程序设计课程的教材,也是Java语言开发人员的极佳参考用书。
【作者介绍】
Eric S. Roberts,美国斯坦福大学计算机科学系教授,并担任主管教学事务的系主任。他由于教学改革所取得的成就被评为Charles Simonyi荣誉教授。他于1980年获得哈佛大学应用数学博士学位,并曾在加州Palo Alto的DEC公司的系统研究中心工作了5年。作为一位成功的教育工作者,Roberts还获得了1993年的Bing Award奖。
edicated to the memory of Anita Borg (1949--2003)
J 5 (1949-2003)
for her tireless efforts to bring the excitement
of computing to a wider audience.
puting to a wider audience.
ac the Student
Welcome! BV picking up this book, you have taken a step into the world of
J picking up this book, you have taken a step into the world of
.
computer science--a field of study that has grown from almost nothing half a
'
century ago to one of the most vibrant and active disciplines of our time.
.
Over that time, the computer has opened up extraordinary possibilities in almost
everV area of human endeavor. Business leaders todaV are able to manage global
y area of human endeavor. Business leaders today are able to manage global
enterprises on an unprecedented scale because computers enable them to transfer
.
data anVwhere in a fraction of a second. Scientists can now solve problems that
y where in a fraction of a second. Scientists can now solve problems that
,,
were beyond their reach in the days before comDUters made the necessary
J J puters made the necessary
1'.
calculations possible. The World Wide Web puts a vast amount of information at
your fingertips and lies at the foundation of a vibrant industry that did not exist a
decade ago. Filmmakers can use computer technology to create animated features
that would have been unthinkable in Walt DisneV's time. Modern computation has
y b time. Modern computation has
, I
revolutionized many fields. enabling biologists to sequence the human genome,
.
..
economists to model international markets, and literary scholars to assess whether
.
an unattributed Elizabethan manuscript might have been penned by Shakespeare.
Computing is a profoundly empowering technology. The computing industry
. I
continues to grow, with more jobs available today than at the height of the internet
boom of the 1990s. But the advances we have seen up to now are small compared to
,..
what we will experience in this century. Those of you who are students today will
.,.,
soon inherit the responsibility of guiding that progress. No matter what field you
,,
choose, understanding how to use computing effectively will be of enormous value.
Like most skills that are worth knowing, learning how computers work and how
to control their enormous power takes time. You will not understand it all at once.
You must start somewhere. Twenty-five centuries ago, the Chinese philosopher
J a I the Chinese philosopher
Lao-tin observed that the longest journey begins with a single step. This book can
be Vour beZinning.
y our beginning.
For many of Von, however, the first step can be the hardest to take. Many
J J
students find computers overwhelming and imagine that computer science is beyond
their reach. LearninZ the basics of Drogramming, however, does not require
b programming, however, does not require
1'
advanced mathematics or a detailed understanding of electronics. What matters in
5
..'
programming is whether you can progress from the statement of a problem to its
,.
solution. To do so, you must be able to think logically. You must have the necessary
discipline to express your logic in a form that the computer can understand. Perhaps
I
most impoftantly, you must be able to see the task through to its completion without
.
getting discouraged by difficulties and setbacks. If you stick with the process, you
., 1,.,
will discover that reaching the solution is so exhilaratinZ that it more than makes UD
& [he solution is so exhilarating that it more than makes up
for anV frustrations you encounter along the way.
y trustrations you encounter along the way.
I wish Von a pleasant tourney along that road.
J pleasant journey along that road.
Eric Roberts
Qtonford Universit\l
atanford University
.
JanuarV 2007
y
.
IV
ac the instructor
This text is intended for use in the first programming course in a typical college or
..
university curriculum. It covers the material in a traditional CSI course, as defined
J, as defined
in the Curriculum '78 report prepared by the Association for Computing Machinery
(ACM). It also includes the full set of topics specified for the CS 10ic or CS 1 1 ic
courses in the computer science volume of the more recent Computing Curriculum
2001 report.
The Art and Science o[Java uses a similar approach to that of my 1995 textbook,
u Java uses a similar approach to that of my 1995 textbook,
The Art and Science of C. Each of these texts uses libraries to make programming
less complex and consequently more accessible to the novice. In the C-based
..
version, those libraries proved to be extremely successful with students, not only at
Stanford, but at many other institutions as well. This book uses the ACM Java
Libraries to achieve the same goals.
In the Vears since its initial release in 1995, the Java programming language has
;, the Java programming language has
become increasingly imDoftant as an instructional languaZe, to the point that it is
.iy important as an instructional language, to the point that it is
now something of a standard in introductory computing courses. On the positive
side, Java offers many advantages over earlier teaching languages, primarily by
making it possible for students to write highly interactive programs that capture
& it possible for students to write highly interactive programs that capture
their interest and imagination. At the same time, Java is far more sophisticated than
languages that have traditionally filled the role of teaching languages, such as
BASIC and Pascal. The complexity that accompanies Java's sophistication can be a
.. n.
significant barrier to both teachers and students as they try to understand the
structure of the language.
To address the problems that introductory instructors encountered using Java, in
2004 the ACM established the Java Task Force and gave it the following charge:
To review the Java language, APIs, and tools from the perspective of
introductory computing education and to develop a stable collection of
pedagogical resources that will make it easier to teach Java to first-year
computing students without having those students overwhelmed by its
complexity.
Over the next two years, the Java Task Force develODed a new set of libraries
J. pod a new set of libraries
..
intended to support the use of Java at the introductory level. After releasing two
pport the use of Java at the introductory level. After releasing two
preliminary drafts to obtain community feedback, the Java Task Force published its
final report in the summer of 2006. The ACM Java Libraries described in that
report are available on the following web site:
http: //j if. am. org/
In addition to the ACM Java Libraries themselves, the web site contains a large
collection of demo programs, a tutorial guide, an extensive discussion of the
rationale behind the design of the various packages, and an executive summary that
identifies the following as the greatest strengths of the libraries. The ACM Java
Libraries provide
provide
v
. A simDle obiect-oriented model for programs. The Program class dehned in
pie object-oriented modelfor programs. The Program class dehned in
the acm.program package offers an easy-to-use model for writing simple
x,,..
programs. In addition to hiding the static main method, the Program class
and its standard subclasses provide a highly intuitive example of
object.
onented class hierarchies.
. 4 model for innut and outnut that treats traditional console I/O and dialog
A model for inDUt and outDut that treats traditional console I/O and dialog
J put and output that treats traditional console I/O and dialog
I/O svmmetricallv. The acm. ic package defines the classes IOConsole and
ymmetrically. The acm. ic package defines the classes IOConsole and
IODialog that share a common interface for all input/output operations. This
design addresses Java's lack of a simple input mechanism in a way that
I.
emphasizes the value of interface-based design.
. In extensive librarl) of graphical objects. The acm.graphics package
An extensive library of graphical objects. The acm.graphics package
.,.
implements a simple but extremely powerful model for creating graphical
piements a simple but extremely powerful model for creating graphical
..
pictures based on the metaphor of a felt board in which students construct
,.
graphical objects of various types and place them on a canvas. This design
,.
emphasizes the use of objects and frees the student from having to respond
,...
explicitly to repaint requests.
.' minimal set of new classes to sunoort develonment of oraohical user
A minimal set of new classes to suDDort develoDment of graphical user
J new classes to suPPort development Of graphical user
.
interfaces. The acm. gut package includes a small set of classes to bring
J cul package includes a small set of classes to bring
Java's extensive GUI-development resources within the reach of novice
programmers.
. Backward comDatibility [or aPPlets. Unlike most Java code today, programs
patibilityfor aPPlets. Unlike most Java code today, programs
developed using the ACM Java Libraries can typically be executed as applets
pod using the ACM Java Libraries can typically be executed as applets
1,,, m'.
even on older web browsers. This flexibility makes these libraries an ideal
J makes these libraries an ideal
foundation for web-based teaching tools and lecture demonstrations.
Given the enormous number of classes and methods that are available in Java's
,.,... I
own libraries, it is inevitable that a book of this sort will leave out some particular
feature of Java. It is impossible to cover everything and still produce a book that is
.,,
accessible to the average student. In terms of the choice of topics, this book seeks
to offer a coherent presentation that teaches the fundamentals of computer science
rather than to cover everVthing there is to know about Java. In many ways, the
J & Lhere is to know about Java. In many ways, the
.'...
guiding principle for the choice of topics in this book comes' from the following
observation from Antoine de Saint-Exupery in his 1942 memoirs Pilote de Guerre
(later quoted by Tony Hoars in his 1980 Turing Award lecture).
Perfection is attained, not when there is nothing left to add, but when
there is nothing left to take away.
While this book certainlV makes no claims to perfection, it would probably have
y makes no claims to perfection, it would probably have
been better to leave more topics out than to put more topics in.
Although the book covers topics in an order that has proven successful here at
cranford, you may want to vary the order of presentation to suit your audience and
otanford, you may want to vary the order of presentation to suit your audience and
the goals of your course. The following notes provide an overview of the chapters
,.,
and indicate some of the more important dependencies.
Chapter I traces the history of computing and describes the programming
al,
process. rhe chapter requires no programming per sc but provides the contextual
background for the rest of the text.
.
yi
I have designed Chapter 2 for students with little or no computing background.
This chapter is conceptual in its approach and focuses on developing a holistic
.
understanding of object-oriented programming rather than on the details of the Java
& sect-oriented programming rather than on the details of the Java
language. When new students are faced with detailed rules of syntax and structure,
they concentrate on learning the rules instead of the underlying concepts, which are
vastlV more important at this stage. If your students already know some
y more important at this stage. If your students already know some
.',,.,,
programming, you can probably move quickly through this material.
Chapters 3, 4, and 5 offer relatively traditional introductions to expressions,
.
statements, and methods so that students understand these basic concepts.
Chapters 6 and 7 then go on to introduce the fundamentals of objects and classes.
'
Chapter 6 provides the high-level view, focusing on how to use objects and classes
'
rather than on their underlVinZ structure. ChaDter 7 then turns to the low-level
ding structure. Chapter 7 then turns to the low-level
details involved of how obiects are represented in memorV' Although Chapter 7 is
Jects are represented in memory. Although Chapter 7 is
not absolutelV required, students who can Dicture the internal structure of an obiect
y required, students who can picture the internal structure of an object
are much more likelV to understand the essential conceDt of a reference.
y to understand the essential concept of a reference.
The next three chapters introduce particular classes from either Java's standard
libraries or the ACM packages. Chapter & covers the String class, which is
presumably an important topic in any introductory course. Chapter 9 describes the
acm. graphics package in detail, which makes it possible for students to write far
..
more exciting DroZrams. Pafts of the acm. qraDhics package are included in earlier
b programs. Parts of the acm. graphics package are included in earlier
chapters, and it is certainly possible to cover only some of the topics in Chapter 9.
Chapter 10 offers a similar overview of event-driven programming. The first
.
several sections in Chapter 10 focus on mouse and keyboard events; the remaining
'
.
sections provide an introduction to graphical user interfaces (GUIs) and the standard
.,
interactor classes from j avax. swing. This second part of the chapter is valuable if
you want to have students design GUI-based programs, but it is not necessary to
understand subsequent chapters.
Chapters 11 and 12 address the idea of arrays, but do so from different
'
perspectives. Chapter I I introduces both the built-in array type and the ArrayList
utility class from the i ava. util package. Both of these topics seem essential to
J J ava. util package. Both of these topics seem essential to
any Java-based introductory course. Chapter 12 focuses on algorithms for searching
and sorting arrays. The chapter also includes a brief discussion of computational
complexity that will help students understand the importance of algorithmic design.
'
Chapter 13 describes the Java Collections Framework, which is perhaps more
.
often presented in a second programming course. However, because Java takes care
of so manV of the underlVing details, it is actually quite reasonable to teach
y of the underlying details, it is actually quite reasonable to teach
.
introductory students how to use these classes, even if they can't understand their
; .indents how to use these classes, even if they can't understand their
.,.
implementation. The only essential class from the Java Collections Framework is
ArrayList, which has already appeared in Chapter I 1.
Chapter 14 includes four important topics that sometimes appear in a first
'
..
programming course: recursion, concurrency, networking, and programming
patterns. At Stanford, which is on the quafter system, we teach these topics in the
second course. If Von decide to teach recursion in the first course, I strongly
.
recommend that von do so earlV enouZh to allow students time to assimilate the
J y enough to allow students time to assimilate the
material. One possibility is to discuss recursive functions immediately after Chapter
.
5 and recursive algorithms at the end of Chapter 12.
..
viI
SuDDlemental Resources
PPlemental Resources
For stUdentS
The followinZ items are available to all readers of this book at the Addison-Wesley
& items are available to all readers of this book at the Addison-Wesley
j
,.
web site (http: //~. aw. coo/cssupport/)f
. Source code files for each examDle program in the book
pie program in the book
~, 1, n
. Full-color PDF versions of sample runs
pie runs
pie runs
. Answers to review questions
Answers to review questions
For instructors
The following items are available to oualified instructors from Addison-Wesley's
o items are available to qualified instructors from Addison-Wesley's
J O
Instructor Resource Center (http: //~. aw. corn/irc/);
. Source code files for each examDle program in the book
pie program in the book
~, 1, n
. Full-color PDF versions of samDle runs
' .pie runs
. Answers to review ql,postions
Answers to review questions
. Solutions to DroZramminq exercises
programming exercises
. ADDlet-based lecture slides that include animations of the p 1
Applet-based lecture slides that include animations of the proZram examDles
program examples
For adopters of the ACM Java Libraries
The Association for Computing Machinery maintains an extensive web site on the
puting Machinery maintains an extensive web site on the
ACM Java Libraries developed by the Java Task Force (http: //jtf. am.org/).
pod by the Java Task Force (http: //jtf. am.org/).
That site includes the following resourcest
o
. An executive summary outlining the purpose of the ACM Java Libraries
An executive summary outlining the purpose of the ACM Java Libraries
y outlining the purpose of the ACM Java Libraries
n
. Downloadable copies of ACM libraries in both source and comD=l 1 6
Downloadable copies of ACM libraries in both source and compiled form
piled form
. An extensive demo Zqll. l', liar I c
an extensive demo gallery including source code for the examples
. A n introductory 'tutorial to using the ACM libraries
An Introductory 'tutorial to using the ACM libraries
J tutorial to using the ACM libraries
. A comDr hensive discussion of the rationale behind the dest
, L comDrehensive discussion of the rationale behind the design
prehensive discussion of the rationale behind the design
...
VIII
Acknowledgments
Writing a textbook is never the work of a single individual. In putting this book
& a textbook is never the work of a single individual. In putting this book
together, I have been extremely fortunate to have the help of many talented and
dedicated people. I particularlV want to thank mV colleagues on the ACM Java Task
people. I particularly want to thank my colleagues on the ACM Java Task
Force--Kim Bruce, James H. Cross II, Robb Cutier, Scott Grissom, Karl Klee,
Susan Rodger, Fran Trees, Ian Utting, and Frank Yellin--for their hard work on the
..
project, as well as the National Science Foundation, the ACM Education Board, and
the SIGCSE Special Projects Fund for their financial support. I also want to thank
everyone who reSDOnded to the Java Task Force's call for proposals in 2004: Alvce
J ponded to the Java Task Force's call for proposals in 2004: Alyce
BradV, Kim Bruce, Pain Cutter, Ken Lambeft, Robely McCartney, Dave Musicant,
J, Kim Bruce, Pain Cutter, Ken Lambeft, Robely McCartney, Dave Musicant,
Martin Osborne, Nick Parlante, Viera Proulx, Richard Rasala, Juris Reinfelds, Dean
Sanders, Kathryn Sanders, Ruth Ungar, and Andries van Dam. As the design
document for the Java Task Force makes clear, these suggestions were of enormous
value even if the task force did not adopt the designs in their original form.
Here at Stanford, thanks are due to many people. In many ways, the people who
have shaped the book as much as anyone have been my students, who have had to
'
learn the material from a series of preliminary drafts over the last year and a half.
For one thing, the students in Stanford's introductory course have certainly risen to
the challenge of using a new approach to the material and have demonstrated
beyond my expectations how much students can accomplish using the ACM Java
Libraries. For another, my students have proven to be vigilant readers of the
., n
various drafts, never hesitating to point out opportunities for improvement. I also
want to thank the entire team of undergraduate teaching assistants, who have had to
explain to students all the concepts I left out of the earlier versions.
I want to exDress mV gratitude to my editor, Michael Hirsch, and the other
press my gratitude to my editor, Michael Hirsch, and the other
Inembers of the team at Addison-Weslev for their support on this book as well as its
J tor their support on this book as well as its
predecessor.
As alwaVs, the greatest thanks are due to my wife Lauren Rusk, who has again
y >, the greatest thanks are due to my wife Lauren Rusk, who has again
worked her magic as my developmental editor. Lauren's expertise has added
considerable claritV and polish to the text. As I said in the Dreface to my 1995 book,
y and polish to the text. As I said in the preface to my 1995 book,
without her, nothing would ever come out as well as it should.
.
l In.roducfion I
1 .1 A brief history ot comDutinq 2
y of computing 2
1 .2 What is computer science? 4
1 .3 A brief tour of computer hardware 5
The CFU 6, ....;un)?rsh?:f:oa:es'o?o.. 7, Input/output
. =,.M?m.laprsh?:f:oa:es'o?o,. 7, Input/output
devices 7, Network 8
1.4 Alaorithms 8
.orlthms 8
1 .5 Staaes in the Droaramminq orocess 9
nes in the programming process 9
CreotinQ cud 85n?no:p?::n?sn;?c::so,?m.,,. errors cud
d 9 progroms 9, Frogromming errors cud
d.b,.d7,. 12,,;?::g'omS,:.n;oeo'om",,g errors cud
.ding 12,,.l::g'omS,:.n;oeo'om",,g errors cud
1 .6 Java and the obiect-oriented paradigm 15
The history of
3.3 Operators and operands 65
Combininq,,,..',So:?n+foso,if3-.',,, numbers 66 Integer
d Integers cud flooting-point numbers 66, Integer
division cud the remoinder operotor 67, Precedence 68,
Applying rules of,,...d.,.eeiodlCI .=?onncez I'1
pplying rules of precedence 70, Type conversion 71
3.4 Assianment slot6ments 73
.Inment slot6ments 73
',.,so?deoS::ant:?n?not:.:?o,, 76 The increment cud
.,.,,fo?deoS::ant:?n?not:.:?o,, 76 The increment cud
anment operotors 76, The increment cud
decrement operotors 77
3.5 Boolean expressions 77
seIQtiono[ .;ne[:?:rSn)87To,,..I operotors 78, Shortcircuit
i i. Pe,,tZ,, 78of.Logicol operotorrs.'91 Shortcircuit
evoluotion 81 1 Flogs b'2, AneXom;o,:\s,::eosnn,,,,,,,,,,
l gtion 801K Flogs b'2, AneXom;o,:\s,::eosnn,,,,,,,,,,
colCulotion 82
3.6 Desiqninq for chanae 83
Uning for change 83
The importonce ot reodobility 83, U5ing nomed constonts to
1. mobiling so3) U5ing nomed.constonts to
','D:rrDMA sssi "us;?noa==S,O
support progrom mointenonce 84, Using nomed constonts to
i port progrom mointenonce 84, Using nomed constonts to
I I I O
Support progrom development 85
qllmman' 88
summary 88
y 88
Review questions 89
Proqrammina exercises 91
"ramming exercises 91
4 Sfot6menf Forms 95
4.1 Statement adDes in Java 96
Simple,,.,.me?tt 'nJ,vfoZ,,d stotements 98, Control
I I I ac o
stotements 98
4.2 Control statements and problem solying 99
GenerolizinQ the ..,,..:;=t'a,yg,h.
reDeotNd [he nddZIntegers progrom IOUgTh.
repeotN- F from 100, The repeot-
Ntimes pottern 101 1 The,..d-,,,,l-
,.?tin:,;3:r,'"leor:p,,,,4.3 The if statement 105
finale-line if stotements 107 Multiline if stotements 107 The
.Inqle-line if stotements 107, Multiline if stotements 107, The
.ie-line if stotements 107, Multiline if stotements 107, The
. ~ .ie-line if,,,,,"?:tj 1?71 Multiline,f s,o,e"e,t,s.107I The
if-else stotement 10/, Coscoding if stotements 107, The ?:
-,
l'. I d if stotements 1 07, The ?:
operotor 108
4.4 The switch slot6ment 1 10
4.5 The while slot6ment 1 12
UsinQ tnewhile fooD 1 1 3 Inrinite l000s 1 14 'SolvinQ the look
d lhewhile loop 1 1 3, Intinite loops 1 14, Solving the loop
.d .thsrwnile looP, Ill 3, Infinite loops 1 14, Solving the loop
cud-o-holf problem 1 15
4.6 The for slot6ment 1 18
The relotionship between for cud while 1 20, Using for with
ftootinq-point boot:el;;?
5 Mefhods 133
5.1 A quick overview of methods 1 34
Methods os mechonisms for hiding complexics 1 35, Methods os
tools for progrommers rother thou U,.,, 1 35, Method coils os
.
expressions 1 36, Method coils os messoges 1 37
5.2 Writing yogr own methods 138
The formot of o method 1 39, The return stotement 1 39,
Methods involving internol control structures 141, Methods thot
return nonnumeric volues 142, Fredicote methods 144
5.3 Mechanics of the method-calling process 147
Forometer possing 148, Colting ?eo:odcseffo.IW:,, other
methods 1 52
5.4 Decomposition 158
Stepwise refinement 1 59, Specifying porometers 161
oesigning from the top down 1 63, Looking for common
feotures 164, Completing the decomposition 165
5.5 Algorithmic methods 166
The fib,,t. f.,..il opproQch 1 66, Euclid's olgorithm 1 68,
Defending the correctness of E..lidi, olgorithm 1 68, Compering
the efficiency of the two olgorithms 170
Summary 170
Review questions 171
Programming exercises 172
6 Obiec.s and classes I7T
6.1 Using the Randondenerator class 178
F,.,Jo,..d.. numbers 1 79, Using the Randbenerator
closs 1 80, The role of the rondom number seed 1 83
6.2 The javadoc documentQtion system 185
6.3 Defining your own classes lisse" 185
The structure of o closs definition 1 88, Controlling the visibility of
entries 189, Encopsulotion 189
6.4 Representing student information 190
Y Obiects cud Memory 221
7.1 The structure of memory 222
Bits, bytes, cud words 2222BI.ry cud hexodecimol
i. ..ic',2!2,zBlo7 cud hi-c3tecimol
representotions 223, Memory .d;r.,,., 225
7.2 The allocation of memory to variables 226
Memory diooroms for the 2::acg:?ss % forbore
;... ~., ~. ~ o. ~..' ~. ~.... ~ --~ ~ ~ ~~~~~ ~. ~ ~~ ~ ~' I ~ ~. ~ ~ or
I. ac ac ac
collection 232
7.3 Primitive adDes versus obiects 232
ypes versus obiects 232
Porometer po55ing 234, cropper closses 236, Boxing cud
I. ac o Q
unboxinQ 238
d L O o
...
7.4 Linkinq obiects toqether 240
d I .ether 240
MessoQe .o,,i,.,n?:hed n,,.,{ The beocons ot
d= possing in linked structures f The beocons of
Gondor 240, The internol representotion of linked
l I ac A O
structures 243
qumman' 9
summary 244
y 244
Review questions 245
Proarammina exercises 247
dramming exercises 247
8 Strinas and chorocfers 249
gs and chorocfers 249
8.1 The principle of enumeration 250
kepresenting enumeroted types inside the mochine 25 1 1
representing enumeroted types os integers 252, Defining new
i
i i J n .;, types os integers 252, Defining new
enumeroted adDes 253 /pos os Integers 252, Defining new
lpes 253
8.2 Characters 254
The doto aiDe char 254 The ASCll cud Unicode coding
IPe char 254, The ASCll cud Unicode coding
l 'saing ct?:,:}et.on;f'Zo;? ?inn,,",,.,",,,g I f
sVstems 254 Chorocter constonts 257 I.gco?toentc:fJ:2,,,., of
lorems 254, Chorocter constonts 257, Importont p,.pe,ti., of
the Unicode representotion 257, Speciol .ho?;t:tetrP'oP;r,,,, of
Chorocter orithmetic 259, Useful methods in the character
l n 4 1 ~ I I I 1. 1. I I n' ac
closs 261 1 Control stotements involving chorocters 263
8.3 Strinqs as an abstract idea 263
ac as an abstract idea 263
Holistic cud reductionist views of strinQs 264 The notion ot on
or I
I I I I ac A 4
obstroct aiDe 264
/po 264
8.4 Usinq the methods in the String class 265
U the methods in the String class 265
DetermininQ the lenQth of o string 265, Selecting chorocters trom
or .rh ot o string 265, Selecting chorocters trom
.. .2--rhe length ot o string 265, Selecting chorocters trom
o string 267, Concotenotion 267, ExtroctinQ forts:oC,,,, from
d L67, Concotenotion 267, Extrocting forts:oC,,,, from
',,,,.'.if;e::::?ZiVMC:.
.trlnQ 2o9, ComDorinQ one strinQ .:X,;onc:'tne,P31so?f:e.,.h,,.
d L69, Compering one string with onother 270, Seorching
. d L69, Compering one string with onother 270, Seorching
within o
9 Obiec.-orien'ed Grophics 295
9.1 The acm.graphics model 296
9.2 Structure ot the acm.graphics package ?97
The ocanvas closs 297, Further detoils .:t?,:eL,..
class 300, The GPoint, GDhension, cud GRectangle
closses 301, The breath closs 302, The subject closs cud its
I I
Subclosses 303
9.3 Using the shape classes 306
The ffeabel .11?? 3'O:?e!hes:aee.. closs cud its subclosses
(~undaect cud G3Daect) 31 1, The coyal closs 31 1, The
GLine closs 31 2, The GArc cio55 31 3, The GImage clQss 3 1 o,
The GPolygon closs 32 1
9.4 Creating compound obieCts 328
A simple GC~ound exomple 328, The GCompound coordinote
system 331, Obiect
constroints 390, Using TableLayout to creote o simple
l l' and
colculotor 390
Rummanf '?99
summary 399
y 399
Review questions 401
Proqrammina exercises 402
"ramming exercises 402
l 1 Arrays and ArrayLists 4O9
ys and ArrayLists 4O9
1 1 .1 Introduction to arrays 410
Arroy declorotion 41y' trloov selection 41 2, An exomple ot o
i I I .rroy selection 41 2, An exompte ot o
. i I I .rroy Selection 41 2, An,eXompte ot o
Simple orroy 41 3, Chonging the index rouge 414, Arroys ot
l .pie orroy 41 3, Chonging the index rouge 414, Arroys ot
obiects 415, U5ing .,,.,S'M:ColPZ:, 4I A,,;v, of
diqression on the ++ cud "- .;o'r:'\sr;g,,", 41 5, A
.resslon on the ++ cud "- .;o'r:'\sr;g,,", 41 5, A
1 1 .2 Im6rnal representotion of arrays 419
1 1 .3 Passina arrays as parameters 421
u arrays as parameters 421
1 1 .4 Usina arrays for tabulation 427
u arrays for tabulation 427
1 1 .5 Initialization of arrays 428
ys 428
1 1 .6 Multidimensional arrays 430
FossinQ .,I,,d,..,,,.,.lxosr,o'v??o methods 431, Initiolizinq
d multidimensionol'orroys to methods 431 1 Initiolizing
IJ. l.. I I n n
multidimensionol orroVs 432
ye 432
1 1 .7 lmaae Drocessina 432
d processing 432
Kepresentotion of imoges 433, Using the Glance closs tO
i des 433, Using the Glance closs tO
. 1. des 433, Using the Glance closs tO
monlpulote imoges 433, Bit ..,,,,totroen';7rt?"4t:,,
I i
operotions to isolote components of o pixel 437, Creoting o
i. ponents oT o pixel 437, Creoting o
qroVscole imoQe 438, in:::::;i:?::l.:?"tiJ:si:3ti?; o
.royscole imoge 438, Smoothing .,imc',e7"{6,;',,,,,, o
.% tymsn::::);$?il,rs::3ting o
overoqinQ 4i00? H?u?d.M'ge7"{6u;',,,,,, o
.lug 439, Hiding complexity 439
1 1 .8 The ArrayList class 442
qllmman, 448
summary 448
y 448
Review questions 449
Proaramminq exercises 450
Urammlng exercises 450
12 Searching and Sorfino 461
9 and Soaking 461
1 2.1 Searchina 462
d
q..,.hi,.?, on inteoer orro\/ 462 Seorchina o tobte 463
...,.hi,ql, on integer orroy 4o2 SeorchinQ o tobte 4o3,
d in on integer orroy 462, Seorching o tobte 463,
computotionol complexity from code structure 483, Worst-cose
I
versus overoQe-cose comDlexify 485
d pie-city 485
12.4 Usinq data tiles 486
U data files 486
The concept of o file 486, 6eodinq text files in Jovo 488,
Exception F;:;;.',48,'n:,moomt?:'r+;'::,S n,
'...:!;can;SLY't?,Ztt5Z3,,,
selecting files,,,.7o.;?e?i 4Cb?gtt5Z34,,,
d tiles
14.3 Usina the network 562
U the network 562
14.4 Proaramminq oatterns 562
cramming patterns 562
The model/view/controller pottern 563, An illustrotive exomplef
Grophing spreodsheet d.t.' 564 1 p,':
qumman' F70
summary 570
y 570
Review questions 570
Proaramminq exercises 571
"ramming exercises 571
Index 5T5
..
xviI