forked from ChrisMayfield/ThinkJava2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch00.tex
More file actions
291 lines (204 loc) · 18 KB
/
ch00.tex
File metadata and controls
291 lines (204 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
\chapter*{Prefacio}
\markboth{PREFACIO}{PREFACIO}
\addcontentsline{toc}{chapter}{Prefacio}
%{\it Think Java} is an introduction to computer science and programming intended for readers with little or no experience.
{\it Think Java} es una introducción a las ciencias de la computación (informática) y la programación dirigida a lectores con poca o ninguna experiencia.
%We start with the most basic concepts and are careful to define all terms when they are first used.
Comenzaremos con los conceptos más básicos y pone un cuidado especial en definir cada término cuando se usa por primera vez.
%The book presents each new idea in a logical progression.
El libro presenta cada nueva idea en una progresión lógica.
%Larger topics, like control flow statements and object-oriented programming, are divided into smaller examples and introduced over the course of several chapters.
Los contenidos de más entidad, como las sentencias de control de flujo o la programación orientada a objetos, se dividen en partes más pequeñas y son presentados a lo largo de varios capítulos.
%This book is intentionally concise.
La intención de este libro es ser conciso.
%Each chapter is 12--14 pages and covers the material for one week of a college course.
Cada capítulo tiene unas 12 páginas y proporciona material para una semana de un curso de enseñanza superior.
%It is not meant to be a comprehensive presentation of Java, but rather, an initial exposure to programming constructs and techniques.
No está concebido para ser una presentación exhaustiva del lenguaje Java, sino una primera toma de contacto con las técnicas y construcciones que se usan en programación.
%We begin with small problems and basic algorithms and work up to object-oriented design.
Comenzaremos con problemas pequeños y algoritmos básicos e iremos progresando hasta el diseño orientado a objetos.
%In the vocabulary of computer science pedagogy, this book uses the ``objects late'' approach.
En el vocabulario de la pedagogía de las ciencias de la computación, este libro usa la aproximación llamada ``objetos tardíos'' (objects late).
%\section*{The Philosophy Behind the Book}
\section*{La Filosofía del Libro}
%Here are the guiding principles that make the book the way it is:
Estos son los principios que hacen que este libro sea como es:
\begin{description}
%\item[One concept at a time:]
\item[Un concepto a la vez:]
%We break down topics that give beginners trouble into a series of small steps, so that they can exercise each new concept in isolation before continuing.
Dividimos los temas que suelen ser mas difíciles y problemáticos para los principiantes en series de pasos pequeños de modo que se pueda entender y practicar cada concepto de forma aislada.
%\item[Balance of Java and concepts:]
\item[Equilibrio entre enseñar Java y enseñar conceptos:]
%The book is not primarily about Java; it uses code examples to demonstrate computer science.
El principal tema del libro no es Java, es usar la programación como introducción a las ciencias de la computación.
%Most chapters start with language features and end with concepts.
La mayoría de los capítulos comienzan con características del lenguaje y terminan con conceptos.
%\item[Conciseness:]
\item[Concisión:]
%An important goal of the book is to be small enough so that students can read and understand the entire text in a one-semester college or AP course.
%Students can read 1--2 chapters per week, depending on the pace of the instruction.
Uno de los objetivos más importantes del libro es ser suficientemente breve como para que los estudiantes puedan leer y entender el texto completo en un semestre de un curso de educación superior.
%\item[Emphasis on vocabulary:]
\item[Énfasis en el vocabulario:]
%We try to introduce the minimum number of terms and define them carefully when they are first used.
Intentamos introducir el mínimo número de terminos y definirlos cuidadosamente cuando se usan por primera vez.
%We also organize them in glossaries at the end of each chapter.
También se incluye un glosario al final de cada capítulo.
%\item[Program development:]
\item[Desarrollo de programas:]
%There are many strategies for writing programs, including bottom-up, top-down, and others.
Hay muchas estrategias para escribir programas, descendiente (top-down), ascendiente (bottom-up), etc.
%We demonstrate multiple program development techniques, allowing readers to choose methods that work best for them.
Se muestran múltiples estrategias y técnicas de desarrollo de programas para permitir que el lector escoja aquella que le funciona mejor.
%\item[Multiple learning curves:]
\item[Múltiples curvas de aprendizaje:]
%To write a program, you have to understand the algorithm, know the programming language, and be able to debug errors.
Para escribir un programa hay que entender el algoritmo, conocer el lenguaje de programación y ser capaz de depurar los errores que surjan.
%We discuss these and other aspects throughout the book and summarize our advice in Appendix~\ref{debugging}.
Se presentan estos y otros aspectos a lo largo del libro y un resumen de nuestros consejos en el Appendice~\ref{debugging}
%\item[Spiral approach:]
%Some concepts take time to sink in.
%The more difficult ideas in the book, like recursion, appear several times.
%By coming back to these topics, we give learners a chance to review and reinforce.
%\item[Keep it simple:]
%We use the minimum amount of Java to get the maximum amount of programming ability.
%The goal of this book is to teach fundamental ideas from computer science, not Java.
%We leave out some language features, like the \java{switch} statement, that are unnecessary, and we present only a few of the many classes in the Java libraries.
\end{description}
%\section*{Object-Oriented Programming}
\section*{Programación Orientada a Objetos}
%Some Java books introduce classes and objects immediately; others begin with procedural programming and transition to object-oriented more gradually.
Algunos libros de Java introducen los conceptos de clase y objeto al principio; otros empiezan con la programación procedural y presentan una transición gradual hacia la orientación a objetos.
%Many of Java's object-oriented features are motivated by problems with previous languages, and their implementations are influenced by this history.
Muchos aspectos de la orientación a objetos en Java son motivados por problemas existentes en otros lenguajes de programación anteriores, y por tanto están influenciados por ese pasado.
%Some of these features are hard to explain when people aren't familiar with the problems they solve.
Esto hace que algunos de estos aspectos sean difíciles de explicar y de comprender cuando uno no conoce los problemas que motivaron su creación.
%We get to object-oriented programming as quickly as possible (beginning with Chapter~\ref{immutable}).
Abordamos la Programación Orientada a Objetos lo antes posible (comenzando en el Capítulo~\ref{immutable}).
%But we introduce concepts one at a time, as clearly as possible, in a way that allows readers to practice each idea in isolation before moving on.
Iremos introduciendo los conceptos de uno en uno, de la forma más clara posible y de un modo que permita a los lectores practicar cada uno de forma individual antes de pasar al siguiente.
%So it takes some time to get there.
Conocer y comprender la Programación Orientada a Objetos lleva su tiempo.
%You can't write Java programs (even Hello World) without encountering object-oriented features.
No se pueden escribir programas Java (ni siquiera el modesto Hola Mundo) sin toparse con aspectos de la Programación Orientada a Objetos.
%In some cases we explain a feature briefly when it first appears, and then explain it more deeply later on.
Por eso en algunos casos daremos una breve explicación de ese aspecto concreto, en el momento en el que aparezca, y se explicará con mas profundidad más adelante.
%If you read the entire book, you will see nearly every topic required for Java SE Programmer I certification.
Si lees el libro completo, habrás visto prácticamente todas las materias requeridas para la certificación Java SE Programmer I.
%Supplemental lessons are available in the official Java tutorials on Oracle's website (\url{https://thinkjava.org/tutorial}).
Hay disponibles lecciones adicionales en los tutoriales oficiales de Java en el sitio web de Oracle (\url{https://thinkjava.org/tutorial}).
%This book is also well suited to prepare high school students for the AP Computer Science A exam , which includes object-oriented design and implementation.
%(AP is a registered trademark of The College Board.)
Este libro es también adecuado para preparar a los estudiantes de Ciclos Superiores para el examen "AP Computer Science A" \footnotemark, que incluye diseño e implementación de programas con orientación a objetos.
%We introduce nearly every topic in the ``AP Java subset'' with a few exceptions.
Se introducen todos los temas del "AP Java subset", con unas pocas excepciones.
%A mapping of {\it Think Java} section numbers to the AP course is available on our website: \url{https://thinkjava.org/}.
La correspondencia entre los números de seccion del {\it Think Java} con los del "AP course" se puede consultar en nuestro sitio web: \url{https://thinkjava.org/}.
\footnotetext{N. del T.: el examen que se menciona es parte del programa "Advanced Placement" (\url{https://apstudents.collegeboard.org/}) de la organización estadounidense "College Board". Este programa
consiste en dar acceso a contenidos de nivel universitario a estudiantes pre-universitarios, de modo que puedan mejorar su educación y obtener visibilidad para estar mejor posicionados a la hora de acceder
a las distintas universidades.}
%\section*{Changes to the Second Edition}
\section*{Cambios en la Segunda Edición}
This new edition was written over several years, with feedback from dozens of instructors and hundreds of students.
A complete history of all changes is available on GitHub.
Here are some of the highlights:
\begin{description}
\item[Chapters 1--4:]
We reordered the material in Chapter~1 to present a more interesting balance of theory and practice.
Chapters~2--3 are much cleaner now too.
Methods are now presented in a single chapter, along with additional in-depth examples.
\item[Chapters 5--8:]
We rearranged these chapters a lot, added many examples and new figures, and removed unnecessary details.
Strings are covered earlier (before arrays) so that readers can apply them to loop problems.
The material on recursion is now a chapter, and we added new sections to explain binary numbers and {\it CodingBat}.
\item[Chapters 9--12:]
Our main goal for these chapters was to provide better explanations and more diagrams.
Chapters~9--10 focus more on immutable versus mutable objects, and we added new sections on BigInteger and StringBuilder.
The other content is largely the same, but it should be easier to understand now.
\item[Chapters 13--17:]
We balanced the amount of content in Chapters~13--14 by moving ArrayLists earlier, and we implement the ``War'' card game as another example.
Chapters~15--17 are brand new in this edition; they cover more advanced topics including 2D arrays, graphics, exceptions, abstract classes, interfaces, and events.
\item[Appendixes:]
We added Appendix~\ref{javadoc} to explain documentation comments and Javadoc in more detail. % and Appendix~\ref{extras} to present special topics.
%Most of the examples in the chapters do not include documentation comments to save space.
The other three appendixes that were present in the first edition have been revised for clarity and layout.
\end{description}
\section*{About the Appendixes}
The chapters of this book are meant to be read in order, because each one builds on the previous one.
We also include several appendixes with material that can be read at any time:
\begin{description}
\item[Appendix A, ``Tools''] \hfill
This appendix explains how to download and install Java so you can compile programs on your computer.
It also provides a brief introduction to DrJava---an integrated development environment designed primarily for students---and other development tools, including Checkstyle for code quality and JUnit for testing.
\item[Appendix B, ``Javadoc''] \hfill
It's important to document your classes and methods so that other programmers (including yourself in the future) will know how to use them.
This appendix explains how to read documentation, how to write documentation, and how to use the Javadoc tool.
\item[Appendix C, ``Graphics''] \hfill
Java provides libraries for working with graphics and animation, and these topics can be engaging for students.
The libraries require object-oriented features that students will not completely understand until after Chapter~\ref{mutable}, but they can be used much earlier.
\item[Appendix D, ``Debugging''] \hfill
We provide debugging suggestions throughout the book, but this appendix provides many more suggestions on how to debug your programs.
We recommend that you review this appendix frequently as you work through the book.
%\item[Appendix E, ``Extras''] \hfill
%
%With each new edition, we add new material, remove old material, and revise everything else.
%Some of the old material may still be useful, so rather than delete it, we moved it to this appendix.
\end{description}
\section*{Using the Code Examples}
\label{code}
Most of the code examples in this book are available from a Git repository at \url{https://github.com/ChrisMayfield/ThinkJavaCode2}.
Git is a ``version control system'' that allows you to keep track of the files that make up a project.
A collection of files under Git's control is called a ``repository''.
\index{repository}
\index{GitHub}
GitHub is a hosting service that provides storage for Git repositories and a convenient web interface.
It provides several ways to work with the code:
\begin{itemize}
\item You can create a copy of the repository on GitHub by clicking the {\sf Fork} button.
If you don't already have a GitHub account, you'll need to create one.
After forking, you'll have your own repository on GitHub that you can use to keep track of code you write.
Then you can ``clone'' the repository, which downloads a copy of the files to your computer.
\item Alternatively, you could clone the original repository without forking.
If you choose this option, you don't need a GitHub account, but you won't be able to save your changes on GitHub.
\item If you don't want to use Git at all, you can download the code in a ZIP archive using the {\sf Clone} button on the GitHub page, or this link: \url{https://thinkjava.org/code2zip}.
\end{itemize}
After you clone the repository or unzip the ZIP file, you should have a directory named {\it ThinkJavaCode2} with a subdirectory for each chapter in the book.
The examples in this book were developed and tested using OpenJDK~11.
If you are using a more recent version, everything should still work.
If you are using an older version, some of the examples might not.
\section*{Acknowledgments}
Many people have sent corrections and suggestions over the years, and we appreciate their valuable feedback!
This list begins with Version 4.0 of the open source edition, so it omits those who contributed to earlier versions:
\begin{itemize}
\item Ellen Hildreth used this book to teach Data Structures at Wellesley College and submitted a whole stack of corrections and suggestions.
\item Tania Passfield pointed out that some glossaries had leftover terms that no longer appeared in the text.
\item Elizabeth Wiethoff noticed that the series expansion of $\exp(-x^2)$ was wrong.
She has also worked on a Ruby version of the book.
\item Matt Crawford sent in a whole patch file full of corrections.
\item Chi-Yu Li pointed out a typo and an error in one of the code examples.
\item Doan Thanh Nam corrected an example.
\item Muhammad Saied translated the book into Arabic and found several errors in the process.
\item Marius Margowski found an inconsistency in a code example.
\item Leslie Klein discovered another error in the series expansion of $\exp(-x^2)$, identified typos in card array figures, and helped clarify several exercises.
\item Micah Lindstrom reported half a dozen typos and sent corrections.
\item James Riely ported the textbook source from LaTeX to Sphinx.
\\ \url{http://fpl.cs.depaul.edu/jriely/thinkapjava/}
\item Peter Knaggs ported the book to C\#.
\\ \url{https://www.rigwit.co.uk/think/sharp/}
\item Heidi Gentry-Kolen recorded several video lectures that follow the book.
\\ \url{https://www.youtube.com/user/digipipeline}
\item Waldo Ribeiro submitted a pull request that corrected a dozen typos.
\item Michael Stewart made several suggestions for improving the first half of the book.
\item Steven Richardson adapted the book for an online course and contributed many ideas for improving the text.
\item Fazl Rahman provided detailed feedback, chapter by chapter, and offered many suggestions for improving the text.
\end{itemize}
We are especially grateful to the technical reviewers of the O'Reilly Media first edition: Blythe Samuels, David Wisneski, and Stephen Rose.
They found errors, made many great suggestions, and helped make the book much better.
Likewise, we thank Marc Loy for his thorough review of the O'Reilly Media second edition.
He contributed many corrections, insights, and clarifications.
Many students have given exceptional feedback, including Ian Staton, Tanner Wernecke, Jacob Green, Rasha Abuhantash, Nick Duncan, Kylie Davidson, Shirley Jiang, Elena Trafton, Jennifer Gregorio, and Azeem Mufti.
Other contributors who found one or more typos: Stijn Debrouwere, Guy Driesen, Andai Velican, Chris Kuszmaul, Daniel Kurikesu, Josh Donath, Rens Findhammer, Elisa Abedrapo, Yousef BaAfif, Bruce Hill, Matt Underwood, Isaac Sultan, Dan Rice, Robert Beard, Daniel Pierce, Michael Giftthaler, Chris Fox, Min Zeng, Markus Geuss, Mauricio Gonzalez, Enrico Sartirana, Kasem Satitwiwat, Jason Miller, Kevin Molloy, Cory Culbertson, Will Crawford, and Shawn Brenneman.
%\medskip
If you have additional comments or ideas about the text, please send them to: \href{mailto:feedback@greenteapress.com}{\tt feedback@greenteapress.com}.
\hfill Allen Downey and Chris Mayfield